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
|
<file_sep>using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeEval
{
class TestClass
{
public void BitConvert(string line)
{
string[] subStr = line.Split(',');
string result = "";
//PrintTest(subStr);
int value, pos1, pos2;
Int32.TryParse(subStr[0], out value);
Int32.TryParse(subStr[1], out pos1);
Int32.TryParse(subStr[2], out pos2);
pos1 -= 1;
pos2 -= 1;
if (((value >> pos1) & 1) == ((value >> pos2) & 1))
{
result = "true";
}
else
{
result = "false";
}
Console.WriteLine(result);
}
private void PrintTest(string[] subStr)
{
foreach(var x in subStr)
{
Console.WriteLine(x);
}
}
// multiples of a number
public void MultipleCompare(string line)
{
string[] subStr = line.Split(',');
int x, n;
Int32.TryParse(subStr[0], out x);
Int32.TryParse(subStr[1], out n);
int index = n;
while(n < x)
{
n += index;
}
Console.WriteLine(n);
}
public void MultiplicationTable(int value)
{
for (int i = 1; i <= value; i++)
{
for (int j = 1; j <= value; j++)
{
//product[j - 1] = (i * j).ToString();
Console.Write("{0,4}", (i * j));
}
Console.WriteLine();
}
}
public void LowerCase(string line)
{
Console.WriteLine(line.ToLower());
}
public void DataRecovery(string line)
{
string[] subStr = line.Split(';');
Dictionary<string,string> wordsList = new Dictionary<string , string >();
wordsList.Add(subStr[1], subStr[0]);
}
public void LongestLines(string line)
{
}
}
}
<file_sep>using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeEval
{
class Program
{
static void Main(string[] args)
{
//string fileInput = "125,1,2";
//string multipleInput = "358, 32";
string dataRecov = ("programming first The language;3 2 1");
TestClass test = new TestClass();
//test.MultipleCompare(multipleInput);
//test.MultiplicationTable(12);
//test.LowerCase("Eqpu'pg%UnT!jo)7V}u5RF*~~-L_2dYV4");
test.DataRecovery(dataRecov);
string filePath = "C:/Users/Marc/Documents/Visual Studio 2015/Projects/CodeEval/input.txt";
StreamReader reader = File.OpenText(filePath);
while(!reader.EndOfStream)
{
string line = reader.ReadLine();
}
}
}
}
<file_sep>using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeEval
{
class Problems
{
public void LongestLine(string filePath)
{
StreamReader reader = File.OpenText(filePath);
Dictionary<string, int> strSet = new Dictionary<string, int>();
int count = 0;
int loopDisplay = 0;
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (line.Length == 0)
continue;
if(count == 0)
{
System.Int32.TryParse(line, out loopDisplay);
Console.WriteLine("value => {0}", loopDisplay);
}
else
{
strSet.Add(line, line.Length);
}
count += 1;
}
int temp = 0;
foreach (var i in strSet.OrderByDescending(index => index.Value))
{
if (temp < loopDisplay)
{
Console.WriteLine(i.Key);
temp += 1;
}
else
{
break;
}
}
}
public void Lower(string filePath)
{
using (StreamReader reader = File.OpenText(filePath))
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (null == line)
continue;
Console.WriteLine(line.ToLower());
}
}
#region Data Recovery
public void DataRecovery(string filePath)
{
StreamReader reader = File.OpenText(filePath);
while(!reader.EndOfStream)
{
string line = reader.ReadLine();
if (line.Length == 0)
continue;
string[] subStr = line.Split(';');
}
}
private void RearrangeLines(string[] strArr)
{
Dictionary<int, string> dataSet = new Dictionary<int, string>();
string[] textData = strArr[0].Split(' ');
string[] indexData = strArr[1].Split(' ');
int index = 0;
for(int i = 0; i < textData.Length; i++)
{
if(i != textData.Length - 1)
{
System.Int32.TryParse(indexData[i], out index);
dataSet.Add(index, textData[i]);
}
else
{
dataSet.Add(i, textData[i]);
}
}
}
#endregion
}
}
s
|
9273cc3e356523e05d08804a6d7dfc9cc317af94
|
[
"C#"
] | 3
|
C#
|
marclacerna/codeeval
|
dc39221b7bc1512d5dc47d8e3e32b7cfc628c7dd
|
575b53a33353ac89a915bc237500647ec6c55aae
|
refs/heads/master
|
<repo_name>gabihtoledo0/SquadIncriveis<file_sep>/app/models/user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
validates_with ::IncriveisValidator
validates :cpf, uniqueness: true, if: :cpf_is_true?
validates :cnpj, uniqueness: true, if: :cnpj_is_true?
def cpf_is_true?
pf_pj == "PF"
end
def cnpj_is_true?
pf_pj== "PJ"
end
def self.search_by(attribute, value)
where("#{attribute} = ?", value).first
end
end
<file_sep>/app/helpers/application_helper.rb
module ApplicationHelper
PAGEJS_ALIASES = { 'create' => 'new', 'update' => 'edit' }
def pagejs
controller = params[:controller]
view = PAGEJS_ALIASES[pagejs_action] || pagejs_action
"#{controller}##{view}"
end
def pagejs_action
if params[:controller] == 'orders'
"#{params[:insurance_type]}_#{params[:current_step]}"
else
params[:action]
end
end
def centralized_logo(current_page)
pages_with_centralized_logo = [
'devise/registrations#edit',
'ideas#index',
'ideas#edit',
'incrivel#index',
'users#index'
]
pages_with_centralized_logo.include?(current_page)
end
def full_width_container(current_page)
pages_with_centralized_logo = [
'ideas#index',
'ideas#show',
'ideas#new',
'ideas#edit',
'incrivel#index',
'users#index'
]
pages_with_centralized_logo.include?(current_page)
end
end
<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
skip_before_action :authenticate_user!, only: [:emailcheck, :cpfcheck, :cnpjcheck]
skip_before_action :verify_authenticity_token, only: [:emailcheck, :cpfcheck, :cnpjcheck]
def index
@users = User.all
end
def delete
@user.destroy
respond_to do |format|
format.html { redirect_to new_user_session, notice: 'Login desfeito com sucesso!' }
format.json { head :no_content }
end
end
def emailcheck
@user = User.search_by(:email, params[:email])
respond_to do |format|
format.json {render :json => {email_exists: @user.present?}}
end
end
def cpfcheck
@user = User.search_by(:cpf, params[:cpf])
respond_to do |format|
format.json {render :json => {cpf_exists: @user.present?}}
end
end
def cnpjcheck
@user = User.search_by(:cnpj, params[:cnpj])
respond_to do |format|
format.json {render :json => {cnpj_exists: @user.present?}}
end
end
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user!
before_action :configure_permitted_parameters, if: :devise_controller?
# before_action :
def inactive_message
account_active? ? super : :account_inactive
end
def index
end
def create
# save post
flash[:notice] = "Post successfully created"
redirect_to @post
end
def show
# doesn't need to assign the flash notice to the template, that's done automatically
end
def after_sign_out_path_for(resource_or_scope)
'/users/sign_in'
end
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up) { |u| u.permit(:name, :email, :password_confirmation, :password, :fullname, :razaosocial, :pf_pj, :cpf, :cnpj, :rua, :cep, :bairro, :cidade, :estado, :numero)}
devise_parameter_sanitizer.permit(:account_update) { |u| u.permit(:name, :email, :password_confirmation, :password, :current_password, :fullname, :razaosocial, :pf_pj, :cpf, :cnpj, :rua, :cep, :bairro, :cidade, :estado, :numero)}
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
get 'incrivel/index'
get 'users/index'
devise_for :users
#resources :users
match '/users', to: 'users#index', via: 'get'
get 'pages/info'
get "pages/info"
resources :ideas
root to: redirect('/ideas')
devise_scope :user do
post '/checkemail', to: 'users#emailcheck'
post '/checkcpf', to: 'users#cpfcheck'
post '/checkcnpj', to: 'users#cnpjcheck'
end
end
<file_sep>/db/migrate/20191204122231_add_full_name_to_users.rb
class AddFullNameToUsers < ActiveRecord::Migration[6.0]
def change
add_column :users, :fullname, :string
add_column :users, :razaosocial, :string
add_column :users, :pf_pj, :string
add_column :users, :cpf, :string, unique: true
add_column :users, :cnpj, :string
add_column :users, :rua, :string
add_column :users, :cep, :string
add_column :users, :bairro, :string
add_column :users, :cidade, :string
add_column :users, :estado, :string
add_column :users, :numero, :string
add_column :users, :adm, :boolean, default: false
end
end
<file_sep>/config/initializers/warden.rb
Warden::Strategies.add(:unsecure_authentication, UnsecureAuthenticableStrategy)<file_sep>/app/validators/incriveis_validator.rb
class IncriveisValidator < ActiveModel::Validator
def validate(record)
if record.pf_pj == "PF"
if !BRDocuments::CPF.valid?(record.cpf)
record.errors[:cpf] << "inválido."
end
if record.fullname == ""
record.errors[:fullname] << "não pode ser nulo."
end
if record.fullname.length > 50
record.errors[:fullname] << "deve possuir menos que 51 caracteres."
end
if !record.fullname.match(/\A[[:alpha:][:blank:]]+\z/)
record.errors[:fullname] << "deve conter apenas letras e espaços."
end
record.cnpj = nil
record.razaosocial = nil
elsif record.pf_pj == "PJ"
if !BRDocuments::CNPJ.valid?(record.cnpj)
record.errors[:cnpj] << "inválido."
end
if record.razaosocial == ""
record.errors[:razaosocial] << "não pode ser nulo."
end
if record.cep == ""
record.errors[:cep] << "não pode ser nulo."
end
record.cpf = nil
record.fullname = nil
end
if record.password && !record.password.match(/(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*\W+).*$/)
record.errors[:password] << "deve conter um caractere especial, uma letra maiúscula, uma letra minúscula e um número."
end
if !record.email.match(/\A[^@\s]+<EMAIL>/);
record.errors[:email] << "deve ser no formato '<EMAIL>'."
end
if record.pf_pj == ""
record.errors[:pf_pj] << "Selecione o tipo de pessoa"
end
end
end
|
70e2249951a783ee69beffbe63148f42c92b6441
|
[
"Ruby"
] | 8
|
Ruby
|
gabihtoledo0/SquadIncriveis
|
f1e4c36da4902e4a3bd2dc2fd71cd7e58d98c72f
|
397ff6d2a56d73b0074e46e27cc79dae40762e96
|
refs/heads/void
|
<file_sep>//
// This file is part of the GNU ARM Eclipse distribution.
// Copyright (c) 2014 <NAME>.
//
// ----------------------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include "diag/Trace.h"
#include "stm32f10x.h"
#include "myDelay.h"
// ----------------------------------------------------------------------------
//
// Standalone STM32F1 em pty sample (trace via NONE).
//
// Trace support is enabled by adding the TRACE macro definition.
// By default the trace messages are forwarded to the NONE output,
// but can be rerouted to any device or completely suppressed, by
// changing the definitions required in system/src/diag/trace_impl.c
// (currently OS_USE_TRACE_ITM, OS_USE_TRACE_SEMIHOSTING_DEBUG/_STDOUT).
//
// ----- main() ---------------------------------------------------------------
// Sample pragmas to cope with warnings. Please note the related line at
// the end of this function, used to pop the compiler diagnostics status.
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wmissing-declarations"
#pragma GCC diagnostic ignored "-Wreturn-type"
#define LED_PIN 0x100
#define LED_OFF GPIOB->BSRR |= LED_PIN
#define LED_ON GPIOB->BSRR |= (LED_PIN << 16)
//void initialise_monitor_handles(void);
void hw_init();
int main(int argc, char* argv[]) {
// initialise_monitor_handles();
// At this stage the system clock should have already been configured
// at high speed.
myDelay_init();
hw_init();
// NVIC_EnableIRQ(USB_LP_CAN1_RX0_IRQn);
LED_ON;
myDelay(3000);
LED_OFF;
// printf("Hello Semi\n");
// trace_puts("Hello ARM World!");
// Infinite loop
usb_init();
while (1) {
// if (GPIOC->IDR & (1 << 11)) LED_ON; else LED_OFF;
// myDelay(1000);
}
}
void EXTI15_10_IRQHandler() {
if (EXTI->PR & 0x800) {
EXTI->PR |= 0x800;
}
if (GPIOC->IDR & 0x800) GPIOA->BSRR = 0x20;
else GPIOA->BSRR = (0x20 << 16);
}
#pragma GCC diagnostic pop
// ----------------------------------------------------------------------------
<file_sep>/*
* usbcore.c
*
* Created on: 26 янв. 2017 г.
* Author: valeriy
*/
#define MYUSBLIB
#include "stm32f10x.h"
#include "usb.h"
#define DSETADDR 1
#define POST0 2
#define POSTDATA 3
#define BUF0SIZE 8
void ep_init();
#pragma pack(push,1)
union {
USBReqestType req;
uint8_t buf[4];
} reqBuf;
#pragma pack(pop)
struct {
uint16_t daddr; // device addr
uint8_t * baddr; // buffer addres to TX (IN)
uint16_t count; // count tx bytes
} usbData;
const uint8_t *strdesc[]={StringLangID,StringVendor,StringProduct,StringSerial};
static uint16_t stat,saveRXst, saveTXst, in_stat, bmap;
void EP0Int();
void getDesc();
void getDeviceDesc(USBReqestType *ur);
void getConfigDesc();
void getStringDesc();
void setup_process();
void getConfig();
void setConfig();
void usb_ctr_int() {
stat = USB->ISTR;
// pbufcpy(reqBuf.buf, 0);
switch (stat & 0xf) {
case 0:
saveRXst = (USB->EPR[0] & 0x3000) >> STRX;
saveTXst = (USB->EPR[0] & 0x30) >> STTX;
EP0Int();
setStatRx(0, saveRXst);
setStatTx(0, saveTXst);
break;
}
}
void usb_pma_int() {
stat = USB->ISTR;
}
void usb_err_int() {
stat = USB->ISTR;
}
void usb_reset_int() {
ep_init();
in_stat = usbData.daddr = bmap = 0;
// lens[dcount++] = dcount;
}
void usb_sof_int() {
stat = USB->ISTR;
// lens[dcount++] = dcount;
}
void usb_esof_int() {
stat = USB->ISTR;
}
void EP0Int() {
if (USB->ISTR & DIR) {
clrCTR_rx(0); // OUT Process (RX)
pma2usr(reqBuf.buf, getTableRxAddr(0), getTableRxCount(0));
if (USB->EPR[0] & SETUP) {
setup_process(); // Получили пакет SETUP
} else {
// Получили пакет обычный
saveRXst = VALID;
if (usbData.baddr) {
saveRXst = VALID;
usbData.baddr = 0;
}
}
} else {
clrCTR_tx(0); // IN Process (TX)
/*
if (usbData.count == 0x8000) { // TX STALLed
clrCTR_rx(0);
saveTXst = NAK;
saveRXst = VALID;
return;
}
*/
if (usbData.count & 0x3ff) { // Проверяем есть ли пакет для отправки
// Если да - отправляем
uint8_t tmp =
((usbData.count & 0x3ff) > BUF0SIZE) ?
BUF0SIZE : (usbData.count & 0x3ff);
usr2pma(usbData.baddr, getTableTxAddr(0), tmp);
usbData.baddr += tmp;
usbData.count -= tmp;
setTxCount(0, tmp);
//toggleTx(0);
in_stat += tmp;
saveRXst = NAK;
saveTXst = VALID;
} else { // Если нет
if (((USB->DADDR & 0x7f) == 0) && (usbData.daddr)) {
// Проверяем установлен ли адрес устройства
// Если нет устанавливаем
USB->DADDR = 0x80 | usbData.daddr;
saveRXst = VALID;
} else {
// и отправляем нулевой пакет
setTxCount(0, 0);
if (!(USB->EPR[0] & 0x40))
toggleTx(0);
saveTXst = VALID;
saveRXst = VALID;
}
}
}
}
void setup_process() {
switch (reqBuf.req.bReq) {
case 0: // GET_STATUS
bmap |= 1;
break;
case 1: // CLEAR_FEATURE
bmap |= 2;
break;
case 3: // SET_FEATURE
bmap |= 3;
break;
case 5: // SET_ADDRESS
bmap |= 8;
usbData.daddr = reqBuf.req.wValue;
usbData.count &= 0xf000;
setTxCount(0, 0);
saveTXst = VALID;
break;
case 6: // GET_DESCRIPTOR
bmap |= 0x10;
getDesc();
break;
case 7: // SET_DESCRIPTOR
bmap |= 0x20;
break;
case 8: // GET_CONFIGURATION
bmap |= 0x40;
getConfig();
break;
case 9: // SET_CONFIGURATION
bmap |= 0x80;
setConfig();
break;
}
}
/*
void EP0Interrupt() {
uint16_t tmp;
if (USB->ISTR & DIR) { // OUT reqest
clrCTR_rx(0);
if (USB->EPR[0] & SETUP) {
pbufcpy(reqBuf.buf, 0);
switch (reqBuf.req.bReq) {
case 0:
bmap |= 1;
pbufcpy(reqBuf.buf, 0);
break;
case 1:
bmap |= 2;
pbufcpy(reqBuf.buf, 0);
break;
case 3:
bmap |= 4;
pbufcpy(reqBuf.buf, 0);
break;
case 5:
bmap |= 8;
usbData.daddr = reqBuf.req.wValue;
in_stat = DSETADDR;
setTxCount(0, 0);
saveTXst = VALID;
//saveRXst = STALL;
break;
case 6:
bmap |= 0x10;
getDesc();
break;
case 7:
bmap |= 0x20;
break;
case 8:
bmap |= 0x40;
break;
case 9:
bmap |= 0x80;
break;
}
} else {
tmp = getTableRxCount(0);
if (tmp) {
saveRXst = VALID;
} else {
saveRXst = VALID;
if (usbData.count)
saveTXst = VALID;
}
//pbufcpy(reqBuf.buf, 0);
clrCTR_rx(0);
saveTXst = VALID;
saveRXst = VALID;
}
} else { // IN Request
// if (USB->EPR[0] & CTR_TX){
bmap |= 0x100;
//clrCTR_tx(0);
switch (in_stat) {
case DSETADDR:
USB->DADDR = 0x80 | usbData.daddr;
saveRXst = VALID;
break;
case POST0:
setTxCount(0, 0);
saveRXst = VALID;
break;
case POSTDATA:
if (usbData.count == 0) {
saveRXst = VALID;
return;
}
if (usbData.count >= BUF0SIZE)
tmp = BUF0SIZE;
else
tmp = usbData.count;
userpbuf(usbData.baddr, getTableTxAddr(0), tmp);
saveTXst = VALID;
setTxCount(0, tmp);
usbData.count -= tmp;
usbData.baddr += tmp;
if (usbData.count == 0)
in_stat = POST0;
clrCTR_rx(0);
//saveRXst = VALID;
//toggleTx(0);
break;
}
}
}
*/
void getDesc() {
uint8_t sw;
sw = reqBuf.req.wValue >> 8;
switch (sw) {
case 1:
getDeviceDesc(&reqBuf.req);
// lens[dcount++] = ur.wLen;
break;
case 2:
getConfigDesc();
break;
case 3:
getStringDesc();
break;
}
}
void getConfig() {
uint8_t cfg = 1;
usr2pma(&cfg,getTableTxAddr(0),1);
setTxCount(0,1);
usbData.count = 0;
saveTXst = VALID;
}
void setConfig() {
usbData.count = 0;
setTxCount(0,0);
saveTXst = VALID;
}
void getDeviceDesc(USBReqestType *ur) {
if (ur->wLen > BUF0SIZE) {
// userpbuf((uint8_t*) DeviceDescriptor, getTableTxAddr(0), BUF0SIZE);
usr2pma((uint8_t*) DeviceDescriptor, getTableTxAddr(0), BUF0SIZE);
usbData.baddr = &DeviceDescriptor[BUF0SIZE];
usbData.count = ur->wLen - BUF0SIZE;
setTxCount(0, BUF0SIZE);
saveTXst = VALID;
} else {
// userpbuf((uint8_t*) DeviceDescriptor, getTableTxAddr(0), ur->wLen);
usr2pma((uint8_t*) DeviceDescriptor, getTableTxAddr(0), ur->wLen);
usbData.count = 0;
setTxCount(0, ur->wLen);
saveTXst = VALID;
saveRXst = VALID;
}
/*
usbData.baddr = &DeviceDescriptor[BUF0SIZE];
usbData.count = ur->wLen - BUF0SIZE;
in_stat = POSTDATA;
setTxCount(0, BUF0SIZE);
saveTXst = VALID;
*/
}
void getConfigDesc() {
uint16_t len = reqBuf.req.wLen;
uint16_t gsize = (len > BUF0SIZE)? BUF0SIZE:len;
usr2pma((uint8_t*) ConfigDescriptor, getTableTxAddr(0), gsize);
usbData.baddr = &ConfigDescriptor[gsize];
usbData.count = len - gsize;
// in_stat = POSTDATA;
setTxCount(0, gsize);
saveTXst = VALID;
}
void getStringDesc() {
uint8_t *sel;
uint8_t cnt;
sel = strdesc[reqBuf.req.wValue & 0xff];
cnt = sel[0];
if (cnt > BUF0SIZE) {
usr2pma((uint8_t*) sel, getTableTxAddr(0), BUF0SIZE);
usbData.baddr = &sel[BUF0SIZE];
usbData.count = cnt - BUF0SIZE;
// in_stat = POSTDATA;
setTxCount(0, BUF0SIZE);
saveTXst = VALID;
} else {
usr2pma((uint8_t*) sel, getTableTxAddr(0), cnt);
// in_stat = POST0;
setTxCount(0, cnt);
saveTXst = VALID;
}
}
<file_sep>/*
* hw_init.c
*
* Created on: 25 янв. 2017 г.
* Author: valeriy
*/
#include "stm32f10x.h"
#include "usb.h"
void hw_init() {
// USB CLK Init инициализация тактирования USB
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
RCC->APB2ENR |= RCC_APB2ENR_IOPBEN;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
RCC_USBCLKConfig(RCC_USBCLKSource_PLLCLK_1Div5);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USB, ENABLE);
// USB Pin Config
GPIO_InitTypeDef io;
io.GPIO_Mode = GPIO_Mode_AF_PP;
io.GPIO_Pin = GPIO_Pin_11 | GPIO_Pin_12;
io.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &io);
// port B init (leds) open Drain
GPIOB->CRH |= 0x11;
GPIOB->ODR |= 0x300;
/*
io.GPIO_Mode = GPIO_Mode_Out_PP;
io.GPIO_Pin = GPIO_Pin_5;
io.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_Init(GPIOA, &io);
io.GPIO_Mode = GPIO_Mode_IN_FLOATING;
io.GPIO_Pin = GPIO_Pin_11;
io.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_Init(GPIOC, &io);
io.GPIO_Mode = GPIO_Mode_Out_OD;
io.GPIO_Pin = GPIO_Pin_12;
io.GPIO_Speed = GPIO_Speed_10MHz;
GPIO_Init(GPIOC, &io);
AFIO->EXTICR[2] |= AFIO_EXTICR3_EXTI11_PC;
EXTI->IMR |= EXTI_IMR_MR11;
EXTI->RTSR |= EXTI_RTSR_TR11;
EXTI->FTSR |= EXTI_FTSR_TR11;
*/
}
void intToUni(uint32_t ui, uint8_t *buf, uint8_t len) {
uint8_t i1,i2;
for (i1 = 0; i1 < len; i1++) {
i2 = ui >> 28;
buf[2*i1] = i2 + (i2 < 0xa)?'0':('A' - 10);
ui <<= 4;
buf[(2*i1)+1] = 0;
}
}
<file_sep>/*
* usb.h
*
* Created on: 8 июн. 2017 г.
* Author: valeriy
*/
#ifndef USB_H_
#define USB_H_
#define EPCOUNT 3
#define USB_BASE ((uint32_t)0x40005C00)
#define USB_PBUFFER ((uint32_t)0x40006000)
#define EP_BULK 0
#define EP_CONTROL 0x200
#define EP_ISO 0x400
#define EP_INT 0x600
#define SDIS 0
#define STALL 1
#define NAK 2
#define VALID 3
#define STRX 12
#define STTX 4
#define SETUP 0x800
#define DTOG_RX 0x4000
#define DTOG_TX 0x40
#define DIR 0x10
#define CTR_RX 0x8000
#define CTR_TX 0x80
#define EP_KIND 0x100
#define RXCNT(bsize,nblock) (uint16_t)(((bsize & 1) << 15) | ((nblock & 31) << 10))
#pragma pack(push,1)
typedef struct {
unsigned rec:5;
unsigned type:2;
unsigned dir:1;
}ReqType;
typedef struct {
ReqType bmReq;
uint8_t bReq;
uint16_t wValue;
uint16_t wIndex;
uint16_t wLen;
} USBReqestType;
#pragma pack(pop)
typedef struct {
uint32_t EPR[8];
uint32_t RESERVED[8];
uint32_t CNTR;
uint32_t ISTR;
uint32_t FNR;
uint32_t DADDR;
uint32_t BTABLE;
}USB_TypeDef;
#define USB ((USB_TypeDef *)USB_BASE)
typedef struct {
uint16_t mem;
uint16_t reserv;
}PBElement;
typedef struct {
PBElement addr;
PBElement count;
}BTElement;
typedef struct {
BTElement tx;
BTElement rx;
}BTable;
#pragma pack(push,2)
typedef union {
struct {
unsigned count:10;
unsigned nblok:5;
unsigned bsize:1;
} f;
uint16_t word;
}RXCount;
typedef union {
uint16_t w;
struct BW {
uint8_t bb1;
uint8_t bb0;
} bw;
} uint16_t_uint8_t;
#pragma pack(pop)
#ifdef MYUSBLIB
extern BTable *table;
extern PBElement *PBuffer;
extern uint8_t DeviceDescriptor[];
extern uint8_t ConfigDescriptor[];
extern uint8_t StringLangID[];
extern uint8_t StringVendor[];
extern uint8_t StringProduct[];
extern uint8_t StringSerial[];
#endif
void usb_init();
void setTableTx(uint8_t inx, uint16_t addr, uint16_t count);
void setTableRx(uint8_t inx, uint16_t addr, uint16_t count);
uint16_t getTableTxAddr(uint8_t ep);
uint16_t getTableRxAddr(uint8_t ep);
uint16_t getTableRxCount(uint8_t ep);
void setTxCount(uint8_t ep, uint16_t cnt);
void setRxCount(uint8_t ep, uint16_t cnt);
void setEPType(uint8_t ep, uint16_t type);
void setStatTx(uint8_t ep, uint16_t stat);
void setStatRx(uint8_t ep, uint16_t stat);
void clrCTR_tx(uint8_t ep);
void clrCTR_rx(uint8_t ep);
void toggleRx(uint8_t ep);
void toggleTx(uint8_t ep);
void usr2pma(uint8_t *src, uint16_t addr, uint16_t cnt);
void pma2usr(uint8_t *dst, uint16_t addr, uint16_t cnt);
#endif /* USB_H_ */
<file_sep>/*
* usb.c
*
* Created on: 8 июн. 2017 г.
* Author: valeriy
*/
#include "stm32f10x.h"
#include "usb.h"
#define EPCOUNT 3
#define BLSIZE 0x8000
void usb_ctr_int();
void usb_pma_int();
void usb_err_int();
void usb_reset_int();
void usb_sof_int();
void usb_esof_int();
volatile uint16_t intStat;
BTable *table = (BTable*) USB_PBUFFER;
PBElement *PBuffer = (PBElement*) USB_PBUFFER;
//volatile RXCount rx1;
void usb_init() {
intStat = 0;
NVIC_EnableIRQ(USB_LP_CAN1_RX0_IRQn);
// NVIC_EnableIRQ(USB_HP_CAN1_TX_IRQn);
USB->BTABLE = 0;
USB->DADDR = 0;
USB->CNTR = (1 << 10);
USB->ISTR = 0;
GPIOC->CRL |= GPIO_CRL_MODE7_1;
// USB->DADDR = 0x80;
// USB_CNTR_CTRM;
}
void setTableTx(uint8_t inx, uint16_t addr, uint16_t count) {
table[inx].tx.addr.mem = addr;
table[inx].tx.count.mem = count;
}
inline void setTxCount(uint8_t ep, uint16_t cnt) {
table[ep].tx.count.mem = cnt;
}
inline uint16_t getTableTxAddr(uint8_t ep) {
return (table[ep].tx.addr.mem);
}
void setTableRx(uint8_t inx, uint16_t addr, uint16_t count) {
table[inx].rx.addr.mem = addr;
table[inx].rx.count.mem = count;
}
inline void setRxCount(uint8_t ep, uint16_t cnt) {
table[ep].rx.count.mem = cnt;
}
inline uint16_t getTableRxAddr(uint8_t ep) {
return (table[ep].rx.addr.mem);
}
inline uint16_t getTableRxCount(uint8_t ep) {
return ((table[ep].rx.count.mem) & 0x3ff);
}
/*
uint16_t rxcnt(uint16_t bsize, uint16_t nblock) {
uint16_t tmp = ((bsize & 1) << 15) | ((nblock & 31) << 10);
return tmp;
}
*/
void setEPType(uint8_t ep, uint16_t type) {
register uint16_t tmp = USB->EPR[ep] & 0x10f;
tmp |= type | CTR_RX | CTR_TX;
USB->EPR[ep] = tmp;
}
void toggleRx(uint8_t ep) {
register uint16_t tmp = USB->EPR[ep] & 0x70f;
tmp |= CTR_RX | CTR_TX | 0x4000;
USB->EPR[ep] = tmp;
}
void toggleTx(uint8_t ep) {
register uint16_t tmp = USB->EPR[ep] & 0x70f;
tmp |= CTR_RX | CTR_TX | 0x40;
USB->EPR[ep] = tmp;
}
void setStatTx(uint8_t ep, uint16_t stat) {
register uint16_t tmp = USB->EPR[ep] & 0x73f;
tmp ^= (stat << STTX);
USB->EPR[ep] = tmp | CTR_RX | CTR_TX;
}
void setStatRx(uint8_t ep, uint16_t stat) {
register uint16_t tmp = USB->EPR[ep] & 0x370f;
tmp ^= (stat << STRX);
USB->EPR[ep] = tmp | CTR_RX | CTR_TX;
}
inline void clrCTR_rx(uint8_t ep) {
USB->EPR[ep] &= 0x78f;
}
inline void clrCTR_tx(uint8_t ep) {
USB->EPR[ep] &= 0x870f;
}
/*
void clrCTR_rx(uint8_t ep) {
uint16_t tmp = USB->EPR[ep] & 0x78f;
USB->EPR[0] = tmp;
}
void clrCTR_tx(uint8_t ep) {
uint16_t tmp = USB->EPR[ep] & 0x870f;
USB->EPR[0] = tmp;
}
*/
void usr2pma(uint8_t *src, uint16_t addr, uint16_t cnt) {
while (cnt--) {
if (addr & 1) {
PBuffer[addr >> 1].mem |= (*(src++) << 8);
addr++;
} else {
PBuffer[addr >> 1].mem = *(src++);
addr++;
}
}
}
void pma2usr(uint8_t *dst, uint16_t addr, uint16_t cnt) {
while (cnt--) {
*(dst++) =
(addr & 1) ?
((PBuffer[addr >> 1].mem) >> 8) :
(PBuffer[addr >> 1].mem);
addr++;
}
}
void tableInit() {
uint16_t tstart = EPCOUNT << 3;
setTableTx(0, tstart, 16);
setTableRx(0, tstart + 16, RXCNT(0, 4));
setTableTx(1, tstart + 24, 16);
setTableRx(2, tstart + 40, RXCNT(0, 8));
}
void ep_init() {
tableInit();
for (uint8_t i = 0; i < 8; i++) {
uint16_t tmp = USB->EPR[i];
tmp &= 0x7070;
tmp |= i;
USB->EPR[i] = tmp;
}
USB->ISTR = 0;
USB->CNTR |= 0x8600;
setEPType(0, EP_CONTROL);
setStatRx(0, VALID);
USB->DADDR = 0x80;
}
/*
static void IntToUnicode(uint32_t value, uint8_t *pbuf, uint8_t len) {
uint8_t idx = 0;
for (idx = 0; idx < len; idx++) {
if (((value >> 28)) < 0xA) {
pbuf[2 * idx] = (value >> 28) + '0';
} else {
pbuf[2 * idx] = (value >> 28) + 'A' - 10;
}
value = value << 4;
pbuf[2 * idx + 1] = 0;
}
}
*/
void USB_LP_CAN1_RX0_IRQHandler() {
if (USB->ISTR & (1 << 15)) {
usb_ctr_int();
return;
}
if (USB->ISTR & (1 << 14)) {
USB->ISTR = ~(1 << 14);
usb_pma_int();
return;
}
if (USB->ISTR & (1 << 13)) {
usb_err_int();
USB->ISTR = ~(1 << 13);
return;
}
if (USB->ISTR & (1 << 10)) {
USB->ISTR = ~(1 << 10);
usb_reset_int();
return;
}
if (USB->ISTR & (1 << 9)) {
USB->ISTR = ~(1 << 9);
usb_sof_int();
return;
}
if (USB->ISTR & (1 << 8)) {
USB->ISTR = ~(1 << 8);
usb_esof_int();
return;
}
}
void USB_HP_CAN1_TX_IRQHandler(void) {
uint16_t isr, ep;
isr = USB->ISTR;
if (isr & 0x8000) {
ep = isr & 0xf;
USB->EPR[ep] &= 0x3f;
}
}
|
9896491a12fd828d25635012a56f0a822a82e5c1
|
[
"C"
] | 5
|
C
|
Void1509/tstusb
|
0ed710890b536b4c06f14e8f5265de3d0fabcdae
|
d21469f6ba980bf4a582c762c70980489c72f6c8
|
refs/heads/master
|
<repo_name>DisSh33/identity-server<file_sep>/my.identity.server/AppSettings.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityModel;
using IdentityServer4;
using IdentityServer4.Models;
using mi.identity.server.Data.DataAccess;
using mi.identity.server.ViewModels;
using Microsoft.Extensions.Configuration;
namespace mi.identity.server
{
public class AppSettings
{
public readonly Common Common = new Common();
public readonly DataAccessConstants DataAccessConstants = new DataAccessConstants();
public IConfiguration Configuration { get; }
#if DEBUG
private const string DefaultEnvironmentName = "debug";
#elif RELEASE
private const string DefaultEnvironmentName = "release";
#endif
public AppSettings()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
.AddJsonFile($"appsettings.{DefaultEnvironmentName}.json", optional: true, reloadOnChange: false);
Configuration = builder.Build();
Configuration.GetSection("Common").Bind(Common);
Configuration.GetSection("DataAccessConstants").Bind(DataAccessConstants);
}
public IEnumerable<ApiScope> GetApisScope()
{
return new List<ApiScope>
{
new ApiScope { Name = "shared.scope" },
new ApiScope { Name = "my.admin.scope" },
new ApiScope { Name = "my.dashboard.scope" }
};
}
public IEnumerable<ApiResource> GetApis()
{
return new List<ApiResource>
{
new ApiResource
{
Name = "my.identity.api",
Scopes = { "shared.scope", "my.admin.scope" },
UserClaims = { "role", "full_access" }
},
new ApiResource
{
Name = "my.dashboard.api",
Scopes = { "shared.scope", "my.dashboard.scope" },
UserClaims = { "role", "full_access" }
}
};
}
public IEnumerable<Client> GetClients() =>
new List<Client>
{
new Client
{
ClientId = "my.identity.client.mvc",
ClientSecrets = {new Secret("secret_my.identity.client.mvc_secret".ToSha256())},
AllowedGrantTypes = GrantTypes.Code,
RequireConsent = false,
RequirePkce = true,
RedirectUris = {$"{Common.IdentityServer.Authority}/signin-oidc"},
PostLogoutRedirectUris = { $"{Common.IdentityServer.Authority}/signout-callback-oidc"},
AlwaysIncludeUserClaimsInIdToken = true,
AccessTokenLifetime = TimeSpan.FromDays(1).Seconds,
AllowOfflineAccess = true,
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
"offline_access",
"shared.scope",
"my.admin.scope"
}
},
new Client
{
ClientId = "my.identity.api.client",
ClientSecrets = {new Secret("secret_my.identity.api.client_secret".ToSha256())},
AllowedGrantTypes = GrantTypes.ClientCredentials,
AccessTokenLifetime = TimeSpan.FromDays(1).Seconds,
AllowOfflineAccess = true,
AllowedScopes =
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
IdentityServerConstants.StandardScopes.Email,
"offline_access",
"shared.scope",
"my.admin.scope"
}
},
};
public IEnumerable<IdentityResource> GetIdentityResources()
{
return new List<IdentityResource>
{
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email(),
new IdentityResource
{
Name = "my.identity_resourse",
UserClaims ={ "role", "full_access" },
}
};
}
}
public class Common
{
public HostSettings Host { get; set; }
public IdentitySettings IdentityServer { get; set; }
}
public class HostSettings
{
public string IpAddress { get; set; }
public int HttpPort { get; set; }
public int HttpsPort { get; set; }
public string Root { get; set; }
}
public class IdentitySettings
{
public string Authority { get; set; }
}
}
<file_sep>/my.identity.server/Controllers/ClaimController.cs
using System.Threading.Tasks;
using MediatR;
using mi.identity.server.Data.DataAccess.Commands;
using mi.identity.server.Data.DataAccess.Responses;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace mi.identity.server.Controllers
{
[Route("api/claim")]
[ApiController]
[Authorize]
public class ClaimController : ControllerBase
{
private readonly IMediator _mediator;
public ClaimController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPost]
[Route("")]
public async Task<ClaimResponse> Create([FromBody]ClaimCreateCommand command)
{
return await _mediator.Send(command);
}
[HttpDelete]
[Route("")]
public async Task<ClaimResponse> Delete([FromBody]ClaimDeleteCommand command)
{
return await _mediator.Send(command);
}
}
}
<file_sep>/my.identity.client.test/Startup.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Serilog;
namespace mi.identity.client.test
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(config =>
{
config.DefaultScheme = "Cookie";
config.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookie", config =>
{
config.Cookie.SecurePolicy = CookieSecurePolicy.None;
//config.Cookie.SameSite = SameSiteMode.Unspecified;
})
.AddOpenIdConnect("oidc", config => {
config.Authority = $"{AppSettings.Common.IdentityServer.Authority}";
config.SignInScheme = "Cookie";
config.RequireHttpsMetadata = false;
config.ClientId = "my.identity.client.mvc";
config.ClientSecret = "secret_my.identity.client.mvc_secret";
config.ResponseType = "code";
config.SaveTokens = true;
config.SignedOutCallbackPath = "/identity/signout-callback-oidc";
config.GetClaimsFromUserInfoEndpoint = true;
config.ClaimActions.MapAll();
config.Scope.Add("shared.scope");
config.Scope.Add("my.admin.scope");
config.Scope.Add("openid");
config.Scope.Add("profile");
config.Scope.Add("offline_access");
});
services.AddHttpClient();
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Use(async (context, next) =>
{
context.Request.Scheme = "https";
await next.Invoke();
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireAuthorization();
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}").RequireAuthorization();
});
}
}
}
<file_sep>/my.identity.server/Data/DataAccess/Responses/UserRoleResponse.cs
using mi.identity.server.ViewModels;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Responses
{
public class UserRoleResponse
{
public IdentityRole Role { get; set; }
public ProfileViewModel User { get; set; }
}
}
<file_sep>/my.identity.server/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace mi.identity.server.Controllers
{
public class HomeController : Controller
{
private IIdentityServerInteractionService _identityServerInteractionService;
public HomeController(IIdentityServerInteractionService identityServerInteractionService)
{
_identityServerInteractionService = identityServerInteractionService;
}
[Route("error")]
public async Task<object> Error(string errorId)
{
return await _identityServerInteractionService.GetErrorContextAsync(errorId);
}
}
}
<file_sep>/my.identity.server/Program.cs
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Mappers;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace mi.identity.server
{
public class Program
{
public static void Main(string[] args)
{
var appSettings = new AppSettings();
var host = CreateHostBuilder(args).Build();
using (var scope = host.Services.CreateScope())
{
#region ConfigurationDbSeedScript
//var context = scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
//if (!context.Clients.Any())
//{
// foreach (var client in appSettings.GetClients())
// {
// context.Clients.Add(client.ToEntity());
// }
// context.SaveChanges();
//}
//if (!context.IdentityResources.Any())
//{
// foreach (var resource in appSettings.GetIdentityResources())
// {
// context.IdentityResources.Add(resource.ToEntity());
// }
// context.SaveChanges();
//}
//if (!context.ApiScopes.Any())
//{
// foreach (var resource in appSettings.GetApisScope())
// {
// context.ApiScopes.Add(resource.ToEntity());
// }
// context.SaveChanges();
//}
//if (!context.ApiResources.Any())
//{
// foreach (var resource in appSettings.GetApis())
// {
// context.ApiResources.Add(resource.ToEntity());
// }
// context.SaveChanges();
//}
#endregion
}
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
var appSettings = new AppSettings();
var hostSettings = appSettings.Common.Host;
var urls = new List<string>()
{
$"http://{hostSettings.IpAddress}:{hostSettings.HttpPort}"
};
if (hostSettings.HttpsPort > 0)
{
urls.Add($"https://{hostSettings.IpAddress}:{hostSettings.HttpsPort}");
}
return Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseStartup<Startup>()
.UseUrls(urls.ToArray());
});
}
}
}
<file_sep>/my.identity.client.test/Controllers/TokenController.cs
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace mi.identity.client.test.Controllers
{
public class TokenController : Controller
{
private readonly IHttpClientFactory _httpClientFactory;
public TokenController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[AllowAnonymous]
public async Task<IActionResult> Index()
{
var accessToken = await HttpContext.GetTokenAsync("access_token");
var idToken = await HttpContext.GetTokenAsync("id_token");
if (accessToken != null && idToken != null)
{
var _claims = User.Claims.ToList();
var _accessToken = new JwtSecurityTokenHandler().ReadJwtToken(accessToken);
var _idToken = new JwtSecurityTokenHandler().ReadJwtToken(idToken);
}
var apiClient = _httpClientFactory.CreateClient();
apiClient.SetBearerToken(accessToken);
var response = await apiClient.GetAsync($"https://{AppSettings.Common.Api.IpAddress}:{AppSettings.Common.Api.HttpsPort}/secret");
var content = await response.Content.ReadAsStringAsync();
var output = new OutputViewModel
{
Content = content
};
return View(output);
}
}
}
<file_sep>/my.identity.server/Data/DataAccess/Commands/User/AddClaimCommand.cs
using IdentityServer4.EntityFramework.Entities;
using MediatR;
using mi.identity.server.Data.DataAccess.Responses;
using mi.identity.server.Models;
using mi.identity.server.ViewModels;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Commands.User
{
public class AddClaimCommand : IRequest<UserClaimResponse>
{
public string UserId { get; set; }
public ClaimViewModel Claim { get; set; }
public AddClaimCommand()
{
}
public AddClaimCommand(string userId, ClaimViewModel claim)
{
UserId = userId;
Claim = claim;
}
}
public class AddClaimHandler : IRequestHandler<AddClaimCommand, UserClaimResponse>
{
private readonly AppDbContext _appDbContext;
private readonly UserManager<ApplicationUser> _userManager;
private readonly IMediator _mediator;
public AddClaimHandler(
AppDbContext appDbContext,
UserManager<ApplicationUser> userManager,
IMediator mediator)
{
_appDbContext = appDbContext;
_userManager = userManager;
_mediator = mediator;
}
public async Task<UserClaimResponse> Handle(AddClaimCommand request, CancellationToken cancellationToken)
{
var user = await _userManager.FindByIdAsync(request.UserId);
var existingClaim = _appDbContext.UserClaims.FirstOrDefault(c => c.ClaimType == request.Claim.Type && c.UserId == request.UserId);
if (existingClaim != null)
{
await _userManager.ReplaceClaimAsync(user, existingClaim.ToClaim(), new Claim(request.Claim.Type, request.Claim.Value));
}
else
{
await _mediator.Send(new ClaimCreateCommand(request.Claim.Type, request.Claim.ApiResourceName, request.Claim.IdentityResourceName));
await _userManager.AddClaimAsync(user, new Claim(request.Claim.Type, request.Claim.Value));
}
return new UserClaimResponse
{
Type = request.Claim.Type,
Value = request.Claim.Value,
User = new ProfileViewModel(user)
};
}
}
}
<file_sep>/my.identity.server/Data/DataAccess/Queries/UserGetByIdQuery.cs
using MediatR;
using mi.identity.server.Data.DataAccess.Responses;
using mi.identity.server.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Queries
{
public class UserGetByIdQuery : IRequest<ProfileViewModel>
{
public string UserId { get; set; }
public UserGetByIdQuery(string userId)
{
UserId = userId;
}
}
public class UserGetByIdHandler : IRequestHandler<UserGetByIdQuery, ProfileViewModel>
{
private readonly AppDbContext _appDbContext;
public UserGetByIdHandler(AppDbContext appDbContext)
{
_appDbContext = appDbContext;
}
public async Task<ProfileViewModel> Handle(UserGetByIdQuery request, CancellationToken cancellationToken)
{
return new ProfileViewModel(_appDbContext.Users.FirstOrDefault(user => user.Id == request.UserId));
}
}
}
<file_sep>/my.identity.server/Data/DataAccess/Responses/UserClaimResponse.cs
using mi.identity.server.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Responses
{
public class UserClaimResponse
{
public string Type { get; set; }
public string Value { get; set; }
public ProfileViewModel User { get; set; }
}
}
<file_sep>/my.identity.server/Controllers/UserController.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MediatR;
using mi.identity.server.Data.DataAccess.Commands.User;
using mi.identity.server.Data.DataAccess.Queries;
using mi.identity.server.Data.DataAccess.Responses;
using mi.identity.server.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace mi.identity.server.Controllers
{
[Route("api/user")]
[ApiController]
[Authorize]
public class UserController : ControllerBase
{
private readonly IMediator _mediator;
public UserController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
[Route("{userId}")]
public async Task<ProfileViewModel> GetById([FromRoute]string userId)
{
return await _mediator.Send(new UserGetByIdQuery(userId));
}
[HttpGet]
[Route("")]
public async Task<List<ProfileViewModel>> GetAll()
{
return await _mediator.Send(new UserGetAllQuery());
}
[HttpPost]
[Route("")]
public async Task<UserResponse> Create([FromBody]UserCreateCommand command)
{
return await _mediator.Send(command);
}
[HttpDelete]
[Route("{userId}")]
public async Task<ProfileViewModel> Delete([FromRoute] string userId)
{
return await _mediator.Send(new UserDeleteCommand(userId));
}
[HttpPost]
[Route("{userId}/role")]
public async Task<UserRoleResponse> AddRole([FromRoute]string userId, string roleName)
{
return await _mediator.Send(new AssignRoleCommand(userId, roleName));
}
[HttpDelete]
[Route("{userId}/role")]
public async Task<UserRoleResponse> RemoveRole([FromRoute]string userId, string roleName)
{
return await _mediator.Send(new RemoveRoleCommand(userId, roleName));
}
[HttpPost]
[Route("{userId}/claim")]
public async Task<UserClaimResponse> AddClaim([FromRoute]string userId, [FromBody]ClaimViewModel claim)
{
return await _mediator.Send(new AddClaimCommand(userId, claim));
}
[HttpPut]
[Route("{userId}/claim")]
public async Task<UserClaimResponse> ChangeClaim([FromRoute]string userId,[FromBody] ClaimViewModel claim)
{
return await _mediator.Send(new ChangeClaimCommand(userId, claim));
}
[HttpDelete]
[Route("{userId}/claim")]
public async Task<UserClaimResponse> RemoveClaim([FromRoute]string userId, [FromBody]ClaimViewModel claim)
{
return await _mediator.Send(new RemoveClaimCommand(userId, claim));
}
}
}
<file_sep>/my.identity.server/Data/DataAccess/Commands/ClaimCreateCommand.cs
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Entities;
using MediatR;
using mi.identity.server.Data.DataAccess.Responses;
using mi.identity.server.ViewModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Commands
{
public class ClaimCreateCommand : IRequest<ClaimResponse>
{
public string Type { get; set; }
public string ApiResourceName { get; set; }
public string IdentityResourceName { get; set; }
public ClaimCreateCommand()
{
}
public ClaimCreateCommand(string type)
{
Type = type;
}
public ClaimCreateCommand(string type, string apiResourceName, string identityResourceName)
{
Type = type;
ApiResourceName = apiResourceName;
IdentityResourceName = identityResourceName;
}
}
public class ClaimCreateHandler : IRequestHandler<ClaimCreateCommand, ClaimResponse>
{
private readonly ConfigurationDbContext _configurationDbContext;
public DataAccessConstants DataAccessConstants { get; set; }
public ClaimCreateHandler(ConfigurationDbContext configurationDbContext)
{
_configurationDbContext = configurationDbContext;
var appSettings = new AppSettings();
DataAccessConstants = appSettings.DataAccessConstants;
}
public async Task<ClaimResponse> Handle(ClaimCreateCommand request, CancellationToken cancellationToken)
{
var apiResource = await AddToApiResources(request);
var identityResource = await AddToIdentityResources(request);
return new ClaimResponse
{
Type = request.Type,
ApiResource = new ResourceViewModel
{
Id = apiResource.Id,
Name = apiResource.Name
},
IdentityResource = new ResourceViewModel
{
Id = identityResource.Id,
Name = identityResource.Name
}
};
}
private async Task<ApiResource> AddToApiResources(ClaimCreateCommand request)
{
var apiResourceName = request.ApiResourceName;
if (string.IsNullOrEmpty(request.ApiResourceName))
{
apiResourceName = DataAccessConstants.DefaultApiResourceName;
}
var apiResource =
_configurationDbContext.ApiResources
.Include(x => x.UserClaims)
.FirstOrDefault(resource => resource.Name == apiResourceName);
if (apiResource != null)
{
var apiClaims = apiResource.UserClaims ?? new List<ApiResourceClaim>();
if (apiClaims.FirstOrDefault(claim => claim.Type == request.Type) == null)
{
apiClaims.Add(new ApiResourceClaim
{
Type = request.Type,
ApiResourceId = apiResource.Id
});
apiResource.UserClaims = apiClaims;
_configurationDbContext.Update(apiResource);
await _configurationDbContext.SaveChangesAsync();
}
}
return apiResource;
}
private async Task<IdentityResource> AddToIdentityResources(ClaimCreateCommand request)
{
var identityResourceName = request.IdentityResourceName;
if (string.IsNullOrEmpty(request.IdentityResourceName))
{
identityResourceName = DataAccessConstants.DefaultIdentityResourceName;
}
var identityResource =
_configurationDbContext.IdentityResources
.Include(x => x.UserClaims)
.FirstOrDefault(resource => resource.Name == identityResourceName);
if (identityResource != null)
{
var identityClaims = identityResource.UserClaims ?? new List<IdentityResourceClaim>();
if (identityClaims.FirstOrDefault(claim => claim.Type == request.Type) == null)
{
identityClaims.Add(new IdentityResourceClaim()
{
Type = request.Type,
IdentityResourceId = identityResource.Id
});
identityResource.UserClaims = identityClaims;
_configurationDbContext.Update(identityResource);
await _configurationDbContext.SaveChangesAsync();
}
}
return identityResource;
}
}
}
<file_sep>/my.identity.server/Data/DataAccess/Commands/User/RemoveClaimCommand.cs
using MediatR;
using mi.identity.server.Data.DataAccess.Responses;
using mi.identity.server.Models;
using mi.identity.server.ViewModels;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Commands.User
{
public class RemoveClaimCommand : IRequest<UserClaimResponse>
{
public string UserId { get; set; }
public ClaimViewModel Claim { get; set; }
public RemoveClaimCommand()
{
}
public RemoveClaimCommand(string userId, ClaimViewModel claim)
{
UserId = userId;
Claim = claim;
}
}
public class RemoveClaimHandler : IRequestHandler<RemoveClaimCommand, UserClaimResponse>
{
private readonly AppDbContext _appDbContext;
private readonly UserManager<ApplicationUser> _userManager;
public RemoveClaimHandler( AppDbContext appDbContext, UserManager<ApplicationUser> userManager)
{
_appDbContext = appDbContext;
_userManager = userManager;
}
public async Task<UserClaimResponse> Handle(RemoveClaimCommand request, CancellationToken cancellationToken)
{
var user = await _userManager.FindByIdAsync(request.UserId);
var claimToRemove = _appDbContext.UserClaims.FirstOrDefault(c => c.ClaimType == request.Claim.Type && c.UserId == request.UserId);
if (claimToRemove != null)
{
await _userManager.RemoveClaimAsync(user, claimToRemove.ToClaim());
}
return new UserClaimResponse
{
Type = claimToRemove?.ClaimType,
Value = claimToRemove?.ClaimValue,
User = new ProfileViewModel(user)
};
}
}
}
<file_sep>/my.identity.server/ViewModels/ClientCredentialsViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace mi.identity.server.ViewModels
{
public class ClientCredentialsViewModel
{
public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string Scope { get; set; }
}
}
<file_sep>/README.md
# Identity-Server
Authrization server using OAuth 2.0 and IdentityServer4 with test api, test mvc-client and test api-client

During the work on the project:
• The Authorization Server was designed using IdentyServer4 and OAuth 2.0, which supports various types of authorization (authorization code, implicit, client credentials, hybrid)
• A database (PostgeSQL) has been created to store user models and configuration of the authorization server (information about client applications, settings for access tokens, api resources, orders and volumes)
• Possibility of authorization using both access_token and cookies (the ability to authorize both specific users and external services)
• Developed and configured a test API with a closed authorization method
• Developed and configured a test MVC client and an API client for testing various authorization options through the server
• The architecture and methods of interaction of the authorization server with closed APIs and client applications have been developed
• An API has been added to the authorization server for managing users, their roles and items
• User data management and corresponding API methods are implemented using SQRC and Mediator templates (using MediatR library), as well as EntityFramework Core as ORM
• Policy and claims used to control user and service access
• Implemented support for refresh_token and offline_access
• Added additional settings for SameSiteCookiePolicy for correct operation in newer versions of browsers
------------------------------------------------------------------------------------------
В ходе работы над проектом:
• Разработан сервер авторизации с использованием IdentyServer4 и протокола OAuth 2.0, поддерживающий различные типы авторизации (Authorization code, Implicit, Client credentials, Hybrid)
• Создана база данных (PostgeSQL) для хранения моделей пользователей и конфигурации сервера авторизации (информация о приложениях-клиентах, настройки для access tokens, api resources, claims и scopes)
• Возможность авторизации как с помощью access_token, так и с помощью cookies (возможность авторизации как конкретных пользователей, так и внешних сервисов)
• Разработано и настроено тестовое API с закрытым авторизацией методом
• Разработаны и настроены тестовые MVC-клиент и API-клиент для проверки различных вариантов авторизации через сервер
• Проработана архитектура и способы взаимодействия для сервера авторизации с закрытыми API и приложениями-клиентами
• К серверу авторизации добавлено API для управления пользователями, их ролями и клаймами
• Управление данными пользователей и соответсвующие API-методы реализованы с помощью паттернов SQRC и Mediator (использована библиотека MediatR), а также EntityFramework Core в качестве ORM
• Использованы policy и claims для управления доступом пользователей и сервисов
• Реализована поддержка refresh_token и offline_access
• Добавлены дополнительные настройки для SameSiteCookiePolicy для корректной работы в новых версиях браузеров
<file_sep>/my.identity.server/Data/DataAccess/Commands/User/ChangeClaimCommand.cs
using MediatR;
using mi.identity.server.Data.DataAccess.Responses;
using mi.identity.server.Models;
using mi.identity.server.ViewModels;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Commands.User
{
public class ChangeClaimCommand : IRequest<UserClaimResponse>
{
public string UserId { get; set; }
public ClaimViewModel Claim { get; set; }
public ChangeClaimCommand()
{
}
public ChangeClaimCommand(string userId, ClaimViewModel claim)
{
UserId = userId;
Claim = claim;
}
}
public class ChangeClaimHandler : IRequestHandler<ChangeClaimCommand, UserClaimResponse>
{
private readonly AppDbContext _appDbContext;
private readonly UserManager<ApplicationUser> _userManager;
private readonly IMediator _mediator;
public ChangeClaimHandler(
AppDbContext appDbContext,
UserManager<ApplicationUser> userManager,
IMediator mediator)
{
_appDbContext = appDbContext;
_userManager = userManager;
_mediator = mediator;
}
public async Task<UserClaimResponse> Handle(ChangeClaimCommand request, CancellationToken cancellationToken)
{
var user = await _userManager.FindByIdAsync(request.UserId);
var claimToChange = _appDbContext.UserClaims.FirstOrDefault(c => c.ClaimType == request.Claim.Type && c.UserId == request.UserId);
if (claimToChange != null)
{
await _userManager.ReplaceClaimAsync(user, claimToChange.ToClaim(), new Claim(request.Claim.Type, request.Claim.Value));
}
else
{
await _mediator.Send(new AddClaimCommand(request.UserId, request.Claim));
}
return new UserClaimResponse
{
Type = request.Claim.Type,
Value = request.Claim.Value,
User = new ProfileViewModel(user)
};
}
}
}
<file_sep>/my.identity.client.test/AppSettings.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
namespace mi.identity.client.test
{
public static class AppSettings
{
public static readonly Common Common = new Common();
public static IConfiguration Configuration { get; }
#if DEBUG
private const string DefaultEnvironmentName = "debug";
#elif RELEASE
private const string DefaultEnvironmentName = "release";
#endif
static AppSettings()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false)
.AddJsonFile($"appsettings.{DefaultEnvironmentName}.json", optional: true, reloadOnChange: false);
Configuration = builder.Build();
Configuration.GetSection("Common").Bind(Common);
}
}
public class Common
{
public HostSettings Host { get; set; }
public HostSettings Api { get; set; }
public IdentitySettings IdentityServer { get; set; }
}
public class HostSettings
{
public string IpAddress { get; set; }
public int HttpPort { get; set; }
public int HttpsPort { get; set; }
public string Root { get; set; }
}
public class IdentitySettings
{
public string Authority { get; set; }
}
}<file_sep>/my.identity.api.client/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace mi.identity.api.client.Controllers
{
[Route("home")]
public class HomeController : Controller
{
public IActionResult Index()
{
return Ok("OK test");
}
}
}<file_sep>/my.identity.server/Data/Migrations/AppMigrations/20201029205223_AppUsers.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace mi.identity.server.Data.Migrations.AppMigrations
{
public partial class AppUsers : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
}
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
<file_sep>/my.identity.server/Controllers/IdentityController.cs
using System;
using System.Threading.Tasks;
using mi.identity.server.Models;
using mi.identity.server.ViewModels;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace mi.identity.server.Controllers
{
[ApiController]
[Route("api/identity")]
public class IdentityController : ControllerBase
{
private readonly SignInManager<ApplicationUser> _signInManager;
public IdentityController(SignInManager<ApplicationUser> signInManager)
{
_signInManager = signInManager;
}
[HttpPost]
[Route("login")]
public async Task<object> Login(LoginViewModel vm)
{
var result = await _signInManager.PasswordSignInAsync(vm.Username, vm.Password, false, false);
if (result.Succeeded)
{
return _signInManager.Context.Request.Cookies;
}
return new ProfileViewModel();
}
}
}
<file_sep>/my.identity.server/Controllers/AuthController.cs
using System;
using System.Threading.Tasks;
using IdentityServer4.Services;
using mi.identity.server.Models;
using mi.identity.server.ViewModels;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace mi.identity.server.Controllers
{
[Route("auth")]
public class AuthController : Controller
{
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IIdentityServerInteractionService _interactionService;
public AuthController(SignInManager<ApplicationUser> signInManager, IIdentityServerInteractionService interactionService)
{
_signInManager = signInManager;
_interactionService = interactionService;
}
[HttpGet]
[Route("logout")]
public async Task<IActionResult> Logout(string logoutId)
{
await _signInManager.SignOutAsync();
var logoutRequest = await _interactionService.GetLogoutContextAsync(logoutId);
if (string.IsNullOrEmpty(logoutRequest.PostLogoutRedirectUri))
{
return Ok("Logout is already done");
}
return Redirect(logoutRequest.PostLogoutRedirectUri);
}
[HttpGet]
[Route("login")]
public async Task<IActionResult> Login(string returnUrl)
{
return View(new LoginViewModel { ReturnUrl = returnUrl });
}
[HttpPost]
[Route("login")]
public async Task<IActionResult> Login(LoginViewModel vm)
{
if (!ModelState.IsValid)
{
vm.ErrorMessage = "Неверное имя пользователя или пароль";
return View(vm);
}
var result = await _signInManager.PasswordSignInAsync(vm.Username, vm.Password, false, false);
if (result.Succeeded)
{
vm.ErrorMessage = "";
return Redirect(vm.ReturnUrl);
}
else
{
vm.ErrorMessage = "Неверное имя пользователя или пароль";
return View(vm);
}
}
}
}
<file_sep>/my.identity.server/Data/DataAccess/Commands/User/RemoveRoleCommand.cs
using MediatR;
using mi.identity.server.Data.DataAccess.Responses;
using mi.identity.server.Models;
using mi.identity.server.ViewModels;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Commands.User
{
public class RemoveRoleCommand : IRequest<UserRoleResponse>
{
public string UserId { get; set; }
public string RoleName { get; set; }
public RemoveRoleCommand(string userId, string roleName)
{
UserId = userId;
RoleName = roleName;
}
}
public class RemoveRoleHandler : IRequestHandler<RemoveRoleCommand, UserRoleResponse>
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly IMediator _mediator;
public DataAccessConstants DataAccessConstants { get; set; }
public RemoveRoleHandler(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
IMediator mediator)
{
_userManager = userManager;
_roleManager = roleManager;
_mediator = mediator;
var appSettings = new AppSettings();
DataAccessConstants = appSettings.DataAccessConstants;
}
public async Task<UserRoleResponse> Handle(RemoveRoleCommand request, CancellationToken cancellationToken)
{
var user = await _userManager.FindByIdAsync(request.UserId);
var role = await _roleManager.FindByNameAsync(request.RoleName);
if (role != null)
{
await _userManager.RemoveFromRoleAsync(user, role.Name);
await RemoveClaimsByRole(request);
}
return new UserRoleResponse
{
Role = role,
User = new ProfileViewModel(user)
};
}
private async Task RemoveClaimsByRole(RemoveRoleCommand request)
{
var permissions = DataAccessConstants.RolePermissions.FirstOrDefault(role => role.Key == request.RoleName);
foreach (var permission in permissions.Value)
{
await _mediator.Send(new RemoveClaimCommand(request.UserId, new ClaimViewModel { Type = permission, Value = "true" }));
}
}
}
}
<file_sep>/my.identity.server/Data/DataAccess/DataAccessConstants.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess
{
public class DataAccessConstants
{
public string DefaultApiResourceName { get; set; }
public string DefaultIdentityResourceName { get; set; }
public Dictionary<string, List<string>> RolePermissions { get; set; }
}
}
<file_sep>/my.identity.server/Data/DataAccess/Responses/ClaimResponse.cs
using mi.identity.server.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Responses
{
public class ClaimResponse
{
public string Type { get; set; }
public ResourceViewModel ApiResource { get; set; }
public ResourceViewModel IdentityResource { get; set; }
}
}
<file_sep>/my.identity.server/Data/DataAccess/Commands/RoleCreateCommand.cs
using MediatR;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Commands
{
public class RoleCreateCommand : IRequest<IdentityRole>
{
public string RoleName { get; set; }
public RoleCreateCommand()
{
}
public RoleCreateCommand(string roleName)
{
RoleName = roleName;
}
}
public class RoleCreateHandler : IRequestHandler<RoleCreateCommand, IdentityRole>
{
private readonly RoleManager<IdentityRole> _roleManager;
private readonly IMediator _mediator;
public DataAccessConstants DataAccessConstants { get; set; }
public RoleCreateHandler(RoleManager<IdentityRole> roleManager, IMediator mediator)
{
_roleManager = roleManager;
_mediator = mediator;
var appSettings = new AppSettings();
DataAccessConstants = appSettings.DataAccessConstants;
}
public async Task<IdentityRole> Handle(RoleCreateCommand request, CancellationToken cancellationToken)
{
var role = await _roleManager.FindByNameAsync(request.RoleName);
if (role == null)
{
await _roleManager.CreateAsync(new IdentityRole(request.RoleName));
await CreateClaimsByRole(request.RoleName);
}
return await _roleManager.FindByNameAsync(request.RoleName);
}
private async Task CreateClaimsByRole(string roleName)
{
var permissions = DataAccessConstants.RolePermissions.FirstOrDefault(role => role.Key == roleName);
foreach (var permission in permissions.Value)
{
await _mediator.Send(new ClaimCreateCommand(permission));
}
}
}
}
<file_sep>/my.identity.server/Data/DataAccess/Commands/ClaimDeleteCommand.cs
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Entities;
using MediatR;
using mi.identity.server.Data.DataAccess.Responses;
using mi.identity.server.ViewModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Commands
{
public class ClaimDeleteCommand : IRequest<ClaimResponse>
{
public string Type { get; set; }
public string ApiResourceName { get; set; }
public string IdentityResourceName { get; set; }
public ClaimDeleteCommand()
{
}
public ClaimDeleteCommand(string type)
{
Type = type;
}
public ClaimDeleteCommand(string type, string apiResourceName, string identityResourceName)
{
Type = type;
ApiResourceName = apiResourceName;
IdentityResourceName = identityResourceName;
}
}
public class ClaimDeleteHandler : IRequestHandler<ClaimDeleteCommand, ClaimResponse>
{
private readonly ConfigurationDbContext _configurationDbContext;
public DataAccessConstants DataAccessConstants { get; set; }
public ClaimDeleteHandler(ConfigurationDbContext configurationDbContext)
{
_configurationDbContext = configurationDbContext;
var appSettings = new AppSettings();
DataAccessConstants = appSettings.DataAccessConstants;
}
public async Task<ClaimResponse> Handle(ClaimDeleteCommand request, CancellationToken cancellationToken)
{
var apiResource = await RemoveFromApiResources(request);
var identityResource = await RemoveFromIdentityResources(request);
return new ClaimResponse
{
Type = request.Type,
ApiResource = new ResourceViewModel
{
Id = apiResource.Id,
Name = apiResource.Name
},
IdentityResource = new ResourceViewModel
{
Id = identityResource.Id,
Name = identityResource.Name
}
};
}
private async Task<ApiResource> RemoveFromApiResources(ClaimDeleteCommand request)
{
var apiResourceName = request.ApiResourceName;
if (string.IsNullOrEmpty(request.ApiResourceName))
{
apiResourceName = DataAccessConstants.DefaultApiResourceName;
}
var apiResource =
_configurationDbContext.ApiResources
.Include(x => x.UserClaims)
.FirstOrDefault(resource => resource.Name == apiResourceName);
if (apiResource != null)
{
var apiClaims = apiResource.UserClaims ?? new List<ApiResourceClaim>();
var claimToRemove = apiClaims.FirstOrDefault(claim => claim.Type == request.Type);
if (claimToRemove != null)
{
apiClaims.Remove(claimToRemove);
apiResource.UserClaims = apiClaims;
_configurationDbContext.Update(apiResource);
await _configurationDbContext.SaveChangesAsync();
}
}
return apiResource;
}
private async Task<IdentityResource> RemoveFromIdentityResources(ClaimDeleteCommand request)
{
var identityResourceName = request.IdentityResourceName;
if (string.IsNullOrEmpty(request.IdentityResourceName))
{
identityResourceName = DataAccessConstants.DefaultIdentityResourceName;
}
var identityResource =
_configurationDbContext.IdentityResources
.Include(x => x.UserClaims)
.FirstOrDefault(resource => resource.Name == identityResourceName);
if (identityResource != null)
{
var identityClaims = identityResource.UserClaims ?? new List<IdentityResourceClaim>();
var claimToRemove = identityClaims.FirstOrDefault(claim => claim.Type == request.Type);
if (claimToRemove != null)
{
identityClaims.Remove(claimToRemove);
identityResource.UserClaims = identityClaims;
_configurationDbContext.Update(identityResource);
await _configurationDbContext.SaveChangesAsync();
}
}
return identityResource;
}
}
}
<file_sep>/my.identity.server/ViewModels/ProfileViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using mi.identity.server.Models;
namespace mi.identity.server.ViewModels
{
public class ProfileViewModel
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public ProfileViewModel()
{
}
public ProfileViewModel(ApplicationUser applicationUser)
{
Id = applicationUser.Id;
FirstName = applicationUser.FirstName;
LastName = applicationUser.LastName;
Email = applicationUser.Email;
}
public static IEnumerable<ProfileViewModel> GetUserProfiles(IEnumerable<ApplicationUser> users)
{
var profiles = new List<ProfileViewModel> { };
foreach (ApplicationUser user in users)
{
profiles.Add(new ProfileViewModel(user));
}
return profiles;
}
}
}
<file_sep>/my.identity.server/Data/DataAccess/Queries/UserGetAllQuery.cs
using MediatR;
using mi.identity.server.Data.DataAccess.Responses;
using mi.identity.server.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Queries
{
public class UserGetAllQuery : IRequest<List<ProfileViewModel>>
{
}
public class UserGetAllHandler : IRequestHandler<UserGetAllQuery, List<ProfileViewModel>>
{
private readonly AppDbContext _appDbContext;
public UserGetAllHandler(AppDbContext appDbContext)
{
_appDbContext = appDbContext;
}
public async Task<List<ProfileViewModel>> Handle(UserGetAllQuery request, CancellationToken cancellationToken)
{
return _appDbContext.Users.Select(user => new ProfileViewModel(user)).ToList();
}
}
}
<file_sep>/my.identity.api.client/AppSettings.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
namespace mi.identity.api.client
{
public static class AppSettings
{
public static readonly IConfigurationRoot Configuration;
public static readonly Common Common;
#if DEBUG
private const string DefaultEnvironmentName = "debug";
#elif RELEASE
private const string DefaultEnvironmentName = "release";
#endif
static AppSettings()
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
.AddJsonFile($"appsettings.{DefaultEnvironmentName}.json", optional: true, reloadOnChange: false);
Configuration = builder.Build();
var сommon = new Common();
Configuration.GetSection("Common").Bind(сommon);
Common = сommon;
}
}
public class Common
{
public HostSettings Host { get; set; }
public HostSettings Api { get; set; }
public IdentitySettings IdentityServer { get; set; }
}
public class HostSettings
{
public string IpAddress { get; set; }
public int HttpPort { get; set; }
public int HttpsPort { get; set; }
public string Root { get; set; }
}
public class IdentitySettings
{
public string Authority { get; set; }
}
}
<file_sep>/my.identity.client.test/OutputViewModel.cs
namespace mi.identity.client.test
{
public class OutputViewModel
{
public string Content { get; set; }
}
}
<file_sep>/my.identity.server/Data/DataAccess/Commands/User/AssignRoleCommand.cs
using MediatR;
using mi.identity.server.Data.DataAccess.Responses;
using mi.identity.server.Models;
using mi.identity.server.ViewModels;
using Microsoft.AspNetCore.Identity;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Commands.User
{
public class AssignRoleCommand : IRequest<UserRoleResponse>
{
public string UserId { get; set; }
public string RoleName { get; set; }
public AssignRoleCommand(string userId, string roleName)
{
UserId = userId;
RoleName = roleName;
}
}
public class AssignRoleHandler : IRequestHandler<AssignRoleCommand, UserRoleResponse>
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly IMediator _mediator;
public DataAccessConstants DataAccessConstants { get; set; }
public AssignRoleHandler(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
IMediator mediator)
{
_userManager = userManager;
_roleManager = roleManager;
_mediator = mediator;
var appSettings = new AppSettings();
DataAccessConstants = appSettings.DataAccessConstants;
}
public async Task<UserRoleResponse> Handle(AssignRoleCommand request, CancellationToken cancellationToken)
{
var user = await _userManager.FindByIdAsync(request.UserId);
var role = await _roleManager.FindByNameAsync(request.RoleName);
if (role == null)
{
await _mediator.Send(new RoleCreateCommand(request.RoleName));
}
await _userManager.AddToRoleAsync(user, role.Name);
await AddClaimsByRole(request);
return new UserRoleResponse
{
Role = role,
User = new ProfileViewModel(user)
};
}
private async Task AddClaimsByRole(AssignRoleCommand request)
{
var permissions = DataAccessConstants.RolePermissions.FirstOrDefault(role => role.Key == request.RoleName);
foreach (var permission in permissions.Value)
{
await _mediator.Send(new AddClaimCommand(request.UserId, new ClaimViewModel { Type = permission, Value = "true" }));
}
}
}
}
<file_sep>/my.identity.server/Startup.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using IdentityModel;
using IdentityServer4.EntityFramework.Interfaces;
using IdentityServer4.EntityFramework.Options;
using IdentityServer4.Extensions;
using IdentityServer4.Services;
using MediatR;
using mi.identity.server.Data;
using mi.identity.server.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
namespace mi.identity.server
{
public class Startup
{
public IConfiguration _configuration { get; }
public IWebHostEnvironment _environment { get; }
public AppSettings AppSettings { get; set; } = new AppSettings();
public Startup(IConfiguration configuration, IWebHostEnvironment environment)
{
_configuration = configuration;
_environment = environment;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(_configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>(config =>
{
config.Password.RequiredLength = 8;
config.Password.RequireDigit = true;
config.Password.RequireUppercase = true;
config.Password.RequireNonAlphanumeric = false;
})
.AddEntityFrameworkStores<AppDbContext>()
.AddDefaultTokenProviders();
services.ConfigureApplicationCookie(config =>
{
config.Cookie.Name = "IdentityServer.Cookie";
config.LoginPath = "/auth/login";
config.LogoutPath = "/auth/logout";
config.Cookie.Path = "/";
config.Cookie.SameSite = SameSiteMode.Unspecified;
});
services.ConfigureNonBreakingSameSiteCookies();
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddIdentityServer()
.AddAspNetIdentity<ApplicationUser>()
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = b => b.UseNpgsql(_configuration.GetConnectionString("DefaultConnection"),
sql => sql.MigrationsAssembly(migrationsAssembly));
options.IdentityResourceClaim = new TableConfiguration("IdentityResourceClaim");
options.ApiResourceClaim = new TableConfiguration("ApiResourceClaim");
})
.AddOperationalStore(options =>
{
options.ConfigureDbContext = b => b.UseNpgsql(_configuration.GetConnectionString("DefaultConnection"),
sql => sql.MigrationsAssembly(migrationsAssembly));
})
#if DEBUG
.AddDeveloperSigningCredential();
#else
.AddSigningCredential(new X509Certificate2(Path.Combine(@"/tmp", "IdentityServerCert.pfx")));
#endif
services.AddAuthentication(config =>
{
config.DefaultScheme = "Cookie";
config.DefaultChallengeScheme = "oidc";
})
.AddCookie("Cookie", config =>
{
config.Cookie.SecurePolicy = CookieSecurePolicy.None;
})
.AddOpenIdConnect("oidc", config =>
{
config.Authority = AppSettings.Common.IdentityServer.Authority;
config.SignInScheme = "Cookie";
config.RequireHttpsMetadata = false;
config.ClientId = "mi.identity.server.api";
config.ClientSecret = "secret_mi.identity.server.api";
config.ResponseType = "code";
config.SaveTokens = true;
config.SignedOutCallbackPath = "/identity/signout-callback-oidc";
config.GetClaimsFromUserInfoEndpoint = true;
config.ClaimActions.MapAll();
config.Scope.Add("shared.scope");
config.Scope.Add("my.admin.scope");
config.Scope.Add("openid");
config.Scope.Add("profile");
config.Scope.Add("offline_access");
});
services.AddCors(options =>
{
options.AddPolicy("default", policy =>
{
policy.WithOrigins("https://localhost")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddMediatR(typeof(Startup));
services.AddMvc(option => option.EnableEndpointRouting = false);
services.AddControllers();
services.AddSwaggerGen(option =>
{
option.SwaggerDoc("v1", new OpenApiInfo { Title = "my.identity.server", Version = "1" });
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UsePathBase(AppSettings.Common.Host.Root);
app.Use(async (context, next) =>
{
context.Request.Scheme = "https";
await next.Invoke();
});
app.UseCors("default");
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("./v1/swagger.json", "my.identity.server"));
app.UseRouting();
app.UseCookiePolicy();
app.UseIdentityServer();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
<file_sep>/my.identity.api.client/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace mi.identity.api.client
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
var hostSettings = AppSettings.Common.Host;
var urls = new List<string>()
{
$"http://{hostSettings.IpAddress}:{hostSettings.HttpPort}"
};
if (hostSettings.HttpsPort > 0)
{
urls.Add($"https://{hostSettings.IpAddress}:{hostSettings.HttpsPort}");
}
return Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseStartup<Startup>()
.UseUrls(urls.ToArray());
});
}
}
}
<file_sep>/my.identity.api.client/Controllers/MiAdminController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using IdentityModel.Client;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Logging;
using Newtonsoft.Json;
namespace mi.identity.api.client.Controllers
{
[Route("mi")]
[ApiController]
public class MiAdminController : ControllerBase
{
public async Task<IActionResult> Index()
{
HttpClientHandler clientHandler = new HttpClientHandler();
clientHandler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true;
IdentityModelEventSource.ShowPII = true;
using var serverClient = new HttpClient(clientHandler);
string error = "";
string innerError = "";
string tokenError = "";
string responseContent = "";
var tokenUrl = $"{AppSettings.Common.IdentityServer.Authority}/token/ClientCredentials";
var model = new
{
ClientId = "my.identity.api.client",
ClientSecret = "secret_my.identity.api.client_secret"
};
var stringContent = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
var responseToken = await serverClient.PostAsync(tokenUrl, stringContent);
var accessToken = await responseToken.Content.ReadAsStringAsync();
try
{
using var apiClient = new HttpClient();
apiClient.SetBearerToken(accessToken);
var responseApi = await apiClient.GetAsync($"http://{AppSettings.Common.Api.IpAddress}:{AppSettings.Common.Api.HttpPort}/secret");
responseContent = responseApi.StatusCode.ToString() +
" --- ReasonPhrase: " + responseApi.ReasonPhrase +
" --- Content: " + await responseApi.Content.ReadAsStringAsync() +
" --- RequestMessage: " + responseApi.RequestMessage;
}
catch (Exception e)
{
error = " --- ErrorMessage: " + e.Message +
" --- StackTrase: " + e.StackTrace;
innerError = " --- InnerErrorMessage: " + e.InnerException?.Message +
" --- InnerErrorInfo" + e.InnerException.ToString();
}
return Ok(
$"AccessToken: {accessToken}, {Environment.NewLine}" +
$"TokenError: {tokenError}, {Environment.NewLine}" +
$"Error: {error}, {Environment.NewLine}" +
$"InnerErroor: {innerError}, {Environment.NewLine}" +
$"ResponseFromApi: {responseContent}");
}
[Route("test")]
[HttpGet]
public IActionResult Test()
{
return Ok("OK");
}
}
}
<file_sep>/my.identity.server/Data/DataAccess/Queries/RoleGetAllQuery.cs
using MediatR;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Queries
{
public class RoleGetAllQuery : IRequest<List<IdentityRole>>
{
}
public class RoleGetAllHandler : IRequestHandler<RoleGetAllQuery, List<IdentityRole>>
{
private readonly AppDbContext _appDbContext;
public RoleGetAllHandler(AppDbContext appDbContext)
{
_appDbContext = appDbContext;
}
public async Task<List<IdentityRole>> Handle(RoleGetAllQuery request, CancellationToken cancellationToken)
{
return _appDbContext.Roles.ToList();
}
}
}
<file_sep>/my.identity.server/Data/DataAccess/Commands/RoleDeleteCommand.cs
using MediatR;
using mi.identity.server.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Commands
{
public class RoleDeleteCommand : IRequest<IdentityRole>
{
public string RoleName { get; set; }
}
public class RoleDeleteHandler : IRequestHandler<RoleDeleteCommand, IdentityRole>
{
private readonly RoleManager<IdentityRole> _roleManager;
private readonly AppDbContext _appDbContext;
public RoleDeleteHandler(RoleManager<IdentityRole> roleManager, AppDbContext appDbContext)
{
_roleManager = roleManager;
_appDbContext = appDbContext;
}
public async Task<IdentityRole> Handle(RoleDeleteCommand request, CancellationToken cancellationToken)
{
var roleToDelete = await _roleManager.FindByNameAsync(request.RoleName);
var userWithRole = _appDbContext.UserRoles.Where(x => x.RoleId == roleToDelete.Id).ToList();
if (roleToDelete != null && userWithRole.Count == 0)
{
await _roleManager.DeleteAsync(roleToDelete);
return roleToDelete;
}
return null;
}
}
}
<file_sep>/my.identity.server/Data/DataAccess/Commands/User/UserDeleteCommand.cs
using MediatR;
using mi.identity.server.Data.DataAccess.Responses;
using mi.identity.server.Models;
using mi.identity.server.ViewModels;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Commands.User
{
public class UserDeleteCommand : IRequest<ProfileViewModel>
{
public string UserId { get; set; }
public UserDeleteCommand(string userId)
{
UserId = userId;
}
}
public class UserDeleteHandler : IRequestHandler<UserDeleteCommand, ProfileViewModel>
{
private readonly UserManager<ApplicationUser> _userManager;
public UserDeleteHandler(UserManager<ApplicationUser> userManager)
{
_userManager = userManager;
}
public async Task<ProfileViewModel> Handle(UserDeleteCommand request, CancellationToken cancellationToken)
{
var user = await _userManager.FindByIdAsync(request.UserId);
await _userManager.DeleteAsync(user);
return new ProfileViewModel(user);
}
}
}
<file_sep>/my.identity.server/Data/DataAccess/Commands/User/UserCreateCommand.cs
using MediatR;
using mi.identity.server.Data.DataAccess.Responses;
using mi.identity.server.Models;
using mi.identity.server.ViewModels;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace mi.identity.server.Data.DataAccess.Commands.User
{
public class UserCreateCommand : IRequest<UserResponse>
{
public string UserName { get; set; }
public string Password { get; set; }
public ProfileViewModel UserProfile { get; set; }
public string RoleName { get; set; }
}
public class UserCreateHandler : IRequestHandler<UserCreateCommand, UserResponse>
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly IMediator _mediator;
public UserCreateHandler(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager,
IMediator mediator)
{
_userManager = userManager;
_roleManager = roleManager;
_mediator = mediator;
}
public async Task<UserResponse> Handle(UserCreateCommand request, CancellationToken cancellationToken)
{
var user = new ApplicationUser
{
UserName = request.UserName,
FirstName = request.UserProfile.FirstName,
LastName = request.UserProfile.LastName,
Email = request.UserProfile.Email
};
var createResult = await _userManager.CreateAsync(user, request.Password);
string roleName = request.RoleName ?? "Basic"; ///// DEFAULT ROLE
if (createResult.Succeeded)
{
await _mediator.Send(new AssignRoleCommand(user.Id, roleName));
await _mediator.Send( new AddClaimCommand(user.Id, new ClaimViewModel { Type = "user_name", Value = user.UserName }) );
await _mediator.Send( new AddClaimCommand(user.Id, new ClaimViewModel { Type = "first_name", Value = user.FirstName }) );
await _mediator.Send( new AddClaimCommand(user.Id, new ClaimViewModel { Type = "last_name", Value = user.LastName }) );
await _mediator.Send( new AddClaimCommand(user.Id, new ClaimViewModel { Type = "email", Value = user.Email }) );
await _mediator.Send( new AddClaimCommand(user.Id, new ClaimViewModel { Type = "role", Value = roleName }) );
return new UserResponse
{
User = new ProfileViewModel(user),
UserRole = await _roleManager.FindByNameAsync(roleName)
};
}
return new UserResponse();
}
}
}
<file_sep>/my.identity.server/Controllers/TokenController.cs
using System;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
using mi.identity.server.ViewModels;
using Microsoft.AspNetCore.Mvc;
namespace mi.identity.server.Controllers
{
[Route("token")]
[ApiController]
public class TokenController : ControllerBase
{
[HttpPost]
[Route("ClientCredentials")]
public async Task<string> GetClientCredentialsToken(ClientCredentialsViewModel clientCredentials)
{
using var serverClient = new HttpClient();
var appSettings = new AppSettings();
var authorityUrl = appSettings.Common.IdentityServer.Authority;
var discoveryDocument = await serverClient.GetDiscoveryDocumentAsync(authorityUrl);
var tokenResponse = await serverClient.RequestClientCredentialsTokenAsync(
new ClientCredentialsTokenRequest
{
RequestUri = new Uri(discoveryDocument.TokenEndpoint),
GrantType = "client_credentials",
ClientId = clientCredentials.ClientId,
ClientSecret = clientCredentials.ClientSecret,
Scope = clientCredentials.Scope ?? "my.admin.scope",
});
return tokenResponse.AccessToken;
}
}
}
<file_sep>/my.identity.api/Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using System.IO;
using System.Security.Cryptography.X509Certificates;
namespace mi.identity.api
{
public class Startup
{
public IConfiguration Configuration { get; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
var appSettings = new AppSettings();
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = $"{appSettings.Common.IdentityServer.Authority}";
options.Audience = "my.identity.api";
options.RequireHttpsMetadata = false;
});
services.AddAuthorization(options =>
{
options.AddPolicy("TestPolicy", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("client_AA", "123");
});
});
services.AddCors(options =>
{
options.AddPolicy("default", policy =>
{
policy.WithOrigins("http://localhost")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//app.UseHttpsRedirection();
app.UseCors("default");
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers().RequireAuthorization("TestPolicy");
});
}
}
}
<file_sep>/my.identity.client.test/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
namespace mi.identity.client.test
{
public class Program
{
public static void Main(string[] args)
{
var host = CreateHostBuilder(args)
.ConfigureLogging((hostContext, loggingBuilder) =>
{
var logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.MinimumLevel.Debug()
.WriteTo.File("LogFile.txt")
.CreateLogger();
loggingBuilder
.AddSerilog(logger)
.AddConsole()
.AddDebug();
}).Build();
host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
var hostSettings = AppSettings.Common.Host;
var urls = new List<string>()
{
$"http://{hostSettings.IpAddress}:{hostSettings.HttpPort}"
};
if (hostSettings.HttpsPort > 0)
{
urls.Add($"https://{hostSettings.IpAddress}:{hostSettings.HttpsPort}");
}
return Host.CreateDefaultBuilder(args)
.UseSerilog()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseStartup<Startup>()
.UseUrls(urls.ToArray());
});
}
}
}
<file_sep>/my.identity.server/Controllers/RoleController.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using MediatR;
using mi.identity.server.Data;
using mi.identity.server.Data.DataAccess.Commands;
using mi.identity.server.Data.DataAccess.Queries;
using mi.identity.server.Models;
using mi.identity.server.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace mi.identity.server.Controllers
{
[Route("api/role")]
[ApiController]
[Authorize]
public class RoleController : ControllerBase
{
private readonly IMediator _mediator;
public RoleController( IMediator mediator)
{
_mediator = mediator;
}
[HttpGet]
[Route("")]
public async Task<List<IdentityRole>> GetAllRolesAsync()
{
return await _mediator.Send(new RoleGetAllQuery());
}
//[HttpGet]
//[Route("userRoles")]
//public async Task<List<IdentityRole>> GetUserRoles(string userId)
//{
// var user = await _userManager.FindByIdAsync(userId);
// var pairList = _context.UserRoles.Where(x => x.UserId == user.Id).ToList();
// var output = new List<IdentityRole>();
// foreach (var pair in pairList)
// {
// var role = await _roleManager.FindByIdAsync(pair.RoleId);
// output.Add(role);
// }
// return output;
//}
//[HttpGet]
//[Route("usersWithRole")]
//public async Task<List<ApplicationUser>> GetUsersWithRole(string roleName)
//{
// var role = await _roleManager.FindByNameAsync(roleName);
// var pairList = _context.UserRoles.Where(x => x.RoleId == role.Id).ToList();
// var output = new List<ApplicationUser>();
// foreach (var pair in pairList)
// {
// var user = await _userManager.FindByIdAsync(pair.UserId);
// output.Add(user);
// }
// return output;
//}
[HttpPost]
[Route("")]
public async Task<IdentityRole> Create([FromBody]RoleCreateCommand command)
{
return await _mediator.Send(command);
}
[HttpDelete]
[Route("")]
public async Task<IdentityRole> Delete([FromBody]RoleDeleteCommand command)
{
return await _mediator.Send(command);
}
}
}
|
9abe403b6fb885cf81faff1bb841690f50488ce3
|
[
"Markdown",
"C#"
] | 42
|
C#
|
DisSh33/identity-server
|
565b436aad98e891744b1bfc34f2013179b8fd88
|
35fa4f3dc7f494432793432bbeb4870ed9d31608
|
refs/heads/master
|
<file_sep>#Overview
train_SGD.py runs a Logistic Regression Classifier with Stochastic Gradient Descent to predict if a user ends up buying a product or not
#Python Libraries Pre-Requisites:
scikit-learn, numpy, scipy
If using virtualenv
pip install -r requirements.txt
#Run code:
python train_SGD.py
<file_sep>numpy==1.9.2
scikit-learn==0.16.1
scipy==0.16.0
sklearn==0.0
<file_sep>#----------------------------------------------------------------------------------
# LR Classifier
# <NAME>
#----------------------------------------------------------------------------------
#
import csv
import numpy as np
from sklearn import linear_model
from sklearn.linear_model import SGDClassifier
#feature names derived from raw dataset
fieldnames = ['ACCOUNT', 'OTHER_PAGE', 'SKU', 'SEARCH_RESULTS', 'CART', 'CLASS', 'DEPARTMENT', 'HOME', 'SKUSET', 'BUY']
#training dataset
input_file = 'train.csv'
#test dataset
test_file = 'test.csv'
def readCSV(input_file):
#read csv file into a list of lists
new_rows = []
with open(input_file, 'r') as test:
test_reader = csv.reader(test)
for row in test_reader:
#append to temporary location in memory
new_rows.append(row)
return new_rows
def processCols(new_rows):
#processes columns to get time spent per activity from cumulative time
for index in xrange(len(new_rows)):
for col in xrange(1, 14, 2):
new_rows[index][col] = int(new_rows[index][col+2]) - int(new_rows[index][col])
new_rows[index][15] = 0
return new_rows
def createDict(new_rows, nolabel):
data = []
#gets the index of label in the dataset
label_index = len(new_rows[0])-1
#create a dictionary of features per row
#each row is made of dict with 10 keys, including label
for index in xrange(len(new_rows)):
row = dict.fromkeys(fieldnames, 0)
for col in xrange(0, 15, 2):
row[new_rows[index][col]] = row[new_rows[index][col]] + new_rows[index][col+1]
#calculate labels only for train set
if(nolabel == False):
row['BUY'] = new_rows[index][label_index]
data.append(row)
#returns a list of dict
return data
def createFeature(feature):
#convert and seperate the dictionary into an array of features and labels
#saves the list
dataSet = []
for row in feature:
#saves a row
item = []
#ten pre-defined fieldnames/features initialized above
for key in fieldnames:
item.append(row[key])
dataSet.append(item)
#convert to array
dataSet = np.array(dataSet)
return dataSet[:,:9], dataSet[:,9]
def writeTarget(target):
print "Writing predicted target values to predicted_labels.csv..."
with open('predicted_labels.csv', 'w') as solutions:
sol_writer = csv.writer(solutions, delimiter=',')
for row in target:
#writes to solution row by row
sol_writer.writerow(row)
def trainLR(trainingSet, label):
#regularized logistic regression using the liblinear library, newton-cg and lbfgs solvers
clf = SGDClassifier(loss="log", penalty="l2")
clf.fit(trainingSet, label)
return clf
def predictBuy(lr_clf, test_set):
#list to save predicted labels
predict_target = []
for index in xrange(len(test_set)):
#predict using a trained logistic regression model
predict_target.append(lr_clf.predict(test_set[index]))
return predict_target
def extract(input_file, nolabel):
#extract from csv into memory for preprocessing
new_rows = readCSV(input_file)
#process times in cols and get actual time per column from cumulative time
processed_rows = processCols(new_rows)
#convert into a lower dimensional feature set derived from categories
dataset = createDict(processed_rows, nolabel)
#use the list of dictionary features to get an input matrix and label array
feature, label = createFeature(dataset)
return feature, label
def main():
#call extract with input filename and nolabel boolean set to false
feature, label = extract(input_file, False)
print "Training a logistic regression classifier on training set..."
#train a logistic regression classifier
lr_clf = trainLR(feature, label)
#discards label as we are not provided that for the test set
test_set, label = extract(test_file, True)
#use a logistic regression classfier to predict on test set
predict_target = predictBuy(lr_clf, test_set)
#print target values to file
writeTarget(predict_target)
if __name__ == "__main__":
main()
|
da1b35c56b274f7c8dcb526a690e9c8abbdeb172
|
[
"Markdown",
"Python",
"Text"
] | 3
|
Markdown
|
smritijha/LRClassifier
|
fef77081e0308fbb81f84d3cbb19cecf477cd61c
|
e1079380cf2ef15eb175c96d52688b01abef4ceb
|
refs/heads/master
|
<file_sep>var chai = require('chai');
var expect = chai.expect;
var pigLatin = require('./pig-latin.js');
describe('Pig Latin Translator', function(){
describe('English to Pig Latin Function', function () {
it('should be a function', function () {
expect(pigLatin.englishToPig).to.be.a('function');
});
it('should only accept a string as an argument', function () {
expect(pigLatin.englishToPig.bind(null)).to.throw();
});
it('should append "ay" to the end of words that start with a vowel', function () {
var eat = pigLatin.englishToPig('eat');
expect(eat).to.equal('eatay');
var omelet = pigLatin.englishToPig('omelet');
expect(omelet).to.equal('omeletay');
var are = pigLatin.englishToPig('are');
expect(are).to.equal('areay');
});
it('should move consonant letters up to the first vowel to the end of the word and append "ay" to words that start with a consonant', function () {
var pig = pigLatin.englishToPig('pig');
expect(pig).to.equal('ig-pay');
var banana = pigLatin.englishToPig('banana');
expect(banana).to.equal('anana-bay');
var trash = pigLatin.englishToPig('trash');
expect(trash).to.equal('ash-tray');
});
it('should convert all words in a sentence to Pig Latin following the rules of whether they start with a vowel or consonant', function () {
var sentence = pigLatin.englishToPig('I am here');
expect(sentence).to.equal('Iay amay ere-hay');
var question = pigLatin.englishToPig('Are we there yet');
expect(question).to.equal('Areay e-way ere-thay et-yay');
});
});
});
describe('English Translator', function(){
describe('Pig Latin to English Function', function () {
it('should be a function', function () {
expect(pigLatin.pigToEnglish).to.be.a('function');
});
it('should only accept a string as an argument', function () {
expect(pigLatin.pigToEnglish.bind(null)).to.throw();
});
it('should remove "ay" to the end of words that have "ay" appended', function () {
var eatPTE = pigLatin.pigToEnglish('eatay');
expect(eatPTE).to.equal('eat');
var omeletPTE = pigLatin.pigToEnglish('omeletay');
expect(omeletPTE).to.equal('omelet');
var arePTE = pigLatin.pigToEnglish('areay');
expect(arePTE).to.equal('are');
});
it('should move consonant(s) to the from of the word after "-" as well as remove the "-"', function () {
var pigPTE = pigLatin.pigToEnglish('ig-pay');
expect(pigPTE).to.equal('pig');
var bananaPTE = pigLatin.pigToEnglish('anana-bay');
expect(bananaPTE).to.equal('banana');
var trashPTE = pigLatin.pigToEnglish('ash-tray');
expect(trashPTE).to.equal('trash');
});
it('should convert all words in a sentence to Pig Latin following the rules of whether they start with a vowel or consonant', function () {
var sentencePTE = pigLatin.pigToEnglish('Iay amay ere-hay');
expect(sentencePTE).to.equal('I am here');
var questionPTE = pigLatin.pigToEnglish('Areay e-way ere-thay et-yay');
expect(questionPTE).to.equal('Are we there yet');
});
});
});<file_sep>var engToPigBtn = document.getElementById('pig-translation-btn');
engToPigBtn.addEventListener('click', translateToPig);
var pigToEngBtn = document.getElementById('eng-translation-btn');
pigToEngBtn.addEventListener('click', translateToEng);
function translateToPig() {
var input = document.getElementById('translation-input').value;
var outputContainer = document.getElementById('translated');
var output = document.getElementById('translated-text');
if (input === ""){
if (document.getElementById('translation-input').placeholder === 'Please type something to translate.'){
document.getElementById('translation-input').placeholder = 'This translator works best when you type in text to translate.';
}else{
document.getElementById('translation-input').placeholder = 'Please type something to translate.';
}
}else{
var translated = englishToPig(input);
output.innerHTML = translated;
outputContainer.setAttribute("style", "display:block");
}
}
function translateToEng() {
var input = document.getElementById('translation-input').value;
var outputContainer = document.getElementById('translated');
var output = document.getElementById('translated-text');
if (input === ""){
if (document.getElementById('translation-input').placeholder === 'Please type something to translate.'){
document.getElementById('translation-input').placeholder = 'This translator works best when you type in text to translate.';
}else{
document.getElementById('translation-input').placeholder = 'Please type something to translate.';
}
}else{
var translated = pigToEnglish(input);
output.innerHTML = translated;
outputContainer.setAttribute("style", "display:block");
}
}
function englishToPig(engString){
if (typeof engString !== 'string'){
throw new Error();
}
//1. seperate sentence into array
var seperate = engString.split(' ');
for (var i = 0; i < seperate.length; i++){
//2. take each word and split based on if it starts with vowel or consonant ('y' considered vowel if within word)
var splitUp = seperate[i].split(/([aeiouyAEIOUY].*)/);
//this string starts with a vowel
if (splitUp[0].length === 0){
if (splitUp[1].charAt(0) === 'y' || splitUp[1].charAt(0) === 'Y'){ //if word begins with 'y' then considered consonant
var secondSplit = splitUp[1].split(/([aeiouAEIOU].*)/);
if (secondSplit.length === 1){ //this is just the letter 'y'
splitUp[1] += 'ay';
}else{
secondSplit[0] += 'ay';
secondSplit[1] += '-';
splitUp = secondSplit.reverse();
}
}else{
splitUp[1] += 'ay';
}
}else if (splitUp.length === 1){ //this string does not have vowels
splitUp[0] +='-ay';
}else{ //this string begins with a consonant
splitUp[0] += 'ay';
splitUp[1] += '-';
splitUp.reverse();
}
//3. put the word back together
seperate[i] = splitUp.join('');
}
//4. put the sentence back together
return seperate.join(' ');
}
function pigToEnglish(pigString) {
if (typeof pigString !== 'string'){
throw new Error();
}
//1. seperate sentence into array
var seperate = pigString.split(' ');
//2. take each word and remove/move the end based on if appended with "ay" or "'-' + consonant + 'ay'"
for (var i = 0; i < seperate.length; i++) {
//this will be an English word that begins with a vowel
if (seperate[i].indexOf('-') === -1){
seperate[i] = seperate[i].slice(0, -2);
}else{ //this will be an English word that begins with a consonant
var clippedEnd = seperate[i].slice(0, -2);
seperate[i] = clippedEnd.split('-').reverse().join('');
}
}
//3. put the sentence back together
return seperate.join(' ');
}<file_sep>function englishToPig(engString){
if (typeof engString !== 'string'){
throw new Error();
}
//1. seperate sentence into array
var seperate = engString.split(' ');
for (var i = 0; i < seperate.length; i++){
//2. take each word and split based on if it starts with vowel or consonant
var splitUp = seperate[i].split(/([aeiouAEIOU].*)/);
//this string starts with a vowel
if (splitUp[0].length === 0){
splitUp[1] += 'ay';
}else{ //this string begins with a consonant
splitUp[0] += 'ay';
splitUp[1] += '-';
splitUp.reverse();
}
//3. put the word back together
seperate[i] = splitUp.join('');
}
//4. put the sentence back together
return seperate.join(' ');
}
function pigToEnglish(pigString) {
if (typeof pigString !== 'string'){
throw new Error();
}
//1. seperate sentence into array
var seperate = pigString.split(' ');
//2. take each word and remove/move the end based on if appended with "ay" or "'-' + consonant + 'ay'"
for (var i = 0; i < seperate.length; i++) {
//this will be an English word that begins with a vowel
if (seperate[i].indexOf('-') === -1){
seperate[i] = seperate[i].slice(0, -2);
}else{ //this will be an English word that begins with a consonant
var clippedEnd = seperate[i].slice(0, -2);
seperate[i] = clippedEnd.split('-').reverse().join('');
}
}
//3. put the sentence back together
return seperate.join(' ');
}
module.exports = {
englishToPig: englishToPig,
pigToEnglish: pigToEnglish
};<file_sep># Pig Latin Translator
This is a pig latin translator that will take in an english sentence and translate it into pig latin!
## Here's How It Works:
### Translate English To Pig Latin
- Words that start with a vowel (A, E, I, O, U) simply have "ay" appended to the end of the word.
- Words that start with a consonant have all consonant letters up to the first vowel moved to the end of the word (as opposed to just the first consonant letter), and "-ay" is appended.
## Translate Text Today!
[https://lisazhou.github.io/pig-latin-translator](https://lisazhou.github.io/pig-latin-translator)
|
009f84179802297062c65e69cc1bb3c28ba0462a
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
Chinmoykoch/pig-latin-translator
|
8e01eca279523f22195f79a4c300ab56d9b5e672
|
621d9eb00fec4fc615372a39371e5c2901fe90dc
|
refs/heads/master
|
<repo_name>ExpediaInc/apiary-extensions<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.hotels</groupId>
<artifactId>hotels-oss-parent</artifactId>
<version>2.3.3</version>
</parent>
<groupId>com.expedia.apiary</groupId>
<artifactId>apiary-extensions-parent</artifactId>
<description>Various extensions to Apiary that provide additional, optional functionality</description>
<version>1.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>Apiary Extensions Parent</name>
<inceptionYear>2018</inceptionYear>
<scm>
<connection>scm:git:git@github.com:ExpediaInc/apiary-extensions.git</connection>
<developerConnection>scm:git:git@github.com:ExpediaInc/apiary-extensions.git</developerConnection>
<url>https://github.com/ExpediaInc/apiary-extensions</url>
<tag>HEAD</tag>
</scm>
<properties>
<aws-java-sdk.version>1.11.333</aws-java-sdk.version>
<jdk.version>1.8</jdk.version>
<hive.version>2.3.3</hive.version>
<ranger.version>1.1.0</ranger.version>
<junit.version>4.12</junit.version>
<mockito.version>2.21.0</mockito.version>
<shade.prefix>${project.groupId}.shaded</shade.prefix>
<slf4j.version>1.7.25</slf4j.version>
</properties>
<modules>
<module>apiary-metastore-listener</module>
<module>apiary-gluesync-listener</module>
<module>apiary-ranger-metastore-plugin</module>
<module>apiary-metastore-metrics</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencyManagement>
</project>
<file_sep>/apiary-gluesync-listener/src/test/java/com/expedia/apiary/extensions/gluesync/listener/ApiaryGlueSyncTest.java
/**
* Copyright (C) 2018 Expedia Inc.
*
* 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 com.expedia.apiary.extensions.gluesync.listener;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.Order;
import org.apache.hadoop.hive.metastore.api.SerDeInfo;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.events.CreateTableEvent;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import com.amazonaws.services.glue.AWSGlue;
import com.amazonaws.services.glue.model.CreateTableRequest;
import com.amazonaws.services.glue.model.CreateTableResult;
@RunWith(MockitoJUnitRunner.class)
public class ApiaryGlueSyncTest {
@Mock
private AWSGlue glueClient;
@Mock
private Configuration configuration;
@Mock
private CreateTableResult createTableResult;
@Captor
private ArgumentCaptor<CreateTableRequest> requestCaptor;
private String tableName = "some_table";
private String dbName = "some_db";
private String[] colNames = { "col1", "col2", "col3" };
private String[] partNames = { "part1", "part2" };
private String gluePrefix = "test_";
private ApiaryGlueSync glueSync;
@Before
public void setup() {
glueSync = new ApiaryGlueSync(configuration, glueClient, gluePrefix);
when(glueClient.createTable(any(CreateTableRequest.class))).thenReturn(createTableResult);
}
@Test
public void onCreateTable() throws MetaException {
CreateTableEvent event = mock(CreateTableEvent.class);
when(event.getStatus()).thenReturn(true);
Table table = new Table();
table.setTableName(tableName);
table.setDbName(dbName);
StorageDescriptor sd = new StorageDescriptor();
List<FieldSchema> fields = new ArrayList<FieldSchema>();
for (int i = 0; i < colNames.length; ++i) {
fields.add(new FieldSchema(colNames[i], "string", ""));
}
sd.setCols(fields);
sd.setInputFormat("org.apache.hadoop.mapred.TextInputFormat");
sd.setOutputFormat("org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat");
sd.setSerdeInfo(new SerDeInfo());
sd.getSerdeInfo().setParameters(new HashMap<String, String>());
sd.getSerdeInfo().getParameters().put(org.apache.hadoop.hive.serde.Constants.SERIALIZATION_FORMAT, "1");
sd.setSortCols(new ArrayList<Order>());
table.setSd(sd);
List<FieldSchema> partitions = new ArrayList<FieldSchema>();
for (int i = 0; i < partNames.length; ++i) {
partitions.add(new FieldSchema(partNames[i], "string", ""));
}
table.setPartitionKeys(partitions);
when(event.getTable()).thenReturn(table);
glueSync.onCreateTable(event);
verify(glueClient).createTable(requestCaptor.capture());
CreateTableRequest createTableRequest = requestCaptor.getValue();
assertThat(createTableRequest.getDatabaseName(), is(gluePrefix + dbName));
assertThat(createTableRequest.getTableInput().getName(), is(tableName));
assertThat(createTableRequest
.getTableInput()
.getPartitionKeys()
.stream()
.map(p -> p.getName())
.collect(Collectors.toList()), is(partitions.stream().map(p -> p.getName()).collect(Collectors.toList())));
assertThat(createTableRequest
.getTableInput()
.getStorageDescriptor()
.getColumns()
.stream()
.map(p -> p.getName())
.collect(Collectors.toList()), is(fields.stream().map(p -> p.getName()).collect(Collectors.toList())));
}
// TODO: tests for other onXxx() methods
}
<file_sep>/README.md
# Overview
For more information please refer to the main [Apiary](https://github.com/ExpediaInc/apiary) project page.
# Contact
## Mailing List
If you would like to ask any questions about or discuss Apiary please join our mailing list at
[https://groups.google.com/forum/#!forum/apiary-user](https://groups.google.com/forum/#!forum/apiary-user)
# Legal
This project is available under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0.html).
Copyright 2018 Expedia Inc.
<file_sep>/CHANGELOG.md
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [1.0.0] - 2018-10-31
### Added
- Partition Keys with Data types added to the JSON Events from ApiarySNSListener.
### Changed
- `partition` is renamed to `partitionValues` and `oldPartition` to `oldPartitionValues` in the JSON Events from ApiarySNSListener.
### Fixed
- JSON Events from ApiarySNSListener now marshals list as a JSONArray.
## [0.2.0] - 2018-10-03
### Added
- `apiary-gluesync-listener` sub-module.
- `apiary-metastore-metrics` sub-module.
- `apiary-ranger-metastore-plugin` sub-module.
## [0.1.0] - 2018-09-11
### Changed
- Apiary SNS listener now configured using standard AWS configuration mechanisms. See [#4](https://github.com/ExpediaInc/apiary-extensions/issues/4).
### Added
- A `protocolVersion` field to the SNS messages generated by `ApiarySnsListener`. See [#2](https://github.com/ExpediaInc/apiary-extensions/issues/2).
- Support for `INSERT` metastore events. See [#6](https://github.com/ExpediaInc/apiary-extensions/issues/6).
## [0.0.1] - 2018-08-23
### Added
- Initial version to test that releases to Maven Central work.
<file_sep>/apiary-metastore-listener/src/main/java/com/expedia/apiary/extensions/metastore/listener/ApiarySnsListener.java
/**
* Copyright (C) 2018 Expedia Inc.
*
* 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 com.expedia.apiary.extensions.metastore.listener;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.metastore.MetaStoreEventListener;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.events.AddPartitionEvent;
import org.apache.hadoop.hive.metastore.events.AlterPartitionEvent;
import org.apache.hadoop.hive.metastore.events.AlterTableEvent;
import org.apache.hadoop.hive.metastore.events.CreateTableEvent;
import org.apache.hadoop.hive.metastore.events.DropPartitionEvent;
import org.apache.hadoop.hive.metastore.events.DropTableEvent;
import org.apache.hadoop.hive.metastore.events.InsertEvent;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.AmazonSNSClientBuilder;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.PublishResult;
/**
* <p>
* A simple Hive Metastore Event Listener which spits out Event Information in JSON format to SNS Topic specified
* through ${SNS_ARN} environment variable.
* </p>
*/
public class ApiarySnsListener extends MetaStoreEventListener {
private static final Logger log = LoggerFactory.getLogger(ApiarySnsListener.class);
private static final String TOPIC_ARN = System.getenv("SNS_ARN");
final static String PROTOCOL_VERSION = "1.0";
private final String protocolVersion = PROTOCOL_VERSION;
private final AmazonSNS snsClient;
public ApiarySnsListener(Configuration config) {
super(config);
snsClient = AmazonSNSClientBuilder.defaultClient();
log.debug("ApiarySnsListener created ");
}
ApiarySnsListener(Configuration config, AmazonSNS snsClient) {
super(config);
this.snsClient = snsClient;
log.debug("ApiarySnsListener created");
}
@Override
public void onCreateTable(CreateTableEvent event) throws MetaException {
if (event.getStatus() == false) {
return;
}
publishEvent(EventType.CREATE_TABLE, event.getTable(), null, null, null);
}
@Override
public void onDropTable(DropTableEvent event) throws MetaException {
if (event.getStatus() == false) {
return;
}
publishEvent(EventType.DROP_TABLE, event.getTable(), null, null, null);
}
@Override
public void onAlterTable(AlterTableEvent event) throws MetaException {
if (event.getStatus() == false) {
return;
}
publishEvent(EventType.ALTER_TABLE, event.getNewTable(), event.getOldTable(), null, null);
}
@Override
public void onAddPartition(AddPartitionEvent event) throws MetaException {
if (event.getStatus() == false) {
return;
}
Iterator<Partition> partitions = event.getPartitionIterator();
while (partitions.hasNext()) {
// TODO: do we want to have a separate event for each partition or one event with all of them?
publishEvent(EventType.ADD_PARTITION, event.getTable(), null, partitions.next(), null);
}
}
@Override
public void onDropPartition(DropPartitionEvent event) throws MetaException {
if (event.getStatus() == false) {
return;
}
Iterator<Partition> partitions = event.getPartitionIterator();
while (partitions.hasNext()) {
// TODO: do we want to have a separate event for each partition or one event with all of them?
publishEvent(EventType.DROP_PARTITION, event.getTable(), null, partitions.next(), null);
}
}
@Override
public void onInsert(InsertEvent event) throws MetaException {
if (event.getStatus() == false) {
return;
}
publishInsertEvent(EventType.INSERT, event.getDb(), event.getTable(), event.getPartitionKeyValues(),
event.getFiles(), event.getFileChecksums());
}
@Override
public void onAlterPartition(AlterPartitionEvent event) throws MetaException {
if (event.getStatus() == false) {
return;
}
publishEvent(EventType.ALTER_PARTITION, event.getTable(), null, event.getNewPartition(), event.getOldPartition());
}
private void publishEvent(
EventType eventType,
Table table,
Table oldtable,
Partition partition,
Partition oldpartition)
throws MetaException {
JSONObject json = createBaseMessage(eventType, table.getDbName(), table.getTableName());
if (oldtable != null) {
json.put("oldTableName", oldtable.getTableName());
}
if (partition != null) {
LinkedHashMap<String, String> partitionKeysMap = new LinkedHashMap<>();
for (FieldSchema fieldSchema : table.getPartitionKeys()) {
partitionKeysMap.put(fieldSchema.getName(), fieldSchema.getType());
}
JSONObject partitionKeys = new JSONObject(partitionKeysMap);
json.put("partitionKeys", partitionKeys);
JSONArray partitionValuesArray = new JSONArray(partition.getValues());
json.put("partitionValues", partitionValuesArray);
}
if (oldpartition != null) {
JSONArray partitionValuesArray = new JSONArray(oldpartition.getValues());
json.put("oldPartitionValues", partitionValuesArray);
}
sendMessage(json);
}
private void publishInsertEvent(
EventType eventType,
String dbName,
String tableName,
Map<String, String> partitionKeyValues,
List<String> files,
List<String> fileChecksums) {
JSONObject json = createBaseMessage(eventType, dbName, tableName);
JSONArray filesArray = new JSONArray(files);
json.put("files", filesArray);
JSONArray fileChecksumsArray = new JSONArray(fileChecksums);
json.put("fileChecksums", fileChecksumsArray);
JSONObject partitionKeyValuesObject = new JSONObject(partitionKeyValues);
json.put("partitionKeyValues", partitionKeyValuesObject);
sendMessage(json);
}
private JSONObject createBaseMessage(EventType eventType, String dbName, String tableName) {
JSONObject json = new JSONObject();
json.put("protocolVersion", protocolVersion);
json.put("eventType", eventType.toString());
json.put("dbName", dbName);
json.put("tableName", tableName);
return json;
}
private void sendMessage(JSONObject json) {
String msg = json.toString();
PublishRequest publishRequest = new PublishRequest(TOPIC_ARN, msg);
log.debug(String.format("Sending Message: {} to {}", msg, TOPIC_ARN));
PublishResult publishResult = snsClient.publish(publishRequest);
// TODO: check on size of message and truncation etc (this can come later if/when we add more)
log.debug("Published SNS Message - " + publishResult.getMessageId());
}
}
|
187e720128783eed2969c270a2b22d89c5d792e6
|
[
"Markdown",
"Java",
"Maven POM"
] | 5
|
Maven POM
|
ExpediaInc/apiary-extensions
|
a44a51e19e449d3d1202c935a322dc94c547eca0
|
a714c6055e142244496c1fe8cdb5f522f1247833
|
refs/heads/master
|
<file_sep><?php
namespace cleartag\satis;
class Demo {
}
|
64f692cc60b2769fabe25b9b24c5b7930b3d5001
|
[
"PHP"
] | 1
|
PHP
|
cleartag/statis-demo-3
|
c6fa77bda7a6a64062b96452883a5f62968f382d
|
72278a6ac9bfb2ae7acb70a9ce997c677e92a7f7
|
refs/heads/master
|
<file_sep>import os.path
import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate
import matplotlib
matplotlib.rcParams["font.family"] = "STSong" # 设置中文字体
matplotlib.rcParams["font.size"] = 14 # 设置字号
current_dir = os.path.dirname(os.path.abspath(__file__)) # 文件路径
def two_p(p1, p2):
"""
由两点确定一条直线
: para : p1, p2: 形如[x, y]的两点
: return : 直线方程(函数)f(x)
"""
x1, y1 = p1
x2, y2 = p2
slope = (y2 - y1) / (x2 - x1)
intercept = (y1 * x2 - x1 * y2) / (x2 - x1)
return lambda x: slope * x + intercept
# parse args
flag = input("(1)全回流 /(2)部分回流 [选择1或者2]:")
if flag == "2": # 部分回流
flag = False
# 数据
delta = float(input("delta:"))
r = 4
xw = float(input("xw:"))
xd = float(input("xd:"))
xf = float(input("xf:"))
elif flag == "1": # 全回流
flag = True
# 数据
xw = float(input("xw:"))
xd = float(input("xd:"))
else:
raise ValueError("Expect 1/2, but get {}".format(flag))
if flag: # 全回流的情况
title = "全回流"
else: # 部分回流的情况
#title = "部分回流, R={}, 板{}进料".format(r, level)
title = "部分回流,R={}".format(r)
a = [xd, xd]
b = [xw, xw]
c = [0, xd/(r+1)]
l_jl = two_p(a, c)
d = [(xf/(delta-1)+xd/(r+1))/(delta/(delta-1)-r/(r+1)), 0]
d[1] = l_jl(d[0])
l_tl = two_p(b, d)
x_y = np.loadtxt(os.path.join(current_dir, "x_y.csv"), delimiter=',')
f_y_x = interpolate.interp1d(x_y[1], x_y[0], kind="slinear") # 线性插值做出平衡线
# 作图相关参数设置
plt.title(title)
plt.xlabel("$x$")
plt.ylabel('$y$')
# 做出平衡线与对角线
plt.plot(x_y[0], x_y[1], color="black")
plt.plot([0, 1], [0, 1], color="black")
# 标记出各点
plt.annotate("$a$ ($x_d$, $x_d$)", [xd, xd], xytext=(5, -10), textcoords="offset points")
plt.annotate("$b$ ($x_w$, $x_w$)", [xw, xw], xytext=(5, -10), textcoords="offset points")
plt.scatter([xd, xw], [xd, xw], color="black", s=10)
# 部分回流的情况
if not flag:
plt.annotate("$d$ ({0:.2}, {1:.2})".format(*d), d, xytext=(5, -10), textcoords="offset points", color="red")
plt.plot([b[0], d[0], a[0]],[b[1], d[1], a[1]], color="red")
plt.scatter(*d, color="red", marker="o", s=15)
def l(x):
"""
操作线方程
"""
if flag or x < xw:
return x
elif x < d[0]:
return l_tl(x)
else:
return l_jl(x)
# 绘制折线
x_tmp = xd
y_tmp = l(x_tmp)
x_line = []
y_line = []
cnt = 0
while x_tmp > xw+0.005: # 加上一个小数,否则在xw=0时会出问题
cnt += 1
x_line.append(x_tmp)
y_line.append(y_tmp)
x_tmp = f_y_x(y_tmp)
x_line.append(x_tmp)
y_line.append(y_tmp)
plt.annotate(cnt, [x_tmp, y_tmp], xytext=(-10, 5), textcoords="offset points")
y_tmp = l(x_tmp)
x_line.append(x_tmp)
y_line.append(y_tmp)
plt.plot(x_line, y_line) # 把折线在图上画出来
plt.show()
plt.savefig(os.path.join(current_dir, "{}.svg".format(title)))<file_sep># 精馏塔回流曲线绘图工具
## 安装
```shell
pip install -r requirements.txt
```
## 绘图
```shell
python ./cheme.py
```

|
daa745c5e355c9de029e1463ae6634f24a52908b
|
[
"Markdown",
"Python"
] | 2
|
Python
|
idocx/reflux-ratio-tool
|
86b0073ccf4484a800dfcf2f08c60f6458b885ba
|
5981936d298f981f531bf1570b46880d9015052a
|
refs/heads/master
|
<repo_name>wstence/ReverseString<file_sep>/Makefile
all:
g++ -o rev revString.cpp
<file_sep>/README.md
Reverse String
Program displays reversed string.
Sample input string: cat
Sample output: Reversed string: tac
<file_sep>/revString.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i, j;
string orig = "hello";
string result = orig;
int rsize = result.size();
for (i = 0, j = rsize-1; i < orig.size(); i++, j--)
result[i] = orig[j];
cout << "Reversed string: " << result << "\n";
return 0;
}
|
676b9689b278340608f45a349dbe6277c76fec3b
|
[
"Markdown",
"Makefile",
"C++"
] | 3
|
Makefile
|
wstence/ReverseString
|
2b91ba9324aa8f7d7b62f804a0a548ade96f5844
|
8fc604217a8cb057b18b7a4d5fc355da814c9c3e
|
refs/heads/master
|
<repo_name>Przemyslaw5/test<file_sep>/springboot-api-docker/src/main/resources/application.properties
server.port=10101
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://database:3306/animaldb
spring.datasource.username=user
spring.datasource.password=<PASSWORD>
spring.datasource.driver-class-name=com.mysql.jdbc.Driver<file_sep>/springboot-api-docker/Dockerfile
FROM openjdk:15-jdk-alpine3.12
ADD target/springboot-api-docker-0.0.1-SNAPSHOT.jar .
EXPOSE 10101
CMD java -jar springboot-api-docker-0.0.1-SNAPSHOT.jar<file_sep>/springboot-client-docker/Dockerfile
FROM openjdk:15-jdk-alpine3.12
ADD target/springboot-client-docker-0.0.1-SNAPSHOT.jar .
EXPOSE 12121
CMD java -jar springboot-client-docker-0.0.1-SNAPSHOT.jar<file_sep>/springboot-client-docker/src/main/java/pl/theliver/springbootclientdocker/AnimalClient.java
package pl.theliver.springbootclientdocker;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class AnimalClient {
@GetMapping("/showForGui")
public Animal[] get() {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Animal[]> exchange = restTemplate.exchange("http://api:10101/animals",
HttpMethod.GET,
HttpEntity.EMPTY,
Animal[].class);
Animal[] body = exchange.getBody();
return body;
}
}
<file_sep>/springboot-client-docker/src/test/java/pl/theliver/springbootclientdocker/SpringbootClientDockerApplicationTests.java
package pl.theliver.springbootclientdocker;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringbootClientDockerApplicationTests {
@Test
void contextLoads() {
}
}
|
345d4dd4e35cfa732d803f6db454aca8d6df22f8
|
[
"Java",
"Dockerfile",
"INI"
] | 5
|
INI
|
Przemyslaw5/test
|
1fa08010f8fff36a5faa758d5ab8ba4fdd151ab1
|
a757a85801b2b846058f04f7ae27f706819aa384
|
refs/heads/master
|
<file_sep>import itertools
import enchant
print("Enter the outer circle letters")
letters = list(input().split())
print("Enter middle letter")
mid = input()
D = enchant.Dict("en_US")
Dx = enchant.Dict("en_UK")
words = []
n = len(letters)
for i in range(2**n):
curlist = []
for j in range(n):
if(i & (1 << j)):
curlist.append(letters[j])
if len(curlist) < 3:
continue
curlist.append(mid)
for perm in itertools.permutations(curlist):
r = "".join(perm)
if D.check(r) or Dx.check(r):
words.append(r)
words = set(words)
print(words, end = '\n')
<file_sep># Word Wheel Puzzle Solver
Solver for Word Wheel Puzzle using Python Enchant library
|
ed76cddc64925954c6c01e7e46545c8c5af0289f
|
[
"Markdown",
"Python"
] | 2
|
Python
|
sainanee/word-wheel
|
894dadc4c6d1f5d90261b7b89cac80ced2ded581
|
ddca02afb5b7460f56316f7b28b407c2abe95cd4
|
refs/heads/master
|
<repo_name>DamnCoder/dcpp_math<file_sep>/project/include/math/matrix.h
//
// matrix.h
//
// Based upon Mathlib.h -- Copyright (c) 2005-2006 <NAME>
//
// This code is licenced under the MIT license.
//
// Modified by <NAME> on 17/07/12.
//
#ifndef bitthemall_matrix_h
#define bitthemall_matrix_h
#include "vector3.h"
#include "vector4.h"
#include "quaternion.h"
#include <string.h>
namespace dc
{
namespace math
{
/////////////////////////////////////////////////////////////////////////////
//
// class Matrix4x4<Real> - Implement a 4x4 Matrix class that can represent
// any 3D affine transformation.
//
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
//
// class Matrix4x4<Real> implementation.
//
// --------------------------------------------------------------------------
//
// MATRIX ORGANIZATION
//
// The purpose of this class is so that a user might perform transformations
// without fiddling with plus or minus signs or transposing the matrix
// until the output "looks right". But of course, the specifics of the
// internal representation is important. Not only for the implementation
// in this file to be correct, but occasionally direct access to the
// matrix variables is necessary, or beneficial for optimization. Thus,
// we document our matrix conventions here.
//
// Strict adherance to linear algebra rules dictates that the
// multiplication of a 4x4 matrix by a 3D vector is actually undefined.
// To circumvent this, we can consider the input and output vectors as
// having an assumed fourth coordinate of 1. Also, since the rightmost
// column is [ 0 0 0 1 ], we can simplificate calculations ignoring
// this last column. This is shown below:
//
// | m11 m12 m13 0 | | x | | x'|
// | m21 m22 m23 0 | | y | = | y'|
// | m31 m32 m33 0 | | z | | z'|
// | tx ty tz 1 | | 1 | | 1 |
//
// We use row vectors to represent the right, up and forward vectors
// in the 4x4 matrix. OpenGL uses column vectors, but the elements of
// an OpenGL matrix are ordered in columns so that m[i][j] is in row j
// and column i. This is the reverse of the standard C convention in
// which m[i][j] is in row i and column j. The matrix should be
// transposed before being sent to OpenGL.
//
// Column - Row Row - Column
// | m11 m21 m31 tx | | m0 m4 m8 m12 | | m0 m1 m2 m3 |
// | m12 m22 m32 ty | | m1 m5 m9 m13 | | m4 m5 m6 m7 |
// | m13 m23 m33 tz | | m2 m6 m10 m14 | | m8 m9 m10 m11 |
// | 0 0 0 tw | | m3 m7 m11 m15 | | m12 m13 m14 m15 |
//
// OpenGL style OpenGL matrix standard C
// arrangement convention
//
// Fortunately, accessing to the raw matrix data via the m[] array gives
// us the transpose matrix; i.e. in OpenGL form, so that we can directly use
// it with glLoadMatrix{fd}() or glMultMatrix{fd}().
//
// Also, since the rightmost column (in standard C form) should always
// be [ 0 0 0 1 ], and sice these values (h14, h24, h34 and tw) are
// initialized in constructors, we don't need to modify them in our
// matrix operations, so we don't perform useless calculations...
//
// The right-hand rule is used to define "positive" rotation.
//
// +y +x'
// | |
// | |
// |__+x +y'__|
// / /
// / /
// +z +z'
//
// initial position Positive rotation of
// pi/2 around z-axis
//
/////////////////////////////////////////////////////////////////////////////
template <typename Real>
class Matrix4x4
{
public:
// ===========================================================
// Constant / Enums / Typedefs internal usage
// ===========================================================
// ===========================================================
// Static fields / methods
// ===========================================================
public:
// Matrix-builder functions
static Matrix4x4<Real> Create (const Vector3<Real>& position, const Quaternion<Real>& rotation, const Vector3<Real>& scale);
static Matrix4x4<Real> Frustum (Real left, Real right, Real bottom, Real top, Real near, Real far);
static Matrix4x4<Real> Orthographic (Real left, Real right, Real bottom, Real top, Real near, Real far);
static Matrix4x4<Real> Perspective (Real fovY, Real aspect, Real near, Real far);
static Matrix4x4<Real> LookAt (const Vector3<Real>& eye, const Vector3<Real>& target, const Vector3<Real>& camUp);
static Matrix4x4<Real> Inverse (const Matrix4x4<Real>& mat);
static Matrix4x4<Real> Identity ();
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
public:
// Basis vectors from matrix
const Vector3<Real> Right() const { return Vector3<Real>(m11, m12, m13); }
const Vector3<Real> Up() const { return Vector3<Real>(m21, m22, m23); }
const Vector3<Real> Forward() const { return Vector3<Real>(m31, m32, m33); }
const Vector4<Real> Row1() const { return Vector4<Real>(m11, m12, m13, h14); }
const Vector4<Real> Row2() const { return Vector4<Real>(m21, m22, m23, h24); }
const Vector4<Real> Row3() const { return Vector4<Real>(m31, m32, m33, h34); }
const Vector4<Real> Row4() const { return Vector4<Real>(tx, ty, tz, tw); }
Vector3<Real> Position() const { return Vector3<Real>(tx, ty, tz); }
Vector3<Real> Scale() const { return Vector3<Real>(m11, m22, m33); }
Quaternion<Real> Rotation() const;
Vector3<Real> EulerAngles () const;
const bool IsSingular() const;
const Real Determinant3x3() const;
// ===========================================================
// Constructors
// ===========================================================
public:
Matrix4x4(): h14(0), h24(0), h34(0), tw(1)
{}
Matrix4x4(const Matrix4x4& copy)
{
memcpy(&m, copy.m, 16 * sizeof(Real));
//PrintMatrix(*this);
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
public:
void operator= (const Matrix4x4<Real>& m);
// Matrix comparison
const bool operator==(const Matrix4x4<Real>& m) const;
const bool operator!=(const Matrix4x4<Real>& m) const;
// Combined assignment operators to conform to C notation convention
Matrix4x4<Real>& operator+= (const Matrix4x4<Real>& m);
Matrix4x4<Real>& operator-= (const Matrix4x4<Real>& m);
Matrix4x4<Real> operator+ (const Matrix4x4<Real>& m) const;
Matrix4x4<Real> operator- (const Matrix4x4<Real>& m) const;
// ===========================================================
// Methods
// ===========================================================
public:
void Set(const Vector3<Real>& position, const Quaternion<Real>& rotation, const Vector3<Real>& scale);
void Identify();
void Transpose();
void Translate (const Vector3<Real>& position);
void Rotation (const Vector3<Real>& rotation);
void Rotation (const Real x, const Real y, const Real z);
void Rotation (const Vector3<Real>& axis, const Real theta);
void Rotation (const Quaternion<Real> &q);
void Scale (const Vector3<Real>& scale);
Vector3<Real> TransformPosition (const Vector3<Real>& position) const;
Vector3<Real> InverseTransformPosition (const Vector3<Real>& position) const;
Vector3<Real> TransformRotation (const Vector3<Real>& rotation) const;
Vector3<Real> InverseTransformRotation (const Vector3<Real>& rotation) const;
public:
// Accessor. This allows to use the matrix object
// like an array of Real. For example:
// Matrix4x4<float> mat;
// float f = mat[4]; // access to m21
operator const Real *() { return m; }
operator const Real *() const { return m; }
// ===========================================================
// Fields
// ===========================================================
public:
// Member variables
// The values of the matrix. Basically the upper 3x3 portion
// contains a linear transformation, and the last column is the
// translation portion. Here data is transposed, check the header
// for more details.
union
{
struct
{
Real m11, m12, m13, h14;
Real m21, m22, m23, h24;
Real m31, m32, m33, h34;
Real tx, ty, tz, tw;
};
// Access to raw packed matrix data
Real m[16];
};
};
// ===========================================================
// Class typedefs
// ===========================================================
// Predefined Matrix4x4 types
typedef Matrix4x4<float> Matrix4x4f;
typedef Matrix4x4<double> Matrix4x4d;
inline void PrintMatrix(const math::Matrix4x4f& matrix)
{
printf("%f %f %f %f\n", matrix[0], matrix[1], matrix[2], matrix[3]);
printf("%f %f %f %f\n", matrix[4], matrix[5], matrix[6], matrix[7]);
printf("%f %f %f %f\n", matrix[8], matrix[9], matrix[10], matrix[11]);
printf("%f %f %f %f\n", matrix[12], matrix[13], matrix[14], matrix[15]);
}
// Nonmember Matrix4x4 functions
// Matrix concatenation
template <typename Real>
Matrix4x4<Real> operator* (const Matrix4x4<Real>& m1, const Matrix4x4<Real>& m2);
template <typename Real>
Matrix4x4<Real> operator*= (const Matrix4x4<Real>& m1, const Matrix4x4<Real>& m2);
// ===========================================================
// Template/Inline implementation
// ===========================================================
template <typename Real>
inline
void Matrix4x4<Real>::operator= (const Matrix4x4<Real>& copy)
{
memcpy(&m, copy.m, 16 * sizeof(Real));
//PrintMatrix(*this);
}
template <typename Real>
inline
void Matrix4x4<Real>::Set(const Vector3<Real>& position, const Quaternion<Real>& rotation, const Vector3<Real>& scale)
{
const float xs = rotation.x * 2.f, ys = rotation.y * 2.f, zs = rotation.z * 2.f;
const float wx = rotation.w * xs, wy = rotation.w * ys, wz = rotation.w * zs;
const float xx = rotation.x * xs, xy = rotation.x * ys, xz = rotation.x * zs;
const float yy = rotation.y * ys, yz = rotation.y * zs, zz = rotation.z * zs;
m11 = scale.x * (1.f - (yy + zz));
m21 = scale.y * (xy - wz);
m31 = scale.z * (xz + wy);
tx = position.x;
m12 = scale.x * (xy + wz);
m22 = scale.y * (1.f - (xx + zz));
m32 = scale.z * (yz - wx);
ty = position.y;
m13 = scale.x * (xz - wy);
m23 = scale.y * (yz + wx);
m33 = scale.z * (1.f - (xx + yy));
tz = position.z;
h14 = 0.f;
h24 = 0.f;
h34 = 0.f;
tw = 1.f;
}
template <typename Real>
inline
Matrix4x4<Real> Matrix4x4<Real>::Create(const Vector3<Real>& position, const Quaternion<Real>& rotation, const Vector3<Real>& scale)
{
Matrix4x4<Real> m;
const float xs = rotation.x * 2.f, ys = rotation.y * 2.f, zs = rotation.z * 2.f;
const float wx = rotation.w * xs, wy = rotation.w * ys, wz = rotation.w * zs;
const float xx = rotation.x * xs, xy = rotation.x * ys, xz = rotation.x * zs;
const float yy = rotation.y * ys, yz = rotation.y * zs, zz = rotation.z * zs;
m.m11 = scale.x * (1.f - (yy + zz));
m.m21 = scale.y * (xy - wz);
m.m31 = scale.z * (xz + wy);
m.tx = position.x;
m.m12 = scale.x * (xy + wz);
m.m22 = scale.y * (1.f - (xx + zz));
m.m32 = scale.z * (yz - wx);
m.ty = position.y;
m.m13 = scale.x * (xz - wy);
m.m23 = scale.y * (yz + wx);
m.m33 = scale.z * (1.f - (xx + yy));
m.tz = position.z;
m.h14 = 0.f;
m.h24 = 0.f;
m.h34 = 0.f;
m.tw = 1.f;
return m;
}
#include "matrix.inl"
}
}
#endif
<file_sep>/project/include/math/dcmath.h
//
// dcmath.h
//
// A small group of utility functions to be used with real numbers.
//
// Created by <NAME> on 15/07/12.
//
#ifndef bitthemall_real_h
#define bitthemall_real_h
#include <cmath>
namespace dc
{
namespace math
{
const double DC_EPSILON = 0.0001;
// Declare a global constant for pi and a few multiples.
const double DC_PI = 3.14159265358979323846264338327950288;
const double DC_PI2 = DC_PI * 2.0;
const double DC_PI_OVER_2 = DC_PI / 2.0;
const double DC_ONE_OVER_PI = 1.0 / DC_PI;
const double DC_ONE_OVER_2PI = 1.0 / DC_PI2;
const double DC_ONE_OVER_180 = 1.0 / 180.0;
const double DC_PI_OVER_180 = DC_PI / 180.0; // Grados a radianes
const double DC_180_OVER_PI = 180.0 / DC_PI; // Radianes a grados
template <typename Real>
inline
const Real
Sin (const Real rad)
{
return std::sin (rad);
}
template <typename Real>
inline
const Real
Cos (const Real rad)
{
return std::cos (rad);
}
template <typename Real>
inline
const Real
Atan2 (const Real y, const Real x)
{
return std::atan2 (y, x);
}
template <typename Real>
inline
const Real
Asin (const Real x)
{
return std::asin (x);
}
// Convert between degrees and radians
template <typename Real>
inline
const Real
DegToRad (const Real deg)
{
return deg * DC_PI_OVER_180;
}
// Convert between radians and degrees
template <typename Real>
inline
const Real
RadToDeg (const Real rad)
{
return rad * DC_180_OVER_PI;
}
// Clamps a value between min and max
template<typename Real>
inline
const Real
Clamp(const Real value, const Real min, const Real max)
{
if(value > 1.0) return max;
if(value < 0.0) return min;
return value;
}
template<typename Real>
inline
const Real
LerpClamped(const Real from, const Real to, const Real perc)
{
return (from + Clamp<Real>(perc, 0.0, 1.0)*(to - from));
}
template<typename Real>
inline
const Real
Lerp(const Real from, const Real to, const Real perc)
{
return (from + perc*(to - from));
}
template<typename Real>
inline
Real Abs(Real x)
{
return (x > 0) ? x : -x;
}
template<typename Real>
inline
const bool
Approximately(const Real a, const Real b, const Real epsilon)
{
return Abs<Real>(a - b) < epsilon;
}
template<typename Real>
inline
const bool
Approximately(const Real a, const Real b)
{
return Abs<Real>(a - b) < DC_EPSILON;
}
template<typename Real>
inline
const Real Sign(const Real x)
{
if (0 < x) return 1.0;
if (x < 0) return -1.0;
return 0.0;
}
template<typename Real>
inline
const Real Sqrt(const Real value)
{
return std::sqrt(value);
}
template<typename Real>
inline
const Real Normal(const Real a, const Real b, const Real c, const Real d)
{
return Sqrt(a * a + b * b + c * c + d * d);
}
inline
const int
Half(const int value)
{
return value >> 1;
}
inline
const int
Double(const int value)
{
return 1 << value;
}
/*
inline
int Abs(int a) {
int mask = (a >> (sizeof(int) * CHAR_BIT - 1));
return (a + mask) ^ mask;
}
inline
float Abs(float f)
{
int i=((*(int*)&f)&0x7fffffff);
return (*(float*)&i);
}
inline
double Abs(double g)
{
unsigned long int *gg;
gg=(unsigned long int*)&g;
*(gg)&=9223372036854775807llu;
return g;
}
inline
float Neg(float f)
{
int i=((*(int*)&f)^0x80000000);
return (*(float*)&i);
}
inline
int Sign(float f)
{
return 1+(((*(int*)&f)>>31)<<1);
}
*/
}
}
#endif
<file_sep>/project/include/math/quaternion.h
//
// quaternion.h
//
// Based upon Mathlib.h -- Copyright (c) 2005-2006 <NAME>
//
// This code is licenced under the MIT license.
//
// Modified by <NAME> on 17/07/12.
//
#ifndef bitthemall_quaternion_h
#define bitthemall_quaternion_h
#include "dcmath.h"
namespace dc
{
namespace math
{
template<typename Real>
class Matrix4x4;
template<typename Real>
class Vector3;
/////////////////////////////////////////////////////////////////////////////
//
// class Quaternion<Real> - Implement a quaternion, for purposes of
// representing an angular displacement (orientation) in 3D.
//
/////////////////////////////////////////////////////////////////////////////
template <typename Real>
class Quaternion
{
public:
// Quaternion <-> Euler conversions; XYZ rotation order; angles in radians
static Quaternion<Real> FromEulerRad (const Real pitch, const Real yaw, const Real roll);
static Quaternion<Real> FromEulerRad (const Vector3<Real>& rotationRad);
static Vector3<Real> EulerRad (const Quaternion<Real>& q);
public:
const Real GimbalPole() const;
const Real YawRad() const;
const Real PitchRad() const;
const Real RollRad() const;
const Real RotationAngle () const;
Vector3<Real> RotationAxis () const;
// Getters / Setters
/*
Accessor. This allows to use the vector object
like an array of Real. For example:
Vector3<float> v (...);
float f = v[1]; // access to _y
*/
operator const Real *() const { return q; }
public:
// Constructors
Quaternion () { }
Quaternion (Real x, Real y, Real z): x (x), y (y), z (z), w (0.0) { ComputeW(); }
Quaternion (Real x, Real y, Real z, Real w): x (x), y (y), z (z), w (w) {}
Quaternion (const Matrix4x4<Real>& matrix) { FromMatrix(matrix); }
// Copy Constructor
Quaternion (const Quaternion<Real>& copy): x (copy.x), y (copy.y), z (copy.z), w (copy.w) { }
public:
// Public interface
void Identity ();
void Normalize ();
void ComputeW ();
void Rotate (Vector3<Real>& v) const;
void FromMatrix (const Matrix4x4<Real>& m);
// Quaternion comparison
const bool operator== (const Quaternion<Real>& q) const;
const bool operator!= (const Quaternion<Real>& q) const;
// Quaternion operations
Quaternion<Real> operator+ (const Quaternion<Real>& q) const;
Quaternion<Real> operator- (const Quaternion<Real>& q) const;
Quaternion<Real> operator* (const Quaternion<Real>& q) const;
Quaternion<Real> operator* (const Vector3<Real>& v) const;
Quaternion<Real> operator* (const Real k) const;
Quaternion<Real> operator/ (const Real k) const;
Quaternion<Real>& operator+= (const Quaternion<Real>& q);
Quaternion<Real>& operator-= (const Quaternion<Real>& q);
Quaternion<Real>& operator*= (const Quaternion<Real>& q);
Quaternion<Real>& operator*= (const Vector3<Real>& v);
Quaternion<Real>& operator*= (const Real k);
Quaternion<Real>& operator/= (const Real k);
Quaternion<Real> operator~ () const; // Quaternion conjugate
Quaternion<Real> operator- () const; // Quaternion negation
public:
// Member variables
// The 4 values of the quaternion. Normally, it will not
// be necessary to manipulate these directly. However,
// we leave them public, since prohibiting direct access
// makes some operations, such as file I/O, unnecessarily
// complicated.
union
{
struct
{
Real x, y, z, w;
};
Real q[4];
};
};
// Predefined Quaternion types
typedef Quaternion<float> Quaternionf;
typedef Quaternion<double> Quaterniond;
// A global "identity" quaternion constant
static const Quaternionf QuaternionIdentityf (0.0f, 0.0f, 0.0f, 1.0f);
static const Quaterniond QuaternionIdentityd (0.0, 0.0, 0.0, 1.0);
//
// Nonmember Quaternion functions
//
template <typename Real>
Quaternion<Real> operator* (const Real k, const Quaternion<Real>& q);
template <typename Real>
Real DotProduct (const Quaternion<Real>& a, const Quaternion<Real>& b);
template <typename Real>
Quaternion<Real> Conjugate (const Quaternion<Real>& q);
template <typename Real>
Quaternion<Real> Inverse (const Quaternion<Real>& q);
template <typename Real>
Quaternion<Real> RotationQuaternion (const Vector3<Real>& axis, const Real theta);
template <typename Real>
Quaternion<Real> Log (const Quaternion<Real>& q);
template <typename Real>
Quaternion<Real> Exp (const Quaternion<Real>& q);
template <typename Real>
Quaternion<Real> Pow (const Quaternion<Real>& q, const Real exponent);
template <typename Real>
Quaternion<Real> Slerp (const Quaternion<Real>& from, const Quaternion<Real>& to, const Real perc);
template <typename Real>
Quaternion<Real> Squad (const Quaternion<Real>& q0, const Quaternion<Real>& qa,
const Quaternion<Real>& qb, const Quaternion<Real>& q1, const Real perc);
template <typename Real>
inline void Intermediate (const Quaternion<Real>& qprev, const Quaternion<Real>& qcurr,
const Quaternion<Real>& qnext, Quaternion<Real>& qa,
Quaternion<Real>& qb);
/////////////////////////////////////////////////////////////////////////////
//
// class Quaternion<Real> implementation.
//
/////////////////////////////////////////////////////////////////////////////
// --------------------------------------------------------------------------
// Quaternion::identity
//
// Set to identity
// --------------------------------------------------------------------------
template <typename Real>
inline void
Quaternion<Real>::Identity ()
{
x = y = z = 0.0;
w = 1.0;
}
// --------------------------------------------------------------------------
// Quaternion::normalize
//
// "Normalize" a quaternion. Note that normally, quaternions
// are always normalized (within limits of numerical precision).
//
// This function is provided primarily to combat floating point "error
// creep", which can occur when many successive quaternion operations
// are applied.
// --------------------------------------------------------------------------
template <typename Real>
inline void
Quaternion<Real>::Normalize ()
{
// Compute magnitude of the quaternion
Real mag = Sqrt ((x * x) + (y * y) + (z * z) + (w * w));
// Check for bogus length, to protect against divide by zero
if (mag > 0.0)
{
// Normalize it
Real oneOverMag = 1.0 / mag;
x *= oneOverMag;
y *= oneOverMag;
z *= oneOverMag;
w *= oneOverMag;
}
}
// --------------------------------------------------------------------------
// Quaternion<Real>::computeW
//
// Compute the W component of a unit quaternion given its x,y,z components.
// --------------------------------------------------------------------------
template <typename Real>
inline void
Quaternion<Real>::ComputeW ()
{
Real t = 1.0 - (x * x) - (y * y) - (z * z);
if (t < 0.0)
w = 0.0;
else
w = -Sqrt (t);
}
// --------------------------------------------------------------------------
// Quaternion<Real>::rotate
//
// Rotate a point by quaternion. v' = q.p.q*, where p = <0, v>.
// --------------------------------------------------------------------------
template <typename Real>
inline void
Quaternion<Real>::Rotate (Vector3<Real>& v) const
{
Quaternion<Real> qf = (*this) * v * ~(*this);
v.x = qf.x;
v.y = qf.y;
v.z = qf.z;
}
// --------------------------------------------------------------------------
// Quaternion::fromMatrix
//
// Setup the quaternion to perform a rotation, given the angular displacement
// in matrix form.
// --------------------------------------------------------------------------
template <typename Real>
inline void
Quaternion<Real>::FromMatrix (const Matrix4x4<Real>& m)
{
const Real trace = m.m11 + m.m22 + m.m33 + 1.0;
if (trace > DC_EPSILON)
{
const Real s = 0.5 / std::sqrt (trace);
w = 0.25 / s;
x = (m.m23 - m.m32) * s;
y = (m.m31 - m.m13) * s;
z = (m.m12 - m.m21) * s;
}
else
{
if ((m.m11 > m.m22) && (m.m11 > m.m33))
{
const Real s = 0.5 / std::sqrt (1.0 + m.m11 - m.m22 - m.m33);
x = 0.25 / s;
y = (m.m21 + m.m12) * s;
z = (m.m31 + m.m13) * s;
w = (m.m32 - m.m23) * s;
}
else if (m.m22 > m.m33)
{
const Real s = 0.5 / std::sqrt (1.0 + m.m22 - m.m11 - m.m33);
x = (m.m21 + m.m12) * s;
y = 0.25 / s;
z = (m.m32 + m.m23) * s;
w = (m.m31 - m.m13) * s;
}
else
{
const Real s = 0.5 / std::sqrt (1.0 + m.m33 - m.m11 - m.m22);
x = (m.m31 + m.m13) * s;
y = (m.m32 + m.m23) * s;
z = 0.25 / s;
w = (m.m21 - m.m12) * s;
}
}
}
// --------------------------------------------------------------------------
// Quaternion::fromEulerAngles
//
// Setup the quaternion to perform an object->inertial rotation, given the
// orientation in XYZ-Euler angles format. x,y,z parameters must be in
// radians.
//
// X-Axis -> Bank - Pitch
// Y-Axis -> Heading - Yaw
// Z-Axis -> Attitude - Roll
//
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/index.htm
// http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/steps/index.htm
// --------------------------------------------------------------------------
template <typename Real>
inline
Quaternion<Real>
Quaternion<Real>::FromEulerRad (const Real pitch, const Real yaw, const Real roll)
{
// Compute sine and cosine of the half angles
// X-Axis -> Bank - Pitch
const Real hp = pitch * 0.5;
const Real shp = Sin (hp);
const Real chp = Cos (hp);
// Y-Axis -> Heading - Yaw
const Real hy = yaw * 0.5f;
const Real shy = Sin (hy);
const Real chy = Cos (hy);
// Z-Axis -> Attitude - Roll
const Real hr = roll * 0.5;
const Real shr = Sin (hr);
const Real chr = Cos (hr);
const Real chy_chp = chy * chp;
const Real chy_shp = chy * shp;
const Real shy_chp = shy * chp;
const Real shy_shp = shy * shp;
const Real x = (chr * chy_shp) + (shr * shy_chp);
const Real y = (chr * shy_chp) + (shr * chy_shp);
const Real z = (shr * chy_chp) - (chr * shy_shp);
const Real w = (chr * chy_chp) - (shr * shy_shp);
// Compute values
return Quaternion<Real>(x, y, z, w);
}
template <typename Real>
inline
Quaternion<Real>
Quaternion<Real>::FromEulerRad (const Vector3<Real>& rotationRad)
{
return Quaternionf::FromEulerRad(rotationRad.x, rotationRad.y, rotationRad.z);
}
// --------------------------------------------------------------------------
// Quaternion::toEulerAngles
//
// Setup the Euler angles, given an object->inertial rotation quaternion.
// Returned x,y,z are in radians.
// --------------------------------------------------------------------------
/**
Theory:
http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/
Examples:
http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/steps/index.htm
// X-Axis -> Bank - Pitch
bank = atan2(2*qx*qw-2*qy*qz , 1 - 2*qx2 - 2*qz2)
// Y-Axis -> Heading - Yaw
heading = atan2(2*qy*qw-2*qx*qz , 1 - 2*qy2 - 2*qz2)
// Z-Axis -> Attitude - Roll
attitude = asin(2*qx*qy + 2*qz*qw)
*/
template <typename Real>
inline
Vector3<Real>
Quaternion<Real>::EulerRad (const Quaternion<Real>& q)
{
const Real sqx = q.x * q.x;
const Real sqy = q.y * q.y;
const Real sqz = q.z * q.z;
const Real pole = q.GimbalPole();
Real yaw = 0.0;
Real pitch = 0.0;
const Real roll = Asin(Clamp(2.0*(q.x * q.y + q.z * q.w), -1.0, 1.0));
if ((0.5 - DC_EPSILON) < pole)
{
yaw = 2 * Atan2(q.x, q.w);
return Vector3<Real> (pitch, yaw, roll);
}
else if (pole < (DC_EPSILON - 0.5))
{
yaw = -2 * Atan2(q.x, q.w);
return Vector3<Real> (pitch, yaw, roll);
}
yaw = Atan2(2.0*(q.y * q.w - q.x * q.z), 1.0 - 2.0 * (sqy + sqz));
pitch = Atan2(2.0*(q.x * q.w - q.y * q.z), 1.0 - 2.0 * (sqx + sqz));
return Vector3<Real> (pitch, yaw, roll);
}
template <typename Real>
inline const Real
Quaternion<Real>::GimbalPole() const
{
return x*y + z*w;
//return t > 0.5 ? 1.0 : (t < -0.5 ? -1.0 : 0.0);
}
template <typename Real>
inline const Real
Quaternion<Real>::RollRad() const
{
const Real pole = GimbalPole();
if (pole == 0.0)
return Atan2(2.0*(w*z + y*x), 1.0 - 2.0 * (x*x + z*z));
return (float)pole * 2.0 * atan2(y, w);
}
template <typename Real>
inline const Real
Quaternion<Real>::YawRad() const
{
if (GimbalPole() == 0.0)
return Atan2(2.0*(y*w + x*z), 1.0 - 2.0*(y*y + x*x));
return 0.0;
}
template <typename Real>
inline const Real
Quaternion<Real>::PitchRad() const
{
const Real pole = GimbalPole();
if (pole == 0.0)
return Asin(Clamp(2.0*(w*x - z*y), -1.0, 1.0));
return pole * math::DC_PI_OVER_2;
}
// --------------------------------------------------------------------------
// Quaternion::getRotationAngle
//
// Return the rotation angle theta (in radians).
// --------------------------------------------------------------------------
template <typename Real>
inline const Real
Quaternion<Real>::RotationAngle () const
{
// Compute the half angle. Remember that w = cos(theta / 2)
Real thetaOver2 = safeAcos (w);
// Return the rotation angle
return thetaOver2 * 2.0;
}
// --------------------------------------------------------------------------
// Quaternion::getRotationAxis
//
// Return the rotation axis.
// --------------------------------------------------------------------------
template <typename Real>
inline Vector3<Real>
Quaternion<Real>::RotationAxis () const
{
// Compute sin^2(theta/2). Remember that w = cos(theta/2),
// and sin^2(x) + cos^2(x) = 1
Real sinThetaOver2Sq = 1.0 - (w * w);
// Protect against numerical imprecision
if (sinThetaOver2Sq <= 0.0)
{
// Identity quaternion, or numerical imprecision. Just
// return any valid vector, since it doesn't matter
return Vector3<Real> (1.0, 0.0, 0.0);
}
// Compute 1 / sin(theta/2)
Real oneOverSinThetaOver2 = 1.0 / std::sqrt (sinThetaOver2Sq);
// Return axis of rotation
return Vector3<Real> (x * oneOverSinThetaOver2,
y * oneOverSinThetaOver2,
z * oneOverSinThetaOver2);
}
// --------------------------------------------------------------------------
// Quaternion operators
//
// Operator overloading for basic quaternion operations.
// --------------------------------------------------------------------------
template <typename Real>
inline
const bool
Quaternion<Real>::operator== (const Quaternion<Real> &q) const
{
return Approximately(x, q.x) && Approximately(y, q.y) && Approximately(z, q.z) && Approximately(w, q.w);
}
template <typename Real>
inline
const bool
Quaternion<Real>::operator!= (const Quaternion<Real> &q) const
{
return (!Approximately(x, q.x) || !Approximately(y, q.y) || !Approximately(z, q.z) || !Approximately(w, q.w));
}
template <typename Real>
inline Quaternion<Real>
Quaternion<Real>::operator+ (const Quaternion<Real> &q) const
{
return Quaternion<Real> (x + q.x, y + q.y, z + q.z, w + q.w);
}
template <typename Real>
inline Quaternion<Real> &
Quaternion<Real>::operator+= (const Quaternion<Real> &q)
{
x += q.x; y += q.y; z += q.z; w += q.w;
return *this;
}
template <typename Real>
inline Quaternion<Real>
Quaternion<Real>::operator- (const Quaternion<Real> &q) const
{
return Quaternion<Real> (x - q.x, y - q.y, z - q.z, w - q.w);
}
template <typename Real>
inline Quaternion<Real> &
Quaternion<Real>::operator-= (const Quaternion<Real> &q)
{
x -= q.x;
y -= q.y;
z -= q.z;
w -= q.w;
return *this;
}
// Quaternion multiplication. The order of multiplication, from left
// to right, corresponds to the order of concatenated rotations.
// NOTE: Quaternion multiplication is NOT commutative, p * q != q * p
template <typename Real>
inline Quaternion<Real>
Quaternion<Real>::operator* (const Quaternion<Real> &q) const
{
// We use the Grassman product formula:
// pq = <w1w2 - dot(v1, v2), w1v2 + w2v1 + cross(v1, v2)>
return Quaternion<Real> ((x * q.w) + (w * q.x) + (y * q.z) - (z * q.y),
(y * q.w) + (w * q.y) + (z * q.x) - (x * q.z),
(z * q.w) + (w * q.z) + (x * q.y) - (y * q.x),
(w * q.w) - (x * q.x) - (y * q.y) - (z * q.z));
}
template <typename Real>
inline Quaternion<Real> &
Quaternion<Real>::operator*= (const Quaternion<Real> &q)
{
x = (x * q.w) + (w * q.x) + (y * q.z) - (z * q.y);
y = (y * q.w) + (w * q.y) + (z * q.x) - (x * q.z);
z = (z * q.w) + (w * q.z) + (x * q.y) - (y * q.x);
w = (w * q.w) - (x * q.x) - (y * q.y) - (z * q.z);
return *this;
}
template <typename Real>
inline Quaternion<Real>
Quaternion<Real>::operator* (const Vector3<Real> &v) const
{
// q * v = q * p where p = <0,v>
// Thus, we can simplify the operations.
return Quaternion<Real> ( (w * v.x) + (y * v.z) - (z * v.y),
(w * v.y) + (z * v.x) - (x * v.z),
(w * v.z) + (x * v.y) - (y * v.x),
- (x * v.x) - (y * v.y) - (z * v.z));
}
template <typename Real>
inline Quaternion<Real> &
Quaternion<Real>::operator*= (const Vector3<Real> &v)
{
x = (w * v.x) + (y * v.z) - (z * v.y);
y = (w * v.y) + (z * v.x) - (x * v.z);
z = (w * v.z) + (x * v.y) - (y * v.x);
w = - (x * v.x) - (y * v.y) - (z * v.z);
return *this;
}
template <typename Real>
inline Quaternion<Real>
Quaternion<Real>::operator* (Real k) const
{
return Quaternion<Real> (x * k, y * k, z * k, w * k);
}
template <typename Real>
inline Quaternion<Real> &
Quaternion<Real>::operator*= (Real k)
{
w *= k; x *= k; y *= k; z *= k;
return *this;
}
template <typename Real>
inline Quaternion<Real>
Quaternion<Real>::operator/ (Real k) const
{
Real oneOverK = 1.0 / k;
return Quaternion<Real> (x * oneOverK, y * oneOverK, z * oneOverK, w * oneOverK);
}
template <typename Real>
inline Quaternion<Real> &
Quaternion<Real>::operator/= (Real k)
{
Real oneOverK = 1.0 / k;
w *= oneOverK; x *= oneOverK; y *= oneOverK; z *= oneOverK;
return *this;
}
// Quaternion conjugate
template <typename Real>
inline Quaternion<Real>
Quaternion<Real>::operator~ () const
{
return Quaternion<Real> (-x, -y, -z, w);
}
// Quaternion negation
template <typename Real>
inline Quaternion<Real>
Quaternion<Real>::operator- () const
{
return Quaternion<Real> (-x, -y, -z, -w);
}
// --------------------------------------------------------------------------
//
// Nonmember Quaternion functions
//
// --------------------------------------------------------------------------
// Scalar on left multiplication
template <typename Real>
inline Quaternion<Real>
operator* (Real k, const Quaternion<Real> &q)
{
return Quaternion<Real> (q.x * k, q.y * k, q.z * k, q.w * k);
}
// Quaternion dot product
template <typename Real>
inline Real
DotProduct (const Quaternion<Real> &a, const Quaternion<Real> &b)
{
return ((a.x * b.x) + (a.y * b.y) + (a.z * b.z) + (a.w * b.w));
}
// Compute the quaternion conjugate. This is the quaternian
// with the opposite rotation as the original quaternion.
template <typename Real>
inline Quaternion<Real>
Conjugate (const Quaternion<Real> &q)
{
return Quaternion<Real> (-q.x, -q.y, -q.z, q.w);
}
// Compute the inverse quaternion (for unit quaternion only).
template <typename Real>
inline Quaternion<Real>
Inverse (const Quaternion<Real> &q)
{
// Assume this is a unit quaternion! No check for this!
Quaternion<Real> res (-q.x, -q.y, -q.z, q.w);
res.Normalize ();
return res;
}
// --------------------------------------------------------------------------
// RotationQuaternion
//
// Setup the quaternion to rotate about the specified axis. theta must
// be in radians.
// --------------------------------------------------------------------------
template <typename Real>
inline Quaternion<Real>
RotationQuaternion (const Vector3<Real> &axis, Real theta)
{
Quaternion<Real> res;
// The axis of rotation must be normalized
assert (std::fabs (DotProduct (axis, axis) - 1.0) < 0.001);
// Compute the half angle and its sin
Real thetaOver2 = theta * 0.5;
Real sinThetaOver2 = std::sin (thetaOver2);
// Set the values
res.x = axis.x * sinThetaOver2;
res.y = axis.y * sinThetaOver2;
res.z = axis.z * sinThetaOver2;
res.w = std::cos (thetaOver2);
return res;
}
// --------------------------------------------------------------------------
// Log
//
// Unit quaternion logarithm. log(q) = log(cos(theta) + n*sin(theta))
// --------------------------------------------------------------------------
template <typename Real>
inline Quaternion<Real>
Log (const Quaternion<Real> &q)
{
Quaternion<Real> res;
res.w = 0.0;
if (std::fabs (q.w) < 1.0)
{
Real theta = std::acos (q.w);
Real sintheta = std::sin (theta);
if (std::fabs (sintheta) > 0.00001)
{
Real thetaOverSinTheta = theta / sintheta;
res.x = q.x * thetaOverSinTheta;
res.y = q.y * thetaOverSinTheta;
res.z = q.z * thetaOverSinTheta;
return res;
}
}
res.x = q.x;
res.y = q.y;
res.z = q.z;
return res;
}
// --------------------------------------------------------------------------
// Exp
//
// Quaternion exponential.
// --------------------------------------------------------------------------
template <typename Real>
inline Quaternion<Real>
Exp (const Quaternion<Real> &q)
{
Real theta = std::sqrt (DotProduct (q, q));
Real sintheta = std::sin (theta);
Quaternion<Real> res;
res.w = std::cos (theta);
if (std::fabs (sintheta) > 0.00001)
{
Real sinThetaOverTheta = sintheta / theta;
res.x = q.x * sinThetaOverTheta;
res.y = q.y * sinThetaOverTheta;
res.z = q.z * sinThetaOverTheta;
}
else
{
res.x = q.x;
res.y = q.y;
res.z = q.z;
}
return res;
}
// --------------------------------------------------------------------------
// Pow
//
// Quaternion exponentiation.
// --------------------------------------------------------------------------
template <typename Real>
inline Quaternion<Real>
Pow (const Quaternion<Real> &q, Real exponent)
{
// Check for the case of an identity quaternion.
// This will protect against divide by zero
if (std::fabs (q.w) > 0.9999)
return q;
// Extract the half angle alpha (alpha = theta/2)
Real alpha = std::acos (q.w);
// Compute new alpha value
Real newAlpha = alpha * exponent;
// Compute new quaternion
Vector3<Real> n (q.x, q.y, q.z);
n *= std::sin (newAlpha) / std::sin (alpha);
return Quaternion<Real> (n, std::cos (newAlpha));
}
// --------------------------------------------------------------------------
// Slerp
//
// Spherical linear interpolation.
// --------------------------------------------------------------------------
template <typename Real>
inline Quaternion<Real>
Slerp (const Quaternion<Real> &q0, const Quaternion<Real> &q1, Real t)
{
// Check for out-of range parameter and return edge points if so
if (t <= 0.0) return q0;
if (t >= 1.0) return q1;
// Compute "cosine of angle between quaternions" using dot product
Real cosOmega = DotProduct (q0, q1);
// If negative dot, use -q1. Two quaternions q and -q
// represent the same rotation, but may produce
// different slerp. We chose q or -q to rotate using
// the acute angle.
Real q1w = q1.w;
Real q1x = q1.x;
Real q1y = q1.y;
Real q1z = q1.z;
if (cosOmega < 0.0)
{
q1w = -q1w;
q1x = -q1x;
q1y = -q1y;
q1z = -q1z;
cosOmega = -cosOmega;
}
// We should have two unit quaternions, so dot should be <= 1.0
assert (cosOmega < 1.1);
// Compute interpolation fraction, checking for quaternions
// almost exactly the same
Real k0, k1;
if (cosOmega > 0.9999)
{
// Very close - just use linear interpolation,
// which will protect againt a divide by zero
k0 = 1.0 - t;
k1 = t;
}
else
{
// Compute the sin of the angle using the
// trig identity sin^2(omega) + cos^2(omega) = 1
Real sinOmega = std::sqrt (1.0 - (cosOmega * cosOmega));
// Compute the angle from its sin and cosine
Real omega = std::atan2 (sinOmega, cosOmega);
// Compute inverse of denominator, so we only have
// to divide once
Real oneOverSinOmega = 1.0 / sinOmega;
// Compute interpolation parameters
k0 = std::sin ((1.0 - t) * omega) * oneOverSinOmega;
k1 = std::sin (t * omega) * oneOverSinOmega;
}
// Interpolate and return new quaternion
return Quaternion<Real> ((k0 * q0.x) + (k1 * q1x),
(k0 * q0.y) + (k1 * q1y),
(k0 * q0.z) + (k1 * q1z),
(k0 * q0.w) + (k1 * q1w));
}
// --------------------------------------------------------------------------
// Squad
//
// Spherical cubic interpolation.
// squad = slerp (slerp (q0, q1, t), slerp (qa, qb, t), 2t(1 - t)).
// --------------------------------------------------------------------------
template <typename Real>
inline Quaternion<Real>
Squad (const Quaternion<Real> &q0, const Quaternion<Real> &qa,
const Quaternion<Real> &qb, const Quaternion<Real> &q1, Real t)
{
Real slerpt = 2.0 * t * (1.0 - t);
Quaternion<Real> slerpq0 = Slerp (q0, q1, t);
Quaternion<Real> slerpq1 = Slerp (qa, qb, t);
return Slerp (slerpq0, slerpq1, slerpt);
}
// --------------------------------------------------------------------------
// Intermediate
//
// Compute intermediate quaternions for building spline segments.
// --------------------------------------------------------------------------
template <typename Real>
inline void
Intermediate (const Quaternion<Real> &qprev, const Quaternion<Real> &qcurr,
const Quaternion<Real> &qnext, Quaternion<Real> &qa, Quaternion<Real> &qb)
{
// We should have unit quaternions
assert (DotProduct (qprev, qprev) <= 1.0001);
assert (DotProduct (qcurr, qcurr) <= 1.0001);
Quaternion<Real> invprev = Conjugate (qprev);
Quaternion<Real> invcurr = Conjugate (qcurr);
Quaternion<Real> p0 = invprev * qcurr;
Quaternion<Real> p1 = invcurr * qnext;
Quaternion<Real> arg = (Log (p0) - Log (p1)) * 0.25;
qa = qcurr * Exp ( arg);
qb = qcurr * Exp (-arg);
}
}
}
#endif
<file_sep>/project/include/math/vector.h
//
// Header.h
// bitthemall
//
// Created by <NAME> on 17/07/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#ifndef bitthemall_Header_h
#define bitthemall_Header_h
#include "vector2.h"
#include "vector3.h"
#include "vector4.h"
#endif
<file_sep>/project/include/math/vector3.inl
/////////////////////////////////////////////////////////////////////////////
//
// class Vector3<Real> implementation.
//
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//
// Static operations
//
//////////////////////////////////////////////////////////////////////////////
template <typename Real>
inline
const Vector3<Real>
Vector3<Real>::PositiveEulerAngles(const Vector3<Real>& euler)
{
//return Vector3<Real>(remainder(euler.x + 360.0, 360.0), remainder(euler.y + 360.0, 360.0), remainder(euler.z + 360.0, 360.0));
Vector3<Real> positiveEuler;
positiveEuler.x = euler.x;
if (positiveEuler.x < 0.0)
positiveEuler.x += 360.0;
positiveEuler.y = euler.y;
if (positiveEuler.y < 0.0)
positiveEuler.y += 360.0;
positiveEuler.z = euler.z;
if (positiveEuler.z < 0.0)
positiveEuler.z += 360.0;
return positiveEuler;
}
// Decodifica las normales en forma polar y devuelve un vector normal
template <typename Real>
inline
Vector3<Real>
Vector3<Real>::FromPolarAngles(Real zenith, Real azimuth)
{
Real lat = zenith * (DC_PI2)/255.0;
Real lng = azimuth * (DC_PI2)/255.0;
return Vector3<Real>(std::cos(lng) * std::sin(lat), std::sin(lng) * std::sin(lat), std::cos(lat));
}
// Devuelve el vector unidad que apunta en la orientacion pasada como argumento, en el plano X,Y
template <typename Real>
inline
Vector3<Real>
Vector3<Real>::UnitVectorFromOrientation(Real degrees)
{
const float rads = DegToRad(degrees);
return Vector3<Real>(std::sin(rads), -std::cos(rads), 0);
}
// Vector3 dot product
template <typename Real>
inline
Real
Vector3<Real>::DotProduct (const Vector3<Real> &a, const Vector3<Real> &b)
{
return ((a.x * b.x) + (a.y * b.y) + (a.z * b.z));
}
// Vector3 cross product
template <typename Real>
inline
Vector3<Real>
Vector3<Real>::CrossProduct (const Vector3<Real> &a, const Vector3<Real> &b)
{
return Vector3<Real> ((a.y * b.z) - (a.z * b.y),
(a.z * b.x) - (a.x * b.z),
(a.x * b.y) - (a.y * b.x));
}
// Compute normal plane given three points
template <typename Real>
inline
Vector3<Real>
Vector3<Real>::ComputeNormal (const Vector3<Real> &p1, const Vector3<Real> &p2, const Vector3<Real> &p3)
{
Vector3<Real> vec1 (p1 - p2);
Vector3<Real> vec2 (p1 - p3);
Vector3<Real> result (CrossProduct (vec1, vec2));
result.Normalize ();
return result;
}
// Compute distance between two points
template <typename Real>
inline
Real
Vector3<Real>::Distance (const Vector3<Real>& from, const Vector3<Real>& to)
{
Real dx = to.x - from.x;
Real dy = to.y - from.y;
Real dz = to.z - from.z;
return std::sqrt ((dx * dx) + (dy * dy) + (dz * dz));
}
// Compute squared distance between two points.
// Useful when comparing distances, since we don't need
// to square the result.
template <typename Real>
inline
Real
Vector3<Real>::DistanceSquared (const Vector3<Real>& from, const Vector3<Real>& to)
{
Real dx = to.x - from.x;
Real dy = to.y - from.y;
Real dz = to.z - from.z;
return ((dx * dx) + (dy * dy) + (dz * dz));
}
/**
* Interpolacion lineal de vectores en funcion de un parametro
* porcentual t.
* Siendo t el porcentaje de interpolacion entre un vector y el otro.
* Si t = 0, no hay interpolacion, si t = 1 la interpolacion seria
* el vector final
*/
template <typename Real>
inline
Vector3<Real>
Vector3<Real>::Lerp(const Vector3<Real>& from, const Vector3<Real>& to, const Real t)
{
return (from + Clamp<float>(t, 0.0f, 1.0f)*(to - from));
}
//////////////////////////////////////////////////////////////////////////////
//
// Getters / Setters
//
//////////////////////////////////////////////////////////////////////////////
template <typename Real>
inline
void Vector3<Real>::SetCoords(const Real x, const Real y, const Real z)
{
this->x = x; this->y = y; this->z = z;
}
// --------------------------------------------------------------------------
// Vector3::IsZero
//
// Return true if is zero vector.
// --------------------------------------------------------------------------
template <typename Real>
inline
const bool
Vector3<Real>::IsZero () const
{
return (x == 0.0) && (y == 0.0) && (z == 0.0);
}
template <typename Real>
inline
const bool
Vector3<Real>::IsNearZero() const
{
return Approximately(x, 0.0) && Approximately(y, 0.0) && Approximately(z, 0.0);
}
template <typename Real>
inline
const bool
Vector3<Real>::IsNearZero(const Real epsilon) const
{
return Approximately(x, 0.0, epsilon) && Approximately(y, 0.0, epsilon) && Approximately(z, 0.0, epsilon);
}
template <typename Real>
inline
const bool
Vector3<Real>::IsApprox(const Vector3<Real>& v) const
{
return Approximately(x, v.x) && Approximately(y, v.y) && Approximately(z, v.z);
}
template <typename Real>
inline
const bool
Vector3<Real>::IsApprox(const Vector3<Real>& v, const Real epsilon) const
{
return Approximately(x, v.x, epsilon) && Approximately(y, v.y, epsilon) && Approximately(z, v.z, epsilon);
}
// --------------------------------------------------------------------------
// Vector3::Length
//
// Gets the vector magnitude
// --------------------------------------------------------------------------
template <typename Real>
inline
const Real
Vector3<Real>::Length() const
{
return std::sqrt((x * x) + (y * y) + (z * z));
}
// --------------------------------------------------------------------------
// Vector3::normalize
//
// Set vector length to 1.
// --------------------------------------------------------------------------
template <typename Real>
inline
void
Vector3<Real>::Normalize()
{
Real magSq = (x * x) + (y * y) + (z * z);
if (magSq > 0.0)
{
Real oneOverMag = 1.0 / std::sqrt (magSq);
x *= oneOverMag;
y *= oneOverMag;
z *= oneOverMag;
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Vector transformations
//
// Operator overloading for basic vector operations.
//
//////////////////////////////////////////////////////////////////////////////
// Vector comparison
template <typename Real>
inline
const bool
Vector3<Real>::operator== (const Vector3<Real> &v) const
{
return Approximately(x, v.x) && Approximately(y, v.y) && Approximately(z, v.z);
}
template <typename Real>
inline
const bool
Vector3<Real>::operator!= (const Vector3<Real> &v) const
{
return (!Approximately(x, v.x) || !Approximately(y, v.y) || !Approximately(z, v.z));
}
// Vector negation
template <typename Real>
inline
Vector3<Real>
Vector3<Real>::operator- () const
{
return Vector3<Real> (-x, -y, -z);
}
template <typename Real>
inline
Vector3<Real>
Vector3<Real>::operator+ (const Vector3<Real> &v) const
{
return Vector3<Real> (x + v.x, y + v.y, z + v.z);
}
template <typename Real>
inline
Vector3<Real>
Vector3<Real>::operator- (const Vector3<Real> &v) const
{
return Vector3<Real> (x - v.x, y - v.y, z - v.z);
}
template <typename Real>
inline
Vector3<Real>
Vector3<Real>::operator* (const Vector3<Real>& v) const
{
return Vector3<Real>(x * v.x, y * v.y, z * v.z);
}
template <typename Real>
inline
Vector3<Real>
Vector3<Real>::operator^ (const Vector3<Real>& v) const
{
return Vector3<Real> ((y * v.z) - (z * v.y),
(z * v.x) - (x * v.z),
(x * v.y) - (y * v.x));
}
template <typename Real>
inline
Vector3<Real>
Vector3<Real>::operator* (const Real s) const
{
return Vector3<Real> (x * s, y * s, z * s);
}
template <typename Real>
inline
Vector3<Real>
Vector3<Real>::operator/ (const Real s) const
{
Real oneOverS = 1.0 / s; // Note: no check for divide by zero
return Vector3<Real> (x * oneOverS, y * oneOverS, z * oneOverS);
}
// Combined assignment operators to conform to C notation convention
template <typename Real>
inline
Vector3<Real>&
Vector3<Real>::operator+= (const Vector3<Real> &v)
{
x += v.x;
y += v.y;
z += v.z;
return *this;
}
template <typename Real>
inline
Vector3<Real>&
Vector3<Real>::operator-= (const Vector3<Real> &v)
{
x -= v.x;
y -= v.y;
z -= v.z;
return *this;
}
template <typename Real>
inline
Vector3<Real>&
Vector3<Real>::operator*= (const Vector3<Real> &v)
{
x *= v.x;
y *= v.y;
z *= v.z;
return *this;
}
template <typename Real>
inline
Vector3<Real>&
Vector3<Real>::operator^= (const Vector3<Real> &v)
{
// We can't modify the member atributes because with this operation we modify them and the result is affected
*this = *this ^ v;
return *this;
}
template <typename Real>
inline
Vector3<Real>&
Vector3<Real>::operator*= (const Real s)
{
x *= s;
y *= s;
z *= s;
return *this;
}
template <typename Real>
inline
Vector3<Real>&
Vector3<Real>::operator/= (const Real s)
{
Real oneOverS = 1.0 / s; // Note: no check for divide by zero!
x *= oneOverS;
y *= oneOverS ;
z *= oneOverS;
return *this;
}
//////////////////////////////////////////////////////////////////////////////
//
// Methods
//
//////////////////////////////////////////////////////////////////////////////
/**
* Situa el vector en el vertice más alejado
* de la hipotenusa de un triangulo rectangulo
* con catetos x = cos(degrees) y z = sin (degrees)
*
* Eje Z * (vector resultado)
* ^ /|
* | / |
* | / |
* | / |
* | / | sin(degrees)
* | / |
* | / |
* | / ] degrees |
* (origen) *----------------|-----> Eje X
* cos(degrees)
*/
template <typename Real>
inline void
Vector3<Real>::RotateAndMoveXZ(const Real degrees, const Real distance)
{
const float rads = DegToRad(degrees);
x += std::cos(rads) * distance;
z -= std::sin(rads) * distance;
}
template <typename Real>
inline void
Vector3<Real>::RotateAndMoveXY(const Real degrees, const Real distance)
{
const float rads = DegToRad(degrees);
x += std::cos(rads) * distance;
y -= std::sin(rads) * distance;
}
template <typename Real>
inline void
Vector3<Real>::RotateAndMoveYZ(const Real degrees, const Real distance)
{
const float rads = DegToRad(degrees);
y += std::cos(rads) * distance;
z -= std::sin(rads) * distance;
}
//////////////////////////////////////////////////////////////////////////////
//
// Nonmember methods
//
//////////////////////////////////////////////////////////////////////////////
// Scalar on the left multiplication, for symmetry
template <typename Real>
inline
Vector3<Real>
operator* (const Real k, const Vector3<Real>& v)
{
return Vector3<Real> (k * v.x, k * v.y, k * v.z);
}
<file_sep>/project/include/math/vector4.inl
//
// vector4.inl.h
// bitthemall
//
// Created by <NAME> on 17/07/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
// Decide if a plane is facing a point
template <typename Real>
inline bool
IsFacingTo (const Vector4<Real> plane, const Vector3<Real> &v)
{
return ((plane.x*v.x) + (plane.y*v.y) + (plane.z*v.z) + (plane.w))>0;
}
// Decide if a plane is facing a sphere
template <typename Real>
inline bool
IsFacingTo (const Vector4<Real> plane, const Vector3<Real> &v, Real radius)
{
return ((plane.x*v.x) + (plane.y*v.y) + (plane.z*v.z) + (plane.w))>-radius;
}
<file_sep>/project/include/math/vector4.h
//
// vector4.h
//
// Based upon Mathlib.h -- Copyright (c) 2005-2006 <NAME>
//
// This code is licenced under the MIT license.
//
// Modified by <NAME> on 17/07/12.
//
#ifndef bitthemall_vector4_h
#define bitthemall_vector4_h
#include "vector3.h"
#include "math.h"
/////////////////////////////////////////////////////////////////////////////
//
// class Vector4<Real> - A simple 4D vector class.
//
/////////////////////////////////////////////////////////////////////////////
namespace dc
{
namespace math
{
template <typename Real>
class Vector4
{
public:
static Vector4<Real> Red() { return Vector4<Real>(1.0, 0.0, 0.0, 1.0); }
static Vector4<Real> Green() { return Vector4<Real>(0.0, 1.0, 0.0, 1.0); }
static Vector4<Real> Blue() { return Vector4<Real>(0.0, 0.0, 1.0, 1.0); }
static Vector4<Real> White() { return Vector4<Real>(1.0, 1.0, 1.0, 1.0); }
static Vector4<Real> Black() { return Vector4<Real>(0.0, 0.0, 0.0, 1.0); }
public:
Vector4() : x (0), y (0), z(0), w(0) {}
Vector4(Real x, Real y, Real z, Real w)
: x(x), y(y), z(z), w(w) {}
// Copy constructor
Vector4(const Vector4<Real>& copy): x(copy.x), y(copy.y), z(copy.z), w(copy.w) {}
public:
// Vector operations
// Vector comparison
const bool operator== (const Vector4<Real>& v) const;
const bool operator!= (const Vector4<Real>& v) const;
// Accessor. This allows to use the vector object
// like an array of Real. For example:
// Vector3<float> v (...);
// float f = v[1]; // access to _y
operator const Real *() const { return vec; }
public:
void Normalize ();
union
{
struct
{
Real x, y, z, w;
};
struct
{
Real r, g, b, a;
};
Real vec[4];
};
};
// Predefined Vector3 types
typedef Vector4<float> Vector4f;
typedef Vector4<float> Planef;
typedef Vector4<float> ColorRGBAf;
typedef Vector4<double> Vector4d;
typedef Vector4<double> Planed;
typedef Vector4<double> ColorRGBAd;
//
// Nonmember Vector4 functions
//
template <typename Real>
bool IsFacingTo (const Vector4<Real> plane, const Vector3<Real> &v);
template <typename Real>
bool IsFacingTo (const Vector4<Real> plane, const Vector3<Real> &v, Real radius);
/////////////////////////////////////////////////////////////////////////////
//
// class Vector4<Real> implementation.
//
/////////////////////////////////////////////////////////////////////////////
// --------------------------------------------------------------------------
// Vector4 operators
//
// Operator overloading for basic vector operations.
// --------------------------------------------------------------------------
// Vector comparison
template <typename Real>
inline
const bool
Vector4<Real>::operator== (const Vector4<Real> &v) const
{
return Approximately(x, v.x) && Approximately(y, v.y) && Approximately(z, v.z) && Approximately(w, v.w);
}
template <typename Real>
inline
const bool
Vector4<Real>::operator!= (const Vector4<Real> &v) const
{
return (!Approximately(x, v.x) || !Approximately(y, v.y) || !Approximately(z, v.z) || !Approximately(w, v.w));
}
// Decide if a plane is facing a point
template <typename Real>
inline
bool
IsFacingTo (const Vector4<Real> plane, const Vector3<Real> &v)
{
return ((plane.x*v.x) + (plane.y*v.y) + (plane.z*v.z) + (plane.w))>0;
}
// Decide if a plane is facing a sphere
template <typename Real>
inline
bool
IsFacingTo (const Vector4<Real> plane, const Vector3<Real> &v, Real radius)
{
return ((plane.x*v.x) + (plane.y*v.y) + (plane.z*v.z) + (plane.w))>-radius;
}
}
}
#endif
<file_sep>/project/include/math/vector3.h
//
// vector3.h
//
// Based upon Mathlib.h -- Copyright (c) 2005-2006 <NAME>
//
// This code is licenced under the MIT license.
//
// Modified by <NAME> on 14/07/12.
//
#ifndef VECTOR3_H
#define VECTOR3_H
#include "dcmath.h"
#include <stdio.h>
namespace dc
{
namespace math
{
//////////////////////////////////////////////////
//
// class Vector3<Real> - A simple 3D vector class.
//
//////////////////////////////////////////////////
template <typename Real>
class Vector3
{
public:
// Basic Vector3 creation ops
static const Vector3<Real> Zero() { return Vector3<Real>(); }
static const Vector3<Real> One() { return Vector3<Real>(1, 1, 1); }
static const Vector3<Real> Up() { return Vector3<Real>(0, 1, 0); }
static const Vector3<Real> Down() { return Vector3<Real>(0, -1, 0); }
static const Vector3<Real> Right() { return Vector3<Real>(1, 0, 0); }
static const Vector3<Real> Left() { return Vector3<Real>(-1, 0, 0); }
static const Vector3<Real> Back() { return Vector3<Real>(0, 0, 1); }
static const Vector3<Real> Front() { return Vector3<Real>(0, 0, -1); }
// Basic Vector3 Colors
static Vector3<Real> Red() { return Vector3<Real>(1.0, 0.0, 0.0); }
static Vector3<Real> Green() { return Vector3<Real>(0.0, 1.0, 0.0); }
static Vector3<Real> Blue() { return Vector3<Real>(0.0, 0.0, 1.0); }
static Vector3<Real> White() { return Vector3<Real>(1.0, 1.0, 1.0); }
static Vector3<Real> Black() { return Vector3<Real>(0.0, 0.0, 0.0); }
static const Vector3<Real> PositiveEulerAngles(const Vector3<Real>& euler);
static Vector3<Real> FromPolarAngles(Real azimuth, Real zenith);
static Vector3<Real> UnitVectorFromOrientation(Real degrees);
static Real DotProduct (const Vector3<Real>& a, const Vector3<Real>& b);
static Vector3<Real> CrossProduct (const Vector3<Real>& a, const Vector3<Real>& b);
static Vector3<Real> ComputeNormal (const Vector3<Real>& p1, const Vector3<Real>& p2, const Vector3<Real>& p3);
static Real Distance (const Vector3<Real>& from, const Vector3<Real>& to);
static Real DistanceSquared (const Vector3<Real>& from, const Vector3<Real>& to);
static Vector3<Real> Lerp(const Vector3<Real>& from, const Vector3<Real>& to, const Real perc);
// Getters / Setters
public:
/*
Accessor. This allows to use the vector object
like an array of Real. For example:
Vector3<float> v (...);
float f = v[1]; // access to _y
*/
operator const Real *() const { return vec; }
void SetCoords(const Real x, const Real y, const Real z);
const bool IsZero () const;
const bool IsNearZero() const;
const bool IsNearZero(const Real epsilon) const;
const bool IsApprox(const Vector3<Real>& v) const;
const bool IsApprox(const Vector3<Real>& v, const Real epsilon) const;
const Real Length() const;
void Normalize ();
// Constructors
public:
Vector3 () : x(0), y(0), z(0) {}
Vector3 (const Real x, const Real y,const Real z = 0):x(x), y(y), z(z) {}
// Copy constructor
Vector3 (const Vector3<Real>& copy):x(copy.x), y(copy.y), z(copy.z) {}
// Vector operations
public:
// Vector comparison
const bool operator== (const Vector3<Real>& v) const;
const bool operator!= (const Vector3<Real>& v) const;
// Vector negation
Vector3<Real> operator- () const;
// Vector transformations
Vector3<Real> operator+ (const Vector3<Real>& v) const;
Vector3<Real> operator- (const Vector3<Real>& v) const;
Vector3<Real> operator* (const Vector3<Real>& v) const;
Vector3<Real> operator^ (const Vector3<Real>& v) const;
Vector3<Real> operator* (const Real s) const;
Vector3<Real> operator/ (const Real s) const;
// Combined assignment operators to conform to C notation convention
Vector3<Real>& operator+= (const Vector3<Real>& v);
Vector3<Real>& operator-= (const Vector3<Real>& v);
Vector3<Real>& operator*= (const Vector3<Real>& v);
Vector3<Real>& operator^= (const Vector3<Real>& v);
Vector3<Real>& operator*= (const Real s);
Vector3<Real>& operator/= (const Real s);
// Methods
public:
void RotateAndMoveXZ (Real degrees, Real distance);
void RotateAndMoveXY (Real degrees, Real distance);
void RotateAndMoveYZ (Real degrees, Real distance);
public:
// Member variables
union
{
struct
{
Real x, y, z;
};
struct
{
Real r, g, b;
};
Real vec[3];
};
};
// Predefined Vector3 types
typedef Vector3<float> Vector3f;
typedef Vector3<float> Position3f;
typedef Vector3<float> ColorRGBf;
typedef Vector3<double> Vector3d;
typedef Vector3<double> Position3d;
typedef Vector3<double> ColorRGBd;
//
// Nonmember Vector3 functions
//
inline void PrintVector(const math::Vector3f& v)
{
printf("(%f, %f, %f)\n", v.x, v.y, v.z);
}
template <typename Real>
Vector3<Real>
operator* (const Real k, const Vector3<Real>& v);
#include "vector3.inl"
}
}
#endif
<file_sep>/project/include/math/vector2.h
//
// vector2.h
//
// Based upon Mathlib.h -- Copyright (c) 2005-2006 <NAME>
//
// This code is licenced under the MIT license.
//
// Modified by <NAME> on 17/07/12.
//
#ifndef bitthemall_vector2_h
#define bitthemall_vector2_h
namespace dc
{
namespace math
{
/////////////////////////////////////////////////////////////////////////////
//
// class Vector2<Real> - A simple 2D vector class.
//
/////////////////////////////////////////////////////////////////////////////
template <typename Number>
class Vector2
{
// Static operations for class methods
public:
static const Vector2<Number> Zero();
static const Vector2<Number> One();
static const Vector2<Number> Up();
static const Vector2<Number> Down();
static const Vector2<Number> Left();
static const Vector2<Number> Right();
// Constructors
public:
Vector2() : x (0), y (0) {}
Vector2(Number x, Number y): x(x), y(y) {}
// Copy constructor
Vector2(const Vector2<Number>& copy): x(copy.x), y(copy.y) {}
// Accessors
public:
// Accessor. This allows to use the vector object
// like an array of Real. For example:
// Vector3<float> v (...);
// float f = v[1]; // access to _y
operator const Number *() const { return vec; }
// Methods
public:
// Vector comparison
const bool operator== (const Vector2<Number>& v) const;
const bool operator!= (const Vector2<Number>& v) const;
// Vector negation
Vector2<Number> operator- () const;
// Vector transformations
Vector2<Number> operator+ (const Vector2<Number>& v) const;
Vector2<Number> operator- (const Vector2<Number>& v) const;
Vector2<Number> operator* (const Vector2<Number>& v) const;
Vector2<Number> operator* (const Number s) const;
Vector2<Number> operator/ (const Number s) const;
// Combined assignment operators to conform to C notation convention
Vector2<Number>& operator+= (const Vector2<Number>& v);
Vector2<Number>& operator-= (const Vector2<Number>& v);
Vector2<Number>& operator*= (const Vector2<Number>& v);
Vector2<Number>& operator*= (const Number s);
Vector2<Number>& operator/= (const Number s);
public:
Vector2<Number>& Half() const;
Vector2<Number>& Double() const;
// Fields
public:
union
{
struct
{
Number x, y;
};
struct
{
Number u, v;
};
struct
{
Number width, height;
};
Number vec[2];
};
};
// Predefined Vector3 types
typedef Vector2<float> Vector2f;
typedef Vector2<float> UVf;
typedef Vector2<double> Vector2d;
typedef Vector2<double> UVd;
typedef Vector2<int> Vector2i;
#include "vector2.inl"
}
}
#endif
<file_sep>/project/include/math/matrix.inl
/////////////////////////////////////////////////////////////////////////////
//
// class Matrix4x4<Real> Matrix-builder functions
//
/////////////////////////////////////////////////////////////////////////////
// --------------------------------------------------------------------------
// Frustum
//
// Setup a frustum matrix given the left, right, bottom, top, near, and far
// values for the frustum boundaries.
// --------------------------------------------------------------------------
template <typename Real>
inline
Matrix4x4<Real>
Matrix4x4<Real>::Frustum (Real l, Real r, Real b, Real t, Real n, Real f)
{
assert (n >= 0.0);
assert (f >= 0.0);
Matrix4x4<Real> res;
Real nn = 2 * n;
Real width = r - l;
Real height = t - b;
Real depth = f - n;
res.m[0] = (nn) / width;
res.m[1] = 0.0;
res.m[2] = 0.0;
res.m[3] = 0.0;
res.m[4] = 0.0;
res.m[5] = (nn) / height;
res.m[6] = 0.0;
res.m[7] = 0.0;
res.m[8] = (r + l) / width;
res.m[9] = (t + b) / height;
res.m[10]= -(f + n) / depth;
res.m[11]= -1.0;
res.m[12]= 0.0;
res.m[13]= 0.0;
res.m[14]= -(nn * f) / depth;
res.m[15]= 0.0;
return res;
}
// --------------------------------------------------------------------------
// Orthographic
//
// Setup an orthographic Matrix4x4 given the left, right, bottom, top, near,
// and far values for the frustum boundaries.
// --------------------------------------------------------------------------
template <typename Real>
inline
Matrix4x4<Real>
Matrix4x4<Real>::Orthographic (Real l, Real r, Real b, Real t, Real n, Real f)
{
Matrix4x4<Real> res;
Real width = r - l;
Real height = t - b;
Real depth = f - n;
res.m[0] = 2.0 / width;
res.m[1] = 0.0;
res.m[2] = 0.0;
res.m[3] = 0.0;
res.m[4] = 0.0;
res.m[5] = 2.0 / height;
res.m[6] = 0.0;
res.m[7] = 0.0;
res.m[8] = 0.0;
res.m[9] = 0.0;
res.m[10]= -2.0 / depth;
res.m[11]= 0.0;
res.m[12]= -(r + l) / width;
res.m[13]= -(t + b) / height;
res.m[14]= -(f + n) / depth;
res.m[15]= 1.0;
return res;
}
// --------------------------------------------------------------------------
// Perspective
//
// Setup a perspective matrix given the field-of-view in the Y direction
// in degrees, the aspect ratio of Y/X, and near and far plane distances.
// --------------------------------------------------------------------------
template <typename Real>
inline
Matrix4x4<Real>
Matrix4x4<Real>::Perspective (Real fovY, Real aspect, Real near, Real far)
{
Matrix4x4<Real> res;
Real tan = std::tan (DegToRad(fovY * 0.5));
Real oneOverFNDist = 1.0 / (far - near);
res.m[0] = 1.0 / (tan * aspect);
res.m[1] = 0.0;
res.m[2] = 0.0;
res.m[3] = 0.0;
res.m[4] = 0.0;
res.m[5] = 1.0 / tan;
res.m[6] = 0.0;
res.m[7] = 0.0;
res.m[8] = 0.0;
res.m[9] = 0.0;
res.m[10]= -(far + near) * oneOverFNDist;
res.m[11]= -1.0;
res.m[12]= 0.0;
res.m[13]= 0.0;
res.m[14]= -(2 * far * near) * oneOverFNDist;
res.m[15]= 0.0;
return res;
}
// --------------------------------------------------------------------------
// LookAt (Right Handed)
// Setup a new matrix to perform a "Look At" transformation like a first
// person camera.
// --------------------------------------------------------------------------
template <typename Real>
inline
Matrix4x4<Real>
Matrix4x4<Real>::LookAt(const Vector3<Real>& eye, const Vector3<Real>& target, const Vector3<Real>& camUp)
{
Vector3<Real> forward((target - eye));
forward.Normalize();
Vector3<Real> right(Vector3<Real>::CrossProduct(forward, camUp));
right.Normalize();
Vector3<Real> up(Vector3<Real>::CrossProduct(right, forward));
up.Normalize();
Matrix4x4<Real> res;
res.m11 = right.x;
res.m21 = right.y;
res.m31 = right.z;
res.m12 = up.x;
res.m22 = up.y;
res.m32 = up.z;
res.m13 = -forward.x;
res.m23 = -forward.y;
res.m33 = -forward.z;
res.tx = -Vector3<Real>::DotProduct(right, eye);
res.ty = -Vector3<Real>::DotProduct(up, eye);
res.tz = Vector3<Real>::DotProduct(forward, eye);
return res;
}
// --------------------------------------------------------------------------
// Inverse
//
// Compute the inverse of a matrix. We use the classical adjoint divided
// by the determinant method.
//
// Caution! This function did not check if the matrix is singular
// --------------------------------------------------------------------------
template <typename Real>
inline
Matrix4x4<Real>
Matrix4x4<Real>::Inverse(const Matrix4x4<Real>& mat)
{
// Compute the determinant of the 3x3 portion
const Real det = mat.Determinant3x3 ();
// Compute one over the determinant, so we divide once and
// can *multiply* per element
const Real oneOverDet = 1.0 / det;
// Compute the 3x3 portion of the inverse, by
// dividing the adjoint by the determinant
Matrix4x4<Real> res;
res.m11 = ((mat.m22 * mat.m33) - (mat.m23 * mat.m32)) * oneOverDet;
res.m12 = ((mat.m13 * mat.m32) - (mat.m12 * mat.m33)) * oneOverDet;
res.m13 = ((mat.m12 * mat.m23) - (mat.m13 * mat.m22)) * oneOverDet;
res.m21 = ((mat.m23 * mat.m31) - (mat.m21 * mat.m33)) * oneOverDet;
res.m22 = ((mat.m11 * mat.m33) - (mat.m13 * mat.m31)) * oneOverDet;
res.m23 = ((mat.m13 * mat.m21) - (mat.m11 * mat.m23)) * oneOverDet;
res.m31 = ((mat.m21 * mat.m32) - (mat.m22 * mat.m31)) * oneOverDet;
res.m32 = ((mat.m12 * mat.m31) - (mat.m11 * mat.m32)) * oneOverDet;
res.m33 = ((mat.m11 * mat.m22) - (mat.m12 * mat.m21)) * oneOverDet;
// Compute the translation portion of the inverse
res.tx = -((mat.tx * res.m11) + (mat.ty * res.m21) + (mat.tz * res.m31));
res.ty = -((mat.tx * res.m12) + (mat.ty * res.m22) + (mat.tz * res.m32));
res.tz = -((mat.tx * res.m13) + (mat.ty * res.m23) + (mat.tz * res.m33));
// Return it.
return res;
}
template <typename Real>
inline
Matrix4x4<Real>
Matrix4x4<Real>::Identity()
{
Matrix4x4<Real> res;
res.m11 = 1.0; res.m12 = 0.0; res.m13 = 0.0; res.h14 = 0.0;
res.m21 = 0.0; res.m22 = 1.0; res.m23 = 0.0; res.h24 = 0.0;
res.m31 = 0.0; res.m32 = 0.0; res.m33 = 1.0; res.h34 = 0.0;
res.tx = 0.0; res.ty = 0.0; res.tz = 0.0; res.tw = 1.0;
return res;
}
/////////////////////////////////////////////////////////////////////////////
//
// class Matrix4x4<Real> member functions implementation.
//
/////////////////////////////////////////////////////////////////////////////
template <typename Real>
inline
Quaternion<Real> Matrix4x4<Real>::Rotation() const
{
return Quaternion<Real>(*this);
}
// --------------------------------------------------------------------------
// EulerAngles
//
// Setup the euler angles in radians, given a rotation matrix. The rotation
// matrix could have been obtained from euler angles given the expression:
// M = Y * X * Z
// where X, Y and Z are rotation matrices about X, Y and Z axes.
// This is the "opposite" of the fromEulerAngles function.
// --------------------------------------------------------------------------
template <typename Real>
inline
Vector3<Real>
Matrix4x4<Real>::EulerAngles() const
{
float bank, heading, attitude;
if(0.998 < m21)
{
bank = 0;
heading = std::atan2( m13, m33);
attitude = DC_PI_OVER_2;
return Vector3<Real>(bank, heading, attitude);
}
if(m21 < -0.998)
{
bank = 0;
heading = std::atan2( m13, m33);
attitude = -DC_PI_OVER_2;
return Vector3<Real>(bank, heading, attitude);
}
bank = std::atan2( -m23, m22);
heading = std::atan2( -m31, m11);
attitude = std::asin ( m21);
return Vector3<Real>(bank, heading, attitude);
}
// --------------------------------------------------------------------------
// IsSingular
//
// If the determinant of the 3x3 matrix part is 0, then is singular, which
// means there are no Inverse of the 3x3 matrix part.
// --------------------------------------------------------------------------
template <typename Real>
inline
const bool
Matrix4x4<Real>::IsSingular() const
{
return Approximately(Determinant3x3(), 0.0f);
}
// --------------------------------------------------------------------------
// Determinant
//
// Compute the determinant of the 3x3 portion of the matrix.
// --------------------------------------------------------------------------
template <typename Real>
inline
const Real
Matrix4x4<Real>::Determinant3x3 () const
{
return
m11 * ((m22 * m33) - (m23 * m32))
+
m12 * ((m23 * m31) - (m21 * m33))
+
m13 * ((m21 * m32) - (m22 * m31));
}
// --------------------------------------------------------------------------
// operator ==
//
// Matrix equals comparison.
// --------------------------------------------------------------------------
template <typename Real>
inline
const bool
Matrix4x4<Real>::operator==(const Matrix4x4<Real> &m) const
{
return Row1() == Row1() && Row2() == m.Row2() && Row3() == m.Row3() && Row4() == m.Row4();
}
// --------------------------------------------------------------------------
// operator !=
//
// Matrix distinct comparison.
// --------------------------------------------------------------------------
template <typename Real>
inline
const bool
Matrix4x4<Real>::operator!=(const Matrix4x4<Real> &m) const
{
return Row1() != m.Row1() || Row2() != m.Row2() || Row3() != m.Row3() || Row4() != m.Row4();
}
template <typename Real>
inline
Matrix4x4<Real>&
Matrix4x4<Real>::operator +=(const Matrix4x4<Real>& m)
{
m11 += m.m11; m12 += m.m12; m13 += m.m13;
m21 += m.m21; m22 += m.m22; m23 += m.m23;
m31 += m.m31; m32 += m.m32; m33 += m.m33;
tx += m.tx; ty += m.ty; tz += m.tz;
return *this;
}
template <typename Real>
inline
Matrix4x4<Real>&
Matrix4x4<Real>::operator -=(const Matrix4x4<Real>& m)
{
m11 -= m.m11; m12 -= m.m12; m13 -= m.m13;
m21 -= m.m21; m22 -= m.m22; m23 -= m.m23;
m31 -= m.m31; m32 -= m.m32; m33 -= m.m33;
tx -= m.tx; ty -= m.ty; tz -= m.tz;
return *this;
}
template <typename Real>
inline
Matrix4x4<Real>
Matrix4x4<Real>::operator+ (const Matrix4x4<Real>& m) const
{
Matrix4x4<Real> res;
res.m11 = m11 + m.m11; res.m12 = m12 + m.m12; res.m13 = m13 + m.m13;
res.m21 = m21 + m.m21; res.m22 = m22 + m.m22; res.m23 = m23 + m.m23;
res.m31 = m31 + m.m31; res.m32 = m32 + m.m32; res.m33 = m33 + m.m33;
res.tx = tx + m.tx; res.ty = ty + m.ty; res.tz = tz + m.tz;
return res;
}
template <typename Real>
inline
Matrix4x4<Real>
Matrix4x4<Real>::operator- (const Matrix4x4<Real>& m) const
{
Matrix4x4<Real> res;
res.m11 = m11 - m.m11; res.m12 = m12 - m.m12; res.m13 = m13 - m.m13;
res.m21 = m21 - m.m21; res.m22 = m22 - m.m22; res.m23 = m23 - m.m23;
res.m31 = m31 - m.m31; res.m32 = m32 - m.m32; res.m33 = m33 - m.m33;
res.tx = tx - m.tx; res.ty = ty - m.ty; res.tz = tz - m.tz;
return res;
}
// --------------------------------------------------------------------------
// Identify
//
// Set matrix to identity.
// --------------------------------------------------------------------------
template <typename Real>
inline void
Matrix4x4<Real>::Identify()
{
m11 = 1.0; m12 = 0.0; m13 = 0.0; h14 = 0.0;
m21 = 0.0; m22 = 1.0; m23 = 0.0; h24 = 0.0;
m31 = 0.0; m32 = 0.0; m33 = 1.0; h34 = 0.0;
tx = 0.0; ty = 0.0; tz = 0.0; tw = 1.0;
}
// --------------------------------------------------------------------------
// Transpose
//
// Transpose the current matrix.
// --------------------------------------------------------------------------
template <typename Real>
inline
void Matrix4x4<Real>::Transpose()
{
Matrix4x4<Real> res;
res.m11 = m11; res.m12 = m21; res.m13 = m31; res.h14 = tx;
res.m21 = m12; res.m22 = m22; res.m23 = m32; res.h24 = ty;
res.m31 = m13; res.m32 = m23; res.m33 = m33; res.h34 = tz;
res.tx = h14; res.ty = h24; res.tz = h34; res.tw = tw;
*this = res;
}
// --------------------------------------------------------------------------
// Translate
//
// Build a translation matrix given a translation vector.
// --------------------------------------------------------------------------
template <typename Real>
inline
void
Matrix4x4<Real>::Translate (const Vector3<Real>& position)
{
tx = position.x;
ty = position.y;
tz = position.z;
}
// --------------------------------------------------------------------------
// Rotation
//
// Build rotation part given a vector3 with euler angles
// --------------------------------------------------------------------------
template <typename Real>
inline
void
Matrix4x4<Real>::Rotation(const Vector3<Real>& rotation)
{
Rotation(rotation.x, rotation.y, rotation.z);
}
// --------------------------------------------------------------------------
// Rotation
//
// Setup a rotation matrix, given three X-Y-Z rotation angles. The
// rotations are performed first on x-axis, then y-axis and finaly z-axis.
// --------------------------------------------------------------------------
template <typename Real>
inline void
Matrix4x4<Real>::Rotation (const Real x, const Real y, const Real z)
{
// Fetch sine and cosine of angles
// Bank
Real cb = std::cos (x);
Real sb = std::sin (x);
// Heading
Real ch = std::cos (y);
Real sh = std::sin (y);
// Attitude
Real ca = std::cos (z);
Real sa = std::sin (z);
Real sacb = sa * cb;
Real sasb = sa * sb;
// Fill in the matrix elements
m11 = (ch * ca); m12 = -(ch * sacb) + (sh * sb); m13 = (ch * sasb) + (sh * cb);
m21 = (sa); m22 = (ca * cb); m23 = -(ca * sb);
m31 = -(sh * ca); m32 = -(sh * sacb) + (ch * sb); m33 = -(sh * sasb) + (ch * cb);
}
// --------------------------------------------------------------------------
// Rotation
//
// Build rotation part from a given axis and angle.
// --------------------------------------------------------------------------
template <typename Real>
inline
void
Matrix4x4<Real>::Rotation(const Vector3<Real>& axis, const Real theta)
{
// Quick sanity check to make sure they passed in a unit vector
// to specify the axis
assert (axis.Length() <= 1.0);
// Get sin and cosine of rotation angle
Real s = std::sin (theta);
Real c = std::cos (theta);
// Compute 1 - cos(theta) and some common subexpressions
Real a = 1.0 - c;
Real ax = a * axis.x;
Real ay = a * axis.y;
Real az = a * axis.z;
// Set the matrix elements. There is still a little more
// opportunity for optimization due to the many common
// subexpressions. We'll let the compiler handle that...
m11 = (ax * axis.x) + c;
m12 = (ax * axis.y) + (axis.z * s);
m13 = (ax * axis.z) - (axis.y * s);
m21 = (ay * axis.x) - (axis.z * s);
m22 = (ay * axis.y) + c;
m23 = (ay * axis.z) + (axis.x * s);
m31 = (az * axis.x) + (axis.y * s);
m32 = (az * axis.y) - (axis.x * s);
m33 = (az * axis.z) + c;
}
// --------------------------------------------------------------------------
// Rotation
//
// Build rotation part from a rotation expressed as a quaternion
// --------------------------------------------------------------------------
template <typename Real>
inline void
Matrix4x4<Real>::Rotation (const Quaternion<Real> &q)
{
// Compute a few values to optimize common subexpressions
Real ww = 2.0 * q.w;
Real xx = 2.0 * q.x;
Real yy = 2.0 * q.y;
Real zz = 2.0 * q.z;
// Set the matrix elements. There is still a little more
// opportunity for optimization due to the many common
// subexpressions. We'll let the compiler handle that...
m11 = 1.0 - (yy * q.y) - (zz * q.z);
m12 = (xx * q.y) + (ww * q.z);
m13 = (xx * q.z) - (ww * q.y);
m21 = (xx * q.y) - (ww * q.z);
m22 = 1.0 - (xx * q.x) - (zz * q.z);
m23 = (yy * q.z) + (ww * q.x);
m31 = (xx * q.z) + (ww * q.y);
m32 = (yy * q.z) - (ww * q.x);
m33 = 1.0 - (xx * q.x) - (yy * q.y);
}
// --------------------------------------------------------------------------
// Scale
//
// Setup the matrix to perform scale on each axis. For uniform scale by k,
// use a vector of the form Vector3( k, k, k ).
//
// --------------------------------------------------------------------------
template <typename Real>
inline
void
Matrix4x4<Real>::Scale(const Vector3<Real>& s)
{
// Set the matrix elements. Pretty straightforward
m11 = s.x;
m22 = s.y;
m33 = s.z;
}
// --------------------------------------------------------------------------
// TransformPosition
//
// Transform a point by the matrix.
// --------------------------------------------------------------------------
template <typename Real>
inline
Vector3<Real>
Matrix4x4<Real>::TransformPosition(const Vector3<Real>& position) const
{
// Grind through the linear algebra.
return Vector3<Real>( (position.x * m11) + (position.y * m21) + (position.z * m31) + tx,
(position.x * m12) + (position.y * m22) + (position.z * m32) + ty,
(position.x * m13) + (position.y * m23) + (position.z * m33) + tz );
}
// --------------------------------------------------------------------------
// InverseTransformPosition
//
// Translate a point by the inverse matrix.
// --------------------------------------------------------------------------
template <typename Real>
inline
Vector3<Real>
Matrix4x4<Real>::InverseTransformPosition (const Vector3<Real> &v) const
{
return Vector3<Real>(v.x - tx, v.y - ty, v.z - tz);
}
// --------------------------------------------------------------------------
// TransformRotation
//
// Rotate a point by the 3x3 upper left portion of the matrix.
// --------------------------------------------------------------------------
template <typename Real>
inline
Vector3<Real>
Matrix4x4<Real>::TransformRotation(const Vector3<Real>& rotation) const
{
return Vector3<Real>( (rotation.x * m11) + (rotation.y * m21) + (rotation.z * m31),
(rotation.x * m12) + (rotation.y * m22) + (rotation.z * m32),
(rotation.x * m13) + (rotation.y * m23) + (rotation.z * m33));
}
// --------------------------------------------------------------------------
// InverseTransformRotation
//
// Rotate a point by the inverse 3x3 upper left portion of the matrix.
// --------------------------------------------------------------------------
template <typename Real>
inline
Vector3<Real>
Matrix4x4<Real>::InverseTransformRotation (const Vector3<Real> &v) const
{
return Vector3<Real> ( (v.x * m11) + (v.y * m12) + (v.z * m13),
(v.x * m21) + (v.y * m22) + (v.z * m23),
(v.x * m31) + (v.y * m32) + (v.z * m33));
}
/////////////////////////////////////////////////////////////////////////////
//
// class Vector3<Real> non - member functions implementation.
//
/////////////////////////////////////////////////////////////////////////////
// --------------------------------------------------------------------------
// Matrix4x4 * Matrix4x4
//
// Matrix concatenation.
//
// We also provide a *= operator, as per C convention.
// --------------------------------------------------------------------------
template <typename Real>
inline Matrix4x4<Real>
operator* (const Matrix4x4<Real>& m1, const Matrix4x4<Real>& m2)
{
Matrix4x4<Real> res;
// Compute the left 4x3 (linear transformation) portion
res.m11 = (m1.m11 * m2.m11) + (m1.m21 * m2.m12) + (m1.m31 * m2.m13) + (m1.tx * m2.h14);
res.m12 = (m1.m12 * m2.m11) + (m1.m22 * m2.m12) + (m1.m32 * m2.m13) + (m1.ty * m2.h14);
res.m13 = (m1.m13 * m2.m11) + (m1.m23 * m2.m12) + (m1.m33 * m2.m13) + (m1.tz * m2.h14);
res.h14 = (m1.h14 * m2.m11) + (m1.h24 * m2.m12) + (m1.h34 * m2.m13) + (m1.tw * m2.h14);
res.m21 = (m1.m11 * m2.m21) + (m1.m21 * m2.m22) + (m1.m31 * m2.m23) + (m1.tx * m2.h24);
res.m22 = (m1.m12 * m2.m21) + (m1.m22 * m2.m22) + (m1.m32 * m2.m23) + (m1.ty * m2.h24);
res.m23 = (m1.m13 * m2.m21) + (m1.m23 * m2.m22) + (m1.m33 * m2.m23) + (m1.tz * m2.h24);
res.h24 = (m1.h14 * m2.m21) + (m1.h24 * m2.m22) + (m1.h34 * m2.m23) + (m1.tw * m2.h24);
res.m31 = (m1.m11 * m2.m31) + (m1.m21 * m2.m32) + (m1.m31 * m2.m33) + (m1.tx * m2.h34);
res.m32 = (m1.m12 * m2.m31) + (m1.m22 * m2.m32) + (m1.m32 * m2.m33) + (m1.ty * m2.h34);
res.m33 = (m1.m13 * m2.m31) + (m1.m23 * m2.m32) + (m1.m33 * m2.m33) + (m1.tz * m2.h34);
res.h34 = (m1.h14 * m2.m31) + (m1.h24 * m2.m32) + (m1.h34 * m2.m33) + (m1.tw * m2.h34);
// Compute the translation portion
res.tx = (m1.m11 * m2.tx) + (m1.m21 * m2.ty) + (m1.m31 * m2.tz) + (m1.tx * m2.tw);
res.ty = (m1.m12 * m2.tx) + (m1.m22 * m2.ty) + (m1.m32 * m2.tz) + (m1.ty * m2.tw);
res.tz = (m1.m13 * m2.tx) + (m1.m23 * m2.ty) + (m1.m33 * m2.tz) + (m1.tz * m2.tw);
res.tw = (m1.h14 * m2.tx) + (m1.h24 * m2.ty) + (m1.h34 * m2.tz) + (m1.tw * m2.tw);
return res;
}
template <typename Real>
inline Matrix4x4<Real> &
operator*= (Matrix4x4<Real>& m1, const Matrix4x4<Real>& m2)
{
m1 = m1 * m2;
return m1;
}
<file_sep>/project/CMakeLists.txt
CMAKE_MINIMUM_REQUIRED(VERSION 3.1)
#[PROJECT_NAME]
PROJECT(DCPPMath)
#[BUILD_TYPE]
SET(CMAKE_BUILD_TYPE Debug)
# Set the output folders where the program will be created
SET(DCPPMATH_LIB_OUTPUT_PATH ${PROJECT_BINARY_DIR}/lib)
#[PRJ_INCLUDE]
INCLUDE_DIRECTORIES(include)
INCLUDE_DIRECTORIES(include/math)
#[PRJ_HEADER_FILES]
SET(HEADERS
include/math/dcmath.h
include/math/matrix.inl
include/math/matrix.h
include/math/quaternion.inl
include/math/quaternion.h
include/math/vector2.inl
include/math/vector2.h
include/math/vector3.inl
include/math/vector3.h
include/math/vector4.inl
include/math/vector4.h
include/math/vector.h
)
# Generate the static library from the sources
ADD_LIBRARY(${PROJECT_NAME} INTERFACE)
TARGET_SOURCES(${PROJECT_NAME} INTERFACE ${HEADERS})
# From here, the target '${PROJECT_NAME}' can be customised
#TARGET_INCLUDE_DIRECTORIES(${PROJECT_NAME}) # Transitively forwarded
#INSTALL(TARGETS ${PROJECT_NAME})
# Copy the include directory where the lib is installed
INSTALL(DIRECTORY include DESTINATION ${DCPPMATH_LIB_OUTPUT_PATH})
# HACK: have the files showing in the IDE, under the name '${PROJECT_NAME}_IDE'
ADD_CUSTOM_TARGET(${PROJECT_NAME}_IDE SOURCES ${HEADERS})
<file_sep>/project/include/math/vector2.inl
/////////////////////////////////////////////////////////////////////////////
//
// class Vector2<Number> implementation.
//
/////////////////////////////////////////////////////////////////////////////
// --------------------------------------------------------------------------
// Vector2 operators
//
// Operator overloading for basic vector operations.
// --------------------------------------------------------------------------
// Vector comparison
template <typename Number>
inline
const bool
Vector2<Number>::operator== (const Vector2<Number> &v) const
{
return Approximately(x, v.x) && Approximately(y, v.y);
}
template <typename Number>
inline
const bool
Vector2<Number>::operator!= (const Vector2<Number> &v) const
{
return (!Approximately(x, v.x) || !Approximately(y, v.y));
}
// Vector negation
template <typename Number>
inline
Vector2<Number>
Vector2<Number>::operator- () const
{
return Vector2<Number> (-x, -y);
}
// Vector transformations
template <typename Number>
inline
Vector2<Number>
Vector2<Number>::operator+ (const Vector2<Number> &v) const
{
return Vector2<Number> (x + v.x, y + v.y);
}
template <typename Number>
inline
Vector2<Number>
Vector2<Number>::operator- (const Vector2<Number> &v) const
{
return Vector2<Number> (x - v.x, y - v.y);
}
template <typename Number>
inline
Vector2<Number>
Vector2<Number>::operator* (const Vector2<Number>& v) const
{
return Vector2<Number>(x * v.x, y * v.y);
}
template <typename Number>
inline
Vector2<Number>
Vector2<Number>::operator* (const Number s) const
{
return Vector2<Number> (x * s, y * s);
}
template <typename Number>
inline
Vector2<Number>
Vector2<Number>::operator/ (const Number s) const
{
const Number oneOverS = 1.0 / s; // Note: no check for divide by zero
return Vector2<Number> (x * oneOverS, y * oneOverS);
}
// Combined assignment operators to conform to C notation convention
template <typename Number>
inline
Vector2<Number>&
Vector2<Number>::operator+= (const Vector2<Number> &v)
{
x += v.x;
y += v.y;
return *this;
}
template <typename Number>
inline
Vector2<Number>&
Vector2<Number>::operator-= (const Vector2<Number> &v)
{
x -= v.x;
y -= v.y;
return *this;
}
template <typename Number>
inline
Vector2<Number>&
Vector2<Number>::operator*= (const Vector2<Number> &v)
{
x *= v.x;
y *= v.y;
return *this;
}
template <typename Number>
inline
Vector2<Number>&
Vector2<Number>::operator*= (const Number s)
{
x *= s;
y *= s;
return *this;
}
template <typename Number>
inline
Vector2<Number>&
Vector2<Number>::operator/= (const Number s)
{
Number oneOverS = 1.0 / s; // Note: no check for divide by zero!
x *= oneOverS;
y *= oneOverS;
return *this;
}
// --------------------------------------------------------------------------
// Static operations
// --------------------------------------------------------------------------
template <typename Number>
inline
const Vector2<Number>
Vector2<Number>::Zero()
{
return Vector2<Number>();
}
template <typename Number>
inline
const Vector2<Number>
Vector2<Number>::One()
{
return Vector2<Number>(1, 1);
}
template <typename Number>
inline
const Vector2<Number>
Vector2<Number>::Up()
{
return Vector2<Number>(0, 1);
}
template <typename Number>
inline
const Vector2<Number>
Vector2<Number>::Down()
{
return Vector2<Number>(0, -1);
}
template <typename Number>
inline
const Vector2<Number>
Vector2<Number>::Left()
{
return Vector2<Number>(-1, 0);
}
template <typename Number>
inline
const Vector2<Number>
Vector2<Number>::Right()
{
return Vector2<Number>(1, 0);
}
template <typename Number>
inline
Vector2<Number>&
Vector2<Number>::Half() const
{
return this * 0.5;
}
template <typename Number>
inline
Vector2<Number>&
Vector2<Number>::Double() const
{
return this * 2.0;
}
|
def47590fcfb40bb4dd94dbbab3ec8dcf3b796e3
|
[
"C",
"CMake",
"C++"
] | 12
|
C++
|
DamnCoder/dcpp_math
|
11e05222cc24ad63391cd899fd931ef08192d2f5
|
09402ac75437bb5f0a614429d42af227aabac790
|
refs/heads/master
|
<file_sep>package com.paskie.callrecorder.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import com.paskie.callrecorder.models.Call;
/**
* Created by user on 4/24/2017.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "call_recorder_db";
public static final int DATABASE_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(Call.CREATE_CALL_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion != newVersion) {
db.execSQL("DROP TABLE "+ Call.CALL_RECORDER_TABLE);
}
}
}
<file_sep>package com.paskie.callrecorder.ui.activities;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import com.paskie.callrecorder.R;
import com.paskie.callrecorder.database.DatabaseManager;
import com.paskie.callrecorder.listeners.IDialogOperationListener;
import com.paskie.callrecorder.models.Call;
import com.paskie.callrecorder.ui.adapters.CallListAdapter;
import com.paskie.callrecorder.ui.fragments.CallOperationOptionDialog;
import java.io.File;
import java.util.List;
import butterknife.BindView;
/**
* Created by user on 4/24/2017.
*/
public class Main extends BaseActivity implements CallListAdapter.IMoreClickListener, IDialogOperationListener{
@BindView(R.id.rv_call_list)
RecyclerView mRecyclerView;
@BindView(R.id.tv_no_call)
TextView noCallTv;
private CallListAdapter callListAdapter;
private Call mSelectedCall;
private List<Call> callList;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
if(checkPermission()) {
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
callList = DatabaseManager.getInstance(this).all();
if(callList.isEmpty()) {
noCallTv.setVisibility(View.VISIBLE);
}else {
noCallTv.setVisibility(View.GONE);
}
callListAdapter = new CallListAdapter(this, callList, this);
mRecyclerView.setAdapter(callListAdapter);
}
ActionBar actionBar = getSupportActionBar();
if(actionBar != null) {
actionBar.setTitle("Callr");
}
}
boolean checkPermission() {
//int granted =
return true;
}
@Override
public void onAction(int action) {
switch (action) {
case ACTION_DELETE_CALL:
new AlertDialog.Builder(this)
.setTitle("Delete Record").setMessage("Delete this call record. Can not be undone")
.setPositiveButton("YES", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
File file = new File(mSelectedCall.mPath);
if(file.exists())
file.delete();
DatabaseManager.getInstance(Main.this).delete(mSelectedCall);
callList.remove(mSelectedCall);
callListAdapter.notifyDataSetChanged();
}
}).setNegativeButton("CANCEL", null).create().show();
break;
case ACTION_LISTEN:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(mSelectedCall.mPath)), "audio/*");
//if(getPackageManager().resolveActivity(intent, PackageManager.GET_META_DATA))
if(intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
}
@Override
public void onMoreClick(int pos) {
mSelectedCall = callList.get(pos);
CallOperationOptionDialog callOperationOptionDialog = new CallOperationOptionDialog();
callOperationOptionDialog.show(getSupportFragmentManager(), "CRP");
}
}
<file_sep>package com.paskie.callrecorder.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.paskie.callrecorder.models.Call;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by user on 4/24/2017.
*/
public class DatabaseManager {
public static DatabaseManager instance;
private DatabaseHelper databaseHelper;
public static synchronized DatabaseManager getInstance(Context context) {
if(instance == null) {
instance = new DatabaseManager(context);
}
return instance;
}
private DatabaseManager(Context context) {
databaseHelper = new DatabaseHelper(context);
}
public DatabaseHelper getDatabaseHelper() {
return databaseHelper;
}
public SQLiteDatabase getDB() {
return databaseHelper.getWritableDatabase();
}
public List<Call> getUnsent() {
String whereClause = Call.CALL_SENT + "=?";
String[] whereArgs = {String.valueOf(0)};
Cursor cursor = getDB().query(Call.CALL_RECORDER_TABLE, null, whereClause, whereArgs, null, null, null);
if(cursor == null)
return Collections.emptyList();
List<Call> callList = new ArrayList<>();
while (cursor.moveToNext()) {
Call call = Call.from(cursor);
callList.add(call);
}
cursor.close();
return callList;
}
public List<Call> all() {
Cursor cursor = getDB().rawQuery("SELECT * FROM "+Call.CALL_RECORDER_TABLE, null);
if(cursor == null)
return Collections.emptyList();
List<Call> callList = new ArrayList<>();
while (cursor.moveToNext()) {
Call call = Call.from(cursor);
callList.add(call);
}
cursor.close();
return callList;
}
public void save(Call call) {
if(call == null)
return;
ContentValues contentValues = call.getContentValues();
SQLiteDatabase sqLiteDatabase = getDB();
sqLiteDatabase.insert(Call.CALL_RECORDER_TABLE, null, contentValues);
}
public synchronized void update(Call call) {
String where = Call.CALL_ID + "=?";
String args[] = {String.valueOf(call.callID)};
int updated = getDB().update(Call.CALL_RECORDER_TABLE, call.getContentValues(), where, args);
if(updated != -1) {
File file = new File(call.mPath);
if(file.exists())
file.delete();
}
}
public synchronized void delete(Call call) {
getDB().delete(Call.CALL_RECORDER_TABLE, Call.CALL_ID + "=?", new String[]{String.valueOf(call.callID)});
}
}
<file_sep>package com.paskie.callrecorder.services;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.SyncHttpClient;
import com.paskie.callrecorder.database.DatabaseManager;
import com.paskie.callrecorder.listeners.CustomResponseHandler;
import com.paskie.callrecorder.models.Call;
import com.paskie.callrecorder.utils.Pref;
import com.paskie.callrecorder.utils.Util;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import cz.msebera.android.httpclient.Header;
/**
* Created by user on 4/24/2017.
*/
public class CallUploadService extends IntentService {
public CallUploadService() {
super("UploadService");
}
private AsyncHttpClient asyncHttpClient = new SyncHttpClient();
public static final String TAG = CallUploadService.class.getSimpleName();
List<Call> sent = new ArrayList<>();
private Context mContext;
@Override
protected void onHandleIntent(@Nullable Intent intent) {
if(!Util.online(this)) {
stopSelf();
return;
}
List<Call> unSent = DatabaseManager.getInstance(this).getUnsent();
if(unSent == null)
return;
mContext = this;
int count = 0;
asyncHttpClient.setTimeout(60000 * 3);
RequestParams requestParams = new RequestParams();
for (int i = 0; i < unSent.size(); i++) {
count += 1;
if(count == 5)
break;
Call next = unSent.get(i);
requestParams.put("user_id", Pref.getInstance().getUser().ID);
requestParams.put("phone_number", next.phoneNumber + " ");
requestParams.put("contact_name", next.phoneNumber + " ");
try{
String pName = "call_"+i;
requestParams.put(pName, new File(next.mPath));
}catch (FileNotFoundException ex) {
Log.d(TAG, "ERROR", ex);
}
sent.add(next);
}
if(sent.size() > 0) {
requestParams.put("count_", sent.size());
String URL = Util.URL + "/call";
asyncHttpClient.post(URL, requestParams, customResponseHandler);
}
}
private CustomResponseHandler customResponseHandler = new CustomResponseHandler(sent) {
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
List<Call> sent = get();
for (Call call : sent) {
DatabaseManager.getInstance(mContext).update(call);
}
}
@Override
public void onProgress(long bytesWritten, long totalSize) {
super.onProgress(bytesWritten, totalSize);
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
}
};
}
<file_sep>package com.paskie.callrecorder.ui.activities;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import com.paskie.callrecorder.R;
import com.paskie.callrecorder.utils.Pref;
/**
* Created By <NAME>
* 7/12/2017.
* Beem24, Inc
*/
public class Splash extends BaseActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if(Pref.getInstance().hasSession()) {
Intent intent = new Intent(Splash.this, Main.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}else {
Intent intent = new Intent(Splash.this, SignUpActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}, 4000);
}
}
<file_sep>package com.paskie.callrecorder.ui.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Patterns;
import android.widget.EditText;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.paskie.callrecorder.R;
import com.paskie.callrecorder.utils.Pref;
import com.paskie.callrecorder.utils.Util;
import org.json.JSONException;
import org.json.JSONObject;
import butterknife.BindView;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;
/**
* Created By <NAME>
* 7/12/2017.
* Beem24, Inc
*/
public class LoginActivity extends BaseActivity {
@BindView(R.id.edt_email_callr_login)
EditText emailEditText;
@BindView(R.id.edt_password_login)
EditText passwordEditText;
private ProgressDialog progressDialog;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
progressDialog = new ProgressDialog(this);
}
@OnClick(R.id.btn_create_account) public void onCreateAccountClick() {
Intent intent = new Intent(this, SignUpActivity.class);
startActivity(intent);
}
@OnClick(R.id.btn_sign_in) public void onSignInClick() {
if(!Patterns.EMAIL_ADDRESS.matcher(Util.text(emailEditText)).matches()) {
showDialog("Error", "Invalid email address");
return;
}
if(Util.empty(passwordEditText)) {
showDialog("Error", "Please enter your password.");
return;
}
if(!Util.online(this)) {
showDialog("Error", "Device is offline");
return;
}
Util.hideKeyboard(this);
RequestParams requestParams = new RequestParams();
requestParams.put("email", Util.text(emailEditText));
requestParams.put("password", Util.text(passwordEditText));
Util.asyncHttpClient.post(Util.URL + "/login", requestParams, new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
showDialog("Error", "Network response unknown. Please retry.");
}
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
try {
JSONObject jsonObject = new JSONObject(responseString);
Pref.getInstance().save(jsonObject.getJSONObject("data"));
Intent intent = new Intent(LoginActivity.this, Main.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}catch (JSONException je) {}
}
@Override
public void onStart() {
super.onStart();
progressDialog.show();
}
@Override
public void onFinish() {
super.onFinish();
progressDialog.cancel();
}
});
}
}
<file_sep>package com.paskie.callrecorder.listeners;
import android.os.Bundle;
import com.loopj.android.http.TextHttpResponseHandler;
import com.paskie.callrecorder.models.Call;
import java.util.List;
import cz.msebera.android.httpclient.Header;
/**
* Created by user on 4/26/2017.
*/
public class CustomResponseHandler extends TextHttpResponseHandler {
public List<Call> data;
public CustomResponseHandler(List<Call> call) {
data = call;
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
}
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
}
public List<Call> get() {
return data;
}
}
<file_sep>package com.paskie.callrecorder.ui.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Patterns;
import android.widget.EditText;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.paskie.callrecorder.R;
import com.paskie.callrecorder.utils.Pref;
import com.paskie.callrecorder.utils.Util;
import org.json.JSONException;
import org.json.JSONObject;
import butterknife.BindView;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;
/**
* Created By <NAME>
* 7/12/2017.
* Beem24, Inc
*/
public class SignUpActivity extends BaseActivity {
@BindView(R.id.email_edt_sign_up)
EditText mailEditText;
@BindView(R.id.edt_username_sign_up)
EditText usernameEditText;
@BindView(R.id.edt_password_sign_up)
EditText passwordEditText;
private ProgressDialog progressDialog;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up_activity);
progressDialog = new ProgressDialog(this);
}
@OnClick(R.id.btn_sign_up_sign_up) public void onSignUpClick() {
if(!Patterns.EMAIL_ADDRESS.matcher(Util.text(mailEditText)).matches()) {
showDialog("Error", "Invalid email address.");
return;
}
if(Util.empty(usernameEditText)) {
showDialog("Error", "Please enter a username.");
return;
}
if(Util.empty(passwordEditText)) {
showDialog("Error", "Invalid password");
return;
}
if(!Util.online(this)) {
showDialog("Error", "Device is offline");
return;
}
Util.hideKeyboard(this);
RequestParams requestParams = new RequestParams();
requestParams.put("email", Util.text(mailEditText));
requestParams.put("password", Util.text(passwordEditText));
requestParams.put("username", Util.text(usernameEditText));
Util.asyncHttpClient.post(Util.URL + "/register", requestParams, new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
showDialog("Error", "Network response unknown. Please retry.");
}
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
try {
JSONObject jsonObject = new JSONObject(responseString);
Pref.getInstance().save(jsonObject.getJSONObject("data"));
Intent intent = new Intent(SignUpActivity.this, Main.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}catch (JSONException je) {}
}
@Override
public void onFinish() {
super.onFinish();
progressDialog.cancel();
}
@Override
public void onStart() {
super.onStart();
progressDialog.show();
}
});
}
}
<file_sep>package com.paskie.callrecorder.ui.adapters;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import com.paskie.callrecorder.R;
import com.paskie.callrecorder.models.Call;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* Created By <NAME>
* 7/12/2017.
* Beem24, Inc
*/
public class CallListAdapter extends RecyclerView.Adapter<CallListAdapter.CallListViewHolder> {
private List<Call> callList;
private Context mContext;
private LayoutInflater mLayoutInflater;
public interface IMoreClickListener {
void onMoreClick(int pos);
}
private IMoreClickListener iMoreClickListener;
public CallListAdapter(Context context, List<Call> calls, IMoreClickListener moreClickListener) {
callList = calls;
mContext = context;
if(mContext != null)
mLayoutInflater = LayoutInflater.from(mContext);
iMoreClickListener = moreClickListener;
}
@Override
public CallListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if(mLayoutInflater == null) mLayoutInflater = LayoutInflater.from(parent.getContext());
return new CallListViewHolder(mLayoutInflater.inflate(R.layout.call_, parent, false));
}
@Override
public void onBindViewHolder(CallListViewHolder holder, int position) {
Call call = callList.get(position);
holder.name.setText(String.valueOf(call.phoneNumber));
holder.time.setText(String.valueOf(call.time_));
final int idx = position;
holder.more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(iMoreClickListener != null)
iMoreClickListener.onMoreClick(idx);
}
});
}
@Override
public int getItemCount() {
return callList.size();
}
class CallListViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.tv_callr_name_call)
TextView name;
@BindView(R.id.tv_call_time_call)
TextView time;
@BindView(R.id.btn_more_call)
ImageButton more;
public CallListViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
<file_sep>package com.paskie.callrecorder.utils;
/**
* Created by user on 4/24/2017.
*/
public class Data {
public static final int INCOMING_CALL = 0;
public static final int OUTGOING_CALL = 1;
public static final int CALL_END = 2;
}
<file_sep>package com.paskie.callrecorder.reciever;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.util.Log;
import com.paskie.callrecorder.services.CallUploadService;
import com.paskie.callrecorder.utils.Util;
/**
* Created by user on 4/26/2017.
*/
public class NetworkReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
boolean online = Util.online(context);
if(online) {
Intent i = new Intent(context, CallUploadService.class);
context.startService(i);
}
}
}
}
<file_sep>#CallRecorder.
An advanced call logging system. Track all incoming and outgoing calls, periodically back them up on remote server!.
|
44700720d9d07e499e8ec6d188cd30b799c97ec7
|
[
"Markdown",
"Java"
] | 12
|
Java
|
adigunhammedolalekan/callr
|
27ef514142f938395507b8b5cbc047155b47bc05
|
4c8ef7cd819a9594551e8e11f29e93887f1e5b41
|
refs/heads/master
|
<file_sep> function tap( dom, callback ){
var startTime = 0;
var endTime = 0;
dom.addEventListener("touchstart",function(){
// 记录按下屏幕的时间
startTime = Date.now();
});
dom.addEventListener("touchend",function(){
// 记录松开屏幕的时间
endTime = Date.now();
// 计算他们的时间差 毫秒为单位
var ms = endTime - startTime;
// 判断两个时间差
if( ms < 150 ){// 是轻触事件
/* if( callback ){
callback();
} */
callback && callback();
}
});
}<file_sep>window.onload = function(){
var list = [
"热门推荐",
"手机数码",
"电脑办公",
"家用电器",
"计生情趣",
"美妆护肤",
"个护清洁",
"汽车生活",
"京东超市",
"男装",
"男鞋",
"女装",
"女鞋",
"母婴童鞋",
"图书音像",
"运动户外",
"内衣配饰",
"食品生鲜",
"酒水饮料",
"家居家装",
"家具厨具",
"箱包手袋",
"钟表珠宝",
"玩具乐器",
"医药保健",
"宠物生活",
"礼品鲜花",
"农资绿植",
"生活旅行",
"奢饰品",
"京东国际",
"艺术邮币",
"二手商品",
"特产馆",
"京东金融",
"国际名牌",
"拍卖",
"房产",
"工业品"
];
function query(selector) {
//selector: css选择器
return document.querySelector(selector);
};
var hd_Height = query(".header").offsetHeight;
var ft_Height = query(".footer").offsetHeight;
var td_Height = query(".sidebar").offsetHeight;
var l_ul = query(".sidebar .sidebar_left ul");
list.forEach(function (v, i) {
var lis = document.createElement("li");
var liText = document.createTextNode(v);
lis.appendChild(liText);
l_ul.appendChild(lis);
});
var r_ul = query(".sidebar .sidebar_right ul");
list.forEach(function (v, i) {
var lis = document.createElement("li");
var liText = document.createTextNode(v);
lis.appendChild(liText);
r_ul.appendChild(lis);
});
var l_lis = document.querySelectorAll(".sidebar .sidebar_left ul li");
var r_lis = document.querySelectorAll(".sidebar .sidebar_right ul li");
l_lis[0].className = "hover";
r_lis[0].style.display = "block";
for (var i = 0; i < l_lis.length; i++) {
l_lis[i].setAttribute("data-i", i);
}
// 左侧栏目滑动
var tb_l = query(".sidebar .sidebar_left");
// 记录开始位置
var startY = 0;
// 记录当前位置
var nowY = 0;
var eve = {};
tb_l.ontouchstart = function (e) {
// 赋值当前与顶部的距离
var target = e.target;
eve = {
click:function () {
for (var j = 0; j < r_lis.length; j++) {
l_lis[j].className = "";
r_lis[j].style.display = "none";
}
target.className = "hover";
var index = target.getAttribute("data-i");
r_lis[index].style.display = "block";
}
}
nowY = this.offsetTop;
startY = e.targetTouches[0].pageY;
};
tap(tb_l, function () {
eve.click();
});
tb_l.ontouchmove = function (e) {
// 阻止浏览器默认行为
e.preventDefault();
var moveY = e.targetTouches[0].pageY;
var boxY = moveY - startY + nowY;
var maxY = -(l_ul.offsetHeight + ft_Height - td_Height);
if (boxY > hd_Height) {
boxY = hd_Height;
} else if (boxY < maxY) {
boxY = maxY;
}
this.style.marginTop = boxY + "px";
};
}
|
2165b643e509ca834b56a96f40811bc2d112f3e8
|
[
"JavaScript"
] | 2
|
JavaScript
|
kkl2020/mobile_learn
|
dc818f345f7414783a7bf83b889378545c2893f8
|
1b2bea5212a33bbc6430e1798682da7cf9825610
|
refs/heads/master
|
<repo_name>bingzhang007/dc<file_sep>/js/kfl.js
var utilModule = angular.module('utilModule', ['ionic']);
//什么时候检查:添加到购物车时,下单时,进入购物车时,查看订单中心
//什么时候设置:登录成功时,设置为1, 退出登录时,设置为-1
utilModule.service('$LoginOperate', [function () {
//检查是否已经登录
this.checkLoginFlag = function () {
var flag = sessionStorage.getItem('LoginFlag')
console.log(flag);
return flag;
}
//设置登录的状态
this.setLoginFlag = function (flag) {
sessionStorage.setItem('LoginFlag', flag)
}
}])
utilModule.service('$httpKfl', ['$http', '$ionicLoading', function ($http, $ionicLoading) {
this.sendRequest = function (urlWithArgs, succFunc) {
$ionicLoading.show({
template: 'loading...'
})
$http.get(urlWithArgs).success(function (data) {
succFunc(data);
$ionicLoading.hide();
})
}
}]);
var app = angular.module('kfl', ['ionic', 'utilModule']);
app.config(
function ($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$ionicConfigProvider.tabs.position('bottom');
$stateProvider
.state('start', {
url: '/kflStart',
templateUrl: 'tpl/start.html',
controller: 'startCtrl'
})
.state('main', {
url: '/kflMain',
templateUrl: 'tpl/main.html',
controller: 'mainCtrl'
})
.state('detail', {
url: '/kflDetail/:id',
templateUrl: 'tpl/detail.html',
controller: 'detailCtrl'
})
.state('order', {
url: '/kflOrder/:data',
templateUrl: 'tpl/order.html',
controller: 'orderCtrl'
})
.state('myOrder', {
url: '/kflMyOrder',
templateUrl: 'tpl/myOrder.html',
controller: 'myOrderCtrl'
})
.state('myCart', {
url: '/kflMyCart',
templateUrl: 'tpl/myCart.html',
controller: 'myCartCtrl'
})
.state('login', {
url: '/kflMylogin/:name/:args',
templateUrl: 'tpl/login.html',
controller: 'loginCtrl'
})
.state('setting', {
url: '/kflSetting',
templateUrl: 'tpl/setting.html',
controller: 'settingCtrl'
})
$urlRouterProvider.otherwise('/kflStart')
})
app.controller('parentCtrl', ['$scope', '$state', '$LoginOperate',
function ($scope, $state, $LoginOperate) {
$scope.data = {totalNumInCount: 0};
var flag = $LoginOperate.checkLoginFlag();
if (flag != -1 && flag != 1) {
$LoginOperate.setLoginFlag(-1);
}
$scope.jump = function (stateName, arg) {
$state.go(stateName, arg);
}
$scope.logOut = function () {
sessionStorage.clear();
$LoginOperate.setLoginFlag(-1);
$scope.jump('start');
$scope.data.totalNumInCount = 0;
}
$scope.funcSelect = function (index) {
if (index == 0) {
$scope.jump('start');
}
else if (index == 1) {
$scope.jump('myOrder');
}
else if (index == 2) {
$scope.jump('myCart');
}
else if (index == 3) {
$scope.jump('setting');
}
}
}]);
app.controller('loginCtrl', ['$scope', '$stateParams', '$http', '$LoginOperate', '$httpKfl', '$ionicPopup',
function ($scope, $stateParams, $http, $LoginOperate, $httpKfl, $ionicPopup) {
$scope.user = {name: '', pwd: ''}
$scope.submit = function () {
$httpKfl.sendRequest(
'data/login.php?uname=' + $scope.user.name + "&pwd=" + $scope.user.pwd, succCallback
)
};
var succCallback = function (data) {
if (data[0].msg == 'succ') {
$LoginOperate.setLoginFlag(1);
sessionStorage.setItem('id', data[0].uid);
if ($stateParams.args && $stateParams.args != "") {
$scope.jump($stateParams.name, angular.fromJson($stateParams.args));
}
else {
$scope.jump($stateParams.name);
}
}
else {
$ionicPopup.alert({
template: '登录失败'
})
}
};
}]);
app.controller('startCtrl', ['$scope', '$state', '$timeout', function ($scope, $state, $timeout) {
$timeout(function () {
if ($state.current.name == 'start') {
$scope.jump('main');
}
}, 2000);
}])
app.controller('mainCtrl', ['$scope', '$http', '$httpKfl',
function ($scope, $http, $httpKfl) {
$scope.dishList = [];
$scope.inputData = {kw: ''};
$scope.hasMore = true;
$httpKfl.sendRequest('data/dish_getbypage.php', function (data) {
$scope.dishList = data;
});
$scope.loadMore = function () {
$httpKfl.sendRequest('data/dish_getbypage.php?start=' + $scope.dishList.length,
function (data) {
if (data.length < 5) {
$scope.hasMore = false;
}
$scope.dishList = $scope.dishList.concat(data);
$scope.$broadcast('scroll.infiniteScrollComplete');
})
}
$scope.$watch('inputData.kw', function () {
if ($scope.inputData.kw) {
$httpKfl.sendRequest('data/dish_getbykw.php?kw=' + $scope.inputData.kw, function (data) {
$scope.dishList = data;
});
}
})
}]);
app.controller('detailCtrl', ['$scope', '$http', '$stateParams', '$LoginOperate', '$httpKfl',
function ($scope, $http, $stateParams, $LoginOperate, $httpKfl) {
$httpKfl.sendRequest('data/dish_getbyid.php?id=' + $stateParams.id, function (data) {
$scope.dish = data[0];
});
$scope.addToCart = function () {
if ($LoginOperate.checkLoginFlag() == -1) {
$scope.jump('login', {name: 'detail', args: '{"id":' + $stateParams.id + '}'});
return;
}
$httpKfl.sendRequest('data/cart_update.php?did=' + $scope.dish.did +
"&count=-1" + "&uid=" + sessionStorage.getItem('id'), function (data) {
if (data.msg == 'succ') {
alert('添加成功');
$scope.data.totalNumInCount++;
}
else {
alert('添加失败')
}
}
)
}
}
]);
app.controller('orderCtrl',
['$scope', '$http', "$stateParams", '$httpParamSerializerJQLike', '$LoginOperate',
function ($scope, $http, $stateParams, $httpParamSerializerJQLike, $LoginOperate) {
var cart = angular.fromJson($stateParams.data);
var allPrice = 0;
angular.forEach(cart, function (value, key) {
allPrice += (value.dishCount * value.price);
})
$scope.order = {
cartDetail: $stateParams.data,
totalprice: allPrice
};
$scope.submitOrder = function () {
if ($LoginOperate.checkLoginFlag() == -1) {
$scope.jump('login', {name: 'order', args: '{"data":' + $stateParams.data + '}'});
return;
}
var result = $httpParamSerializerJQLike($scope.order);
$http.defaults.headers.post = {'Content-Type': 'application/x-www-form-urlencoded'};
$http
.post('data/order_add.php?', result)
.success(function (data) {
if (data[0].msg == 'succ') {
// sessionStorage.setItem('phone', $scope.order.phone);
$scope.succMsg = "下单成功,订单编号为:" + data[0].oid;
$scope.data.totalNumInCount = 0;
}
else {
$scope.errMsg = "下单失败";
}
})
}
}
])
app.controller('myOrderCtrl', ['$scope', '$http', '$LoginOperate', '$httpKfl',
function ($scope, $http, $LoginOperate, $httpKfl) {
console.log('in myOrderCtrl ');
if ($LoginOperate.checkLoginFlag() == -1) {
console.log('未登录');
$scope.jump('login', {name: 'myOrder'});
return;
}
$httpKfl.sendRequest('data/order_getbyuserid.php?userid=1', function (dataServer) {
$scope.orderList = dataServer.data;
})
}]);
app.controller("myCartCtrl", ["$scope", '$http', '$LoginOperate', '$httpKfl',
function ($scope, $http, $LoginOperate, $httpKfl) {
if ($LoginOperate.checkLoginFlag() == -1) {
console.log('未登录');
$scope.jump('login', {name: 'myCart'});
return;
}
$scope.hasDish = true;
$scope.editEnable = false;
$scope.editShowMsg = "编辑";
$scope.hasChange = false;
$scope.funcToggleEdit = function () {
$scope.editEnable = !$scope.editEnable;
if ($scope.editEnable) {
$scope.hasChange = false;
$scope.editShowMsg = "完成";
}
else {
$scope.editShowMsg = "编辑";
}
}
$httpKfl.sendRequest('data/cart_select.php?uid=' + sessionStorage.getItem('id'), function (dataServer) {
$scope.cart = dataServer.data;
if ($scope.cart.length == 0) {
$scope.hasDish = false;
}
else {
$scope.data.totalNumInCount = 0;
angular.forEach($scope.cart, function (value, key) {
$scope.data.totalNumInCount += parseInt(value.dishCount);
})
}
})
$scope.updateToServer = function (did, count) {
$httpKfl.sendRequest('data/cart_update.php?did=' + did + "&count=" + count + "&uid=" + sessionStorage.getItem('id'), function (data) {
$scope.data.totalNumInCount = 0;
angular.forEach($scope.cart, function (value, key) {
$scope.data.totalNumInCount += parseInt(value.dishCount);
})
})
}
$scope.add = function (index) {
$scope.hasChange = true;
$scope.cart[index].dishCount++;
$scope.updateToServer($scope.cart[index].did, $scope.cart[index].dishCount);
}
$scope.delete = function (index) {
$scope.hasChange = true;
var num = $scope.cart[index].dishCount
num--;
if (num <= 0) {
num = 1;
}
else {
$scope.cart[index].dishCount = num;
$scope.updateToServer($scope.cart[index].did, $scope.cart[index].dishCount);
}
}
$scope.sumAll = function () {
var sum = 0;
angular.forEach($scope.cart, function (value, index) {
sum += value.dishCount * value.price;
})
return sum;
}
$scope.jumpToOrder = function () {
var str = angular.toJson($scope.cart);
$scope.jump('order', {data: str});
}
}]);
app.controller('settingCtrl', ['$ionicModal', '$scope', function ($ionicModal, $scope) {
$ionicModal.fromTemplateUrl('tpl/about.html', {
scope: $scope
}).then(function (modal) {
$scope.modal = modal;
})
$scope.open = function () {
$scope.modal.show();
}
$scope.hide = function () {
$scope.modal.hide();
}
}])
<file_sep>/data/order_getbyuserid.php
<?php
/**根据用户id查询订单数据**/
header('Content-Type:application/json');
$output = [];
@$userid = $_REQUEST['userid'];
if(empty($userid)){
echo "[]"; //若客户端未提交用户id,则返回一个空数组,
return; //并退出当前页面的执行
}
//访问数据库
require('init.php');
$sql = "SELECT kf_order.oid,kf_order.userid,kf_order.phone,kf_order.addr,
kf_order.totalprice,kf_order.user_name,kf_order.order_time,
kf_orderdetails.did,kf_orderdetails.dishcount,kf_orderdetails.price,
kf_dish.name,kf_dish.img_sm
from kf_order,kf_orderdetails,kf_dish
WHERE kf_order.oid = kf_orderdetails.oid and kf_orderdetails.did = kf_dish.did and kf_order.userid='$userid'";
$result = mysqli_query($conn, $sql);
$output['data'] = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($output);
?>
<file_sep>/data/database.sql
SET NAMES 'utf8';
DROP DATABASE IF EXISTS kaifanla_new;
CREATE DATABASE kaifanla_new CHARSET=UTF8;
USE kaifanla_new;
CREATE TABLE kf_dish(
did INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(64),
price FLOAT(6,2),
img_sm VARCHAR(64),
img_lg VARCHAR(64),
detail VARCHAR(2048),
material VARCHAR(2048)
);
INSERT INTO kf_dish(did,img_sm,img_lg,name,price,material,detail) VALUES
( null,
'p0281.jpg',
'p0281-l.jpg',
'【酸甜开胃虾】',
36,
'明虾、番茄酱、白糖、白醋、葱、姜、淀粉',
'话说有两个地方是我挪不动脚的,一个是图书馆,另外一个便是菜市场! 每周有七天,留给自己的时间却很少。既要带儿子去上早教课,又要陪女儿上兴趣班,还要留一个半天带孩子们泡图书馆! 有时真的觉得妈妈是这个世界上最伟大的职业,累,并快乐着! 这个时节正是各类果蔬大量上市的时候,拖着买菜专用的小拉车,徜徉在人声鼎沸的菜市场,从海鲜区、肉类区再慢慢逛到我最喜爱的果蔬区,感受季节的变换带给人们餐桌上的喜悦………… '
),
( null,
'p2679.jpg',
'p2679-l.jpg',
'【桂香紫薯山药卷】',
16.5,
'切片吐司、紫薯、铁棍山药、糖桂花、炼乳',
'今天用紫薯,山药和吐司来做一款漂亮又健康的点心,做为早餐或者夜宵都是很好的选择哦! 做法其实很简单,只要将各种食材层叠卷起来就行。提前煮好山药和紫薯,那么只要几分钟就能完成。 但就是这么一点小小的改变,就能立刻让原本平淡无奇的吐司变身抢手货哟~ 生活总是这样,时不时的有一些小惊喜,才会更加精彩不是嘛~'
),
( null,
'p8489.jpg',
'p8489-l.jpg',
'【小米椒爆炒小公鸡】',
32,
'三黄鸡、杭椒、干红椒、新鲜小米椒、麻椒、八角、香叶、葱、姜、生抽',
'算起来有一个星期没有更新了,忙着赶紧完成手头的工作,和孩子一起开启度假模式。我总是毫不避讳地称自己为吃货,对于我来说,度假中缺少美食是万万不可的。想要找一个风景与美食兼顾的度假地点可不太容易,工作之余忙着查路线,查攻略,总算是定好了目的地。其实我这个嗜辣族最想去的还是成都重庆一带,考虑到季节的原因,还是留到冬天再前往吧。今天上一道火辣辣的小米椒爆炒小公鸡,虽在家中,也是十足的过了把食辣的瘾,不擅吃辣的伙伴们做这道菜的时候可要记得减少辣椒的用量哦。'
),
( null,
'p7818.jpg',
'p7818-l.jpg',
'【口袋饼】',
6.5,
'面粉、黄瓜、香肠、热水、土豆、盐、醋、生抽、油。',
'热水和面!面团擀成薄薄的面片之后切成长条,之后中间抹油!折叠之后用手把两边按扁,使其黏到一起!如图!然后用刀背划出花边!平底锅抹油小火煎制口袋饼,两边烙上金黄色即可!土豆切丝!黄瓜和香肠切条状!炒土豆丝,放入盐,醋和生抽炒均匀就可以了,然后放入烙好的口袋饼里,放入黄瓜和香肠即可!'
),
( null,
'p9138.jpg',
'p9138-l.jpg',
'【橄榄油版酸奶蛋糕】',
32,
'鸡蛋、玉米淀粉、绵白糖、白醋、低筋粉、橄榄油、酸奶。',
'酸奶蛋糕,这是第二次做。自前一次做了带去单位分享后,吃到的同事都说好吃,连不爱甜食的自己也觉得细腻可口。特别是入冰箱后取出品味风味尤佳。喜欢那一丝丝的凉意一丝丝的甜味,入口的感觉特别绵软,很适合夏季食用的。这次还是没有用黄油,因为等融化嫌麻烦,继续用了橄榄油。不同的是这次用了水浴法烘焙的。我用的模具是八寸的活底蛋糕模具,成品有一点收腰,但口味还挺成功的。只是早上拍照心急得很,因为LG上班比较早。难得他如此喜欢吃了最大的两块。'
),
( null,
'p4788.jpg',
'p4788-l.jpg',
'【番茄肉酱意大利面】',
25,
'意大利面、番茄、洋葱、蒜泥、肉糜、黑胡椒粉、番茄酱、盐',
'听说,台风天,电影和意大利面更配喔汤锅倒水烧开,放一勺盐一勺橄榄油,加入意面,煮13分钟。(意面种类不同,煮的时间也不一样,5-15分钟不等)。煮好的面控水,拌入一勺橄榄油,以防面粘连。平底锅倒油预热,蒜泥炒香,下肉糜翻炒至变色,倒入洋葱丁、番茄丁,翻炒一分钟,放番茄酱、盐、黑胡椒,继续翻炒。肉酱里加热水大火烧开,倒入意面转中火,待意面吸饱汤汁后,关火盛盘。'
),
( null,
'p7933.jpg',
'p7933-l.jpg',
'【放心油条】',
1.5,
'面粉、安琪油条膨松剂、温水、植物油。',
'自己炸的油条不含明矾,也不用担心地沟油,吃的比较放心。准备中筋粉,油条膨松剂和植物油。面粉和膨松剂混合均匀,加入50-60度温水搅拌。揉成光滑的面团,盖上保鲜膜醒30分钟左右。将醒发好的面团切成长形小剂子,两个叠在一起用筷子按压一下。用手捏住两头抻拉一下,放入7成热(约180-200度)的油锅中炸至金黄即可。'
),
( null,
'p6611.jpg',
'p6611-l.jpg',
'【蒸饺】',
12,
'鸡蛋、豆角酱肉馅、西红柿鸡蛋馅、猪生抽、生抽、海鲜酱油、糖、盐',
'昨天突然好想吃蒸饺,但是貌似没听过北京哪家蒸饺好吃,于是决定自己做啦,重要的事最近爱上做饭,能与大家分享美食乐趣也让我又燃起了烹饪的热情。想必最好吃的东西还是自己家的家常便饭!面粉300克,开水100ml左右(这个量可以在和面的时候自己调节下,蒸饺一定是烫面的)鸡蛋一个,我是用面包机和的面团,准备其他馅时一直在醒面(半小时内)。豆角酱肉馅:做法见我的豆角酱肉卤菜谱'
);
##SELECT * FROM kf_dish;
/*用户表*/
CREATE TABLE kf_users(
userid INT PRIMARY KEY AUTO_INCREMENT, /*购物车编号*/
uname VARCHAR(20), /*用户名*/
pwd VARCHAR(20), /*密码*/
phone VARCHAR(20) /*电话*/
);
INSERT INTO kf_users VALUES
(NULL,'mary','11111','13111112345'),
(NULL,'jerry','22222','13819196547'),
(NULL,'john','33333','13819196547');
/*订单表*/
CREATE TABLE kf_order(
oid INT PRIMARY KEY AUTO_INCREMENT, /*订单ID*/
userid INT, /*用户*/
phone VARCHAR(16), /*联系电话*/
user_name VARCHAR(16), /*收货方用户名*/
order_time LONG, /*下单时间*/
addr VARCHAR(256), /*订单地址*/
totalprice FLOAT(6,2) /*订单总价*/
);
INSERT INTO kf_order VALUES
(NULL,1,'13501234567','大旭',1445154859209,'大钟寺中鼎B座',20.5),
(NULL,1,'13501257543','琳妹妹',1445154997543,'大钟寺中鼎B座',12.5),
(NULL,2,'13207654321','东东',1445254997612,'大钟寺中鼎B座',55),
(NULL,2,'13899999999','文兄',1445354959209,'大钟寺中鼎B座',35),
(NULL,3,'13683675299','梅姐',1445355889209,'大钟寺中鼎B座',45);
/**购物车表**/
CREATE TABLE kf_cart(
ctid INT PRIMARY KEY AUTO_INCREMENT, /*购物车编号*/
userid INT, /*用户编号:假定有用户id为 1 和 3 的两个用户有数据*/
did INT, /*产品编号*/
dishCount INT /*数量*/
);
INSERT INTO kf_cart VALUES (1,1,1,1),
(2,1,2,4),
(3,1,5,2),
(4,3,2,10),
(5,3,6,1);
##SELECT * FROM kf_order;
/**订单详情表**/
CREATE TABLE kf_orderdetails(
oid INT , /*订单编号*/
did INT, /*产品id*/
dishCount INT, /*购买数量*/
price FLOAT(8,2) /*产品单价:需要记载,因为产品价格可能波动*/
);
INSERT INTO kf_orderdetails VALUES (1,1,2,5),
(1,2,1,10.5),
(2,3,1,12.5),
(3,1,3,5),
(3,2,4,10),
(4,4,7,5),
(5,5,5,4),
(5,6,2,12.5);
<file_sep>/README.md
# dc
一个移动端订餐网站,包含登录、搜索、查看商品详情、下订单等基本功能。
登录名:mary,密码:<PASSWORD> 手机:13111112345
|
0e62e99d93fabfae047e4a17796ac62e2acbf015
|
[
"JavaScript",
"SQL",
"Markdown",
"PHP"
] | 4
|
JavaScript
|
bingzhang007/dc
|
46f15acc5561ba67ebc2d4de536d1c1e66f42505
|
4b926b90ba8f88ad5eede843fe8d32b287725b34
|
refs/heads/master
|
<repo_name>preamsai123/project<file_sep>/project/PROJECT/src/com/dao/UserDao.java
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.bean.User;
public class UserDao {
public static boolean CheckEmailexitsorNot(String email) throws ClassNotFoundException, SQLException {
Connection c =ConnectionUtility.getconnection();
PreparedStatement ps = c.prepareStatement("select * from user where email=?");
ps.setString(1,email);
ResultSet rs =ps.executeQuery();
if(rs.next())
return true;
return false;
}
public static boolean AddCustomer(User u) throws ClassNotFoundException, SQLException {
Connection con = ConnectionUtility.getconnection();
PreparedStatement ps = con.prepareStatement("insert into user(name,email,password)values(?,?,aes_encrypt(?,'k1'))");
ps.setString(1, u.getName());
ps.setString(2,u.getEmail());
ps.setString(3, u.getPassword());
int val = ps.executeUpdate();
if (val > 0) {
return true;
} else
return false;
}
public static String Uservalidation(String email) throws ClassNotFoundException, SQLException {
Connection c =ConnectionUtility.getconnection();
PreparedStatement ps = c.prepareStatement("select aes_decrypt(password,'k1') from user where email=?" );
ps.setString(1,email);
ResultSet rs =ps.executeQuery();
rs.next();
return rs.getString(1);
}
public static String UserName(String email) throws ClassNotFoundException, SQLException {
Connection c =ConnectionUtility.getconnection();
PreparedStatement ps = c.prepareStatement("select name from user where email =?");
ps.setString(1,email);
ResultSet rs =ps.executeQuery();
rs.next();
return rs.getString(1);
}
public static int UserID(String email) throws ClassNotFoundException, SQLException {
Connection c =ConnectionUtility.getconnection();
PreparedStatement ps = c.prepareStatement("select id from user where email =?");
ps.setString(1,email);
ResultSet rs =ps.executeQuery();
rs.next();
return rs.getInt(1);
}
}
<file_sep>/project/PROJECT/src/com/dao/OrderDao.java
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
public class OrderDao {
public static boolean Generatebill(int custId,int ta,Timestamp t) throws ClassNotFoundException, SQLException {
Connection con = ConnectionUtility.getconnection();
PreparedStatement ps = con.prepareStatement("insert into orders(user_id,total_amount,order_date)values(?,?,?)");
ps.setInt(1, custId);
ps.setInt(2,ta);
ps.setTimestamp(3,t);
int val = ps.executeUpdate();
if (val > 0) {
return true;
} else
return false;
}
public static int GetOrderIDwithUserIdandTimestamp(int custId,Timestamp t) throws ClassNotFoundException, SQLException {
Connection c =ConnectionUtility.getconnection();
PreparedStatement ps = c.prepareStatement("select id from orders where user_id =? and order_date =?");
ps.setInt(1,custId);
ps.setTimestamp(2, t);
ResultSet rs =ps.executeQuery();
rs.next();
return rs.getInt(1);
}
}
<file_sep>/project/commands.sql
drop database urbanladder;
create database urbanladder;
use urbanladder;
create table product(id int primary key auto_increment,name varchar(30),price int,image_url varchar(30),category varchar(30))auto_increment=1001;
create table user(id int primary key auto_increment,name varchar(30),email varchar(20),password varchar(80))auto_increment=5001;
create table orders(id int primary key auto_increment,user_id int,total_amount int,order_date timestamp,foreign key(user_id) references user(id))auto_increment=3001;
create table order_details(id int primary key auto_increment,order_id int,product_id int,quantity int,foreign key(order_id) references orders(id),foreign key(product_id) references product(id)) auto_increment=6001;
insert into product(name,price,image_url,category) values('mordern',62354,'bed1.jpg','beds');
insert into product(name,price,image_url,category) values('etnic',85246,'bed2.jpg','beds');
insert into product(name,price,image_url,category) values('simple',28654,'bed3.jpg','beds');
insert into product(name,price,image_url,category) values('kids',52252,'bed4.jpg','beds');
insert into product(name,price,image_url,category) values('large',78562,'bed5.jpg','beds');
insert into product(name,price,image_url,category) values('recliner',80298,'sofa1.jpg','sofa');
insert into product(name,price,image_url,category) values('leather sofa',50000,'sofa2.jpg','sofa');
insert into product(name,price,image_url,category) values('fur soafa',30000,'sofa3.jpg','sofa');
insert into product(name,price,image_url,category) values('single sofa',90729,'sofa4.jpg','sofa');
insert into product(name,price,image_url,category) values('still sofa',25621,'sofa5.jpg','sofa');
insert into product(name,price,image_url,category) values('royal',158246,'dinning1.jpg','dinning table');
insert into product(name,price,image_url,category) values('ethnic',24563,'dinning2.jpg','dinning table');
insert into product(name,price,image_url,category) values('mordern',74569,'dinning3.jpg','dinning table');
insert into product(name,price,image_url,category) values('wooden',23569,'dinning4.jpg','dinning table');
insert into product(name,price,image_url,category) values('glass',79456,'dinning5.jpg','dinning table');
insert into product(name,price,image_url,category) values('low table',172569,'office1.jpg','office furniture');
insert into product(name,price,image_url,category) values('wooden',29563,'office2.jpg','office furniture');
insert into product(name,price,image_url,category) values('mordern',79569,'office3.jpg','office furniture');
insert into product(name,price,image_url,category) values('glass',29569,'office4.jpg','office furniture');
insert into product(name,price,image_url,category) values('partisions',80456,'office5.jpg','office furniture');
|
200d1641a58a1f343bd25c7638df9eb55f180dbe
|
[
"Java",
"SQL"
] | 3
|
Java
|
preamsai123/project
|
49772a7aba4ddea9f58a09193f7288e2f4acd28c
|
ca0143269a6db21e8609f63d4b5d685e2cdeade2
|
refs/heads/master
|
<file_sep># Code for "DEFIne: A Fluent Interface DSL for Deep Learning Applications".
This repository contains the code for the following paper:
<NAME> and <NAME> (2017) DEFIne: A Fluent Interface DSL for Deep Learning Applications. Proceedings of the 2nd International Workshop on Real World Domain Specific Languages. ACM Digital Library International Conference Proceedings Series (ICPS). Austin, Texas, US.
See link here: https://dl.acm.org/doi/10.1145/3039895.3039898
The basic idea with this paper is to shorten the process from idea to implementation of well-understood standard neural
network architectures for new tasks or datasets. DEFIne provides a set of simple commands that can be combined and
chained together to pre-process a new dataset, compare a variety of neural networks, generate benchmark results and
visualisations. It is build in Python on top of deep learning libraries Keras and Theano.
<figure>
<img src="/img/architecture.png" alt="drawing" width="400"/>
<figcaption>
<em>Architecture for code optimisation and generation.</em>
</figcaption>
</figure>
</br></br></br>
In the paper, we present a proof-of-concept results for heart disease diagnosis, hand-written digit recognition and
weather forecast generation. Results in terms of accuracy, runtime and lines of code show that our domain-specific language (DSL)
achieves equivalent accuracy and runtime to state-of-the-art models, while requiring only about 10 lines of code per application.
<figure>
<img src="/img/results.png" alt="drawing" width="400"/>
<figcaption>
<em>Performance results (including hyper-parameter optimisation and runtime comparison) in a number of domains.</em>
</figcaption>
</figure>
</br></br></br>
# Code
DEFIne can be run from the <code>test.py</code> example file. The <code>config</code> files (any format) contains default values.
<figure>
<img src="/img/code.png" alt="drawing" width="400"/>
<figcaption>
<em>Minimal DEFIne code example for training a 2-layered multi-layer perceptron. </em>
</figcaption>
</figuer>
</br></br></br>
The <code>data_repository</code> contains example datasets for a variety of classification and regression tasks.
Models can be trained from scratch (using <code>text.py</code>) or from prior knowledge. For the latter, please
use <code>from_prior.py</code>. Json files <code>knowledge.json</code> and <code>knowledge_regression.json</code> contain pre-trained models to facilitate
and accelerate training of new models, but need not be adapted.
This is a later version of code that adds hyper-parameter optimisation and model definition from configuration files beyond what
was presented in the paper.
<file_sep>from dataSet import *
from deepLearner import *
from dataRepository import *
import os
import numpy as np
from keras.optimizers import SGD
import time
from keras.datasets import mnist
import sys
'''
Code to train a deep learner with hyper-parameter optimisation using only those hyper-parameters
that were good predictors of performance in the most similar dataset in previous experiments.
It will gather basic statistics about the target dataset: inputs, outputs, instances, distribution, skew etc.
Then it will look into knowledge.json and find (based on the "normalised" vector) whatever the most similar dataset is.
It then inherits those hyper-parameters for optimisation that had a length scale of no more than 3.
Nina, 22 Nov 2017.
'''
data_repo = DataRepository()
data_repo.load('imdb_out.txt')
X_set = np.asarray(data_repo.X_set)
Y_set = np.asarray(data_repo.Y_set)
start_time = time.time()
data = DataSet(X_set, Y_set, 'classification')
data.representData().shuffleAndSplit()
print('-'*50)
# now choose and compile a deep learning model, train it and save the outputs.
print('(DeepLearner)')
parameters = {
'model_name' : 'heart',
'model_string' : 'MLP',
'prediction' : data.prediction
}
test = data.getNormalisedVector()
print('test',test)
sys.exit(0)
json_data=open("knowledge_regression.json").read()
kdata = json.loads(json_data)
#for d in kdata:
# i = getImportantParameters(kdata[d])
# print(d, "=", i)
# v = getDataVector(kdata[d])
# print(v)
# print('euclidean', euclideanDistance(test, v))
# print('cosine', cosineDistance(test, v))
deep = defineDL(parameters).designModel(data).compileModel()
dataset, similar = deep.getMostSimilarDataset(test, kdata)
#dataset, similar = getMostSimilarDataset(test, kdata)
#print(dataset, similar)
i = deep.getImportantParameters(kdata[dataset])
# Use this to train with given parameters.
#deep = defineDL(parameters).designModel(data).compileModel().trainModel(data, output_file='model-weights.h5', verbose=False)
#deep.trainModel(data, output_file='out-weights.h5', verbose=False)
print("--- %s seconds ---" % (time.time() - start_time))
<file_sep>from dataSet import *
from deepLearner import *
from dataRepository import *
import os
import numpy as np
from keras.optimizers import SGD
import time
from keras.datasets import mnist
import sys
'''
Some code that creates an MLP to train on eeg eyes classification dataset.
Nina, 20 Dec 2017.
'''
data_repo = DataRepository()
data_repo.load('eeg_eyes.txt')
X_set = np.asarray(data_repo.X_set)
Y_set = np.asarray(data_repo.Y_set)
print('-'*50)
print('Designing model: ***', 'eeg_eyes', '***')
print('(DataSet)')
start_time = time.time()
# analyse data and represent as needed, count some items we need to know.
data = DataSet(X_set, Y_set, 'classification')
data.representData().shuffleAndSplit()
print('-'*50)
# now choose and compile a deep learning model, train it and save the outputs.
print('(DeepLearner)')
parameters = {
'model_name' : 'eeg_eyes_mlp',
'modelString' : 'MLP',
'prediction' : data.prediction
}
# Use this to train with given parameters.
defineDL(parameters).designModel(data).compileModel().trainModel(data, output_file='model-weights.h5', verbose=False)
print("--- %s seconds ---" % (time.time() - start_time))
<file_sep>from dataSet import *
from deepLearner import *
from dataRepository import *
import os
import numpy as np
from keras.optimizers import SGD
import time
from keras.datasets import mnist
import sys
'''
Some code that tests the new dataRepository class using data from here: http://archive.ics.uci.edu/ml/
Datasets include some classification tasks and regression tasks.
Should all run on MLP, recurrent models (RNN, LSTM and GRU) in either a multithreaded or single-threaded setting.
Nina, 13 June 2017.
'''
data_repo = DataRepository()
data_repo.load('eeg_eyes.txt')
X_set = np.asarray(data_repo.X_set)
Y_set = np.asarray(data_repo.Y_set)
print('-'*50)
print('Designing model: ***', 'eeg_eyes', '***')
print('(DataSet)')
start_time = time.time()
# analyse data and represent as needed, count some items we need to know.
data = DataSet(X_set, Y_set, 'classification')
data.representData().shuffleAndSplit()
print('-'*50)
# now choose and compile a deep learning model, train it and save the outputs.
print('(DeepLearner)')
parameters = {
'model_name' : 'eeg_eyes_mlp',
'modelString' : 'MLP',
'prediction' : data.prediction
}
# Use this to do hyper-parameter optimisation.
# Method create_model4hyperOpt takes a list of parameters to optimise.
deep = defineDL(parameters)
def create_model4hyperOpt(learning_rate=deep.learning_rate, momentum=deep.momentum, init_mode=deep.init_mode, activation1=deep.activation1, activation2=deep.activation2, dropout_rate=deep.dropout_rate, weight_constraint=deep.weight_constraint, hidden_size=deep.hidden_size, loss=deep.loss, optimiser=deep.optimiser, epochs=deep.epochs, batch_size=deep.batch_size, layers=deep.layers, modelString=deep.modelString):
deep.designModel(data).compileModel()
return deep.model
best = deep.hyperOptimise(create_model4hyperOpt, data.X_set, data.Y_set, ['optimiser', 'layers', 'dropout_rate', 'weight_constraint', 'hidden_size', 'learning_rate', 'momentum', 'init_mode', 'activation_1', 'activation_2', 'loss', 'epochs', 'batch_size'], verbose=1, search='random', multithreaded=True)
#deep.updateParameters(best[1])
#deep.trainModel(data, output_file='heart_disease-weights.h5', verbose=False)
print("--- %s seconds ---" % (time.time() - start_time))
<file_sep>from dataSet import *
from dataRepository import *
import numpy as np
import sys
import json
'''
Lazy way to produce knowledge.json files for hyperparameter transfer.
'''
def all_numeric(labels):
print("Test if outputs are all numeric.")
types = [isinstance(n, numbers.Number) for n in labels]
if not False in types:
return True
else:
return False
features = {
1 : 'search',
2 : 'init_mode',
3 : 'loss',
4 : 'modelString',
5 : 'epochs',
6 : 'learning_rate',
7 : 'batch_size',
8 : 'dropout_rate',
9 : 'hidden_size',
10 : 'layers',
11 : 'optimiser',
12 : 'momentum',
13 : 'activation1',
14 : 'activation2',
15 : 'weight_constraint',
16 : 'fit_time',
17 : 'cpu_cores',
18 : 'search_algorithm',
19 : 'search_space',
20 : 'hardware',
21 : 'learning_tasks',
22 : 'size_of_datasets',
23 : 'input_features',
24 : 'output_features',
25 : 'data_type',
26 : 'vocab_size',
27 : 'dimensionality',
28 : 'score',
}
print(features)
dict = {}
infile_gp = open("results_regression.txt", "r")
counter = 1
for line in infile_gp:
if line.replace("\n", "").endswith(".txt"):
counter = 1
name = line.replace("\n", "")
dict[name] = {}
if line.startswith("beeest"):
dict[name][features[counter]] = line.replace("\n", "").replace("beeest1**2 * RBF", "")
counter = counter + 1
print(dict)
print(len(dict))
infile_gp.close()
def normalized(a, axis=-1, order=2):
l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
l2[l2==0] = 1
return a / np.expand_dims(l2, axis)
for key in dict:
print("Analysing dataset:", key)
data_vector = []
infile_stats = key
data_repo = DataRepository()
data_repo.load(infile_stats)
X_set = np.asarray(data_repo.X_set)
Y_set = np.asarray(data_repo.Y_set)
data = DataSet(X_set, Y_set, 'regression')
data.representData()
prediction = 1
input_features = data.max_len
output_features = data.outputs
# dimensionality = data.dimensionality
data_type = data.data_type
instances = len(data.X_set)
vocab_size = len(data.vocab)
mean = data.mean_X
median = data.median_X
std = data.stds_x
iqr = data.iqr_x
skew = data.skew_x
kurtosis = data.kurtosis_x
label_distribution = data.label_distribution
normal_distribution = data.normal_distribution
print('normal', normal_distribution)
if normal_distribution == True:
normal_distribution = 1
else:
normal_distribution = 0
if all_numeric(set(data_repo.Y_set)):
if(len(set(data_repo.Y_set))) < 11:
prediction = 1
else:
prediction = 0
if data_type == "numeric":
data_type = 0
else:
data_type = 1
print("prediction", prediction)
data_vector.append(prediction)
print("input_features", input_features)
data_vector.append(input_features)
print("output_features", output_features)
data_vector.append(output_features)
# print("dimensionality", dimensionality)
print("data_type", data_type)
data_vector.append(data_type)
print("instances", instances)
data_vector.append(instances)
print("vocab_size", vocab_size)
data_vector.append(vocab_size)
print("mean", mean)
data_vector.append(mean)
print("median", median)
data_vector.append(median)
print("std", std)
data_vector.append(std)
print("iqr", iqr)
data_vector.append(iqr)
print("skew", skew)
data_vector.append(skew)
print("kurtosis", kurtosis)
data_vector.append(kurtosis)
print("label_distribution", label_distribution)
print("normal_distribution", normal_distribution)
data_vector.append(normal_distribution)
normalised = normalized(data_vector)
dict[key]['normalised'] = str(normalised)
print(key, dict[key])
with open('knowledge_regression.json', 'w') as k:
json.dump(dict , k)
<file_sep>from dataSet import *
from deepLearner import *
from dataRepository import *
from keras.optimizers import SGD
import time
import json, yaml
from bs4 import BeautifulSoup
import sys
'''
Added code to extract parameters from various configuration file inputs: json, yaml, xml.
This will hopefully be the simplest possible way to configure a deep learner, and can also
act as a baseline to later DSL approaches...
Nina, 26 June 2017.
'''
def isFloat(value):
try:
float(value)
return True
except ValueError:
return False
def isInt(value):
try:
int(value)
return True
except ValueError:
return False
def toBool(val):
if val=="True" or val=='True' or val==True:
return True
else:
return False
start_time = time.time()
print("--- %s seconds ---" % (time.time() - start_time))
# Example 1: create deep learner from json file
def create_from_json(file):
config = {}
with open(file) as json_data_file:
config = json.load(json_data_file)
for c in config['setup']:
config['setup'][c] = toBool(config['setup'][c])
return config
# Example 2: create deep learner from yaml file
def create_from_yaml(file):
config = {}
with open(file, 'r') as ymlfile:
config = yaml.load(ymlfile)
for c in config['setup']:
config['setup'][c] = toBool(config['setup'][c])
return config
# Example 3: create deep learner from xml file
# (slightly more complicated)
def create_from_xml(file):
config = {}
with open(file) as f:
content = f.read()
y = BeautifulSoup(content, "lxml")
dl_parameters = {}
dataset = {}
setup = {}
hyperparameter_setup = {}
for element in y.dl_parameters:
if not element=='\n':
if isInt(element.contents[0]):
dl_parameters[element.name] = int(element.contents[0])
elif isFloat(element.contents[0]):
dl_parameters[element.name] = float(element.contents[0])
else:
dl_parameters[element.name] = element.contents[0]
for element in y.dataset:
if not element=='\n':
dataset[element.name] = element.contents[0]
for element in y.x_setup:
if not element=='\n':
setup[element.name] = element.contents[0]
for element in y.hyperparameter_setup:
if not element=='\n':
hyperparameter_setup[element.name] = element.contents[0]
config['dl_parameters'] = dl_parameters
config['dataset'] = dataset
config['setup'] = setup
for c in config['setup']:
config['setup'][c] = toBool(config['setup'][c])
config['hyperparameter_setup'] = hyperparameter_setup
return config
################################################################
# Here the input file please...
file = 'config.json'
################################################################
# Parameters to be read in from configuration file...
config = {}
if file.endswith('.json'):
print('Reading configuration from file', file, '...')
config = create_from_json(file)
elif file.endswith('.yml'):
print('Reading configuration from file', file, '...')
config = create_from_yaml(file)
elif file.endswith('.xml'):
print('Reading configuration from file', file, '...')
config = create_from_xml(file)
else:
print('Error - input file needs to be one of .json, .yml or .xml')
# From hereon using information provided to arrange data and create a learning agent.
data_repo = DataRepository()
data_repo.load(config['dataset']['path'])
data = DataSet(data_repo.X_set, data_repo.Y_set, config['dl_parameters']['prediction'])
data.representData().shuffleAndSplit()
#data.visualise()
deep = defineDL(config['dl_parameters'])
if config['setup']['hyperparameters']:
print('Optimising hyperparameters...')
def create_model4hyperOpt(learning_rate=deep.learning_rate, momentum=deep.momentum, init_mode=deep.init_mode, activation1=deep.activation1, activation2=deep.activation2, dropout_rate=deep.dropout_rate, weight_constraint=deep.weight_constraint, hidden_size=deep.hidden_size, loss=deep.loss, optimiser=deep.optimiser, epochs=deep.epochs, batch_size=deep.batch_size, layers=deep.layers, model_string=deep.model_string):
deep.designModel(data).compileModel()
return deep.model
best = deep.hyperOptimise(create_model4hyperOpt, data.X_set, data.Y_set, ['optimiser', 'layers', 'dropout_rate', 'weight_constraint', 'hidden_size', 'learning_rate', 'momentum', 'init_mode', 'activation_1', 'activation_2', 'loss', 'epochs', 'batch_size'], verbose=config['hyperparameter_setup']['verbose'], search=config['hyperparameter_setup']['search'], multithreaded=config['setup']['multithreaded'], logging=config['hyperparameter_setup']['logging'])
deep.updateParameters(best[1])
if config['setup']['train']:
print('Training with updated hyperparameters...')
deep.trainModel(data, output_file=config['dataset']['weights_out'], verbose=config['setup']['verbose'])
else:
deep.designModel(data).compileModel()
if config['setup']['train']:
print('Training with specified parameters...')
deep.trainModel(data, output_file=config['dataset']['weights_out'], verbose=config['setup']['verbose'])
print("--- %s seconds ---" % (time.time() - start_time))
<file_sep>import numpy as np
from keras.preprocessing import sequence
from keras.engine.training import _slice_arrays
import numbers
from keras.utils import np_utils
import sys
from sklearn.preprocessing import *
class DataRepository:
def __init__(self):
self.repository_path = './data_repository/'
self.X_set = []
self.Y_set = []
def isFloat(self, value):
try:
float(value)
return True
except ValueError:
return False
def isInt(self, value):
try:
int(value)
return True
except ValueError:
return False
def load(self, name):
X_set = []
Y_set = []
print('Loading dataset, attempting to determine features...')
for line in open(self.repository_path + name, 'r'):
data = line.split(',')[:-1]
x = []
for i in data:
if self.isInt(i):
x.append(int(i))
elif self.isFloat(i):
x.append(float(i))
else:
x.append(i)
X_set.append(x)
label = line.split(',')[-1].replace('\n', '')
if self.isInt(label):
Y_set.append(int(label))
elif self.isFloat(label):
Y_set.append(float(label))
else:
Y_set.append(label)
self.X_set = np.asarray(X_set)
self.Y_set = np.asarray(Y_set)
return self.X_set, self.Y_set
<file_sep>print(__doc__)
'''
Using scikit learn's Gaussian Process regressor and random search hyperparameter optimisation to find the identify
length scales from experiments on source datasets and find the most predictive hyperparameters for source datasets.
Nina, 20 Dec 2017.
'''
import numpy as np
import pandas
import sys
import os
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, ConstantKernel as C
from sklearn.metrics import mean_squared_error, mean_absolute_error
np.random.seed(1)
features = {
'name' : 0,
'search' : 1,
'init_mode' : 2,
'loss' : 3,
'modelString' : 4,
'epochs' : 5,
'learning_rate' : 6,
'batch_size' : 7,
'dropout_rate' : 8,
'hidden_size' : 9,
'layers' : 10,
'optimiser' : 11,
'momentum' : 12,
'activation1' : 13,
'activation2' : 14,
'weight_constraint' : 15,
'fit_time' : 16,
'cpu_cores' : 17,
'search_algorithm' : 18,
'search_space' : 19,
'hardware' : 20,
'learning_tasks' : 21,
'size_of_datasets' : 22,
'input_features' : 23,
'output_features' : 24,
'data_type' : 25,
'vocab_size' : 26,
'dimensionality' : 27,
'score' : 28,
}
def loadData(file, feature):
infile = open('./gp_data_regression/bike_sharing_day.txt', 'r')
X_set = []
Y_set = []
for line in infile:
data = line.replace("\n", "").split(",")
# x_data = data[1:-1]
x_data = data[features[feature]]
# new_x = []
# for x in x_data:
# new_x.append(float(x))
X_set.append(float(x_data))
label = data[-1]
Y_set.append(float(label))
infile.close()
return X_set, Y_set
X = []
Y = []
def create_gp(kernel=C(1.0, (1e-3, 1e3)) * RBF(10, (1e-2, 1e2))):
gp1 = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=9)
return gp1
results_file = open("results_regression.txt", 'w')
output = []
for f in os.listdir("./gp_data_regression/"):
print(f)
if f.endswith(".txt"):
print("Reading dataset", f)
output.append(str(f))
output.append("================================")
for fea in features:
if not fea=="name":
X, Y = loadData(f, fea)
X = np.asarray(X)
X = np.atleast_2d(X).T
y = np.asarray(Y)
print(X, y)
output.append(X)
output.append(y)
gp1 = create_gp(kernel=C(1.0, (1e-3, 1e3)) * RBF(10, (1e-2, 1e2)))
param_grid = dict(kernel=[C(1.0, (1e-3, 1e3)) * RBF(1.0, (1e-2, 1e2)), C(1.0, (1e-3, 1e3)) * RBF(2.0, (1e-2, 1e2)), C(1.0, (1e-3, 1e3)) * RBF(3.0, (1e-2, 1e2)), C(1.0, (1e-3, 1e3)) * RBF(4.0, (1e-2, 1e2)), C(1.0, (1e-3, 1e3)) * RBF(5.0, (1e-2, 1e2)), C(1.0, (1e-3, 1e3)) * RBF(6.0, (1e-2, 1e2)), C(1.0, (1e-3, 1e3)) * RBF(7.0, (1e-2, 1e2)), C(1.0, (1e-3, 1e3)) * RBF(8.0, (1e-2, 1e2)), C(1.0, (1e-3, 1e3)) * RBF(9.0, (1e-2, 1e2)), C(1.0, (1e-3, 1e3)) * RBF(10.0, (1e-2, 1e2))])
grid = GridSearchCV(estimator=gp1, param_grid=param_grid, n_jobs=1, cv=2)
grid_result = grid.fit(X, y)
means = grid_result.cv_results_['mean_test_score']
stds = grid_result.cv_results_['std_test_score']
params = grid_result.cv_results_['params']
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
output.append("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
for mean, stdev, param in zip(means, stds, params):
print("%f (%f) with: %r" % (mean, stdev, param))
print('beeest', grid_result.best_params_['kernel'])
output.append('beeest' + str(grid_result.best_params_['kernel']))
output.append("================================")
for o in output:
print(o)
results_file.writelines(str(o) + "\n")
output = []
results_file.close()
def f(x):
"""The function to predict."""
return x * np.sin(x)
# Mesh the input space for evaluations of the real function, the prediction and
# its MSE
x = np.atleast_2d(np.linspace(0, 10, 1000)).T
# Instanciate a Gaussian Process model
kernel=C(1.0, (1e-3, 1e3)) * RBF(10.0, (1e-2, 1e2))
gp = GaussianProcessRegressor(kernel=kernel, n_restarts_optimizer=9)
# Fit to data using Maximum Likelihood Estimation of the parameters
gp.fit(X, y)
# Make the prediction on the meshed x-axis (ask for MSE as well)
y_pred, sigma = gp.predict(x, return_std=True)
# Plot the function, the prediction and the 95% confidence interval based on
# the MSE
fig = plt.figure()
plt.plot(x, f(x), 'r:', label=u'$f(x) = x\,\sin(x)$')
plt.plot(X, y, 'r.', markersize=10, label=u'Observations')
plt.plot(x, y_pred, 'b-', label=u'Prediction')
plt.fill(np.concatenate([x, x[::-1]]),
np.concatenate([y_pred - 1.9600 * sigma,
(y_pred + 1.9600 * sigma)[::-1]]),
alpha=.5, fc='b', ec='None', label='95% confidence interval')
plt.xlabel('$x$')
plt.ylabel('$f(x)$')
plt.ylim(-10, 20)
plt.legend(loc='upper left')
plt.show()<file_sep>from keras.models import Sequential
from keras.layers import Activation, TimeDistributed, Dense, RepeatVector, recurrent, Embedding, Flatten, Reshape, Dropout
import datetime, time
import numpy as np
from keras.constraints import maxnorm
from keras.optimizers import SGD, Adam, RMSprop, Adagrad, Adadelta, Adamax, Nadam
from keras.wrappers.scikit_learn import KerasClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import RandomizedSearchCV
import multiprocessing
import json
import sys
from scipy import spatial
from scipy.spatial import distance
class DeepLearner:
def __init__(self, model_string, layers=2, batch_size=32, epochs=50, dropout_rate=0.0, weight_constraint=5, hidden_size=128, embedding_size=1000, learning_rate = 0.01, momentum= 0.9, optimiser='adam', init_mode='uniform', activation1='relu', activation2='sigmoid', loss="mean_squared_error", eval_metrics=['accuracy'], model_name='model_1', prediction='regression'):
self.model_string = model_string
self.model_name = model_name
self.model = ''
self.layers = layers
self.batch_size = batch_size
self.epochs = epochs
self.hidden_size = hidden_size
self.embedding_size = embedding_size
self.learning_rate = learning_rate
self.momentum = momentum
self.loss = loss
self.eval_metrics = eval_metrics
self.dropout_rate = dropout_rate
self.weight_constraint = weight_constraint
self.optimiser = Adam(learning_rate)
self.init_mode = init_mode
self.activation1 = activation1
self.activation2 = activation2
self.prediction = prediction
def designModel(self, dataset):
# Based on data representation, choose the best model to design.
if dataset.dimensionality=='3D':
self.designSeq2Seq(dataset.max_len, dataset.vocab)
# two paths for 2D models, recurrent or not.
elif self.model_string=='MLP':
self.designMLP(dataset.max_len, dataset.outputs)
else:
self.designRNN(dataset.max_len, dataset.outputs)
return self
def designSeq2Seq(self, max_len, vocab):
# Puts together a model that learns to map an input sequence to an output sequence. Requires 3D input matrices.
print('Designing a(n) sequence-to-sequence', self.model_string, 'with', self.layers, 'layers,', self.hidden_size, 'hidden nodes, and', self.activation1, 'activation.')
RNN = recurrent.LSTM
if self.model_string=='LSTM':
RNN = recurrent.LSTM
elif self.model_string=='RNN':
RNN = recurrent.SimpleRNN
elif self.model_string=='GRU':
RNN = recurrent.GRU
self.model = Sequential()
self.model.add(RNN(self.hidden_size, input_shape=(max_len, len(vocab))))
self.model.add(RepeatVector(max_len))
for _ in range(self.layers):
self.model.add(RNN(self.hidden_size, return_sequences=True))
self.model.add(TimeDistributed(Dense(len(vocab))))
self.model.add(Activation(self.activation1))
# self.model.summary()
return self.model
def designRNN(self, max_len, outputs):
# Puts together a model that learns to map an input sequence to a single output value. Requires 2D input matrices.
print('Designing a(n) ', self.model_string, 'with', self.layers, 'layers,', self.hidden_size, 'hidden nodes, and', self.activation1, ' activation.')
RNN = recurrent.LSTM
if self.model_string=='LSTM':
RNN = recurrent.LSTM
elif self.model_string=='RNN':
RNN = recurrent.SimpleRNN
elif self.model_string=='GRU':
RNN = recurrent.GRU
self.model = Sequential()
self.model.add(Embedding(self.embedding_size, self.hidden_size, input_length=max_len))
self.model.add(Dropout(self.dropout_rate))
self.model.add(RNN(self.hidden_size, recurrent_dropout=0.2, dropout=0.2))
self.model.add(RepeatVector(max_len))
for _ in range(self.layers):
self.model.add(RNN(self.hidden_size, return_sequences=True))
self.model.add(Flatten())
if self.prediction=='regression':
self.model.add(Dense(1))
else:
self.model.add(Dense(outputs))
self.model.add(Activation(self.activation1))
# self.model.summary()
return self.model
def designMLP(self, max_len, outputs):
# Puts a model together that learns to map an input sequence to an output sequence. Requires 3D input matrices.
print('Designing a(n) ', self.model_string, 'with', self.layers, 'layers,', self.hidden_size, 'hidden nodes, and', self.activation1, ' activation.')
self.model = Sequential()
self.model.add(Dense(self.hidden_size, input_dim=max_len, kernel_initializer=self.init_mode, activation=self.activation1 ))
self.model.add(Dropout(self.dropout_rate))
if self.layers == 2:
self.model.add(Dense(self.hidden_size, input_dim=max_len, kernel_initializer=self.init_mode, activation=self.activation1 ))
self.model.add(Dropout(self.dropout_rate))
if self.layers == 3:
self.model.add(Dense(self.hidden_size, input_dim=max_len, kernel_initializer=self.init_mode, activation=self.activation1 ))
self.model.add(Dropout(self.dropout_rate))
if self.layers > 3:
print('Not doing MLPs with more than 3 layers now - it is no use anyway...')
if self.prediction=='regression':
self.model.add(Dense(1, kernel_initializer=self.init_mode, activation=self.activation2))
else:
self.model.add(Dense(outputs, kernel_initializer=self.init_mode, activation=self.activation2))
self.model.compile(loss=self.loss, optimizer=self.optimiser, metrics=self.eval_metrics)
print(self.model.summary())
# self.model.summary()
return self.model
def designMLP3D(self, max_len):
# Puts a model together that learns to map an input sequence to an output sequence. Requires 3D input matrices.
print('Designing a(n) ', self.model_string, 'with', self.layers, 'layers,', self.hidden_size, 'hidden nodes, and', self.activation1, 'activation.')
self.model = Sequential()
self.model.add(Dense(self.hidden_size, input_shape=(max_len,)))
self.model.add(Activation(self.activation1))
self.model.add(Dropout(0.2))
self.model.add(Dense(512))
self.model.add(Activation('relu'))
self.model.add(Dropout(0.2))
self.model.add(Dense(10))
self.model.add(Activation(self.activation2))
# self.model.summary()
return self.model
def compileModel(self):
# Compiles the model ready for training or testing with the chosen optimisation and training parameters.
print('Model is ready to train (or test), using', self.loss, ',', self.optimiser, 'optimisation, and evaluating', self.eval_metrics, '.')
if self.prediction =='regression':
self.loss = 'mean_absolute_error'
self.model.compile(loss=self.loss,
optimizer=self.optimiser,
metrics=self.eval_metrics)
return self
def loadWeights(self, model, file):
print("Loading pre-trained weights from ", file)
self.model.load_weights(file)
return self.model.get_weights()
def trainModel(self, data, output_file='out.txt', verbose=True):
if verbose:
self.trainVerbose(data.X_train, data.Y_train, data.X_val, data.Y_val, data.indices_char, data.dimensionality, output_file)
else:
self.train(data.X_train, data.Y_train, data.X_val, data.Y_val, output_file)
def train(self, X_train, Y_train, X_val, Y_val, output_file='out.txt'):
# Actually trains for a given number of epochs.
#print X_train
print('Started training at:', (time.strftime("%d/%m/%Y")), (time.strftime("%H:%M:%S")))
for iteration in range(1, self.epochs):
print()
print('-' * 50)
print('Iteration', iteration)
self.model.fit(X_train, Y_train, batch_size=self.batch_size, nb_epoch=1, validation_data=(X_val, Y_val))
score, acc = self.model.evaluate(X_val, Y_val, batch_size=self.batch_size)
json_string = self.model.to_json()
self.model.save_weights(output_file, overwrite=True)
print('Test score:', score)
print('Test accuracy:', acc)
print('Finished at:', (time.strftime("%d/%m/%Y")), (time.strftime("%H:%M:%S")))
def decode3D(self, X, indices_char, calc_argmax=True):
# this decodes 3D items.
if calc_argmax:
X = X.argmax(axis=-1)
return ' '.join(indices_char[x] for x in X)
def decode2D(self, X_item, indices_char):
# this decodes 2D X items.
new_X = []
for x in X_item:
new = indices_char[int(x)]
new_X.append(new)
new_X = ' '.join(new_X).replace('mask_zeros', '')
return ' '.join(new_X.split())
def trainVerbose(self, X_train, Y_train, X_val, Y_val, indices_char, dimensionality, output_file='out.txt'):
if dimensionality=='3D':
self.trainVerbose3D(X_train, Y_train, X_val, Y_val, indices_char, output_file)
else:
self.trainVerbose2D(X_train, Y_train, X_val, Y_val, indices_char, output_file)
def trainVerbose2D(self, X_train, Y_train, X_val, Y_val, indices_char, output_file='out.txt'):
# Actually trains for a given number of epochs and prints some example tests after each epoch.
#print X_train
print('Started training at:', (time.strftime("%d/%m/%Y")), (time.strftime("%H:%M:%S")))
numeric = False
if type(X_train) is np.ndarray:
numeric = True
for iteration in range(1, self.epochs):
print()
print('-' * 50)
print('Iteration', iteration)
self.model.fit(X_train, Y_train, batch_size=self.batch_size, nb_epoch=1, validation_data=(X_val, Y_val))
score, acc = self.model.evaluate(X_val, Y_val, batch_size=self.batch_size)
# Select 10 samples from the validation set at random to visualise and inspect.
for i in range(10):
ind = np.random.randint(0, len(X_val))
rowX, rowy = X_val[np.array([ind])], Y_val[np.array([ind])]
print(rowX, rowy)
preds = self.model.predict_classes(rowX, verbose=0)
if numeric:
q = rowX[0]
else:
q = self.decode2D(rowX[0], indices_char)
print(rowy[0], preds[0])
correct = int(rowy[0])
guess = int(preds[0])
print()
print('Input vector: ', q)
print('Correct label: ', correct)
print('Predicted label: ' + str(guess) + ' (good)' if correct == guess else 'Predicted label: ' + str(guess) + ' (bad)' )
print('---')
json_string = self.model.to_json()
self.model.save_weights(output_file, overwrite=True)
print('Test score:', score)
print('Test accuracy:', acc)
print('Finished at:', (time.strftime("%d/%m/%Y")), (time.strftime("%H:%M:%S")))
def trainVerbose3D(self, X_train, Y_train, X_val, Y_val, indices_char, output_file='out.txt'):
# Actually trains for a given number of epochs and prints some example tests after each epoch.
#print X_train
print('Started training at:', (time.strftime("%d/%m/%Y")), (time.strftime("%H:%M:%S")))
for iteration in range(1, self.epochs):
print()
print('-' * 50)
print('Iteration', iteration)
self.model.fit(X_train, Y_train, batch_size=self.batch_size, nb_epoch=1, validation_data=(X_val, Y_val))
score, acc = self.model.evaluate(X_val, Y_val, batch_size=self.batch_size)
# Select 10 samples from the validation set at random to visualise and inspect.
for i in range(10):
ind = np.random.randint(0, len(X_val))
rowX, rowy = X_val[np.array([ind])], Y_val[np.array([ind])]
preds = self.model.predict_classes(rowX, verbose=0)
q = self.decode3D(rowX[0], indices_char)
correct = self.decode3D(rowy[0], indices_char)
guess = self.decode3D(preds[0], indices_char, calc_argmax=False)
print()
print('Input vector: ', q)
print('Correct label: ', correct)
print('Predicted label: ' + str(guess) + ' (good)' if correct == guess else 'Predicted label: ' + str(guess) + ' (bad)' )
print('---')
json_string = self.model.to_json()
self.model.save_weights(output_file, overwrite=True)
print('Test score:', score)
print('Test accuracy:', acc)
print('Finished at:', (time.strftime("%d/%m/%Y")), (time.strftime("%H:%M:%S")))
def hyperOptimise(self, model, X_set, Y_set, paras4Op, verbose=False, search='grid', multithreaded=True, logging=True, cv=5, n_iter=50):
start_time = time.time()
if multithreaded==True:
n_jobs = -1
else:
n_jobs = 1
# picking up some values in case config file got type wrong...
if verbose=='True' or verbose==True:
verbose = 1
else:
verbose = 0
if logging=='True' or logging==True:
logging=True
else:
logging = False
kerasmodel = KerasClassifier(build_fn=model, verbose=verbose)
if 'init_mode' in paras4Op:
init_mode = ['uniform', 'lecun_uniform', 'normal', 'zero', 'glorot_normal', 'glorot_uniform', 'he_normal', 'he_uniform']
# init_mode = ['uniform']
else:
init_mode = [self.init_mode]
if 'weight_constraint' in paras4Op:
# weight_constraint = [1]
weight_constraint = [1, 2, 3, 4, 5]
else:
weight_constraint = [self.weight_constraint]
if 'dropout_rate' in paras4Op:
# dropout_rate = [0.0]
dropout_rate = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]
else:
dropout_rate = [self.dropout_rate]
if 'learning_rate' in paras4Op:
# learning_rate = [0.001]
learning_rate = [0.001, 0.01, 0.1, 0.2, 0.3]
else:
learning_rate = [self.learning_rate]
if 'momentum' in paras4Op:
# momentum = [0.0]
momentum = [0.0, 0.2, 0.4, 0.6, 0.8, 0.9]
else:
momentum = [self.momentum]
if 'hidden_size' in paras4Op:
# hidden_size = [1]
hidden_size = [1, 5, 10, 15, 20, 25, 30, 50, 100, 150, 200]
else:
hidden_size = [self.hidden_size]
if 'batch_size' in paras4Op:
# batch_size= [10]
batch_size= [10, 20, 40, 60, 80, 100]
else:
batch_size = [self.batch_size]
if 'epochs' in paras4Op:
# epochs = [10]
epochs = [10, 20, 50, 100]
else:
epochs = [self.epochs]
if 'activation1' in paras4Op:
# activation1 = ['softmax']
activation1 = ['softmax', 'softplus', 'softsign', 'relu', 'tanh', 'sigmoid', 'hard_sigmoid', 'linear']
else:
activation1 = [self.activation1]
if 'activation2' in paras4Op:
# activation2 = ['relu']
activation2 = ['softmax', 'softplus', 'softsign', 'relu', 'tanh', 'sigmoid', 'hard_sigmoid', 'linear']
else:
activation2 = [self.activation2]
if 'optimiser' in paras4Op:
# optimiser = ['Adam', 'SGD']
# optimiser = ['SGD']
optimiser = ['SGD', 'RMSprop', 'Adagrad', 'Adadelta', 'Adam', 'Adamax', 'Nadam']
else:
optimiser = [Adam(learning_rate, momentum)]
if 'loss' in paras4Op:
# loss = ['mean_squared_error']
loss = ['mean_squared_error', 'mean_absolute_error', 'mean_absolute_percentage_error', 'mean_squared_logarithmic_error', 'squared_hinge, hinge', 'logcosh', 'categorical_crossentropy', 'sparse_categorical_crossentropy', 'binary_crossentropy', 'kullback_leibler_divergence', 'poisson', 'cosine_proximity']
else:
loss = [self.loss]
if 'layers' in paras4Op:
# layers = [1]
layers = [1, 2, 3]
else:
layers = [self.layers]
if 'model_string' in paras4Op:
model_string = ['RNN', 'LSTM', 'GRU']
else:
model_string = [self.model_string]
param_grid = dict(optimiser=optimiser, init_mode=init_mode, weight_constraint=weight_constraint, dropout_rate=dropout_rate, learning_rate=learning_rate, momentum=momentum, hidden_size=hidden_size, batch_size=batch_size, epochs=epochs, activation1=activation1, activation2=activation2, loss=loss, layers=layers, model_string=model_string)
# add optimiser=optimiser to list, doesn't work currently
# grid = GridSearchCV(estimator=kerasmodel, param_grid=param_grid, n_jobs=-1)
if search=='random':
search_algorithm = RandomizedSearchCV(estimator=kerasmodel, param_distributions=param_grid, n_jobs=n_jobs, cv=cv, n_iter=n_iter)
else:
search_algorithm = GridSearchCV(estimator=kerasmodel, param_grid=param_grid, n_jobs=n_jobs, cv=cv)
search_space = len(init_mode) * len(weight_constraint) * len(dropout_rate) * len(optimiser) * len(batch_size) * len(epochs) * len(learning_rate) * len(momentum) * len(activation1) * len(activation2) * len(loss) * len(hidden_size) * len(layers) * len(model_string)
print('Using all possible parameters, searching a space of', search_space, ' options...')
print('X', X_set.shape)
print('Y', Y_set.shape)
search_result = search_algorithm.fit(X_set, Y_set)
print("Best: %f using %s" % (search_result.best_score_, search_result.best_params_))
print("Optimised parameters", param_grid, '.')
means = search_result.cv_results_['mean_test_score']
fit_times = search_result.cv_results_['mean_fit_time']
stds = search_result.cv_results_['std_test_score']
params = search_result.cv_results_['params']
for mean, stdev, param in zip(means, stds, params):
print("%f (%f) with: %r" % (mean, stdev, param))
if logging==True:
self.logHyperParameters(self.model_name, search, search_space, start_time, (search_result.best_score_, search_result.best_params_), zip(means, params, fit_times), multithreaded, cv, n_iter)
return (search_result.best_score_, search_result.best_params_)
def logHyperParameters(self, model_name, search_algorithm, search_space, start_time, best_search, all_searches, multithreaded, cross_validation_folds, hyper_iterations):
outfile = open("./logs/"+model_name+".json", 'w')
# make sure models come out correctly...
general_parameters = {}
general_parameters['cpu_cores'] = multiprocessing.cpu_count()
general_parameters['search_algorithm'] = search_algorithm
general_parameters['search_space'] = search_space
general_parameters['best_result'] = best_search[0]
general_parameters['prediction'] = self.prediction
general_parameters['multithreaded'] = multithreaded
general_parameters['cross_validation_folds'] = cross_validation_folds
general_parameters['hyper_iterations'] = hyper_iterations
best_parameters = best_search[1]
for key in best_parameters:
general_parameters['best_'+key] = best_parameters[key]
x = 0
for mean, param, fit_time in all_searches:
x = x+1
m_name = 'search_'+str(x)
current_score = mean
current_parameters = param
dict = {}
dict['score'] = mean
dict['fit_time'] = fit_time
dict['param'] = param
general_parameters[m_name] = dict
run_time = (time.time() - start_time)
general_parameters['run_time'] = run_time
json.dump(general_parameters, outfile)
outfile.close()
print('\n Best model achieves', best_search[0], 'with parameters', best_search[1], '... yay! \n')
def getImportantParameters(self, dict):
parameters = ['init_mode', 'vocab_size', 'activation1', 'activation2', 'loss', 'hidden_size', 'momentum', 'layers', 'dropout_rate', 'epochs', 'learning_rate', 'optimiser', 'weight_constraint', 'batch_size']
length_scale_cutoff = 4
important = []
for d in dict:
if d in parameters:
feature = d
length_scale = int(str(dict[d]).replace("(length_scale=", "").replace(")", ""))
if length_scale < 3:
important.append(d)
return important
def getDataVector(self, dict):
vector = []
for d in dict:
if d=='normalised':
vector = dict[d]
vector = vector.replace("\n", "").replace("[", "").replace("]", "").split()
v = []
for ele in vector:
v.append(float(ele))
vector = np.array(v).flatten()
return vector
def getMostSimilarDataset(self, vector, dict, metric='euclidean'):
similar = 1000
dataset = ""
for d in dict:
v = self.getDataVector(dict[d])
if metric=='cosine':
s = 1 - spatial.distance.cosine(v, vector)
if s < similar:
similar = s
dataset = d
else:
s = distance.euclidean(v, vector)
if s < similar:
similar = s
dataset = d
return dataset, similar
def updateParameters(self, best):
for key in best:
if 'learning_rate' in key:
self.learning_rate = best[key]
elif 'momentum' in key:
self.momentum = best[key]
elif 'init_mode' in key:
self.init_mode = best[key]
elif 'activation1' in key:
self.activation1 = best[key]
elif 'activation2' in key:
self.activation2 = best[key]
elif 'dropout_rate' in key:
self.dropout_rate = best[key]
elif 'weight_constraint' in key:
self.weight_constraint = best[key]
elif 'hidden_size' in key:
self.hidden_size = best[key]
elif 'loss' in key:
self.loss = best[key]
elif 'optimiser' in key:
self.optimiser = best[key]
elif 'epochs' in key:
self.epochs = best[key]
elif 'batch_size' in key:
self.batch_size = best[key]
elif 'model_string' in key:
self.model_string = best[key]
elif 'layers' in key:
self.layers = best[key]
def defineDL(parameters):
models = ['LSTM', 'RNN', 'GRU', 'MLP']
dl = ""
st = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d-%H:%M:%S')
if not 'model_string' in parameters:
print("Error - you need to provide a model_string out of: ", models)
else:
model_string = parameters.get('model_string', 'MLP')
layers = parameters.get('layers', 2)
batch_size = parameters.get('batch_size', 32)
epochs = parameters.get('epochs', 20)
dropout_rate = parameters.get('dropout_rate', 0)
weight_constraint = parameters.get('weight_constraint', 0)
hidden_size = parameters.get('hidden_size', 20)
embedding_size = parameters.get('embedding_size', 10000)
learning_rate = parameters.get('learning_rate', 0.01)
momentum = parameters.get('momentum', 0.9)
optimiser = parameters.get('optimiser', 'adam')
if optimiser == 'SGD':
optimiser = SGD(learning_rate, momentum)
elif optimiser == 'RMSprop':
optimiser = RMSprop(learning_rate)
elif optimiser == 'Adagrad':
optimiser = Adagrad(learning_rate)
elif optimiser == 'Adadelta':
optimiser = Adadelta(learning_rate)
elif optimiser == 'Adamax':
optimiser = Adamax(learning_rate)
elif optimiser == 'Nadam':
optimiser = Nadam(learning_rate)
else:
optimiser = Adam(learning_rate)
init_mode = parameters.get('init_mode', 'uniform')
activation1 = parameters.get('activation1', 'relu')
activation2 = parameters.get('activation2', 'sigmoid')
loss = parameters.get('loss', 'categorical_crossentropy')
eval_metrics = parameters.get('eval_metrics', ['accuracy'])
model_name = parameters.get('model_name', 'model_'+st)
prediction = parameters.get('prediction', 'regression')
dl = DeepLearner(model_string, layers, batch_size, epochs, dropout_rate, weight_constraint, hidden_size, embedding_size, learning_rate, momentum, optimiser, init_mode, activation1, activation2, loss, eval_metrics, model_name, prediction)
return dl
<file_sep>import numpy as np
from keras.preprocessing import sequence
from keras.engine.training import _slice_arrays
import numbers
from keras.utils import np_utils
import sys
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.decomposition import PCA
from scipy import stats
from scipy.stats import iqr, kurtosis, skew
class DataSet:
def __init__(self, X_set, Y_set, prediction='classification'):
self.X_set = X_set
self.Y_set = Y_set
self.max_len = 0
self.X_train = []
self.X_val = []
self.Y_train = []
self.Y_val = []
self.text = 'mask_zeros '
self.vocab = set()
self.char_indices = {}
self.indices_char = {}
self.dimensionality = ''
self.outputs = 1
self.labels = []
if not hasattr(Y_set[0], '__iter__'):
self.outputs = len(set(Y_set))
self.prediction = prediction
self.data_type = 'numeric'
# determine number of symbols and maximum sequence length.
self.countSymbols()
self.countMaxLen()
# some other statistics about the datasets
self.mean_X = 0
self.median_X = 0
self.means = []
self.medians = []
self.modes = []
self.stds = []
self.stds_x = 0
self.iqr_x = 0
self.iqrs = []
self.normal_distribution = True
self.skew = 0
self.skew_x = 0
self.kurtosis = 0
self.kurtosis_x = 0
self.label_distribution = []
# keep a copy of the flat output label vector for visualisation.
self.labels = Y_set
def representData(self):
# Find out what representation is needed, 2D or 3D.
sample_X = self.X_set[0]
if self.prediction=='classification':
labels = set(self.Y_set)
label_mappings = {}
for i, item in enumerate(labels):
label_mappings[item] = int(i)
for j, jtem in enumerate(self.Y_set):
self.Y_set[j] = label_mappings[jtem]
self.Y_set = np.asarray(self.Y_set, dtype=np.int32)
sample_Y = self.Y_set[0]
self.outputs = len(set(self.Y_set))
self.labels = self.Y_set
if hasattr(sample_Y, '__iter__'):
print('Use a 3D representation to model sequence-to-sequence task... (encoding.)')
self.dimensionality = '3D'
X, Y = self.representDataAs3D(self.X_set, self.Y_set)
else:
self.dimensionality ='2D'
types = [isinstance(n, numbers.Number) for n in self.X_set[0]]
if not False in types:
print('Use a 2D representation for classification task (numeric values)... (no encoding.)')
X, Y = self.representDataAs2DNumeric(self.X_set, self.Y_set)
self.data_type = 'numeric'
else:
print('Use a 2D representation for classification task (symbolic values)... (encoding.)')
X, Y = self.representDataAs2D(self.X_set, self.Y_set)
self.data_type = 'symbolic'
self.X_set = X
self.Y_set = Y
self.computeCentrality()
self.computeNormalDistribution()
self.computeDispersion()
self.computeShape()
self.computeDistribution()
return self
def representDataAs2DNumeric(self, X_set, Y_set):
# Use this for tasks that classify a single output value.
lens = []
X_2D = np.asarray(X_set)
Y_2D = np.asarray(Y_set)
new_X = X_2D
# Look into this later - paddings pads them all to 0s and 1s...
# new_X = sequence.pad_sequences(X_2D, maxlen=self.max_len, value=0)
if self.prediction=='classification':
new_Y = np_utils.to_categorical(Y_2D, self.outputs)
else:
new_Y = Y_2D
print('Representing data X with shape', new_X.shape, 'and Y with shape:', new_Y.shape)
return new_X, new_Y
def representDataAs2D(self, X_set, Y_set):
# Use this for tasks that classify a single output value.
X_2D = np.asarray(X_set)
Y_2D = np.asarray(Y_set)
# Get mapping dicts for input representations.
self.char_indices = dict((c, i) for i, c in enumerate(self.vocab))
self.indices_char = dict((i, c) for i, c in enumerate(self.vocab))
#print self.char_indices
new_X = self.encode2DIntegerX(X_2D)
new_X = sequence.pad_sequences(new_X, maxlen=self.max_len)
if self.prediction=='classification':
new_Y = np_utils.to_categorical(Y_2D, self.outputs)
else:
new_Y = Y_2D
print('Representing data X with shape', new_X.shape, 'and Y with shape:', new_Y.shape)
return new_X, new_Y
def representDataAs3D(self, X_set, Y_set):
# Use this for sequence-to-sequence learning with 3D methods below.
X_3D = np.zeros((len(self.X_set), self.max_len, len(self.vocab)), dtype=np.bool)
Y_3D = np.zeros((len(self.Y_set), self.max_len, len(self.vocab)), dtype=np.bool)
# Get mapping dicts for input representations.
self.char_indices = dict((c, i) for i, c in enumerate(self.vocab))
self.indices_char = dict((i, c) for i, c in enumerate(self.vocab))
print('Representing data X and Y with shape:', X_3D.shape)
new_X = self.encode3DBooleanX(X_set)
new_Y = self.encode3DBooleanX(Y_set)
print('Padding all sequences to max_len:', self.max_len)
new_X = sequence.pad_sequences(new_X, maxlen=self.max_len)
new_Y = sequence.pad_sequences(new_Y, maxlen=self.max_len)
return new_X, new_Y
def encode2DIntegerX(self, X_set):
# encode X into a 2D matrix / array of arrays.
for i, item in enumerate(X_set):
for j, jtem in enumerate(item):
item[j] = self.char_indices[jtem]
X_set[i] = item
return X_set
def encode3DBooleanX(self, X_set):
# encode X into a boolean matrix
X_3D = np.zeros((len(self.X_set), self.max_len, len(self.vocab)), dtype=np.bool)
for i, item in enumerate(X_set):
X1 = np.zeros((self.max_len, len(self.vocab)))
for j, c in enumerate(item):
X1[j, self.char_indices[c]] = 1
X_3D[i] = X1
return X_3D
def encode3DBooleanY(self, Y_set):
# encode Y into a boolean matrix
for i, item in enumerate(Y_set):
Y1 = np.zeros((self.max_len, len(self.vocab)))
for j, c in enumerate(item):
Y1[j, char_indices[c]] = 1
Y[i] = Y1
return Y_set
def decode3D(self, X, calc_argmax=True):
# this decodes 3D items.
if calc_argmax:
X = X.argmax(axis=-1)
return ' '.join(indices_char[x] for x in X)
def decode2D(X_item, model):
# this decodes 2D X items.
new_X = []
for x in X_item:
new = indices_char[int(x)]
new_X.append(new)
new_X = ' '.join(new_X).replace('mask_zeros', '')
return ' '.join(new_X.split())
def countSymbols(self):
# find all the different types of symbols in the input and output.
types = [isinstance(n, numbers.Number) for n in self.X_set[0]]
if False in types:
self.vocab = self.assembleVocab()
else:
print('Using numeric values only - no vocabulary needed.')
self.vocab = set()
def assembleVocab(self):
for x in self.X_set:
self.text = self.text + ' '.join(x) + ' '
# print(self.text)
if hasattr(self.Y_set[0], '__iter__'):
for y in self.Y_set:
self.text = self.text + ' '.join(y) + ' '
chars = set(self.text.split())
vocab = list(chars)
vocab.insert(0, 'mask_zeros')
print('Found', len(vocab), 'unique vocabulary items.')
return vocab
def countMaxLen(self):
# find the max len of an input or output sequence so we can pad all sequences.
for x in self.X_set:
if len(x) > self.max_len:
self.max_len = len(x)
if hasattr(self.Y_set[0], '__iter__'):
for y in self.Y_set:
if len(y) > self.max_len:
self.max_len = len(y)
def computeCentrality(self):
# Compute the mean, median and mode of X
self.mean_X = np.mean(self.X_set)
self.median_X = np.median(self.X_set)
means = []
medians = []
modes = []
X_T = np.transpose(self.X_set)
for x in X_T:
means.append(np.mean(x))
medians.append(np.median(x))
modes.append(stats.mode(x)[0])
self.means = np.asarray(means)
self.medians = np.asarray(medians)
self.modes = np.asarray(modes).flatten()
def computeDispersion(self):
# compute the standard deviation of this dataset and the inter-quartile range
stds = []
iqrs = []
X_T = np.transpose(self.X_set)
for x in X_T:
stds.append(x.std())
iqrs.append(iqr(x))
self.stds = stds
self.iqrs = iqrs
self.stds_x = self.X_set.std()
self.iqr_x = iqr(self.X_set)
def computeNormalDistribution(self):
# find out whether the data has a normal distribution or not
x = self.X_set[0]
if len(x) > 8:
z,pval = stats.normaltest(x)
print(z, pval)
if(pval < 0.055):
self.normal_distribution = False
else:
self.normal_distribution = True
def computeShape(self):
# Compute the skew and kurtosis
X_T = np.transpose(self.X_set)
if len(X_T) > 8:
self.skew = skew(X_T)
self.kurtosis = kurtosis(X_T)
self.kurtosis_x = kurtosis(self.X_set.flatten())
self.skew_x = skew(self.X_set.flatten())
def computeDistribution(self):
# find the distribution of labels
labels = set(self.labels)
self.label_distribution = np.histogram(self.labels, bins=len(labels))[0]
def normalized(self, a, axis=-1, order=2):
l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
l2[l2==0] = 1
return a / np.expand_dims(l2, axis)
def getNormalisedVector(self):
vector = []
if self.prediction == "classification":
vector.append(1)
else:
vector.append(0)
vector.append(self.max_len)
vector.append(self.outputs)
if self.data_type == "numeric":
vector.append(0)
else:
vector.append(1)
vector.append(len(self.X_set))
vector.append(len(self.vocab))
vector.append(self.mean_X)
vector.append(self.median_X)
vector.append(self.stds_x)
vector.append(self.iqr_x)
vector.append(self.skew_x)
vector.append(self.kurtosis_x)
if self.normal_distribution == True:
vector.append(1)
else:
vector.append(0)
normalised = self.normalized(vector)
return normalised
def shuffleAndSplit(self):
# Shuffle (X, y) in unison as the later parts of X will almost all be larger digits
indices = np.arange(len(self.Y_set))
X = self.X_set[indices]
Y = self.Y_set[indices]
# Explicitly set apart 10% for validation data that we never train over
split_at = int(len(X) * 0.8)
X_train = X[:split_at]
X_val = X[split_at:]
Y_train = Y[:split_at]
Y_val = Y[split_at:]
print('Shuffled and split dataset into', len(X_train), 'training instances and', len(X_val), 'test instances.')
self.X_train = X_train
self.Y_train = Y_train
self.X_val = X_val
self.Y_val = Y_val
return X_train, X_val, Y_train, Y_val
def visualise(self):
X = self.X_set
y = self.labels
fig = plt.figure(0, figsize=(10, 8))
ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134)
pca = PCA(n_components=3)
X_reduced = pca.fit_transform(X)
used_labels = []
colour_scheme = plt.cm.Set1
for i, item in enumerate(X_reduced):
if not y[i] in used_labels:
ax.scatter(item[0], item[1], item[2], c = colour_scheme(y[i]/10), s=40, edgecolor='k', label=y[i])
used_labels.append(y[i])
else:
ax.scatter(item[0], item[1], item[2], c = colour_scheme(y[i]/10), s=40, edgecolor='k')
ax.legend(loc="lower right")
ax.set_title("First three PCA directions")
ax.set_xlabel("1st eigenvector")
ax.w_xaxis.set_ticklabels([])
ax.set_ylabel("2nd eigenvector")
ax.w_yaxis.set_ticklabels([])
ax.set_zlabel("3rd eigenvector")
ax.w_zaxis.set_ticklabels([])
plt.savefig('fig.png', format='png', dpi=1200)
plt.show()
<file_sep>gp_data contains outputs of hyperparameter optimisations over various source datasets from UCI repository.
response.py will run hyperparameter optimisation over those output files to fit Gaussian Processes and identify the most predictive hyperparameters for each of these datasets. It does this by analysing the length scales.
analyse_response.py produces a json file that represents each dataset as a vector of metrics about the dataset and contains the “best” hyperparameters.
|
23240db82fad2040a6c9c8dc626c15677c92cc73
|
[
"Markdown",
"Python",
"Text"
] | 11
|
Markdown
|
ndethlefs/DEFIne
|
230657427d0da6d508b7d76d8d7cf0bcfdfae55f
|
c253c82c782b6d5c4c98fcca6dbd6bcfe531d633
|
refs/heads/master
|
<repo_name>ThePuffin/atelierReact<file_sep>/films/listefilm/src/components/Films.js
import React, {
Component
} from 'react';
import "./Films.css"
class Films extends Component {
constructor(props) {
super(props);
this.state = {
listeFilm: [{
titre: "batman",
note: 4,
description: "un film de Batman",
img: "https://media.senscritique.com/media/000012723320/source_big/Batman.jpg"
},
{
titre: "<NAME>",
note: 3,
description: "un autre film de Batman",
img: "https://i2.cdscdn.com/pdt2/5/8/4/1/700x700/auc2009958396584/rw/affiche-batman-robin-arnold-schwarzenegger.jpg"
},
{
titre: "catwoman",
note: 1,
description: "il y a <NAME>",
img: "http://fr.web.img3.acsta.net/r_1280_720/medias/nmedia/18/35/23/93/18378823.jpg"
},
{
titre: "avenger",
note: 4,
description: "hmm Scarlett",
img: "https://ae01.alicdn.com/kf/HTB1OEShOFXXXXcEXVXXq6xXFXXXA/Peinture-Murale-personnalis-e-Lego-Papier-Peint-Lego-Affiche-Thor-Autocollant-Marvel-Comics-Super-H-ros.jpg_640x640.jpg"
},
{
titre: "star wars",
note: 5,
description: "star wars avec yoda",
img: "https://i2.cdscdn.com/pdt2/3/7/6/1/700x700/clo4035519445376/rw/poster-star-warsl-empire-contre-attaque-couvert.jpg"
},
{
titre: "fight club",
note: 5,
description: "<NAME> se bat contre <NAME>",
img: "https://media.senscritique.com/media/000014744218/source_big/Fight_Club.jpg"
},
{
titre: "tous en scene",
note: 3,
description: "Scarlett chante dedans",
img: "https://pmcdn.priceminister.com/photo/tous-en-scene-sing-affiche-originale-de-cinema-format-120x160-cm-un-film-de-garth-jennings-avec-les-voix-de-patrick-bruel-jenifer-bartoli-elodie-martelet-laurent-gerra-annee-2017-1103005488_ML.jpg"
}
]
}
}
render() {
return <div >
<
h2 > Liste de Films < /h2>
{
/* < div class = "row" >
<
div class = "small-10 medium-11 columns" >
<
div class = "range-slider"
data-slider data-options = "display_selector: #sliderOutput3;" >
<
span class = "range-slider-handle"
role = "slider"
tabindex = "0" > < /span> <
span class = "range-slider-active-segment" > < /span> <
/div> <
/div> <
div class = "small-2 medium-1 columns" >
<
span id = "sliderOutput3" > < /span> <
/div> <
/div> */
}
<
div className = 'row' > {
this.state.listeFilm.map(film =>
<
div class = "card offset-1 col-2" >
<
img class = "card-img-top"
src = {
film.img
}
alt = {
film.titre
}
height = "auto"
width = "33rem" / >
<
div class = "card-body" >
<
h5 class = "card-title" > {
film.titre
} < /h5> <
p class = "card-text" > {
film.description
} < /p> < /
div > <
/div>)
}
<
/div> <
/div>
}
}
export default Films;<file_sep>/exo05/05/src/components/Jeu.js
import React, { Component } from "react";
class Jeu extends Component {
constructor(props) {
super(props);
this.state = {
nbrDevine: 0,
disabled: true,
phrase: "",
icon: "",
valeurEntree: 0,
bouton: [
{ type: "btn btn-primary", value: 10, text: "easy" },
{ type: "btn btn-secondary", value: 100, text: "medium" },
{ type: "btn btn-warning", value: 1000, text: "hard" }
]
};
this.handleClick = this.handleClick.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.changeValeur = this.changeValeur.bind(this);
this.nombreAleatoire = this.nombreAleatoire.bind(this);
}
nombreAleatoire(max) {
return Math.floor(Math.random() * Math.floor(max));
}
handleClick(e) {
e.preventDefault();
// alert(e.target.value);
let alea = this.nombreAleatoire(e.target.value);
this.setState({ nbrDevine: alea, disabled: false });
}
changeValeur(e) {
console.log("a deviner :", this.state.nbrDevine);
console.log("entree :", e.target.value);
this.setState({ valeurEntree: e.target.value });
}
handleSubmit(e) {
e.preventDefault();
let devine = this.state.nbrDevine;
let propose = this.state.valeurEntree;
if (propose < devine) {
this.setState({ phrase:"trop bas" });
} else if (propose > devine) {
this.setState({ phrase: "trop haut" });
} else {
this.setState({ phrase: "bravo" });
}
}
render() {
// let icon = [battery - empty, battery - quarter, battery - three - quarters];
return (
<div>
{this.state.bouton.map(btn => (
<button
className={btn.type}
value={btn.value}
onClick={this.handleClick}
>
{btn.text}
</button>
))}
<form className="row">
<input
type="number"
class="form-control game-display offset-5 col-2"
placeholder="enter number"
value={this.state.valeurEntree}
onChange={this.changeValeur}
/>
</form>
<br />
<button
type="submit"
disabled={this.state.disabled}
className="btn btn-dark"
onClick={this.handleSubmit}
>
GUESS
</button>
{this.state.phrase !== "" ? <p>{this.state.phrase}</p> : null}
{this.state.icon !== "" ? <i class="fas fa-{this.state.icon}" /> : null}
</div>
);
}
}
export default Jeu;
<file_sep>/exo02/src/components/Button.js
import React, { Component } from "react";
import "./Button.css";
class Button extends Component {
constructor(props) {
super(props);
this.state = {
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.props.switcher()
}
render() {
return (
<div>
<label class="switch">
<input type="checkbox" onChange={this.handleChange} />
<span class="slider round"> </span>
</label>
</div>
);
}
}
export default Button;
<file_sep>/react axios/reacxios/src/components/Axio.js
import React, { Component } from 'react';
import axios from "axios";
class Axio extends Component {
constructor(props) {
super(props);
this.state = {
pokemons: [],
search: ""
};
this.handleChange = this.handleChange.bind(this)
}
componentDidMount() {
axios.get(`https://pokeapi.co/api/v2/pokemon/?limit=200`).then(res => {
const pokemons = res.data.results;
this.setState({
pokemons
});
});
}
handleChange(e){
// console.log(e.target.value);
this.setState({search:e.target.value})
}
render() {
let pokemonster = this.state.pokemons
pokemonster.map(el => <li> {el.name} </li>);
let regex = new RegExp(`${this.state.search}`, "gi");
return <div>
<form>
<input type="name" placeholder="recherche" onChange={this.handleChange} />{" "}
</form> <ul>
{this.state.search === ""
? pokemonster.map(el => <li> {el.name} </li>)
: pokemonster
.filter(nom => regex.test(nom.name))
.map(el => <li> {el.name} </li>)}
</ul>{" "}
</div>;
}
}
export default Axio;
// {
// this.state.search;
// }
{ /* {pokemonster.length > 0 ? JSON.stringify(pokemonster) : console.log("pas de données")} */ }<file_sep>/exo02/src/components/Horloge.js
import React, { Component } from "react";
import Button from "./Button";
import "./Horloge.css";
class Horloge extends Component {
constructor(props) {
super(props);
this.state = { time: "", day: "", on: 0 };
this.heure = this.heure.bind(this);
this.switcher = this.switch.bind(this);
}
componentDidMount() {
this.interval = setInterval(() => {
let all = this.heure();
// console.log("re re re");
this.setState({ time: all.time, day: all.day });
}, 1000);
}
switch() {
let number = this.state.on + 1;
this.setState({ on: number });
console.log(this.state.on);
}
heure() {
let weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
let date = new Date();
let heure = date.getHours();
let min = date.getMinutes();
let secondes = date.getSeconds();
let time = `${heure}:${min}:${secondes}`;
let day = weekday[date.getDay()];
let jour = date.getDate();
let month = date.getMonth();
let year = date.getFullYear();
let fullDay = `${day} ${jour} ${month} ${year}`;
let all = { time: time, day: fullDay };
// console.log("heure")
return all;
}
render() {
let switched = this.state.on
return <div>
<div className="row offset-5 col-4">
<Button switcher={this.switcher} />
<p>
:
<i class="far fa-calendar-alt" />
</p>
</div>
<div className="row offset-4 col-4 ">
<div className="container horloge tictac">
<p className="text">{this.state.time}</p>
{switched % 2 === 0 ? null : <p className="text">
{this.state.day}
</p>}
</div>
</div>
</div>;
}
}
export default Horloge;
<file_sep>/devine nombre/05/src/components/Jeu.js
import React, { Component } from "react";
import Recommence from "./Recommence";
import Historique from "./Historique";
class Jeu extends Component {
constructor(props) {
super(props);
this.state = {
win: false,
nbrDevine: 0,
disabled: true,
phrase: "",
proche: "",
icon: "",
valeurEntree: 0,
max: 0,
historique:0,
bouton: [
{ type: "btn btn-primary", value: 10, text: "easy" },
{ type: "btn btn-secondary", value: 100, text: "medium" },
{ type: "btn btn-warning", value: 1000, text: "hard" }
]
};
this.handleClick = this.handleClick.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.changeValeur = this.changeValeur.bind(this);
}
nombreAleatoire(max) {
return Math.floor(Math.random() * Math.floor(max));
}
handleClick(e) {
e.preventDefault();
// alert(e.target.value);
let alea = this.nombreAleatoire(e.target.value);
this.setState({ nbrDevine: alea, disabled: false, max: e.target.value });
}
changeValeur(e) {
console.log("a deviner :", this.state.nbrDevine);
console.log("entree :", e.target.value);
this.setState({ valeurEntree: e.target.value });
}
handleSubmit(e) {
e.preventDefault();
this.setState({historique : this.state.valeurEntree})
let devine = this.state.nbrDevine;
let propose = this.state.valeurEntree;
let difference = Math.abs(propose - devine);
// alert(difference);
if (difference === 0) {
this.setState({
icon: "fas fa-trophy",
proche: "tu as trouvé la solution",
win: true
});
} else if (difference < 0.05 * this.state.nbrDevine) {
this.setState({
icon: "fas fa-battery-full",
proche: "tu es bouillant"
});
} else if (difference < 0.25 * this.state.nbrDevine) {
console.log(0.25 * this.state.nbrDevine);
this.setState({
icon: "fas fa-battery-three-quarters",
proche: "tu es chaud"
});
} else if (difference < 0.5 * this.state.nbrDevine) {
console.log(0.5 * this.state.nbrDevine);
this.setState({ icon: "fas fa-battery-half", proche: "tu es tiède" });
} else if (difference < 0.75 * this.state.nbrDevine) {
console.log(0.75 * this.state.nbrDevine);
this.setState({
icon: "fas fa-battery-quarter",
proche: "tu es froid"
});
} else if (difference <= 0.9 * this.state.nbrDevine) {
this.setState({
icon: "fas fa-battery-empty",
proche: "tu es glacé"
});
} else {
this.setState({
icon: "fab fa-safari",
proche: "Tu es dans une galaxie très très lointaine"
});
}
if (propose < devine) {
this.setState({ phrase: "trop bas" });
} else if (propose > devine) {
this.setState({ phrase: "trop haut" });
} else {
this.setState({ phrase: "bravo" });
}
}
render() {
return (
<div>
{this.state.win === false ? (
<div>
{this.state.bouton.map(btn => (
<button
className={btn.type}
value={btn.value}
onClick={this.handleClick}
>
{btn.text}
</button>
))}
<hr />
{this.state.disabled !== true ? (
<div>
<p>Choisi une valeur entre 0 et {this.state.max}</p>
<form className="row" onSubmit={this.handleSubmit}>
<input
type="number"
class="form-control game-display offset-5 col-2"
placeholder="enter number"
value={this.state.valeurEntree}
onChange={this.changeValeur}
/>
<br />
<button
type="submit"
disabled={this.state.disabled}
className="btn btn-dark"
>
GUESS
</button>
</form>
{this.state.phrase !== "" ? (
<p>
{this.state.phrase}, {this.state.proche}
</p>
) : null}
{this.state.icon !== "" ? <i class={this.state.icon} /> : null}
<hr />
</div>
) : (
<h3>Choisi un niveau</h3>
)}
{this.state.disabled !== true ? (
<div>
<Historique />
</div>
) : null}
</div>
) : (
<Recommence />
)}
</div>
);
}
}
export default Jeu;
// ajouter l'historique
// ajouter un nombre d'essai par difficulté
// bloquer le bouton proposition de chiffre si niveau pas choisi
// faire une page de win
// afficher le temps pour résoudre la solution au win
<file_sep>/demo antho/src/components/User.js
import React, { Component } from "react";
import HighOrder from "./Hoc";
const CurrentUser = TagComponent =>
class extends Component {
constructor(props) {
super(props);
this.state = {
user: {
name: "vincent",
type: "h1",
style: {
color: "blue"
}
}
};
}
render() {
const user = this.props.connected
? this.state.user
: { name: "antho", type: "h3" };
return (
<TagComponent
name={user.name}
Type={user.type}
style={user.style}
{...this.props}
/>
);
}
};
export default CurrentUser;
<file_sep>/devine nombre/05/src/components/Devinette.js
import React, { Component } from "react";
class Devinette extends Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
return (
<div>
{this.state.bouton.map(btn => (
<button
className={btn.type}
value={btn.value}
onClick={this.handleClick}
>
{btn.text}
</button>
))}
<form className="row">
<input
type="number"
class="form-control game-display offset-5 col-2"
placeholder="enter number"
value={this.state.valeurEntree}
onChange={this.changeValeur}
/>
</form>
<br />
<button
type="submit"
disabled={this.state.disabled}
className="btn btn-dark"
onClick={this.handleSubmit}
>
GUESS
</button>
{this.state.phrase !== "" ? (
<p>
{this.state.phrase}, {this.state.proche}
</p>
) : null}
{this.state.icon !== "" ? <i class={this.state.icon} /> : null}
</div>
);
}
}
export default Devinette;
<file_sep>/a finir/exo10/src/components/Formulaire.js
import React, {
Component
} from "react";
import {
ToastContainer,
toast
} from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
// import validator from 'validator';
class Formulaire extends Component {
constructor(props) {
super(props);
this.state = {
sexe: "",
username: "",
age: "",
tel: "",
email: "",
password: "",
password2: "",
hobbies: "",
sports: "",
error: "veuillez remplir ce champ"
};
this.handleUserInput = this.handleUserInput.bind(this);
this.validation = this.validation.bind(this);
}
validation(name, value) {
//test username
console.log(value);
(name === "username") ?(value.length < 6) ? this.setState({error: "nom trop court"}): this.setState({error: ""}): null;
//test age
(name === "age") ? ((value > 18 && value < 99) ? this.setState({
error: ""
}) : this.setState({
error: "vous n'avez pas l'âge requis"
})) : null;
//test telephone
(name === "tel") ? (((/(\d){10}/).test(value)) ? this.setState({
error: ""
}) : this.setState({
error: "le numéro n'est pas valable"
})) : null;
//test mail
(name === "mail") ? (((/^\w+@\w+.\w{2,3}$/).test(value)) ? this.setState({
error: ""
}) : this.setState({
error: "l'adresse n'est pas valable"
})) : null;
//test password
(name === "password") ? (((/\w{5,}\W+/gi).test(value)) ? this.setState({
error: ""
}) : this.setState({
error: "mot de passe trop court"
})) : null;
}
handleUserInput(e) {
const name = e.target.name;
let value = e.target.value;
const check = e.target.checked;
// (check === true)?value=true: value=false;
this.setState({
[name]: value
});
this.validation(name, value)
}
notify = () => {
(this.state.error !== "") ? toast(this.state.error): null;
this.setState({
error: "veuillez remplir ce champ"
})
};
render() {
return <div >
<
div className = "container" >
<
ToastContainer / >
<
form onChange = {
event => this.handleUserInput(event)
} >
<
fieldset class = "form-group" >
<
div class = "row" >
<
legend class = "col-form-label col-sm-2 pt-0" > Sexe < /legend> <
div class = "col-sm-10" >
<
div class = "form-check" >
<
input class = "form-check-input"
type = "radio"
name = "sexe"
id = "sexe1"
value = "homme"
/ >
<
label class = "form-check-label"
for = "sexe1" >
Homme
<
/label> < /
div > <
div class = "form-check" >
<
input class = "form-check-input"
type = "radio"
name = "sexe"
id = "sexe2"
value = "femme" / >
<
label class = "form-check-label"
for = "sexe2" >
Femme
<
/label> < /
div > <
div class = "form-check" >
<
input class = "form-check-input"
type = "radio"
name = "sexe"
id = "sexe3"
value = "autre" / >
<
label class = "form-check-label"
for = "sexe3" >
Autre
<
/label> < /
div > <
/div> < /
div > <
/fieldset> <
div class = "form-group row" >
<
label
for = "name"
class = "col-sm-2 col-form-label" >
Name <
/label> <
div class = "col-sm-10" >
<
input type = "text"
class = "form-control"
id = "name"
placeholder = ""
value = {
this.state.name
}
name = "username"
onChange = {
event => this.handleUserInput(event)
}
onBlur = {
this.notify
}
onFocus = {
this.validation("usename", this.state.username)
}
/> < /
div > <
/div> <
div class = "form-group row" >
<
label
for = "name"
class = "col-sm-2 col-form-label" >
Age <
/label> <
div class = "col-sm-10" >
<
input type = "number"
class = "form-control"
id = "age"
placeholder = ""
value = {
this.state.age
}
name = "age"
onChange = {
event => this.handleUserInput(event)
}
onBlur = {
this.notify
}
onFocus = {
this.validation
}
/> < /
div > <
/div> <
div class = "form-group row" >
<
label
for = "name"
class = "col-sm-2 col-form-label" >
Telephone <
/label> <
div class = "col-sm-10" >
<
input type = "tel"
class = "form-control"
id = "phone"
placeholder = ""
value = {
this.state.tel
}
name = "tel"
onChange = {
event => this.handleUserInput(event)
}
onBlur = {
this.notify
}
onFocus = {
this.validation
}
/> < /
div > <
/div> <
div class = "form-group row" >
<
label
for = "inputEmail3"
class = "col-sm-2 col-form-label" >
Email <
/label> <
div class = "col-sm-10" >
<
input type = "email"
class = "form-control"
id = "inputEmail"
placeholder = "mail"
value = {
this.state.mail
}
name = "email"
onChange = {
event => this.handleUserInput(event)
}
onBlur = {
this.notify
}
onFocus = {
this.validation
}
/> < /
div > <
/div> <
div class = "form-group row" >
<
label
for = "input<PASSWORD>"
class = "col-sm-2 col-form-label" >
Password <
/label> <
div class = "col-sm-10" >
<
input type = "password"
class = "form-control"
id = "inputPassword"
placeholder = "<PASSWORD>"
value = {
this.state.password
}
name = "password"
onChange = {
event => this.handleUserInput(event)
}
onBlur = {
this.notify
}
onFocus = {
this.validation
}
/> < /
div > <
/div> <
div class = "form-group row" >
<
label
for = "input<PASSWORD>"
class = "col-sm-2 col-form-label" >
Password check <
/label> <
div class = "col-sm-10" >
<
input type = "password"
class = "form-control"
id = "inputPassword2"
placeholder = "<PASSWORD>"
value = {
this.state.password
}
name = "password2"
onChange = {
event => this.handleUserInput(event)
}
onBlur = {
this.notify
}
onFocus = {
this.validation
}
/> < /
div > <
/div>
{ /* les checkbox et radio ne sont pas en onchange , pas de name et pas de value */ } <
div class = "form-group row" >
<
div class = "col-sm-2" > Hobbies < /div> <
div class = "col-sm-4" >
<
div class = "form-check" >
<
div className = "col-1" >
<
input class = "form-check-input"
type = "checkbox"
id = "Manger" / >
<
label class = "form-check-label"
for = "gridCheck1" >
Manger
<
/label> < /
div > <
div className = "col-1" >
<
input class = "form-check-input"
type = "checkbox"
id = "Dormir" / >
<
label class = "form-check-label"
for = "gridCheck1" >
Dormir
<
/label> < /
div > <
div className = "col-1" >
<
input class = "form-check-input"
type = "checkbox"
id = "Voyager" / >
<
label class = "form-check-label"
for = "gridCheck1" >
Voyager
<
/label> < /
div > <
/div> < /
div > <
div class = "col-sm-2" > Sport < /div> <
div class = "col-sm-4" >
<
div class = "form-check" >
<
div className = "col-1" >
<
input class = "form-check-input"
type = "checkbox"
id = "Hockey" / >
<
label class = "form-check-label"
for = "gridCheck1" >
Hockey
<
/label> < /
div > <
div className = "col-1" >
<
input class = "form-check-input"
type = "checkbox"
id = "Rugby" / >
<
label class = "form-check-label"
for = "gridCheck1" >
Rugby
<
/label> < /
div > <
div className = "col-1" >
<
input class = "form-check-input"
type = "checkbox"
id = "Hurling" / >
<
label class = "form-check-label"
for = "gridCheck1" >
Hurling
<
/label> < /
div > <
/div> < /
div > <
/div> <
div class = "form-group row" >
<
div class = "col-sm-10" >
<
button type = "submit"
class = "btn btn-primary" >
Sign in
<
/button> < /
div > <
/div> < /
form > <
/div>; < /
div >
}
}
export default Formulaire;<file_sep>/atelier/src/Display.js
import React, { Component } from "react";
import Age from "./Age";
import LaTextarea from "./Textarea";
class Display extends Component {
constructor(props) {
super(props);
this.state = {
prenom: "Vincent",
nom: "Ballut",
age: 36,
ville: "Villeurbanne",
adresse: "3 boulevard eugene reguillon",
GPS: { long: 4.36665, lat: 45.75666 },
chanteurs: ["Ibeyi", "<NAME>", "Bjork"],
url:
"http://www.laroutedurock.com/wp-content/uploads/2015/03/AngelOlsen_540x420_5-1024x1024.jpg",
site: "http://www.google.fr",
textearea: "",
message: "tada"
};
this.rajeunir = this.rajeunir.bind(this);
this.vieillir = this.vieillir.bind(this);
this.txtArea = this.txtArea.bind(this);
}
rajeunir() {
this.setState({ age: this.state.age - 1 });
}
vieillir() {
this.setState({ age: this.state.age + 1 });
}
txtArea(e) {
// console.log(e);
this.setState({ textearea: e });
if (e.length > 0 && e.length <= 3) {
this.setState({ message: "" });
} else {
this.setState({ message: "tada" });
}
}
render() {
let tableauTxtArea= this.state.textearea.split(" ");
let nombre = tableauTxtArea.length
return (
<div>
<h3>
{this.state.nom} {this.state.prenom}
</h3>
{/* <h5>Age : {this.state.age} ans</h5> */}
{this.state.age <= 15 ? (
<h5>"trop jeune"</h5>
) : (
<h5> {this.state.age} ans </h5>
)}
<Age rajeunir={this.rajeunir} vieillir={this.vieillir} />
<ul>{this.state.chanteurs.map(user => <li>{user}</li>)}</ul>
<img style={{ width: "20vh" }} src={this.state.url} alt="angel olsen" />
<br />
<a href={this.state.site}> {this.state.site} </a>
<hr />
<LaTextarea txtArea={this.txtArea} />
<p>{this.state.textearea}</p>
<p className={this.state.message}>Ce message est trop court</p>
<p> Le nom de mot dans la page est : {nombre}</p>
<hr />
</div>
);
}
}
export default Display;
<file_sep>/exo06/src/components/Hoc.js
import React, { Component } from "react";
const HighOrder = ClassComponent =>
class extends Component {
constructor(props) {
super(props);
this.state = {
connected: false
};
this.authorize = this.authorize.bind(this);
}
componentDidMount() {
this.authorize();
}
authorize() {
this.setState({ connected: true });
}
render() {
return (
<ClassComponent
connected={this.state.connected}
onClick={() => this.setState({ connected: false })}
/>
);
}
};
export default HighOrder;
<file_sep>/atelier/src/Textarea.js
import React, { Component } from "react";
import "./Textearea.css";
class LaTextarea extends Component {
constructor(props) {
super(props);
this.state = {};
this.handleChange = this.handleChange.bind(this);
this.handleBlur = this.handleBlur.bind(this);
}
handleChange(event) {
this.props.txtArea(event.target.value);
}
handleBlur(event) {
let phrase = event.target.value.toLowerCase().split(" ").join("");
console.log(phrase);
event.target.value=phrase
}
render() {
return (
<div>
<label>Zone de texte</label>
<br />
<textarea
onChange={this.handleChange}
onBlur={this.handleBlur}
className="form-control"
id="exampleFormControlTextarea1"
rows="3"
/>
</div>
);
}
}
export default LaTextarea;
|
816e607d64446bf24e3d56e73f37f6178c28ad37
|
[
"JavaScript"
] | 12
|
JavaScript
|
ThePuffin/atelierReact
|
60e01dcf1efd3977e0d707b80ee569815b7ede17
|
0ad03ff768676318f183a7adbeeb2861448f4e68
|
refs/heads/master
|
<repo_name>OsmarHofman/WildWestFirstPerson<file_sep>/Pause.js
class Pause {
constructor() {
}
pauseMouse() {
var bloqueado = document.getElementById('bloqueado');
var instrucoes = document.getElementById('instrucoes');
var bloqueioPonteiro = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document;
if (bloqueioPonteiro) {
var element = document.body;
var pointerlockchange = function (event) {
if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element) {
controlesAtivado = true;
controles.enabled = true;
bloqueado.style.display = 'none';
} else {
controles.enabled = false;
bloqueado.style.display = '-webkit-box';
bloqueado.style.display = '-moz-box';
bloqueado.style.display = 'box';
instrucoes.style.display = '';
}
};
var pointerlockerror = function (event) {
instrucoes.style.display = '';
};
// Eventos de alteração de estado de bloqueio do ponteiro de gancho
document.addEventListener('pointerlockchange', pointerlockchange, false);
document.addEventListener('mozpointerlockchange', pointerlockchange, false);
document.addEventListener('webkitpointerlockchange', pointerlockchange, false);
document.addEventListener('pointerlockerror', pointerlockerror, false);
document.addEventListener('mozpointerlockerror', pointerlockerror, false);
document.addEventListener('webkitpointerlockerror', pointerlockerror, false);
instrucoes.addEventListener('click', function (event) {
instrucoes.style.display = 'none';
// Pede ao navegador para bloquear o ponteiro
element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;
if (/Firefox/i.test(navigator.userAgent)) {
var fullscreenchange = function (event) {
if (document.fullscreenElement === element || document.mozFullscreenElement === element || document.mozFullScreenElement === element) {
document.removeEventListener('fullscreenchange', fullscreenchange);
document.removeEventListener('mozfullscreenchange', fullscreenchange);
element.requestPointerLock();
}
};
document.addEventListener('fullscreenchange', fullscreenchange, false);
document.addEventListener('mozfullscreenchange', fullscreenchange, false);
element.requestFullscreen = element.requestFullscreen || element.mozRequestFullscreen || element.mozRequestFullScreen || element.webkitRequestFullscreen;
element.requestFullscreen();
} else {
element.requestPointerLock();
}
}, false);
} else {
instrucoes.innerHTML = 'Seu navegador parece não suportar a API Pointer Lock';
}
}
}<file_sep>/script.js
var canvas;
var objects = [];
var cenario = new Cenario();
var controlesMovimento = new Controles();
var controlesAtivado = false;
var movFrente = false;
var movTras = false;
var movEsquerda = false;
var movDireita = false;
var prevTime = performance.now();
var velocidade = new THREE.Vector3();
//Método para pausar a tela
var pause = new Pause();
pause.pauseMouse();
//teste physics
Physijs.scripts.worker = 'physijs_worker.js';
Physijs.scripts.ammmo = 'ammo.js';
//Câmera
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000);
var cena = new Physijs.Scene;
// AudioListener pra camera
var listener = new THREE.AudioListener();
camera.add(listener);
// Criando um PositionalAudio
var sound = new THREE.PositionalAudio(listener);
//Luz Ambiente
var luz = cenario.buildAmbientLight(0, 0, 2000);
cena.add(luz);
// Direcional
var sunLight = new THREE.PointLight(0xffa500, 1);
sunLight.position.set(0, 100, -300);
sunLight.castShadow = true;
sunLight.shadow.mapSize.width = window.innerWidth;
sunLight.shadow.mapSize.height = window.innerHeight;
var d = 80;
sunLight.shadow.camera.left = - d;
sunLight.shadow.camera.right = d;
sunLight.shadow.camera.top = d;
sunLight.shadow.camera.bottom = - d;
sunLight.shadow.camera.far = 1000;
cena.add(sunLight);
//Controles
var controles = new THREE.PointerLockControls(camera);
cena.add(controles.getObject());
var onKeyDown = controlesMovimento.keyDown();
var onKeyUp = controlesMovimento.keyUp();
document.addEventListener('keydown', onKeyDown, false);
document.addEventListener('keyup', onKeyUp, false);
var raycaster = new THREE.Raycaster(new THREE.Vector3(), new THREE.Vector3(0, - 1, 0), 0, 10);
//chao
var chao = cenario.buildFloor(200, 480);
chao.receiveShadow = true;
chao.position.z = -138;
cena.add(chao);
//Paredes
//Parede frente
var parede1 = cenario.buildWall(200, 150);
parede1.rotation.x = Math.PI / 2;
parede1.position.set(0, 75, -378)
cena.add(parede1);
//Parede esquerda
var parede2 = cenario.buildWall(480, 150);
parede2.rotation.x = Math.PI / 2;
parede2.rotation.z = -Math.PI / 2;
parede2.position.set(-100, 75, -138);
cena.add(parede2);
//Parede direita
var parede3 = cenario.buildWall(480, 150);
parede3.rotation.x = Math.PI / 2;
parede3.rotation.z = Math.PI / 2;
parede3.position.set(100, 75, -138);
cena.add(parede3);
//Parede trás
var parede4 = cenario.buildWall(200, 150);
parede4.rotation.y = 3.142;
parede4.rotation.x = -Math.PI / 2;
parede4.position.set(0, 75, 101);
cena.add(parede4);
//Fachadas da direita
var saloonDireita = cenario.buildSaloon(480, 25);
saloonDireita.rotation.y = - Math.PI / 2;
saloonDireita.position.set(95, 12, -138);
saloonDireita.receiveShadow = true;
cena.add(saloonDireita);
//Fachadas da esquerda
var saloonDireita = cenario.buildSaloon(480, 25);
saloonDireita.rotation.y = Math.PI / 2;
saloonDireita.position.set(- 95, 12, -138);
cena.add(saloonDireita);
//Ceu
var ceu = cenario.buildSky(200, 480);
ceu.position.z = -138;
ceu.position.y = 150;
cena.add(ceu);
//Sol
var sol = cenario.buildFlatSun(50, 32);
sol.position.z = -375;
cena.add(sol);
// Carregando e adicionando som ao Sol
var audioLoader = new THREE.AudioLoader();
audioLoader.load('old-town-road.mp3', function (buffer) {
sound.setBuffer(buffer);
sound.setLoop(true);
sound.setRefDistance(5);
sound.setVolume(1);
sound.play();
});
sol.add(sound);
//adicionando objetos
var palanque = cenario.getHorseKeeper(90, 0);
cena.add(palanque);
var palanque2 = cenario.getHorseKeeper(90, -80);
cena.add(palanque2);
var palanque3 = cenario.getHorseKeeper(90, -180);
cena.add(palanque3);
var palanque4 = cenario.getHorseKeeper(-90, -0);
cena.add(palanque4);
var palanque5 = cenario.getHorseKeeper(-90, -80);
cena.add(palanque5);
var palanque6 = cenario.getHorseKeeper(-90, -180);
cena.add(palanque6);
//Agua cavalos
var waterSupply1 = cenario.getWaterSupply(87, -20);
cena.add(waterSupply1);
var water1 = cenario.getWater(87, -20);
cena.add(water1);
var waterSupply2 = cenario.getWaterSupply(87, -100);
cena.add(waterSupply2);
var water2 = cenario.getWater(87, -100);
//cena.add(water2);
var waterSupply3 = cenario.getWaterSupply(87, -200);
cena.add(waterSupply3);
var water3 = cenario.getWater(87, -200);
//cena.add(water3);
var waterSupply4 = cenario.getWaterSupply(-87, -20);
waterSupply4.rotation.z = Math.PI;
cena.add(waterSupply4);
var water4 = cenario.getWater(-87, -20);
//cena.add(water4);
var waterSupply5 = cenario.getWaterSupply(-87, -100);
waterSupply5.rotation.z = Math.PI;
cena.add(waterSupply5);
var water5 = cenario.getWater(-87, -100);
//cena.add(water5);
var waterSupply6 = cenario.getWaterSupply(-87, -200);
waterSupply6.rotation.z = Math.PI;
cena.add(waterSupply6);
var water6 = cenario.getWater(-87, -200);
//cena.add(water6);
//Feno
var feno1 = cenario.buildHay(80, 5, 20);
cena.add(feno1);
var feno2 = cenario.buildHay(80, 5, -130);
cena.add(feno2);
var feno3 = cenario.buildHay(85, 5, -155);
cena.add(feno3);
var feno4 = cenario.buildHay(-80, 5, -40);
cena.add(feno4);
var feno5 = cenario.buildHay(-40, 5, -100);
cena.add(feno5);
var feno6 = cenario.buildHay(-28, 5, -100);
cena.add(feno6);
var feno7 = cenario.buildHay(-32, 5, -114);
cena.add(feno7);
var feno7 = cenario.buildHay(-27, 18, -115);
cena.add(feno7);
var feno8 = cenario.buildHay(-45, 18, -100);
cena.add(feno8);
//Render
var render = cenario.getRender();
render.setPixelRatio(window.devicePixelRatio);
render.setSize(window.innerWidth, window.innerHeight);
render.shadowMap.enabled = true;
render.shadowMap.type = THREE.BasicShadowMap;
window.addEventListener('resize', onWindowResize, false);
canvasInitialize();
animacao();
function canvasInitialize() {
canvas = cenario.getCanvas();
document.body.appendChild(canvas);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
render.setSize(window.innerWidth, window.innerHeight);
}
function animacao() {
cena.simulate();
requestAnimationFrame(animacao);
controlesMovimento.ativaMouse(controlesAtivado);
render.render(cena, camera);
}
<file_sep>/cenario.js
class Cenario {
constructor() {
//Render
this.render = new THREE.WebGLRenderer({
antialias: true
});
this.render.setSize(window.innerWidth, window.innerHeight);
this.render.setClearColor(0x101010);
//Shadow
this.render.shadowMap.enabled = true;
this.render.shadowMap.type = THREE.PCFSoftShadowMap;
//Canvas
this.canvas = this.render.domElement;
}
buildAmbientLight(x, y, z) {
this.luz = new THREE.AmbientLight(0xeeeeee, 0.7);
this.luz.position.set(x, y, z);
return this.luz;
}
buildFloor(largura, altura) {
var geometria = new THREE.PlaneGeometry(largura, altura, 100, 100);
geometria.rotateX(-Math.PI / 2);
var material = new THREE.MeshPhongMaterial({
map: new THREE.TextureLoader().load('Wasteland.jpg')
});
var chao = new Physijs.PlaneMesh(geometria, material, 0);
chao.receiveShadow = true;
return chao;
}
buildFlatSun(r, segments) {
var sunGeometry = new THREE.CircleGeometry(r, segments, 0, Math.PI);
var sunMaterial = new THREE.MeshBasicMaterial({
color: 0xff9d00
});
var sol = new THREE.Mesh(sunGeometry, sunMaterial);
sol.castShadow = false;
sol.receiveShadow = false;
return sol;
}
buildWall(largura, altura) {
var geometria = new THREE.PlaneGeometry(largura, altura, 100, 100);
geometria.rotateX(-Math.PI / 2);
var material = new THREE.MeshPhongMaterial({
map: new THREE.TextureLoader().load('sky.jpg')
});
var parede = new THREE.Mesh(geometria, material);
parede.receiveShadow = true;
return parede;
}
buildSky(largura, altura) {
var geometria = new THREE.PlaneGeometry(largura, altura, 100, 100);
geometria.rotateX(Math.PI / 2);
var material = new THREE.MeshPhongMaterial({
map: new THREE.TextureLoader().load('circular-sky.jpg')
});
var ceu = new THREE.Mesh(geometria, material);
ceu.receiveShadow = true;
return ceu;
}
buildSaloon(largura, altura) {
var geometria = new THREE.PlaneGeometry(largura, altura, 100, 100);
var texture = new THREE.TextureLoader().load('saloon-facade.jpg', function (texture) {
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.offset.set(0, 0);
texture.repeat.set(8, 1)
});
var material = new THREE.MeshPhongMaterial({
map: texture
});
var saloon = new THREE.Mesh(geometria, material);
saloon.receiveShadow = true;
return saloon;
}
buildHay(x, y, z) {
var hay = new Physijs.BoxMesh(
new THREE.CubeGeometry(10, 10, 10),
new THREE.MeshPhongMaterial({
map: new THREE.TextureLoader().load('hay.jpg')
})
);
hay.position.set(x, y, z);
hay.receiveShadow = true;
hay.castShadow = true;
return hay;
}
getHorseKeeper(x, z) {
var poleGeo = new THREE.CylinderBufferGeometry(0.5, 0.5, 10, 64);
var poleMat = new THREE.MeshPhongMaterial({
color: 0x964B00
});
var poste1 = new THREE.Mesh(poleGeo, poleMat);
poste1.position.y = 5;
poste1.position.z = -5;
poste1.receiveShadow = true;
poste1.castShadow = true;
var poste2 = new THREE.Mesh(poleGeo, poleMat);
poste2.position.y = 5;
poste2.position.z = 8;
poste2.receiveShadow = true;
poste2.castShadow = true;
var posteCima = new THREE.Mesh(new THREE.CylinderBufferGeometry(0.5, 0.5, 13, 64), poleMat);
posteCima.rotation.x = 1.57;
posteCima.position.y = 9.5;
posteCima.position.z = 1.5;
posteCima.receiveShadow = true;
posteCima.castShadow = true;
var group = new THREE.Group();
group.add(poste1);
group.add(poste2);
group.add(posteCima);
group.position.x = x;
group.position.z = z;
group.receiveShadow = true;
group.castShadow = true;
return group;
}
getWaterSupply(x, z) {
var geometry = new THREE.CylinderGeometry(5, 5, 20, 32, 1, false, 5, Math.PI);
var material = new THREE.MeshPhongMaterial({
color: 0x964B00
});
material.side = THREE.DoubleSide;
var cylinder = new THREE.Mesh(geometry, material);
var group = new THREE.Group();
group.add(cylinder);
cylinder.position.x = x;
cylinder.position.y = 5;
cylinder.position.z = z;
cylinder.rotation.x = Math.PI / 2;
cylinder.castShadow = true;
cylinder.receiveShadow = true;
return cylinder;
}
getWater(x, z) {
var waterGeometry = new THREE.PlaneBufferGeometry(8, 20);
var water = new THREE.Water(waterGeometry, {
color: '#ffffff',
scale: 4,
flowDirection: new THREE.Vector2(1, 1),
textureWidth: 1024,
textureHeight: 1024
});
water.position.x = x;
water.position.y = 2;
water.position.z = z;
water.rotation.x = Math.PI * - 0.5;
return water;
}
getHorse() {
var loader = new TDSLoader();
loader.setResourcePath('models/3ds/portalgun/textures/');
loader.load('standinghorse.3DS', function (object) {
object.traverse(function (child) {
if (child.isMesh) {
child.material.normalMap = normal;
}
});
return object
});
}
getRender() {
return this.render;
}
getCanvas() {
return this.canvas;
}
}<file_sep>/README.md
# WildWestFirstPerson
<NAME> com visão em primeira pessoa, feito em ThreeJS para a disciplina de Computação Gráfica.
<file_sep>/Controles.js
class Controles {
constructor() {
}
keyDown() {
return function (event) {
switch (event.keyCode) {
case 38: // frente
case 87: // w
movFrente = true;
break;
case 37: // esquerda
case 65: // a
movEsquerda = true;
break;
case 40: // atrás
case 83: // s
movTras = true;
break;
case 39: // direita
case 68: // d
movDireita = true;
break;
}
};
}
keyUp() {
return function (event) {
switch (event.keyCode) {
case 38: // up
case 87: // w
movFrente = false;
break;
case 37: // left
case 65: // a
movEsquerda = false;
break;
case 40: // down
case 83: // s
movTras = false;
break;
case 39: // right
case 68: // d
movDireita = false;
break;
}
};
}
ativaMouse(controlesAtivado) {
if (controlesAtivado) {
raycaster.ray.origin.copy(controles.getObject().position);
raycaster.ray.origin.y -= 10;
var intersections = raycaster.intersectObjects(objects);
var isOnObject = intersections.length > 0;
var time = performance.now();
var delta = (time - prevTime) / 1000;
velocidade.x -= velocidade.x * 10.0 * delta;
velocidade.z -= velocidade.z * 10.0 * delta;
velocidade.y -= 9.8 * 100.0 * delta; // 100.0 = mass
if (movFrente) {
velocidade.z -= 400.0 * delta;
this.movimenta(delta);
}
if (movTras) {
velocidade.z += 400.0 * delta;
this.movimenta(delta);
}
if (movEsquerda) {
velocidade.x -= 400.0 * delta;
this.movimenta(delta);
}
if (movDireita) {
velocidade.x += 400.0 * delta;
this.movimenta(delta);
}
if (isOnObject === true) {
velocidade.y = Math.max(0, velocidade.y);
}
if (controles.getObject().position.y < 10) {
velocidade.y = 0;
controles.getObject().position.y = 10;
}
prevTime = time;
}
}
movimenta(delta) {
controles.getObject().translateX(velocidade.x * delta);
controles.getObject().translateY(velocidade.y * delta);
controles.getObject().translateZ(velocidade.z * delta);
}
}
|
d717c0df06268e9606279be880d09d628265665c
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
OsmarHofman/WildWestFirstPerson
|
8df8f92f8c3b3e679a8736b9b61074986b736c1b
|
eed0be0295b5f592de6de51818cbf837dd12fd7f
|
refs/heads/master
|
<repo_name>deewlabs/CovidAssitUI<file_sep>/covid-assist-ui/src/api/saveHospital.js
import client from "./client";
const endpoint = "saveHospital";
const saveHospital = (payload) => client.post(`${endpoint}${payload}`);
export default { saveHospital };
<file_sep>/covid-assist-ui/src/components/hooks/useGeoLocation.js
import { useEffect, useState } from "react";
import MESSAGES from "../../const/messages";
function useGeoLocation(props) {
const [position, setPosition] = useState(null);
const [error, setError] = useState("");
useEffect(() => {
if ("geolocation" in navigator) {
console.log("Location available");
navigator.geolocation.getCurrentPosition(
function (position) {
console.log("Latitude is :", position.coords.latitude);
console.log("Longitude is :", position.coords.longitude);
console.log({ position });
setPosition(position);
},
function (error) {
console.log({ error });
console.error("Error Code = " + error.code + " - " + error.message);
setError(MESSAGES.errorLocationNotAllowed);
}
);
} else {
console.log("location unavailable");
setError(MESSAGES.errorBrowserNotCompatibleLocation);
}
}, []);
return { position, error };
}
export default useGeoLocation;
<file_sep>/README.md
# CovidAssitUI
React/Angular Code for Covid Assit
<file_sep>/covid-assist-ui/src/App.js
import React from "react";
import "./App.css";
import { BrowserRouter, Route, Redirect, Switch } from "react-router-dom";
import UserPatientForm from "./components/forms/UserPatientForm";
import HospitalReistrationForm from "./components/forms/HospitalReistrationForm";
import PatientEnrollmentForm from "./components/forms/PatientEnrollmentForm";
import Header from "./components/Header";
import SideDrawer from "./components/SideDrawer";
import Dashboard from "./components/Dashboard";
function App() {
return (
<>
<BrowserRouter basename="">
<Header />
<SideDrawer />
<Switch>
<Route path="/" exact render={() => <Redirect to="/dashboard" />} />
<Route path="/dashboard" component={Dashboard} />
<Route path="/user-patient" component={UserPatientForm} />
<Route
path="/hospital-registration"
component={HospitalReistrationForm}
/>
<Route path="/patient-enrollment" component={PatientEnrollmentForm} />
</Switch>
</BrowserRouter>
</>
);
}
export default App;
<file_sep>/covid-assist-ui/src/api/client.js
import axios from "axios";
import settings from "../config/settings";
export default axios.create({
baseURL: settings.apiUrl,
// headers: {
// "Access-Control-Allow-Origin": "*",
// },
});
<file_sep>/covid-assist-ui/src/components/Header.js
import React, { useState } from "react";
import { makeStyles } from "@material-ui/core/styles";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";
import IconButton from "@material-ui/core/IconButton";
import MenuIcon from "@material-ui/icons/Menu";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemText from "@material-ui/core/ListItemText";
import ChevronLeftIcon from "@material-ui/icons/ChevronLeft";
import Divider from "@material-ui/core/Divider";
import { withRouter } from "react-router-dom";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import AssignmentIcon from "@material-ui/icons/Assignment";
import SideDrawer from "./SideDrawer";
import LABELS from "../const/labels";
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
},
drawerHeader: {
display: "flex",
alignItems: "center",
padding: theme.spacing(0, 1),
// necessary for content to be below app bar
...theme.mixins.toolbar,
justifyContent: "flex-end",
},
}));
const anchor = "left";
function Header({ history, location }) {
const classes = useStyles();
const [isSideDrawerOpen, setIsSideDrawerOpen] = useState(false);
const list = () => (
<>
<div className={classes.drawerHeader}>
<IconButton onClick={() => setIsSideDrawerOpen(false)}>
<ChevronLeftIcon />
</IconButton>
</div>
<Divider />
<div className={classes.list} role="presentation">
<List>
{[
{ label: LABELS.dasboard, pathname: "/dashboard" },
{ label: LABELS.listPatientForm, pathname: "/user-patient" },
{
label: LABELS.listHospitalReg,
pathname: "/hospital-registration",
},
{
label: LABELS.listPatientEnrollment,
pathname: "/patient-enrollment",
},
].map((item, index) => (
<ListItem
button
key={index}
onClick={handleListItemSelect(item)}
onKeyDown={handleListItemSelect(item)}
selected={item.pathname === location.pathname}
>
<ListItemIcon>
<AssignmentIcon />
</ListItemIcon>
<ListItemText primary={item.label} />
</ListItem>
))}
</List>
</div>
</>
);
const handleListItemSelect = (selectedListItem) => (event) => {
if (
event.type === "keydown" &&
(event.key === "Tab" || event.key === "Shift")
) {
return;
}
history.push(selectedListItem.pathname);
setIsSideDrawerOpen(false);
};
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<IconButton
edge="start"
className={classes.menuButton}
color="inherit"
aria-label="menu"
onClick={() => {
setIsSideDrawerOpen(true);
}}
>
<MenuIcon />
</IconButton>
<Typography variant="h6" className={classes.title}>
Covid Assist
</Typography>
<Button color="inherit">Login</Button>
</Toolbar>
</AppBar>
<SideDrawer
list={list()}
anchor={anchor}
isOpen={isSideDrawerOpen}
onClose={() => setIsSideDrawerOpen(false)}
/>
</div>
);
}
export default withRouter(Header);
<file_sep>/covid-assist-ui/src/components/Dashboard.js
import React, { useEffect } from "react";
import GroupedBarChart from "./charts/GroupedBarChart";
import useApi from "./hooks/useApi";
import dashboardApi from "../api/dashboard";
function Dashboard(props) {
const dashBoardDataApi = useApi(dashboardApi.getDashboardData);
useEffect(() => {
dashBoardDataApi.request();
}, []);
return (
<div style={{ padding: "100px" }}>
{dashBoardDataApi.data.length > 0 && (
<GroupedBarChart
data={formatResponseForGroupChart(dashBoardDataApi.data[0])}
/>
)}
</div>
);
}
export default Dashboard;
function formatResponseForGroupChart(data) {
return [
{ name: "Ambulance Not Serviced", value: data.ambulanceNotServiced },
{ name: "Ambulance Serviced", value: data.ambulanceServiced },
{ name: "iCU Not Serviced", value: data.iCUNotServiced },
{ name: "iCU Serviced", value: data.iCUServiced },
{ name: "Isolation Bed Not Serviced", value: data.isolationBedNotServiced },
{ name: "Isolation Bed Serviced", value: data.isolationBedServiced },
{
name: "Oxygen Cylinder Not Serviced",
value: data.oxygenCylinderNotServiced,
},
{ name: "Oxygen Cylinder Serviced", value: data.oxygenCylinderServiced },
{ name: "Ventilator Not Serviced", value: data.ventilatorNotServiced },
{ name: "Ventilator Serviced", value: data.ventilatorServiced },
{ name: "Total Covid Tests Conducted", value : data.totalCovidTests},
{ name: "Total Positive Cases", value : data.totalPositiveTests}
];
}
<file_sep>/covid-assist-ui/src/api/savePatient.js
import client from "./client";
const endpoint = "savePatient";
const savePatient = (payload) => client.post(`${endpoint}${payload}`);
export default { savePatient };
<file_sep>/covid-assist-ui/src/components/forms/UserPatientForm.js
import React, { useEffect } from "react";
import CssBaseline from "@material-ui/core/CssBaseline";
import Typography from "@material-ui/core/Typography";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import Grid from "@material-ui/core/Grid";
import Container from "@material-ui/core/Container";
import FormControl from "@material-ui/core/FormControl";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Radio from "@material-ui/core/Radio";
import RadioGroup from "@material-ui/core/RadioGroup";
import FormLabel from "@material-ui/core/FormLabel";
import FormGroup from "@material-ui/core/FormGroup";
import Checkbox from "@material-ui/core/Checkbox";
import FormHelperText from "@material-ui/core/FormHelperText";
import Button from "@material-ui/core/Button";
import ButtonGroup from "@material-ui/core/ButtonGroup";
import DeleteIcon from "@material-ui/icons/Delete";
import SaveIcon from "@material-ui/icons/Save";
import { useForm } from "react-hook-form";
import Switch from "@material-ui/core/Switch";
import Divider from "@material-ui/core/Divider";
import useGeoLocation from "./../hooks/useGeoLocation";
import ErrorBanner from "./../ErrorBanner";
import LABELS from "../../const/labels";
import MESSAGES from "../../const/messages";
import useApi from "./../hooks/useApi";
import allCovidSymptonsApi from "../../api/allCovidSymptons";
import allMedicalConditionApi from "../../api/allMedicalCondition";
import savePatientApi from "../../api/savePatient";
import axios from "axios";
// import fakeCovidSymptoms from "../../temp/fakeAllCovidSymps";
import { getSavePatientPayload } from "./../../utils/payloadConstructorUtil";
const useStyles = makeStyles((theme) => ({
buttonGrp: {
// background: "white",
// position: "sticky",
// top: 20,
// bottom: 20,
// paddingTop: '40px',
// paddingBottom: '40px',
// zIndex: 5,
paddingTop: 8,
},
form: {
marginTop: 16,
},
}));
function UserPatientForm() {
const classes = useStyles();
const { position, error } = useGeoLocation();
const {
handleSubmit,
register,
errors,
reset,
trigger,
watch,
setValue,
} = useForm({
criteriaMode: "all",
defaultValues: {
lattitude: position?.coords?.latitude,
longitude: position?.coords?.longitude,
},
});
const getAllCovidSymptomsApi = useApi(
allCovidSymptonsApi.getAllCovidSymptoms
);
const getAllMedicalConditionApi = useApi(
allMedicalConditionApi.getAllMedicalConditions
);
const savePatientDataApi = useApi(savePatientApi.savePatient);
const watchFields = watch(["ambulanceRequired", "hospitalRequired"]);
useEffect(() => {
getAllCovidSymptomsApi.request();
getAllMedicalConditionApi.request();
}, []);
useEffect(() => {
setValue("lattitude", position?.coords?.latitude);
setValue("longitude", position?.coords?.longitude);
}, [position]);
useEffect(() => {
trigger(["needAmbulanceService", "lookingForHospitals"]);
}, [watchFields.needAmbulanceService, watchFields.lookingForHospitals]);
const onSubmit = async (data) => {
console.table(data);
const payload = getSavePatientPayload(data);
console.log(JSON.stringify(data));
const result = await savePatientDataApi.request(payload);
reset({
lattitude: position?.coords?.latitude,
longitude: position?.coords?.longitude,
});
console.log({ result });
};
return (
<>
<ErrorBanner errorMSG={error} />
<CssBaseline />
<Container maxWidth="md">
<Typography variant="h1">Patient form</Typography>
<Divider />
<form
className={classes.form}
noValidate
autoComplete="off"
onSubmit={handleSubmit(onSubmit)}
>
<Grid container spacing={3}>
<Grid item xs={12}>
<TextField
required
id="standard-required"
label={LABELS.name}
fullWidth
disabled={!position}
name="name"
variant="filled"
inputRef={register({
required: MESSAGES.errorNoBlank,
})}
error={errors.name}
helperText={errors.name?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
id="standard-required"
label={LABELS.age}
variant="filled"
name="age"
fullWidth
disabled={!position}
inputRef={register({
required: MESSAGES.errorNoBlank,
min: {
value: 1,
message: "must be greater than 1",
},
max: {
value: 99,
message: "must be lesser than 100",
},
pattern: {
value: /^[0-9]*$/,
message: MESSAGES.errorOnlyNumberAllowed,
},
})}
inputProps={{
maxLength: 2,
}}
error={errors.age}
helperText={errors.age?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<FormControl component="fieldset" required>
<FormLabel component="legend">{LABELS.sex}</FormLabel>
<RadioGroup aria-label="gender" name="sex" defaultValue="F">
<FormControlLabel
value="F"
control={<Radio inputRef={register} disabled={!position} />}
label="Female"
/>
<FormControlLabel
value="M"
control={<Radio inputRef={register} disabled={!position} />}
label="Male"
/>
</RadioGroup>
</FormControl>
</Grid>
<Grid item xs={12}>
<FormControl component="fieldset" className={classes.formControl}>
<FormLabel component="legend">
{LABELS.questionSymptoms}
</FormLabel>
<FormGroup>
{getAllCovidSymptomsApi.data.map((item) => (
<FormControlLabel
key={item.symptonId}
control={
<Checkbox
name={`covidSympton-${item.symptonId}`}
inputRef={register}
disabled={!position}
/>
}
label={item.symptons}
/>
))}
</FormGroup>
<FormHelperText>{LABELS.symptomsHelperText}</FormHelperText>
</FormControl>
</Grid>
<Grid item xs={12}>
<FormControl component="fieldset" className={classes.formControl}>
<FormLabel component="legend">
{LABELS.questionDiseaseList}
</FormLabel>
<FormGroup>
{getAllMedicalConditionApi.data.map((item) => (
<FormControlLabel
key={item.pastMedConId}
control={
<Checkbox
name={`medicalCondition-${item.pastMedConId}`}
inputRef={register}
disabled={!position}
/>
}
label={item.medCon}
/>
))}
</FormGroup>
</FormControl>
</Grid>
<Grid item xs={12}>
<FormControl component="fieldset">
<FormLabel component="legend">
{LABELS.questionTravelHistory}
</FormLabel>
<FormGroup>
<FormControlLabel
control={
<Switch
name="internationalTravel"
inputRef={register}
disabled={!position}
/>
}
/>
</FormGroup>
</FormControl>
</Grid>
<Grid item xs={12}>
<FormControl
component="fieldset"
error={errors.hospitalRequired}
required
>
<FormLabel component="legend" required>
{LABELS.questionServiceAmbulance}
</FormLabel>
<FormGroup>
<FormControlLabel
control={
<Switch
name="ambulanceRequired"
inputRef={register({
validate: (value) =>
value ||
watchFields.hospitalRequired ||
"Do you need Ambulance Service or Are you looking for Hospitals. One among these two fields must be selected as Yes.",
})}
required
disabled={!position}
/>
}
/>
</FormGroup>
<FormHelperText>
{errors.ambulanceRequired?.message}
</FormHelperText>
</FormControl>
</Grid>
<Grid item xs={12}>
<FormControl component="fieldset" error={errors.hospitalRequired}>
<FormLabel component="legend" required>
{LABELS.questionLookupHospitals}
</FormLabel>
<FormGroup>
<FormControlLabel
control={
<Switch
name="hospitalRequired"
inputRef={register({
validate: (value) =>
value ||
watchFields.ambulanceRequired ||
"Do you need Ambulance Service or Are you looking for Hospitals. One among these two fields must be selected as Yes.",
})}
required
disabled={!position}
defaultChecked
/>
}
/>
</FormGroup>
<FormHelperText>
{errors.hospitalRequired?.message}
</FormHelperText>
</FormControl>
</Grid>
<Grid item xs={12}>
<TextField
required
id="standard-required"
label={LABELS.contactNumber}
variant="filled"
name="contactNo"
fullWidth
disabled={!position}
inputRef={register({
required: MESSAGES.errorNoBlank,
minLength: {
value: 10,
message: "must be 10 characters",
},
maxLength: {
value: 10,
message: "must be 10 characters",
},
pattern: {
value: /^[0-9]*$/,
message: MESSAGES.errorOnlyNumberAllowed,
},
})}
inputProps={{
maxLength: 10,
}}
error={errors.contactNo}
helperText={errors.contactNo?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
id="standard-required"
label={LABELS.emailId}
variant="filled"
name="emailId"
fullWidth
disabled={!position}
inputRef={register({
required: MESSAGES.errorNoBlank,
pattern: {
value: /\S+@\S+\.\S+/,
message: MESSAGES.errorInvalidEmail,
},
})}
error={errors.emailId}
helperText={errors.emailId?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
id="standard-required"
label={LABELS.emergencyContactNumber}
variant="filled"
name="emergencyContactNo"
fullWidth
disabled={!position}
inputRef={register({
required: MESSAGES.errorNoBlank,
minLength: {
value: 10,
message: "must be 10 characters",
},
maxLength: {
value: 10,
message: "must be 10 characters",
},
pattern: {
value: /^[0-9]*$/,
message: MESSAGES.errorOnlyNumberAllowed,
},
})}
inputProps={{
maxLength: 10,
}}
error={errors.emergencyContactNo}
helperText={errors.emergencyContactNo?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
id="patientAddress"
label={LABELS.address}
variant="filled"
name="address"
fullWidth
disabled={!position}
inputRef={register}
multiline
rows={4}
rowsMax={4}
error={errors.address}
helperText={errors.address?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={6}>
<TextField
id="lattitude"
required
label={LABELS.lattitude}
variant="filled"
disabled={!position}
inputProps={{
readOnly: true,
}}
name="lattitude"
fullWidth
inputRef={register}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={6}>
<TextField
id="longitude"
required
label={LABELS.longitude}
variant="filled"
disabled={!position}
inputProps={{
readOnly: true,
}}
name="longitude"
fullWidth
inputRef={register}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<Divider />
<div className={classes.buttonGrp}>
<ButtonGroup
color="primary"
aria-label="outlined primary button group"
>
<Button
variant="outlined"
color="primary"
startIcon={<SaveIcon />}
type="submit"
disabled={!position}
>
Submit
</Button>
<Button
variant="outlined"
color="secondary"
startIcon={<DeleteIcon />}
onClick={reset}
disabled={!position}
>
Reset
</Button>
</ButtonGroup>
</div>
</Grid>
</Grid>
</form>
</Container>
</>
);
}
export default UserPatientForm;
<file_sep>/covid-assist-ui/src/utils/payloadConstructorUtil.js
export const getSavePatientPayload = ({
name,
age,
sex,
internationalTravel,
ambulanceRequired,
hospitalRequired,
contactNo,
emailId,
emergencyContactNo,
address,
lattitude,
longitude,
...rest
}) => {
const payload = {
name,
age: Number(age),
sex,
contactNo,
emailId,
emergencyContactNo,
address,
lattitude: Number(lattitude),
longitude: Number(longitude),
internationalTravel: internationalTravel ? "yes" : "no",
ambulanceRequired: ambulanceRequired ? "yes" : "no",
hospitalRequired: hospitalRequired ? "yes" : "no",
medicalCondition: Object.entries(rest)
.filter(([key, value]) => key.includes("medicalCondition-") && value)
.map(([key, value]) => key.split("-").pop())
.join(","),
covidSympton: Object.entries(rest)
.filter(([key, value]) => key.includes("covidSympton-") && value)
.map(([key, value]) => key.split("-").pop())
.join(","),
};
return `?${Object.entries(payload)
.filter(([key, value]) => value)
.map(([key, value]) => `${key}=${value}`)
.join("&")}`;
};
export const getSaveHospitalPayload = ({
hospitalName,
ambulanceServiceAvailable,
numberOfAmbulance,
totalIsolationBed,
totalIcu,
totalOxygenUnit,
totalVentilator,
contactNo,
emailId,
hospitalAddress,
lattitude,
longitude,
}) => {
const payload = {
hospitalName,
ambulanceServiceAvailable,
numberOfAmbulance,
totalIsolationBed,
totalIcu,
totalOxygenUnit,
totalVentilator,
contactNo,
emailId,
hospitalAddress,
lattitude,
longitude,
};
return `?${Object.entries(payload)
.filter(([key, value]) => value)
.map(([key, value]) => `${key}=${value}`)
.join("&")}`;
};
<file_sep>/covid-assist-ui/src/const/labels.js
export default Object.freeze({
name: "Name",
age: "Age",
sex: "Sex",
questionSymptoms: "Are you experiencing any of the following symptoms?",
questionDiseaseList: "Have you ever had?",
questionTravelHistory:
"Have you travelled anywhere internationally in the last 14 days?",
questionServiceAmbulance: "Do you need Ambulance Service?",
questionLookupHospitals: "Are you looking for Hospitals?",
contactNumber: "Contact Number",
emailId: "Email id",
emergencyContactNumber: "Emergency contact Number",
address: "Address",
currentLocation: "Current Location",
buttonSubmit: "Submit",
buttonReset: "Reset",
listPatientForm: "Patient form",
listHospitalReg: "Hospital Registration Form",
listPatientEnrollment: "Patient enrollment form",
symptomsCough: "Cough",
symptomsFever: "Fever",
symptomsBreathingDifficulty: "Diffuculty in Breathing",
symptomsNoneOfTheDiseaseList: "None of the Above",
symptomsHelperText:
"Would be nice to provide these questions which will help improve better recommendation.",
hospitalName: "Hospital Name",
availableServiceAmbulance: "Do you provide Ambulance services?",
numberOfAmbulance: "Number of Ambulances?",
availableIsolationWard: "Do you Have Isolation ward?",
numberIsolationBeds: "Number of Isolation beds for COVID-19",
numberIcuBeds: "Number of ICU beds for COVID-19",
numberOxygenUnits: "Number of Oxygen Units",
numberVentilators: "Number of Ventilators",
locationHospital: "Hospital Location",
patientId: "Patient Id",
enrollmentDate: "Date of Enrollment",
diseaseDiabetes: "Diabetes",
diseaseHypertension: "Hypertension",
diseaseLungDisease: "Lung disease",
diseaseHeartDisease: "Heart disease",
lattitude: "Latitude",
longitude: "Longitude",
dasboard: "Dashboard",
});
<file_sep>/covid-assist-ui/src/components/charts/GroupedBarChart.js
import React, { useState } from "react";
// import Plot from "react-plotly.js";
function GroupedBarChart({ data }) {
let barHeight = 30;
let barGroups = data.map((d, i) => (
<g transform={`translate(0, ${i * barHeight})`}>
<BarGroup d={d} barHeight={barHeight} />
</g>
));
return (
<svg width="100%" height="600">
<g className="container">
<text className="title" x="10" y="30">
Dashboard
</text>
<g className="chart" transform="translate(100,60)">
{barGroups}
</g>
</g>
</svg>
);
}
export default GroupedBarChart;
function BarGroup(props) {
let barPadding = 2;
let barColour = props.d.name.includes("Not") ? "red" : "#348AA7";
let widthScale = (d) => d * 30;
let width = widthScale(props.d.value);
let yMid = props.barHeight * 0.5;
return (
<g className="bar-group">
<text className="name-label" x="-6" y={yMid} alignmentBaseline="middle">
{props.d.name}
</text>
<rect
y={barPadding * 0.5}
width={width}
height={props.barHeight - barPadding}
fill={barColour}
/>
<text
className="value-label"
x={width - 8}
y={yMid}
alignmentBaseline="middle"
>
{props.d.value}
</text>
</g>
);
}
<file_sep>/covid-assist-ui/src/components/forms/patientEnrollmentForm.js
import React from "react";
import CssBaseline from "@material-ui/core/CssBaseline";
import Typography from "@material-ui/core/Typography";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import Grid from "@material-ui/core/Grid";
import Container from "@material-ui/core/Container";
import FormControl from "@material-ui/core/FormControl";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Radio from "@material-ui/core/Radio";
import RadioGroup from "@material-ui/core/RadioGroup";
import FormLabel from "@material-ui/core/FormLabel";
import FormGroup from "@material-ui/core/FormGroup";
import Checkbox from "@material-ui/core/Checkbox";
import FormHelperText from "@material-ui/core/FormHelperText";
import Button from "@material-ui/core/Button";
import ButtonGroup from "@material-ui/core/ButtonGroup";
import DeleteIcon from "@material-ui/icons/Delete";
import SaveIcon from "@material-ui/icons/Save";
import { useForm } from "react-hook-form";
import Switch from "@material-ui/core/Switch";
import Divider from "@material-ui/core/Divider";
import InputAdornment from "@material-ui/core/InputAdornment";
import IconButton from "@material-ui/core/IconButton";
import Search from "@material-ui/icons/Search";
import "react-datepicker/dist/react-datepicker.css";
import LABELS from "../../const/labels";
import MESSAGES from "../../const/messages";
const useStyles = makeStyles((theme) => ({
buttonGrp: {
// background: "white",
// position: "sticky",
// top: 20,
// bottom: 20,
// paddingTop: '40px',
// paddingBottom: '40px',
// zIndex: 5,
paddingTop: 8,
},
form: {
marginTop: 16,
},
}));
function PatientEnrollmentForm(props) {
const classes = useStyles();
const { handleSubmit, register, errors, reset, control } = useForm({
criteriaMode: "all",
defaultValues: {},
});
const onSubmit = (data) => {
console.table(data);
console.log(JSON.stringify(data));
};
return (
<>
{/* <ErrorBanner errorMSG={error} /> */}
<CssBaseline />
<Container maxWidth="md">
<Typography variant="h1">Patient enrollment form</Typography>
<Divider />
<form
className={classes.form}
noValidate
autoComplete="off"
onSubmit={handleSubmit(onSubmit)}
>
<Grid container spacing={3}>
<Grid item xs={12}>
<TextField
required
id="patientId"
label={LABELS.patientId}
fullWidth
name="patientId"
variant="filled"
inputRef={register({
required: MESSAGES.errorNoBlank,
})}
error={errors.patientId}
helperText={errors.patientId?.message}
InputLabelProps={{
shrink: true,
}}
InputProps={{
endAdornment: (
<InputAdornment>
<IconButton
aria-label="search patient id"
onClick={() => alert("search triggered")}
// onMouseDown={handleMouseDownPassword}
>
<Search />
</IconButton>
</InputAdornment>
),
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
id="patientId"
label={LABELS.name}
fullWidth
name="patientName"
variant="filled"
inputRef={register({
required: MESSAGES.errorNoBlank,
})}
error={errors.patientName}
helperText={errors.patientName?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
id="standard-required"
label={LABELS.age}
variant="filled"
name="patientAge"
fullWidth
inputRef={register({
required: MESSAGES.errorNoBlank,
min: {
value: 1,
message: "must be greater than 1",
},
max: {
value: 99,
message: "must be lesser than 100",
},
pattern: {
value: /^[0-9]*$/,
message: MESSAGES.errorOnlyNumberAllowed,
},
})}
inputProps={{
maxLength: 2,
}}
error={errors.patientAge}
helperText={errors.patientAge?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<FormControl component="fieldset" required>
<FormLabel component="legend">{LABELS.sex}</FormLabel>
<RadioGroup
aria-label="gender"
name="patientGender"
defaultValue="female"
>
<FormControlLabel
value="female"
control={<Radio inputRef={register} />}
label="Female"
/>
<FormControlLabel
value="male"
control={<Radio inputRef={register} />}
label="Male"
/>
</RadioGroup>
</FormControl>
</Grid>
<Grid item xs={12}>
<TextField
id="date"
required
label={LABELS.enrollmentDate}
type="date"
name="enrollmentDate"
// defaultValue="2017-05-24"
className={classes.textField}
InputLabelProps={{
shrink: true,
}}
inputRef={register({
required: MESSAGES.errorNoBlank,
})}
error={errors.enrollmentDate}
helperText={errors.enrollmentDate?.message}
/>
</Grid>
<Grid item xs={12}>
<FormControl component="fieldset" className={classes.formControl}>
<FormLabel component="legend">
{LABELS.questionSymptoms}
</FormLabel>
<FormGroup>
<FormControlLabel
control={<Checkbox name="cough" inputRef={register} />}
label={LABELS.symptomsCough}
/>
<FormControlLabel
control={<Checkbox name="fever" inputRef={register} />}
label={LABELS.symptomsFever}
/>
<FormControlLabel
control={
<Checkbox
name="breathingDifficulty"
inputRef={register}
/>
}
label={LABELS.symptomsBreathingDifficulty}
/>
<FormControlLabel
control={
<Checkbox
name="noneOfTheDiseaseList"
inputRef={register}
/>
}
label={LABELS.symptomsNoneOfTheDiseaseList}
/>
</FormGroup>
<FormHelperText>{LABELS.symptomsHelperText}</FormHelperText>
</FormControl>
</Grid>
<Grid item xs={12}>
<FormControl component="fieldset" className={classes.formControl}>
<FormLabel component="legend">
{LABELS.questionDiseaseList}
</FormLabel>
<FormGroup>
<FormControlLabel
control={
<Checkbox name="diseaseDiabetes" inputRef={register} />
}
label={LABELS.diseaseDiabetes}
/>
<FormControlLabel
control={
<Checkbox
name="diseaseHypertension"
inputRef={register}
/>
}
label={LABELS.diseaseHypertension}
/>
<FormControlLabel
control={
<Checkbox name="diseaseLungDisease" inputRef={register} />
}
label={LABELS.diseaseLungDisease}
/>
<FormControlLabel
control={
<Checkbox
name="diseaseHeartDisease"
inputRef={register}
/>
}
label={LABELS.diseaseHeartDisease}
/>
<FormControlLabel
control={
<Checkbox name="diseaseNone" inputRef={register} />
}
label={LABELS.symptomsNoneOfTheDiseaseList}
/>
</FormGroup>
</FormControl>
</Grid>
<Grid item xs={12}>
<FormControl component="fieldset">
<FormLabel component="legend">
{LABELS.questionTravelHistory}
</FormLabel>
<FormGroup>
<FormControlLabel
control={
<Switch
name="internationalTravelLast14Days"
inputRef={register}
/>
}
/>
</FormGroup>
</FormControl>
</Grid>
<Grid item xs={12}>
<TextField
required
id="standard-required"
label={LABELS.contactNumber}
variant="filled"
name="patientContactNumber"
fullWidth
inputRef={register({
required: MESSAGES.errorNoBlank,
pattern: {
value: /^[0-9]*$/,
message: MESSAGES.errorOnlyNumberAllowed,
},
})}
inputProps={{
maxLength: 15,
}}
error={errors.patientContactNumber}
helperText={errors.patientContactNumber?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
id="standard-required"
label={LABELS.emailId}
variant="filled"
name="emailId"
fullWidth
inputRef={register({
required: MESSAGES.errorNoBlank,
pattern: {
value: /\S+@\S+\.\S+/,
message: MESSAGES.errorInvalidEmail,
},
})}
error={errors.emailId}
helperText={errors.emailId?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
id="standard-required"
label={LABELS.emergencyContactNumber}
variant="filled"
name="patientEmergencyContactNumber"
fullWidth
inputRef={register({
required: MESSAGES.errorNoBlank,
pattern: {
value: /^[0-9]*$/,
message: MESSAGES.errorOnlyNumberAllowed,
},
})}
inputProps={{
maxLength: 15,
}}
error={errors.patientEmergencyContactNumber}
helperText={errors.patientEmergencyContactNumber?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
id="patientAddress"
label={LABELS.address}
variant="filled"
name="patientAddress"
fullWidth
required
inputRef={register({
required: MESSAGES.errorNoBlank,
})}
multiline
rows={4}
rowsMax={4}
error={errors.patientAddress}
helperText={errors.patientAddress?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<Divider />
<div className={classes.buttonGrp}>
<ButtonGroup
color="primary"
aria-label="outlined primary button group"
>
<Button
variant="outlined"
color="primary"
startIcon={<SaveIcon />}
type="submit"
>
Submit
</Button>
<Button
variant="outlined"
color="secondary"
startIcon={<DeleteIcon />}
onClick={reset}
>
Reset
</Button>
</ButtonGroup>
</div>
</Grid>
</Grid>
</form>
</Container>
</>
);
}
export default PatientEnrollmentForm;
<file_sep>/covid-assist-ui/src/components/forms/HospitalReistrationForm.js
import React, { useEffect } from "react";
import CssBaseline from "@material-ui/core/CssBaseline";
import Typography from "@material-ui/core/Typography";
import { makeStyles } from "@material-ui/core/styles";
import TextField from "@material-ui/core/TextField";
import Grid from "@material-ui/core/Grid";
import Container from "@material-ui/core/Container";
import FormControl from "@material-ui/core/FormControl";
import FormControlLabel from "@material-ui/core/FormControlLabel";
import Radio from "@material-ui/core/Radio";
import RadioGroup from "@material-ui/core/RadioGroup";
import FormLabel from "@material-ui/core/FormLabel";
import FormGroup from "@material-ui/core/FormGroup";
import Checkbox from "@material-ui/core/Checkbox";
import FormHelperText from "@material-ui/core/FormHelperText";
import Button from "@material-ui/core/Button";
import ButtonGroup from "@material-ui/core/ButtonGroup";
import DeleteIcon from "@material-ui/icons/Delete";
import SaveIcon from "@material-ui/icons/Save";
import { useForm } from "react-hook-form";
import Switch from "@material-ui/core/Switch";
import Divider from "@material-ui/core/Divider";
import useGeoLocation from "./../hooks/useGeoLocation";
import ErrorBanner from "./../ErrorBanner";
import LABELS from "../../const/labels";
import MESSAGES from "../../const/messages";
import saveHospitalApi from "../../api/saveHospital";
import useApi from "./../hooks/useApi";
import { getSaveHospitalPayload } from "../../utils/payloadConstructorUtil";
const useStyles = makeStyles((theme) => ({
buttonGrp: {
// background: "white",
// position: "sticky",
// top: 20,
// bottom: 20,
// paddingTop: '40px',
// paddingBottom: '40px',
// zIndex: 5,
paddingTop: 8,
},
form: {
marginTop: 16,
},
}));
function HospitalReistrationForm() {
const classes = useStyles();
const { position, error } = useGeoLocation();
const { handleSubmit, register, errors, reset, setValue } = useForm({
criteriaMode: "all",
defaultValues: {},
});
const saveHospitalDataApi = useApi(saveHospitalApi.saveHospital);
useEffect(() => {
setValue("lattitude", position?.coords?.latitude);
setValue("longitude", position?.coords?.longitude);
}, [position]);
const onSubmit = async (data) => {
console.table(data);
const payload = getSaveHospitalPayload(data);
const result = await saveHospitalDataApi.request(payload);
reset();
console.log({ result });
};
return (
<>
<ErrorBanner errorMSG={error} />
<CssBaseline />
<Container maxWidth="md">
<Typography variant="h1">Hospital registration form</Typography>
<Divider />
<form
className={classes.form}
noValidate
autoComplete="off"
onSubmit={handleSubmit(onSubmit)}
>
<Grid container spacing={3}>
<Grid item xs={12}>
<TextField
required
id="hospitalName"
label={LABELS.hospitalName}
fullWidth
disabled={!position}
name="hospitalName"
variant="filled"
inputRef={register({
required: MESSAGES.errorNoBlank,
})}
error={errors.hospitalName}
helperText={errors.hospitalName?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<FormControl component="fieldset">
<FormLabel component="legend" required>
{LABELS.availableServiceAmbulance}
</FormLabel>
<FormGroup>
<FormControlLabel
control={
<Switch
name="ambulanceServiceAvailable"
inputRef={register}
required
disabled={!position}
/>
}
/>
</FormGroup>
</FormControl>
</Grid>
<Grid item xs={12}>
<TextField
required
id="numberOfAmbulance"
label={LABELS.numberOfAmbulance}
variant="filled"
name="numberOfAmbulance"
fullWidth
disabled={!position}
inputRef={register({
required: MESSAGES.errorNoBlank,
pattern: {
value: /^[0-9]*$/,
message: MESSAGES.errorOnlyNumberAllowed,
},
})}
error={errors.numberOfAmbulance}
helperText={errors.numberOfAmbulance?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<FormControl component="fieldset">
<FormLabel component="legend" required>
{LABELS.availableIsolationWard}
</FormLabel>
<FormGroup>
<FormControlLabel
control={
<Switch
name="availableIsolationWard"
inputRef={register}
required
disabled={!position}
/>
}
/>
</FormGroup>
</FormControl>
</Grid>
<Grid item xs={12}>
<TextField
required
id="numberIsolationBeds"
label={LABELS.numberIsolationBeds}
variant="filled"
name="totalIsolationBed"
fullWidth
disabled={!position}
inputRef={register({
required: MESSAGES.errorNoBlank,
pattern: {
value: /^[0-9]*$/,
message: MESSAGES.errorOnlyNumberAllowed,
},
})}
error={errors.totalIsolationBed}
helperText={errors.totalIsolationBed?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
id="numberIcuBeds"
label={LABELS.numberIcuBeds}
variant="filled"
name="totalIcu"
fullWidth
disabled={!position}
inputRef={register({
required: MESSAGES.errorNoBlank,
pattern: {
value: /^[0-9]*$/,
message: MESSAGES.errorOnlyNumberAllowed,
},
})}
error={errors.totalIcu}
helperText={errors.totalIcu?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
id="numberOxygenUnits"
label={LABELS.numberOxygenUnits}
variant="filled"
name="totalOxygenUnit"
fullWidth
disabled={!position}
inputRef={register({
required: MESSAGES.errorNoBlank,
pattern: {
value: /^[0-9]*$/,
message: MESSAGES.errorOnlyNumberAllowed,
},
})}
error={errors.totalOxygenUnit}
helperText={errors.totalOxygenUnit?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
id="numberVentilators"
label={LABELS.numberVentilators}
variant="filled"
name="totalVentilator"
fullWidth
disabled={!position}
inputRef={register({
required: MESSAGES.errorNoBlank,
pattern: {
value: /^[0-9]*$/,
message: MESSAGES.errorOnlyNumberAllowed,
},
})}
error={errors.totalVentilator}
helperText={errors.totalVentilator?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
id="contactNumber"
label={LABELS.contactNumber}
variant="filled"
name="contactNo"
fullWidth
disabled={!position}
inputRef={register({
required: MESSAGES.errorNoBlank,
minLength: {
value: 10,
message: "must be 10 characters",
},
maxLength: {
value: 10,
message: "must be 10 characters",
},
pattern: {
value: /^[0-9]*$/,
message: MESSAGES.errorOnlyNumberAllowed,
},
})}
inputProps={{
maxLength: 10,
}}
error={errors.contactNo}
helperText={errors.contactNo?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
required
id="emailId"
label={LABELS.emailId}
variant="filled"
name="emailId"
fullWidth
disabled={!position}
inputRef={register({
required: MESSAGES.errorNoBlank,
pattern: {
value: /\S+@\S+\.\S+/,
message: MESSAGES.errorInvalidEmail,
},
})}
error={errors.emailId}
helperText={errors.emailId?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<TextField
id="hospitalAddress"
required
label={LABELS.address}
variant="filled"
name="hospitalAddress"
fullWidth
disabled={!position}
inputRef={register({
required: MESSAGES.errorNoBlank,
})}
multiline
rows={4}
rowsMax={4}
error={errors.hospitalAddress}
helperText={errors.hospitalAddress?.message}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={6}>
<TextField
id="lattitude"
required
label={LABELS.lattitude}
variant="filled"
disabled={!position}
inputProps={{
readOnly: true,
}}
name="lattitude"
fullWidth
inputRef={register}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={6}>
<TextField
id="longitude"
required
label={LABELS.longitude}
variant="filled"
disabled={!position}
inputProps={{
readOnly: true,
}}
name="longitude"
fullWidth
inputRef={register}
InputLabelProps={{
shrink: true,
}}
/>
</Grid>
<Grid item xs={12}>
<Divider />
<div className={classes.buttonGrp}>
<ButtonGroup
color="primary"
aria-label="outlined primary button group"
>
<Button
variant="outlined"
color="primary"
startIcon={<SaveIcon />}
type="submit"
disabled={!position}
>
Submit
</Button>
<Button
variant="outlined"
color="secondary"
startIcon={<DeleteIcon />}
onClick={reset}
disabled={!position}
>
Reset
</Button>
</ButtonGroup>
</div>
</Grid>
</Grid>
</form>
</Container>
</>
);
}
export default HospitalReistrationForm;
|
067c8330790e7f1813fdd7a6e9c8fdfbfcab40a4
|
[
"JavaScript",
"Markdown"
] | 14
|
JavaScript
|
deewlabs/CovidAssitUI
|
2791e650f77aca0f8dd6823643d137af7596655f
|
d9fb6cca483b74e2f0bdd19921a00c0a4bcb93a1
|
refs/heads/master
|
<repo_name>pohl/Explorem<file_sep>/Sources/Explorem/LoremParser.swift
// LoremParser.swift
// SeinfeldChain
//
// Created by pohl on 6/20/14.
// Copyright (c) 2014 pohl. All rights reserved.
//
import Foundation
import StringScanner
let alphanumeric = CharactersSet.alphaNumeric
let whitespace = CharactersSet.space
let wordTerminators = CharactersSet.string(".,; ")
enum Punctuation {
case Comma
case Period
case Semicolon
case Unknown
case None
var description: String {
switch self {
case .Comma:
return ","
case .Period:
return "."
case .Semicolon:
return ";"
case .Unknown:
return "[UNKNOWN]"
case .None:
return "[NONE]"
}
}
}
extension StringScanner {
func advanceToNextWord() -> String? {
return self.scan(untilCharacterSet: alphanumeric).toString()
}
func checkForPunctuation() -> Punctuation? {
let string = self.scan(untilCharacterSet: whitespace).toString()
if let string = string {
if "," == string {
return Punctuation.Comma
} else if "." == string {
return Punctuation.Period
} else if ";" == string {
return Punctuation.Semicolon
} else {
return Punctuation.Unknown
}
} else {
return nil
}
}
func checkForNewParagraph() -> Bool {
let whitespace = self.scan(untilCharacterSet: alphanumeric).toString() ?? ""
let hasNewline = whitespace.contains("\n")
let length = whitespace.count
let hasSpace = whitespace.contains(" ")
return hasNewline
}
func checkForWord() -> Token? {
let word = self.scan(untilCharacterSet: wordTerminators).toString()
if let word = word {
return Token.Word(word.lowercased())
} else {
return nil
}
}
func nextPhrase() -> Phrase? {
var result: [Token] = []
var punctuation: Punctuation? = nil
while punctuation == nil {
let _ = self.advanceToNextWord()
let word = self.scan(untilCharacterSet: wordTerminators).toString()
if let word = word {
result.append(Token.Word(word.lowercased()))
punctuation = checkForPunctuation()
} else {
punctuation = Punctuation.None
}
}
if let punctuation = punctuation {
result.append(Token.Punctuation(punctuation.description))
if punctuation == Punctuation.Semicolon {
NSLog("hmm")
}
}
return !result.isEmpty ? Phrase(fromTokens: result) : nil
}
func nextSentence() -> Sentence? {
var phrases: [Phrase] = []
var phrase: Phrase? = nil
outerLoop: while true {
phrase = nextPhrase()
if let phrase = phrase {
phrases.append(phrase)
if phrase.isSentenceTerminator {
break outerLoop
} else {
continue
}
} else {
break outerLoop
}
}
return phrases.count != 0 ? Sentence(fromPhrases: phrases) : nil
}
func nextParagraph() -> Paragraph? {
var result: [Sentence] = []
var foundNewParagraph = false
while !foundNewParagraph {
let sentence = self.nextSentence()
if let sentence = sentence {
result.append(sentence)
}
foundNewParagraph = checkForNewParagraph()
}
return !result.isEmpty ? Paragraph(fromSentences: result) : nil
}
}
@available(OSX 10.15, *)
class LoremParser {
class func readLorem(index: Int) -> String? {
let filename = FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Code")
.appendingPathComponent("Explorem")
.appendingPathComponent("Resources")
.appendingPathComponent("loremipsum\(index).txt")
var lorem: String? = nil
do {
lorem = try String(contentsOf: filename, encoding: String.Encoding.utf8)
} catch {
NSLog("yo")
}
return lorem
}
func parseParagraphs(string: String) -> [Paragraph] {
let scanner = StringScanner(string: string)
var paragraphs: [Paragraph] = []
while true {
if let paragraph = scanner.nextParagraph() {
paragraphs.append(paragraph)
} else {
break
}
}
return paragraphs
}
func readAllParagraphs() -> [Paragraph] {
var paragraphs: [Paragraph] = []
for i in 0...0 {
let rawString = LoremParser.readLorem(index: i)!
let moreParagraphs = self.parseParagraphs(string: rawString)
paragraphs = paragraphs + moreParagraphs
}
return paragraphs
}
}
extension ScannerResult {
func toString() -> String? {
switch self {
case .end:
return nil
case .none:
return nil
case .value(let s):
return s
}
}
}
<file_sep>/Sources/Explorem/Models.swift
//
// Models.swift
// SeinfeldChain
//
// Created by pohl on 6/24/14.
// Copyright (c) 2014 pohl. All rights reserved.
//
import Foundation
protocol HasWords: Hashable {
var words: [String] { get }
}
enum Token: Hashable {
case Word(String)
case Punctuation(String)
var description: String {
switch self {
case .Word(let w):
return w
case .Punctuation(let p):
return p
}
}
func hash(into hasher: inout Hasher) {
switch self {
case .Word(let w):
hasher.combine(w.hashValue)
case .Punctuation(let p):
hasher.combine(p.hashValue)
}
}
var isWord: Bool {
switch self {
case .Word(_):
return true
default:
return false
}
}
var isSentenceTerminator: Bool {
switch self {
case .Word:
return false
case .Punctuation(let p):
return p != ","
}
}
}
func == (lhs: Token, rhs: Token) -> Bool {
switch (lhs, rhs) {
case (.Word(let w1), .Word(let w2)):
return w1 == w2
case (.Punctuation(let p1), .Punctuation(let p2)):
return p1 == p2
default:
return false
}
}
struct Phrase: CustomStringConvertible, HasWords {
var tokens:[Token]
init(fromTokens t: [Token]) {
tokens = t
}
var words: [String] {
return tokens
.filter { $0.isWord }
.map { $0.description }
}
var description: String {
return tokens.map { $0.description }.joined(separator: " ")
}
func hash(into hasher: inout Hasher) {
hasher.combine(tokens)
}
var isSentenceTerminator: Bool {
return tokens
.filter { $0.isSentenceTerminator }
.count != 0
}
}
struct Sentence: CustomStringConvertible, HasWords {
var phrases:[Phrase]
init(fromPhrases p: [Phrase]) {
phrases = p
}
var tokens: [Token] {
return phrases
.map { $0.tokens }
.flatMap { $0 }
}
var words: [String] {
return phrases
.map { $0.words }
.flatMap { $0 }
}
var description: String {
return tokens.map { $0.description }.joined(separator: " ")
}
func hash(into hasher: inout Hasher) {
hasher.combine(phrases)
}
}
struct Paragraph: CustomStringConvertible, HasWords {
var sentences:[Sentence]
init(fromSentences p: [Sentence]) {
sentences = p
}
var tokens: [Token] {
return sentences
.map { $0.tokens }
.flatMap { $0 }
}
var words: [String] {
return sentences
.map { $0.words }
.flatMap { $0 }
}
var description: String {
return tokens.map { $0.description }.joined(separator: " ")
}
func hash(into hasher: inout Hasher) {
hasher.combine(sentences)
}
}
extension HasWords {
func findRepeatedWords() -> Set<String> {
let words = self.words
var wordsUsed: Set<String> = Set()
var repeatedWords: Set<String> = Set()
for word in words {
if wordsUsed.contains(word) {
repeatedWords.insert(word)
}
wordsUsed.insert(word)
}
return repeatedWords
}
func hasRepatedWords() -> Bool {
return findRepeatedWords().count != 0
}
}
<file_sep>/Sources/Explorem/Timer.swift
//
// Timer.swift
// Explorem
//
// Created by <NAME> on 7/28/14.
// Copyright (c) 2014 the screaming organization. All rights reserved.
//
import Foundation
func printMeasurement(title:String, operation:()->()) {
let measurement = measure(operation: operation)
let timeElapsed = Double(round(100*measurement)/100)
print("Time elapsed for \(title): \(timeElapsed)s")
}
func measure (operation: ()->()) -> Double {
let startTime = CFAbsoluteTimeGetCurrent()
operation()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
return Double(timeElapsed)
}
<file_sep>/Tests/LinuxMain.swift
import XCTest
import ExploremTests
var tests = [XCTestCaseEntry]()
tests += ExploremTests.allTests()
XCTMain(tests)
<file_sep>/Sources/Explorem/main.swift
//
// main.swift
// Explorem
//
// Created by <NAME> on 7/27/14.
// Copyright (c) 2014 the screaming organization. All rights reserved.
//
import Foundation
extension Int {
func percent(of total: Int) -> Int {
return (self * 200 + total)/(2 * total)
}
}
private func displaySentences(_ sentenceCounts: Multiset<Sentence>) {
let sortedSentences = sentenceCounts
.dictionary
.sorted(by: { $0.0.tokens.count < $1.0.tokens.count })
for (key, value) in sortedSentences {
print("\(value): \(key)")
}
}
private func displayLengths<T>(_ counts: Multiset<T>) where T: HasWords {
var lengths = Multiset<Int>()
var total = 0
for (key, value) in counts {
lengths.add(item: key.words.count)
total += value
}
let sortedLengths = lengths.dictionary.sorted(by: { $0.0 < $1.0 })
for (key, value) in sortedLengths {
print("\(key): \(value.percent(of: total))")
}
}
private func displayWords(_ wordCounts: Multiset<String>) {
let sortedWords = wordCounts.dictionary.sorted(by: { $0.1 < $1.1 })
for (key, value) in sortedWords {
print("\(value): \(key)")
}
print("\(wordCounts.dictionary.count) unique words in sample")
}
private func displayPhrases(_ phraseCounts: Multiset<Phrase>) {
let sortedPhrases = phraseCounts
.dictionary
.sorted(by: { $0.0.tokens.count < $1.0.tokens.count })
.sorted(by: { $0.1 < $1.1 })
for (key, value) in sortedPhrases {
print("\(value): \(key)")
}
print("\(phraseCounts.dictionary.count) unique phrases in sample")
}
private func displayRepeats<T>(_ counts: Multiset<T>) where T: HasWords {
var repeats = Multiset<String>()
for (key, _) in counts {
repeats.add(items: key.findRepeatedWords())
}
let sortedRepeats = repeats
.dictionary
.sorted(by: { $0.1 < $1.1 })
for (key, value) in sortedRepeats {
print("\(value): \(key)")
}
}
@available(OSX 10.15, *)
func run() -> () {
let parser = LoremParser()
let paragraphs: [Paragraph] = parser
.readAllParagraphs()
let sentences = paragraphs
.map { $0.sentences }
.flatMap { $0 }
.filter( {!cannedSentences.contains($0) })
printMeasurement(title: "main", operation: {
var sentenceCounts = Multiset<Sentence>()
var phraseCounts = Multiset<Phrase>()
var wordCounts = Multiset<String>()
for sentence in sentences {
sentenceCounts.add(item: sentence)
for phrase in sentence.phrases {
phraseCounts.add(item: phrase)
}
for word in sentence.words {
wordCounts.add(item: word)
}
}
displaySentences(sentenceCounts)
//displayLengths(sentenceCounts)
//displayRepeats(sentenceCounts)
//displayWords(wordCounts)
//displayPhrases(phraseCounts)
//displayLengths(phraseCounts)
//displayRepeats(sentenceCounts)
})
}
if #available(OSX 10.15, *) {
run()
} else {
// Fallback on earlier versions
}
<file_sep>/Sources/Explorem/MarkovModel.swift
//
// MarkovModel.swift
// Explorem
//
// Created by <NAME> on 8/1/14.
// Copyright (c) 2014 the screaming organization. All rights reserved.
//
import Foundation
public struct State: CustomStringConvertible, Equatable, Hashable {
let penultimate: String?
let ultimate: String?
init(penultimate: String?, ultimate: String?) {
self.penultimate = penultimate
self.ultimate = ultimate
}
init() {
self.penultimate = nil
self.ultimate = nil
}
public var description: String {
return "(\(penultimate ?? ""),\(ultimate ?? ""))"
}
public func hash(into hasher: inout Hasher) {
hasher.combine(penultimate)
hasher.combine(ultimate)
}
}
public func == (lhs: State, rhs: State) -> Bool {
return lhs.penultimate == rhs.penultimate && lhs.ultimate == rhs.ultimate
}
public class StateEdges {
private var subsequentWords: Multiset<String> = Multiset()
private var total: UInt32 = 0
init() {
}
func addWord(word: String) {
subsequentWords.add(item: word)
total = total + 1
}
func nextState(current: State) -> State {
let randomNumber = Int(arc4random_uniform(total))
var n = 0
for (word, count) in subsequentWords {
n = n + count
if (n > randomNumber) {
return State(penultimate: current.ultimate, ultimate: word)
}
}
return State()
}
}
<file_sep>/README.md
# Explorem
A description of this package.
<file_sep>/Sources/Explorem/Sentences.swift
//
// File.swift
//
//
// Created by Pohl on 8/4/19.
//
import Foundation
let cannedSentences = [
Sentence(fromPhrases: loremIpsum),
Sentence(fromPhrases: interdumEt),
Sentence(fromPhrases: cumSociis),
Sentence(fromPhrases: pellentesqueHabitant),
Sentence(fromPhrases: classAptent),
Sentence(fromPhrases: nullaFacilisi),
Sentence(fromPhrases: vestibulumAnte),
Sentence(fromPhrases: suspendissePotenti),
Sentence(fromPhrases: aliquamErat),
Sentence(fromPhrases: inHac),
]
private let loremIpsum:[Phrase] = [
Phrase(fromTokens: [
.Word("lorem"),
.Word("ipsum"),
.Word("dolor"),
.Word("sit"),
.Word("amet"),
.Punctuation(","),
]),
Phrase(fromTokens: [
.Word("consectetur"),
.Word("adipiscing"),
.Word("elit"),
.Punctuation("."),
]),
]
private let interdumEt:[Phrase] = [
Phrase(fromTokens: [
.Word("interdum"),
.Word("et"),
.Word("malesuada"),
.Word("fames"),
.Word("ac"),
.Word("ante"),
.Word("ipsum"),
.Word("primis"),
.Word("in"),
.Word("faucibus"),
.Punctuation("."),
]),
]
private let cumSociis:[Phrase] = [
Phrase(fromTokens: [
.Word("cum"),
.Word("sociis"),
.Word("natoque"),
.Word("penatibus"),
.Word("et"),
.Word("magnis"),
.Word("dis"),
.Word("parturient"),
.Word("montes"),
.Punctuation(","),
]),
Phrase(fromTokens: [
.Word("nascetur"),
.Word("ridiculus"),
.Word("mus"),
.Punctuation("."),
]),
]
private let pellentesqueHabitant:[Phrase] = [
Phrase(fromTokens: [
.Word("pellentesque"),
.Word("habitant"),
.Word("morbi"),
.Word("tristique"),
.Word("senectus"),
.Word("et"),
.Word("netus"),
.Word("et"),
.Word("malesuada"),
.Word("fames"),
.Word("ac"),
.Word("turpis"),
.Word("egestas"),
.Punctuation("."),
]),
]
private let classAptent:[Phrase] = [
Phrase(fromTokens: [
.Word("class"),
.Word("aptent"),
.Word("taciti"),
.Word("sociosqu"),
.Word("ad"),
.Word("litora"),
.Word("torquent"),
.Word("per"),
.Word("conubia"),
.Word("nostra"),
.Punctuation(","),
]),
Phrase(fromTokens: [
.Word("per"),
.Word("inceptos"),
.Word("himenaeos"),
.Punctuation("."),
]),
]
private let nullaFacilisi:[Phrase] = [
Phrase(fromTokens: [
.Word("nulla"),
.Word("facilisi"),
.Punctuation("."),
]),
]
private let vestibulumAnte:[Phrase] = [
Phrase(fromTokens: [
.Word("vestibulum"),
.Word("ante"),
.Word("ipsum"),
.Word("primis"),
.Word("in"),
.Word("faucibus"),
.Word("orci"),
.Word("luctus"),
.Word("et"),
.Word("ultrices"),
.Word("posuere"),
.Word("cubilia"),
.Word("curae"),
.Punctuation(";"),
]),
]
private let suspendissePotenti:[Phrase] = [
Phrase(fromTokens: [
.Word("suspendisse"),
.Word("potenti"),
.Punctuation("."),
]),
]
private let aliquamErat:[Phrase] = [
Phrase(fromTokens: [
.Word("aliquam"),
.Word("erat"),
.Word("volutpat"),
.Punctuation("."),
]),
]
private let inHac:[Phrase] = [
Phrase(fromTokens: [
.Word("in"),
.Word("hac"),
.Word("habitasse"),
.Word("platea"),
.Word("dictumst"),
.Punctuation("."),
]),
]
<file_sep>/Sources/Explorem/Multiset.swift
// Copyright (c) 2014 <NAME>. All rights reserved.
struct Multiset<T: Hashable>: Sequence, Equatable {
var dictionary: Dictionary<T,Int> = [:]
mutating func add(item: T) -> () {
if let currentCount = dictionary[item] {
dictionary.updateValue(currentCount + 1, forKey: item)
} else {
dictionary.updateValue(1, forKey: item)
}
}
mutating func add(items: Set<T>) -> () {
for item in items {
self.add(item: item)
}
}
func count(item: T) -> Int {
if let currentCount = dictionary[item] {
return currentCount
} else {
return 0
}
}
func makeIterator() -> DictionaryIterator<T,Int> {
return dictionary.makeIterator()
}
// func generate() -> DictionaryGenerator<T,Int> {
// return dictionary.generate()
// }
subscript (i: T) -> Int? {
get {
return dictionary[i]
}
}
}
func == <T: Hashable> (lhs: Multiset<T>, rhs: Multiset<T>) -> Bool {
return lhs.dictionary == rhs.dictionary
}
|
ff44c66c876d05bac09263c120c95318caaed01e
|
[
"Swift",
"Markdown"
] | 9
|
Swift
|
pohl/Explorem
|
38bb7a214793c4be0ca382804074e5c444e84701
|
604791ee4cf21b6fe2a00d30cd30c586b03bf3c7
|
refs/heads/master
|
<file_sep>using System;
using System.IO;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mame2LCD
{
class processScraper
{
List<string> procs = new List<string>();
string watchFile = @"d:\mame\etc\data.dat";
public string currentTitle = "";
public bool running = true;
public processScraper()
{
while (running)
{
bool noMame = true;
procs.Clear();
System.Threading.Thread.Sleep(1000);
foreach (Process p in Process.GetProcesses())
{
if (p.MainWindowTitle != "Mame2LCD")
{
procs.Add(p.ProcessName);
string name = p.ProcessName.ToLower();
string title = p.MainWindowTitle.Replace("MAME:", "")
.Split('(')[0]
.Split('[')[0]
.Trim() + " ";;
if (name.Contains("mame"))
{
if (title.Length > 3 && !title.Contains("No Driver Loaded"))
{
noMame = false;
try
{
Console.WriteLine(name + " | " + title);
File.WriteAllText(watchFile, title);
}
catch
{
}
}
}
}
}
if (noMame)
{
if (File.ReadAllText(watchFile) != "")
{
File.WriteAllText(watchFile, "");
}
}
}
}
}
}
<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 Mame2LCD
{
public partial class Form1 : Form
{
System.Threading.Thread scrapeThread;
processScraper scraper;
public Form1()
{
InitializeComponent();
this.Resize += Form1_Resize;
scrapeThread = new System.Threading.Thread(StartScrape);
scrapeThread.Start();
this.ShowInTaskbar = false;
this.FormClosing += (sender, e) =>
{
scrapeThread.Abort();
mynotifyicon.Visible = false;
};
}
void Form1_Resize(object sender, EventArgs e)
{
popUp();
}
private void popUp()
{
mynotifyicon.Visible = true;
if (this.WindowState == FormWindowState.Minimized)
{
this.Hide();
}
}
private void StartScrape()
{
scraper = new processScraper();
this.FormClosed += (sender, e) =>
{
scraper.running = false;
};
}
private void Form1_Load(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Minimized;
}
private void mynotifyicon_Click(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Normal;
this.BringToFront();
this.Show();
}
private void Form1_VisibleChanged(object sender, EventArgs e)
{
}
private void mynotifyicon_MouseMove(object sender, MouseEventArgs e)
{
}
}
}
|
74e598d2a3bc73e92d0c6e816f9c3d4dc339920e
|
[
"C#"
] | 2
|
C#
|
FallenWyvern/Mame2LCD
|
45cb306bbd8ebfea3c8ed91ca529d4dab0c43848
|
a0685c8739883d912f5406f070bb44c228787858
|
refs/heads/master
|
<repo_name>msergdeez/mass_telnet<file_sep>/README.md
mass_telnet
===========
Put settings to many devices via telnet
<file_sep>/put_settings.py
#!/usr/bin/env python
#coding=utf-8
"""
Put settings into many switches via telnet
"""
from telnetlib import Telnet
import socket
from datetime import datetime
from switshes_list import *
class telnet_terminal(object):
""" Telnet interface of switch (DES-32xx) """
def __init__(self, ip):
self.ip = ip
self.terminal = None
try:
self.terminal = Telnet(self.ip)
except socket.error, e:
print(e.strerror)
def run_script(self, start_str, end_str, script):
""" run commands from script when read start_str while not end_str """
if self.terminal:
self.terminal.read_until(start_str)
self.terminal.write(script)
return self.terminal.read_until(end_str, timeout=5)
# change login/passwd from defaults
script_change_account = ""\
"{old_login}\r"\
"{old_passwd}\r"\
"create account admin {new_login}\r"\
"{new_passwd}\r"\
"{new_passwd}\r"\
"delete account {old_login}\r"\
"save all\r\r\r\r"\
"logout\r".format(
old_login='admin',
old_passwd='<PASSWORD>',
new_login=sw_login,
new_passwd=sw_passwd)
# echo sys-time of device
script_show_time = ""\
"{login}\r"\
"{passwd}\r"\
"show time\r"\
"logout\r".format(
login=sw_login,
passwd=sw_passwd)
# set sys-time on device (current system time)
script_set_time = ""\
"{login}\r"\
"{passwd}\r"\
"config time {time_01}\r"\
"config time {time_02}\r"\
"config time_zone operator + hour 3 min 0\r"\
"show time\r"\
"save all\r"\
"logout\r".format(
time_01=datetime.strftime(datetime.now(), '%d%b%Y %H:%M:%S'),
time_02=datetime.strftime(datetime.now(), '%d%m%Y %H:%M:%S'),
login=sw_login,
passwd=sw_passwd)
# run needful script on all switches
for sw_ip in switches:
print('-' * 60)
print(sw_ip)
print(telnet_terminal(sw_ip).run_script('UserName:', 'logout', script_set_time))
|
2c53eac36c6a67c1a08ceba302f196150f82327e
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
msergdeez/mass_telnet
|
8143fddbde6f627da3b2dff28acdcce48beaa700
|
3e5740ba201f09320a5b90866596c278e231ed15
|
refs/heads/master
|
<repo_name>c-trimm/NoteWin<file_sep>/js/script.js
// NoteWin
// Author: <NAME>
// Created: July 2010
$(document).ready(function() {
var $formBox, $title, $note, $submit, $dToggle, $clearBtn, title, note, editor, windowStates;
function init() {
$formBox = $("#form");
$title = $("#title");
$note = $("#note");
$submit = $("#form button");
$dToggle = $("#showPane");
$clearBtn = $("#clear-form");
$formBox.data("showing", true);
editor = $("#note").cleditor({width: "100%"});
$submit.button();
$dToggle.icon({icon : "circle-plus"});
$dToggle.click(toggleForm);
$submit.click(submitForm);
$clearBtn.click(clearForm);
for (var winID in localStorage) {
if (localStorage.hasOwnProperty(winID)) {
createWindow({uniqueID: winID, state: JSON.parse(localStorage[winID])});
}
}
//toggleForm();
}
function createWindow(attrs) {
var $newWin, title, note, uniqueID, state, existing;
if (!attrs) {
throw new Error("Window attributes not supplied!");
}
existing = null;
title = attrs.title;
note = attrs.note;
uniqueID = attrs.uniqueID
state = attrs.state;
// Create new element and bind events
$newWin = $("<div />")
.bind("saveState", saveWindowState)
.bind("close", removeWindowState);
if (state && uniqueID) {
existing = {
uniqueID: uniqueID,
state: state
}
}
// Create window element
$newWin.attr("title", title);
$newWin.html(note);
// Apply plugin and open window
$newWin.miniWin(existing).miniWin("open");
return $newWin;
}
function toggleForm() {
var animateTo, showing, $showPane;
showing = $formBox.data("showing");
animateTo = { top : 20, left : 20 };
$showPane = $("#showPane");
if (showing) {
animateTo = {
top : (0 - (parseInt($formBox.height()) + 40)) + 25,
left : (0 - (parseInt($formBox.width()) + 40)) + 25
};
$showPane.icon("option", "icon", "circle-plus");
}
else {
$showPane.icon("option", "icon", "closethick");
}
$formBox.animate(animateTo);
$formBox.data("showing", !showing);
}
function submitForm() {
var $newWin, title, note;
title = ($title.val()) ? $title.val() : "Untitled";
note = $note.val();
if (note === "") {
return alert("You must enter note text!");
}
// Create a new note window, add bindings, and open it
$newWin = createWindow({
title: title,
note: note
});
saveWindowState.call($newWin);
// Hide the form
toggleForm();
clearForm();
}
function saveWindowState() {
var winID = $(this).miniWin("getID");
var state = $(this).miniWin("getState");
localStorage[winID] = JSON.stringify(state);
}
function removeWindowState() {
var winID = $(this).miniWin("getID");
localStorage.removeItem(winID);
}
function clearForm() {
$title.val("");
$note.cleditor()[0].clear();
}
init();
});<file_sep>/README.md
NoteWin
=======
A simple app for keeping "sticky" notes.
**Demo:** http://www.caseytrimm.com/projects/NoteWin/
|
0e81b01611a14f0e064db0d495b3d7eb693a096b
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
c-trimm/NoteWin
|
10013cb627e9f942ede751305012ce918285119d
|
df3b97079a4fef7f58a01943ecc4253a15419b93
|
refs/heads/main
|
<file_sep>[Squares]
Enh = 1
Colorize = 0
<file_sep>import copy
init_pos = "rnbqkbnrpppppppp................................PPPPPPPPRNBQKBNR"
init_fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"
q_atks=[]
b_atks=[]
r_atks=[]
n_atks=[]
k_atks=[]
bp_atks=[]
wp_atks=[]
rays = [] # Three dimensional lists of directional rays.
for sq in range(64):
rays.append([
[i for i in range(sq+1, 64, +1) if sq/8 == i/8 and i < 64],
[i for i in range(sq+9, 64, +9) if sq%8 < i%8 and i < 64],
[i for i in range(sq+8, 64, +8) if i<64],
[i for i in range(sq+7, 64, +7) if sq%8> i% 8 and i < 64],
[i for i in range(sq-1, -1, -1) if sq/8 == i/8 and i >= 0],
[i for i in range(sq-9, -1, -9) if sq%8 > i%8 and i >= 0],
[i for i in range(sq-8, -1, -8) if i >= 0],
[i for i in range(sq-7, -1, -7) if sq%8 < i%8 and i >= 0],
])
# Initialize attack maps
for i in range(64):
r_atks.append([])
b_atks.append([])
q_atks.append([])
k_atks.append([])
n_atks.append([])
bp_atks.append([])
wp_atks.append([])
# list indices
# 0 1 2
# \ | /
# 3 -sqr- 4
# / | \
# 5 6 7
# convenience methods
def sqr_to_pgn(sqr):
return "{}{}".format(chr(ord('a')+(sqr % 8)),8-sqr // 8)
def pgn_to_sqr(pgn):
return (8-int(pgn[1]))*8 + ord(pgn[0]) - ord('a')
def build_atk_maps():
for sq in range(64):
delta=-9
if sq + delta >= 0 and sq % 8 > (sq + delta) % 8:
k_atks[sq].append(sq + delta)
r = []
while sq + delta >= 0 and sq % 8 > (sq + delta) % 8:
r.append(sq + delta)
delta-=9
b_atks[sq].append(r)
q_atks[sq].append(r)
delta=-8
if sq + delta >= 0:
k_atks[sq].append(sq + delta)
r = []
while sq + delta >= 0:
r.append(sq + delta)
delta -= 8
r_atks[sq].append(r)
q_atks[sq].append(r)
delta = -7
if sq + delta >= 0 and sq % 8 < (sq + delta) % 8:
k_atks[sq].append(sq + delta)
r = []
while sq + delta >= 0 and sq % 8 < (sq + delta) % 8:
r.append(sq + delta)
delta -= 7
b_atks[sq].append(r)
q_atks[sq].append(r)
delta=-1
if sq + delta >= 0 and sq % 8 > (sq+delta) % 8:
k_atks[sq].append(sq + delta)
r = []
while sq + delta >= 0 and sq % 8 > (sq+delta) % 8:
r.append(sq + delta)
delta -= 1
r_atks[sq].append(r)
q_atks[sq].append(r)
delta = 1
if sq + delta < 64 and sq % 8 < (sq+delta) % 8:
k_atks[sq].append(sq + delta)
r = []
while sq + delta < 64 and sq % 8 < (sq+delta) % 8:
r.append(sq + delta)
delta += 1
r_atks[sq].append(r)
q_atks[sq].append(r)
delta= 7
if sq + delta < 64 and sq % 8 > (sq + delta) % 8:
k_atks[sq].append(sq + delta)
r = []
while sq + delta < 64 and sq % 8 > (sq + delta) % 8:
r.append(sq + delta)
delta += 7
b_atks[sq].append(r)
q_atks[sq].append(r)
delta = 8
if sq + delta < 64:
k_atks[sq].append(sq + delta)
r = []
while sq + delta < 64:
r.append(sq + delta)
delta += 8
r_atks[sq].append(r)
q_atks[sq].append(r)
delta = 9
if sq + delta < 64 and sq % 8 < (sq + delta) % 8:
k_atks[sq].append(sq + delta)
r = []
while sq + delta < 64 and sq % 8 < (sq + delta) % 8:
r.append(sq + delta)
delta += 9
b_atks[sq].append(r)
q_atks[sq].append(r)
# knight maps
for d in [-17,-15,-10,-6,6,10,15,17]:
tsq = sq + d
if abs( sq // 8 - tsq // 8) + abs( sq % 8 - tsq %8 ) == 3 \
and tsq >=0 and tsq < 64:
n_atks[sq].append(sq + d)
# pawn maps
delta = 7
if sq + delta < 64 and sq % 8 > (sq + delta) % 8:
bp_atks[sq].append(sq + delta)
delta = 9
if sq + delta < 64 and sq % 8 < (sq + delta) % 8:
bp_atks[sq].append(sq + delta)
bp_atks.append(r)
delta = -7
if sq + delta >=0 and sq % 8 < (sq + delta) % 8:
wp_atks[sq].append(sq + delta)
delta = -9
if sq + delta >=0 and sq % 8 > (sq + delta) % 8:
wp_atks[sq].append(sq + delta)
class Move(object):
def __init__(self, src, dst):
self.src, self.dst = src, dst
self.pgn = ""
def __str__(self):
return str(self.dst)
def __repr__(self):
return "{}>{}".format(sqr_to_pgn(self.src),sqr_to_pgn(self.dst))
# Castling rights constants
#r_K=0b0001
#r_Q=0b0010
#r_k=0b0100
#r_q=0b1000
cr_K= 1 << 0
cr_Q= 1 << 1
cr_k= 1 << 2
cr_q= 1 << 3
class Chess(object):
def __init__(self):
self.bb = {}
self._fire_action = None
self.t = -1
self.ply = -1
self.crights = -1
self.ep_sqr = None
def __copy__(self):
cp = Chess()
cp.bb=copy.deepcopy(self.bb)
cp._fire_action = None
cp.t = self.t
cp.ply = self.ply
cp.crights = self.crights
cp.ep_sqr = self.ep_sqr
return cp
def setup(self, fen = None):
self.t = 1
self.ply = 0
self.crights = cr_K | cr_Q | cr_k | cr_q
self.ep_sqr = None
# initialize bitboards
for p in 'prnbqkrPRNBQKR':
self.bb[p]=0
if fen == None:
fen = init_fen
i=0
tokens = fen.split()
for c in tokens[0]:
if c.isalpha():
self.bb[c] |= 1 << i
i+=1
elif c.isdigit():
i+=int(c)
self.t = 1 if tokens[1] == "w" else "b"
self.crights = 0
if "K" in tokens[2]:
self.crights |= cr_K
if "Q" in tokens[2]:
self.crights |= cr_Q
if "k" in tokens[2]:
self.crights |= cr_k
if "q" in tokens[2]:
self.crights |= cr_q
self.ep_sqr = None if tokens[3]=="-" else tokens[3]
if self._fire_action is not None:
self._fire_action("<<setup>>",fen)
def print(self):
for sq in range(64):
b = 1 << sq
found = False
for p in "prnbqkPRNBQK":
if self.bb[p] & b:
print(" {}".format(p), end='')
found = True
if not found:
print(" .", end='')
if sq % 8 == 7:
print("")
def fen(self):
# encode FEN notation
l=[]
spc = 0
for sq in range(64):
b = 1 << sq
found = False
for p in "prnbqkPRNBQK":
if self.bb[p] & b:
l.append(p)
found = True
if not found:
spc += 1
if sq % 8 == 7 and sq != 63:
if spc > 0:
l.append(str(spc))
spc = 0
l.append("/")
l.append(" ")
l.append("b" if self.t == 0 else "w")
l.append(" ")
if self.crights == 0:
l.append ("-")
else:
l.append("K" if self.crights & cr_K else "")
l.append("Q" if self.crights & cr_Q else "")
l.append("k" if self.crights & cr_k else "")
l.append("q" if self.crights & cr_q else "")
l.append(" ")
l.append("-" if self.ep_sqr == None else sqr_to_pgn(self.ep_sqr))
l.append(" 0 ")
l.append(str(self.ply+1))
return "".join(l)
# def put(self,sq,pc):
# self.bb[pc] |= 1 << sq
# def remove(self,sq,pc):
# self.bb[pc] &= ~(1 << sq)
def get_all_moves(self):
occ = [0,0]
for x in 'prnbqk':
occ[0] |= self.bb[x]
for x in 'PRNBQK':
occ[1] |= self.bb[x]
empt = ~(occ[0] | occ[1])
if self.t == 0:
for sq in range(64):
if self.bb['r'] & 1 << sq:
for ray in r_atks[sq]:
for tsq in ray:
if empt & 1 << tsq:
yield Move(sq, tsq)
elif occ[1] & 1 << tsq:
yield Move(sq, tsq)
break
else:
break
elif self.bb['b'] & 1 << sq:
for ray in b_atks[sq]:
for tsq in ray:
if empt & 1 << tsq:
yield Move(sq, tsq)
elif occ[1] & 1 << tsq:
yield Move(sq, tsq)
break
else:
break
elif self.bb['q'] & 1 << sq:
for ray in q_atks[sq]:
for tsq in ray:
if empt & 1 << tsq:
yield Move(sq, tsq)
elif occ[1] & 1 << tsq:
yield Move(sq, tsq)
break
else:
break
elif self.bb['k'] & 1 << sq:
for tsq in k_atks[sq]:
if empt & 1 << tsq or occ[1] & 1 << tsq:
yield Move(sq, tsq)
if sq == 4:
if self.crights & cr_k and empt & 1 << 5 and empt & 1 << 6:
yield Move(4, 6)
elif self.crights & cr_q and empt & 1 << 3 and empt & 1 << 2:
yield Move(4, 2)
elif self.bb['p'] & 1 << sq:
for tsq in bp_atks[sq]:
if occ[1] & 1 << tsq or tsq == self.ep_sqr: # pawn capture
yield Move(sq, tsq)
if sq+8 < 64 and empt & 1 << sq + 8: # pawn advance
yield Move(sq, sq + 8)
if sq//8 == 1 and empt & 1 << sq + 8 and empt & 1 << sq + 16:
yield Move(sq ,sq + 16)
elif self.bb['n'] & 1 << sq:
for tsq in n_atks[sq]:
if empt & 1 << tsq or occ[1] & 1 << tsq:
yield Move(sq, tsq)
else:
for sq in range(64):
if self.bb['R'] & 1 << sq:
for ray in r_atks[sq]:
for tsq in ray:
if empt & 1 << tsq:
yield Move(sq, tsq)
elif occ[0] & 1 << tsq:
yield Move(sq, tsq)
break
else:
break
elif self.bb['B'] & 1 << sq:
for ray in b_atks[sq]:
for tsq in ray:
if empt & 1 << tsq:
yield Move(sq, tsq)
elif occ[0] & 1 << tsq:
yield Move(sq, tsq)
break
else:
break
elif self.bb['Q'] & 1 << sq:
for ray in q_atks[sq]:
for tsq in ray:
if empt & 1 << tsq:
yield Move(sq, tsq)
elif occ[0] & 1 << tsq:
yield Move(sq, tsq)
break
else:
break
elif self.bb['K'] & 1 << sq:
for tsq in k_atks[sq]:
if empt & 1 << tsq or occ[0] & 1 << tsq:
yield Move(sq, tsq)
if sq == 60:
if self.crights & cr_K and empt & 1 << 61 and empt & 1 << 62:
yield Move(60, 62)
elif self.crights & cr_Q and empt & 1 << 59 and empt & 1 << 58:
yield Move(60, 58)
elif self.bb['P'] & 1 << sq:
for tsq in wp_atks[sq]:
if occ[0] & 1 << tsq or tsq == self.ep_sqr: # pawn capture
yield Move(sq, tsq)
if sq+8 < 64 and empt & 1 << sq - 8: # pawn advance
yield Move(sq, sq - 8)
if sq//8 == 6 and empt & 1 << sq - 8 and empt & 1 << sq - 16:
yield Move(sq, sq - 16)
elif self.bb['N'] & 1 << sq:
for tsq in n_atks[sq]:
if empt & 1 << tsq or occ[0] & 1 << tsq:
yield Move(sq, tsq)
def is_self_checking_move(self, mv):
cp = copy.copy(self)
# cp._fire_action = None
k_pos = cp.bb['k' if cp.t == 0 else 'K'].bit_length()-1
cp.move(mv)
atks = 0
for m in cp.get_all_moves():
# atks |= 1 << m.dst
if m.dst == k_pos:
return True
return False
def move(self, mv):
piece, capt = '',''
for k,v in self.bb.items():
if v & 1 << mv.dst:
capt = k
self.bb[capt] &= ~(1 << mv.dst)
for k,v in self.bb.items():
if v & 1 << mv.src:
piece = k
self._move(piece, mv.src, mv.dst)
#castling
if piece == 'k':
if mv.src==4 and mv.dst==6:
self.move('r',7,5)
elif mv.src==4 and mv.dst==2:
self.move('r',0,3)
self.crights &= ~(cr_k|cr_q)
elif piece == 'K':
if mv.src==60 and mv.dst==62:
self.move('R',63,61)
elif mv.src==60 and mv.dst==58:
self.move('R',56,59)
self.crights &= ~(cr_K|cr_Q)
#promotion
elif piece == 'p':
if mv.dst // 8 == 7:
pass
elif mv.dst == self.ep_sqr: #ep capture
self._remove('p', mv.dst - 8)
elif piece == 'P':
if mv.dst // 8 == 0:
pass
elif mv.dst == self.ep_sqr:
self._remove('p', mv.dst + 8)
#ep square set/unset
if piece == 'p' and mv.dst - mv.src == 16: #ep-sqr set
self.ep_sqr = mv.src + 8
elif piece == 'P' and mv.src - mv.dst == 16:
self.ep_sqr = mv.src - 8
else:
self.ep_sqr = None
self.t ^= 1
self.ply += 1
def make(self, src, dst):
print("MAKE--:{}->{}".format(src,dst))
legal_moves = (list(filter(lambda x: not self.is_self_checking_move(x),
self.get_all_moves())))
for m in legal_moves:
if src == m.src and dst == m.dst:
print("MAKE-Move()")
self.move(m)
return True
return False
def _move(self, piece, src, dst):
self.bb[piece] &= ~(1 << src)
self.bb[piece] |= 1 << dst
if self._fire_action is not None:
self._fire_action("<<move>>",{"piece":piece,"src":src,"dst":dst})
def _remove(self, piece, sqr):
self.bb[piece] &= ~(1 << sqr)
if self._fire_action is not None:
self._fire_action("<<remove>>",[piece,sqr])
if __name__=="__main__":
build_atk_maps()
chess = Chess()
chess.setup()
while True:
chess.print()
pgn = input("{} to move,Enter your move(e2e4 etc):".format("Black" if chess.t==0 else "White"))
if not chess.make(pgn_to_sqr(pgn[0:2]),pgn_to_sqr(pgn[2:4])):
print("Wrong move.")
<file_sep>import tkinter as tk
from PIL import Image, ImageEnhance, ImageTk
import chess
cs = 80
class ChessBoard(tk.Canvas):
def __init__(self, master = None):
super().__init__(master,width = cs*8, height = cs*8)
self.master = master
self.pieces = {}
for sq in range(64):
i,j = sq % 8, sq // 8
x,y = i * cs, j * cs
self.create_rectangle(
x, y, x+cs, y+cs, width=0,
fill= "green" if (i+j)%2 == 1 else "light green")
# self.create_image(cs/2, cs/2, image=pieces['P'], anchor="center")
self.bind("<Button-1>",self._handle_click)
self.bind("<MouseWheel>",self._wheel)
self.pack()
self.selected_sqrs = []
self.selected_squares_objs = []
self._fire_action = None
def setup (self, fen):
tokens = fen.split()[0]
sq=0
for c in tokens:
if c.isalpha():
x, y = sq%8, sq//8
self.pieces[sq]=self.create_image(
x*cs+cs/2, y*cs+cs/2, image=pieces[c],
anchor="center")
sq+=1
elif c.isdigit():
sq+=int(c)
def _handle_click(self, evt):
x, y = evt.x // cs, evt.y // cs
sq = y*8 + x
if len(self.selected_sqrs) < 2:
self.selected_sqrs.append(sq)
self.select_square(sq)
if len(self.selected_sqrs) >= 2:
if self._fire_action is not None:
self._fire_action("<<request_move>>", self.selected_sqrs)
for o in self.selected_squares_objs:
self.delete(o)
self.selected_squares_objs = []
self.selected_sqrs = []
def _wheel(self, evt):
print("wheel:{}".format(evt))
def set (self, pc, sq):
x, y = sq%8, sq//8
self.pieces[sq]=self.create_image(
x*cs+cs/2, y*cs+cs/2,
image=pieces[pc], anchor="center")
def remove (self, sq):
try:
self.delete(self.pieces[sq])
del self.pieces[sq]
except KeyError:
pass
def select_square (self, sq):
x, y = sq%8, sq//8
i=self.create_rectangle(
x*cs, y*cs,(x+1)*cs-1,(y+1)*cs-1,
outline = "red" )
self.selected_squares_objs.append(i)
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.chessboard = None
self.chess =None
self.create_widgets()
def create_widgets(self):
self.chessboard = ChessBoard(self)
self.chess = chess.Chess()
self.chess._fire_action = self._handle_action
self.chessboard._fire_action = self._handle_action
self.chess.setup()
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Hello World\n(click me)"
self.hi_there.pack(side="top")
self.quit = tk.Button(
self, text="QUIT", fg="red",
command=self.master.destroy)
self.quit.pack(side="bottom")
def _handle_action(self, action, args):
if action == "<<setup>>":
self.chessboard.setup(args)
elif action == "<<move>>":
print(" ### Move ### {} -> {}".format(args["src"],args["dst"]))
self.chessboard.remove(args["src"])
self.chessboard.set(args["piece"], args["dst"])
print("<<move>>")
elif action == "<<remove>>":
print("<<remove>>")
elif action == "<<request_move>>":
if self.chess.make(args[0],args[1]):
pass
else:
print("illegal move:{}->{}".format(args[0],args[1]))
def resize_image(img, w, h):
img2 = img.resize((w,h), Image.ANTIALIAS)
return img2
def darker_image(img, ratio):
pxls = img.load()
for i in range(img.size[0]):
for j in range(img.size[1]):
alpha = ratio # 0..1 : 0 is darkest
beta = -30
pxls[i,j] = (
int(pxls[i,j][0] * alpha + beta),
int(pxls[i,j][1] * alpha + beta),
int(pxls[i,j][2] * alpha + beta),
pxls[i,j][3])
return img
root = tk.Tk()
pieces={}
for a in "PRNBQK":
# pieces[a] = tk.PhotoImage(file = "data/PIECE/Dyche/{}.png".format(a))
img = resize_image(Image.open("data/PIECE/Dyche/{}.png".format(a)), cs, cs)
pieces[a] = ImageTk.PhotoImage(img)
pieces[a.lower()] = ImageTk.PhotoImage(darker_image(img, 0.5))
app = Application(master=root)
app.mainloop()
<file_sep>[Squares]
Enh = 1
Colorize = 1
<file_sep>import copy
init_pos = "rnbqkbnrpppppppp................................PPPPPPPPRNBQKBNR"
q_atks=[]
b_atks=[]
r_atks=[]
n_atks=[]
k_atks=[]
bp_atks=[]
wp_atks=[]
# Initialize attack maps
for i in range(64):
r_atks.append([])
b_atks.append([])
q_atks.append([])
k_atks.append([])
n_atks.append([])
bp_atks.append([])
wp_atks.append([])
# list indices
# 0 - 1 - 2
# \ | /
# 3 -sqr- 4
# / | \
# 5 6 7
# convenience methods
def sqr_to_pgn(sqr):
return "{}{}".format(chr(ord('a')+(sqr % 8)),8-sqr // 8)
def pgn_to_sqr(pgn):
return (8-int(pgn[1]))*8 + ord(pgn[0]) - ord('a')
def build_atk_maps():
for sq in range(64):
delta=-9
if sq + delta >= 0 and sq % 8 > (sq + delta) % 8:
k_atks[sq].append(sq + delta)
r = []
while sq + delta >= 0 and sq % 8 > (sq + delta) % 8:
r.append(sq + delta)
delta-=9
b_atks[sq].append(r)
q_atks[sq].append(r)
delta=-8
if sq + delta >= 0:
k_atks[sq].append(sq + delta)
r = []
while sq + delta >= 0:
r.append(sq + delta)
delta -= 8
r_atks[sq].append(r)
q_atks[sq].append(r)
delta = -7
if sq + delta >= 0 and sq % 8 < (sq + delta) % 8:
k_atks[sq].append(sq + delta)
r = []
while sq + delta >= 0 and sq % 8 < (sq + delta) % 8:
r.append(sq + delta)
delta -= 7
b_atks[sq].append(r)
q_atks[sq].append(r)
delta=-1
if sq + delta >= 0 and sq % 8 > (sq+delta) % 8:
k_atks[sq].append(sq + delta)
r = []
while sq + delta >= 0 and sq % 8 > (sq+delta) % 8:
r.append(sq + delta)
delta -= 1
r_atks[sq].append(r)
q_atks[sq].append(r)
delta = 1
if sq + delta < 64 and sq % 8 < (sq+delta) % 8:
k_atks[sq].append(sq + delta)
r = []
while sq + delta < 64 and sq % 8 < (sq+delta) % 8:
r.append(sq + delta)
delta += 1
r_atks[sq].append(r)
q_atks[sq].append(r)
delta= 7
if sq + delta < 64 and sq % 8 > (sq + delta) % 8:
k_atks[sq].append(sq + delta)
r = []
while sq + delta < 64 and sq % 8 > (sq + delta) % 8:
r.append(sq + delta)
delta += 7
b_atks[sq].append(r)
q_atks[sq].append(r)
delta = 8
if sq + delta < 64:
k_atks[sq].append(sq + delta)
r = []
while sq + delta < 64:
r.append(sq + delta)
delta += 8
r_atks[sq].append(r)
q_atks[sq].append(r)
delta = 9
if sq + delta < 64 and sq % 8 < (sq + delta) % 8:
k_atks[sq].append(sq + delta)
r = []
while sq + delta < 64 and sq % 8 < (sq + delta) % 8:
r.append(sq + delta)
delta += 9
b_atks[sq].append(r)
q_atks[sq].append(r)
# knight maps
delta = -16-1
if sq + delta >= 0 and sq % 8 > (sq + delta) % 8:
n_atks[sq].append(sq + delta)
delta = -16+1
if sq + delta >= 0 and sq % 8 < (sq + delta) % 8:
n_atks[sq].append(sq + delta)
delta = -8-2
if sq + delta >= 0 and sq % 8 > (sq + delta) % 8:
n_atks[sq].append(sq + delta)
delta = -8+2
if sq + delta >= 0 and sq % 8 < (sq + delta) % 8:
n_atks[sq].append(sq + delta)
delta = +8-2
if sq + delta < 64 and sq % 8 > (sq + delta) % 8:
n_atks[sq].append(sq + delta)
delta = +8+2
if sq + delta < 64 and sq % 8 < (sq + delta) % 8:
n_atks[sq].append(sq + delta)
delta = +16-1
if sq + delta < 64 and sq % 8 > (sq + delta) % 8:
n_atks[sq].append(sq + delta)
delta = +16+1
if sq + delta < 64 and sq % 8 < (sq + delta) % 8:
n_atks[sq].append(sq + delta)
# pawn maps
delta = 7
if sq + delta < 64 and sq % 8 > (sq + delta) % 8:
bp_atks[sq].append(sq + delta)
delta = 9
if sq + delta < 64 and sq % 8 < (sq + delta) % 8:
bp_atks[sq].append(sq + delta)
bp_atks.append(r)
delta = -7
if sq + delta >=0 and sq % 8 < (sq + delta) % 8:
wp_atks[sq].append(sq + delta)
delta = -9
if sq + delta >=0 and sq % 8 > (sq + delta) % 8:
wp_atks[sq].append(sq + delta)
class Move:
def __init__(self, src, dst):
self.src, self.dst = src, dst
self.pgn = ""
def __str__(self):
return str(self.dst)
def __repr__(self):
return "{}>{}".format(sqr_to_pgn(self.src),sqr_to_pgn(self.dst))
# Castling rights constants
K=0b0001
Q=0b0010
k=0b0100
q=0b1000
class Chess:
def __init__(self, fen = None):
print("init")
self.bb = {}
self.t = 1
self.ply = 0
self.crights = K | Q | k | q
self.ep_sqr = None
# initialize bitboards
for p in 'prnbqkrPRNBQKR':
self.bb[p]=0
for i in range(len(init_pos)):
if init_pos[i] != '.':
self.bb[init_pos[i]] |= 1 << i
def print(self):
for sq in range(64):
b = 1 << sq
found = False
for p in "prnbqkPRNBQK":
if self.bb[p] & b:
print(" {}".format(p), end='')
found = True
if not found:
print(" .", end='')
if sq % 8 == 7:
print("")
pass
def put(self,sq,pc):
self.bb[pc] |= 1 << sq
pass
def remove(self,sq,pc):
self.bb[pc] &= ~(1 << sq)
pass
def get_all_moves(self):
occ = [self.bb['p'] | self.bb['r'] | self.bb['n'] | self.bb['b'] | self.bb['q'] | self.bb['k'],
self.bb['P'] | self.bb['R'] | self.bb['N'] | self.bb['B'] | self.bb['Q'] | self.bb['K']]
empt = ~(occ[0] | occ[1])
if self.t == 0:
for sq in range(64):
if self.bb['r'] & 1 << sq:
for ray in r_atks[sq]:
for tsq in ray:
if empt & 1 << tsq:
yield Move(sq, tsq)
elif occ[1] & 1 << tsq:
yield Move(sq, tsq)
break
else:
break
elif self.bb['b'] & 1 << sq:
for ray in b_atks[sq]:
for tsq in ray:
if empt & 1 << tsq:
yield Move(sq, tsq)
elif occ[1] & 1 << tsq:
yield Move(sq, tsq)
break
else:
break
elif self.bb['q'] & 1 << sq:
for ray in q_atks[sq]:
for tsq in ray:
if empt & 1 << tsq:
yield Move(sq, tsq)
elif occ[1] & 1 << tsq:
yield Move(sq, tsq)
break
else:
break
elif self.bb['k'] & 1 << sq:
for tsq in k_atks[sq]:
if empt & 1 << tsq or occ[1] & 1 << tsq:
yield Move(sq, tsq)
if sq == 4:
if self.crights & k and empt & 1 << 5 and empt & 1 << 6:
yield Move(4, 6)
elif self.crights & q and empt & 1 << 3 and empt & 1 << 2:
yield Move(4, 2)
elif self.bb['p'] & 1 << sq:
for tsq in bp_atks[sq]:
if occ[1] & 1 << tsq or tsq == self.ep_sqr: # pawn capture
yield Move(sq, tsq)
if sq+8 < 64 and empt & 1 << sq + 8: # pawn advance
yield Move(sq, sq + 8)
if sq//8 == 1 and empt & 1 << sq + 8 and empt & 1 << sq + 16:
yield Move(sq ,sq + 16)
elif self.bb['n'] & 1 << sq:
for tsq in n_atks[sq]:
if empt & 1 << tsq or occ[1] & 1 << tsq:
yield Move(sq, tsq)
else:
for sq in range(64):
if self.bb['R'] & 1 << sq:
for ray in r_atks[sq]:
for tsq in ray:
if empt & 1 << tsq:
yield Move(sq, tsq)
elif occ[0] & 1 << tsq:
yield Move(sq, tsq)
break
else:
break
elif self.bb['B'] & 1 << sq:
for ray in b_atks[sq]:
for tsq in ray:
if empt & 1 << tsq:
yield Move(sq, tsq)
elif occ[0] & 1 << tsq:
yield Move(sq, tsq)
break
else:
break
elif self.bb['Q'] & 1 << sq:
for ray in q_atks[sq]:
for tsq in ray:
if empt & 1 << tsq:
yield Move(sq, tsq)
elif occ[0] & 1 << tsq:
yield Move(sq, tsq)
break
else:
break
elif self.bb['K'] & 1 << sq:
for tsq in k_atks[sq]:
if empt & 1 << tsq or occ[0] & 1 << tsq:
yield Move(sq, tsq)
if sq == 60:
if self.crights & K and empt & 1 << 61 and empt & 1 << 62:
yield Move(60, 62)
elif self.crights & Q and empt & 1 << 59 and empt & 1 << 58:
yield Move(60, 58)
elif self.bb['P'] & 1 << sq:
for tsq in wp_atks[sq]:
if occ[0] & 1 << tsq or tsq == self.ep_sqr: # pawn capture
yield Move(sq, tsq)
if sq+8 < 64 and empt & 1 << sq - 8: # pawn advance
yield Move(sq, sq - 8)
if sq//8 == 6 and empt & 1 << sq - 8 and empt & 1 << sq - 16:
yield Move(sq, sq - 16)
elif self.bb['N'] & 1 << sq:
for tsq in n_atks[sq]:
if empt & 1 << tsq or occ[0] & 1 << tsq:
yield Move(sq, tsq)
def is_self_checking_move(self, mv):
c = copy.deepcopy(self)
k_pos = c.bb['k' if c.t == 0 else 'K'].bit_length()-1
c.make_move(mv)
atks = 0
for m in c.get_all_moves():
# atks |= 1 << m.dst
if m.dst == k_pos:
return True
return False
def move(self, piece, src, dst):
self.bb[piece] &= ~(1 << src)
self.bb[piece] |= 1 << dst
def remove(self, piece, sqr):
self.bb[piece] &= ~(1 << sqr)
def make_move(self, mv):
piece, capt = '',''
for k,v in self.bb.items():
if v & 1 << mv.dst:
capt = k
self.bb[capt] &= ~(1 << mv.dst)
for k,v in self.bb.items():
if v & 1 << mv.src:
piece = k
self.move(piece, mv.src, mv.dst)
#castling
if piece == 'k':
if mv.src==4 and mv.dst==6:
self.move('r',7,5)
elif mv.src==4 and mv.dst==2:
self.move('r',0,3)
self.crights &= ~(k|q)
elif piece is 'K':
if mv.src==60 and mv.dst==62:
self.move('R',63,61)
elif mv.src==60 and mv.dst==58:
self.move('R',56,59)
self.crights &= ~(K|Q)
#promotion
elif piece is 'p':
if mv.dst // 8 == 7:
pass
elif mv.dst == self.ep_sqr: #ep capture
self.remove('p', mv.dst - 8)
elif piece is 'P':
if mv.dst // 8 == 0:
pass
elif mv.dst == self.ep_sqr:
self.remove('p', mv.dst + 8)
#ep square set/unset
if piece is 'p' and mv.dst - mv.src == 16: #ep-sqr set
self.ep_sqr = mv.src + 8
elif piece is 'P' and mv.src - mv.dst == 16:
self.ep_sqr = mv.src - 8
else:
self.ep_sqr = None
self.t ^= 1
self.ply += 1
build_atk_maps()
chess = Chess()
while True:
chess.print()
mvs = chess.get_all_moves()
legal_moves = (list(filter(lambda x: not chess.is_self_checking_move(x),mvs)))
pgn = input("{} to move,Enter your move:".format("Black" if chess.t==0 else "White"))
handled = False
for m in legal_moves:
mv = Move(pgn_to_sqr(pgn[0:2]),pgn_to_sqr(pgn[2:4]))
if mv.src == m.src and mv.dst == m.dst:
chess.make_move(mv)
handled = True
if not handled:
print("Wrong move.")
|
e876a178e51f56be2c576a5ecb0d6ecdc42e200d
|
[
"Python",
"INI"
] | 5
|
INI
|
yachess/vchess
|
59d6f6eecd5466153e64db97cc614b754a636c98
|
3a3f22d1d20ecef2bd875ce715b94bfd05585f22
|
refs/heads/main
|
<repo_name>OskarKozaczka/pp5-java<file_sep>/src/test/java/pl/mbruzda/misc/GreetingTest.java
package pl.mbruzda.misc;
import org.junit.jupiter.api.Test;
import pl.mbruzda.misc.Greeter;
import static org.junit.jupiter.api.Assertions.*;
public class GreetingTest {
@Test
public void itGreetsUser(){
//Arrange
String name = "Marcin";
Greeter greeter = new Greeter();
//Act
String greetingText = greeter.hello("Marcin");
//Assertions
assertEquals("Hello Marcin!", greetingText);
}
}
<file_sep>/src/main/java/pl/mbruzda/credit/CardApi.java
package pl.mbruzda.credit;
public class CardApi {
public void handleWithdraw(withdrawRequest withdrawRequest) {
}
}
<file_sep>/src/main/java/pl/mbruzda/credit/withdrawRequest.java
package pl.mbruzda.credit;
import java.math.BigDecimal;
public class withdrawRequest {
private final String card1;
private final BigDecimal valueOf;
public withdrawRequest(String card1, BigDecimal valueOf) {
this.card1 = card1;
this.valueOf = valueOf;
}
public String getCard1() {
return card1;
}
public BigDecimal getValueOf() {
return valueOf;
}
}
<file_sep>/src/test/java/pl/mbruzda/credit/CreditCardTest.java
package pl.mbruzda.credit;
import com.sun.source.tree.AssertTree;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import static org.junit.jupiter.api.Assertions.*;
public class CreditCardTest {
@Test
public void itAllowsAssignLimitToCC(){
CreditCard card = thereIsCreditCard();
card.assignLimit(BigDecimal.valueOf(200));
assertEquals(BigDecimal.valueOf(200), card.getCurrentLimit());
}
private CreditCard thereIsCreditCard() {
return new CreditCard("1234-5678");
}
@Test
public void itIsNotPossibleToAssignLimitBelowTreshold(){
CreditCard card = thereIsCreditCard();
try {
card.assignLimit(BigDecimal.valueOf(50));
} catch (CreditLimitBelowMinimumValueException e){
assertTrue(true);
}
}
@Test
public void itAllowsToCheckCurrentBalance(){
CreditCard card = thereIsCreditCard();
card.assignLimit(BigDecimal.valueOf(1000));
card.withdraw(BigDecimal.valueOf(500));
assertEquals(BigDecimal.valueOf(500), card.getBalance());
}
@Test
public void cantWithdrawBelowBalance(){
CreditCard card = thereIsCreditCard();
card.assignLimit(BigDecimal.valueOf(1000));
card.withdraw(BigDecimal.valueOf(500));
card.withdraw(BigDecimal.valueOf(500));
assertThrows(NotEnoughMoneyException.class, () -> {
card.withdraw(BigDecimal.valueOf(500));
});
}
}
<file_sep>/src/test/java/pl/mbruzda/letters/CharCounterTest.java
package pl.mbruzda.letters;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class CharCounterTest {
@Test
public void itCountCharsInInputString(){
String inputString = "Ala ma kota";
CharCounter charCounter = new CharCounter();
int charCount = charCounter.count('a', inputString);
assertEquals(4, charCount);
}
}
<file_sep>/src/main/java/pl/mbruzda/credit/NotEnoughMoneyException.java
package pl.mbruzda.credit;
public class NotEnoughMoneyException extends IllegalStateException {
}
|
a7036559206a609153464c4942eaa77e2989bee5
|
[
"Java"
] | 6
|
Java
|
OskarKozaczka/pp5-java
|
66ada9e5c9acf5043ede6fe6cd9635945cba26a9
|
76237699c9bc9cb741a2a13ea2c18b13f8d085ea
|
refs/heads/master
|
<repo_name>kanika26arora/Mouse-Controller<file_sep>/KanikaArora_Controller.java
import java.awt.Point;
import java.awt.Robot;
class KanikaArora_Controller extends javax.swing.JFrame
{
Robot r;
int x,y;
public boolean leftKeyPressed = false;
public boolean rightKeyPressed = false;
public boolean upKeyPressed = false;
public boolean downKeyPressed = false;
public boolean spaceKeyPressed = false;
public KanikaArora_Controller()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("Move Cursor with Keyboard");
setDefaultCloseOperation(3);
setUndecorated(true);
setOpacity(0.0F);
setVisible(true);
try
{
r = new Robot();
}
catch (Exception localException) {}
addKeyListener(new java.awt.event.KeyAdapter()
{
public void keyPressed(java.awt.event.KeyEvent paramAnonymousKeyEvent)
{
if (r == null) { return;
}
Point localPoint = java.awt.MouseInfo.getPointerInfo().getLocation();
int i = paramAnonymousKeyEvent.getKeyCode();
if (i == 38)
{
r.mouseMove(x, y - 1);
upKeyPressed = true;
}
if (i == 40)
{
r.mouseMove(x, y + 1);
downKeyPressed = true;
}
if (i == 37)
{
r.mouseMove(x - 1, y);
leftKeyPressed = true;
}
if (i == 39)
{
r.mouseMove(x + 1, y);
rightKeyPressed = true;
}
if ((rightKeyPressed) && (downKeyPressed)) {
r.mouseMove(x + 1, y + 1);
}
if ((rightKeyPressed) && (upKeyPressed)) {
r.mouseMove(x + 1, y - 1);
}
if ((leftKeyPressed) && (upKeyPressed)) {
r.mouseMove(x - 1, y - 1);
}
if ((leftKeyPressed) && (downKeyPressed)) {
r.mouseMove(x - 1, y + 1);
}
if (i == 32)
{
r.mousePress(16);
r.mouseRelease(16);
}
if ((i == 32) && ((downKeyPressed) || (upKeyPressed) || (rightKeyPressed) || (leftKeyPressed)))
{
r.mousePress(4);
r.mouseRelease(4);
}
}
public void keyReleased(java.awt.event.KeyEvent paramAnonymousKeyEvent) {
int i = paramAnonymousKeyEvent.getKeyCode();
if (i == 39)
{
rightKeyPressed = false;
}
if (i == 38)
{
upKeyPressed = false;
}
if (i == 40)
{
downKeyPressed = false;
}
if (i == 37)
{
leftKeyPressed = false;
}
}
});
}
public static void main(String[] paramArrayOfString)
{
new KanikaArora_Controller();
}
}
|
9456ec4a5136efabc766695a6075f7858522b3d5
|
[
"Java"
] | 1
|
Java
|
kanika26arora/Mouse-Controller
|
e672e6ac33ddfd78c5c75288d9a936112c8e21ed
|
bd2ab1f152cf7616b0b3d1116268f9fa1f5ce181
|
refs/heads/master
|
<repo_name>SimonYanng/MLS<file_sep>/Inoherb4/util/Constants.h
//
// Constants.h
// SFA
//
// Created by <NAME> on 13-11-12.
// Copyright (c) 2013年 Bruce.ren. All rights reserved.
//
#define DOWNLOADURL @"http://www.parrowtech.com/ios/RB-business.html"
//#define BASEURL @"http://172.16.31.10:8078/DataWebService.asmx"
#define BASEURL @"http://172.16.31.10:8357/DataWebService.asmx"
#define APPVERSION @"1.0"
#define APPVERSION1 @"v1.0"
#define HOTLINE @"客服电话:400-672-9851"
//服务器
#define LOGINSERVICE @"loginService"
#define QUERYSERVICE @"downloadService"
#define UPLOADSERVICE @"uploadService"
//接口方法
//#define LOGIN @"login"
#define LOGIN @"UserLogin"
//登录参数
#define USERNAME @"userName"
#define PWD @"pwd"
#define IMEI @"imei"
#define VERSION @"appVersion"
#define DEVICETYPE @"deviceType"
//查询参数
#define USERID @"userId"
#define ISALL @"isAll"
#define STARTROW @"startRow"
#define NEXTSTARTROW @"nextstartrow"
#define METHOD @"method"
#define LASTTIME @"lastTime"
//返回的数据
#define ERRMSG @"Msg"
#define DESC @"MsgInfo"
#define SUCCESS @"success"
#define USERID @"userId"
#define DONE @"done"
//#define NEXTSTARTROW @"nextStartRow"
#define RETURNTYPE @"type"
//数据列表
#define MSGTYPELIST @"msgTypeList"
#define CLIENTTABLE @"clientTable"
#define TABLE @"Table"
//数据库信息
#define FILENAME @"manon"
#define DBNAME @"yw.sqlite"
#define MOBILE_KEY @"uuid"
//tableview参数
#define HEADHEIGHT 30.0f
#define CELLHEIGHT 50
//标题栏参数
#define SYSTITLEHEIGHT 60.0f
#define BOTTOMHEIGHT 50.0f
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
//屏幕宽度
//#if __IPHONE_OS_VERSION_MIN_REQUIRED >= 60000
//#define SYSTEMW 640
//#else
//#define SYSTEMW 320
//#endif
//#define SYSTEMW 320
#define SYSTEMH 640
//圆角大小
#define CORNERRADIUS 3.0f
//进出店照片高度
#define CHECKPHOTOHEIGHT 50
//字典参数
#define DICTITEMNAME @"labelname"
#define DICTVALUE @"value"
#define DICTREMARK @"remark"
#define DICTCODE @"dictcode"
#define DICTNAME @"dictname"
//地图参数
#define CLIENTNAME @"clientname"
#define CLIENTADD @"clientadd"
//#define CLIENTLONG @"clientlong"
#define CLIENTLATLONG @"clientgps"
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0];
#define user_version [[UIDevice currentDevice] systemVersion]
#define client_type platformString()
//NSString * platformString(void)
//{
// size_t size;
// sysctlbyname("hw.machine", NULL, &size, NULL, 0);
// char *machine = malloc(size);
// sysctlbyname("hw.machine", machine, &size, NULL, 0);
// NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
// free(machine);
//
// if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 1G";
// if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
// if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
// if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
// if ([platform isEqualToString:@"iPhone3,3"]) return @"Verizon iPhone 4";
// if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
// if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (GSM)";
// if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (GSM+CDMA)";
// if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (GSM)";
// if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (GSM+CDMA)";
// if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (GSM)";
// if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (GSM+CDMA)";
// if ([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
// if ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
// if ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
// if ([platform isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";
// if ([platform isEqualToString:@"iPod5,1"]) return @"iPod Touch 5G";
// if ([platform isEqualToString:@"iPad1,1"]) return @"iPad";
// if ([platform isEqualToString:@"iPad2,1"]) return @"iPad 2 (WiFi)";
// if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2 (GSM)";
// if ([platform isEqualToString:@"iPad2,3"]) return @"iPad 2 (CDMA)";
// if ([platform isEqualToString:@"iPad2,4"]) return @"iPad 2 (WiFi)";
// if ([platform isEqualToString:@"iPad2,5"]) return @"iPad Mini (WiFi)";
// if ([platform isEqualToString:@"iPad2,6"]) return @"iPad Mini (GSM)";
// if ([platform isEqualToString:@"iPad2,7"]) return @"iPad Mini (GSM+CDMA)";
// if ([platform isEqualToString:@"iPad3,1"]) return @"iPad 3 (WiFi)";
// if ([platform isEqualToString:@"iPad3,2"]) return @"iPad 3 (GSM+CDMA)";
// if ([platform isEqualToString:@"iPad3,3"]) return @"iPad 3 (GSM)";
// if ([platform isEqualToString:@"iPad3,4"]) return @"iPad 4 (WiFi)";
// if ([platform isEqualToString:@"iPad3,5"]) return @"iPad 4 (GSM)";
// if ([platform isEqualToString:@"iPad3,6"]) return @"iPad 4 (GSM+CDMA)";
// if ([platform isEqualToString:@"iPad4,1"]) return @"iPad Air (WiFi)";
// if ([platform isEqualToString:@"iPad4,2"]) return @"iPad Air (Cellular)";
// if ([platform isEqualToString:@"iPad4,4"]) return @"iPad mini 2G (WiFi)";
// if ([platform isEqualToString:@"iPad4,5"]) return @"iPad mini 2G (Cellular)";
// if ([platform isEqualToString:@"i386"]) return @"Simulator";
// if ([platform isEqualToString:@"x86_64"]) return @"Simulator";
// return platform;
//}
#define idfv [[[UIDevice currentDevice] identifierForVendor] UUIDString]
//当控件为text时,验证类型
enum
{
DEFAULT,
NUMBER,
AMOUNT,
PHONE,
EMAIL,
NUMBERTEXT,
URL,
BIGTEXT
};
typedef NSUInteger Verifytype;
//模板类型
enum
{
LOGIN_FRM,
MAINMENU_FRM,
};
typedef NSUInteger TempLateType;
//排列类型
enum
{
HORIZONTAL,
VERTICAL
};
typedef NSUInteger Orientation;
//控件类型
enum
{
NONE,
TEXT,
MULTICHOICE,
SINGLECHOICE,
RADIOBUTTON,
DATE,
CHECKBOX,
TIME,
DATETIME,
BUTTON,
SELECTPRODUCT,
TAKEPHOTO,
SHOTPHOTO
};
typedef NSUInteger ControlType;
//request类型
enum
{
LOGIN_REQUEST,
QUERY_REQUEST,
UPLOAD_REQUEST,
UPLOAD_PLAN,
QUERY_MSG,
UPLOAD_MSG
};
typedef NSUInteger RequestType;
//数据库,表的字段类型
enum
{
VACHAR,
INTEGER,
BLOB,
TIMESTAMP
};
typedef NSUInteger TableFieldType;
//拍照类型
enum
{
CHECKIN,
CHECKOUT
};
typedef NSUInteger PhotoType;
//sql类型
enum
{
VISITPLAN,
HOCPLAN,
DICTSQL,
SEARCHCLIENT,
COMPLETERPT
};
typedef NSUInteger SqlType;
//按钮类型
enum
{
LOGINBUTTON,
NAVBUTTON,
RPTBUTTON
};
typedef NSUInteger buttonType;
//计算类型
enum
{
DIVISOR,//除数
DIVIDER,//被除数
};
typedef NSUInteger RequestType;
|
5fcd578266537e5a2ac358c853ee076319f53e74
|
[
"C"
] | 1
|
C
|
SimonYanng/MLS
|
e0d2181ec2549dd95d3ead0c973dafde25a9bb63
|
18000529bf538d1bd45b0b64390f21f0147bdb6b
|
refs/heads/master
|
<repo_name>regexpressyourself/cms<file_sep>/public/manage_admins.php
<?php $layout_context = "admin"; ?>
<?php include("../includes/session.php");?>
<?php include("../includes/functions.php");?>
<?php confirm_logged_in(); ?>
<?php require_once("../includes/db_connection.php");?>
<?php require_once("../includes/layouts/header.php");?>
<?php
$admin_set = find_all_admins();
?>
<div id="main">
<div id="navigation">
<br />
<a href="admin.php">«Main Menu</a><br />
</div>
<div id="page">
<?php echo message(); ?>
<h2>Manage Admins</h2>
<br />
<table>
<tr>
<td style="width: 200px; text-align: left;"><strong>Username</strong></td>
<td style="width: 200px; text-align: left;"><strong>Actions</strong></td>
</tr>
<?php
while ($admin = mysqli_fetch_assoc($admin_set)) {
$output = "";
$output .= "<tr>";
$output .= "<td style=\"width: 200px; text-align: left;\">";
$output .= htmlentities($admin["username"]);
$output .= "</td>";
$output .= "<td style=\"width: 200px; text-align: left;\">";
$output .= "<a href=\"edit_admin.php?admin=";
$output .= htmlentities($admin["id"]);
$output .= "\">Edit</a>" ;
$output .= " ";
$output .= "<a href=\"delete_admin.php?admin=";
$output .= htmlentities($admin["id"]);
$output .= "\" onclick=\"return confirm('Are you sure?');\"";
$output .= ">Delete</a>" ;
$output .= "</td>";
$output .= "</tr>";
echo $output;
}
?>
</table>
<br /><br /><br />
<a href="new_admin.php">Add new admin</a>
</div>
</div>
<?php include("../includes/layouts/footer.php");?>
|
8e68d235dcf22b2a5e216322d9e2903186e5f051
|
[
"PHP"
] | 1
|
PHP
|
regexpressyourself/cms
|
a992e6865d309d3b41447dfbcf85deb7f8b27158
|
cc834138730b70e7db67e7f1689ad8272755bbd0
|
refs/heads/master
|
<repo_name>Jyothsna99/Web_Table_from_CSV<file_sep>/csvmodule.py
'''using csv module we can read the contents of the csv
This program reads the data from csv file and create a table in the web page using the data that is red from csv file'''
import csv
def csv_to_html_table(fname,headers=None,delimiter=","):
f=open(fname,'r')
content=csv.reader(f)
rows = list(content)
table = "<center><h1>Student Table</h1></center><table align='center' border='3'>"
#creating HTML header row if header is provided
if headers is not None:
table+= "".join(["<th>"+cell+"</th>" for cell in headers.split(delimiter)])
else:
table+= "".join(["<th>"+cell+"</th>" for cell in rows[0].split(delimiter)])
rows=rows[1:]
#Converting csv to html row by row
for row in rows:
table+="<tr>"
for i in row:
table+="<td>"+i+"</td>"
table+="</tr>"
table+="</table><br>"
return table
if __name__=='__main__':
myheader='roll no,name,marks'
w=csv_to_html_table("E://table.csv",myheader)
#table.csv is the name of the csv file in which the information is stored
f=open("table.html","w")
f.write(w)
f.close()
|
6385ba1dcb38fda4e9c26e868915ac3e32802943
|
[
"Python"
] | 1
|
Python
|
Jyothsna99/Web_Table_from_CSV
|
43c76dc06797dd77fa44b982518d05c9e57cf4de
|
f4802453f41e9457cce4ebb886567157aa9e3000
|
refs/heads/master
|
<repo_name>mehgancook/WebServiceLab1<file_sep>/app/src/androidTest/java/mehganc/tacoma/uw/edu/webservicelab/SignInActivityTest.java
package mehganc.tacoma.uw.edu.webservicelab;
import android.test.ActivityInstrumentationTestCase2;
import com.robotium.solo.Solo;
import mehganc.tacoma.uw.edu.webservicelab.authenticate.SignInActivity;
public class SignInActivityTest extends
ActivityInstrumentationTestCase2<SignInActivity> {
private Solo solo;
public SignInActivityTest() {
super(SignInActivity.class);
}
// @Override
// public void setUp() throws Exception {
// super.setUp();
// solo = new Solo(getInstrumentation(), getActivity());
// }
//
// @Override
// public void tearDown() throws Exception {
// //tearDown() is run after a test case has finished.
// //finishOpenedActivities() will finish all the activities that have been opened during the test execution.
// solo.finishOpenedActivities();
//
// }
//
// public void testSignInFragmentLoads() {
// boolean fragmentLoaded = solo.searchText("Enter your userid");
// assertTrue("Login fragment loaded", fragmentLoaded);
// }
//
// public void testSignInWorks() {
// solo.enterText(0, "userid@");
// solo.enterText(1, "<PASSWORD>");
// solo.clickOnButton("Sign In");
// boolean worked = solo.searchText("Course List");
// assertTrue("Sign in worked!", worked);
// }
}
|
7a5442d03b60ef356bb1166e8e2139e57d3aa243
|
[
"Java"
] | 1
|
Java
|
mehgancook/WebServiceLab1
|
ebf9e9ce14e9ad2cc1fb185dbe251968dcb469ec
|
5b6cc8d52341da67a5a6997a3053bc671abf30b8
|
refs/heads/master
|
<file_sep>argon-web
=========
原型,测试修改中。请前往其他分支。
<file_sep>import tornado.ioloop
import tornado.web
import os.path
import tornado.options
import tornado.httpserver
class LoginHandler(tornado.web.RequestHandler):
def initialize(self):
self.Islogin = False
def get(self):
self.render("templates/index.html" , IsLogin = self.Islogin)
def post(self):
if self.get_argument("Username") == "wangyufei" and self.get_argument("Password")=="<PASSWORD>" :
self.Islogin = True
self.render("templates/index.html" , IsLogin = self.Islogin )
class EmailHandler(tornado.web.RequestHandler):
def get(self):
self.render("templates/email.html", IsLogin = True)
class BoardHandler(tornado.web.RequestHandler):
def get(self):
self.render("templates/board.html", IsLogin = True)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", LoginHandler),
(r"/email", EmailHandler),
(r"/board", BoardHandler)
]
settings = dict(
static_path=os.path.join(os.path.dirname(__file__), "static"),
debug=True ,
)
tornado.web.Application.__init__(self, handlers, **settings)
def main():
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(8888)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
<file_sep>// simple jquery linkify plugin for argo
(function($){
var urls = [
[/&/g, '&'],
[/</g, '<'],
[/>/g, '>'],
// 1. jpg|png|gif pic to <img> tag, class from link
[/(|\s)(http:\/\/.+?\.)(jpg|png|gif)(\s|$)/g, '$1<img src="$2$3" class="fromlink attach_picture" alt="" />'],
[/(http:\/\/.+\.)(mp3)/g, '<audio src="$1$2" controls="controls" />'],
// 2. (http://)v.youku.com... to <embed> tag
[/(^|\s)(http:\/\/)?v\.youku\.com\/v_show\/id_(\w+)\.html(\s|$)/g,
'$1<embed wmode="opaque" src="http://player.youku.com/player.php/sid/$3/v.swf" allowFullScreen="true" quality="high" width="480" height="400" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash"></embed>'],
// to be added
// n - 1, url without proto to <a> tag
[/(^|\s)(www\..+?\..+?)(\s|$)/g, '$1<a href="http://$2">$2</a>$3'],
// n, url to <a> tag
[/(^|\s)(((https?|ftp):\/\/).+?)(\s|$)/g, '$1<a href="$2">$2</a>$5'],
//@gcc
[/@([a-zA-Z]{2,12})/g, '<a href="/profile/query/$1/">@$1</a>'],
];
linkifyThis = function () {
var childNodes = this.childNodes,
i = childNodes.length;
while(i--) {
var n = childNodes[i];
// 简单将灰色字体的行(<font class="c30">: ...</font>)当作引用,不对引用进行过滤。
if ($(n).hasClass("c30"))
continue;
if (n.nodeType == 3) {
var html = $.trim(n.nodeValue);
if (html)
{
for (u in urls) {
html = html.replace(urls[u][0], urls[u][1]);
}
$(n).after(html).remove();
}
}
else if (n.nodeType == 1 && !/^(a|button|textarea)$/i.test(n.tagName)) {
linkifyThis.call(n);
}
}
};
$.fn.linkify = function () {
return this.each(linkifyThis);
};
})(jQuery);
|
c9bc1fd4dc84f427ceef3268b47aa6c363f28ed1
|
[
"Markdown",
"Python",
"JavaScript"
] | 3
|
Markdown
|
argolab/argon-web
|
9e2bb4336f0c57ad2061b1f8d882aa481ddfee66
|
b75375398bb13ddf68ad84488d1bb364b0a621a3
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react';
import './App.css';
import AudioAnalyser from "./AudioAnalyser";
import Pitchfinder from "pitchfinder";
class App extends Component {
constructor(props) {
super(props);
this.state = {
audio: null
};
//We're going to use this toggle method with the button in the interface.
// To do so, we'll need to bind its context to the component.
// It's then referenced in the render function
this.toggleMicrophone = this.toggleMicrophone.bind(this);
}
// Below method uses async await to getUserMedia and set audio stream in state
async getMicrophone() {
const audio = await navigator.mediaDevices.getUserMedia({
audio: true,
video: false
});
this.setState({audio});
}
//Below will stop audio capture
stopMicrophone() {
this.state.audio.getTracks().forEach(track => track.stop());
this.setState({audio: null});
}
//now make a toggle method
toggleMicrophone() {
if (this.state.audio) {
this.stopMicrophone();
} else {
this.getMicrophone();
}
}
render() {
return (
<div className="App">
<div className="App">
<div className="controls">
<button onClick={this.toggleMicrophone}>
{this.state.audio ? 'Stop microphone' : 'Get microphone input'}
</button>
</div>
{this.state.audio ? <AudioAnalyser audio={this.state.audio} /> : ''}
{/*Here we're including the analyser only if the state contains the audio stream*/}
</div>
</div>
);
}
}
export default App;<file_sep>import React, {Component} from 'react';
class AudioVisualiser extends Component {
// need to get a reference to the <canvas> element so that we can draw on it later.
// In the constructor create the reference using React.createRef() and add the ref
// attribute to the <canvas> element.
constructor(props) {
super(props);
this.canvas = React.createRef();
}
//The draw function needs to run every time the audioData is updated. Add the following function to the component:
componentDidUpdate() {
this.draw(); // remember that 'draw' is our function we created below...
}
// The idea is to take the audioData we created in the previous component and draw a line from left to right
// between each data point in the array.
//
// Start with a new function called draw. This function will be called each
// time we get new data from the analyser. We start by setting up the variables we want to use:
draw() {
const {audioData} = this.props; //the audioData from the props and its length
const canvas = this.canvas.current; //the canvas from the ref
const height = canvas.height; //the height and width of the canvas
const width = canvas.width;
const context = canvas.getContext('2d'); // a 2d drawing context from the canvas
let x = 0; //will be used to track across the canvas
const sliceWidth = (width * 1.0) / audioData.length; //the amount we will move to the right every time we draw
// First setting our drawing style, in this case setting a line width of 2 and stroke style to the colour
// black. Then we clear previous drawings from the canvas.
context.lineWidth = 2;
context.strokeStyle = '#000000';
context.clearRect(0, 0, width, height);
// Next, begin the path we are going to draw and move the drawing position to halfway down the left side of the
// canvas.
context.beginPath();
context.moveTo(0, height / 2);
// Loop over the data in audioData. Each data point is between 0 and 255. To normalise this to our canvas we
// divide by 255 and then multiply by the height of the canvas. We then draw a line from the previous point to
// this one and increment x by the sliceWidth.
for (const item of audioData) {
const y = (item / 255.0) * height;
context.lineTo(x, y);
x += sliceWidth;
}
// Finally we draw a line to the point halfway down the right side of the canvas and direct the canvas to
// colour the entire path.
context.lineTo(x, height / 2);
context.stroke();
}
render() {
// We want to draw onto a canvas...
return <canvas width="300" height="300" ref={this.canvas}/>;
}
}
export default AudioVisualiser;
|
1e72924a15d0323860a5aa617e2a1240c314594b
|
[
"JavaScript"
] | 2
|
JavaScript
|
tcaraher/musician-toolbox-prototype
|
cd0d7033922122628f4aefce1806f1d71a26ce59
|
9a544e316cccc5a77fc1351ae884ff917de836fa
|
refs/heads/master
|
<repo_name>wade009/tinysquare-ops<file_sep>/util/PageUtil.js
function getPageBegin(pageNum, pageSize) {
if (pageNum != null && pageSize != null) {
pageNum = parseInt(pageNum,10);
pageSize = parseInt(pageSize,10);
return pageNum == null || pageNum <= 1 ? 0 : ((pageNum - 1) * pageSize);
}
return 0;
}
function getTotalPage(totalCount, pageSize) {
if (totalCount != null) {
totalCount = parseInt(totalCount,10);
pageSize = parseFloat(pageSize);
return Math.ceil(totalCount / pageSize);
}
return 0;
}
exports.getPageBegin = getPageBegin;
exports.getTotalPage = getTotalPage;
<file_sep>/public/js/common/dateutil.js
//define([], function () {
//});
function dateMinString(string) {
string = string.replace(/-/g, "/");
string += " 00:00:00.000";
return string;
}
function dateMaxString(string) {
string = string.replace(/-/g, "/");
string += " 23:59:59.999";
return string;
}
function dateString(string){
string = string.replace(/-/g, "/");
string = string.replace("T"," ");
string = string.replace(".000Z","");
string = string.replace(".999Z"," ");
return string;
}
<file_sep>/entity/VipConsumerRecord.js
var sequelize = require('sequelize');
var sequelizeDao = require('../dao/SequelizeDao');
const attributes = {
id: {
type: sequelize.BIGINT,
autoIncrement: true,
primaryKey: true
},
vipCardId: {
field: "vip_card_id",
type: sequelize.BIGINT
},
originalPrice: {
field: "original_price",
type: sequelize.DECIMAL
},
payPrice: {
field: "pay_price",
type: sequelize.DECIMAL
},
discount: sequelize.DECIMAL,
entrydate: sequelize.DATE
};
const options = {
tableName: "tiny_vip_consumer_record",
createdAt: false,
updatedAt: false,
deletedAt: false
};
const vipConsumerRecord = sequelizeDao.connections.define('VipConsumerRecord', attributes, options);
module.exports = vipConsumerRecord;
<file_sep>/dao/SequelizeDao.js
var sequelize = require('sequelize');
const URL = "mysql://localhost:3306/tinysquare?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull";
const CONFIG = {
username: "root",
password: "<PASSWORD>",
database: "tinysquare"
};
const CONNECTION_OPTIONS = {
host: 'localhost',
port: 3306,
dialect: 'mysql',
//queue: false,
pool: {
maxConnections: 6,
minConnections: 3,
maxIdleTime: 3600000
}
};
const OPTIONS_QUERY = {
raw: false,
transaction: null,
type: "SELECT"
};
const OPTIONS_UPDATE = {
raw: false,
transaction: null,
type: "BULKUPDATE"
};
const OPTIONS_DELETE = {
raw: false,
transaction: null,
type: "BULKDELETE"
};
var sequelizeConnections = new sequelize(CONFIG.database, CONFIG.username, CONFIG.password, CONNECTION_OPTIONS);
var sequelizeDao = {
connections: sequelizeConnections,
query: function (sql) {
return sequelizeConnections.query(sql, OPTIONS_QUERY);
},
update: function (sql) {
return sequelizeConnections.query(sql, null, OPTIONS_UPDATE);
},
delete: function (sql) {
return sequelizeConnections.query(sql, null, OPTIONS_DELETE);
}
}
module.exports = sequelizeDao;
<file_sep>/entity/Shop.js
var sequelize = require('sequelize');
var sequelizeDao = require('../dao/SequelizeDao');
const attributes = {
id: {
type: sequelize.BIGINT,
autoIncrement: true,
primaryKey: true
},
userId: {
field: "user_id",
type: sequelize.BIGINT
},
avator: sequelize.STRING,
name: sequelize.STRING,
mobile: sequelize.STRING,
tel: sequelize.STRING,
address: sequelize.STRING,
brief: sequelize.STRING,
description: sequelize.STRING,
favorite_count: sequelize.STRING,
longitude: sequelize.DOUBLE,
latitude: sequelize.DOUBLE,
status: sequelize.INTEGER,
entrydate: sequelize.DATE
};
const options = {
tableName: "tiny_shop",
createdAt: false,
updatedAt: false,
deletedAt: false
};
const shop = sequelizeDao.connections.define('Shop', attributes, options);
module.exports = shop;
<file_sep>/util/PromiseUtil.js
var q = require("q");
function toPromise(method) {
return function () {
var deferred = q.defer();
var args = Array.prototype.slice.call(arguments, 0);
args.push(deferred.callback());
method.apply(null, args);
return deferred.promise;
}
}<file_sep>/api/user/service/UserService.js
var user = require('../../../entity/User');
var pageUtil = require('../../../util/PageUtil');
function findAll(condition, pageNum, pageSize) {
var condtions = {
"where": createWhere(condition),
"order": "entrydate desc",
"offset": pageUtil.getPageBegin(pageNum, pageSize),
"limit": pageSize
};
return user.findAll(condtions);
}
function countAll(condition) {
var condtions = {
"where": createWhere(condition)
};
return user.count(condtions);
}
function createWhere(condition) {
var where = {};
if (condition.account != null && condition.account != "") {
where.account = condition.account;
}
if (condition.email != null && condition.email != "") {
where.email = condition.email;
}
if (condition.token != null && condition.token != "") {
where.token = condition.token;
}
if (condition.from != null && condition.from != "" && condition.to != null && condition.to) {
where.entrydate = {
"gte": new Date(condition.from),
"lte": new Date(condition.to)
};
}
return where;
}
exports.findAll = findAll;
exports.countAll = countAll;
<file_sep>/entity/CouponCode.js
var sequelize = require('sequelize');
var sequelizeDao = require('../dao/SequelizeDao');
const attributes = {
id: {
type: sequelize.BIGINT,
autoIncrement: true,
primaryKey: true
},
couponId: {
field: "coupon_id",
type: sequelize.BIGINT
},
code: sequelize.STRING,
quantity: sequelize.INTEGER,
redeem_time: sequelize.DATETIME,
status: sequelize.INTEGER,
entrydate: sequelize.DATE
};
const options = {
tableName: "tiny_coupon_code",
createdAt: false,
updatedAt: false,
deletedAt: false
};
const couponCode = sequelizeDao.connections.define('CouponCode', attributes, options);
module.exports = couponCode;
<file_sep>/entity/VipCard.js
var sequelize = require('sequelize');
var sequelizeDao = require('../dao/SequelizeDao');
const attributes = {
id: {
type: sequelize.BIGINT,
autoIncrement: true,
primaryKey: true
},
userId: {
field: "user_id",
type: sequelize.BIGINT
},
shopId: {
field: "shop_id",
type: sequelize.BIGINT
},
cardNum: {
field: "card_num",
type: sequelize.STRING
},
img: sequelize.STRING,
brief: sequelize.STRING,
points: sequelize.BIGINT,
user_times: sequelize.INTEGER,
category: sequelize.INTEGER,
is_default: sequelize.INTEGER,
status: sequelize.INTEGER,
entrydate: sequelize.DATE
};
const options = {
tableName: "tiny_vip_card",
createdAt: false,
updatedAt: false,
deletedAt: false
};
const vipCard = sequelizeDao.connections.define('VipCard', attributes, options);
module.exports = vipCard;
<file_sep>/entity/User.js
var sequelize = require('sequelize');
var sequelizeDao = require('../dao/SequelizeDao');
const attributes = {
id: {
type: sequelize.BIGINT,
autoIncrement: true,
primaryKey: true
},
category: sequelize.INTEGER,
account: sequelize.STRING,
tel: sequelize.STRING,
mobile: sequelize.STRING,
email: sequelize.STRING,
avatar: sequelize.STRING,
password: <PASSWORD>,
platform: sequelize.INTEGER,
version: sequelize.STRING,
status: sequelize.INTEGER,
token: sequelize.STRING,
entrydate: sequelize.DATE
};
const options = {
tableName: "tiny_user",
createdAt: false,
updatedAt: false,
deletedAt: false
};
const user = sequelizeDao.connections.define('User', attributes, options);
module.exports = user;
<file_sep>/routes/user.js
var express = require('express');
var router = express.Router();
var co = require('co');
var userService = require('../api/user/service/UserService');
var pageUtil = require('../util/PageUtil');
router.get('/listPage', function (req, res, next) {
res.render('user', null);
});
/* GET users listing. */
router.post('/list', function (req, res, next) {
//res.send('respond with a resource');
var pageNum = req.body.page;
pageNum = parseInt(pageNum, 10);
pageNum = pageNum + 1;
var pageSize = req.body.size;
pageSize = parseInt(pageSize, 10);
var condition = {
account: req.body.account,
email: req.body.email,
token: req.body.token,
from: req.body.from,
to: req.body.to
}
console.log(condition);
co(function * (){
var users = yield userService.findAll(condition, pageNum, pageSize);
var totalCount = yield userService.countAll(condition);
var result = {
"draw": req.body.draw,
"data": users,
"recordsTotal": totalCount,
"recordsFiltered": totalCount
}
res.json(result);
})
return;
});
module.exports = router;
|
fd644ed0fa65a9f88958d4c7230b539b3d8a01e4
|
[
"JavaScript"
] | 11
|
JavaScript
|
wade009/tinysquare-ops
|
05aed4ef49f6a84278f8086027b4b8d7df9a36f2
|
945fa438838771909087766672de730b8907e7e1
|
refs/heads/main
|
<repo_name>asivapra/abs<file_sep>/AWS_Comprehend/parse_comprehend-results.py
#!/usr/bin/env python
"""
parse_comprehend-results.py
GitHub: https://github.com/asivapra/abs/blob/main/AWS_Comprehend/parse_comprehend-results.py
This program parses the results from "AWS Comprehend Custom Entities Recognition" and masks the
entities in the original source document.
Author: Dr. <NAME>
Created on: 28-12-2020
Last Modified on: 01-01-2021
Copyright (c) 2020 by <NAME>, Australian Bureau of Statistics and WebGenie Software Pty Ltd.
"""
import re
import json
import spacy
from spacy.pipeline import EntityRuler
from spellchecker import SpellChecker
import time
import multiprocessing as mp
cer_file = r'avs6b.csv' # This is the CSV file saved from the AWS Custom Entities Recognition
doc_file = "avs4a.csv"
doc_file_masked = "avs4a_masked.csv"
analysis = 2 # 1 = analyse the results from the AWS Comprehend CER analysis. 2 = My own NLP method
limit = 10 # Limit the number of lines to be tested. Make this 0 for no limit.
cer_entities_file = './brands.txt'
spell = SpellChecker()
spell.word_frequency.load_text_file(cer_entities_file)
def mask_entities(offsets, doc_lines):
"""
Mask the entities in the original source document and write out.
:param offsets: The Begin/End positions for the entities. Received as a dict with the line number as the key.
:param doc_lines: The full content of the original document as a list.
:return: line = The entities masked out line.
"""
line_no = list(offsets.keys())[0]
# print(line_no)
line = doc_lines[line_no].rstrip().replace('"', '')
bs = offsets[line_no][0]
es = offsets[line_no][1]
chars = list(line)
for m in range(0, len(bs)):
for n in range(bs[m] + 1, es[m]):
chars[n] = '*'
line = "".join(chars)
# print(line_no, line) # For debugging. Do NOT delete
return line
def parse_cer_result(cer_content, doc_lines, masked_doc_file):
"""
This function cleanses the output from the AWS Athena query of the database table. Then, the required
offsets for the entities in the lines are taken and used to mask the entities.
1. Parse the AWS output data to get the Begin/End offsets and line number for the entities.
- Original lines in the AWS table search:
{"Entities": [{"BeginOffset": 0 "EndOffset": 6 "Score": 0.9999970197767496 "Text": "Palmer"
"Type": "BRAND"}] "File": "avs4.csv" "Line": 157}
- When saved as CSV, extra double quotes are added.
- Also, depending on the number of entities on a line, there will be extra commas and the word, 'output'
- These must be removed before parsing.
"{""Entities"": [{""BeginOffset"": 0"," ""EndOffset"": 10","
""Score"": 0.9999819997552802"," ""Text"": ""GO Healthy""\","
""Type"": ""BRAND""}]"," ""File"": ""avs4.csv""\"," ""Line"": 5663}",,,,,,,,,,,output
- In this function the lines are converted into a string as below, which is the same as in the AWS table.
- Then it can be JSON loaded into a dictionary object.
{"Entities" : [{"BeginOffset":int, "EndOffset":int, "Score": float, "Text": str, "Type": str}],
"File": str, "Line": int}
2. Each line will give the BeginOffset, EndOffset and Row (b, e, r). No need to take the entity's 'Text'
3. Using the b, e and r, mask the entities in the original doc_lines and write out in a file.
:param cer_content: The AWS output data. See read_cer_file(cer_file) for details
:param doc_lines: The full content of the original document as a list.
:param masked_doc_file: Output filename to write the masked lines.
:return: k, j == The numbers of lines actually parsed and the excluded lines
"""
print(f"Output file: {masked_doc_file}")
k = 0 # Number of lines where the entities are masked
j = 0 # Number of lines skipped. These include those without an entity and those with > 3 entities.
with open(masked_doc_file, "w") as mf:
line = "Titles with Masked Entities\n"
mf.writelines(line)
for ir in cer_content:
offsets = {}
ba = []
ea = []
# Replace the double double quotes around the keys
# and around the commas separating the items. These are added when saving as CSV.
# {""Entities"": [{""BeginOffset"": 0"," to {"Entities": [{"BeginOffset": 0",
# ir = i.replace('""', '"').replace('","', ',')
# ",,,,,,,,,,,output to '' and "{"Entities" to {"Entities"
# ir = re.sub(r'",*output', '', ir).replace('"{"', '{"')
try:
# The following line will give an error if the line does not end with a }.
# - ERROR: Expecting ',' delimiter: line 2 column 1
# It happens when there are more than three entities in the line as below.
# {"Entities": [{"BeginOffset": 0 "EndOffset": 5 "Score": 0.9999775891557117
# "Text": "Napro" "Type": "BRAND"} {"BeginOffset": 6 "EndOffset": 13
# "Score": 0.9999967813595916 "Text": "Palette" "Type": "BRAND"} {"BeginOffset": 14
# "EndOffset": 18 "Score": 0.9999977350285647 "Text": "Hair" "Type": "BRAND"}
# {"BeginOffset": 19 "EndOffset": 25
dict_ir = json.loads(ir) # 'dict_ir' is a dict object of the string, 'ir'
r = dict_ir['Line']
le = len(dict_ir['Entities'])
if not le: # There is no entity in the line.
j += 1
for n in range(0, le):
ba.append(dict_ir['Entities'][n]['BeginOffset'])
ea.append(dict_ir['Entities'][n]['EndOffset'])
offsets[r] = [ba, ea]
line = mask_entities(offsets, doc_lines) + "\n"
mf.writelines(line)
k += 1
except json.decoder.JSONDecodeError as e:
j += 1
print(f">>> ERROR: {e}. Skipping the line.")
return k, j
def parse_cer_result_0(cer_content, doc_lines, masked_doc_file):
"""
This function cleanses the output from the AWS Athena query of the database table. Then, the required
offsets for the entities in the lines are taken and used to mask the entities.
1. Parse the AWS output data to get the Begin/End offsets and line number for the entities.
- Original lines in the AWS table search:
{"Entities": [{"BeginOffset": 0 "EndOffset": 6 "Score": 0.9999970197767496 "Text": "Palmer"
"Type": "BRAND"}] "File": "avs4.csv" "Line": 157}
- When saved as CSV, extra double quotes are added.
- Also, depending on the number of entities on a line, there will be extra commas and the word, 'output'
- These must be removed before parsing.
"{""Entities"": [{""BeginOffset"": 0"," ""EndOffset"": 10","
""Score"": 0.9999819997552802"," ""Text"": ""GO Healthy""\","
""Type"": ""BRAND""}]"," ""File"": ""avs4.csv""\"," ""Line"": 5663}",,,,,,,,,,,output
- In this function the lines are converted into a string as below, which is the same as in the AWS table.
- Then it can be JSON loaded into a dictionary object.
{"Entities" : [{"BeginOffset":int, "EndOffset":int, "Score": float, "Text": str, "Type": str}],
"File": str, "Line": int}
2. Each line will give the BeginOffset, EndOffset and Row (b, e, r). No need to take the entity's 'Text'
3. Using the b, e and r, mask the entities in the original doc_lines and write out in a file.
:param cer_content: The AWS output data. See read_cer_file(cer_file) for details
:param doc_lines: The full content of the original document as a list.
:param masked_doc_file: Output filename to write the masked lines.
:return: k, j == The numbers of lines actually parsed and the excluded lines
"""
print(f"Output file: {masked_doc_file}")
k = 0 # Number of lines where the entities are masked
j = 0 # Number of lines skipped. These include those without an entity and those with > 3 entities.
with open(masked_doc_file, "w") as mf:
line = "Titles with Masked Entities\n"
mf.writelines(line)
for i in cer_content:
offsets = {}
ba = []
ea = []
# Replace the double double quotes around the keys
# and around the commas separating the items. These are added when saving as CSV.
# {""Entities"": [{""BeginOffset"": 0"," to {"Entities": [{"BeginOffset": 0",
ir = i.replace('""', '"').replace('","', ',')
# ",,,,,,,,,,,output to '' and "{"Entities" to {"Entities"
ir = re.sub(r'",*output', '', ir).replace('"{"', '{"')
try:
# The following line will give an error if the line does not end with a }.
# - ERROR: Expecting ',' delimiter: line 2 column 1
# It happens when there are more than three entities in the line as below.
# {"Entities": [{"BeginOffset": 0 "EndOffset": 5 "Score": 0.9999775891557117
# "Text": "Napro" "Type": "BRAND"} {"BeginOffset": 6 "EndOffset": 13
# "Score": 0.9999967813595916 "Text": "Palette" "Type": "BRAND"} {"BeginOffset": 14
# "EndOffset": 18 "Score": 0.9999977350285647 "Text": "Hair" "Type": "BRAND"}
# {"BeginOffset": 19 "EndOffset": 25
dict_ir = json.loads(ir) # 'dict_ir' is a dict object of the string, 'ir'
r = dict_ir['Line']
le = len(dict_ir['Entities'])
if not le: # There is no entity in the line.
j += 1
for n in range(0, le):
ba.append(dict_ir['Entities'][n]['BeginOffset'])
ea.append(dict_ir['Entities'][n]['EndOffset'])
offsets[r] = [ba, ea]
line = mask_entities(offsets, doc_lines) + "\n"
mf.writelines(line)
k += 1
except json.decoder.JSONDecodeError as e:
j += 1
print(f">>> ERROR: {e}. Skipping the line.")
return k, j
def read_doc_file(doc_file):
"""
Read the file contents from the source document. e.g. 'avs4.csv'.
:param doc_file: The filename returned by get_doc_file_names(cer_content)
:return: lines == doc_lines. The full content as a list.
"""
with open(doc_file, 'r') as f:
lines = f.readlines()
return lines
def get_doc_file_names(cer_content):
"""
Get the filename of the source document. e.g. 'avs4.csv'. This filename is included
in the AWS output data and is on every line except incomplete and more than 3 entities lines.
:param cer_content: The AWS output data. See read_cer_file(cer_file) for details
:return: doc_file, masked_doc_file == the document file name and the output file to write the masked lines.
"""
for i in (0, len(cer_content)):
ir = cer_content[i].replace('""', '"').replace('","', ',')
ir = re.sub(r'",*output', '', ir).replace('"{"', '{"')
try:
dict_ir = json.loads(ir) # 'dict_ir' is a dict object of the string, 'ir'
doc_file = dict_ir['File']
masked_doc_file = doc_file.replace(".csv", "_masked.csv")
return doc_file, masked_doc_file
except json.decoder.JSONDecodeError as e:
print(f">>> ERROR: {e}. Skipping the line.")
def read_cer_file():
"""
Read the content of the output from the AWS Comprehend analysis
:param cer_file: The data input file. Contents as below.
- The 'avs6a.csv' is the output from the AWS Comprehend analysis.
Sample lines:
1-Entity:
{"Entities": [{"BeginOffset": 0, "EndOffset": 6, "Score": 0.9999970197767496,
"Text": "Palmer", "Type": "BRAND"}], "File": "avs4.csv", "Line": 157}
2-Entitites:
{"Entities": [{"BeginOffset": 0, "EndOffset": 6, "Score": 0.9999930859092101,
"Text": "Palmer", "Type": "BRAND"}, {"BeginOffset": 9, "EndOffset": 16,
"Score": 0.9999995231630692, "Text": "Natural", "Type": "BRAND"}], "File": "avs4.csv",
"Line": 164}
3-Entitites:
{"Entities": [{"BeginOffset": 0, "EndOffset": 7, "Score": 0.9999976158197796,
"Text": "Johnson", "Type": "BRAND"}, {"BeginOffset": 10, "EndOffset": 14,
"Score": 0.9999986886995842, "Text": "Head", "Type": "BRAND"}, {"BeginOffset": 22,
"EndOffset": 26, "Score": 0.9999995231630692, "Text": "Baby", "Type": "BRAND"}],
"File": "avs4.csv" "Line": 5702}
:return: cer_content
"""
print(f'Input file: {cer_file}')
with open(cer_file, 'r') as f:
cer_content = f.readlines() # This is the CSV file saved from the Custom Entities Recognition
cer_content = cer_content[2:]
return cer_content
def lemmatise(text, nlp):
# Implementing lemmatization
lt = []
# It is not necessary to lower case the words since the 'token.lemma_' will do it.
# However, some proper nouns are not lower cased by the lemma_ function.
text = text.lower()
doc = nlp(text)
for token in doc:
# Remove stopwords (like the, an, of), punctuations and junk (like etc., i.e.)
if not token.is_stop and not token.is_punct and not token.pos_ == 'X':
# p = nltk.PorterStemmer()
# word = p.stem(token.lemma_)
# lt.append(word) # Add the lemma of the word in an array
# lt.append(token.lemma_) # Add the lemma of the word in an array
lt.append(token.text) # Add the lemma of the word in an array
return " ".join(lt) # Return it as a full string
def star_entities(b, e, keys, nlp, wr):
"""
This function replaces the identified brands in each line with *'s.
More than one brand in a line can be processed.
How?
- Each line is split into words
- Skip words that are less than 4 letters. Hint: Profanity words are always 4 letters or more.
- This means brands like 3M, A2, Aim, etc. will be skipped.
- Skip words with a digit in it. This is to skip words like 50mg, 100u, etc.
- It too will miss brands like A2, 3M.
- Put the words through 'spell.correction'
- It will correct spelling in most dictionary words.
- Brands are generally not dictionary words, but they will be checked against the 'brand_names' since this
file has been added via 'def build_entity_ruler'. It picks up most common misspellings.
- Join the words to form a spelling corrected line which replaces the original line.
- Create an NLP object, 'docnlp', with the new line.
- Iterate through the 'docnlp.ent' objects and pick those which have the label, 'brand'.
- Find the index position of this entity in the string, 'doc'.
- Add the index and the length of this entity in a 2D array as 'ii = [[i, j]]'
- Split the doc line into a list ('s').
- Iterate through 's' and mask the words using their start index and length from 'ii'
- Join 's' into a line and write it out.
:param b: Start of lines to to be processed
:param e: End of lines.
:param keys: The brands' list as in brand_names.txt
:param nlp: The NLP object using model 'en'
:param wr: The worker number
:return: None
"""
if wr == 0: # Means that the job is in serial mode.
with open(doc_file_masked, "w") as mf:
line = "Lines with brand names masked out\n"
mf.writelines(line)
with open(doc_file_masked, "a") as mf:
if limit:
e = b + limit # Debugging. DO NOT DELETE. To limit the # of lines.
print(f"Worker {wr}: Processing lines {b} to {e}.")
keys = keys[b:e]
n = b
for key in keys:
n += 1
if wr == 0:
print(f"w:{wr} :{n}")
doc_cw = []
ii = []
words = key.split()
for w in words:
if len(w) <= 3:
doc_cw.append(w)
elif re.search('\d', w):
doc_cw.append(w)
else:
cw = spell.correction(w)
doc_cw.append(cw)
doc = " ".join(doc_cw)
docnlp = nlp(doc)
for ent in docnlp.ents:
if ent.label_ == 'brand':
i = doc.index(ent.text)
ii.append([i, len(ent.text)])
s = list(doc)
line = ''
for i in ii:
k1 = i[0]
k2 = i[1]
for j in range(k1 + 1, k1 + k2):
if s[j] == ' ': # Do not change space to *
continue
s[j] = '*'
line = key + "\t" + "".join(s) + "\n"
mf.writelines(line)
print(f"Worker {wr}: Finished.")
def par_star_entities(keys, nlp):
"""
Run it in parallel mode. This is to maximise performance
:return: None
"""
print("Warning: In Parallel Mode:")
print("Writing masked lines in:", doc_file_masked)
with open(doc_file_masked, 'w') as f:
f.write("Original Lines\tMasked Lines\n")
ct0 = time.perf_counter()
# nlp = read_dictionary()
j = len(keys)
print("Total Lines:", j)
# keys1.sort()
# keys2.sort()
num_workers = mp.cpu_count() * 1
chunk_size = j // num_workers
n_chunks = j // chunk_size
remainder = j - (chunk_size * num_workers)
print("Starting: num_workers, chunk_size, remainder:", num_workers, chunk_size, remainder)
workers = []
# Each worker gets a subset of the URLs.
# e.g. 16 workers and nn URLs:
e = r = w = 0 # Declare these to avoid a warning
for w in range(n_chunks):
b = w * chunk_size
e = b + chunk_size
workers.append(mp.Process(target=star_entities, args=(b, e, keys, nlp, w)))
# If the number of items is not an exact multiple of 'num_workers' there will be some leftover.
# Start a new worker to handle those.
# Below, j == the number of keys1. This is to be split across the workers.
# e = total lines allocated across num_workers. If it is not the same as j, there is
# some leftover. Start a new worker for it.
try:
if e:
r = j - e
if r > 0: # See if any leftover
w += 1
workers.append(mp.Process(target=star_entities, args=(e, j, keys, nlp, w)))
except Exception as e:
print(e)
pass
with open(doc_file_masked, "w") as mf:
line = "Lines with brand names masked out\n"
mf.writelines(line)
for w in workers:
w.start()
# Wait for all processes to finish
for w in workers:
w.join()
et = time.perf_counter() - ct0
print("Finished. Time: {:0.2f} sec".format(et))
def build_entity_ruler(nlp):
"""
Add the brand names as custom entities to the NLP object.
:param nlp: The NLP object using the model, 'en'
:return: nlp = the modified NLP object
"""
rulerBrands = EntityRuler(nlp, 'LOWER', overwrite_ents=True)
with open(cer_entities_file, "r") as f:
filecontent = f.readlines()
s1 = {i.strip() for i in filecontent} # Add to a set to remove duplicates
brands = [item.strip() for item in s1 if item != '\n']
for brand_name in brands:
rulerBrands.add_patterns([{"label": "brand", "pattern": brand_name}])
rulerBrands.name = 'rulerBrands'
nlp.add_pipe(rulerBrands)
return nlp
def create_dict(csvfile):
"""
Read the input file and return its content in a list.
:param csvfile: Input file
The csvfile contains the original text lines as:
Name
Leukopot Snap Spool 1.25cm x 5m
:return: keys = list of lines in the input file.
"""
lines = []
with open(csvfile) as f:
for line in f:
line = line.strip()
try: # There are lines with just the URLs. These will give an error
if line == "Name":
continue
lines.append(line)
except ValueError as e:
print(e)
pass
return lines
def read_dictionary():
"""
Read the dictionary.
The stop words are not read separately. They are part of the nlp model.
:return: None
"""
# model = 'en_core_web_sm'
# model = 'en_core_web_md'
# model = 'en_core_web_lg'
model = 'en' # Using 'en' instead of 'en_core_web_md', as the latter has many words without vector data. Check!
print("Starting to read the model:", model)
# nlp = spacy.cli.download("en") # Run this for the first time on a new server.
# nlp = spacy.cli.download("en_core_web_sm") # Run this for the first time on a new server.
# nlp = spacy.cli.download("en_core_web_md") # Run this for the first time on a new server.
# nlp = spacy.cli.download("en_core_web_lg") # Run this for the first time on a new server.
# Smaller models: en_core_web_md and en_core_web_sm
nlp = spacy.load(model) # Use this for subsequent runs
# sr = stopwords.words('english')
return nlp
def main():
"""
This program parses the results from "AWS Comprehend Custom Entities Recognition" and masks the
entities in the original source document.
Tested with "BrandsRecognizer" in AWS using 'avs4.csv' as source file.
How it works:
- analysis == 1:
1. The 'BrandsRecognizer' is generated via AWS Comprehend as described in 'AWS Comprehend Custom Entities.docx'
- Using 'brands.csv' as entities doc and 'avs4.csv' as training doc.
2. The 'avs4.csv' is the same as 'amcal_products_u.txt'
3. The 'avs6a.csv' is the output from the AWS Comprehend analysis.
4. The content in 'avs6a.csv' is read and the top 2 lines removed to form 'cer_content'
(CER = Custom Entities Recognition)
5. The content in 'avs4.csv' is read as 'doc_lines'
6. In parse_cer_result:
- Each line in 'cer_content' can have up to 3 entities.
- A doc_line with more than 3 entities will not have the line number in cer_content and cannot be used.
- Each line is parsed to take the Begin/End offsets of the matching entities.
- Each doc_line is now parsed to mask the entities using the offset values.
- write out in 'masked_doc_file'
- analysis == 2:
This does not use the AWS Comprehend output at all. Instead, uses a custom entity file (e.g. brand_names.txt')
and the document input file to directly compare and mask the words/phrases.
This method is devised as an alternative to AWS Comprehend which has a potential problem of not detecting
all occurrences of the words/phrases in the doc lines. See the doc comment in 'def star_entities' for details.
See the comments in each function for more details.
:return:
"""
global doc_file
if analysis == 1:
# Using the output from the AWS Comprehend Custom Enitity Recognition analysis
cer_content = read_cer_file() # This is the cer_file content (cer = Custom Entity Recognition)
doc_file, masked_doc_file = get_doc_file_names(
cer_content) # This is the file containing the document lines to scan
doc_lines = read_doc_file(doc_file)
k, j = parse_cer_result(cer_content, doc_lines, masked_doc_file)
print(f"Processed: {k} lines with entities masked. Excluding {j} incomplete lines.")
elif analysis == 2:
# Do a comparison with entity recognition using my own NLP method.
nlp = read_dictionary()
keys = create_dict(doc_file) # This is the doc with the original lines.
j = len(keys)
print("Total Lines:", j)
nlp = build_entity_ruler(nlp)
# star_entities(0, len(keys), keys, nlp, 0) # Run as serial job
par_star_entities(keys, nlp) # Run it as a parallel job.
if __name__ == '__main__':
main()
<file_sep>/Word2vec/parse_hotel_reviews.py
#!/usr/bin/env python
"""
Project: ABS
Git: https://github.com/asivapra/abs
Author: <NAME>
Created: 10/01/2021
Last Modified: 10/01/2021
Description:
- To parse a HTMl for hotel reviews from Trevago
"""
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import time
retries = 0 # Number of times to try and retrieve a page.
url = "https://eagle1023.webgenie.com/ABS/Word2Vec/hotel_reviews.html"
def get_soup_bs4(url):
"""
Get the page content displayed as plain HTML.
:param url: The page URL
:return: soup = The page content
"""
hdr = {'User-Agent': 'Mozilla/5.0'}
req = Request(url, headers=hdr)
page = urlopen(req)
soup = BeautifulSoup(page, "html.parser")
return soup
def get_reviews(url):
soup = get_soup_bs4(url)
# print(soup)
review_pees = soup.find_all("p", {"class": "sl-review__summary"})
print("Number of Reviews:", len(review_pees))
n = 0
for i in review_pees:
n += 1
review = i.text
print(review)
def main():
ct0 = time.perf_counter() # Track the elapsed time
get_reviews(url)
et = time.perf_counter() - ct0
print("Total Time: {:0.2f} sec".format(et))
if __name__ == '__main__':
# create_urls() # This is required only once to get a list of URLs for working with the 'main()'
main()
<file_sep>/Word2vec/word2vec.py
#!/usr/bin/env python
"""
Project: ABS/Word2vec
Git: https://github.com/asivapra/abs/tree/main/Word2vec
Author: <NAME>
Created: 08/01/2021
Last Modified: 08/01/2021
Logics to be tried:
1. Word2Vec Similar words
- Build and train the model using a large data set (e.g. hotel reviews 250K lines)
- Prepare a set using common words as...
- Common words between pairs of texts
- Append them together into a set
- Manually classify them as good, bad, ugly and neutral
- Get up to 100 similar words for each class
- Add as class | text. Multiple lines allowed
- Get common words between test line and these bag of words (bow)
- Get CS score between the common words and the bow
- Take the highest CS score and its class
"""
import gzip
import gensim
import logging
import os
import nltk
import string
import re
import spacy
from gensim.models import Word2Vec, KeyedVectors
import RAKE
from spellchecker import SpellChecker
from collections import Counter
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
spell = SpellChecker(distance=10)
# nltk.download('punkt')
# nltk.download('stopwords')
logging.basicConfig(
format='%(asctime)s : %(levelname)s : %(message)s',
level=logging.INFO)
def show_file_contents(input_file):
with gzip.open(input_file, 'rb') as f:
for i, line in enumerate(f):
print(line)
break
def read_input(input_file):
"""
This method reads the input file which is in gzip format
"""
logging.info("reading file {0}...this may take a while".format(input_file))
with gzip.open(input_file, 'rb') as f:
for i, line in enumerate(f):
if i % 10000 == 0:
logging.info("read {0} reviews".format(i))
# do some pre-processing and return list of words for each review
# text
yield gensim.utils.simple_preprocess(line)
def build_save_model(docs):
print("Building, training and saving the model...")
model = gensim.models.Word2Vec(
docs,
size=150,
window=10,
min_count=2,
workers=10)
model.train(docs, total_examples=len(docs), epochs=10)
# save only the word vectors
# model.wv.save(os.path.join(abspath, "../vectors/default"))
model.wv.save_word2vec_format('hotelreviews_model.bin', binary=True)
return model
def read_train_save_model():
abspath = os.path.dirname(os.path.abspath(__file__))
data_file = os.path.join(abspath, "reviews_data.txt.gz")
documents = list(read_input(data_file))
logging.info("Done reading the data file. Now building and saving the model.")
build_save_model(documents)
def Sort_Tuple(tup):
tup.sort(key = lambda x: x[1])
return tup
def read_lines():
with open("reviews_data_3.txt", "r") as f:
for i, line in enumerate(f):
cols = line.split("\t")
yield cols
def similar_words(model, rake_object):
# stop_dir = "../AWS_Comprehend/Classification/stopwords.txt"
# rake_object = RAKE.Rake(stop_dir)
reviews = list(read_lines())
print(len(reviews))
for i in range(1):
s = reviews[i]
keywords = Sort_Tuple(rake_object.run(s))[:]
print(len(keywords), s)
for k in keywords:
try:
w1 = k[0]
score = k[1]
similar_words = []
words = model.most_similar(positive=w1)
for w in words:
spell_corrected_word = spell.correction(w[0])
similar_words.append(spell_corrected_word)
similar_words = sorted(set(similar_words))
print("{:s}: {:0.2f}".format(w1, score), similar_words)
except Exception as e:
# print(k)
# print(f"*****{e}")
pass
def common_words(nlp):
lines = list(read_lines())
with open("results.txt", "w") as f:
f.writelines(f"CS\tdiff\tdoc1\tdoc2\n")
for i in range(1, 31):
class1 = lines[i][0]
# print(lines[i])
translator = str.maketrans(string.punctuation, ' ' * len(string.punctuation)) # map punctuation to space. Works
line1 = lines[i][1].translate(translator).strip()
# print(line1)
document_1_words = set(line1.split())
tokens1_without_sw = [word for word in document_1_words if word not in stopwords.words() and len(word) >= 4]
doc1 = " ".join(tokens1_without_sw)
doc1 = lemmatise(doc1, nlp)
doc1nlp = nlp(doc1)
for j in range(i+1, 31):
translator = str.maketrans(string.punctuation, ' ' * len(string.punctuation))
line2 = lines[j][1].translate(translator)
# print(line2)
document_2_words = set(line2.split())
tokens2_without_sw = [word for word in document_2_words if
word not in stopwords.words() and len(word) >= 4]
common = set(tokens1_without_sw).intersection(set(tokens2_without_sw))
doc2 = " ".join(common)
doc2 = lemmatise(doc2, nlp)
doc2nlp = nlp(doc2)
cs = round(doc1nlp.similarity(doc2nlp), 2) # Average time: 1,993 microsec
print(cs, doc2nlp)
# break
break
def most_common_phrases(rake_object, nlp):
lines = list(read_lines())
with open("results.txt", "w") as f:
f.writelines(f"CS\tdiff\tdoc1\tdoc2\n")
for i in range(1, 31):
class1 = lines[i][0]
translator = str.maketrans(string.punctuation, ' ' * len(string.punctuation)) # map punctuation to space. Works
line1 = lines[i][1].translate(translator).strip()
doc1 = lemmatise(line1, nlp)
doc1nlp = nlp(doc1)
print(i, line1)
tot_csh = {}
k = 0
prev_class = ""
tot_cs = 0.00
for j in range(1, 31):
k += 1
class2 = lines[j][0]
this_class = class2
if not prev_class:
prev_class = this_class
translator = str.maketrans(string.punctuation, ' ' * len(string.punctuation))
line2 = lines[j][1].translate(translator)
key_phrases = Sort_Tuple(rake_object.run(line2))[:] # returns [(key/phrase, score)...] in ascending score order
substring = ""
try:
for s in key_phrases[:]: # Take the highest 10 phrases.
# print(s)
if s[1] > 1.0:
substring += s[0] + " "
except Exception as e:
print(e)
pass
doc2 = lemmatise(substring, nlp)
doc2nlp = nlp(doc2)
cs = round(doc1nlp.similarity(doc2nlp), 2) # Average time: 1,993 microsec
# print(i, j, cs, class1, class2)
try:
tot_csh[this_class] += cs
except:
tot_csh[this_class] = cs
if prev_class == this_class:
tot_cs += cs
else:
prev_class = ""
k = 0
# avg_cs = round(tot_cs / (k-1), 2)
# print(f"avgs_cs:{avg_cs} = {tot_cs} / {k-1}")
# tot_cs = 0.00
# f.writelines(f"Avg:{avg_cs}\t\t\n")
f.writelines(f"{cs}\t{0.91-cs}\t{line1}\t{line2}\n")
# print(class1, tot_csh)
# avg_cs = round(tot_cs / (k - 1), 2)
# print(f"avgs_cs:{avg_cs} = {tot_cs} / {k - 1}")
# f.writelines(f"Avg:{avg_cs}\t\t\n")
# print(i, j, class1, class2, cs, substring)
def most_common_words():
reviews = list(read_lines())
words = []
for i in range(1):
line = reviews[i].translate(str.maketrans('', '', string.punctuation)) # Remove punctuations
print("line:", line)
text_tokens = word_tokenize(line)
tokens_without_sw = [word for word in text_tokens if word not in stopwords.words() and len(word) >= 4]
# keywords = reviews[i].split()
# print(s)
# keywords = s.split()
# keywords = Sort_Tuple(rake_object.run(s))[:]
print("A.:", tokens_without_sw)
for k in tokens_without_sw:
words.append(k)
print(words)
C = Counter(words)
most_occur = C.most_common(4)
print(most_occur)
def get_rake_object():
stop_dir = "../AWS_Comprehend/Classification/stopwords.txt"
rake_object = RAKE.Rake(stop_dir)
return rake_object
def read_dictionary():
"""
Read the dictionary.
The stop words are not read separately. They are part of the nlp model.
:return: None
"""
# model = 'en_core_web_sm'
# model = 'en_core_web_md'
# model = 'en_core_web_lg'
model = 'en' # Using 'en' instead of 'en_core_web_md', as the latter has many words without vector data. Check!
print("Starting to read the model:", model)
# nlp = spacy.cli.download(model) # Run this for the first time on a new server.
nlp = spacy.load(model) # Use this for subsequent runs
return nlp
def lemmatise(text, nlp):
# Implementing lemmatization
lt = []
# It is not necessary to lower case the words since the 'token.lemma_' will do it.
# However, some proper nouns are not lower cased by the lemma_ function.
text = text.lower()
doc = nlp(text)
for token in doc:
# Remove stopwords (like the, an, of), punctuations and junk (like etc., i.e.)
# if not token.is_stop and not token.is_punct and not token.pos_ == 'X':
if not token.is_stop and not token.is_punct:
lt.append(token.lemma_) # Add the lemma of the word in an array
return " ".join(lt) # Return it as a full string
def main():
# For reading and training. Required once only
# read_train_save_model() # Comment this out in subsequent runs
nlp = read_dictionary()
# rake_object = get_rake_object()
# model = KeyedVectors.load_word2vec_format('hotelreviews_model.bin', binary=True)
# lookup(model)
# similar_words(model, rake_object)
# most_common_words()
# most_common_phrases(rake_object, nlp)
common_words(nlp)
def lookup(model):
w1 = ["dirty"]
print("Most similar to {0}".format(w1), model.most_similar(positive=w1))
w1 = ["dirty"]
print("Most dissimilar to {0}".format(w1), model.most_similar(negative=w1))
# look up top 6 words similar to 'polite'
w1 = ["polite"]
print("Most similar to {0}".format(w1), model.most_similar(positive=w1, topn=6))
w1 = ["polite"]
print("Most dissimilar to {0}".format(w1), model.most_similar(negative=w1, topn=6))
# look up top 6 words similar to 'france'
w1 = ["france"]
print(
"Most similar to {0}".format(w1),
model.most_similar(
positive=w1,
topn=6))
# look up top 6 words similar to 'shocked'
w1 = ["shocked"]
print(
"Most similar to {0}".format(w1),
model.most_similar(
positive=w1,
topn=6))
# look up top 6 words similar to 'shocked'
w1 = ["beautiful"]
print(
"Most similar to {0}".format(w1),
model.most_similar(
positive=w1,
topn=6))
# get everything related to stuff on the bed
w1 = ["bed", 'sheet', 'pillow']
w2 = ['blanket']
print(
"Most similar to {0}".format(w1),
model.most_similar(
positive=w1,
negative=w2,
topn=10))
# similarity between two different words
print("Similarity between 'dirty' and 'smelly'",
model.similarity(w1="dirty", w2="smelly"))
# similarity between two identical words
print("Similarity between 'dirty' and 'dirty'",
model.similarity(w1="dirty", w2="dirty"))
# similarity between two unrelated words
print("Similarity between 'dirty' and 'unclean'",
model.similarity(w1="dirty", w2="unclean"))
if __name__ == '__main__':
main()
<file_sep>/AWS_Comprehend/Classification/spam_classifier.py
#!/usr/bin/env python
"""
parse_comprehend-results.py
GitHub: https://github.com/asivapra/abs/blob/main/AWS_Comprehend/parse_comprehend-results.py
This program parses the results from "AWS Comprehend Custom Entities Recognition" and masks the
entities in the original source document.
Author: Dr. <NAME>
Created on: 28-12-2020
Last Modified on: 01-01-2021
Copyright (c) 2020 by <NAME>, Australian Bureau of Statistics and WebGenie Software Pty Ltd.
"""
import re
import RAKE
import spacy
from spacy.pipeline import EntityRuler
from spellchecker import SpellChecker
import time
import multiprocessing as mp
spam_phrases = 'spam_phrases.txt' # This is the CSV file saved from the AWS Custom Entities Recognition
spam_lines = "spam_lines.txt"
doc_file_masked = "spam_lines_masked.txt"
limit = 0 # Limit the number of lines to be tested. Make this 0 for no limit.
spell = SpellChecker()
spell.word_frequency.load_text_file(spam_phrases)
def Sort_Tuple(tup):
tup.sort(key=lambda x: x[1])
return tup
def get_phrases(s, spc):
stop_dir = "stopwords.txt"
rake_object = RAKE.Rake(stop_dir)
keywords = Sort_Tuple(rake_object.run(s))[-10:]
# print(keywords)
for i in keywords:
if i[1] >= 4.0:
if i[0] not in spc:
with open(spam_phrases, "a") as f:
f.writelines(f"{i[0]}\n")
def star_entities(b, e, d1, nlp, spc, wr):
"""
This function replaces the identified brands in each line with *'s.
More than one brand in a line can be processed.
How?
- Each line is split into words
- Skip words that are less than 4 letters. Hint: Profanity words are always 4 letters or more.
- This means brands like 3M, A2, Aim, etc. will be skipped.
- Skip words with a digit in it. This is to skip words like 50mg, 100u, etc.
- It too will miss brands like A2, 3M.
- Put the words through 'spell.correction'
- It will correct spelling in most dictionary words.
- Brands are generally not dictionary words, but they will be checked against the 'brand_names' since this
file has been added via 'def build_entity_ruler'. It picks up most common misspellings.
- Join the words to form a spelling corrected line which replaces the original line.
- Create an NLP object, 'docnlp', with the new line.
- Iterate through the 'docnlp.ent' objects and pick those which have the label, 'brand'.
- Find the index position of this entity in the string, 'doc'.
- Add the index and the length of this entity in a 2D array as 'ii = [[i, j]]'
- Split the doc line into a list ('s').
- Iterate through 's' and mask the words using their start index and length from 'ii'
- Join 's' into a line and write it out.
:param d1: Dict object as {urk: text}
:param spc: The spam phrases in 'spam_phrases.txt'
:param b: Start of lines to to be processed
:param e: End of lines.
:param nlp: The NLP object using model 'en'
:param wr: The worker number
:return: None
"""
if wr == 0: # Means that the job is in serial mode.
with open(doc_file_masked, "w") as mf:
line = "Lines with brand names masked out\n"
mf.writelines(line)
if limit:
e = b + limit # Debugging. DO NOT DELETE. To limit the # of lines.
print(f"Worker {wr}: Processing lines {b} to {e}.")
keys = list(d1.keys())
keys = keys[b:e]
n = e - b
for urk in keys:
n -= 1
# if wr == 0:
# print(f"w:{wr} :{n}")
doc_cw = [] # Corrected words
ii = []
text = d1[urk]
words = text.split()
for w in words:
if len(w) <= 3:
doc_cw.append(w)
elif re.search('\d', w):
doc_cw.append(w)
else:
cw = spell.correction(w)
doc_cw.append(cw)
doc = " ".join(doc_cw)
docnlp = nlp(doc)
words = []
# d2 = {}
for ent in docnlp.ents:
if ent.label_ == 'brand':
i = doc.index(ent.text)
ii.append([i, len(ent.text)])
words.append(ent.text.lower())
# d2[urk] = words
if len(words):
get_phrases(doc, spc)
s = list(doc)
try:
for i in ii:
k1 = i[0]
k2 = i[1]
s[k1-1] = ' >>>'
s[k1+k2] = '<<< '
# for j in range(k1 + 1, k1 + k2):
# if s[j] == ' ': # Do not change space to *
# continue
# s[j] = '*'
except IndexError:
pass
doc = "".join(s)
my_set = set(words)
text = ", ".join(my_set)
print(urk, doc)
with open(doc_file_masked, "a") as mf:
mf.writelines(f"{urk}\tSpam\t{text}\t{doc}\n")
else:
with open(doc_file_masked, "a") as mf:
mf.writelines(f"{urk}\t\t\t{doc}\n")
# if wr == 0:
print(f"Worker_{wr}: {n}")
print(f"Worker {wr}: Finished.")
def par_star_entities(d1, nlp, spc):
"""
Run it in parallel mode. This is to maximise performance
:return: None
"""
print("Warning: In Parallel Mode:")
print("Writing masked lines in:", doc_file_masked)
with open(doc_file_masked, 'w') as f:
f.write("Original Lines\tMasked Lines\n")
ct0 = time.perf_counter()
keys = d1.keys()
j = len(keys)
print(f"Total Lines: {j}. Limiting {limit} per worker")
num_workers = mp.cpu_count() * 1
chunk_size = j // num_workers
n_chunks = j // chunk_size
remainder = j - (chunk_size * num_workers)
print("Starting: num_workers, chunk_size, remainder:", num_workers, chunk_size, remainder)
workers = []
# Each worker gets a subset of the URLs.
# e.g. 16 workers and nn URLs:
e = r = w = 0 # Declare these to avoid a warning
for w in range(n_chunks):
b = w * chunk_size
e = b + chunk_size
workers.append(mp.Process(target=star_entities, args=(b, e, d1, nlp, spc, w)))
# If the number of items is not an exact multiple of 'num_workers' there will be some leftover.
# Start a new worker to handle those.
# Below, j == the number of keys1. This is to be split across the workers.
# e = total lines allocated across num_workers. If it is not the same as j, there is
# some leftover. Start a new worker for it.
try:
if e:
r = j - e
if r > 0: # See if any leftover
w += 1
workers.append(mp.Process(target=star_entities, args=(e, j, d1, nlp, spc, w)))
except Exception as e:
print(e)
pass
with open(doc_file_masked, "w") as mf:
line = "Lines with brand names masked out\n"
mf.writelines(line)
for w in workers:
w.start()
# Wait for all processes to finish
for w in workers:
w.join()
et = time.perf_counter() - ct0
print("Finished. Time: {:0.2f} sec".format(et))
def build_entity_ruler(nlp):
"""
Add the brand names as custom entities to the NLP object.
:param nlp: The NLP object using the model, 'en'
:return: nlp = the modified NLP object
"""
rulerBrands = EntityRuler(nlp, 'LOWER', overwrite_ents=True)
with open(spam_phrases, "r") as f:
filecontent = f.readlines()
spam_phrases_content = [line.strip() for line in filecontent]
s1 = {i for i in spam_phrases_content} # Add to a set to remove duplicates
brands = [item.strip() for item in s1 if item != '\n']
for brand_name in brands:
rulerBrands.add_patterns([{"label": "brand", "pattern": brand_name}])
rulerBrands.name = 'rulerBrands'
nlp.add_pipe(rulerBrands)
return nlp, spam_phrases_content
def read_spam_file(tsvfile):
"""
Read the input file and return its content in a list.
:param tsvfile: Input file
The tsvfile contains the original text lines as:
Name
Leukopot Snap Spool 1.25cm x 5m
:return: keys = list of lines in the input file.
"""
global spam_lines_content
lines = {}
with open(tsvfile, "r") as f:
spam_lines_content = f.readlines()
# with open(tsvfile, "w") as f:
for line in spam_lines_content:
try:
cols = line.strip().split("\t")
urk = cols[0]
text = cols[1]
# f.writelines(f"{line}") # This will rewrite the input file without the blanks
try:
lines[urk] = text
except ValueError:
pass
except IndexError:
pass
return lines
def read_dictionary():
"""
Read the dictionary.
The stop words are not read separately. They are part of the nlp model.
:return: None
"""
model = 'en' # Using 'en' instead of 'en_core_web_md', as the latter has many words without vector data. Check!
print("Starting to read the model:", model)
# nlp = spacy.cli.download("en") # Run this for the first time on a new server.
nlp = spacy.load(model) # Use this for subsequent runs
return nlp
def main():
"""
This program parses the results from "AWS Comprehend Custom Entities Recognition" and masks the
entities in the original source document.
Tested with "BrandsRecognizer" in AWS using 'avs4.csv' as source file.
How it works:
This does not use the AWS Comprehend output at all. Instead, uses a custom entity file (e.g. brand_names.txt')
and the document input file to directly compare and mask the words/phrases.
This method is devised as an alternative to AWS Comprehend which has a potential problem of not detecting
all occurrences of the words/phrases in the doc lines. See the doc comment in 'def star_entities' for details.
See the comments in each function for more details.
:return:
"""
global spam_lines
lines = []
# Do a comparison with entity recognition using my own NLP method.
nlp = read_dictionary()
d1 = read_spam_file(spam_lines) # This is the doc with the spam lines.
keys = d1.keys()
j = len(keys)
print("Total Lines:", j)
for urk in keys:
text = d1[urk]
lines.append(text)
# print(f"URK: {urk} - Line: {text}")
nlp, spc = build_entity_ruler(nlp)
par_star_entities(d1, nlp, spc) # Run it as a parallel job.
if __name__ == '__main__':
main()
<file_sep>/AWS_Comprehend/ner_train1.py
#!/usr/bin/env python
import spacy
import random
# TRAIN_DATA = [('what is the price of polo?', {'entities': [(21, 25, 'PrdName')]}),
# ('what is the price of ball?', {'entities': [(21, 25, 'PrdName')]}),
# ('what is the price of jegging?', {'entities': [(21, 28, 'PrdName')]}),
# ('what is the price of t-shirt?', {'entities': [(21, 28, 'PrdName')]}),
# ('what is the price of jeans?', {'entities': [(21, 26, 'PrdName')]}),
# ('what is the price of bat?', {'entities': [(21, 24, 'PrdName')]}),
# ('what is the price of shirt?', {'entities': [(21, 26, 'PrdName')]}),
# ('what is the price of bag?', {'entities': [(21, 24, 'PrdName')]}),
# ('what is the price of cup?', {'entities': [(21, 24, 'PrdName')]}),
# ('what is the price of jug?', {'entities': [(21, 24, 'PrdName')]}),
# ('what is the price of plate?', {'entities': [(21, 26, 'PrdName')]}),
# ('what is the price of glass?', {'entities': [(21, 26, 'PrdName')]}),
# ('what is the price of moniter?', {'entities': [(21, 28, 'PrdName')]}),
# ('what is the price of desktop?', {'entities': [(21, 28, 'PrdName')]}),
# ('what is the price of bottle?', {'entities': [(21, 27, 'PrdName')]}),
# ('what is the price of mouse?', {'entities': [(21, 26, 'PrdName')]}),
# ('what is the price of keyboad?', {'entities': [(21, 28, 'PrdName')]}),
# ('what is the price of chair?', {'entities': [(21, 26, 'PrdName')]}),
# ('what is the price of table?', {'entities': [(21, 26, 'PrdName')]}),
# ('what is the price of watch?', {'entities': [(21, 26, 'PrdName')]})]
TRAIN_DATA = [('Leukopor Snap Spool 1.25cm x 5m', {'entities': [(0, 8, 'PrdName')]}),
('Leukopor Hypoallergenic Paper Tape Snap Spool 2.5cm x 5m', {'entities': [(0, 8, 'PrdName')]}),
('Leukopor Hypoallergenic Paper Tape Snap Spool 5cm x 5m', {'entities': [(0, 8, 'PrdName')]}),
('Leukosilk Tape 1.25cm x 5m', {'entities': [(0, 9, 'PrdName')]}),
('Leukosilk Hypoallergenic Silk Tape 2.5cm x 5m', {'entities': [(0, 9, 'PrdName')]}),
('Leukoflex Plastic Tape 1.25cm x 5m', {'entities': [(0, 9, 'PrdName')]}),
('Leukoflex Plastic Tape 2.5cm', {'entities': [(0, 9, 'PrdName')]}),
('Leukoplast Rigid Tape Tan - 1.25cm x 5m', {'entities': [(0, 10, 'PrdName')]}),
('Leukoplast Rigid Tape Tan - 2.5cm x 5m', {'entities': [(0, 10, 'PrdName')]}),
('Leukoplast Rigid Tape Tan - 5cm x 5m', {'entities': [(0, 10, 'PrdName')]}),
('Leukoplast Waterproof Tape White - 1.25cm x 5m', {'entities': [(0, 10, 'PrdName')]}),
('Leukoplast Waterproof Tape White - 2.5cm x 5m', {'entities': [(0, 10, 'PrdName')]}),
('Leukoplast Waterproof Tape 5cm x 5m - 1 Roll', {'entities': [(0, 10, 'PrdName')]}),
('Leukofix Tape 1.25cm x 5m', {'entities': [(0, 8, 'PrdName')]}),
('Leukofix Tape 2.5cm x 5m', {'entities': [(0, 8, 'PrdName')]}),
('Nivea Men Anti-Irritation Body Shaving Stick - 75mL', {'entities': [(0, 5, 'PrdName')]}),
('Band-Aid Isopropyl Alcohol with Moisturizer 60percent Cleansing Soluti', {'entities': [(0, 8, 'BRAND'), (9, 18, 'BRAND')]}),
('Scholl Party Feet Gel Heel Shield', {'entities': [(0, 6, 'PrdName')]}),
('Simple Hydrating Light Moisturiser - 50ml', {'entities': [(0, 6, 'PrdName')]}),
('Simple Conditioning Eye Makeup Remover - 50ml', {'entities': [(0, 6, 'PrdName')]})]
def train_spacy(data, iterations):
TRAIN_DATA = data
nlp = spacy.blank('en') # create blank Language class
# nlp = spacy.load('en') # create model Language class
# create the built-in pipeline components and add them to the pipeline
# nlp.create_pipe works for built-ins that are registered with spaCy
if 'ner' not in nlp.pipe_names:
ner = nlp.create_pipe('ner')
nlp.add_pipe(ner, last=True)
else:
ner = nlp.get_pipe('ner')
ner.add_label('BLAH')
# add labels
for _, annotations in TRAIN_DATA:
for ent in annotations.get('entities'):
ner.add_label(ent[2])
# get names of other pipes to disable them during training
other_pipes = [pipe for pipe in nlp.pipe_names if pipe != 'ner']
with nlp.disable_pipes(*other_pipes): # only train NER
optimizer = nlp.begin_training()
for itn in range(iterations):
print("Statring iteration " + str(itn))
random.shuffle(TRAIN_DATA)
losses = {}
for text, annotations in TRAIN_DATA:
nlp.update(
[text], # batch of texts
[annotations], # batch of annotations
drop=0.2, # dropout - make it harder to memorise data
sgd=optimizer, # callable to update weights
losses=losses)
print("A.", losses)
return nlp
prdnlp = train_spacy(TRAIN_DATA, 20)
# Save our trained Model
modelfile = input("Enter your Model Name: ")
prdnlp.to_disk(modelfile)
# Test your text
for i in range(0, 100):
test_text = input("Enter your testing text: ")
doc = prdnlp(test_text)
for ent in doc.ents:
print(ent.text, ent.start_char, ent.end_char, ent.label_)
<file_sep>/AWS_Comprehend/get_url_ssl_unverified.py
#!/usr/bin/env python
from urllib.request import Request, urlopen
from bs4 import BeautifulSoup
import ssl
def get_soup_bs4(url):
"""
Get the page content displayed as plain HTML.
:param url: The page URL
:return: soup = The page content
"""
hdr = {'User-Agent': 'Mozilla/5.0'}
req = Request(url, headers=hdr)
context = ssl._create_unverified_context()
page = urlopen(req, context=context)
soup = BeautifulSoup(page, "html.parser")
return soup
def user_comments_1():
url = "http://eagle1023.webgenie.com/AWS_Comprehend/HTML/user_comments_1.html"
soup = get_soup_bs4(url)
# print(soup)
review_list = soup.find_all("li", {"class": "review-list__item"})
print(len(review_list))
for i in review_list:
comments = i.find("div", {"class": "review__content"})
print(comments.text)
def user_comments_2():
url = "http://eagle1023.webgenie.com/AWS_Comprehend/HTML/user_comments_2.html"
soup = get_soup_bs4(url)
tbody = soup.find("tbody", {})
# print(len(tbody))
k = 0
for i in tbody:
k += 1
cid = "fdbk-comment-" + str(k)
# print(cid)
try:
comment = i.find_all("span", {"data-test-id": cid})
line = comment[0].text.strip().replace("A+", "").replace("+", "")
print(line)
except AttributeError:
pass
# break
# comments = i.find("div", {"class": "card__feedback"})
# print(comments.text)
def main():
# user_comments_1()
user_comments_2()
main()
|
0bf513302cf74b11747381ddd4b52168235d0176
|
[
"Python"
] | 6
|
Python
|
asivapra/abs
|
14a056708afe0697f9d537b092b3da6dfd639cf7
|
ff53e3c63a11c31e722df28d201f61d99901892d
|
refs/heads/master
|
<repo_name>jkasap/python_section2<file_sep>/download2-3-3.py
import urllib.request as req
from urllib.parse import urlencode
API = "http://www.mois.go.kr/gpms/view/jsp/rss/rss.jsp"
values = {
'ctxCd': '1001'
}
print('before', values)
params = urlencode(values)
print('after', params)
url = API + "?" + params
#print('url', url)
reqData = req.urlopen(url).read()#.decode('utf-8')
savePath = "c:/mypy/test.html"
with open(savePath,'wb') as saveFile:
saveFile.write(reqData)
<file_sep>/download2-7-2.py
import sys
import io
import urllib.request as req
from bs4 import BeautifulSoup as bs
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
url = "https://finance.naver.com/sise/"
#savepath = "C:/mypy/test.html"
par = req.urlopen(url).read()
#with open(savepath, 'wb') as saveFile:
# saveFile.write(par)
soup = bs(par, 'html.parser')
list = soup.select("#siselist_tab_0 > tr")
for e in list:
if e.find("a") is not None:
print(e.find("a").string)
#siselist_tab_0 > tbody > tr:nth-child(3) > td:nth-child(4) > a
<file_sep>/download2-8-1(bs4, urlparse, 대량다운, 예외처리).py
import sys
import io
import urllib.request as req
import urllib.parse as rep
from bs4 import BeautifulSoup as bs
import os
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
base = "https://search.naver.com/search.naver?where=image&sm=tab_jum&query="
quote = rep.quote_plus("정연")
tem_url = base + quote
#403 금지 해결
url = req.Request(tem_url, headers={'User-Agent' : 'Mozilla/5.0'})
res = req.urlopen(url)
savePate = "c:/mypy/img_down/"
#예외처리
try:
if not (os.path.isdir(savePate)):
os.makedirs(os.path.join(savePate))
except OSError as e:
if e.errno != errno.EEXIST:
print("폴더 만들기 실패!")
raise
soup = bs(res, "html.parser")
img_list = soup.select("div.img_area._item > a.thumb._thumb > img")
for i, img_list in enumerate(img_list,1):
fullFileName = os.path.join(savePate, savePate+str(i)+'.jpg')
req.urlretrieve(img_list["data-source"], fullFileName)
print("다운로드 완료")
<file_sep>/download2-7-3.py
import sys
import io
import urllib.request as req
from bs4 import BeautifulSoup as bs
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
url = "https://www.inflearn.com/"
#savepath = "C:/mypy/test.html"
par = req.urlopen(url).read()
#with open(savepath, 'wb') as saveFile:
# saveFile.write(par)
soup = bs(par, 'html.parser')
recommand = soup.select("ul.grid")[2]
print(recommand)
for i in recommand:
print(i.select_one("h4.block_title > a").string)
<file_sep>/download2-7-1(bs4, enumerate).py
import sys
import io
import urllib.request as req
from bs4 import BeautifulSoup as bs
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
url = "http://finance.daum.net/index.daum?nil_profile=title&nil_src=stock"
savepath = "C:/mypy/test.html"
par = req.urlopen(url).read()
#with open(savepath, 'wb') as saveFile:
# saveFile.write(par)
soup = bs(par, 'html.parser')
list1 = soup.select("#topMyListNo1 > li")
for i, st in enumerate(list1[0:10]):
print(i+1, st.find('a').string,', ',st.find('span').string)
<file_sep>/download2-3-3_hw.py
import urllib.request as req
from urllib.parse import urlencode
API = "http://www.mois.go.kr/gpms/view/jsp/rss/rss.jsp"
values = {'ctxCd':'1001'}
params = urlencode(values)
reqUrl = API + "?" + params
savePath = "c:/mypy/test.txt"
reqData = req.urlopen(reqUrl).read()
with open(savePath,'wb') as saveFile:
saveFile.write(reqData)
<file_sep>/class_5(클래스 변수, 인스턴스 변수).py
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
class NameTest:
total = 0
print(dir())
print("before: ", NameTest.__dict__)
NameTest.total = 1
print("after: ", NameTest.__dict__)
n1 = NameTest()
n2 = NameTest()
print(id(n1), " vs ", id(n2)) # 서로 다른 인스턴스니까 다른 값이 나옴
print(id(n1.total), " vs ", id(n2.total)) #클래스 변수를 공유하기 때문에 같은 값이 나옴
print(n1.__dict__) # n1의 네임스페이스 확인 -> 비었음
print(n2.__dict__) # n2의 네임스페이스 확인 -> 비었음
n1.total = 77 # n1에만 total 값 부여
print(n1.__dict__) # n1의 네임스페이스 확인 -> tatal:77
print(n2.__dict__) # n2의 네임스페이스 확인 -> 비었음
print(n1.total) # n1에는 total값 부여해서 77
print(n2.total) # n2에는 total값이 없으니 클래스의 total값 1
print(id(n1.total), " vs ", id(n2.total))
print(id(n2.total), " vs ", id(NameTest.total)) # n2가 NameTest의 total값 공유하기에 같음
<file_sep>/download2-2_my(urlopen, with-write).py
import urllib.request as ur
imgUrl = "http://ojsfile.ohmynews.com/PHT_IMG_FILE/2017/0811/IE002202038_PHT.jpg"
savePath1 = "C:/mypy/test1.png"
#ur.urlretrieve(imgUrl, savePath1)
f = ur.urlopen(imgUrl).read()
'''
saveFile1 = open(savePath1,'wb')
saveFile1.write(f)
saveFile1.close()
'''
with open(savePath1, 'wb') as saveFile1:
saveFile1.write(f)
print('done')
<file_sep>/download2-7-4(bs4, get).py
import sys
import io
import urllib.request as req
from bs4 import BeautifulSoup as bs
import re
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
url = "https://www.daum.net/"
par = req.urlopen(url).read()
soup = bs(par, "html.parser")
#내가 푼 것
top10 = soup.select("div.rank_cont > span.txt_issue > a")
for i in top10:
if i.get('tabindex') == '-1':
print(i.string, i.get('href'))
#다른 방법
top10 = soup.find_all("a", tabindex="-1")
for i, e in enumerate(top10,1):
print(i,e.string)
<file_sep>/download2-5-2.py
import sys
import io
from bs4 import BeautifulSoup
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
html = """
<html>
<body>
<h1>파이썬 BeautifulSoup 공부</h1>
<p>태그 선택자</p>
<p>css 선택자</p>
</body>
</html>
"""
soup = BeautifulSoup(html, 'html.parser')
#print(soup.prettify())
h1 = soup.html.body.h1
print(h1)
p1 = soup.html.body.p
print(p1)
p2 = p1.next_sibling.next_sibling
print(p2)
p3 = p1.previous_sibling.previous_sibling
print(p3)
print("h1 >> ", h1.string)
print("p >> ", p1.string)
print("p >> ", p2.string)
<file_sep>/download2-3-3_my.py
import urllib.request as ur
url ="https://ssl.pstatic.net/tveta/libs/1205/1205488/b286bbd6dc5769c39dc3_20180720181318205.png"
savepath = "c:/mypy/test.jpg"
data = ur.urlopen(url).read()
with open(savepath,'wb') as sf:
sf.write(data)
<file_sep>/test_emartmall.py
import sys
import io
import urllib.request as req
from bs4 import BeautifulSoup as bs
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
url = "http://emart.ssg.com/category/main.ssg?dispCtgId=0006110000"
savePath = "c:/mypy/test.html"
response = req.urlopen(url).read()
"""
with open(savePath, 'wb') as saveFile:
saveFile.write(response)
"""
soup = bs(response, "html.parser")
list1 = soup.select(".cunit_info > .cunit_md")
list2 = soup.select(".cunit_info > .cunit_price")
print(list1)
print(list2)
#for i in list1:
# print(i.find('a').string)
<file_sep>/YouTube/youtube_downloader.py
import pytube
import os
import subprocess
url = input("다운 받을 영상 url 입력 : ")
print("정보를 읽어오는 중...")
yt = pytube.YouTube(url) #다운 받을 동영상 지정
videos = yt.streams.all()
#다운 받을 퀄리티
for i in range(len(videos)):
print(i, ',', videos[i])
cNum = int(input("어떤 품질로 받을까?(0~21) : ")) #다운 받을 퀄리티 지정
down_dir = "C:/mypy/YouTube" #mp3 변환 때문에 다운 경로 고정함
print("다운로드 중...")
videos[cNum].download(down_dir) #다운로드
option = input("mp3로 변환하시려면 'Y'를 입력 : ") #mp3변환 옵션
if option == 'y':
oriFileName = videos[cNum].default_filename
newFileName = oriFileName + ".mp3"
subprocess.call(['ffmpeg','-i',
os.path.join(down_dir,oriFileName),
os.path.join(down_dir,newFileName)
])
print("완료!")
elif option == 'Y':
oriFileName = videos[cNum].default_filename
newFileName = oriFileName + ".mp3"
subprocess.call(['ffmpeg','-i',
os.path.join(down_dir,oriFileName),
os.path.join(down_dir,newFileName)
])
print("완료!")
else:
print("완료!")
<file_sep>/test.py
import sys
import io
import urllib.request as req
from bs4 import BeautifulSoup as bs
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
targetUrl = "http://www2.ticketmonster.co.kr/mart/category/19260000"
savePath = 'c:/mypy/test.html'
parse = req.urlopen(targetUrl).read()
with open(savePath, 'wb') as saveFile:
saveFile.write(parse)
'''
soup = bs(parse, 'html.parser')
h1 = soup.find_all('em')
print(h1)
'''
<file_sep>/class_3(클래스 self).py
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')
class SelfTest:
def func1():
print("func1 called")
def func2(self):
#print(id(self))
print("func2 called")
f = SelfTest() #인스턴스 화
#print(dir(f))
#print(id(f))
f.func1() #오류 -> 인스턴스에 대한 self 값이 없기 때문에
f.func2() #정상 -> 인스턴스화해서 self를 매개변수로 받아서
print(SelfTest.func1()) #정상 -> 인스턴스화 하지 않고 클래스 이름으로 접근하여 호출
"""
파이썬 클래스에서 메쏘드를 호출하는 방법은 2개
클래스에 이름으로 직접 접근,
인스턴스화해서"""
<file_sep>/download2-3-1(urlparse).py
import urllib.request as req
from urllib.parse import urlparse
url = "http://www.encar.com"
mem = req.urlopen(url)
#print(type(mem))
'''
print("geturl", mem.geturl())
print("status", mem.status)
print("headers", mem.headers)
'''
#print("read", mem.read(50).decode("utf-8"))
print(urlparse("http://www.encar.com"))
|
340f52302c10af6ad844ed55cc3bb55cf648be20
|
[
"Python"
] | 16
|
Python
|
jkasap/python_section2
|
388d9a290f2645c9429a4f130c0363118d5e19ee
|
4d8ef9d74570a41376d60442e945c480e099c033
|
refs/heads/master
|
<repo_name>pikamegan/rookiehacks<file_sep>/src/App.js
import React, {useState} from 'react';
import './App.css';
import About from './components/About';
import Blog from './components/Blog';
import Navigation from './components/Navigation';
import LoginForm from './components/Login';
import SignupForm from './components/Signup';
import Home from './components/Home';
import UserAbout from './components/UserAbout';
import UserAccount from './components/UserAccount';
import UserBlog from './components/UserBlog';
import UserForum from './components/UserForum';
import UserHome from './components/UserHome';
import UserNavigation from './components/UserNavigation';
import {
BrowserRouter as Router,
Switch,
Route
} from "react-router-dom";
import AlertComponent from './components/AlertComponent';
function App() {
const [title , updateTitle] = useState(null);
const [errorMessage , updateErrorMessage] = useState(null);
return (
<Router>
<div className = "App">
<header title={title}/>
<Navigation/>
<Switch>
<Route path="/Home" component={Home}/>
<Route path="/About" component={About}/>
<Route path="/Blog" component={Blog}/>
<Route path="/Signup" render={() => <SignupForm showError={updateErrorMessage} updateTitle={updateTitle}/>}/>
<Route path="/Login" render={() => <LoginForm showError={updateErrorMessage} updateTitle={updateTitle}/>}/>
<Route path="/Home">
<Home/>
</Route>
<Route path="/" component={Home} exact/>
</Switch>
<AlertComponent errorMessage={errorMessage} hideError={updateErrorMessage}/>
</div>
</Router>
);
}
export default App;
<file_sep>/src/components/Navigation.js
import React from 'react';
import { NavLink } from 'react-router-dom';
const Navigation = () => {
return (
<div>
<NavLink to="/Home">Home</NavLink>
<NavLink to="/About">About</NavLink>
<NavLink to="/Blog">Blog</NavLink>
<NavLink to="/Signup">Sign Up</NavLink>
<NavLink to="/Login">Login</NavLink>
</div>
);
}
export default Navigation;
|
30eed5fb67470353e15b3c472931bff469e12848
|
[
"JavaScript"
] | 2
|
JavaScript
|
pikamegan/rookiehacks
|
564e814ffb06b107894262279f76fd14239b9816
|
aebc79384327de2484c3619e63ee3e222b75e6ca
|
refs/heads/master
|
<repo_name>shagindl/parser_uspr_F16<file_sep>/parser_uspr_F16.py
# -*- coding: cp1251 -*-
import re
slog = open('C:\\Users\ShaginDL\Downloads\Лог толкит.txt', 'r', encoding='utf-8').read()
slog = ''.join(re.findall(' \w\w', slog)).replace(' ', '') # оставляем только ASCII hex
slog = ''.join(re.findall('570103.*57', slog)) #
#slog
print(slog)
|
5a2c3f0eff69f339a9fa02d98fca8cd9bb6f0d80
|
[
"Python"
] | 1
|
Python
|
shagindl/parser_uspr_F16
|
08a7d5314e31fc0f5ef1e4269bcbd68bd6473212
|
e3a01dcd75eeec1bc70ae5c4c3e0bfe312cb6100
|
refs/heads/master
|
<repo_name>davidbernardo/CQProject<file_sep>/API/API/Global.asax.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace API
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
// The only package that needs to be defined, the rest will be imported by CDN
BundleTable.Bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/site.css"));
}
}
}
|
442a5fab0b2e2063a873ef76df92a0807bd358a9
|
[
"C#"
] | 1
|
C#
|
davidbernardo/CQProject
|
a601f45e155f68e3fa846a97829620cdbc3cc722
|
e185f171c8489abfc2a73a94a732b7e5e1da0d54
|
refs/heads/master
|
<repo_name>HiThisIsNotCodeRepo/ProjectGoLiveRun4FrontEnd<file_sep>/src/doc/git/git.md
# Git
## Common Script
`git pull <remote addr>`
- To pull repo from remote
`git merge dev`
- To merge with branch
`git reset HEAD .`
`git checkout .`
- To restore files accidently deleted
`git reset HEAD .`
`git clean -df`
- To delete files accidently added
`git reset HEAD .`
`git checkout .`
- To bring the files to initial condition
<file_sep>/src/app/paotui/component/new-task/change-expected-rate-dialog.component.ts
import {Component, Inject} from '@angular/core';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material/dialog';
import {} from '../search-task/list.component';
import {FormGroup} from '@angular/forms';
import {DialogData} from './new-task.component';
@Component({
selector: 'change-expected-rate-dialog',
templateUrl: './change-expected-rate-dialog.html',
styles: [
''
]
})
export class ChangeExpectedRateDialogComponent {
horizontalStepperForm: FormGroup;
public dataStr;
constructor(
public dialogRef: MatDialogRef<ChangeExpectedRateDialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: DialogData) {
const date = new Date();
const Y = date.getFullYear() + '-';
const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
const D = date.getDate() + '';
const newHour = date.getHours() + 1;
const h = (newHour < 10 ? '0' + newHour : newHour) + ':';
const m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
const dataStr = Y + M + D + 'T' + h + m + '00';
this.dataStr = dataStr;
}
onNoClick(): void {
this.dialogRef.close();
}
}
<file_sep>/src/app/paotui/app.const.ts
export const BASE_URL = 'https://paotui.sg/api/v1';
<file_sep>/src/app/paotui/paotui-interceptor.ts
import {Injectable} from '@angular/core';
import {
HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';
import {Observable} from 'rxjs';
import {PaoTuiAuthService} from './paotui-auth.service';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private _patotuiAuthService: PaoTuiAuthService,) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (!req.url.includes('auth')) {
console.log(`intercept work,${req.url}`);
const authReq = req.clone({headers: req.headers.set('Authorization', this._patotuiAuthService.myToken)});
return next.handle(authReq);
} else {
return next.handle(req);
}
}
}
<file_sep>/README.md
# Go School Project Go Live Run 4
## Project Title: Pao Tui(跑腿)
**Front End Interface**
>Author: <NAME>
>
> Email:<EMAIL>
## Project Description
Due to Covid 19, an ad hoc job posting platform has emerged to provide more job opportunities, anyone can post their urgent task with personalised requirements ,for instance deliver food, buy necessity, send documents etc, it also needs to include max acceptable rate and expected delivery time. Anyone who is interested in making pocket money can bid for the job with their minimum acceptable rate and finish time. Among those service providers, job posters should pick one. Once a job is assigned, the service provider should do their best to complete the task before the deadline to avoid any penalty.
## Front Ende Template Selection
To expediate front end developement, I have choosen a [template](https://themeforest.net/item/fuse-angularjs-material-design-admin-template/12931855?gclid=CjwKCAjwq7aGBhADEiwA6uGZpx14Dv86Apxo_47dPNLqdKC3U5N7gDGr9eBmZ-sn1-lpdgRpDAkTvhoCTmUQAvD_BwE) which provide UI structure layout and material components. So I can more focus on the logic development.
## File Directory
As project progresses now slowly merge file
```
|--src
| |--app
| ...
| |-- paotui
| |-- component # This folder contains main component of the application
| |-- app.const.ts # Some constant
| |-- paotui-auth.service.ts # Singleton service store user data
| |-- paotui-guard.guard.ts # Route guard
| |-- date.pipe.ts # common pipe
| |-- paotui.module.ts # module to export pipe etc
| ...
```
## Installation Note
Now available at [Ansible deployment](https://github.com/qinchenfeng/AnsibleDeployProjectGoLiveRun4)
## New features
### Upload user avatar
Using https://cloudinary.com/

## Core features
1. User id and password login
2. Page routing and guard, it based on token issued by back end.
3. Token storage in the singleton service.
## Demo
### HTTPS

### Login

### Sign Up

### Add Task

### Bid Task

### Edit Task Expected Rate

### Delete Task

### Accept Bid Task

### View Task History

## Main Tech Stack
**Angular**,**HTML**,**CSS**,**Javascript**,**Go**,**MySQL**,**Docker**,**Containerd**,**K8s**
## Other
### Git
[git update](https://github.com/qinchenfeng/ProjectGoLiveRun4FrontEnd/blob/dev/src/doc/git/git.md)
### Angular
[angular update](https://github.com/qinchenfeng/ProjectGoLiveRun4FrontEnd/blob/dev/src/doc/angular/angular.md)
### Log
1. [20210619](https://github.com/qinchenfeng/ProjectGoLiveRun4FrontEnd/blob/dev/src/doc/log/log_20210619.md)
2. [20210620](https://github.com/qinchenfeng/ProjectGoLiveRun4FrontEnd/blob/dev/src/doc/log/log_20210620.md)
<file_sep>/src/app/mock-api/dashboards/project/data.ts
/* eslint-disable */
import * as moment from 'moment';
export const project = {
githubIssues: {
overview: {
'this-week': {
'new-issues': 214,
'closed-issues': 75,
'fixed': 3,
'wont-fix': 4,
're-opened': 8,
'needs-triage': 6
},
'last-week': {
'new-issues': 197,
'closed-issues': 72,
'fixed': 6,
'wont-fix': 11,
're-opened': 6,
'needs-triage': 5
}
},
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
series: {
'this-week': [
{
name: 'Task Spend',
type: 'line',
data: [42, 28, 43, 34, 20, 25, 22]
},
{
name: 'Task Qty',
type: 'column',
data: [11, 10, 8, 11, 8, 10, 17]
}
],
'last-week': [
{
name: 'Task Spend',
type: 'line',
data: [37, 32, 39, 27, 18, 24, 20]
},
{
name: 'Task Qty',
type: 'column',
data: [9, 8, 10, 12, 7, 11, 15]
}
]
}
},
taskDistribution: {
overview: {
'this-week': {
'new': 594,
'completed': 287
},
'last-week': {
'new': 526,
'completed': 260
}
},
labels: ['API', 'Backend', 'Frontend', 'Issues'],
series: {
'this-week': [15, 20, 38, 27],
'last-week': [19, 16, 42, 23]
}
},
budgetDistribution: {
categories: ['Buy Necessity', 'Food Delivery', 'Send Document', 'Other'],
series: [
{
name: 'Budget',
data: [12, 20, 28, 15]
}
]
},
weeklyExpenses: {
amount: 17663,
labels: [
moment().subtract(2, 'days').format('DD MMM'),
moment().subtract(1, 'days').format('DD MMM')
],
series: [
{
name: 'Expenses',
data: [4412, 4345]
}
]
},
monthlyExpenses: {
amount: 54663,
labels: [
moment().subtract(5, 'days').format('DD MMM'),
moment().subtract(4, 'days').format('DD MMM'),
moment().subtract(3, 'days').format('DD MMM'),
moment().subtract(2, 'days').format('DD MMM'),
moment().subtract(1, 'days').format('DD MMM')
],
series: [
{
name: 'Expenses',
data: [15521, 15519, 15522, 15521, 15500]
}
]
},
yearlyExpenses: {
amount: 648813,
labels: [
moment().subtract(10, 'days').format('DD MMM'),
moment().subtract(9, 'days').format('DD MMM'),
moment().subtract(8, 'days').format('DD MMM'),
moment().subtract(7, 'days').format('DD MMM'),
moment().subtract(6, 'days').format('DD MMM'),
moment().subtract(5, 'days').format('DD MMM'),
moment().subtract(4, 'days').format('DD MMM'),
moment().subtract(3, 'days').format('DD MMM'),
moment().subtract(2, 'days').format('DD MMM'),
moment().subtract(1, 'days').format('DD MMM')
],
series: [
{
name: 'Expenses',
data: [45891, 45801, 45834, 45843, 45800, 45900, 45814, 45856, 45910, 45849]
}
]
},
budgetDetails: {
columns: ['type', 'total', 'expensesAmount', 'expensesPercentage', 'remainingAmount', 'remainingPercentage'],
rows: [
{
id: 1,
type: 'Buy Necessity',
total: 14880,
expensesAmount: 14000,
expensesPercentage: 94.08,
remainingAmount: 880,
remainingPercentage: 5.92
},
{
id: 2,
type: 'Food Delivery',
total: 21080,
expensesAmount: 17240.34,
expensesPercentage: 81.78,
remainingAmount: 3839.66,
remainingPercentage: 18.22
},
{
id: 3,
type: 'Send Document',
total: 34720,
expensesAmount: 3518,
expensesPercentage: 10.13,
remainingAmount: 31202,
remainingPercentage: 89.87
},
{
id: 4,
type: 'Other',
total: 18600,
expensesAmount: 0,
expensesPercentage: 0,
remainingAmount: 18600,
remainingPercentage: 100
},
]
},
teamMembers: [
{
id: '2bfa2be5-7688-48d5-b5ac-dc0d9ac97f14',
avatar: 'assets/images/avatars/female-10.jpg',
name: '<NAME>',
email: '<EMAIL>',
phone: '+1-943-511-2203',
title: 'Project Director'
},
{
id: '77a4383b-b5a5-4943-bc46-04c3431d1566',
avatar: 'assets/images/avatars/male-19.jpg',
name: '<NAME>',
email: '<EMAIL>',
phone: '+1-814-498-3701',
title: 'Senior Developer'
},
{
id: '8bb0f597-673a-47ca-8c77-2f83219cb9af',
avatar: 'assets/images/avatars/male-14.jpg',
name: '<NAME>',
email: '<EMAIL>',
phone: '+1-968-547-2111',
title: 'Senior Developer'
},
{
id: 'c318e31f-1d74-49c5-8dae-2bc5805e2fdb',
avatar: 'assets/images/avatars/male-01.jpg',
name: '<NAME>',
email: '<EMAIL>',
phone: '+1-902-500-2668',
title: 'Junior Developer'
},
{
id: '0a8bc517-631a-4a93-aacc-000fa2e8294c',
avatar: 'assets/images/avatars/female-20.jpg',
name: '<NAME>',
email: '<EMAIL>',
phone: '+1-838-562-2769',
title: 'Lead Designer'
},
{
id: 'a4c9945a-757b-40b0-8942-d20e0543cabd',
avatar: 'assets/images/avatars/female-01.jpg',
name: '<NAME>',
email: '<EMAIL>',
phone: '+1-939-555-3054',
title: 'Designer'
},
{
id: 'b8258ccf-48b5-46a2-9c95-e0bd7580c645',
avatar: 'assets/images/avatars/female-02.jpg',
name: '<NAME>',
email: '<EMAIL>',
phone: '+1-933-464-2431',
title: 'Designer'
},
{
id: 'f004ea79-98fc-436c-9ba5-6cfe32fe583d',
avatar: 'assets/images/avatars/male-02.jpg',
name: '<NAME>',
email: '<EMAIL>',
phone: '+1-822-531-2600',
title: 'Marketing Manager'
},
{
id: '8b69fe2d-d7cc-4a3d-983d-559173e37d37',
avatar: 'assets/images/avatars/female-03.jpg',
name: '<NAME>',
email: '<EMAIL>',
phone: '+1-990-457-2106',
title: 'Consultant'
}
]
};
<file_sep>/src/app/paotui/component/sign-up/sign-up.component.ts
import {Component, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {FormBuilder, FormGroup, NgForm, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {fuseAnimations} from '@fuse/animations';
import {FuseAlertType} from '@fuse/components/alert';
import {AuthService} from 'app/core/auth/auth.service';
import {MatSnackBar} from '@angular/material/snack-bar';
import {BASE_URL} from '../../app.const';
import {HttpClient} from '@angular/common/http';
interface RegisterResponse {
status: string;
msg: string;
}
@Component({
selector: 'auth-sign-up',
templateUrl: './sign-up.component.html',
encapsulation: ViewEncapsulation.None,
animations: fuseAnimations
})
export class AuthSignUpComponent implements OnInit {
@ViewChild('signUpNgForm') signUpNgForm: NgForm;
alert: { type: FuseAlertType; message: string } = {
type: 'success',
message: ''
};
signUpForm: FormGroup;
showAlert: boolean = false;
/**
* Constructor
*/
constructor(
private _authService: AuthService,
private _formBuilder: FormBuilder,
private _router: Router,
private _snackBar: MatSnackBar,
private _httpClient: HttpClient,
) {
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void {
// Create the form
this.signUpForm = this._formBuilder.group({
name: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
password: ['', Validators.required],
}
);
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Sign up
*/
signUp(): void {
// Do nothing if the form is invalid
if (this.signUpForm.invalid) {
return;
}
// Disable the form
// this.signUpForm.disable();
// Hide the alert
this.showAlert = false;
console.log(`sign-up name:${this.signUpForm.get('name').value}, sign-up email:${this.signUpForm.get('email').value}
sign-up password:${this.signUpForm.get('password').value}`);
// register
this._httpClient.post<RegisterResponse>(`${BASE_URL}/users/user`, {
name: this.signUpForm.get('name').value,
email: this.signUpForm.get('email').value,
password: this.signUpForm.get('password').value
}).subscribe((data) => {
console.log(data);
if (data.status === 'error') {
this.openSnackBar('User Register Failed');
} else {
this.openSnackBar('User Register Success');
this._router.navigate(['/sign-in']);
}
});
}
openSnackBar(message: string): void {
this._snackBar.open(message, 'close', {
duration: 2000,
panelClass: ['my-snack-bar']
});
}
}
<file_sep>/src/app/paotui/paotui-auth.service.ts
import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class PaoTuiAuthService {
public myToken = '';
public myId = '';
public email = '';
public lastLogin = '';
public avatarUrl = '';
public clearAll(): void {
this.myToken = '';
this.myId = '';
this.email = '';
this.lastLogin = '';
this.avatarUrl = '';
}
}
<file_sep>/src/app/paotui/component/new-task/new-task.module.ts
import { NgModule } from '@angular/core';
import { Route, RouterModule } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatIconModule } from '@angular/material/icon';
import { MatInputModule } from '@angular/material/input';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { MatStepperModule } from '@angular/material/stepper';
import { SharedModule } from 'app/shared/shared.module';
import {FormsWizardsComponent} from './new-task.component';
import {MatTabsModule} from '@angular/material/tabs';
import {MatExpansionModule} from '@angular/material/expansion';
import {MatDividerModule} from '@angular/material/divider';
import {MatListModule} from '@angular/material/list';
import {PaotuiCommonModule} from '../../paotui.module';
import {ChangeExpectedRateDialogComponent} from './change-expected-rate-dialog.component';
import {MatDialogModule} from '@angular/material/dialog';
import {MatSnackBarModule} from '@angular/material/snack-bar';
export const routes: Route[] = [
{
path : '',
component: FormsWizardsComponent
}
];
@NgModule({
declarations: [
FormsWizardsComponent,
ChangeExpectedRateDialogComponent,
],
imports: [
RouterModule.forChild(routes),
MatButtonModule,
MatCheckboxModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatRadioModule,
MatSelectModule,
MatStepperModule,
SharedModule,
MatTabsModule,
MatExpansionModule,
MatDividerModule,
MatListModule,
PaotuiCommonModule,
MatDialogModule,
MatSnackBarModule,
]
})
export class FormsWizardsModule
{
}
<file_sep>/src/app/mock-api/common/navigation/data.ts
/* tslint:disable:max-line-length */
import {FuseNavigationItem} from '@fuse/components/navigation';
export const defaultNavigation: FuseNavigationItem[] = [
{
id: 'search-task',
title: 'Browse Task',
subtitle: 'Custom made application designs',
type: 'basic',
icon: 'heroicons_outline:search',
link: '/browse-search-task',
},
{
id: 'post-task',
title: 'Issue Task',
type: 'basic',
icon: 'heroicons_outline:plus-circle',
link: '/issue-search-task',
}
];
export const horizontalNavigation: FuseNavigationItem[] = [
{
id: 'search-task',
title: 'Browse Task',
type: 'basic',
icon: 'heroicons_outline:search',
link: '/browse-search-task'
},
{
id: 'post-task',
title: 'Issue Task',
type: 'basic',
icon: 'heroicons_outline:plus-circle',
link: '/issue-search-task',
},
];
<file_sep>/src/app/paotui/component/search-task/browse-task.routing.ts
import {Route} from '@angular/router';
import {TaskListComponent} from 'app/paotui/component/search-task/list.component';
export const academyRoutes: Route[] = [
{
path: '',
component: TaskListComponent,
children: [
{
path: '',
pathMatch: 'full',
component: TaskListComponent,
},
]
}
];
<file_sep>/src/app/paotui/component/new-task/new-task.component.ts
import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {AbstractControl, FormBuilder, FormGroup, ValidationErrors, ValidatorFn, Validators} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {BASE_URL} from '../../app.const';
import {PaoTuiAuthService} from '../../paotui-auth.service';
import {MatDialog} from '@angular/material/dialog';
import {ChangeExpectedRateDialogComponent} from './change-expected-rate-dialog.component';
import {MatSnackBar} from '@angular/material/snack-bar';
import {Router} from '@angular/router';
interface NewTaskResponse {
status: string;
msg: string;
}
interface OnGoingNewTaskResponse {
tasks: Task[];
}
export interface DialogData {
animal: string;
rate: number;
}
interface Task {
no: number;
taskId: string;
taskTitle: string;
taskDescription: string;
taskCategoryId: number;
taskFrom: string;
taskTo: string;
taskCreate: string;
taskStart: string;
taskComplete: string;
taskDuration: number;
taskStep: number;
taskOwnerId: string;
taskOwnerRate: number;
taskDeliverId: string;
taskDeliverRate: number;
bidders: Bidder[];
}
interface Bidder {
taskBidderId: string;
taskBidderRate: number;
}
interface UpdateExpectedRateResponse {
status: string;
msg: string;
}
interface DeleteResponse {
status: string;
msg: string;
}
@Component({
selector: 'forms-wizards',
templateUrl: './new-task.component.html',
encapsulation: ViewEncapsulation.None,
styleUrls: ['./new-task.component.css']
})
export class FormsWizardsComponent implements OnInit {
horizontalStepperForm: FormGroup;
public dataStr;
public tasks: Task[];
rate: number;
bidderIdChoice: string;
/**
* Constructor
*/
constructor(private _formBuilder: FormBuilder, private _httpClient: HttpClient, private _patotuiAuthService: PaoTuiAuthService, public dialog: MatDialog, private _snackBar: MatSnackBar, private _router: Router,) {
}
public tabChange(event: any): void {
if (event === 1) {
this._httpClient.get<OnGoingNewTaskResponse>(`${BASE_URL}/tasks/${this._patotuiAuthService.myId}?option=on-going&category=only-me&identity=user`).subscribe(
(data) => {
console.log(data);
this.tasks = data.tasks;
}
);
}
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void {
// Horizontal stepper form
this.horizontalStepperForm = this._formBuilder.group({
step1: this._formBuilder.group({
taskTitle: ['', [Validators.required]],
from: ['', Validators.required],
to: ['', Validators.required],
category: ['', Validators.required],
expectedRate: ['', Validators.required],
}),
step2: this._formBuilder.group({
start: ['', [Validators.required, timeValidator()]],
duration: ['', Validators.required],
description: ['', Validators.required],
}),
});
const date = new Date();
const Y = date.getFullYear() + '-';
const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
const D = date.getDate() + '';
const newHour = date.getHours() + 1;
const h = (newHour < 10 ? '0' + newHour : newHour) + ':';
const m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
const dataStr = Y + M + D + 'T' + h + m + '00';
this.dataStr = dataStr;
this.horizontalStepperForm.get('step2.start').setValue(this.dataStr);
}
sendData(): void {
const taskTitle = this.horizontalStepperForm.get('step1.taskTitle').value;
const from = this.horizontalStepperForm.get('step1.from').value;
const to = this.horizontalStepperForm.get('step1.to').value;
const category = this.horizontalStepperForm.get('step1.category').value;
const expectedRate = this.horizontalStepperForm.get('step1.expectedRate').value;
const duration = this.horizontalStepperForm.get('step2.duration').value;
const start = this.horizontalStepperForm.get('step2.start').value;
const description = this.horizontalStepperForm.get('step2.description').value;
console.log(`taskTitle:${taskTitle} type: ${typeof taskTitle},from:${from} type: ${typeof from},to:${to} type: ${typeof to},category:${category}
type: ${typeof category},expectedRate:${expectedRate} type: ${typeof expectedRate},duration:${duration} type: ${typeof duration},start:${start} type: ${typeof start}`);
this._httpClient.post<NewTaskResponse>(`${BASE_URL}/tasks/task`, {
taskOwnerId: `${this._patotuiAuthService.myId}`,
taskTitle: taskTitle,
from: from,
to: to,
category: Number(category),
expectedRate: expectedRate,
duration: duration,
start: start,
description: description,
}).subscribe((data) => {
console.log(data);
if (data.status === 'success') {
this.openSnackBar('Add successful');
}
})
;
}
trackByFn(index: number, item: any): any {
return item.id || index;
}
updateExpectedRate(taskId: string): void {
const dialogRef = this.dialog.open(ChangeExpectedRateDialogComponent, {
width: '400px',
data: {rate: this.rate}
});
dialogRef.afterClosed().subscribe((result) => {
if (result !== undefined) {
console.log(`The new rate is ${result}`);
this._httpClient.put<UpdateExpectedRateResponse>(`${BASE_URL}/tasks/task/${taskId}?option=update-expected-rate`, {
rate: result,
}).subscribe((data) => {
console.log(data);
if (data.status === 'success') {
this.openSnackBar('Update successful');
this._httpClient.get<OnGoingNewTaskResponse>(`${BASE_URL}/tasks/${this._patotuiAuthService.myId}?option=on-going&category=only-me&identity=user`).subscribe(
(response) => {
console.log(response);
this.tasks = response.tasks;
}
);
}
});
}
});
}
confirmDeliver(taskId: string, deliverId: string): void {
const deliverID = deliverId.split('|')[0];
const deliverRate = deliverId.split('|')[1];
console.log(`confirm deliver taskId: ${taskId},deliverId:${deliverID},deliverRate:${deliverRate}`);
this._httpClient.put<UpdateExpectedRateResponse>(`${BASE_URL}/tasks/task/${taskId}?option=confirm-task-deliver`, {
deliverRate: Number(deliverRate),
deliverId: deliverID,
}).subscribe((data) => {
console.log(data);
if (data.status === 'success') {
this.openSnackBar('Confirm successful');
this._httpClient.get<OnGoingNewTaskResponse>(`${BASE_URL}/tasks/${this._patotuiAuthService.myId}?option=on-going&category=only-me&identity=user`).subscribe(
(response) => {
console.log(response);
this.tasks = response.tasks;
}
);
}
});
}
deleteTask(taskId: string): void {
console.log(`confirm delete taskID: ${taskId}`);
this._httpClient.delete<DeleteResponse>(`${BASE_URL}/tasks/task/${taskId}?option=delete`).subscribe((data) => {
console.log(data);
if (data.status === 'success') {
this.openSnackBar('Delete successful');
this._httpClient.get<OnGoingNewTaskResponse>(`${BASE_URL}/tasks/${this._patotuiAuthService.myId}?option=on-going&category=only-me&identity=user`).subscribe(
(response) => {
console.log(response);
this.tasks = response.tasks;
}
);
} else if (data.status === 'error') {
this.openSnackBar('Delete fail');
}
});
}
openSnackBar(message: string): void {
this._snackBar.open(message, 'close', {
duration: 2000,
panelClass: ['my-snack-bar']
});
}
}
export function timeValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const inputDate = new Date(control.value);
const currentDate = new Date();
const flag = inputDate < currentDate;
return flag ? {invalidTime: {value: control.value}} : null;
};
}
<file_sep>/src/app/layout/layouts/horizontal/material/navigation.data.ts
import {FuseNavigationItem} from '@fuse/components/navigation';
export interface Navigation {
default: FuseNavigationItem[];
horizontal: FuseNavigationItem[];
}
export const naviData: Navigation = {
default:
[
{
id: 'search-task',
title: 'Search Task',
type: 'basic',
icon: 'heroicons_outline:search',
link: '/search-task',
},
{
id: 'post-task',
title: 'New Task',
type: 'basic',
icon: 'heroicons_outline:plus-circle',
link: '/new-task',
},
{
id: 'my-info',
title: 'My Info',
type: 'basic',
icon: 'heroicons_outline:home',
link: '/my-info',
}
],
horizontal:
[
{
id: 'search-task',
title: 'Search Task',
type: 'basic',
icon: 'heroicons_outline:search',
link: '/search-task'
},
{
id: 'post-task',
title: 'New Task',
type: 'basic',
icon: 'heroicons_outline:plus-circle',
link: '/new-task',
},
{
id: 'my-info',
title: 'My Info',
type: 'basic',
icon: 'heroicons_outline:home',
link: '/my-info',
}
]
};
<file_sep>/src/app/paotui/component/search-task/browse-task.module.ts
import {NgModule} from '@angular/core';
import {RouterModule} from '@angular/router';
import {MatButtonModule} from '@angular/material/button';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatIconModule} from '@angular/material/icon';
import {MatInputModule} from '@angular/material/input';
import {MatProgressBarModule} from '@angular/material/progress-bar';
import {MatSelectModule} from '@angular/material/select';
import {MatSidenavModule} from '@angular/material/sidenav';
import {MatSlideToggleModule} from '@angular/material/slide-toggle';
import {MatTooltipModule} from '@angular/material/tooltip';
import {FuseFindByKeyPipeModule} from '@fuse/pipes/find-by-key';
import {SharedModule} from 'app/shared/shared.module';
import {academyRoutes} from 'app/paotui/component/search-task/browse-task.routing';
import {
TaskListComponent
} from 'app/paotui/component/search-task/list.component';
import {MatTabsModule} from '@angular/material/tabs';
import {MatPaginatorModule} from '@angular/material/paginator';
import {FuseCardModule} from '@fuse/components/card';
import {MatDialogModule} from '@angular/material/dialog';
import {PaotuiCommonModule} from '../../paotui.module';
import {ExpectedRateDialogComponent} from './expected-rate-dialog.component';
@NgModule({
declarations: [
TaskListComponent,
ExpectedRateDialogComponent,
],
imports: [
RouterModule.forChild(academyRoutes),
MatButtonModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatProgressBarModule,
MatSelectModule,
MatSidenavModule,
MatSlideToggleModule,
MatTooltipModule,
FuseFindByKeyPipeModule,
SharedModule,
MatTabsModule,
// add on
MatPaginatorModule,
FuseCardModule,
MatDialogModule,
PaotuiCommonModule,
]
})
export class BrowseTaskModule {
}
<file_sep>/src/app/mock-api/index.ts
import { TaskMockApi } from 'app/mock-api/apps/browse-task/api';
import { ActivitiesMockApi } from 'app/mock-api/pages/activities/api';
import { AnalyticsMockApi } from 'app/mock-api/dashboards/analytics/api';
import { AuthMockApi } from 'app/mock-api/common/auth/api';
import { IconsMockApi } from 'app/mock-api/ui/icons/api';
import { MessagesMockApi } from 'app/mock-api/common/messages/api';
import { NavigationMockApi } from 'app/mock-api/common/navigation/api';
import { NotificationsMockApi } from 'app/mock-api/common/notifications/api';
import { ProjectMockApi } from 'app/mock-api/dashboards/project/api';
import { SearchMockApi } from 'app/mock-api/common/search/api';
import { ShortcutsMockApi } from 'app/mock-api/common/shortcuts/api';
import { TasksMockApi } from 'app/mock-api/apps/post-task/api';
import { UserMockApi } from 'app/mock-api/common/user/api';
export const mockApiServices = [
TaskMockApi,
ActivitiesMockApi,
AnalyticsMockApi,
AuthMockApi,
IconsMockApi,
MessagesMockApi,
NavigationMockApi,
NotificationsMockApi,
ProjectMockApi,
SearchMockApi,
ShortcutsMockApi,
TasksMockApi,
UserMockApi
];
<file_sep>/src/doc/log/log_20210619.md
## Update on 2021/6/19
- Work on the task search feature.
### How to make paginator work
The paginator feature is with `<mat-paginator>`tag,you can find the reference [here](https://material.angular.io/components/paginator/overview).
It has a few propertis to suit your need. Here I use `length`,`pageSize`,`pageSizeOptions`, and event `page`.
```
<mat-paginator
#paginatorObj
[length]="b4PaginatorFilterCourseSize"
[pageSize]="pageSize"
[pageSizeOptions]="pageSizeOptions"
(page)="handlePageEvent($event)">
>
</mat-paginator>
```
As we can see, the search page already has some input form.

That means every time when we set new value or update value the list needs to be updated. This can be achieved by RxJs operators `combineLatest`.
The paginator control needs some attention as when other inputs change the final list may change as well, to avoid any page index over the limit I have set the page number to 0 here.
```
if (this.initComplete !== hideCompleted)
...
if (this.initCategory !== categorySlug && !flag)
...
if (this.initQuery !== query && !flag)
...
```
<file_sep>/src/doc/deployment/docker.sh
# 下面命令在project_directory/src/doc/deployment下执行
# 制作原始nginx镜像
docker run --name my-nginx -p 80:80 -d nginx:latest
# 拷贝项目生产代码到nginx容器/my_app目录
docker cp ../../../dist/paotui my-nginx:/my_app
# 拷贝当前目录的配置文件到容器当中
docker cp default.http.conf my-nginx:/etc/nginx/conf.d/default.conf
# 重启容器
docker restart my-nginx
# 将含前端网页的容器重新制作为镜像
# b52947add223
docker commit b52947add223 magicpowerworld/paotui_front_end:20210718
# 制作完镜像之后推送
docker push magicpowerworld/paotui_front_end:20210718
# 生产环境下部署镜像
docker run --name paotui_front_end -p 443:443 -d magicpowerworld/paotui_front_end:20210710
# 进入docker将配置文件复制到本地
docker exec -it my-nginx bash
docker cp my-nginx:/etc/nginx/conf.d/default.conf .
<file_sep>/src/app/paotui/date.pipe.ts
import {Pipe, PipeTransform} from '@angular/core';
/**
* Finds an object from given source using the given key - value pairs
*/
@Pipe({
name: 'convFormat',
pure: false
})
export class ConvFormatPipe implements PipeTransform {
constructor() {
}
transform(value: string): any {
if (value === null) {
return '';
}
const splitArr = value.split('T');
const date = splitArr[0];
const subSplitArr = splitArr[1].split('+');
const time = subSplitArr[0];
return date + ' ' + time;
}
}
<file_sep>/src/app/paotui/component/my-info/chartOptions.ts
import {
ApexAxisChartSeries,
ApexChart, ApexDataLabels,
ApexFill, ApexMarkers, ApexPlotOptions, ApexStroke,
ApexTitleSubtitle,
ApexTooltip,
ApexXAxis,
ApexYAxis
} from 'ng-apexcharts';
export type ChartOptions = {
series: ApexAxisChartSeries;
chart: ApexChart;
xaxis: ApexXAxis;
yaxis: ApexYAxis | ApexYAxis[];
title: ApexTitleSubtitle;
labels: string[];
stroke: any; // ApexStroke;
dataLabels: any; // ApexDataLabels;
fill: ApexFill;
tooltip: ApexTooltip;
};
export type RadarChartOptions = {
series: ApexAxisChartSeries;
chart: ApexChart;
title: ApexTitleSubtitle;
stroke: ApexStroke;
dataLabels: ApexDataLabels;
tooltip: any;
plotOptions: ApexPlotOptions;
fill: ApexFill;
colors: string[];
yaxis: ApexYAxis;
markers: ApexMarkers;
xaxis: ApexXAxis;
};
export type PastTwoDaysEarning = {
chart: ApexChart;
colors: string[];
series: ApexAxisChartSeries;
stroke: ApexStroke;
tooltip: any;
xaxis: ApexXAxis;
yaxis: ApexYAxis;
};
export type PastFiveDaysEarning = {
chart: ApexChart;
colors: string[];
series: ApexAxisChartSeries;
stroke: ApexStroke;
tooltip: any;
xaxis: ApexXAxis;
yaxis: ApexYAxis;
};
export type PastTenDaysEarning = {
chart: ApexChart;
colors: string[];
series: ApexAxisChartSeries;
stroke: ApexStroke;
tooltip: any;
xaxis: ApexXAxis;
yaxis: ApexYAxis;
};
<file_sep>/src/app/paotui/paotui.module.ts
import {NgModule} from '@angular/core';
import {ConvFormatPipe} from './date.pipe';
@NgModule({
imports: [
// dep modules
],
declarations: [
ConvFormatPipe
],
exports: [
ConvFormatPipe
]
})
export class PaotuiCommonModule {}
<file_sep>/src/app/app.routing.ts
import {Route} from '@angular/router';
import {LayoutComponent} from 'app/layout/layout.component';
import {PaotuiGuard} from './paotui/paotui-guard.guard';
// @formatter:off
// tslint:disable:max-line-length
export const appRoutes: Route[] = [
{path: '', pathMatch: 'full', redirectTo: 'sign-in'},
{
path: '',
component: LayoutComponent,
data: {
layout: 'empty'
},
children: [
{
path: 'sign-in',
loadChildren: () => import('app/paotui/component/sign-in/sign-in.module').then(m => m.AuthSignInModule)
},
{
path: 'sign-up',
loadChildren: () => import('app/paotui/component/sign-up/sign-up.module').then(m => m.AuthSignUpModule)
}
]
},
// Auth routes for authenticated users
{
path: '',
component: LayoutComponent,
data: {
layout: 'empty'
},
children: [
{
path: 'sign-out',
loadChildren: () => import('app/paotui/component/sign-out/sign-out.module').then(m => m.AuthSignOutModule)
},
]
},
// Admin routes
{
path: '',
component: LayoutComponent,
canActivate: [PaotuiGuard],
canActivateChild: [PaotuiGuard],
children: [
// Apps
{
path: 'my-info',
loadChildren: () => import('app/paotui/component/my-info/my-info.module').then(m => m.MyInfoModule)
},
{
path: 'search-task',
loadChildren: () => import('app/paotui/component/search-task/browse-task.module').then(m => m.BrowseTaskModule)
},
{
path: 'new-task',
loadChildren: () => import('app/paotui/component/new-task/new-task.module').then(m => m.FormsWizardsModule)
},
]
},
{
path: '**',
pathMatch: 'full',
redirectTo: 'sign-in'
}
];
<file_sep>/src/app/paotui/component/sign-in/sign-in.component.ts
import {Component, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {FormBuilder, FormGroup, NgForm, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {fuseAnimations} from '@fuse/animations';
import {FuseAlertType} from '@fuse/components/alert';
import {HttpClient} from '@angular/common/http';
import {PaoTuiAuthService} from '../../paotui-auth.service';
import {BASE_URL} from '../../app.const';
import {MatSnackBar} from '@angular/material/snack-bar';
interface LoginResponse {
status: string;
msg: string;
token: string;
userId: string;
lastLogin: string;
email: string;
avatarUrl: string;
}
@Component({
selector: 'auth-sign-in',
templateUrl: './sign-in.component.html',
encapsulation: ViewEncapsulation.None,
animations: fuseAnimations,
})
export class AuthSignInComponent implements OnInit {
@ViewChild('signInNgForm') signInNgForm: NgForm;
alert: { type: FuseAlertType; message: string } = {
type: 'success',
message: ''
};
signInForm: FormGroup;
showAlert: boolean = false;
/**
* Constructor
*/
constructor(
private _httpClient: HttpClient,
private _formBuilder: FormBuilder,
private _router: Router,
private _patotuiAuthService: PaoTuiAuthService,
private _snackBar: MatSnackBar
) {
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void {
// Create the form
this.signInForm = this._formBuilder.group({
name: ['user1', Validators.required],
password: ['<PASSWORD>', Validators.required],
rememberMe: ['']
});
console.log(`sign-in init authservice data: ${this._patotuiAuthService.myId} ${this._patotuiAuthService.myToken}`);
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Sign in
*/
signIn(): void {
// Return if the form is invalid
if (this.signInForm.invalid) {
return;
}
// Disable the form
// this.signInForm.disable();
// Hide the alert
this.showAlert = false;
console.log('login');
// Sign in
this._httpClient.post<LoginResponse>(`${BASE_URL}/auth?option=login`, {
name: this.signInForm.get('name').value,
password: this.signInForm.get('password').value
}).subscribe((data) => {
console.log(data);
if (data.status === 'error') {
this.openSnackBar('User name or password incorrect');
} else {
this._patotuiAuthService.myToken = data.token;
this._patotuiAuthService.myId = data.userId;
this._patotuiAuthService.email = data.email;
this._patotuiAuthService.lastLogin = data.lastLogin;
this._patotuiAuthService.avatarUrl = data.avatarUrl;
this._router.navigate(['/search-task']);
}
});
}
search(): void {
this._router.navigate(['/search-task']);
}
openSnackBar(message: string): void {
this._snackBar.open(message, 'close', {
duration: 2000,
panelClass: ['my-snack-bar']
});
}
}
<file_sep>/src/doc/angular/angular.md
# Angular
## Rxjs operator `combineLatest`
This operator is used to read all the inputs given in the operator on the event of input change.
### What is the best situation to use it?
One good example is to use it in the filter process.
```
combineLatest([this.filters.categorySlug$, this.filters.query$, this.filters.hideCompleted$, this.filters.paginator$])
.subscribe(([categorySlug, query, hideCompleted, paginator]) => {
// Reset the filtered courses
this.filteredTasks = this.tasks;
// Filter by category
if (categorySlug !== 'all') {
this.filteredTasks = this.filteredTasks.filter(task => task.category === categorySlug);
}
// Filter by search query
if (query !== '') {
this.filteredTasks = this.filteredTasks.filter(task => task.title.toLowerCase().includes(query.toLowerCase())
|| task.description.toLowerCase().includes(query.toLowerCase())
|| task.category.toLowerCase().includes(query.toLowerCase()));
}
// Filter by completed
if (hideCompleted) {
this.filteredTasks = this.filteredTasks.filter(task => task.assignedUserId === '');
}
// set filtercourse size before paginator
this.b4PaginatorFilterTaskSize = this.filteredTasks.length;
if (this.paginatorObj !== undefined) {
let flag = false;
if (this.initComplete !== hideCompleted) {
flag = true;
this.paginatorObj.firstPage();
this.initComplete = hideCompleted;
}
if (this.initCategory !== categorySlug && !flag) {
flag = true;
this.initCategory = categorySlug;
}
if (this.initQuery !== query && !flag) {
flag = true;
this.initQuery = query;
}
if (flag) {
this.paginatorObj.firstPage();
this.paginatorObj.pageSize = paginator.pageSize;
this.filteredTasks = this.filteredTasks.slice(0, paginator.pageSize);
return;
}
}
this.filteredTasks = this.filteredTasks.slice(paginator.pageIndex * paginator.pageSize, paginator.pageIndex * paginator.pageSize + paginator.pageSize);
});
```
## Angular Resolver
It can be used to prepare data before router get into the specific page.
### Resolver error handling
One strategy is to inject `Router`, and use `pipe` to do view navigation.
```
@Injectable({
providedIn: 'root'
})
export class TaskCategoriesResolver implements Resolve<any> {
/**
* Constructor
*/
constructor(
private _taskService: TaskService,
private _router: Router,
) {
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Resolver
*
* @param route
* @param state
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Category[]> {
return this._taskService.getCategories().pipe(
catchError((error) => {
this._router.navigateByUrl('/404');
return throwError(error);
})
);
}
}
```
## Common Script
`ng n <project name> --routing`
- Create a new project with routing feature.
`ng add @angular/material`
- Add angular material to project
<file_sep>/src/doc/log/log_20210620.md
## Update on 2021/6/20

### Update list
1. Remove unnecessary files.
2. Improve task search interface
1. Now it has 3 phases to transit between different stage
2. Improve main interface to accomodate task search and task post features.

<file_sep>/src/app/paotui/component/my-info/my-info.component.ts
import {
AfterViewInit,
ChangeDetectionStrategy, ChangeDetectorRef,
Component,
OnDestroy,
OnInit,
ViewChild,
ViewEncapsulation
} from '@angular/core';
import {Router} from '@angular/router';
import {Subject} from 'rxjs';
import {MatPaginator} from '@angular/material/paginator';
import {MatTableDataSource} from '@angular/material/table';
import {HttpClient} from '@angular/common/http';
import moment from 'moment';
import {
ChartOptions,
PastFiveDaysEarning,
PastTenDaysEarning,
PastTwoDaysEarning,
RadarChartOptions
} from './chartOptions';
import {BASE_URL} from '../../app.const';
import {PaoTuiAuthService} from '../../paotui-auth.service';
interface SpendingCardResponse {
taskCount: number;
taskSpend: number;
}
interface SpendingSummaryResponse {
lineData: number[];
columnData: number[];
totalTasks: number;
dollarSpent: number;
buyNecessity: number;
foodDelivery: number;
sendDocument: number;
other: number;
}
interface DataSourceResponse {
tasks: Task[];
}
interface Task {
no: number;
completeDateTime: string;
taskTitle: string;
taskCategoryId: number;
taskOwnerId: string;
taskDeliveredId: string;
taskFrom: string;
taskTo: string;
taskDeliverRate: number;
}
interface EarningCardResponse {
pastTwoDaysTotal: number;
pastFiveDaysTotal: number;
pastTenDaysTotal: number;
pastTwoDays: number[];
pastFiveDays: number[];
pastTenDays: number[];
}
interface EarningRadarResponse {
buyNecessity: number;
foodDelivery: number;
sendDocument: number;
other: number;
}
@Component({
selector: 'project',
templateUrl: './my-info.component.html',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyInfoComponent implements OnInit, OnDestroy, AfterViewInit {
@ViewChild(MatPaginator) paginator: MatPaginator;
public spendingTaskSummaryChartOptions: Partial<ChartOptions>;
public earningRadarChartOptions: Partial<RadarChartOptions>;
public earningPastTowDaysChartOptions: Partial<PastTwoDaysEarning>;
public earningPastFiveDaysChartOptions: Partial<PastFiveDaysEarning>;
public earningPastTenDaysChartOptions: Partial<PastTenDaysEarning>;
public buyNecessitySpend;
public buyNecessityCount;
public foodDeliverySpend;
public foodDeliveryCount;
public sendDocumentSpend;
public sendDocumentCount;
public otherSpend;
public otherCount;
public totalTasks;
public dollarSpent;
public buyNecessityWeeklyCount;
public foodDeliveryWeeklyCount;
public sendDocumentWeeklyCount;
public otherWeeklyCount;
public earningPastTwoDaysTotal;
public earningPastFiveDaysTotal;
public earningPastTenDaysTotal;
displayedColumns: string[] = ['no', 'title', 'complete', 'category', 'owner', 'deliver', 'from', 'to', 'rate'];
spendingDataSource = new MatTableDataSource<Task>();
earningDataSource = new MatTableDataSource<Task>();
private _unsubscribeAll: Subject<any> = new Subject<any>();
/**
* Constructor
*/
constructor(
private _router: Router,
private _httpClient: HttpClient,
private cd: ChangeDetectorRef,
private _patotuiAuthService: PaoTuiAuthService,
) {
this.spendingTaskSummaryChartOptions = {
series: [
{
name: 'Task Qty',
type: 'column',
data: [440, 505, 414, 671, 227, 413, 201]
},
{
name: 'Expense',
type: 'line',
data: [23, 42, 35, 27, 43, 22, 17]
}
],
chart: {
height: 350,
type: 'line'
},
stroke: {
width: [0, 4]
},
dataLabels: {
enabled: true,
enabledOnSeries: [1]
},
labels: [
'Mon',
'Tue',
'Wed',
'Thur',
'Fri',
'Sat',
'Sun'
],
xaxis: {
type: 'category'
},
yaxis: [
{
title: {
text: 'Task Qty'
}
},
{
opposite: true,
title: {
text: 'Expense'
}
}
]
};
this.earningRadarChartOptions = {
series: [
{
name: 'Earning',
data: [20, 100, 40, 30]
}
],
chart: {
height: 350,
type: 'radar'
},
dataLabels: {
enabled: true
},
plotOptions: {
radar: {
size: 140,
polygons: {
fill: {
colors: ['#f8f8f8', '#fff']
}
}
}
},
colors: ['#FF4560'],
markers: {
size: 6,
colors: ['#fff'],
strokeColors: ['#FF4560'],
strokeWidth: 5
},
tooltip: {
y: {
formatter: (val): string => `$${val}`
}
},
xaxis: {
categories: [
'Buy Necessity',
'Food Delivery',
'Send Document',
'Other'
]
},
yaxis: {
tickAmount: 7,
labels: {
formatter: (val, i): string => {
if (i % 2 === 0) {
return val.toFixed(2) + '';
} else {
return '';
}
}
}
}
};
this.earningPastTowDaysChartOptions = {
chart: {
animations: {
enabled: false
},
fontFamily: 'inherit',
foreColor: 'inherit',
height: '100%',
type: 'line',
sparkline: {
enabled: true
}
},
colors: ['#22D3EE'],
series: [
{
name: 'Expenses',
data: [4412, 4466]
}
],
stroke: {
curve: 'smooth'
},
tooltip: {
theme: 'dark'
},
xaxis: {
type: 'category',
categories: [
moment().subtract(2, 'days').format('DD MMM'),
moment().subtract(1, 'days').format('DD MMM')
]
},
yaxis: {
labels: {
formatter: (val): string => `$${val}`
}
}
};
this.earningPastFiveDaysChartOptions = {
chart: {
animations: {
enabled: false
},
fontFamily: 'inherit',
foreColor: 'inherit',
height: '100%',
type: 'line',
sparkline: {
enabled: true
}
},
colors: ['#4ADE80'],
series: [
{
name: 'Expenses',
data: [15521, 15519, 15522, 15521, 18000]
}
],
stroke: {
curve: 'smooth'
},
tooltip: {
theme: 'dark'
},
xaxis: {
type: 'category',
categories: [
moment().subtract(5, 'days').format('DD MMM'),
moment().subtract(4, 'days').format('DD MMM'),
moment().subtract(3, 'days').format('DD MMM'),
moment().subtract(2, 'days').format('DD MMM'),
moment().subtract(1, 'days').format('DD MMM')
]
},
yaxis: {
labels: {
formatter: (val): string => `$${val}`
}
}
};
this.earningPastTenDaysChartOptions = {
chart: {
animations: {
enabled: false
},
fontFamily: 'inherit',
foreColor: 'inherit',
height: '100%',
type: 'line',
sparkline: {
enabled: true
}
},
colors: ['#FB7185'],
series: [
{
name: 'Expenses',
data: [45891, 45801, 45834, 45843, 45800, 45900, 45814, 45856, 45910, 45849]
}
],
stroke: {
curve: 'smooth'
},
tooltip: {
theme: 'dark'
},
xaxis: {
type: 'category',
categories: [
moment().subtract(10, 'days').format('DD MMM'),
moment().subtract(9, 'days').format('DD MMM'),
moment().subtract(8, 'days').format('DD MMM'),
moment().subtract(7, 'days').format('DD MMM'),
moment().subtract(6, 'days').format('DD MMM'),
moment().subtract(5, 'days').format('DD MMM'),
moment().subtract(4, 'days').format('DD MMM'),
moment().subtract(3, 'days').format('DD MMM'),
moment().subtract(2, 'days').format('DD MMM'),
moment().subtract(1, 'days').format('DD MMM')
]
},
yaxis: {
labels: {
formatter: (val): string => `$${val}`
}
}
};
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void {
this._httpClient.get<SpendingCardResponse>(`${BASE_URL}/spending/${this._patotuiAuthService.myId}
?chart-type=card&date=yesterday&category=buy-necessity`).subscribe((data) => {
this.buyNecessityCount = data.taskCount;
this.buyNecessitySpend = data.taskSpend;
this.cd.markForCheck();
});
this._httpClient.get<SpendingCardResponse>(`${BASE_URL}/spending/${this._patotuiAuthService.myId}
?chart-type=card&date=yesterday&category=food-delivery`).subscribe((data) => {
this.foodDeliveryCount = data.taskCount;
this.foodDeliverySpend = data.taskSpend;
this.cd.markForCheck();
});
this._httpClient.get<SpendingCardResponse>(`${BASE_URL}/spending/${this._patotuiAuthService.myId}
?chart-type=card&date=yesterday&category=send-document`).subscribe((data) => {
this.sendDocumentCount = data.taskCount;
this.sendDocumentSpend = data.taskSpend;
this.cd.markForCheck();
});
this._httpClient.get<SpendingCardResponse>(`${BASE_URL}/spending/${this._patotuiAuthService.myId}
?chart-type=card&date=yesterday&category=other`).subscribe((data) => {
this.otherCount = data.taskCount;
this.otherSpend = data.taskSpend;
this.cd.markForCheck();
});
this._httpClient.get<SpendingSummaryResponse>(`${BASE_URL}/spending/${this._patotuiAuthService.myId}?chart-type=summary&date=this-week`).subscribe(
(data) => {
console.log(data);
this.totalTasks = data.totalTasks;
this.dollarSpent = data.dollarSpent;
this.buyNecessityWeeklyCount = data.buyNecessity;
this.foodDeliveryWeeklyCount = data.foodDelivery;
this.sendDocumentWeeklyCount = data.sendDocument;
this.otherWeeklyCount = data.other;
this.spendingTaskSummaryChartOptions.series = [
{
name: 'Task Qty',
type: 'column',
data: data.columnData
},
{
name: 'Expense',
type: 'line',
data: data.lineData
}
];
this.cd.markForCheck();
}
);
this._httpClient.get<DataSourceResponse>(`${BASE_URL}/spending/${this._patotuiAuthService.myId}?chart-type=datasource`).subscribe(
(data) => {
this.spendingDataSource.data = data.tasks;
this.cd.markForCheck();
}
);
// Get the data
// Attach SVG fill fixer to all ApexCharts
window['Apex'] = {
chart: {
events: {
mounted: (chart: any, options?: any): void => {
this._fixSvgFill(chart.el);
},
updated: (chart: any, options?: any): void => {
this._fixSvgFill(chart.el);
}
}
}
};
}
public tabChange(evt: any): void {
console.log(evt);
if (evt === 0) {
this._httpClient.get<DataSourceResponse>(`${BASE_URL}/spending/${this._patotuiAuthService.myId}?chart-type=datasource`).subscribe(
(data) => {
this.spendingDataSource.data = data.tasks;
this.spendingDataSource.paginator = this.paginator;
}
);
} else if (evt === 1) {
this._httpClient.get<DataSourceResponse>(`${BASE_URL}/earning/${this._patotuiAuthService.myId}?chart-type=datasource`).subscribe(
(data) => {
this.earningDataSource.data = data.tasks;
this.earningDataSource.paginator = this.paginator;
}
);
this._httpClient.get<EarningCardResponse>(`${BASE_URL}/earning/${this._patotuiAuthService.myId}?chart-type=card`).subscribe(
(data) => {
this.earningPastTwoDaysTotal = data.pastTwoDaysTotal;
this.earningPastFiveDaysTotal = data.pastFiveDaysTotal;
this.earningPastTenDaysTotal = data.pastTenDaysTotal;
this.earningPastTowDaysChartOptions.series = [
{
name: 'Expenses',
data: data.pastTwoDays
}
];
this.earningPastFiveDaysChartOptions.series = [
{
name: 'Expenses',
data: data.pastFiveDays
}
];
this.earningPastTenDaysChartOptions.series = [
{
name: 'Expenses',
data: data.pastTenDays
}
];
this.cd.markForCheck();
console.log(data);
}
);
this._httpClient.get<EarningRadarResponse>(`${BASE_URL}/earning/${this._patotuiAuthService.myId}?chart-type=radar&date=this-week`).subscribe(
(data) => {
this.earningRadarChartOptions.series = [
{
name: 'Earning',
data: [data.buyNecessity, data.foodDelivery, data.sendDocument, data.other]
}
];
this.cd.markForCheck();
console.log(data);
}
);
}
}
/**
* On destroy
*/
ngOnDestroy(): void {
// Unsubscribe from all subscriptions
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
}
ngAfterViewInit(): void {
this.spendingDataSource.paginator = this.paginator;
}
public updateCard(date: string, category: string): void {
this._httpClient.get<SpendingCardResponse>(`${BASE_URL}/spending/${this._patotuiAuthService.myId}
?chart-type=card&date=${date}&category=${category}`).subscribe((data) => {
if (category === 'buy-necessity') {
this.buyNecessityCount = data.taskCount;
this.buyNecessitySpend = data.taskSpend;
} else if (category === 'food-delivery') {
this.foodDeliveryCount = data.taskCount;
this.foodDeliverySpend = data.taskSpend;
} else if (category === 'send-document') {
this.sendDocumentCount = data.taskCount;
this.sendDocumentSpend = data.taskSpend;
} else if (category === 'other') {
this.otherCount = data.taskCount;
this.otherSpend = data.taskSpend;
}
this.cd.markForCheck();
});
}
public updateSummary(date: string): void {
this._httpClient.get<SpendingSummaryResponse>(`${BASE_URL}/spending/${this._patotuiAuthService.myId}?chart-type=summary&date=${date}`).subscribe((data) => {
console.log(data);
this.totalTasks = data.totalTasks;
this.dollarSpent = data.dollarSpent;
this.buyNecessityWeeklyCount = data.buyNecessity;
this.foodDeliveryWeeklyCount = data.foodDelivery;
this.sendDocumentWeeklyCount = data.sendDocument;
this.otherWeeklyCount = data.other;
this.spendingTaskSummaryChartOptions.series = [
{
name: 'Task Qty',
type: 'column',
data: data.columnData
},
{
name: 'Expense',
type: 'line',
data: data.lineData
}
];
this.cd.markForCheck();
});
}
public updateRadar(date: string): void {
this._httpClient.get<EarningRadarResponse>(`${BASE_URL}/earning/${this._patotuiAuthService.myId}?chart-type=radar&date=${date}`).subscribe(
(data) => {
this.earningRadarChartOptions.series = [
{
name: 'Earning',
data: [data.buyNecessity, data.foodDelivery, data.sendDocument, data.other]
}
];
this.cd.markForCheck();
}
);
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Track by function for ngFor loops
*
* @param index
* @param item
*/
trackByFn(index: number, item: any): any {
return item.id || index;
}
// -----------------------------------------------------------------------------------------------------
// @ Private methods
// -----------------------------------------------------------------------------------------------------
/**
* Fix the SVG fill references. This fix must be applied to all ApexCharts
* charts in order to fix 'black color on gradient fills on certain browsers'
* issue caused by the '<base>' tag.
*
* Fix based on https://gist.github.com/Kamshak/c84cdc175209d1a30f711abd6a81d472
*
* @param element
* @private
*/
private _fixSvgFill(element: Element): void {
// Current URL
const currentURL = this._router.url;
// 1. Find all elements with 'fill' attribute within the element
// 2. Filter out the ones that doesn't have cross reference so we only left with the ones that use the 'url(#id)' syntax
// 3. Insert the 'currentURL' at the front of the 'fill' attribute value
Array.from(element.querySelectorAll('*[fill]'))
.filter(el => el.getAttribute('fill').indexOf('url(') !== -1)
.forEach((el) => {
const attrVal = el.getAttribute('fill');
el.setAttribute('fill', `
url(${currentURL}${attrVal.slice(attrVal.indexOf('#'))}
`);
});
}
}
<file_sep>/src/app/paotui/component/my-info/my-info.module.ts
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { MatButtonModule } from '@angular/material/button';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatDividerModule } from '@angular/material/divider';
import { MatIconModule } from '@angular/material/icon';
import { MatMenuModule } from '@angular/material/menu';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSortModule } from '@angular/material/sort';
import { MatTableModule } from '@angular/material/table';
import { MatTabsModule } from '@angular/material/tabs';
import { TranslocoModule } from '@ngneat/transloco';
import { NgApexchartsModule } from 'ng-apexcharts';
import { SharedModule } from 'app/shared/shared.module';
import {MyInfoComponent} from './my-info.component';
import {myInfoRoutes} from './my-info.routing';
import {MatPaginatorModule} from '@angular/material/paginator';
import {PaotuiCommonModule} from "../../paotui.module";
@NgModule({
declarations: [
MyInfoComponent
],
imports: [
RouterModule.forChild(myInfoRoutes),
MatButtonModule,
MatButtonToggleModule,
MatDividerModule,
MatIconModule,
MatMenuModule,
MatProgressBarModule,
MatSidenavModule,
MatSortModule,
MatTableModule,
MatTabsModule,
NgApexchartsModule,
TranslocoModule,
SharedModule,
MatPaginatorModule,
PaotuiCommonModule
]
})
export class MyInfoModule
{
}
<file_sep>/src/app/mock-api/apps/browse-task/data.ts
/* eslint-disable */
export const categories = [
{
id: '9a67dff7-3c38-4052-a335-0cef93438ff6',
title: 'Buy Necessity',
slug: 'Buy Necessity'
},
{
id: 'a89672f5-e00d-4be4-9194-cb9d29f82165',
title: 'Send Document',
slug: 'send-document'
},
{
id: '02f42092-bb23-4552-9ddb-cfdcc235d48f',
title: 'Food Delivery',
slug: 'food-delivery'
},
{
id: '5648a630-979f-4403-8c41-fc9790dea8cd',
title: 'Other',
slug: 'other'
}
];
export const tasks = [
{
id: '694e4e5f-f25f-470b-bd0e-26b1d4f64028',
title: 'Buy Coke',
description: '2 cans of coke need chilled',
category: 'Buy Necessity',
from: 'other',
to: 'Woodlands',
date: '2021/6/22',
time: '13:45',
expectedRate: 10,
agreedRate: 0,
duration: 30,
currentStep: 2,
assignedUserId: 'aA',
taskOwnerId: 'owner1',
},
{
id: 'f924007a-2ee9-470b-a316-8d21ed78277f',
title: 'Buy Beer',
description: 'Two bottles of tiger beer',
category: 'Buy Necessity',
from: 'other',
to: 'Woodlands',
date: '2021/7/22',
time: '19:33',
expectedRate: 20,
agreedRate: 0,
duration: 15,
currentStep: 1,
assignedUserId: 'b',
taskOwnerId: 'owner2',
},
{
id: '0c06e980-abb5-4ba7-ab65-99a228cab36b',
title: 'Wash car',
description: 'Wash car in the car park',
category: 'Other',
from: 'other',
to: '<NAME>',
date: '2021/9/21',
time: '19:33',
expectedRate: 15,
agreedRate: 0,
duration: 15,
currentStep: 0,
assignedUserId: '',
taskOwnerId: 'owner3',
},
{
id: '1b9a9acc-9a36-403e-a1e7-b11780179e38',
title: 'Send package',
description: 'Send document to client office',
category: 'Send Document',
from: 'Admiralty',
to: 'Jurong East',
date: '2021/7/21',
time: '8:20',
expectedRate: 10,
agreedRate: 0,
duration: 30,
currentStep: 0,
assignedUserId: '',
taskOwnerId: 'owner4',
},
{
id: '55eb415f-3f4e-4853-a22b-f0ae91331169',
title: 'Walk my pet',
description: 'Nobody at home tonight till late, the pet needs accompany',
category: 'Other',
from: 'Other',
to: '<NAME>',
date: '2021/7/2',
time: '19:00',
expectedRate: 15,
agreedRate: 0,
duration: 30,
currentStep: 0,
assignedUserId: '',
taskOwnerId: 'owner5',
},
{
id: 'fad2ab23-1011-4028-9a54-e52179ac4a50',
title: 'Buy burger',
description: 'Deliver chicken burger to home',
category: 'Food Delivery',
from: 'Mcdonalds',
to: 'Hougang',
date: '2021/7/2',
time: '16:00',
expectedRate: 10,
agreedRate: 0,
duration: 30,
currentStep: 0,
assignedUserId: '',
taskOwnerId: 'owner5',
},
{
id: 'c4bc107b-edc4-47a7-a7a8-4fb09732e794',
title: 'Buy beer',
description: 'Two bottles of beer to home',
category: 'Buy Necessity',
from: '7-11',
to: 'Bedok',
date: '2021/6/29',
time: '19:30',
expectedRate: 11,
agreedRate: 0,
duration: 30,
currentStep: 0,
assignedUserId: '',
taskOwnerId: 'owner6',
},
{
id: '1449f945-d032-460d-98e3-406565a22293',
title: 'Send receipt',
description: 'Send receipt to client',
category: 'Send Document',
from: 'Novena',
to: 'City Hall',
date: '2021/6/29',
time: '10:30',
expectedRate: 10,
agreedRate: 0,
duration: 15,
currentStep: 0,
assignedUserId: '',
taskOwnerId: 'owner7',
},
{
id: 'f05e08ab-f3e3-4597-a032-6a4b69816f24',
title: 'Buy chicken rice',
description: 'Buy one set of chicken and deliver to home',
category: 'Food Delivery',
from: 'Food court',
to: 'Holland Village',
date: '2021/6/29',
time: '12:30',
expectedRate: 10,
agreedRate: 0,
duration: 15,
currentStep: 0,
assignedUserId: '',
taskOwnerId: 'owner8',
},
{
id: '181728f4-87c8-45c5-b9cc-92265bcd2f4d',
title: 'Buy fried rice',
description: 'Buy two bowls of fried rice',
category: 'Food Delivery',
from: 'Food court',
to: 'Jurong West',
date: '2021/6/29',
time: '12:30',
expectedRate: 15,
agreedRate: 0,
duration: 15,
currentStep: 0,
assignedUserId: '',
taskOwnerId: 'owner9',
},
{
id: 'fcbfedbf-6187-4b3b-89d3-1a7cb4e11616',
title: 'Send contract',
description: 'Send contract document to client',
category: 'Send Document',
from: 'Outram Park',
to: '<NAME>',
date: '2021/6/26',
time: '14:30',
expectedRate: 15,
agreedRate: 0,
duration: 15,
currentStep: 0,
assignedUserId: '',
taskOwnerId: 'owner10',
},
{
id: '5213f6a1-1dd7-4b1d-b6e9-ffb7af534f28',
title: 'Buy cooking oil',
description: 'Get one bottle of cooking oil 500ml',
category: 'Buy Necessity',
from: 'Fair Price',
to: 'Woodlands',
date: '2021/6/26',
time: '9:30',
expectedRate: 15,
agreedRate: 0,
duration: 15,
currentStep: 0,
assignedUserId: '',
taskOwnerId: 'owner11',
},
{
id: '02992ac9-d1a3-4167-b70e-8a1d5b5ba253',
title: 'Buy veges',
description: 'Buy 500g veges from market',
category: 'Buy Necessity',
from: 'Market',
to: 'Braddell',
date: '2021/6/27',
time: '9:30',
expectedRate: 15,
agreedRate: 0,
duration: 15,
currentStep: 0,
assignedUserId: '',
taskOwnerId: 'owner12',
},
{
id: '2139512f-41fb-4a4a-841a-0b4ac034f9b4',
title: 'Play badminton',
description: 'Form a team and play badminton',
category: 'Other',
from: 'other',
to: 'Sports hall',
date: '2021/6/27',
time: '19:30',
expectedRate: 15,
agreedRate: 0,
duration: 15,
currentStep: 0,
assignedUserId: '',
taskOwnerId: 'owner13',
},
];
export const demoTaskIssuedContent = `
Task Issued
`;
export const demoTaskExecutionContent = `
Task Executing
`;
export const demoTaskCompleteContent = `
Task Complete
`;
export const taskSteps = [
{
order: 0,
title: 'Task Issued',
subTitle: `Task is issued! Now the task description is available!`,
content: `<h2 class="text-2xl sm:text-3xl">Task Issued</h1>
<h3>Description</h3>
${demoTaskIssuedContent}
`
},
{
order: 1,
title: 'Task Execution',
subTitle: `Task is in execution stage! Complete before due time to avoid penalty.`,
content: `<h2 class="text-2xl sm:text-3xl">Task Execution</h1>${demoTaskExecutionContent}`
},
{
order: 2,
title: 'Task Complete',
subTitle: `Task is complete.`,
content: `<h2 class="text-2xl sm:text-3xl">Task Complete</h1>${demoTaskCompleteContent}`
},
];
<file_sep>/src/app/mock-api/common/search/api.ts
import {Injectable} from '@angular/core';
import {cloneDeep} from 'lodash-es';
import {FuseNavigationItem, FuseNavigationService} from '@fuse/components/navigation';
import {FuseMockApiService} from '@fuse/lib/mock-api';
import {defaultNavigation} from 'app/mock-api/common/navigation/data';
import {tasks} from 'app/mock-api/apps/post-task/data';
@Injectable({
providedIn: 'root'
})
export class SearchMockApi {
private readonly _defaultNavigation: FuseNavigationItem[] = defaultNavigation;
private readonly _tasks: any[] = tasks;
/**
* Constructor
*/
constructor(
private _fuseMockApiService: FuseMockApiService,
private _fuseNavigationService: FuseNavigationService
) {
// Register Mock API handlers
this.registerHandlers();
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Register Mock API handlers
*/
registerHandlers(): void {
// Get the flat navigation and store it
const flatNavigation = this._fuseNavigationService.getFlatNavigation(this._defaultNavigation);
// -----------------------------------------------------------------------------------------------------
// @ Search results - GET
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onPost('api/common/search')
.reply(({request}) => {
// Get the search query
const query = cloneDeep(request.body.query.toLowerCase());
// If the search query is an empty string,
// return an empty array
if (query === '') {
return [200, {results: []}];
}
// Filter the navigation
const pagesResults = cloneDeep(flatNavigation)
.filter(page => (page.title?.toLowerCase().includes(query) || (page.subtitle && page.subtitle.includes(query))));
// Filter the post-search-task
const tasksResults = cloneDeep(this._tasks)
.filter(task => task.title.toLowerCase().includes(query));
// Prepare the results array
const results = [];
// If there are page results...
if (pagesResults.length > 0) {
// Normalize the results
pagesResults.forEach((result: any) => {
});
// Add to the results
results.push({
id: 'pages',
label: 'Pages',
results: pagesResults
});
}
// If there are post-search-task results...
if (tasksResults.length > 0) {
// Normalize the results
tasksResults.forEach((result) => {
// Add a link
result.link = '/paotui-apps/post-search-task/' + result.id;
});
// Add to the results
results.push({
id: 'tasks',
label: 'Tasks',
results: tasksResults
});
}
// Return the response
return [200, results];
});
}
}
<file_sep>/src/app/paotui/paotui-guard.guard.ts
import {Injectable} from '@angular/core';
import {
ActivatedRouteSnapshot,
CanActivate,
CanActivateChild,
Router,
RouterStateSnapshot,
UrlTree
} from '@angular/router';
import {Observable} from 'rxjs';
import {AuthService} from '../core/auth/auth.service';
import {PaoTuiAuthService} from './paotui-auth.service';
import {HttpClient} from '@angular/common/http';
import {UserService} from '../core/user/user.service';
import {map} from 'rxjs/operators';
import {BASE_URL} from './app.const';
interface VerifyTokenResponse {
status: string;
msg: string;
}
@Injectable({
providedIn: 'root'
})
export class PaotuiGuard implements CanActivate, CanActivateChild {
constructor(
private _authService: AuthService,
private _router: Router,
private _patotuiAuthService: PaoTuiAuthService,
private _httpClient: HttpClient,
private _userService: UserService
) {
}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.checkToken();
}
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return this.checkToken();
}
public checkToken(): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (this._patotuiAuthService.myId.trim().length > 0 && this._patotuiAuthService.myToken.trim().length > 0) {
return this._httpClient.post<VerifyTokenResponse>(`${BASE_URL}/auth?option=token-verify`,
{
userId: this._patotuiAuthService.myId,
token: this._patotuiAuthService.myToken
}).pipe(map((response) => {
if (response.status === 'success') {
return true;
} else {
return this._router.createUrlTree(['/sign-in']);
}
}));
} else {
console.log(`both id and token is empty, redirect to sign-in`);
return this._router.createUrlTree(['/sign-in']);
}
}
}
<file_sep>/src/app/paotui/component/search-task/list.component.ts
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component, Inject,
OnDestroy,
OnInit, ViewChild,
ViewEncapsulation
} from '@angular/core';
import {MatPaginator, PageEvent} from '@angular/material/paginator';
import {ActivatedRoute, Router} from '@angular/router';
import {MatSelectChange} from '@angular/material/select';
import {MatSlideToggleChange} from '@angular/material/slide-toggle';
import {BehaviorSubject, combineLatest, Subject} from 'rxjs';
import {Paginator} from 'app/paotui/component/search-task/browse-task.types';
import {HttpClient} from '@angular/common/http';
import {BASE_URL} from '../../app.const';
import {PaoTuiAuthService} from '../../paotui-auth.service';
import {MatDialog} from '@angular/material/dialog';
import {ExpectedRateDialogComponent} from './expected-rate-dialog.component';
export interface ExpectedRateDialogData {
rate: number;
}
export interface CategoryResponse {
status: string;
msg: string;
categories: Category[];
}
export interface Category {
cid: string;
title: string;
}
interface TaskResponse {
status: string;
msg: string;
tasks: Task[];
}
export interface Task {
no: number;
taskId: string;
taskTitle: string;
taskDescription: string;
taskCategoryId: number;
taskFrom: string;
taskTo: string;
taskCreate: string;
taskStart: string;
taskComplete: string;
taskDuration: number;
taskStep: number;
taskOwnerId: string;
taskOwnerRate: number;
taskDeliverId: number;
taskDeliverRate: number;
bidders: Bidder[];
}
interface Bidder {
taskBidderId: string;
taskBidderRate: number;
}
interface TaskBidResponse {
status: string;
msg: string;
}
@Component({
selector: 'academy-list',
templateUrl: './list.component.html',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TaskListComponent implements OnInit, OnDestroy {
@ViewChild('paginatorObj') paginatorObj: MatPaginator;
rate: number;
initComplete = false;
initCategory = 'all';
initQuery = '';
paginator: Paginator = {
pageIndex: 0,
pageSize: 3,
};
categories: Category[];
tasks: Task[] = null;
filteredTasks: Task[];
filters: {
categorySlug$: BehaviorSubject<string>;
query$: BehaviorSubject<string>;
hideCompleted$: BehaviorSubject<boolean>;
paginator$: BehaviorSubject<Paginator>;
} = {
categorySlug$: new BehaviorSubject('all'),
query$: new BehaviorSubject(''),
hideCompleted$: new BehaviorSubject(false),
paginator$: new BehaviorSubject(this.paginator),
};
// MatPaginator Inputs
pageSize = 3;
pageSizeOptions: number[] = [3, 9];
b4PaginatorFilterTaskSize: number;
private _unsubscribeAll: Subject<any> = new Subject<any>();
/**
* Constructor
*/
constructor(
private _activatedRoute: ActivatedRoute,
private _changeDetectorRef: ChangeDetectorRef,
private _router: Router,
private _httpClient: HttpClient,
private _patotuiAuthService: PaoTuiAuthService,
public dialog: MatDialog
) {
}
bid(taskId: string): void {
const dialogRef = this.dialog.open(ExpectedRateDialogComponent, {
width: '400px',
data: {rate: this.rate}
});
dialogRef.afterClosed().subscribe((result) => {
console.log(`Bid info,bidTaskId:${taskId},bidRate:${result}`);
if (result !== undefined) {
this._httpClient.post<TaskBidResponse>(`${BASE_URL}/tasks/bid`, {
taskId: taskId,
taskBidderId: `${this._patotuiAuthService.myId}`,
taskBidderRate: result,
}).subscribe((data) => {
console.log(data);
this._httpClient.get<TaskResponse>(`${BASE_URL}/tasks/${this._patotuiAuthService.myId}
?option=on-going&category=exclude-me&identity=user`).subscribe((response) => {
// this.tasks = this.filteredTasks = response.tasks;
// console.log(this.tasks);
// this._changeDetectorRef.markForCheck();
this.updateTask();
});
});
}
});
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void {
this._httpClient.get<CategoryResponse>(`${BASE_URL}/categories`).subscribe((data) => {
this.categories = data.categories;
});
this.updateTask();
}
updateTask(): void {
this._httpClient.get<TaskResponse>(`${BASE_URL}/tasks/${this._patotuiAuthService.myId}?option=on-going&category=exclude-me&identity=user`).subscribe((data) => {
this.tasks = this.filteredTasks = data.tasks;
console.log(this.tasks);
this._changeDetectorRef.markForCheck();
combineLatest([this.filters.categorySlug$, this.filters.query$, this.filters.hideCompleted$, this.filters.paginator$])
.subscribe(([categorySlug, query, hideCompleted, paginator]) => {
// Reset the filtered courses
this.filteredTasks = this.tasks;
// Filter by category
if (categorySlug !== 'all') {
this.filteredTasks = this.filteredTasks.filter(task => task.taskCategoryId === Number(categorySlug));
}
// Filter by search query
if (query !== '') {
this.filteredTasks = this.filteredTasks.filter(task => task.taskTitle.toLowerCase().includes(query.toLowerCase())
|| task.taskDescription.toLowerCase().includes(query.toLowerCase()));
}
if (hideCompleted) {
console.log(`toggle triggered ${hideCompleted}`);
this.filteredTasks = this.filteredTasks.filter((task) => {
if (task.bidders === null) {
return false;
}
const found = task.bidders.find(bid => bid.taskBidderId === this._patotuiAuthService.myId);
if (found === undefined) {
return false;
} else {
return true;
}
});
} else {
console.log(`toggle triggered ${hideCompleted}`);
this.filteredTasks = this.filteredTasks.filter((task) => {
if (task.bidders === null) {
return true;
}
const found = task.bidders.find(bid => bid.taskBidderId === this._patotuiAuthService.myId);
if (found === undefined) {
return true;
} else {
return false;
}
});
}
// set filtercourse size before paginator
this.b4PaginatorFilterTaskSize = this.filteredTasks.length;
if (this.paginatorObj !== undefined) {
let flag = false;
if (this.initComplete !== hideCompleted) {
flag = true;
this.paginatorObj.firstPage();
this.initComplete = hideCompleted;
}
if (this.initCategory !== categorySlug && !flag) {
flag = true;
this.initCategory = categorySlug;
}
if (this.initQuery !== query && !flag) {
flag = true;
this.initQuery = query;
}
if (flag) {
this.paginatorObj.firstPage();
this.paginatorObj.pageSize = paginator.pageSize;
this.filteredTasks = this.filteredTasks.slice(0, paginator.pageSize);
return;
}
}
this.filteredTasks = this.filteredTasks.slice(paginator.pageIndex * paginator.pageSize, paginator.pageIndex * paginator.pageSize + paginator.pageSize);
});
});
}
ngOnDestroy(): void {
// Unsubscribe from all subscriptions
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
}
filterByQuery(query: string): void {
this.filters.query$.next(query);
}
filterByCategory(change: MatSelectChange): void {
console.log(change.value);
this.filters.categorySlug$.next(change.value);
}
toggleCompleted(change: MatSlideToggleChange): void {
this.filters.hideCompleted$.next(change.checked);
}
trackByFn(index: number, item: any): any {
return item.id || index;
}
handlePageEvent(event: PageEvent): void {
this.pageSize = event.pageSize;
this.paginator.pageSize = event.pageSize;
this.paginator.pageIndex = event.pageIndex;
this.filters.paginator$.next(this.paginator);
}
isMyIdInBidders(myid: string, bidders: Bidder[]): boolean {
if (bidders === null || bidders === undefined || bidders.length === 0) {
return false;
} else {
const found = bidders.find(bid => bid.taskBidderId === myid);
if (found === undefined) {
return false;
} else {
return true;
}
}
}
MyBidRate(myid: string, bidders: Bidder[]): number {
const found = bidders.find(bid => bid.taskBidderId === myid);
return found.taskBidderRate;
}
}
<file_sep>/src/doc/deployment/docker_https.sh
# 下面命令在project_directory/src/doc/deployment下执行
# 制作原始nginx镜像
docker run --name my-nginx -p 443:443 -d nginx:latest
# 拷贝项目生产代码到nginx容器/my_app目录
docker cp ../../../dist/paotui my-nginx:/my_app
# 拷贝当前目录的配置文件到容器当中
docker cp default.ssl.conf my-nginx:/etc/nginx/conf.d/default.conf
# 生成存放证书和日志的目录
docker exec -it my-nginx bash
mkdir my_ssl && mkdir logs && exit
# 复制证书
docker cp paotui.crt my-nginx:/my_ssl && docker cp paotui.key my-nginx:/my_ssl
# 重启容器
docker restart my-nginx
# 将含前端网页的容器重新制作为镜像
# 0893fcf3620b为容器id
docker commit 0893fcf<PASSWORD>b magicpowerworld/paotui_front_end:20210710
# 制作完镜像之后推送
docker push magicpowerworld/paotui_front_end:20210710
# 生产环境下部署镜像
docker run --name paotui_front_end -p 443:443 -d magicpowerworld/paotui_front_end:20210710
# 进入docker将配置文件复制到本地
docker exec -it my-nginx bash
docker cp my-nginx:/etc/nginx/conf.d/default.conf .
<file_sep>/src/app/core/auth/guards/auth.guard.ts
import {Injectable} from '@angular/core';
import {
ActivatedRouteSnapshot,
CanActivate,
CanActivateChild,
Router,
RouterStateSnapshot,
UrlTree
} from '@angular/router';
import {Observable} from 'rxjs';
import {AuthService} from 'app/core/auth/auth.service';
import {PaoTuiAuthService} from 'app/paotui/paotui-auth.service';
import {HttpClient} from '@angular/common/http';
import {UserService} from '../../user/user.service';
const user = {
id: '<PASSWORD>',
name: '<NAME>',
email: '<EMAIL>',
avatar: 'assets/images/avatars/brian-hughes.jpg',
status: 'online'
};
export interface VerifyTokenResponse {
status: string;
msg: string;
}
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate, CanActivateChild {
/**
* Constructor
*/
constructor(
private _authService: AuthService,
private _router: Router,
private _patotuiAuthService: PaoTuiAuthService,
private _httpClient: HttpClient,
private _userService: UserService
) {
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Can activate
*
* @param route
* @param state
*/
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return true;
}
/**
* Can activate child
*
* @param childRoute
* @param state
*/
canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
return true;
}
}
<file_sep>/src/app/paotui/component/user/user.component.ts
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
Input,
OnDestroy,
OnInit,
ViewEncapsulation
} from '@angular/core';
import {Router} from '@angular/router';
import {BooleanInput} from '@angular/cdk/coercion';
import {Subject} from 'rxjs';
import {UserService} from 'app/core/user/user.service';
import {PaoTuiAuthService} from '../../paotui-auth.service';
import {BASE_URL} from '../../app.const';
import {HttpClient} from '@angular/common/http';
interface AvatarResponse {
status: string;
msg: string;
avatarUrl: string;
}
@Component({
selector: 'user',
templateUrl: './user.component.html',
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UserComponent implements OnInit, OnDestroy {
/* eslint-disable @typescript-eslint/naming-convention */
static ngAcceptInputType_showAvatar: BooleanInput;
/* eslint-enable @typescript-eslint/naming-convention */
@Input() showAvatar: boolean = true;
public id: string;
public email: string;
public lastLogin: string;
private _unsubscribeAll: Subject<any> = new Subject<any>();
/**
* Constructor
*/
constructor(
private _httpClient: HttpClient,
private _changeDetectorRef: ChangeDetectorRef,
private _router: Router,
private _userService: UserService,
private _patotuiAuthService: PaoTuiAuthService,
private cd: ChangeDetectorRef,
) {
}
// -----------------------------------------------------------------------------------------------------
// @ Lifecycle hooks
// -----------------------------------------------------------------------------------------------------
/**
* On init
*/
ngOnInit(): void {
this.id = this._patotuiAuthService.myId;
this.email = this._patotuiAuthService.email;
this.lastLogin = this._patotuiAuthService.lastLogin;
}
/**
* On destroy
*/
ngOnDestroy(): void {
// Unsubscribe from all subscriptions
this._unsubscribeAll.next();
this._unsubscribeAll.complete();
}
/**
* Sign out
*/
signOut(): void {
this._patotuiAuthService.clearAll();
this._router.navigate(['/sign-in']);
}
upload(file: FileList): void {
const formData: FormData = new FormData();
formData.append('avatar', file.item(0), file.item(0).name);
this._httpClient.post<AvatarResponse>(`${BASE_URL}/avatar?userID=${this._patotuiAuthService.myId}`, formData).subscribe((data) => {
console.log(data);
if (data.status === 'success') {
this._patotuiAuthService.avatarUrl = data.avatarUrl;
this.cd.markForCheck();
}
});
console.log(file.item(0));
}
}
<file_sep>/src/app/mock-api/common/navigation/api.ts
import { Injectable } from '@angular/core';
import { cloneDeep } from 'lodash-es';
import { FuseNavigationItem } from '@fuse/components/navigation';
import { FuseMockApiService } from '@fuse/lib/mock-api';
import { defaultNavigation, horizontalNavigation } from 'app/mock-api/common/navigation/data';
@Injectable({
providedIn: 'root'
})
export class NavigationMockApi
{
private readonly _defaultNavigation: FuseNavigationItem[] = defaultNavigation;
private readonly _horizontalNavigation: FuseNavigationItem[] = horizontalNavigation;
/**
* Constructor
*/
constructor(private _fuseMockApiService: FuseMockApiService)
{
// Register Mock API handlers
this.registerHandlers();
}
// -----------------------------------------------------------------------------------------------------
// @ Public methods
// -----------------------------------------------------------------------------------------------------
/**
* Register Mock API handlers
*/
registerHandlers(): void
{
// -----------------------------------------------------------------------------------------------------
// @ Navigation - GET
// -----------------------------------------------------------------------------------------------------
this._fuseMockApiService
.onGet('api/common/navigation')
.reply(() => {
// Fill horizontal navigation children using the default navigation
this._horizontalNavigation.forEach((horizontalNavItem) => {
this._defaultNavigation.forEach((defaultNavItem) => {
if ( defaultNavItem.id === horizontalNavItem.id )
{
horizontalNavItem.children = cloneDeep(defaultNavItem.children);
}
});
});
// Return the response
return [
200,
{
default : cloneDeep(this._defaultNavigation),
horizontal: cloneDeep(this._horizontalNavigation)
}
];
});
}
}
<file_sep>/src/app/paotui/component/my-info/my-info.routing.ts
import { Route } from '@angular/router';
import {MyInfoComponent} from './my-info.component';
export const myInfoRoutes: Route[] = [
{
path : '',
component: MyInfoComponent,
}
];
|
6470ddf0f36c17f109b3759659dbf7ad78cb93e0
|
[
"Markdown",
"TypeScript",
"Shell"
] | 35
|
Markdown
|
HiThisIsNotCodeRepo/ProjectGoLiveRun4FrontEnd
|
9fc59f53c510688a5242092bbda9ffbc86eaa132
|
45fcfffa2fbc63a052474b05718d603ffff1ca86
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
import math
import sys
import time
import dbus
import gatt
LIGHT_CHARACTERISTIC = "932c32bd-0002-47a2-835a-a8d455b859dd"
BRIGHTNESS_CHARACTERISTIC = "932c32bd-0003-47a2-835a-a8d455b859dd"
COLOR_CHARACTERISTIC = "932c32bd-0005-47a2-835a-a8d455b859dd"
class HueLight(gatt.Device):
def __init__(
self, action: str, mac_address: str, manager: gatt.DeviceManager
) -> None:
self.action = action
print(f"connect to {mac_address}...")
super(HueLight, self).__init__(mac_address=mac_address, manager=manager)
def introspect(self) -> None:
for s in self.services:
print(f"service: {s.uuid}")
for c in s.characteristics:
val = c.read_value()
if val is not None:
ary = bytearray()
for i in range(len(val)):
ary.append(int(val[i]))
try:
val = ary.decode("utf-8")
except UnicodeDecodeError:
val = ary
print(f" characteristic: {c.uuid}: {val}")
def toggle_light(self) -> None:
val = self.light_state.read_value()
if val is None:
msg = (
"Could not read characteristic. If that is your first pairing"
"you may need to perform a firmware reset using the mobile phillips hue app and try connect again: "
"https://www.reddit.com/r/Hue/comments/eq0y3y/philips_hue_bluetooth_developer_documentation/"
)
print(msg, file=sys.stderr)
sys.exit(1)
on = val[0] == 1
self.light_state.write_value(b"\x00" if on else b"\x01")
def services_resolved(self) -> None:
super().services_resolved()
for s in self.services:
for char in s.characteristics:
if char.uuid == LIGHT_CHARACTERISTIC:
print("found light characteristics")
self.light_state = char
elif char.uuid == BRIGHTNESS_CHARACTERISTIC:
print("found brightness characteristics")
self.brightness = char
elif char.uuid == COLOR_CHARACTERISTIC:
print("found color characteristics")
self.color = char
if self.action == "toggle":
self.toggle_light()
elif self.action == "introspect":
self.introspect()
else:
print(f"unknown action {self.action}")
sys.exit(1)
sys.exit(0)
# shannans_lamp = "cd:43:95:fe:ce:d6"
# joergs_lamp = "d4:bb:d8:6c:07:86"
def main():
if len(sys.argv) < 3:
print(f"USAGE: {sys.argv[0]} toggle|introspect macaddress", file=sys.stderr)
sys.exit(1)
mac_address = sys.argv[2]
# FIXME adapter_name should be configurable
manager = gatt.DeviceManager(adapter_name="hci0")
device = HueLight(sys.argv[1], mac_address=mac_address, manager=manager)
device.connect()
manager.run()
if __name__ == "__main__":
main()
|
49905be231f7eac18b5ee4a785c36e01defb9140
|
[
"Python"
] | 1
|
Python
|
mussra/hue-ble-ctl
|
06246910e3eca731571b763fb79e9b7ec8e30ce0
|
509e7b2b14586d15f9861fc864988a8358cd282d
|
refs/heads/master
|
<repo_name>coldice1915/logs-analysis<file_sep>/logs_analysis.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# A reporting tool that answers three questions about 'newsdata.sql'
# Question 1: What are the most popular three articles of all time?
# Question 2: Who are the most popular article authors of all time?
# Question 3: On which days did more than 1% of requests lead to errors?
__author__ = 'JamesHan'
import psycopg2
try:
db = psycopg2.connect(database="news")
print ("Connection to the news database successful!")
except psycopg2.connect.Error as e:
print ("Oh no, a connection error has occurred!")
# Helper function in executing and returning queries
def get_results(query):
cursor = db.cursor()
cursor.execute(query)
results = cursor.fetchall()
db.commit()
cursor.close()
return results
# Query statements
query1 = """SELECT *
FROM top_articles;"""
query2 = """SELECT name, sum(article_views.count) AS views
FROM articles_author
JOIN article_views
ON articles_author.title = article_views.title
GROUP BY name
ORDER BY views desc;"""
query3 = """SELECT error_logs.date,
round(100.0 * error_count / log_count, 2) as percent
FROM daily_logs
JOIN error_logs
ON daily_logs.date = error_logs.date
AND error_count > log_count/100;"""
# Defining the three answers
def top_articles(query):
results = get_results(query)
print ('Q.1|| What are the most popular three articles of all time?\n')
for (article, view) in results:
print ('\t{0} - {1} views\n'.format(article, view))
def top_authors(query):
results = get_results(query)
print ('Q.2|| Who are the most popular article authors of all time?\n')
for (author, views) in results:
print ('\t{0} - {1} views\n'.format(author, views))
def error_percent(query):
results = get_results(query)
print ('Q.3|| Which day did more than 1% of requests lead to an error?\n')
for (date, error) in results:
print ('\t{0} - {1}% 404 errors\n'.format(date, error))
# Printing the answers to the three questions
answer_1 = top_articles(query1)
answer_2 = top_authors(query2)
answer_3 = error_percent(query3)
db.close()
<file_sep>/README.md
###### Completed on 09/10/2019
# Logs Analysis
A python script that queries a database and prints the answer to three questions:
1. What are the most popular three articles of all time?
2. Who are the most popular article authors of all time?
3. On which days did more than 1% of requests lead to errors?
## Table of contents
- [Introduction](#introduction)
- [Technologies](#technologies)
- [Setup](#setup)
- [Launch](#launch)
- [Author](#author)
- [What have I done?](#what-have-i-done)
## Introduction
Working on a newspaper site, I've been asked to build an internal reporting tool that will use information from the database to discover what kind of articles the site's readers like.
The database contains newspaper articles, as well as the web server log for the site. The log has a database row for each time a reader loaded a web page. Using this information, my code will answer questions about the site's user activity.
The program will run from the command line and it won't take any input from the user. It will connect to the database, use SQL queries to analyze the log data, and print out the answers to the questions.
My task is to create a reporting tool that prints out reports (in plain text) based on the data in the site database. This reporting tool is a Python program using the `psycopg2` module to connect to the database.
## Technologies
Python 2.7.16 • Psycopg 2.8.3 • Vagrant 2.2.0 • VirtualBox 6.0.10
## Setup
### 1. Install VitualBox
Download [VirtualBox](https://www.virtualbox.org/wiki/Downloads). Install the platform package for your operating system.
### 2. Install Vagrant
Download [Vagrant](https://www.vagrantup.com/downloads.html). Install the version for your operating system.
If Vagrant is successfully installed, you will be able to run `vagrant --version` in your terminal to see the version number.
### 3. Download the VM configuration
Download and unzip this file: [FSND-Virtual-Machine.zip](https://s3.amazonaws.com/video.udacity-data.com/topher/2018/April/5acfbfa3_fsnd-virtual-machine/fsnd-virtual-machine.zip).
(Alternately, you can use Github to fork and clone this [repository](https://github.com/udacity/fullstack-nanodegree-vm).)
### 4. Start the virtual machine
In your terminal, `cd` to the **/vagrant** subdirectory and run the command `vagrant up` to start the Ubuntu Linux installation.
When it is finished running, run the command `vagrant ssh` to log in.
### 5. Download the data
Download and unzip this file: [newsdata.zip](https://d17h27t6h515a5.cloudfront.net/topher/2016/August/57b5f748_newsdata/newsdata.zip). Move the file *newsdata.sql* into the **/vagrant** subdirectory.
`cd` into the **/vagrant** subdirectory and run the command `psql -d news -f newsdata.sql` to connect to the *news* database and run SQL commands in *newsdata.sql*.
### 6. Create the following views:
#### Views for Question 1
```sql
CREATE VIEW articles_author AS
SELECT title, name
FROM articles JOIN authors
ON articles.author = authors.id;
```
```sql
CREATE VIEW top_articles AS
SELECT articles.title, count(log.path)
FROM articles
JOIN log ON log.path = concat('%',articles.slug)
GROUP BY articles.title ORDER BY count(log.path) desc limit 3;
```
#### Views for Question 2
```sql
CREATE VIEW articles_author AS
SELECT title, name
FROM articles JOIN authors
ON articles.author = authors.id;
```
```sql
CREATE VIEW article_views AS
SELECT articles.title, count(log.path)
FROM articles
JOIN log ON log.path = concat('%',articles.slug)
GROUP BY articles.title ORDER BY count(log.path) desc;
```
#### Views for Question 3
```sql
CREATE VIEW daily_logs AS
SELECT date(time) as date, count(*) as log_count
FROM log
GROUP BY date;
```
```sql
CREATE VIEW error_logs AS
SELECT date(time) as date, count(*) as error_count
FROM log
WHERE STATUS = '404 NOT FOUND'
GROUP BY date ORDER BY date;
```
####
After creating the views, exit psql.
## Launch
### 1. Download the script
Download and unzip this file: [logs_analysis_project-master.zip](https://github.com/coldice1915/logs_analysis_project/archive/master.zip).
(Or, you can use Github to fork and clone this [repository](https://github.com/coldice1915/logs_analysis_project.git))
### 2. Run the script
`cd` to the directory and run `python logs_analysis.py` to execute the script
## Author
***[<NAME>](https://www.linkedin.com/in/question-not-doubt/)***
## What have I done?
- [x] Installed and launched a virtual machine to create a familiar environment
- [x] Interacted with the database from both the command line and my code
- [x] Ran SQL commands to view tables and data types within the large database
- [x] Ran SQL statements to analyze the log data (SELECT, WHERE, JOIN, etc.)
- [x] Tested queries to better understand table relationships
- [x] Built queries to answer the three questions
- [x] Added views to the database to refine queries
- [x] Connected Python code to the database using `psycopg2`, a PostgreSQL database adapter
- [x] Cleaned and edited code for readability
- [x] Packaged and submitted project for review
- [x] Received project feedback and committed changes as per reviewer
##### Sources
Udacity
|
b0d9f9444dbba5f0f5c08476d9c871ae18a4a3f7
|
[
"Markdown",
"Python"
] | 2
|
Python
|
coldice1915/logs-analysis
|
01f5c02bfd01eb04ce245292657618959638af5f
|
9ae61af92da7f718a316f4dc7df36cb2f3eac6b3
|
refs/heads/main
|
<repo_name>terrifricker/our-solar-system<file_sep>/client/src/App.js
import { BrowserRouter, Route, Switch } from "react-router-dom";
import { InfoPage } from "./components/InfoPage";
import { SolarSystem } from "./components/solar-system";
import { WebGLProvider } from "./contexts/WebGLContext";
function App() {
return (
<WebGLProvider>
<BrowserRouter>
<Switch>
<Route exact path="/" component={SolarSystem} />
<Route path="/info-page" component={InfoPage} />
</Switch>
</BrowserRouter>
</WebGLProvider>
);
}
export default App;
<file_sep>/backend/solarsystem/src/main/java/com/temocabl/solarsystem/ui/model/controller/IndexController.java
package com.temocabl.solarsystem.ui.model.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("solar")
public class IndexController {
@GetMapping("test")
public String test(){
return "this is test";
}
}
<file_sep>/client/src/components/solar-system/SolarSystem.js
// import { useEffect, useState } from "react";
// import { useWebGL } from "../../hooks/useWebGL";
// import { SolarSystem3D } from "./SolarSystem3D";
import { SolarSystem2D } from "./SolarSystem2D";
export const SolarSystem = () => {
// const [solarSystemUI, setSolarSystemUI] = useState(null);
// const isWebGLAvailable = useWebGL();
// useEffect(() => {
// if (isWebGLAvailable) {
// setSolarSystemUI(<SolarSystem3D />);
// } else {
// setSolarSystemUI(<SolarSystem2D />);
// }
// }, [isWebGLAvailable]);
return (
<>
<SolarSystem2D />
</>
);
};
<file_sep>/client/src/components/InfoPage.js
import { useEffect, useState } from "react";
import { isWebGLAvailable } from "../utils/3D";
import { getPlanet } from "./planets";
import { useQuery } from "../hooks/useQuery";
import { Sun } from "./Sun";
import "../css/InfoPage.css";
export const InfoPage = () => {
const [celestialBody, setCelestialBody] = useState(null);
const query = useQuery();
useEffect(() => {
if (isWebGLAvailable()) {
setCelestialBody(() => {
let querystring = query.get("planet"); // try to get a planet query
// if no planet query then try to get query for a star. i.e: sun
if (!querystring && (querystring = query.get("star"))) {
// when this block is run, then the query is for a star, the sun
return <Sun viewWidth={500} viewHeight={500} />;
}
// default component to earth
let PlanetComponent = getPlanet(querystring ?? "earth");
return <PlanetComponent viewWidth={500} viewHeight={500} />;
});
}
}, []);
return (
<main>
{celestialBody ?? (
<img
className="left-side"
src={`${process.env.REACT_APP_API_ENDPOINT}/resources/planet-photos/mercury.jpg`}
alt="Mercury against the
black of space. It is a medium gray with light-colored lines running primarily
north and south, but with white spots with those light-colored lines runnning
out away from the circle like the rays of the sun. These lines transverse the
north/south lines."
/>
)}
{/** information here can be dynamically fetched from an API */}
<section className="right-side">
<h1>Mercury</h1>
<article className="planet-facts planet-name" id="planet-name-facts">
<h2>Planet Facts</h2>
<div className="facts-container">
<ul>
<li>Distance from sun:</li>
<li>Diameter:</li>
<li>Length of year:</li>
<li>Length of day:</li>
<li>Average temperature:</li>
<li>Gravitational pull at surface:</li>
</ul>
</div>
</article>
<article className="planet-details plant-name" id="planet-name-details">
<h2>Planet Details</h2>
<div className="details-container">
<p>
Here are a few paragraphs about Mercury. Peace understanding
knowledge love smile happy puppy kitty action achievement
agreeable amazing adventure bountiful brave brilliant bubbles
bright color calm clean cheery certain constant creative
delightful energetic enthusiastic encouraging easy engaging
familiar fabulous fantastic friendly funny fresh genius giving
generous good glowing great green orange yellow blue purple pink
peach teal turquoise graceful.
</p>
<p>
Jolly joy kind laugh light lucky legendary marvelous meaningful
miraculous nice nurturing open optimistic pleasant progress
powerful plentiful productive successful protected endearing
protective quiet music quality refreshing rejoice reliable reward
remarkable skilled smiling sunny sparkling special superb secure
safe stupendous support terrific thriving thrilling tranquil
upbeat valued vibrant victory victorious welcome worthy yes yummy
zealous.
</p>
</div>
</article>
</section>
</main>
);
};
<file_sep>/client/src/utils/3D/Sphere.js
import * as THREE from "three";
/**
* @typedef SphereOptions
* @type {object}
* @property {string} mapURL
* @property {string} [bumpMapURL]
* @property {number} [bumpScale]
* @property {number} [radius]
* @property {number} [segmentsWidth]
* @property {number} [segmentsHeight]
* @property {boolean} [shinySurface]
* @property {number} [emissiveColorHex]
* @property {number} [emissiveIntensity]
* @property {string} [emissiveMapURL]
* @property {boolean} [transparent]
*/
/**
* @typedef AnimationCallback
* @type {(mesh: THREE.Mesh) => void}
*/
export class Sphere {
/**
* Creates a new Sphere.
* @param {SphereOptions} sphereOptions
*/
constructor(sphereOptions) {
let materialOptions = {
map: new THREE.TextureLoader().load(sphereOptions.mapURL),
};
if (typeof sphereOptions.bumpMapURL === "string") {
materialOptions.bumpMap = new THREE.TextureLoader().load(
sphereOptions.bumpMapURL
);
}
if (typeof sphereOptions.bumpScale === "number") {
materialOptions.bumpScale = sphereOptions.bumpScale;
}
if (typeof sphereOptions.emissiveColorHex === "number") {
materialOptions.emissive = new THREE.Color(
sphereOptions.emissiveColorHex
);
}
if (typeof sphereOptions.emissiveIntensity === "number") {
materialOptions.emissiveIntensity = sphereOptions.emissiveIntensity;
}
if (typeof sphereOptions.emissiveMapURL === "string") {
materialOptions.emissiveMap = new THREE.TextureLoader().load(
sphereOptions.emissiveMapURL
);
}
if (typeof sphereOptions.transparent === "boolean") {
materialOptions.transparent = sphereOptions.transparent;
}
this.mesh = new THREE.Mesh(
new THREE.SphereBufferGeometry(
sphereOptions.radius,
sphereOptions.segmentsWidth ?? 32,
sphereOptions.segmentsHeight ?? 32
),
sphereOptions.shinySurface
? new THREE.MeshPhongMaterial(materialOptions)
: new THREE.MeshLambertMaterial(materialOptions)
);
}
/**
* @param {AnimationCallback} animationCallback
*/
setAnimation(animationCallback) {
this._animationCallback = animationCallback;
}
animateNextFrame() {
if (!this._animationCallback) return;
this._animationCallback(this.mesh);
}
}
<file_sep>/client/src/hooks/useWebGL.js
import { useContext } from "react";
import { WebGLContext } from "../contexts/WebGLContext";
export const useWebGL = () => {
return useContext(WebGLContext);
};
<file_sep>/client/src/components/planets/Jupiter.js
import { kJupiterProps } from "../../utils/constants";
import { Planet } from "./Planet";
export const Jupiter = ({ viewWidth, viewHeight }) => {
const sceneOptions = {
orbitalControls: {
enable: true,
maxDistance: 10,
minDistance: 2,
},
};
const sphereOptions = {
mapURL: kJupiterProps.surfaceTexture,
};
const animation = (mesh) => {
mesh.rotation.y += kJupiterProps.rotation;
};
return (
<Planet
viewWidth={viewWidth}
viewHeight={viewHeight}
sceneOptions={sceneOptions}
sphereOptions={sphereOptions}
animation={animation}
/>
);
};
<file_sep>/client/src/contexts/WebGLContext.js
import { createContext, useRef } from "react";
import { WEBGL } from "three/examples/jsm/WebGL";
export const WebGLContext = createContext(false);
export const WebGLProvider = ({ children }) => {
const isWebGLAvailableRef = useRef(WEBGL.isWebGLAvailable());
return (
<WebGLContext.Provider value={isWebGLAvailableRef.current}>
{children}
</WebGLContext.Provider>
);
};
<file_sep>/README.md
# Our Solar System
### A collaboration by developers found around the world who found each other on Discord.
A website for learning about our solar system.
## How to use 3D planet components 🧐
```javascript
// component.js
// Assuming that this file is located at /client/src/components
import { Mercury } from "./components/planets";
const Component = () => {
return (
<div>
<Mercury viewWidth={500} viewHeight={500} />
</div>
);
};
```
## How to create a custom 3D planet or sphere component 🧐
```javascript
// Assuming this file is located at /client/src/components/planets
import { Sphere, Scene, Renderer } from "../../utils/3D";
import { useRef, useEffect } from "react";
// viewWidth and viewHeight are required props.
export const PlanetOrSphere = ({ viewWidth, viewHeight }) => {
const rendererRef = useRef(
new Renderer(viewWidth, viewHeight, { antialias: false })
);
const sceneRef = useRef(new Scene(rendererRef.current));
const sphereRef = useRef(
new Sphere({
mapURL: "url/to/map/texture", // this property is required. primary texture of the object.
bumpMapURL: "url/to/bump/map", // this property is optional.
bumpScale: 0.3, // this property is optional.
shinySurface: true, // this property is optional. however, for objects that uses has bumpMapURL set, this must be set to true.
})
);
const canvasRef = useRef(null);
useEffect(() => {
sphereRef.current.setAnimation(() => {
// Sets the animation controller.
// For each frame, this function will be invoked.
sphereRef.current.mesh.rotation.y += 0.0015; // Rotate around the y-axis counter-clockwise.
});
// Multiple objects can be added to the scene.
// The value can be a single Sphere or an array of Spheres.
sceneRef.current.add(sphereRef.current);
// Setting the camera position is very important.
// By default the camera appears at position (0, 0, 0).
// If the camera is not position right, nothing can be seen.
sceneRef.current.positionCamera(0, 0, 3); // x, y, z
// Lighting for the scene.
// For now, there are only two types, ambient and point.
// Ambient light, as the name suggest it is an ambient light.
// Point light, is a 360 degrees light source. Much like how to sun emits light.
sceneRef.current.setAmbientLight(0xffffff, 0.2);
sceneRef.current.setPointLight(0xffffff, 1, { x: 5, y: 3, z: 5 });
// The generated model have to be attached to some sort of DOM element.
rendererRef.current.attachTo(canvasRef.current);
// This will start the animation sequence.
// If no animation was set, then it will just render the same frame over and over.
sceneRef.current.animate();
}, []);
return <div ref={canvasRef}></div>;
};
```
<file_sep>/client/src/components/planets/Uranus.js
import { kUranusProps } from "../../utils/constants";
import { Planet } from "./Planet";
import * as THREE from "three";
export const Uranus = ({ viewWidth, viewHeight }) => {
const sceneOptions = {
orbitalControls: {
enable: true,
maxDistance: 10,
minDistance: 2,
},
};
const sphereOptions = {
mapURL: kUranusProps.surfaceTexture,
};
let innerRadius = 2;
let outerRadius = innerRadius + 0.7;
let ringGeometry = new THREE.RingGeometry(innerRadius, outerRadius, 128);
let pos = ringGeometry.attributes.position;
let v3 = new THREE.Vector3();
for (let i = 0; i < pos.count; i++) {
v3.fromBufferAttribute(pos, i);
ringGeometry.attributes.uv.setXY(
i,
v3.length() < (innerRadius + outerRadius) / 2 ? 0 : 1,
1
);
}
let ring = new THREE.Mesh(
ringGeometry,
new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load(kUranusProps.ringTexture),
transparent: true,
alphaMap: new THREE.TextureLoader().load(kUranusProps.ringTransTexture),
side: THREE.DoubleSide,
})
);
ring.rotation.x = 1;
// mock a sphere
// by default what should be passed to the Planet component should be
// an instance of Sphere, but we created a native THREE.Mesh instance
// hence, there are additional method and property that are not available.
// since everything in js is an object, we can just create an object with the
// missing property and method, hence, we mock a Sphere instance.
let mockSphere = {
mesh: ring,
animateNextFrame: () => {},
};
const animation = (mesh) => {
mesh.rotation.y += kUranusProps.rotation;
};
return (
<Planet
viewWidth={viewWidth}
viewHeight={viewHeight}
sceneOptions={sceneOptions}
sphereOptions={sphereOptions}
animation={animation}
layers={[mockSphere]}
/>
);
};
<file_sep>/client/src/utils/3D/index.js
import { Renderer } from "./Renderer";
import { Scene } from "./Scene";
import { Sphere } from "./Sphere";
import { WEBGL } from "three/examples/jsm/WebGL";
function isWebGLAvailable() {
return WEBGL.isWebGLAvailable();
}
export { Sphere, Scene, Renderer, isWebGLAvailable };
<file_sep>/client/src/components/solar-system/SolarSystem3D.js
import { useEffect, useRef, useState } from "react";
import { useWebGL } from "../../hooks/useWebGL";
import { Scene, Renderer, Sphere } from "../../utils/3D";
import { kCelestialBodies } from "../../utils/constants";
import * as THREE from "three";
import "../../css/SolarSystem3D.css";
export const SolarSystem3D = () => {
const [loading, setLoading] = useState(false);
// this is where the whole scene will be attached to.
const canvasRef = useRef(null);
const rendererRef = useRef(
new Renderer(window.innerWidth, window.innerHeight, {
antialias: false,
alpha: true,
})
);
const sceneRef = useRef(new Scene(rendererRef.current));
// /**
// * To add intellisense
// * @type {MutableRefObject<Map<string, Sphere>>}
// */
// const celestialBodiesRef = useRef(new Map());
const isWebGLAvailable = useWebGL();
const buildSun = async () => {
let sun = new Sphere({
mapURL: kCelestialBodies.Sun.surfaceTexture,
radius: kCelestialBodies.Sun.radius,
segmentsHeight: 64,
segmentsWidth: 64,
shinySurface: true,
emissiveColorHex: 0xffffff,
emissiveIntensity: 1,
emissiveMapURL: kCelestialBodies.Sun.surfaceTexture,
});
sun.setAnimation((mesh) => {
mesh.rotation.y += kCelestialBodies.Sun.rotation;
});
sun.mesh.position.set(-20, 0, 0);
// celestialBodiesRef.current.set("sun", sun);
sceneRef.current.add(sun);
// light is added here since the sun is the only light source in the scene.
sceneRef.current.setAmbientLight(0xffffff, 0.3);
sceneRef.current.setPointLight(0xffffff, 1, { x: -18, y: 0, z: 0 });
};
const buildMercury = async () => {
let mercury = new Sphere({
mapURL: kCelestialBodies.Mercury.surfaceTexture,
bumpMapURL: kCelestialBodies.Mercury.bumpMapTexture,
bumpScale: 0.1,
shinySurface: true,
radius: kCelestialBodies.Mercury.radius,
});
mercury.setAnimation((mesh) => {
mesh.rotation.y += kCelestialBodies.Mercury.rotation;
});
mercury.mesh.position.set(-15, 0, 0);
// celestialBodiesRef.current.set("mercury", mercury);
sceneRef.current.add(mercury);
};
const buildVenus = async () => {
let venus = new Sphere({
mapURL: kCelestialBodies.Venus.surfaceTexture,
radius: kCelestialBodies.Venus.radius,
shinySurface: true,
});
venus.setAnimation((mesh) => {
mesh.rotation.y += kCelestialBodies.Venus.rotation;
});
venus.mesh.position.set(-12, 0, 0);
sceneRef.current.add(venus);
};
const buildEarth = async () => {
let earth = new Sphere({
mapURL: kCelestialBodies.Earth.surfaceTexture,
bumpMapURL: kCelestialBodies.Earth.bumpMapTexture,
bumpScale: 0.1,
shinySurface: true,
radius: kCelestialBodies.Earth.radius,
});
let clouds = new Sphere({
mapURL: kCelestialBodies.Earth.cloudsTexture,
radius: kCelestialBodies.Earth.radius + 0.03,
transparent: true,
});
earth.setAnimation((mesh) => {
mesh.rotation.y += kCelestialBodies.Earth.rotation;
});
clouds.setAnimation((mesh) => {
// rotate 10% slower than the Earth
mesh.rotation.y += kCelestialBodies.Earth.rotation * 0.9;
});
earth.mesh.position.set(-8.5, 0, 0);
clouds.mesh.position.set(-8.5, 0, 0);
sceneRef.current.add(earth, clouds);
};
const buildMars = async () => {
let mars = new Sphere({
mapURL: kCelestialBodies.Mars.surfaceTexture,
bumpMapURL: kCelestialBodies.Mars.bumpMapTexture,
bumpScale: 0.1,
shinySurface: true,
radius: kCelestialBodies.Mars.radius,
});
mars.setAnimation((mesh) => {
mesh.rotation.y += kCelestialBodies.Mars.rotation;
});
mars.mesh.position.set(-5, 0, 0);
sceneRef.current.add(mars);
};
const buildJupiter = async () => {
let jupiter = new Sphere({
mapURL: kCelestialBodies.Jupiter.surfaceTexture,
radius: kCelestialBodies.Jupiter.radius,
});
jupiter.setAnimation((mesh) => {
mesh.rotation.y += kCelestialBodies.Jupiter.rotation;
});
sceneRef.current.add(jupiter);
};
const buildSaturn = async () => {
let saturn = new Sphere({
mapURL: kCelestialBodies.Saturn.surfaceTexture,
radius: kCelestialBodies.Saturn.radius,
});
saturn.setAnimation((mesh) => {
mesh.rotation.y += kCelestialBodies.Saturn.rotation;
});
let innerRadius = kCelestialBodies.Saturn.radius + 0.01;
let outerRadius = kCelestialBodies.Saturn.radius + 3;
let ringGeometry = new THREE.RingGeometry(innerRadius, outerRadius, 64);
let pos = ringGeometry.attributes.position;
let v3 = new THREE.Vector3();
for (let i = 0; i < pos.count; i++) {
v3.fromBufferAttribute(pos, i);
ringGeometry.attributes.uv.setXY(
i,
v3.length() < (innerRadius + outerRadius) / 2 ? 0 : 1,
1
);
}
let ring = new THREE.Mesh(
ringGeometry,
new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load(
kCelestialBodies.Saturn.ringTexture
),
transparent: true,
side: THREE.DoubleSide,
})
);
ring.rotation.x = 1.3;
ring.rotation.y = 1;
saturn.mesh.position.set(6, 0, 0);
ring.position.set(6, 0, 0);
sceneRef.current.add(saturn);
// adding it this way because the ring is not a sphere instance hence
// it does not have the animateNextFrame method defined by me(canttell).
sceneRef.current._scene.add(ring);
};
const buildUranus = async () => {
let uranus = new Sphere({
mapURL: kCelestialBodies.Uranus.surfaceTexture,
radius: kCelestialBodies.Uranus.radius,
});
uranus.setAnimation((mesh) => {
mesh.rotation.y += kCelestialBodies.Uranus.rotation;
});
let innerRadius = kCelestialBodies.Uranus.radius + 1;
let outerRadius = kCelestialBodies.Uranus.radius + 1.05;
let ring = new THREE.Mesh(
new THREE.RingGeometry(innerRadius, outerRadius, 128),
new THREE.MeshBasicMaterial({
color: 0xffffff,
})
);
ring.rotation.x = 1;
uranus.mesh.position.set(12, 0, 0);
ring.position.set(12, 0, 0);
sceneRef.current.add(uranus);
// this ring 3d object is not an instance of Sphere
// so to added to the scene is the only way.
sceneRef.current._scene.add(ring);
};
const buildNeptune = async () => {
let neptune = new Sphere({
mapURL: kCelestialBodies.Neptune.surfaceTexture,
radius: kCelestialBodies.Neptune.radius,
});
neptune.setAnimation((mesh) => {
mesh.rotation.y += kCelestialBodies.Neptune.rotation;
});
neptune.mesh.position.set(19, 0, 0);
sceneRef.current.add(neptune);
};
const buildSolarSystem = () => {
let promises = [
buildSun(),
buildMercury(),
buildVenus(),
buildEarth(),
buildMars(),
buildJupiter(),
buildSaturn(),
buildUranus(),
buildNeptune(),
];
return Promise.all(promises);
};
// this function will run when the component is mounted
useEffect(() => {
// toggle loading screen/animation
setLoading(true);
/**
* Although the availability of webGL is checked
* in the parent component, SolarSystem, this is just to
* ensure when this component is used alone in other components
* will work as expected.
*/
if (isWebGLAvailable) {
// create all celestial bodies
// start with the sun
buildSolarSystem()
.then(() => {
setLoading(false);
// transparent background
rendererRef.current._renderer.setClearColor(0xffffff, 0);
rendererRef.current.attachTo(canvasRef.current);
sceneRef.current.positionCamera(0, 0, 20);
sceneRef.current.animate();
})
.catch(console.error);
} else {
console.error("WebGL is not available.");
setLoading(false);
}
}, [isWebGLAvailable]);
if (loading) {
return <div>Loading...</div>;
}
return (
<section className="solar-system-3d">
<h1 className="title">
<span>Our Solar System</span>
<img
src={`${process.env.REACT_APP_API_ENDPOINT}/resources/fallback-icons/orbit.png`}
alt="Orbit"
/>
</h1>
<div id="threeModel" ref={canvasRef}>
{/**
* here is where the solar system scene will be rendered.
*/}
</div>
</section>
);
};
<file_sep>/backend/nodejs-server/README.md
# Temporal NodeJS HTTP Server
This server is used temprarily to serve static assets, such as images and textures.
# Scripts
## `npm install`
This command will install all the dependencies.
## `npm start`
This will start the server.
## `npm run dev`
This will run the development server.
<file_sep>/client/src/components/planets/Planet.js
/**
* Base component for all planet components.
*/
import { Renderer, Scene, Sphere } from "../../utils/3D";
import { useRef, useEffect } from "react";
import { AnimationCallback, SphereOptions } from "../../utils/3D/Sphere";
import { SceneOptions } from "../../utils/3D/Scene";
import { nanoid } from "nanoid";
/**
* @typedef PlanetProps
* @type {object}
* @property {number} viewWidth
* @property {number} viewHeight
* @property {AnimationCallback} animation
* @property {SceneOptions} sceneOptions
* @property {SphereOptions} sphereOptions
* @property {string} id
* @property {Sphere[]} layers
*/
/**
*
* @param {PlanetProps} props
*/
export const Planet = ({
viewWidth,
viewHeight,
animation,
sceneOptions,
sphereOptions,
id,
layers,
}) => {
// todo: add tilt option, as in the earth is tilted`
// todo: add rotate around the planet's axis instead of the world axis
const rendererRef = useRef(
new Renderer(viewWidth, viewHeight, { antialias: false })
);
const sceneRef = useRef(new Scene(rendererRef.current, sceneOptions));
const sphereRef = useRef(new Sphere(sphereOptions));
const canvasRef = useRef(null);
useEffect(() => {
sphereRef.current.setAnimation(animation);
sceneRef.current.add(sphereRef.current);
if (layers && layers.length) {
for (let layer of layers) {
sceneRef.current.add(layer);
}
}
sceneRef.current.positionCamera(0, 0, 3);
sceneRef.current.setAmbientLight(0xffffff, 0.2);
sceneRef.current.setPointLight(0xffffff, 1, { x: 5, y: 3, z: 5 });
rendererRef.current.attachTo(canvasRef.current);
sceneRef.current.animate();
}, []);
return <div ref={canvasRef} id={id ?? nanoid()}></div>;
};
<file_sep>/backend/solarsystem/src/main/resources/application.properties
server.port=3200
spring.mvc.static-path-pattern=/resources/**<file_sep>/backend/solarsystem/src/main/java/com/temocabl/solarsystem/ui/model/response/LoginResponseModel.java
package com.temocabl.solarsystem.ui.model.response;
public class LoginResponseModel {
}
<file_sep>/client/src/utils/3D/Scene.js
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import Stats from "three/examples/jsm/libs/stats.module";
/**
* @typedef DebugOptions
* @type {object}
* @property {boolean} [axis]
* @property {number} [axisSize]
* @property {boolean} [stats]
*/
/**
* @typedef OrbitalControlsOptions
* @type {object}
* @property {boolean} [enable]
* @property {number} [maxDistance]
* @property {number} [minDistance]
* @property {number} [maxZoom]
* @property {number} [minZoom]
*/
/**
* @typedef SceneOptions
* @type {object}
* @property {DebugOptions} [debug]
* @property {OrbitalControlsOptions} [orbitalControls]
*/
export class Scene {
/**
* Creates a new scene where 3D objects can be displayed.
* @param {import("./Renderer").Renderer} renderer
* @param {SceneOptions} [options]
*/
constructor(renderer, options) {
/**
* @type {import("./Renderer").Renderer}
*/
this._renderer = renderer;
/**
* @type {THREE.Scene}
*/
this._scene = new THREE.Scene();
/**
* @type {THREE.PerspectiveCamera}
*/
this._camera = new THREE.PerspectiveCamera(
60,
this._renderer.aspectRatio,
0.1,
1000
);
/**
* @type {import("./Sphere").Sphere[]}
*/
this._spheres = [];
options = Object.assign(
{
debug: { axis: false, axisSize: 10, stats: false },
orbitalControls: {
enable: true,
maxDistance: Infinity,
minDistance: 0,
maxZoom: Infinity,
minZoom: 0,
},
},
options
);
this._debugHelpers = {
axis: options.debug.axis
? new THREE.AxesHelper(options.debug.axisSize)
: null,
stats: options.debug.stats ? Stats() : null,
};
if (options.debug) {
if (options.debug.axis) {
this._scene.add(this._debugHelpers.axis);
}
if (options.debug.stats) {
document.body.appendChild(this._debugHelpers.stats.domElement);
}
}
if (options.orbitalControls.enable) {
// 💩 code
this._controls = new OrbitControls(
this._camera,
this._renderer._renderer.domElement
);
Object.assign(this._controls, options.orbitalControls);
}
}
/**
*
* @param {import("./Sphere").Sphere[]} spheres
*/
add(...spheres) {
spheres.forEach((sphere) => {
this._spheres.push(sphere);
this._scene.add(sphere.mesh);
});
}
/**
*
* @param {number} x
* @param {number} y
* @param {number} z
*/
positionCamera(x, y, z) {
this._camera.position.set(x, y, z);
}
/**
*
* @param {number} color hexadecial number, i.e: 0xffffff -> white
* @param {number} intensity number between 0 and 1.
*/
setAmbientLight(color, intensity) {
let ambientLight = new THREE.AmbientLight(color, intensity);
this._scene.add(ambientLight);
}
/**
* @param {number} color hexadecial number, i.e: 0xffffff -> white
* @param {number} intensity number between 0 and 1.
* @param {object} [position] the position of the point light.
* @param {number} [position.x]
* @param {number} [position.y]
* @param {number} [position.z]
*/
setPointLight(color, intensity, position = { x: 0, y: 0, z: 0 }) {
let pointLight = new THREE.PointLight(color, intensity);
pointLight.position.set(position.x, position.y, position.z);
this._scene.add(pointLight);
}
/**
* Starts animation sequence.
*/
animate() {
window.requestAnimationFrame(this.animate.bind(this));
for (let sphere of this._spheres) {
sphere.animateNextFrame();
}
this._renderer._render(this._scene, this._camera);
if (this._debugHelpers.stats) this._debugHelpers.stats.update();
}
}
<file_sep>/client/src/components/Sun.js
import { Planet } from "./planets/Planet";
import { kSunProps } from "../utils/constants";
export const Sun = ({ viewWidth, viewHeight }) => {
const sceneOptions = {
orbitalControls: {
enable: true,
maxDistance: 10,
minDistance: 2,
},
};
const sphereOptions = {
mapURL: kSunProps.surfaceTexture,
shinySurface: true,
};
const animation = (mesh) => {
mesh.rotation.y += kSunProps.rotation;
};
return (
<Planet
viewWidth={viewWidth}
viewHeight={viewHeight}
sceneOptions={sceneOptions}
sphereOptions={sphereOptions}
animation={animation}
/>
);
};
<file_sep>/docs/Contributions.md
# Contribution Guidelines
## Table of Content
- [Git Commands](#git-commands)
## Git Commands
### Add one file to the working tree
`git add /path/of/file/to/add`
### Add all files to the working tree
`git add .`
### Commit changes
`git commit -m "commit message"`
### Fetch lastest changes and heads from remote repository
`git fetch <remote>`, where `<remote>` can be empty if `origin` was configured or another remote repository to fetch from.
### Fetch and merge lastest changes
`git pull <remote> <branch-name>`, where `<remote>` can be empty if `origin` was configured or another remote repository and `<branch-name>` is the branch to fetch from.
### Get list of branches
`git branch`
### Create new local branch
`git branch <branch-name>`, where `<branch-name>` can be any non-existent name.
### Delete local branch
`git branch -d <branch-name>`
### Delete local branch by force
`git branch -D <branch-name>`
### Delete remote branch
`git push -d <remote> <branch-name>`, where `<remote>` is the remote repository.
### Switch branch
`git checkout <branch-name>`
### Switch and create new branch
`git checkout -b <branch-name>`
### Merge local branches
The below shows an example of how this is usually done.
```bash
// move from branch2 -> main
git checkout main
git merge branch2
```
### Push changes
`git push <remote> <branch-name>`, where `<remote>` is the repository name and `<branch-name>` is the branch name to be pushed.
### Setup push upstream
`git push -u <remote> <branch-name>`, where `<remote>` is the repository name and `<branch-name>` is the branch name to be pushed.
### Create version tag
`git tag <tag-name>`, where `<tag-name>` is usually a version such as `v1.0.0`.
### Push tag to remote repository
`git push --tags <remote>`
### Add remote repository
`git remote add <remote> <remote-url>`, where `<remote>` is the name given and `<remote-url>` is the url used to clone the repository.
### Remove remote repository
`git remote remove <remote>`
### Check remote repository list
`git remote -v` verbose mode. All URLs and names will be logged in the console.
`git remote` Only the remote repository names will be logged in the console.
<file_sep>/client/src/utils/constants.js
// celestial bodies rotation speed
// negative -> clockwise
// positive -> counter clockwise
export const kSunRotationSpeed = 0.0001;
export const kVenusRotationSpeed = -0.008;
export const kMercuryRotationSpeed = 0.005;
export const kEarthRotationSpeed = 0.0015;
export const kMarsRotationSpeed = 0.0015;
export const kJupiterRotationSpeed = 0.0006;
export const kSaturnRotationSpeed = 0.00066;
export const kUranusRotationSpeed = -0.001;
export const kNeptuneRotationSpeed = 0.001;
// celestial bodies radius
export const kSunRadius = 3;
export const kVenusRadius = 0.9;
export const kMercuryRadius = 0.4;
export const kEarthRadius = 1;
export const kMarsRadius = 1;
export const kJupiterRadius = 2.5;
export const kSaturnRadius = 2.3;
export const kUranusRadius = 2;
export const kNeptuneRadius = 1.95;
// celestial bodies textures urls
export const kSunSurfaceTexture = `${process.env.REACT_APP_API_ENDPOINT}/resources/textures/sun-surface.jpeg`;
export const kMercurySurfaceTexture = `${process.env.REACT_APP_API_ENDPOINT}/resources/textures/mercury-surface.jpg`;
export const kMercuryBumpMapTexture = `${process.env.REACT_APP_API_ENDPOINT}/resources/textures/mercury-bump-map.jpg`;
export const kVenusSurfaceTexture = `${process.env.REACT_APP_API_ENDPOINT}/resources/textures/venus-surface.jpeg`;
export const kEarthSurfaceTexture = `${process.env.REACT_APP_API_ENDPOINT}/resources/textures/earth-surface.jpeg`;
export const kEarthBumpMapTexture = `${process.env.REACT_APP_API_ENDPOINT}/resources/textures/earth-bump-map.jpeg`;
export const kEarthCloudsTexture = `${process.env.REACT_APP_API_ENDPOINT}/resources/textures/earth-clouds.png`;
export const kMarsSurfaceTexture = `${process.env.REACT_APP_API_ENDPOINT}/resources/textures/mars-surface.jpeg`;
export const kMarsBumpMapTexture = `${process.env.REACT_APP_API_ENDPOINT}/resources/textures/mars-bump-map.png`;
export const kJupiterSurfaceTexture = `${process.env.REACT_APP_API_ENDPOINT}/resources/textures/jupiter-surface.jpeg`;
export const kSaturnSurfaceTexture = `${process.env.REACT_APP_API_ENDPOINT}/resources/textures/saturn-surface.jpeg`;
export const kSaturnRingTexture = `${process.env.REACT_APP_API_ENDPOINT}/resources/textures/saturn-ring.png`;
export const kUranusSurfaceTexture = `${process.env.REACT_APP_API_ENDPOINT}/resources/textures/uranus-surface.jpeg`;
export const kUranusRingTexture = `${process.env.REACT_APP_API_ENDPOINT}/resources/textures/uranus-ring.jpg`;
export const kUranusRingTransTexture = `${process.env.REACT_APP_API_ENDPOINT}/resources/textures/uranus-ring-trans-map.gif`;
export const kNeptuneSurfaceTexture = `${process.env.REACT_APP_API_ENDPOINT}/resources/textures/neptune-surface.jpeg`;
// compilation of props for each celestial body
export const kSunProps = {
radius: kSunRadius,
rotation: kSunRotationSpeed,
surfaceTexture: kSunSurfaceTexture,
};
export const kMercuryProps = {
radius: kMercuryRadius,
rotation: kMercuryRotationSpeed,
surfaceTexture: kMercurySurfaceTexture,
bumpMapTexture: kMercuryBumpMapTexture,
};
export const kVenusProps = {
radius: kVenusRadius,
rotation: kVenusRotationSpeed,
surfaceTexture: kVenusSurfaceTexture,
};
export const kEarthProps = {
radius: kEarthRadius,
rotation: kEarthRotationSpeed,
surfaceTexture: kEarthSurfaceTexture,
bumpMapTexture: kEarthBumpMapTexture,
cloudsTexture: kEarthCloudsTexture,
};
export const kMarsProps = {
radius: kMarsRadius,
rotation: kMarsRotationSpeed,
surfaceTexture: kMarsSurfaceTexture,
bumpMapTexture: kMarsBumpMapTexture,
};
export const kJupiterProps = {
radius: kJupiterRadius,
rotation: kJupiterRotationSpeed,
surfaceTexture: kJupiterSurfaceTexture,
};
export const kSaturnProps = {
radius: kSaturnRadius,
rotation: kSaturnRotationSpeed,
surfaceTexture: kSaturnSurfaceTexture,
ringTexture: kSaturnRingTexture,
};
export const kUranusProps = {
radius: kUranusRadius,
rotation: kUranusRotationSpeed,
surfaceTexture: kUranusSurfaceTexture,
ringTexture: kUranusRingTexture,
ringTransTexture: kUranusRingTransTexture,
};
export const kNeptuneProps = {
radius: kNeptuneRadius,
rotation: kNeptuneRotationSpeed,
surfaceTexture: kNeptuneSurfaceTexture,
};
// all in one celestial bodies props
export const kCelestialBodies = {
Sun: kSunProps,
Mercury: kMercuryProps,
Venus: kVenusProps,
Earth: kEarthProps,
Mars: kMarsProps,
Jupiter: kJupiterProps,
Saturn: kSaturnProps,
Uranus: kUranusProps,
Neptune: kNeptuneProps,
};
<file_sep>/client/src/utils/3D/Renderer.js
import * as THREE from "three";
export class Renderer {
/**
* Creates a new renderer for 3D objects.
* @param {number} viewWidth
* @param {number} viewHeight
* @param {THREE.WebGLRendererParameters} [rendererOptions]
*/
constructor(viewWidth, viewHeight, rendererOptions = {}) {
this._renderer = new THREE.WebGLRenderer(rendererOptions);
this._renderer.setSize(viewWidth, viewHeight);
this._renderer.setPixelRatio(viewWidth / viewHeight);
this.pixelRatio = viewWidth / viewHeight;
this.aspectRatio = viewWidth / viewHeight;
}
/**
* Resizes the canvas.
* @param {number} width
* @param {number} height
*/
resize(width, height) {
this._renderer.setSize(width, height);
}
/**
* Attaches the canvas to an element in the DOM.
* @param {HTMLElement} element
*/
attachTo(element) {
element.appendChild(this._renderer.domElement);
}
/**
* This method is used internally by the Scene class.
* @param {THREE.Object3D} scene
* @param {THREE.Camera} camera
*/
_render(scene, camera) {
this._renderer.render(scene, camera);
}
}
<file_sep>/client/src/components/planets/index.js
import { Mercury } from "./Mercury";
import { Venus } from "./Venus";
import { Earth } from "./Earth";
import { Mars } from "./Mars";
import { Jupiter } from "./Jupiter";
import { Saturn } from "./Saturn";
import { Uranus } from "./Uranus";
import { Neptune } from "./Neptune";
export const Planets = {
mercury: Mercury,
venus: Venus,
earth: Earth,
mars: Mars,
jupiter: Jupiter,
saturn: Saturn,
uranus: Uranus,
neptune: Neptune,
};
/**
*
* @param {string} name
*/
export function getPlanet(name) {
return Planets[name.toLowerCase()];
}
export { Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune };
|
57775b095bea8a73972eef43ffc0d522b8a7850d
|
[
"JavaScript",
"Java",
"Markdown",
"INI"
] | 22
|
JavaScript
|
terrifricker/our-solar-system
|
6f42736ec636841117eea8e014dc993adf445388
|
791bd84f250b12bc7a5a9b33233c47566dd06498
|
refs/heads/main
|
<file_sep>using UnityEngine;
namespace Puzzle2DSystem
{
public abstract class PuzzleDataVisualizer
{
public GameObject[] PuzzlePieces { get; protected set; }
public abstract void SetPuzzleData(PuzzleData data);
public abstract GameObject CreateBoardVisual();
public abstract GameObject[] CreatePuzzlePiecesVisual();
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Puzzle2DSystem
{
public class PuzzleDataController
{
public PuzzleData PuzzleData { get; private set; }
List<TriangleData> allTriangles = new List<TriangleData>();
List<TriangleData> availableTriangles = new List<TriangleData>();
int maxPuzzlePieceCount;
int maxTriangleCount;
public PuzzleDataController(int boardSize, int puzzlePieceCount)
{
PuzzleData = new PuzzleData();
PuzzleData.PuzzleBoard = new PuzzleBoard(boardSize);
this.maxPuzzlePieceCount = puzzlePieceCount;
this.maxTriangleCount = boardSize * boardSize;
PuzzleData.PuzzlePieces = new List<PuzzlePiece>();
foreach (var contactPoint in PuzzleData.PuzzleBoard.ContactPoints)
{
allTriangles.AddRange(contactPoint.Triangles);
}
CreateMainPuzzlePieces(puzzlePieceCount);
AssignRestOfTheLeftAvailableTrianglesToPuzzlePiece();
}
void CreateMainPuzzlePieces(int puzzlePieceCount)
{
availableTriangles = allTriangles;
var triangles = availableTriangles.ToArray();
foreach (var triangle in triangles)
{
triangle.SetMyNeighbours(triangles);
}
//Extra 25 try for if piece is too small.
for (int i = 0; i < puzzlePieceCount + 25; i++)
{
if (PuzzleData.PuzzlePieces.Count >= puzzlePieceCount)
break;
CreatePuzzlePiece();
}
}
void CreatePuzzlePiece()
{
if (availableTriangles.Count == 0)
return;
ReOrderAvailableTriangles();
int index = -1;
for (int i = 0; i < availableTriangles.Count; i++)
{
if(availableTriangles[i].GetAvailableNeighbours().Count>0)
{
index = i;
break;
}
}
if (index == -1)
return;
List<TriangleData> triangleDatas = new List<TriangleData>();
triangleDatas.Add(availableTriangles[index]);
var randomNeighbour = triangleDatas[0].GetRandomAvailableNeighbour();
for (int i = 0; i < maxTriangleCount; i++)
{
randomNeighbour = triangleDatas[i].GetRandomAvailableNeighbour();
if (randomNeighbour == null)
break;
triangleDatas.Add(randomNeighbour);
}
if(triangleDatas.Count > PuzzleData.PuzzleBoard.BoardSize)
{
triangleDatas.ForEach(t => availableTriangles.Remove(t));
var puzzlePiece = new PuzzlePiece(triangleDatas);
PuzzleData.PuzzlePieces.Add(puzzlePiece);
}
}
void AssignRestOfTheLeftAvailableTrianglesToPuzzlePiece()
{
while(availableTriangles.Count>0)
{
AssignLeftAvailableTrianglesToTheSmallestAvailablePuzzlePiece();
}
}
void AssignLeftAvailableTrianglesToTheSmallestAvailablePuzzlePiece()
{
if (availableTriangles.Count == 0)
return;
ReOrderAvailableTriangles();
int index = -1;
for (int i = 0; i < availableTriangles.Count; i++)
{
if (availableTriangles[i].GetNeighboursWithOwners().Count > 0)
{
index = i;
break;
}
}
if (index == -1)
return;
var neighbourOwners = availableTriangles[index].GetNeighbourOwners().OrderBy(owner => owner.TriangleDatas.Count()).ToList();
AddTriangleToPuzzlePiece(availableTriangles[index], neighbourOwners[0]);
}
private void ReOrderAvailableTriangles()
{
availableTriangles = availableTriangles.OrderBy(a => Guid.NewGuid()).ToList();
}
void AddTriangleToPuzzlePiece(TriangleData triangleData,PuzzlePiece puzzlePiece)
{
puzzlePiece.AddTriangle(triangleData);
availableTriangles.Remove(triangleData);
}
}
}<file_sep>using System;
using System.Collections.Generic;
namespace Puzzle2DSystem
{
[Serializable]
public class PuzzleData
{
public PuzzleBoard PuzzleBoard;
public List<PuzzlePiece> PuzzlePieces;
}
}<file_sep>using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Puzzle2DSystem
{
[System.Serializable]
public class TriangleData
{
public ContactPoint ContactPoint { get; }
public Vector2 Center { get; }
public Vector2[] Points { get; }
public TriangleData[] Neighbours { get; private set; }
public PuzzlePiece Owner;
public TriangleData(ContactPoint contactPoint, Vector2[] points)
{
ContactPoint = contactPoint;
Points = points;
if(Points.Length>0)
{
Center = Vector2.zero;
for (int i = 0; i < Points.Length; i++)
{
Center += Points[i];
}
Center /= Points.Length;
}
}
public void SetMyNeighbours(TriangleData[] neighbourCandidates)
{
List<TriangleData> neighbours = new List<TriangleData>();
foreach (var candidate in neighbourCandidates)
{
if (IsMyNeighbour(candidate))
neighbours.Add(candidate);
}
Neighbours = neighbours.ToArray();
}
public List<TriangleData> GetAvailableNeighbours()
{
var availableNeighbours = new List<TriangleData>();
foreach (var neighbour in Neighbours)
{
if (neighbour.Owner == null)
availableNeighbours.Add(neighbour);
}
return availableNeighbours;
}
public List<TriangleData> GetNeighboursWithOwners()
{
var neighboursWithOwners = Neighbours.ToList();
GetAvailableNeighbours().ForEach(n => neighboursWithOwners.Remove(n));
return neighboursWithOwners;
}
public List<PuzzlePiece> GetNeighbourOwners()
{
var neighboursWithOwners = GetNeighboursWithOwners();
List<PuzzlePiece> owners= new List<PuzzlePiece>();
for (int i = 0; i < neighboursWithOwners.Count; i++)
{
var owner = neighboursWithOwners[i].Owner;
if (!owners.Contains(owner))
owners.Add(owner);
}
return owners;
}
public TriangleData GetRandomAvailableNeighbour()
{
TriangleData randomNeighbour = null;
var availableNeighbours = GetAvailableNeighbours();
if (availableNeighbours.Count > 0)
randomNeighbour = availableNeighbours[Random.Range(0, availableNeighbours.Count)];
return randomNeighbour;
}
bool IsMyNeighbour(TriangleData neighbourCandidate)
{
int commonPointCount = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (Points[i] == neighbourCandidate.Points[j])
{
commonPointCount++;
break;
}
}
}
return commonPointCount == 2;
}
}
}<file_sep># Block-Puzzle-2D-Prototype
Block Puzzle 2D Prototype
<file_sep>using System.Collections.Generic;
using UnityEngine;
namespace Puzzle2DSystem
{
[System.Serializable]
public class PuzzlePiece
{
public List<TriangleData> TriangleDatas { get; private set; }
public List<ContactPoint> ContactPoints { get; private set; }
public Vector2 Center { get; private set; }
public PuzzlePiece(List<TriangleData> triangleDatas)
{
TriangleDatas = new List<TriangleData>();
ContactPoints = new List<ContactPoint>();
foreach (var triangleData in triangleDatas)
{
AddTriangle(triangleData);
}
}
public void AddTriangle(TriangleData triangleData)
{
triangleData.Owner = this;
TriangleDatas.Add(triangleData);
if (!ContactPoints.Contains(triangleData.ContactPoint))
ContactPoints.Add(triangleData.ContactPoint);
CalculateCenter();
}
void CalculateCenter()
{
Center = Vector2.zero;
TriangleDatas.ForEach(t => Center += t.Center);
Center /= TriangleDatas.Count;
}
}
}<file_sep>using UnityEngine;
namespace Puzzle2DSystem
{
public class PuzzleDataCreator
{
int minBoardSize;
int maxBoardSize;
int minPuzzlePieceCount;
int maxPuzzlePieceCount;
public PuzzleDataCreator (int minBoardSize=4, int maxBoardSize=6, int minPuzzlePieceCount = 5, int maxPuzzlePieceCount = 12)
{
this.minBoardSize = minBoardSize;
this.maxBoardSize = maxBoardSize;
this.minPuzzlePieceCount = minPuzzlePieceCount;
this.maxPuzzlePieceCount = maxPuzzlePieceCount;
}
public PuzzleData GetRandomPuzzleData()
{
return GetRandomPuzzleDataController().PuzzleData;
}
PuzzleDataController GetRandomPuzzleDataController()
{
int boardSize = Random.Range(minBoardSize, maxBoardSize + 1);
int pieceCount = Random.Range(minPuzzlePieceCount, maxPuzzlePieceCount + 1);
return new PuzzleDataController(boardSize, pieceCount);
}
}
}<file_sep>using UnityEngine;
namespace Puzzle2DSystem
{
public class PuzzleDataVisualizerWithMeshRenderer : PuzzleDataVisualizer
{
PuzzleData puzzleData;
Material materialPrefab;
public PuzzleDataVisualizerWithMeshRenderer(PuzzleData data, Material material)
{
puzzleData = data;
materialPrefab = material;
}
public override void SetPuzzleData(PuzzleData data)
{
puzzleData = data;
}
public override GameObject CreateBoardVisual()
{
var board = new GameObject("Board ", typeof(MeshFilter), typeof(MeshRenderer));
board.transform.position = new Vector3(0, 0, .25f);
Vector3[] vertices = new Vector3[4];
int[] triangles = new int[6];
vertices[0] = new Vector2(-0.025f, -0.025f) * puzzleData.PuzzleBoard.BoardSize;
vertices[1] = new Vector2(-0.025f, 1.025f) * puzzleData.PuzzleBoard.BoardSize;
vertices[2] = new Vector2(1.025f, 1.025f) * puzzleData.PuzzleBoard.BoardSize;
vertices[3] = new Vector2(1.025f, -0.025f) * puzzleData.PuzzleBoard.BoardSize;
triangles[0] = 0;
triangles[1] = 1;
triangles[2] = 3;
triangles[3] = 3;
triangles[4] = 1;
triangles[5] = 2;
var mesh = new Mesh();
mesh.vertices = vertices;
mesh.triangles = triangles;
board.GetComponent<MeshFilter>().mesh = mesh;
var material = Object.Instantiate(materialPrefab);
material.color = new Color(.25f, .25f, .25f);
board.GetComponent<MeshRenderer>().material = material;
return board;
}
public override GameObject[] CreatePuzzlePiecesVisual()
{
var pieceCount = puzzleData.PuzzlePieces.Count;
PuzzlePieces = new GameObject[pieceCount];
for (int i = 0; i < pieceCount; i++)
{
PuzzlePieces[i] = CreatePuzzlePiece(puzzleData.PuzzlePieces[i]);
}
return PuzzlePieces;
}
GameObject CreatePuzzlePiece(PuzzlePiece puzzlePiece)
{
var piece = new GameObject("Piece ",typeof(MeshFilter), typeof(MeshRenderer));
piece.transform.position = puzzlePiece.Center;
var pointCount = puzzlePiece.TriangleDatas.Count * 3;
Vector3[] vertices = new Vector3[pointCount];
//Vector2[] uv = new Vector2[pointCount];
int[] triangles = new int[pointCount];
for (int i = 0; i < puzzlePiece.TriangleDatas.Count; i++)
{
for (int j = 0; j < 3; j++)
{
vertices[i * 3 + j] = puzzlePiece.TriangleDatas[i].Points[j]- puzzlePiece.Center;
//uv[i * 3 + j] = puzzlePiece.TriangleDatas[i].Points[j].normalized;
triangles[i * 3 + j] = i * 3 + j;
}
}
var mesh = new Mesh();
mesh.vertices = vertices;
//mesh.uv = uv;
mesh.triangles =triangles;
piece.GetComponent<MeshFilter>().mesh = mesh;
var material = Object.Instantiate(materialPrefab);
material.color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
piece.GetComponent<MeshRenderer>().material = material;
return piece;
}
}
}<file_sep>using UnityEngine;
namespace Puzzle2DSystem
{
[System.Serializable]
public class PuzzleBoard
{
public ContactPoint[] ContactPoints { get; }
public int BoardSize { get; }
public PuzzleBoard(int boardSize)
{
BoardSize = boardSize * 2;
var rawCount = BoardSize;
var columnCount = BoardSize;
ContactPoints = new ContactPoint[boardSize*boardSize];
var index = 0;
for (int i = 1; i < rawCount; i+=2)
{
for (int j = 1; j < columnCount; j+=2)
{
ContactPoints[index] = new ContactPoint(i, j);
Debug.Log(index + ": " + ContactPoints[index].Position);
index++;
}
}
}
}
}<file_sep>using UnityEngine;
namespace Puzzle2DSystem
{
[System.Serializable]
public class ContactPoint
{
public Vector2 Position { get; }
public TriangleData[] Triangles { get; }
Vector2[] clockwisePoints =
{
new Vector2(0,1),
new Vector2(1,1),
new Vector2(1,0),
new Vector2(1,-1),
new Vector2(0,-1),
new Vector2(-1,-1),
new Vector2(-1,0),
new Vector2(-1,1),
};
public ContactPoint (int x, int y)
{
Position = new Vector2(x, y);
Triangles = new TriangleData[8];
for (int i = 0; i < 8; i++)
{
Triangles[i] = new TriangleData(this,new Vector2[] { Position, Position+clockwisePoints[i], Position+clockwisePoints[(i+1) % 8] });
}
}
}
}<file_sep>using UnityEngine;
namespace Puzzle2DSystem
{
public class PuzzleDataVisualizerWithLineRenderers : PuzzleDataVisualizer
{
PuzzleData puzzleData;
Material materialPrefab;
public PuzzleDataVisualizerWithLineRenderers(PuzzleData data,Material material)
{
puzzleData = data;
materialPrefab = material;
}
public override void SetPuzzleData(PuzzleData data)
{
puzzleData = data;
}
public override GameObject CreateBoardVisual()
{
var board = new GameObject("Board");
board.transform.position = new Vector3(0, 0, .25f);
var renderer = board.AddComponent<LineRenderer>();
renderer.useWorldSpace = false;
var material = Object.Instantiate(materialPrefab);
renderer.material = material;
renderer.startWidth = .25f;
renderer.endWidth = .25f;
renderer.positionCount = 5;
renderer.SetPosition(0, Vector2.zero);
renderer.SetPosition(1, puzzleData.PuzzleBoard.BoardSize * Vector2.up);
renderer.SetPosition(2, puzzleData.PuzzleBoard.BoardSize * (Vector2.up + Vector2.right));
renderer.SetPosition(3, puzzleData.PuzzleBoard.BoardSize * Vector2.right);
renderer.SetPosition(4, Vector2.zero);
return board;
}
public override GameObject[] CreatePuzzlePiecesVisual()
{
var pieceCount = puzzleData.PuzzlePieces.Count;
PuzzlePieces = new GameObject[pieceCount];
for (int i = 0; i < pieceCount; i++)
{
PuzzlePieces[i] = CreatePuzzlePiece(puzzleData.PuzzlePieces[i]);
}
return PuzzlePieces;
}
GameObject CreatePuzzlePiece(PuzzlePiece puzzlePiece)
{
var piece = new GameObject("piece");
piece.transform.position = puzzlePiece.Center;
var material = Object.Instantiate(materialPrefab);
material.color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
for (int i = 0; i < puzzlePiece.TriangleDatas.Count; i++)
{
CreateTriangle(puzzlePiece.TriangleDatas[i], material).transform.SetParent(piece.transform);
}
return piece;
}
GameObject CreateTriangle(TriangleData triangleData, Material material)
{
var triangle = new GameObject("puzzlePieceTriangle");
var renderer = triangle.AddComponent<LineRenderer>();
renderer.useWorldSpace = false;
renderer.material = material;
renderer.startWidth = .1f;
renderer.endWidth = .1f;
renderer.positionCount = 4;
for (int i = 0; i < 4; i++)
{
renderer.SetPosition(i, triangleData.Points[i % 3]);
}
return triangle;
}
}
}<file_sep>using Puzzle2DSystem;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoardManager : MonoBehaviour
{
[SerializeField] int minBoardSize=4;
[SerializeField] int maxBoardSize = 6;
[SerializeField] int minPuzzlePieceCount=5;
[SerializeField] int maxPuzzlePieceCount=8;
[SerializeField] Material materialPrefab;
[SerializeField] bool useLineRenderer;
PuzzleDataCreator puzzleDataCreator;
PuzzleDataVisualizer puzzleDataVisualizer;
PuzzleData puzzleData;
GameObject puzzleBoard;
GameObject[] puzzlePieces=new GameObject[0];
private void Start()
{
SetBoardSettings();
CreateRandomPuzzle();
}
[ContextMenu("Assign Changed Board Settings")]
private void SetBoardSettings()
{
puzzleDataCreator = new PuzzleDataCreator(minBoardSize, maxBoardSize, minPuzzlePieceCount, maxPuzzlePieceCount);
puzzleData = puzzleDataCreator.GetRandomPuzzleData();
if (useLineRenderer)
puzzleDataVisualizer = new PuzzleDataVisualizerWithLineRenderers(puzzleData, materialPrefab);
else
puzzleDataVisualizer = new PuzzleDataVisualizerWithMeshRenderer(puzzleData, materialPrefab);
}
[ContextMenu("Create Random Puzzle")]
public void CreateRandomPuzzle()
{
if (puzzleBoard)
Destroy(puzzleBoard);
puzzleData = puzzleDataCreator.GetRandomPuzzleData();
puzzleDataVisualizer.SetPuzzleData(puzzleData);
if (puzzlePieces.Length>0)
{
foreach (var piece in puzzlePieces)
{
Destroy(piece);
}
}
puzzleBoard =puzzleDataVisualizer.CreateBoardVisual();
puzzlePieces = puzzleDataVisualizer.CreatePuzzlePiecesVisual();
SetCamera();
}
private void SetCamera()
{
Camera.main.orthographicSize = puzzleData.PuzzleBoard.BoardSize;
Camera.main.transform.position = new Vector2(.5f, .25f) * puzzleData.PuzzleBoard.BoardSize;
Camera.main.transform.position -= Vector3.forward;
}
}
|
5ed46a31244c79f876d045d2af9f80a3ba9a19e9
|
[
"Markdown",
"C#"
] | 12
|
C#
|
SkyWalker2506/Block-Puzzle-2D-Prototype
|
9945cd39c1eb75d706de8fdcaea419c3c32d5a00
|
6a53e470bc08b9715685e28884e549e8777742fc
|
refs/heads/master
|
<repo_name>Ksu1988/Requests<file_sep>/Data/RequestContext.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Requests.Models;
namespace Requests.Data
{
public class RequestContext : DbContext
{
public RequestContext(DbContextOptions<RequestContext> options)
: base(options)
{
}
public DbSet<StatusChange> StatusChange { get; set; }
public DbSet<Request> Requests { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var converter = new EnumToStringConverter<Status>();
modelBuilder
.Entity<Request>()
.Property(e => e.Status)
.HasConversion(converter);
}
}
}
<file_sep>/Models/StatusChange.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Requests.Models
{
public class StatusChange
{
/// <summary>
/// Id заявки.
/// </summary>
public int StatusChangeId { get; set; }
[Display(Name = "Статус заявки")]
public Status Status { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Дата изменения")]
public DateTime Date { get; set; }
[Display(Name = "Дата изменения")]
public String Comment { get; set; }
public int RequestId { get; set; }
public Request Request { get; set; }
}
}
<file_sep>/Models/FilterViewModel.cs
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
namespace Requests.Models
{
public class FilterViewModel
{
public FilterViewModel(Status status, DateTime date1, DateTime date2)
{
// устанавливаем начальный элемент, который позволит выбрать всех
var statuses = new List<Status>();
statuses.Add(Status.All);
statuses.Add(Status.Open);
statuses.Add(Status.Closed);
statuses.Add(Status.Return);
statuses.Add(Status.Solved);
Statuses = new SelectList(statuses, status);
SelectedStatus = status;
SelectedDate1 = date1;
SelectedDate2 = date2;
}
public SelectList Statuses { get; private set; } // список заявок
public Status SelectedStatus { get; private set; } // выбранная заявка по статусу
public DateTime SelectedDate1 { get; private set; }
public DateTime SelectedDate2 { get; private set; }
}
}
<file_sep>/Models/SeedData.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Requests.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Requests.Models
{
public class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new RequestContext(
serviceProvider.GetRequiredService<
DbContextOptions<RequestContext>>()))
{
if (context.Requests.Any())
{
return;
}
var request1 = new Request
{
Name = "Заявка1",
Content = "Нужно, чтобы все работало хорошо и быстро",
Status = Status.Open,
Date = new DateTime(2020, 04, 1)
};
var statusChange1 = new StatusChange
{
Status = Status.Open,
Date = new DateTime(2020, 04, 1),
Comment = "Новая заявка",
Request = request1
};
request1.StatusChange.Add(statusChange1);
context.StatusChange.Add(statusChange1);
var request2 = new Request
{
Name = "Заявка2",
Content = "Заявка номер два, очень важная",
Status = Status.Open,
Date = new DateTime(2020, 04, 10)
};
var statusChange2 = new StatusChange
{
Status = Status.Open,
Date = new DateTime(2020, 04, 10),
Comment = "Новая заявка",
Request = request2
};
request2.StatusChange.Add(statusChange2);
context.StatusChange.Add(statusChange2);
var request3 = new Request
{
Name = "Заявка3",
Content = "Нужно, чтобы все работало хорошо и быстро. Срочно",
Status = Status.Solved,
Date = new DateTime(2020, 04, 13)
};
var statusChange3 = new StatusChange
{
Status = Status.Open,
Date = new DateTime(2020, 04, 11),
Comment = "Новая заявка",
Request = request3
};
var statusChange5 = new StatusChange
{
Status = Status.Solved,
Date = new DateTime(2020, 04, 13),
Comment = "Все решили",
Request = request3
};
request3.StatusChange.Add(statusChange3);
request3.StatusChange.Add(statusChange5);
context.StatusChange.AddRange(statusChange3, statusChange5);
var request4 = new Request
{
Name = "Заявка4",
Content = "Нужно, чтобы все работало хорошо и правильно",
Status = Status.Open,
Date = new DateTime(2020, 04,18)
};
var statusChange4 = new StatusChange
{
Status = Status.Open,
Date = new DateTime(2020, 04, 18),
Comment = "Новая заявка",
Request = request4
};
request4.StatusChange.Add(statusChange4);
context.StatusChange.Add(statusChange4);
context.Requests.AddRange(request1, request2, request3, request4);
context.SaveChanges();
}
}
}
}
<file_sep>/Models/SortViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Requests.Models
{
public class SortViewModel
{
public SortState StatusSort { get; private set; } // значение для сортировки по статусу
public SortState DateSort { get; private set; } // значение для сортировки по дате
public SortState Current { get; private set; } // текущее значение сортировки
public SortViewModel(SortState sortOrder)
{
StatusSort = sortOrder == SortState.StatusAsc ? SortState.StatusAsc : SortState.StatusAsc;
DateSort = sortOrder == SortState.DateAsc ? SortState.DateDesc : SortState.DateAsc;
Current = sortOrder;
}
}
}
<file_sep>/Models/Request.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Requests.Models
{
public class Request
{
/// <summary>
/// Id заявки.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Название заявки.
/// </summary>
[Display(Name = "Название заявки")]
public string Name { get; set; }
[Display(Name = "Содержание заявки")]
public string Content { get; set; }
// [DataType(DataType.Custom)]
[Display(Name = "Статус заявки")]
public Status Status { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Дата заявки")]
public DateTime Date { get; set; }
/// <summary>
/// История заявки
/// </summary>
[Display(Name = "История заявки")]
public List<StatusChange> StatusChange { get; set; } = new List<StatusChange>();
}
}
<file_sep>/Controllers/RequestsController.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 Requests.Data;
using Requests.Models;
namespace Requests.Controllers
{
public class RequestsController : Controller
{
private readonly RequestContext _context;
public RequestsController(RequestContext context)
{
_context = context;
}
// GET: Requests
public async Task<IActionResult> Index(DateTime date1, DateTime date2,
SortState sortOrder = SortState.StatusAsc, Status status = Status.All)
{
//фильтрация
IQueryable<Request> requests = _context.Requests.Include(x => x.StatusChange);
if (status != Status.All)
{
requests = requests.Where(p => p.Status == status);
}
if (date1.Ticks != 0)
{
requests = requests.Where(p => p.Date >= date1);
}
if (date2.Ticks != 0)
{
requests = requests.Where(p => p.Date <= date2);
}
// сортировка
switch (sortOrder)
{
case SortState.StatusDesc:
requests = requests.OrderByDescending(s => s.Status);
break;
case SortState.DateAsc:
requests = requests.OrderBy(s => s.Date);
break;
case SortState.DateDesc:
requests = requests.OrderByDescending(s => s.Date);
break;
default:
requests = requests.OrderBy(s => s.Status);
break;
}
// формируем модель представления
IndexViewModel viewModel = new IndexViewModel
{
SortViewModel = new SortViewModel(sortOrder),
FilterViewModel = new FilterViewModel(status, date1, date2),
Requests = requests
};
return View(viewModel);
}
// GET: Requests/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var request = await _context.Requests.Include(t => t.StatusChange)
.FirstOrDefaultAsync(m => m.Id == id);
if (request == null)
{
return NotFound();
}
return View(request);
}
// GET: Requests/Create
public IActionResult Create()
{
return View();
}
// POST: Requests/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("Id,Name,Content,Status,Date")] Request request)
{
if (ModelState.IsValid)
{
var status = new StatusChange()
{
Date = request.Date,
RequestId = request.Id,
Request = request,
Status = request.Status,
Comment = "Создана новая заявка"
};
request.StatusChange.Add(status);
_context.Add(status);
_context.Add(request);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(request);
}
// GET: Requests/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var request = await _context.Requests.Include(t => t.StatusChange)
.FirstOrDefaultAsync(m => m.Id == id);
var statuses = new List<Status>();
statuses.Add(request.Status);
switch (request.Status)
{
case Status.Open:
statuses.Add(Status.Solved);
break;
case Status.Solved:
statuses.Add(Status.Closed);
statuses.Add(Status.Return);
break;
//case Status.Closed:
// break;
case Status.Return:
statuses.Add(Status.Solved);
break;
}
ViewData["Status"] = new SelectList(statuses);
if (request == null)
{
return NotFound();
}
return View(request);
}
// POST: Requests/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("Id,Name,Content,Status,Date,StatusChange")] Request request, string comment)
{
if (id != request.Id)
{
return NotFound();
}
var s = request.StatusChange;
if (String.IsNullOrEmpty(comment))
{
ModelState.AddModelError("Comment", "Введите комментарий");
}
if (ModelState.IsValid)
{
try
{
var status = new StatusChange()
{
Date = request.Date,
RequestId = request.Id,
Request = request,
Status = request.Status,
Comment = comment
};
request.StatusChange.Add(status);
_context.Add(status);
_context.Update(request);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!RequestExists(request.Id))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(request);
}
// GET: Requests/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var request = await _context.Requests
.FirstOrDefaultAsync(m => m.Id == id);
if (request == null)
{
return NotFound();
}
return View(request);
}
// POST: Requests/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var request = await _context.Requests.FindAsync(id);
_context.Requests.Remove(request);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool RequestExists(int id)
{
return _context.Requests.Any(e => e.Id == id);
}
}
}
<file_sep>/Models/Status.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace Requests.Models
{
public enum Status
{
[Display(Description="Открыта")]
Open,
[Description("Решена")]
Solved,
Return,
Closed,
All
}
}
<file_sep>/Models/SortState.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Requests.Models
{
public enum SortState
{
StatusAsc, // по статусу по возрастанию
StatusDesc, // по статусу по убыванию
DateAsc, // по дате по возрастанию
DateDesc // по дате по убыванию
}
}
|
3b9313b419544c4afec6220771afe7b9192e76db
|
[
"C#"
] | 9
|
C#
|
Ksu1988/Requests
|
375bc79183681c0b332d7d7dac0e923d0e9ffed5
|
16fcf014472458b4dd4d8f13461befcac4022fdc
|
refs/heads/master
|
<file_sep># BOTLoja
Projeto com o objetivo de criar um BOT para tentar realizar a venda de jogos. Por meio de uma conversa, o BOT tentará realizar uma venda de um jogo.
# Contexto
Uma loja para alugar jogos online onde um BOT realiza a venda.
<file_sep>#<NAME>
#<NAME>
#<NAME>
#<NAME>
import os
import math
import nltk
import re
import stanfordnlp
from sly import Lexer, Parser
from collections import Counter
#nltk.download('punkt')
from nltk import tokenize
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
jogos = [
['call of duty black ops 2', 'tiro em primeira pessoa', 109.99, False],
['call of duty modern warfare', 'tiro em primeira pessoa', 199.90, True],
['fifa 20', 'esporte', 249.90, True],
['pro evolution soccer 2020', 'esporte', 119.90, True],
['left for dead 2', 'acao', 20.69, False]
]
frame = [
['know the game', None,'Do you know the game you want to rent?'],
['game', None, 'Which game do you want to rent?'],
['time', None, 'How long do you want to rent?'],
['payment method', None,'What would be your payment method?']
]
metodos_pagamentos = ['money', 'card', 'cash']
afirmativas = ['ye', 'yeah', 'positiv']
negativas = ['no', 'dont know', 'negativ']
perguntas = ['rent', 'do not know']
#Tokenizar
def TokenizeInput( texto):
palavras_tokenize = tokenize.word_tokenize(texto, language = 'english')
#print(palavras_tokenize)
return palavras_tokenize
#Stemm
def StemmerNLTK( palavra, lista):
#nltk.download('rslp')
stemmer = nltk.stem.RSLPStemmer()
lista.append(stemmer.stem(palavra))
#Remocao de Stopwords
def RemocaoStopWords( palavra, lista):
#nltk.download('stopwords')
if palavra not in set(stopwords.words('english')):
lista.append(palavra)
#funcao que pega digramas de um lista
def getGramas (palavra):
#lista de n-gramas da palavra
par = list()
array = list()
for i in range(len(palavra)):
ind = palavra[i]
for j in range(len(ind) - 1):
array.append(ind[j:2+j])
#print (ind[j:2+j] + " - i-> ", i , " - j-> ", j)
par.append(array)
array = list()
return par
#funcao que pega digramas de um palavra unica
def getGramasPalavraUnica(palavra):
array = list()
for i in range(len(palavra)-1):
array.append(palavra[i:2+i])
return array
#calcula a similaridade entre duas palavras
def checaSimilaridade(listaGramas, ngramasInput):
#print("ngramas - ",ngramasInput)
inputSet = set(ngramasInput)
palavraSet = set(listaGramas)
c = comparaNGramas(inputSet, palavraSet)
a = len(inputSet)
b = len(palavraSet)
return (2*c)/(a+b)
#funçao para verificar digramas iguais
def comparaNGramas(listaA, listaB):
matches = 0
for a in listaA:
for b in listaB:
if a == b:
matches += 1
return matches
#funcao para a retornar o ranking
def comparePalavras(lex, ngramasInput, dicionario):
#print("ngramas - ",ngramasInput)
lista = list()
rank = list()
index = 0
#print("------------------------------")
#print(" Palavras : Similaridade")
#print("------------------------------")
for palavra in lex:
ngramasPalavra = dicionario[index]
s = checaSimilaridade(ngramasPalavra, ngramasInput)
#print(index+1, ') ', palavra, ': ', round(s,4))
lista.append(palavra)
lista.append(round(s,4))
rank.append(lista)
lista = list()
index += 1
return rank
#funcao para dar um sort no ranking
def mySort(lista):
for i in range(len(lista)):
if i == len(lista):
break
else:
j = i+1
for j in range(len(lista)):
if lista[i][1] > lista[j][1]:
aux = lista[i]
lista[i] = lista[j]
lista[j] = aux
return lista
#printar o rank
def printRank(rank):
print("------------------------------")
print(" RANK ")
print("------------------------------")
for i in range(len(rank)):
index = i+1
print(index, ") " + rank[i][0] + " -> ", rank[i][1])
#printar as tabela de jogos com os valores
def printTabelas():
#imprime lista de jogos no catalogo
#imprime valores
frame[0][1] = False
print('========================================')
print(' GAMES')
print('========================================')
print(' GAME - DAILY PRICE')
for i in jogos:
valor = 0.0
if(i[3]):
valor = i[2]*0.08
else:
valor = i[2]*0.04
print(i[0] +' - R$',round(valor,4))
print('----------------------------------------')
def frameConhecimentoDoJogo():
if not frame[0][1]:
print('I am going to help you, here these are our games...')
printTabelas()
def frameTempoAluguel():
inteiro = r'[0-9]+'
print(frame[2][2])
tempo = input('Voce: ')
dialogo = tempo
lista_token = TokenizeInput(dialogo)
print(lista_token)
lista_stemm = list()
for i in lista_token:
StemmerNLTK(i, lista_stemm)
print(lista_stemm)
lista_stopwords = list()
for i in lista_stemm:
RemocaoStopWords(i, lista_stopwords)
print(lista_stopwords)
lista_dialogo = lista_stopwords
for i in lista_dialogo:
if re.match(inteiro, i):
tempo = int(i)
frame[1][1] = tempo
print('Alugando')
#onde tudo funciona
def acao(conversa, verifica):
engano1 = True
engano2 = True
engano3 = True
engano4 = True
recibo = True
verifica2 = -1
if verifica == 1:
print("KRONK: "+frame[0][2])
first = input('You: ')
dialogo = first.lower()
lista_token = TokenizeInput(dialogo)
lista_stemm = list()
for i in lista_token:
StemmerNLTK(i, lista_stemm)
lista_dialogo = lista_stemm
for i in lista_dialogo:
if i in afirmativas:
verifica2 = 1
elif i in negativas:
verifica2 = 0
elif i == 'cancel':
print("KRONK: Why leaving so soon? Bye :(")
conversa = False
return
while(engano1):
if verifica2 == 1:
frame[0][1] = True
elif verifica2 == 0:
frame[0][1] = False
frameConhecimentoDoJogo()
print("KRONK: "+frame[1][2])
second = input('You: ')
second.lower()
if second == 'cancel':
recibo = False
engano1 = False
else:
#print(nome_jogos)
#print("==================================================")
grama_second = getGramasPalavraUnica(second)
grama_jogos = getGramas(nome_jogos)
#ngramasInput = getGramasPalavraUnica(second)
#print("second - ",second,", digrama second - ",ngramasInput)
rank = list()
rank = comparePalavras(nome_jogos,grama_second, grama_jogos)
rank_sorted = mySort(rank)
#printRank(rank_sorted)
while(engano2):
if rank_sorted[0][1] == 1:
frame[1][1] = rank_sorted[0][0]
print("KRONK: You are renting " + frame[1][1])
engano1 = False
engano2 = False
elif rank_sorted[0][1] >= 0.5:
print("KRONK: You meant " + rank_sorted[0][0] +"?")
second = input('You: ')
second = second.lower()
if second == 'cancel':
recibo = False
engano1 = False
engano2 = False
engano3 = False
engano4 = False
else:
lista_token2 = TokenizeInput(second)
lista_stopwords2 = lista_token2
#for i in lista_token2:
#RemocaoStopWords(i, lista_stopwords2)
lista_stemm2 = list()
for i in lista_stopwords2:
StemmerNLTK(i, lista_stemm2)
lista_dialogo2 = lista_stemm2
for i in lista_dialogo2:
if i in afirmativas:
frame[1][1] = rank_sorted[0][0]
print("KRONK: You are renting " + frame[1][1])
engano1 = False
engano2 = False
elif i in negativas:
rank_aux = rank_sorted[1]
rank_sorted[0] = rank_aux
while(engano3):
print("KRONK: Plese do not type number in full")
print("KRONK: "+frame[2][2])
third = input('You: ')
third = third.lower()
if 'cancel' in third:
recibo = False
engano3 = False
engano4 = False
tempo = None
nlp = stanfordnlp.Pipeline()
doc = nlp(third)
for i in doc.sentences[0].words:
if i.dependency_relation == 'nummod':
tempo = i.text
if tempo != None:
frame[2][1] = tempo
engano3 = False
else:
print("KRONK: I did not understood please try again :)")
pagamento = ""
while(engano4):
print("KRONK: "+frame[3][2])
fourth = input('You: ')
fourth = fourth.lower()
if 'cancel' in fourth:
recibo = False
engano4 = False
doc2 = nlp(fourth)
for i in doc2.sentences[0].words:
if i.dependency_relation == 'obl' and i.text in metodos_pagamentos:
pagamento = i.text
frame[3][1] = pagamento
engano4 = False
elif i.dependency_relation == 'obl' and i.text not in metodos_pagamentos:
print("KRONK: Sorry did not understood, please what is your payment method? We only accept money and creadit card")
if recibo:
preco = 0
jogo_comprado = frame[1][1]
for i in range(len(jogos)):
if jogo_comprado == jogos[i][0]:
if jogos[i][3]:
preco = jogos[i][2]*.08*int(frame[2][1])
else:
preco = jogos[i][2]*.04*int(frame[2][1])
print("======================================================================")
print("Game rented: "+frame[1][1]+" ====== Days rented: "+frame[2][1]+" days.")
print("Cost $",round(preco, 2)," ======= Payment method - "+frame[3][1])
print("======================================================================")
print("KRONK: Do you want to confirm the payment?")
final_input = input("You: ")
final_input.lower()
lista_final = TokenizeInput(final_input)
lista_final_stemm = list()
for i in lista_final:
StemmerNLTK(i, lista_final_stemm)
for i in lista_final_stemm:
if i in afirmativas:
print("KRONK: Your order is done")
print("KRONK: Thanks for buying with us. BYEEEeee...:D")
elif i in negativas:
print("KRONK: You have canceled your order...")
print("KRONK: Back where we started :/")
if not recibo:
print("KRONK: Back where we started :/")
elif verifica == 0:
frame[0][1] = False
frameConhecimentoDoJogo()
while(engano1):
frame[0][1] = True
frameConhecimentoDoJogo()
print("KRONK: "+frame[1][2])
second = input('You: ')
second.lower()
if second == 'cancel':
recibo = False
engano1 = False
else:
#print(nome_jogos)
#print("==================================================")
grama_second = getGramasPalavraUnica(second)
grama_jogos = getGramas(nome_jogos)
#ngramasInput = getGramasPalavraUnica(second)
#print("second - ",second,", digrama second - ",ngramasInput)
rank = list()
rank = comparePalavras(nome_jogos,grama_second, grama_jogos)
rank_sorted = mySort(rank)
#printRank(rank_sorted)
while(engano2):
if rank_sorted[0][1] == 1:
frame[1][1] = rank_sorted[0][0]
print("KRONK: You are renting " + frame[1][1])
engano1 = False
engano2 = False
elif rank_sorted[0][1] >= 0.5:
print("KRONK: You meant " + rank_sorted[0][0] +"?")
second = input('You: ')
second = second.lower()
if second == 'cancel':
recibo = False
engano1 = False
engano2 = False
engano3 = False
engano4 = False
else:
lista_token2 = TokenizeInput(second)
lista_stopwords2 = list()
for i in lista_token2:
RemocaoStopWords(i, lista_stopwords2)
lista_stemm2 = list()
for i in lista_stopwords2:
StemmerNLTK(i, lista_stemm2)
lista_dialogo2 = lista_stemm2
for i in lista_dialogo2:
if i in afirmativas:
frame[1][1] = rank_sorted[0][0]
print("KRONK: You are renting " + frame[1][1])
engano1 = False
engano2 = False
elif i in negativas:
rank_aux = rank_sorted[1]
rank_sorted[0] = rank_aux
nlp = stanfordnlp.Pipeline()
while(engano3):
print("KRONK: Plese do not type number in full")
print("KRONK: "+frame[2][2])
third = input('You: ')
third = third.lower()
if 'cancel' in third:
recibo = False
engano3 = False
engano4 = False
tempo = None
doc = nlp(third)
for i in doc.sentences[0].words:
if i.dependency_relation == 'nummod':
tempo = i.text
if tempo != None:
frame[2][1] = tempo
engano3 = False
else:
print("KRONK: I did not understood please try again :)")
pagamento = ""
while(engano4):
print("KRONK: "+frame[3][2])
fourth = input('You: ')
fourth = fourth.lower()
if 'cancel' in fourth:
recibo = False
engano4 = False
doc2 = nlp(fourth)
for i in doc2.sentences[0].words:
if i.dependency_relation == 'obl' and i.text in metodos_pagamentos:
pagamento = i.text
frame[3][1] = pagamento
engano4 = False
elif i.dependency_relation == 'obl' and i.text not in metodos_pagamentos:
print("KRONK: Sorry did not understood, please what is your payment method? We only accept money and creadit card")
if recibo:
preco = 0
jogo_comprado = frame[1][1]
for i in range(len(jogos)):
if jogo_comprado == jogos[i][0]:
if jogos[i][3]:
preco = jogos[i][2]*.08*int(frame[2][1])
else:
preco = jogos[i][2]*.04*int(frame[2][1])
print("======================================================================")
print("Game rented: "+frame[1][1]+" ====== Days rented: "+frame[2][1]+" days.")
print("Cost $",round(preco, 2)," ======= Payment method - "+frame[3][1])
print("======================================================================")
print("KRONK: Do you want to confirm the payment?")
final_input = input("You: ")
final_input.lower()
lista_final = TokenizeInput(final_input)
lista_final_stemm = list()
for i in lista_final:
StemmerNLTK(i, lista_final_stemm)
for i in lista_final_stemm:
if i in afirmativas:
print("KRONK: Your order is done")
print("KRONK: Thanks for buying with us. BYEEEeee...:D")
elif i in negativas:
print("KRONK: You have canceled your order...")
print("KRONK: Back where we started :/")
if not recibo:
print("KRONK: Back where we started :/")
else:
print('KRONK: Sorry i did not understand')
def chat():
conversa = True
os.system('clear')
print('Hi I am KRONK the chatbot. I was created to help you while you are renting games')
print('Obs: Please use lower case')
print('If you want to leave just type cancel :)')
verifica = -1
while conversa:
for i in frame:
i[1] = None
#print(frame)
print("KRONK: How can i help you?")
input_inicial = input("You: ")
input_inicial = input_inicial.lower()
if input_inicial == 'cancel':
print("KRONK: Leaving... Bye :)")
conversa=False
break
grama_inicial = getGramasPalavraUnica(input_inicial)
grama_perguntas = getGramas(perguntas)
rank_perguntas = comparePalavras(perguntas, grama_inicial, grama_perguntas)
rank_perguntas_sorted = mySort(rank_perguntas)
if rank_perguntas_sorted[0][0] == perguntas[0]:
verifica = 1
acao(conversa, verifica)
elif rank_perguntas_sorted[0][0] == perguntas[1]:
verifica = 0
acao(conversa,verifica)
else:
print("KRONK: Sorry i did not understood")
#print(frame)
if __name__ == '__main__':
#dicionario de jogos
nome_jogos = list()
for i in range(len(jogos)):
nome_jogos.append(jogos[i][0])
pares_jogos = getGramas(nome_jogos)
chat()
|
6e89790db1ecc244db259e061aa80248def459f4
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
ViniciusMassao/BOTLoja
|
a6b4814d935761af73f633c6d40ed8fced8b72dd
|
cd9bc41bbb957391752ec6beefc7d188d71eda1a
|
refs/heads/master
|
<repo_name>isml26/newsletter-sign<file_sep>/README.md
# newsletter-sign
subscribe app using mailchimp api
run npm i start server
<file_sep>/app.js
//jshint esversion:6
//npm init
//npm install express
//npm install -g nodemon
//npm install request
//npm install bosdy-parser
//npm install async
//npx nodemon server.js
//npm server.js
//npx nodemon server.js
const mailchimp = require('@mailchimp/mailchimp_marketing');
const express = require("express");
const request = require("request");
const app = express();
const https = require("https");
const async = require('async');
require('dotenv').config();
app.use(express.urlencoded({
extended: true
}))
//To requre static folders we use this method
app.use(express.static("public"));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/signup.html");
})
app.post("/", function(req, res) {
const name = req.body.name;
const surname = req.body.surname;
const email = req.body.email;
mailchimp.setConfig({
apiKey: process.env.API_KEY,
server: "us1",
});
const run = async () => {
try {
const response = await mailchimp.lists.addListMember("78a816e504", {
email_address: email,
status: "subscribed",
merge_fields: {
FNAME: name,
LNAME: surname
}
});
console.log(response);
res.sendFile(__dirname + "/success.html");
} catch (e) {
console.log(e);
res.sendFile(__dirname + "/failure.html");
}
};
run();
});
app.post("/failure",function(req,res){
res.redirect("/");
})
app.listen(process.env.PORT || 3000, function() {
console.log("Server is running on port 3000");
})
// API KEY
//
// LIST
//
|
0e015c68c1e7afbcd2e0d8d422d188b77fdcb378
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
isml26/newsletter-sign
|
f30a3daf2f6de60293720cc6749f8d49a7938f76
|
732d4443b164d98529b10330a589937aaf9106b5
|
refs/heads/main
|
<file_sep>package csv
import (
"encoding/csv"
"log"
"os"
"go.k6.io/k6/js/modules"
)
type CSV struct{}
func init() {
modules.Register("k6/x/csv", new(CSV))
}
func (c *CSV) Append(path string, data []string) {
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, os.ModeAppend)
if err != nil {
log.Fatal(err)
}
defer f.Close()
w := csv.NewWriter(f)
w.Write(data)
if err = w.Error(); err != nil {
log.Fatal(err)
}
w.Flush()
}
<file_sep>module github.com/awcodify/xk6-csv
go 1.16
require go.k6.io/k6 v0.34.1
|
90a2c4e55956a54bd186bdce9384220826492c18
|
[
"Go Module",
"Go"
] | 2
|
Go
|
Tushar-Tiket/xk6-csv
|
5f0fe2de49b60f697b2572f19ec40c9c8569140a
|
50b2b46f5c653aad180069cdbbb6ee0ddc56951e
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<title></title>
</head>
<body>
<?php
foreach(glob("thumb/*.jpg") as $filename){
$temp = strlen($filename) -6;
$temp = substr($filename,11,$temp);
$temp = "bild".$temp;
echo '<div>'."<a href='$temp'><img title='$filename' src='$filename'></a>";
$tmp = strlen($filename) - 10;
echo '<p>'.substr($filename,6,$tmp).'</p>'.'</div>';
}
?>
</body>
</html>
|
69c765682f44616abdbc9bfb01d24938f6643902
|
[
"PHP"
] | 1
|
PHP
|
yazlo/galleri
|
854741a141e56ab705090d3d14fc8887f3817285
|
e77e7b114e471406dd7c66299b34c04ee1aa9e6a
|
refs/heads/master
|
<repo_name>swest599/Inheritance-Polymorphism<file_sep>/src/com/company/Main.java
package com.company;
import java.util.HashMap;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
AlienXenomorph alienXenomorph = new AlienXenomorph();
AlienXenomorph humanXenomorph = new HumanXenomorph(); // static class variable instance = new constructor
AlienXenomorph dogXenomorph = new DogXenomorph();
AlienXenomorph predatorXenomorph = new PredatorXenomorph();
DogXenomorph newDog = (DogXenomorph) dogXenomorph; //?????????????
alienXenomorph.iAmAXenomorph();
alienXenomorph.acidBlood();
humanXenomorph.acidBlood();
humanXenomorph.acidBlood();
//humanXenomorph.walkLikeAHuman();// AlienXenomorph methods are the only methods that can be called because of ABOVE static class type references
dogXenomorph.iAmAXenomorph();
dogXenomorph.acidBlood();
//dogXenomorph.walkLikeADog();
predatorXenomorph.iAmAXenomorph();
predatorXenomorph.acidBlood();
//predatorXenomorph.biteLikeAPredator();
HashMap<String,AlienXenomorph> alienMap = new HashMap<>();
// alienMap.put((alienXenomorph.getClass().getSimpleName() alienXenomorph);
alienMap.put("AlienXenomorph", alienXenomorph);
alienMap.put("HumanXenomorph",humanXenomorph);
alienMap.put("DogXenomorph", dogXenomorph);
alienMap.put("PredatorXenomorph",predatorXenomorph);
//foreach enter
for (String s:alienMap.keySet()) {
alienMap.get(s).iAmAXenomorph();
if (alienMap.get(s) instanceof HumanXenomorph){
((HumanXenomorph)alienMap.get(s)).walkLikeAHuman();
}
}
HashSet<AlienXenomorph> alienSet = new HashSet<>();
alienSet.add(alienXenomorph);
alienSet.add(humanXenomorph);
alienSet.add(dogXenomorph);
alienSet.add(predatorXenomorph);
for (AlienXenomorph a:alienSet){
a.iAmAXenomorph();
}
}
}
|
ad4463e2f9acd29ed86336b855a2681682eef549
|
[
"Java"
] | 1
|
Java
|
swest599/Inheritance-Polymorphism
|
14decb41d1785b6a330fd006611e75925d9cef04
|
412574aea6187a5105c728b541b28ed24e4ad54e
|
refs/heads/master
|
<repo_name>hiroaki-u/share-read<file_sep>/spec/models/bookcase_spec.rb
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Bookcase, type: :model do
before do
@bookcase = FactoryBot.build(:bookcase)
end
context "本棚登録できる時" do
it "まだ本棚登録していない時有効" do
expect(@bookcase).to be_valid
end
end
context "アソシエーションについて" do
it "userがいないとエラーが発生" do
@bookcase.user = nil
@bookcase.valid?
expect(@bookcase.errors.full_messages).to include("Userを入力してください")
end
it "bookがないとエラーが発生" do
@bookcase.book = nil
@bookcase.valid?
expect(@bookcase.errors.full_messages).to include("Bookを入力してください")
end
it '既に本棚登録したbookを本棚登録するとエラーが発生' do
@bookcase.save
@bookcase_repeat = FactoryBot.build(:bookcase)
@bookcase_repeat.user = @bookcase.user
@bookcase_repeat.book = @bookcase.book
@bookcase_repeat.valid?
expect(@bookcase_repeat.errors.full_messages).to include("Bookはすでに存在します")
end
end
end
<file_sep>/db/migrate/20201224140712_create_bookcases.rb
# frozen_string_literal: true
class CreateBookcases < ActiveRecord::Migration[6.0]
def change
create_table :bookcases do |t|
t.integer :read, default: 0, null: false
t.references :book, null: false
t.references :user, null: false, foreign_key: true
t.timestamps
t.index %i[user_id book_id], unique: true
end
add_foreign_key :bookcases, :books, column: :book_id, primary_key: :isbn
end
end
<file_sep>/db/migrate/20201225105949_create_notifications.rb
# frozen_string_literal: true
class CreateNotifications < ActiveRecord::Migration[6.0]
def change
create_table :notifications do |t|
t.bigint :visitor_id
t.bigint :visited_id
t.bigint :review_id
t.bigint :comment_id
t.string :action
t.boolean :checked, default: false, null: false
t.timestamps
end
end
end
<file_sep>/app/controllers/toppages_controller.rb
# frozen_string_literal: true
class ToppagesController < ApplicationController
def index
@reviews = Review.where(status: 1).includes(:book, :user).order(updated_at: :desc)
end
end
<file_sep>/app/models/review.rb
# frozen_string_literal: true
class Review < ApplicationRecord
validates :content, presence: true, length: { maximum: 1200 }
enum status: { "draft": 0, "published": 1 }
validates :status, inclusion: { in: Review.statuses.keys }
belongs_to :user
belongs_to :book, primary_key: "isbn"
has_many :comments, dependent: :destroy
has_many :favorites, dependent: :destroy
has_many :favored, through: :favorites, source: :user
has_many :notifications, dependent: :destroy
def create_notification_favorite(current_user)
temp = Notification.where(["visitor_id = ? and visited_id = ? and review_id = ? and action = ?", current_user.id, user_id, id, "favorite"])
return unless temp.blank?
notification = current_user.active_notifications.new(
review_id: id,
visited_id: user_id,
action: "favorite"
)
notification.save if notification.valid?
notification.visitor_id == notification.visited_id && notification.checked = true
end
def create_notification_comment(current_user, comment_id)
temp_ids = Comment.select(:user_id).where(review_id: id).where.not(user_id: current_user.id).distinct
temp_ids.each do |temp_id|
save_notification_comment(current_user, comment_id, temp_id["user_id"])
end
save_notification_comment(current_user, comment_id, user_id) if temp_ids.blank?
end
def save_notification_comment(current_user, comment_id, visited_id)
notification = current_user.active_notifications.new(
review_id: id,
comment_id: comment_id,
visited_id: visited_id,
action: "comment"
)
notification.visitor_id == notification.visited_id && notification.checked = true
notification.save if notification.valid?
end
def toggle_status!
draft? ? published : draft
end
end
<file_sep>/spec/factories/books.rb
# frozen_string_literal: true
FactoryBot.define do
factory :book do
isbn { Faker::Number.number(digits: 4) }
title { Faker::Book.title }
author { Faker::Book.author }
url { Faker::Internet.url }
image_url { Faker::Internet.url }
book_genre_id { Faker::Number.number(digits: 4) }
caption { Faker::String.random }
end
end
<file_sep>/db/migrate/20201230042031_add_caption_to_books.rb
# frozen_string_literal: true
class AddCaptionToBooks < ActiveRecord::Migration[6.0]
def change
add_column :books, :caption, :text
end
end
<file_sep>/app/controllers/application_controller.rb
# frozen_string_literal: true
class ApplicationController < ActionController::Base
include SessionsHelper
def counts(user)
@count_followings = user.followings.count
@count_followers = user.followers.count
end
private
def require_login
redirect_to login_url unless logged_in?
end
end
<file_sep>/spec/factories/reviews.rb
# frozen_string_literal: true
FactoryBot.define do
factory :review do
content { Faker::String.random(length: 1..1200) }
status { 0 }
association :user
association :book
end
end
<file_sep>/spec/models/relationship_spec.rb
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Relationship, type: :model do
before do
@relationship = FactoryBot.build(:relationship)
end
context "フォローできる時" do
it "まだフォローしていない時有効" do
expect(@relationship).to be_valid
end
end
context "アソシエーションについて" do
it "フォローするuserがいないとエラーが発生" do
@relationship.user = nil
@relationship.valid?
expect(@relationship.errors.full_messages).to include("Userを入力してください")
end
it "フォロー対象のuserがいないとエラーが発生" do
@relationship.follow = nil
@relationship.valid?
expect(@relationship.errors.full_messages).to include("Followを入力してください")
end
it '既にフォローしたuserを再度フォローするとエラーが発生' do
@relationship.save
@relationship_repeat = FactoryBot.build(:relationship)
@relationship_repeat.user = @relationship.user
@relationship_repeat.follow = @relationship.follow
@relationship_repeat.valid?
expect(@relationship_repeat.errors.full_messages).to include("Followはすでに存在します")
end
end
end
<file_sep>/spec/models/review_spec.rb
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Review, type: :model do
before do
@review = FactoryBot.build(:review)
end
context "投稿できる時" do
it "status, contentが正しければ有効" do
expect(@review).to be_valid
end
it "contentが1文字であれば有効" do
@review.content = "a"
expect(@review).to be_valid
end
it "contentが1200文字であれば有効" do
@review.content = Faker::String.random(length: 1200)
expect(@review).to be_valid
end
end
describe "投稿できない時" do
context "contentについて" do
it "contentがnilである時エラーが発生" do
@review.content = nil
@review.valid?
expect(@review.errors.full_messages).to include("本のレビューを入力してください")
end
it "contentが1200文字以上である時エラーが発生" do
@review.content = Faker::String.random(length: 1201)
@review.valid?
expect(@review.errors.full_messages).to include("本のレビューは1200文字以内で入力してください")
end
end
context "アソシエーションについて" do
it "userが紐付いていないと保存できない" do
@review.user = nil
@review.valid?
expect(@review.errors.full_messages).to include("Userを入力してください")
end
it "bookが紐付いていないと保存できない" do
@review.book = nil
@review.valid?
expect(@review.errors.full_messages).to include("Bookを入力してください")
end
end
end
end
<file_sep>/config/initializers/rakuten.rb
# frozen_string_literal: true
RakutenWebService.configure do |c|
c.application_id = '1030420420732807564'
c.affiliate_id = '1e0e3545.328b97c2.1e0e3546.c37c2b39'
end
<file_sep>/config/routes.rb
# frozen_string_literal: true
Rails.application.routes.draw do
root to: 'toppages#index'
get "signup", to: "users#new"
get "login", to: "sessions#new"
post "login", to: "sessions#create"
delete "logout", to: "sessions#destroy"
post 'guest_login', to: "guest_sessions#create"
resources :users, only: %i[show create edit update] do
member do
get :followings
get :followers
get :favorites
get :bookcases
get :draft
end
end
resources :favorites, only: %i[create destroy]
resources :relationships, only: %i[create destroy]
resources :bookcases, only: %i[create destroy]
get 'books/search', to: "books#search"
resources :books, only: %i[show] do
resources :reviews, only: %i[show create update destroy] do
resources :comments, only: %i[create update edit destroy]
end
collection do
get "reviews", to: "reviews#index"
end
end
resources :notifications, only: %i[index]
end
<file_sep>/app/controllers/comments_controller.rb
# frozen_string_literal: true
class CommentsController < ApplicationController
before_action :require_login
before_action :set_comment, only: %i[update edit destroy comment_correct_user]
before_action :set_review
before_action :set_comments, only: %i[create edit destroy]
before_action :comment_correct_user, only: %i[update edit destory]
def create
@comment = current_user.comments.build(comment_params)
if @comment.save
@review.create_notification_comment(current_user, @comment.id)
else
render "post/show"
flash[:alert] = "コメントを(140文字以内で)入力してください"
end
end
def update
if @comment.update(comment_params)
redirect_to book_review_path(@review.book, @review)
else
redirect_back(fallback_location: root_path)
flash[:alert] = "コメントを(140文字以内で)入力してください"
end
end
def edit
@book = @review.book
render "reviews/show"
end
def destroy
@comment.destroy
end
private
def set_comment
@comment = Comment.find(params[:id])
end
def set_review
@review = Review.find(params[:review_id])
end
def set_comments
@comments = @review.comments.order(id: :desc)
end
def comment_params
params.require(:comment).permit(:content, :review_id)
end
def comment_correct_user
redirect_to root_url unless @comment.user_id == current_user.id
end
end
<file_sep>/app/models/book.rb
# frozen_string_literal: true
class Book < ApplicationRecord
self.primary_key = "isbn"
has_many :reviews, dependent: :destroy
has_many :bookcases, dependent: :destroy
end
<file_sep>/app/models/relationship.rb
# frozen_string_literal: true
class Relationship < ApplicationRecord
belongs_to :user
belongs_to :follow, class_name: "User"
validates_uniqueness_of :follow_id, scope: :user_id
end
<file_sep>/app/controllers/bookcases_controller.rb
# frozen_string_literal: true
class BookcasesController < ApplicationController
before_action :require_login
before_action :set_book
def create
current_user.register(@book)
end
def destroy
current_user.unregister(@book)
end
private
def set_book
@book = Book.find_by(isbn: params[:book_id])
end
end
<file_sep>/spec/models/user_spec.rb
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe User, type: :model do
before do
@user = FactoryBot.build(:user)
end
context "新規登録ができる時" do
it "name, email, passwordが正しく入力されれば有効" do
expect(@user).to be_valid
end
it "nameが1〜20文字であれば有効" do
@user.name = Faker::Internet.username(specifier: 1..20)
expect(@user).to be_valid
end
it "passwordが1〜72文字、半角英数字、password_confirmationと一致していれば有効" do
@user.password = Faker::Internet.password(min_length: 1, max_length: 72)
@user.password_confirmation = <PASSWORD>
expect(@user).to be_valid
end
end
describe "新規登録できない時" do
context "nameについて" do
it "nameが空であるとエラーが発生" do
@user.name = nil
@user.valid?
expect(@user.errors.full_messages).to include("名前を入力してください")
end
it "nameが20文字より多いとエラーが発生" do
@user.name = Faker::Name.initials(number: 21)
@user.valid?
expect(@user.errors.full_messages).to include("名前は20文字以内で入力してください")
end
end
context "emailについて" do
it "emailが空であるとエラーが発生" do
@user.email = nil
@user.valid?
expect(@user.errors.full_messages).to include("メールアドレスを入力してください")
end
it "emailが255文字より多いとエラーが発生" do
@user.email = Faker::Internet.email(name: "a" * 255)
@user.valid?
expect(@user.errors.full_messages).to include("メールアドレスは255文字以内で入力してください")
end
it "emailに'@'がないとエラーが発生" do
@user.email = "aaaaa.aa"
@user.valid?
expect(@user.errors.full_messages).to include("メールアドレスは不正な値です")
end
it "emailの'@'の後に'.'がないとエラーが発生" do
@user.email = "aaaaa@aa"
@user.valid?
expect(@user.errors.full_messages).to include("メールアドレスは不正な値です")
end
end
context "passwordについて" do
it "passwordが空だとエラーが発生" do
@user.password = nil
@user.password_confirmation = <PASSWORD>
@user.valid?
expect(@user.errors.full_messages).to include("パスワードを入力してください")
end
it "passwordが72文字よりも多いとエラーが発生" do
@user.password = <PASSWORD>(min_length: 73)
@user.password_confirmation = <PASSWORD>
@user.valid?
expect(@user.errors.full_messages).to include("パスワードは72文字以内で入力してください")
end
it "passwordとpassword_confirmationが一致しないとエラーが発生" do
@user.password = <PASSWORD>
@user.valid?
expect(@user.errors.full_messages).to include("確認用パスワードとパスワードの入力が一致しません")
end
end
end
end
<file_sep>/app/models/user.rb
# frozen_string_literal: true
class User < ApplicationRecord
validates :name, presence: true, length: { maximum: 20 }
validates :email, presence: true, length: { maximum: 255 },
format: { with: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i },
uniqueness: { case_sensitive: false }
has_secure_password
enum gender: { "男性": 1, "女性": 2 }
mount_uploader :user_image, UserImageUploader
has_many :reviews, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :relationships, dependent: :destroy
has_many :followings, through: :relationships, source: :follow
has_many :reverses_relationship, class_name: 'Relationship', foreign_key: 'follow_id', dependent: :destroy
has_many :followers, through: :reverses_relationship, source: :user
has_many :favorites, dependent: :destroy
has_many :favorings, through: :favorites, source: :review
has_many :bookcases, dependent: :destroy
has_many :register_books, through: :bookcases, source: :book
has_many :active_notifications, class_name: "Notification", foreign_key: "visitor_id", dependent: :destroy
has_many :passive_notifications, class_name: "Notification", foreign_key: "visited_id", dependent: :destroy
def feed_reviews
Review.where(user_id: following_ids + [id]).includes(:user, :book)
end
def follow(other_user)
relationships.find_or_create_by(follow_id: other_user.id) unless self == other_user
end
def unfollow(other_user)
relationship = relationships.find_by(follow_id: other_user.id)
relationship&.destroy
end
def following?(other_user)
followings.include?(other_user)
end
def favor(other_review)
favorites.find_or_create_by(review_id: other_review.id)
end
def unfavor(other_review)
favorite = favorites.find_by(review_id: other_review.id)
favorite&.destroy
end
def favoring?(other_review)
favorings.include?(other_review)
end
def register(other_book)
bookcases.find_or_create_by(book_id: other_book.isbn)
end
def unregister(other_book)
bookcase = bookcases.find_by(book_id: other_book.isbn)
bookcase&.destroy
end
def register?(other_book)
register_books.include?(other_book)
end
def create_notification_follow(current_user)
temp = Notification.where(["visitor_id = ? and visited_id = ? and action = ?", current_user.id, id, "follow"])
return unless temp.blank?
notification = current_user.active_notifications.new(
visited_id: id,
action: "follow"
)
notification.save if notification.valid?
end
end
<file_sep>/app/controllers/reviews_controller.rb
# frozen_string_literal: true
class ReviewsController < ApplicationController
before_action :require_login, except: %i[show]
before_action :set_review, only: %i[show update destroy review_correct_user]
before_action :set_book, only: %i[show create update destroy]
before_action :review_correct_user, only: %i[update destroy]
before_action :confirm_draft, only: %i[show update destroy]
def index
@reviews = Review.where(status: 1).includes(:book, :user).order(created_at: :desc).page(params[:page]).per(6)
end
def show
@comments = @review.comments.includes(:book, :user).order(id: :desc)
@comment = Comment.new
end
def create
@review = current_user.reviews.build(review_params)
draft_judge
if @review.save
@review.save
flash[:success] = "投稿しました"
redirect_to book_review_path(@book, @review)
else
flash[:danger] = "レビューが空欄です。投稿できませんでした。"
redirect_to book_url(@book)
end
end
def update
draft_judge
if @review.update(review_params)
flash[:success] = "投稿しました"
else
flash[:danger] = "レビューが空欄です。投稿できませんでした"
end
redirect_to book_review_path(@book, @review)
end
def destroy
@review.destroy
flash[:success] = "投稿を削除しました"
redirect_to root_url
end
private
def review_params
params.require(:review).permit(:content, :status, :book_id)
end
def set_review
@review = Review.find(params[:id])
end
def set_book
@book = Book.find_by(isbn: params[:book_id])
end
def review_correct_user
root_url unless @review.user == current_user
end
def confirm_draft
redirect_to root_path if @review.draft? && @review.user.id != current_user.id
end
def draft_judge
case params[:commit]
when "公開する"
@review.status = "published"
when "下書きする"
@review.status = "draft"
end
end
end
<file_sep>/spec/models/notification_spec.rb
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Notification, type: :model do
before do
@notification = FactoryBot.build(:notification)
end
context "通知が問題なく実行できる時" do
it "全て値が正常であれば、有効" do
expect(@notification).to be_valid
end
end
context "通知でエラーが発生する時" do
it "通知対象のuserがいないとエラーが発生" do
@notification.visited = nil
@notification.valid?
expect(@notification.errors.full_messages).to include("Visitedを入力してください")
end
end
end
<file_sep>/spec/models/favorite_spec.rb
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Favorite, type: :model do
before do
@favorite = FactoryBot.build(:favorite)
end
context "お気に入り登録できる時" do
it "まだお気に入り登録をしていない時有効" do
expect(@favorite).to be_valid
end
end
context "アソシエーションについて" do
it "userがいないとエラーが発生" do
@favorite.user = nil
@favorite.valid?
expect(@favorite.errors.full_messages).to include("Userを入力してください")
end
it "お気に入り対象のreviewがないとエラーが発生" do
@favorite.review = nil
@favorite.valid?
expect(@favorite.errors.full_messages).to include("Reviewを入力してください")
end
it '既にお気に入り登録したreviewをお気に入り登録するとエラーが発生' do
@favorite.save
@favorite_repeat = FactoryBot.build(:favorite)
@favorite_repeat.user = @favorite.user
@favorite_repeat.review = @favorite.review
@favorite_repeat.valid?
expect(@favorite_repeat.errors.full_messages).to include("Reviewはすでに存在します")
end
end
end
<file_sep>/spec/factories/notifications.rb
# frozen_string_literal: true
FactoryBot.define do
factory :notification do
association :visited, factory: :user
association :visitor, factory: :user
association :review
association :comment
checked { false }
end
end
<file_sep>/app/helpers/bookcases_helper.rb
# frozen_string_literal: true
module BookcasesHelper
end
<file_sep>/db/migrate/20201220063200_add_book_to_reviews.rb
# frozen_string_literal: true
class AddBookToReviews < ActiveRecord::Migration[6.0]
def change
add_reference :reviews, :book, null: false
end
end
<file_sep>/app/controllers/users_controller.rb
# frozen_string_literal: true
class UsersController < ApplicationController
before_action :require_login, only: %i[show edit update followings followers favorites bookcases draft]
before_action :set_user, only: %i[show edit update followings followers favorites bookcases draft self_user]
before_action :self_user, only: %i[edit update draft]
def show
@reviews =
if current_user == @user
@user.feed_reviews.where(status: 1).order(updated_at: :desc).page(params[:page]).per(6)
else
@user.reviews.where(status: 1).includes(:user, :book).order(updated_at: :desc).page(params[:page]).per(6)
end
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
redirect_to root_url
flash[:success] = "ユーザー登録完了しました。"
session[:user_id] = @user.id
else
render :new
flash.now[:danger] = "ユーザー登録ができませんでした。"
end
end
def edit; end
def update
if @user.update(profile_params)
flash[:success] = 'プロフィールを更新しました。'
redirect_to @user
else
render :edit
flash.now[:danger] = 'プロフィーを更新できませんでした。'
end
end
def followings
@followings = @user.followings.order(id: :desc).page(params[:page]).per(9)
end
def followers
@followers = @user.followers.order(id: :desc).page(params[:page]).per(9)
end
def favorites
@favorites = @user.favorings.order(updated_at: :desc).page(params[:page]).per(6)
end
def bookcases
@bookcases = @user.register_books.order(updated_at: :desc).page(params[:page]).per(10)
end
def draft
@draft_reviews = @user.reviews.where(status: 0).includes(:user, :book).order(updated_at: :desc).page(params[:page]).per(10)
end
private
def set_user
@user = User.find(params[:id])
end
def self_user
redirect_to root_url unless @user == current_user
end
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
def profile_params
params.require(:user).permit(:name, :gender, :user_image, :birthday, :introduction)
end
end
<file_sep>/README.md
# Share-read
<img width="1435" alt="github用トップ画" src="https://user-images.githubusercontent.com/65746218/103641220-c4c60d00-4f94-11eb-8c87-594d2ef81e95.png">
## :page_facing_up:概要
Share-readはビジネス本をアウトプットするwebアプリです。<br>
人に本の内容をshareすることで、本の知識を自分のものにすることを目的としています。
### 制作背景
社会人になってから、ビジネス本や自己啓発本を読むようになりました。<br>
しかし、読んだらそれっきりになり、せっかく読んだ本の内容もあまり覚えておりませんでした。
ある時アウトプット大全という本を読み、本のアウトプットの重要性を考えさせられました。<br>
そこで、本の内容をアウトプットするために、読書会に参加することにしました。<br>
読んだ本をまとめて人に共有するという工程を踏むだけでも、これまでの読書と打って変わり、本の知識が頭に深く残っていました。<br>
さらに、業務中も本の知識を活かせるようになってきました。<br>
以前の私のように本を読んで終わってしまっている方は、少なからずいるのではないかと考えました。<br>
読書というのは読んで終わりではなく、本の知識を自分の知識として使える状態にすることがゴールであると私は考えております。<br>
そのような考えから本の内容をアウトプットするwebアプリ『Share-read』を開発しようと思いました。
### URL
https://share-read.jp
## :wrench:機能
- ユーザー関連
- 新規登録機能 / 登録情報編集機能
- ログイン機能 / ゲストログイン機能(ポートフォリオをご覧になる際は、こちらをご利用ください)
- フォロー機能(ajaxの利用)
- 通知機能
- 本関連
- 本の検索機能(楽天APIの利用)
- 本棚登録機能(ajaxの利用)
- 楽天の購入ページへのリンク追加
- レビュー関連
- レビュー投稿機能/レビュー編集機能
- レビューの下書き機能
- お気に入り機能(ajaxの利用)
- コメント投稿・削除機能(ajaxの利用)
- コメント編集機能
## :computer:操作
- 本の検索

- レビューの投稿

## :open_file_folder:環境・使用技術
### フロントエンド
- Bootstarp 4.50
- HTML、CSS
- JavaScript、jQuery
### バックエンド
- Ruby 2.7.2
- Rails 6.0.3.4
### 開発環境
- Docker/Docker-compose
- MySQL 5.7
### 本番環境
- AWS(VPC、EC2、RDS for MySQL、S3、ALB、 IAM、Route53)
- MySQL 5.7
- Nginx、puma
- Capistrano
###ER図
<img width="625" alt="ER図" src="https://user-images.githubusercontent.com/65746218/104142775-5227b800-5400-11eb-8303-5c2a5ce25fc2.png">
### インフラ構成図

## :eyes:Anout me
Wantedly、Qiitaをやっています。
よろしければご覧になってください。
Wantedly https://www.wantedly.com/id/hiroaki_ueda_0329
<br>Qiita https://qiita.com/Hiroaki_jr
<file_sep>/app/controllers/books_controller.rb
# frozen_string_literal: true
class BooksController < ApplicationController
before_action :require_login, only: %i[show]
def show
@book = Book.find_by(isbn: params[:id])
@bookcase = Bookcase.new
@reviews = @book.reviews.where(status: 1).order(updated_at: :desc).page(params[:page]).per(6)
@review = current_user.reviews.new
end
def search
@books = []
@title = params[:title]
if @title.present?
results = RakutenWebService::Books::Book.search({ title: @title })
results.each do |result|
book = Book.new(read(result))
bussiness_book_id = %w[001001 001005 001006 001008 001028]
@books << book if bussiness_book_id.any? { |i| book.book_genre_id.include?(i) }
end
end
@books.each do |book|
book.save unless Book.all.include?(book)
end
end
private
def read(result)
title = result["title"]
author = result["author"]
url = result["itemUrl"]
isbn = result["isbn"]
image_url = result["mediumImageUrl"].gsub('?_ex=120x120', '')
book_genre_id = result["booksGenreId"]
caption = result["itemCaption"]
{
title: title,
author: author,
url: url,
isbn: isbn,
image_url: image_url,
book_genre_id: book_genre_id,
caption: caption
}
end
end
<file_sep>/app/helpers/users_helper.rb
# frozen_string_literal: true
module UsersHelper
def user_age
if @user.birthday
user_birthday = @user.birthday.strftime("%Y%m%d").to_i
today = Date.today.strftime("%Y%m%d").to_i
@age ||= (today - user_birthday) / 10_000.round
else
@age = "-"
end
end
end
<file_sep>/app/controllers/favorites_controller.rb
# frozen_string_literal: true
class FavoritesController < ApplicationController
before_action :require_login
before_action :set_review
def create
current_user.favor(@review)
@review.create_notification_favorite(current_user)
end
def destroy
current_user.unfavor(@review)
end
private
def set_review
@review = Review.find(params[:review_id])
end
end
<file_sep>/app/models/bookcase.rb
# frozen_string_literal: true
class Bookcase < ApplicationRecord
belongs_to :user
belongs_to :book, primary_key: "isbn"
validates_uniqueness_of :book_id, scope: :user_id
end
<file_sep>/spec/factories/comments.rb
# frozen_string_literal: true
FactoryBot.define do
factory :comment do
content { Faker::String.random(length: 1..255) }
association :user
association :review
end
end
<file_sep>/db/migrate/20201218075413_add_bookgenreid_to_books.rb
# frozen_string_literal: true
class AddBookgenreidToBooks < ActiveRecord::Migration[6.0]
def change
add_column :books, :book_genre_id, :string
end
end
<file_sep>/spec/factories/bookcases.rb
# frozen_string_literal: true
FactoryBot.define do
factory :bookcase do
association :user
association :book
end
end
<file_sep>/spec/models/comment_spec.rb
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Comment, type: :model do
before do
@comment = FactoryBot.build(:comment)
end
context "投稿できる時" do
it "contentが正しければ有効" do
expect(@comment).to be_valid
end
it "contentが1文字であれば有効" do
@comment.content = "a"
expect(@comment).to be_valid
end
it "contentが255文字であれば有効" do
@comment.content = Faker::String.random(length: 255)
expect(@comment).to be_valid
end
end
describe "投稿できない時" do
context "contentについて" do
it "contentがnilである時エラーが発生" do
@comment.content = nil
@comment.valid?
expect(@comment.errors.full_messages).to include("コメントを入力してください")
end
it "contentが1200文字以上である時エラーが発生" do
@comment.content = Faker::String.random(length: 256)
@comment.valid?
expect(@comment.errors.full_messages).to include("コメントは255文字以内で入力してください")
end
end
context "アソシエーションについて" do
it "userが紐付いていないと保存できない" do
@comment.user = nil
@comment.valid?
expect(@comment.errors.full_messages).to include("Userを入力してください")
end
it "reviewが紐付いていないと保存できない" do
@comment.review = nil
@comment.valid?
expect(@comment.errors.full_messages).to include("Reviewを入力してください")
end
end
end
end
|
08d2e901c4bc885d765b80183a45cded2a2e36d9
|
[
"Markdown",
"Ruby"
] | 35
|
Ruby
|
hiroaki-u/share-read
|
804660a740522e0d06bcf7c23b97c3c6cfe0e9a7
|
5e6727f12c28573fc51dc7c7cd7ad8877b174810
|
refs/heads/master
|
<repo_name>radovanovicslobodan/style-key-chris<file_sep>/js/info-modals.js
/*
Author: <NAME>
Desctiption:
This jQuery code is for modal windows which
appears on pages: measurements-men.html
and measurements-women.html
*/
$(function() {
var modalSettings = {
effect: "fadein",
overlayColor: "#fff",
overlayOpacity: "0.5"
};
var $infoModalsItems = $('a.info-btn');
$infoModalsItems.on('click', function ( e ) {
$.fn.custombox( this, modalSettings);
e.preventDefault();
});
});
<file_sep>/README.md
preview of some pages:\
https://radovanovicslobodan.github.io/style-key-chris/
https://radovanovicslobodan.github.io/style-key-chris/profile.html
https://radovanovicslobodan.github.io/style-key-chris/shop-welcome.html
https://radovanovicslobodan.github.io/style-key-chris/friends.html
https://radovanovicslobodan.github.io/style-key-chris/measurements-women.html
|
17305d9d82ca9bc055ca9400f653887a0f1cf91e
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
radovanovicslobodan/style-key-chris
|
e0be3f53b07422fc95951224c994aef1952059a7
|
70da6dd384266d86806f7b42a2f1e21d5e5c61e3
|
refs/heads/master
|
<file_sep>import React, { useState } from "react"
import styled from "styled-components"
import { Link } from "gatsby"
import Scrollspy from "react-scrollspy"
import Resume from "./resume"
const StyledHeader = styled.header`
height: 100px;
display: flex;
justify-content: center;
align-items: center;
background: transparent;
width: 100%;
transition: 0.4s;
position: absolute;
.navbar {
&__container {
display: flex;
justify-content: space-between;
align-items: center;
z-index: 10;
}
&__logo {
font-family: "Grand Hotel";
font-size: 36px;
color: white;
transition: 0.2s ease;
text-shadow: 0px 0px 10px black;
&:hover {
color: #02d463;
transition: 0.2s ease;
}
}
&__link {
margin-left: 20px;
transition: 0.2s;
text-shadow: 0px 0px 10px black;
&:hover:not(.navbar__resume) {
color: #02d463;
transition: 0.2s;
}
}
}
`
const Header = () => {
const [condition, setCondition] = useState(false)
return (
<StyledHeader id="nav">
<Scrollspy
id="sidenav"
className={condition ? "sidenav sidenav--open" : "sidenav"}
style={{ padding: 0 }}
items={["home", "about", "projects", "contact"]}
currentClassName="colored"
>
<Link to="/#home" className="navbar__link" style={{ display: "none" }}>
Home
</Link>
<Link to="/#about" onClick={() => setCondition(!condition)}>
About
</Link>
<Link to="/#projects" onClick={() => setCondition(!condition)}>
Projects
</Link>
<Link to="/#contact" onClick={() => setCondition(!condition)}>
Contact
</Link>
<Resume />
</Scrollspy>
<nav id="navbar" className="navbar__container container--secondary">
<Link to="/#" className="navbar__logo">
sKug
</Link>
<div className="hamburger__container">
<button
aria-label="menu"
className="hamburger"
onClick={() => setCondition(!condition)}
onKeyDown={() => setCondition(!condition)}
>
<div
className={
condition
? "hamburger__wrapper icon close"
: "hamburger__wrapper icon"
}
>
<span className="hamburger--line top"></span>
<span className="hamburger--line middle"></span>
<span className="hamburger--line bottom"></span>
</div>
</button>
</div>
<Scrollspy
className="navbar__links"
items={["home", "about", "projects", "contact"]}
currentClassName="colored"
>
<Link
to="/#home"
className="navbar__link"
style={{ display: "none" }}
>
Home
</Link>
<Link to="/#about" className="navbar__link">
About
</Link>
<Link to="/#projects" className="navbar__link">
Projects
</Link>
<Link to="/#contact" className="navbar__link">
Contact
</Link>
<Resume />
</Scrollspy>
</nav>
</StyledHeader>
)
}
export default Header
<file_sep>import React from "react"
import styled from "styled-components"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { OutboundLink } from "gatsby-plugin-google-analytics"
const StyledFooter = styled.footer`
height: 100px;
display: flex;
justify-content: center;
align-items: center;
background: #111;
color: white;
border-top: 1px solid #212121;
.footer {
&__container {
display: flex;
justify-content: space-between;
align-items: center;
}
&__link {
color: white;
margin-right: 20px;
transition: 0.2s;
&:hover {
color: #02d463;
transition: 0.2s;
}
svg {
width: 20px;
height: 20px;
filter: drop-shadow(0px 0px 3px black);
}
}
&__copy {
font-size: 14px;
}
&__credit {
font-size: 12px;
color: #333;
}
}
`
const Footer = () => {
return (
<StyledFooter>
<div className="container container--secondary">
<div className="footer__container container--primary">
<div className="footer__links">
<OutboundLink
href="https://www.instagram.com/sieroniekuggy/"
target="_blank"
rel="noopener noreferrer"
className="footer__link"
title="Instagram"
>
<FontAwesomeIcon
data-sal="fade"
data-sal-easing="ease"
icon={["fab", "instagram"]}
className="about__icon"
/>
</OutboundLink>
<OutboundLink
href="https://www.instagram.com/sieroniekuggyofficial/"
target="_blank"
rel="noopener noreferrer"
className="footer__link"
title="Facebook"
>
<FontAwesomeIcon
data-sal="fade"
data-sal-easing="ease"
icon={["fab", "facebook"]}
className="about__icon"
/>
</OutboundLink>
<OutboundLink
href="https://github.com/sieroniekuggy"
target="_blank"
rel="noopener noreferrer"
className="footer__link"
title="GitHub"
>
<FontAwesomeIcon
data-sal="fade"
data-sal-delay="100"
data-sal-easing="ease"
icon={["fab", "github"]}
className="about__icon"
/>
</OutboundLink>
<OutboundLink
href="https://www.twitter.com/in/sieroniekuggy/"
target="_blank"
rel="noopener noreferrer"
className="footer__link"
title="LinkedIn"
>
<FontAwesomeIcon
data-sal="fade"
data-sal-delay="200"
data-sal-easing="ease"
icon={["fab", "twitter"]}
className="about__icon"
/>
</OutboundLink>
<a
href="https://wa.me/8615653242335"
className="footer__link"
title="Email"
>
<FontAwesomeIcon
data-sal="fade"
data-sal-delay="300"
data-sal-easing="ease"
icon="envelope"
/>
</a>
<OutboundLink
href="/resume.pdf"
target="_blank"
rel="noopener noreferrer"
className="footer__link"
title="Resume"
>
<FontAwesomeIcon
data-sal="fade"
data-sal-delay="400"
data-sal-easing="ease"
icon="paperclip"
/>
</OutboundLink>
</div>
<div className="footer__desc section__desc">
<p
data-sal="fade"
data-sal-delay="500"
data-sal-easing="ease"
className="footer__copy"
>
Copyright {new Date().getFullYear()} © CodeTrojans
</p>
<p
data-sal="fade"
data-sal-delay="600"
data-sal-easing="ease"
className="footer__credit"
>
Created by{" "}
<a
href="https://tawk.to/codetrojans"
target="_blank"
rel="noopener noreferrer"
title="<NAME> | Full-Stack Developer"
>
<NAME>
</a>
</p>
</div>
</div>
</div>
</StyledFooter>
)
}
export default Footer
<file_sep>import React from "react"
import styled from "styled-components"
import skug from "../images/skug.png"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
const StyledAbout = styled.section`
display: flex;
justify-content: center;
align-items: flex-start;
padding: 100px 0;
.about {
&__container {
align-items: flex-start;
img {
align-self: flex-end;
opacity: 0.4;
transition: 0.5s;
box-shadow: 0px 0px 20px rgba(0, 0, 0, 1);
border-radius: 4px;
&:hover {
opacity: 1;
transition: 0.5s;
}
}
}
&__desc {
width: 40%;
margin-top: 50px;
color: #bdbdbd;
text-align: justify;
}
&__skills {
list-style: none;
margin: 0;
padding: 0;
display: grid;
grid-template-columns: repeat(2, minmax(140px, 200px));
margin-top: 25px;
}
&__skill {
position: relative;
font-size: 14px;
color: #bdbdbd;
margin-bottom: 10px;
}
}
.about__skill:not(.skill__jquery) {
transition: 0.2s;
&:hover {
span {
color: #02d463;
transition: 0.2s;
}
}
}
.skill__icon {
margin-right: 15px;
color: #02d463;
width: 15px;
height: 15px;
}
.skill__jquery {
.skill__icon,
span {
color: #333;
}
span {
text-decoration: line-through;
}
}
`
export default function About() {
return (
<StyledAbout id="about">
<div className="container--secondary container">
<div className="container container--primary about__container">
<div className="about__wrapper">
<h2 data-sal="slide-up" data-sal-easing="ease">
About me
</h2>
<p
data-sal="slide-up"
data-sal-delay="100"
data-sal-easing="ease"
className="about__desc section__desc"
>
I started coding in September 2017 and I am self-taught
developer. I have serious passion for modern looking websites with
a little bit of animations. I love what I am doing and I am highly
motivated to collaborate with someone. If you are up into some
projects, just let me know!
</p>
<p
data-sal="slide-up"
data-sal-delay="200"
data-sal-easing="ease"
className="about__desc section__desc"
>
Technologies that I use:
</p>
<ul
data-sal="slide-up"
data-sal-delay="300"
data-sal-easing="ease"
className="about__skills"
>
<li className="about__skill">
<FontAwesomeIcon
icon={["fab", "laravel"]}
className="skill__icon"
/>
<span>Laravel</span>
</li>
<li className="about__skill">
<FontAwesomeIcon
icon={["fab", "node-js"]}
className="skill__icon"
/>
<span>Node.js</span>
</li>
<li className="about__skill">
<FontAwesomeIcon
icon={["fab", "js-square"]}
className="skill__icon"
/>
<span>JavaScript</span>
</li>
<li className="about__skill">
<FontAwesomeIcon
icon={["fab", "php"]}
className="skill__icon"
/>
<span>PHP</span>
</li>
<li className="about__skill">
<FontAwesomeIcon
icon={["fab", "html5"]}
className="skill__icon"
/>
<span>HTML</span>
</li> <li className="about__skill">
<FontAwesomeIcon
icon={["fab", "css3-alt"]}
className="skill__icon"
/>
<span>CSS3</span>
</li>
<li className="about__skill">
<FontAwesomeIcon
icon={["fab", "sass"]}
className="skill__icon"
/>
<span>S(CSS)</span>
</li>
<li className="about__skill">
<FontAwesomeIcon icon="fire" className="skill__icon" />
<span>Firebase</span>
</li>
<li className="about__skill">
<FontAwesomeIcon
icon={["fab", "bootstrap"]}
className="skill__icon"
/>
<span>Bootstrap</span>
</li>
<li className="about__skill">
<FontAwesomeIcon
icon={["fab", "sketch"]}
className="skill__icon"
/>
<span>Sketch</span>
</li>
<li className="about__skill">
<FontAwesomeIcon
icon={["fab", "adobe"]}
className="skill__icon"
/>
<span>InDesign</span>
</li>
<li className="about__skill">
<FontAwesomeIcon
icon={["fab", "adobe"]}
className="skill__icon"
/>
<span>Photoshop</span>
</li>
<li className="about__skill">
<FontAwesomeIcon
icon={["fab", "adobe"]}
className="skill__icon"
/>
<span>Illustrator</span>
</li>
<li className="about__skill">
<FontAwesomeIcon
icon={["fab", "wordpress"]}
className="skill__icon"
/>
<span>Wordpress</span>
</li>
<li className="about__skill">
<FontAwesomeIcon
icon={["fab", "magento"]}
className="skill__icon"
/>
<span>Magento</span>
</li>
<li className="about__skill">
<FontAwesomeIcon
icon={["fab", "mdb"]}
className="skill__icon"
/>
<span>MDB</span>
</li>
<li className="about__skill">
<FontAwesomeIcon
icon={["fab", "vuejs"]}
className="skill__icon"
/>
<span>VueJs</span>
</li>
<li className="about__skill">
<FontAwesomeIcon
icon={["fab", "react"]}
className="skill__icon"
/>
<span>React</span>
</li>
<li className="about__skill skill__jquery">
<FontAwesomeIcon icon="cross" className="skill__icon" />
<span>jQuery</span>
</li>
</ul>
</div>
<img
data-sal="zoom-in"
data-sal-delay="400"
data-sal-easing="ease"
src={skug}
alt="Sieroniekuggy"
loading="lazy"
/>
</div>
</div>
</StyledAbout>
)
}
<file_sep>import React from "react"
import { graphql, useStaticQuery } from "gatsby"
import styled from "styled-components"
import bg from "../images/bg.jpg"
import Header from "./header"
import Board from "./board"
import { trackCustomEvent } from "gatsby-plugin-google-analytics"
import cross from "../images/decorations/cross.svg"
import tick from "../images/decorations/tick.svg"
import circle from "../images/decorations/circle.svg"
const StyledHero = styled.section`
background-image: url(${bg});
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
height: fit-content;
display: flex;
justify-content: flex-start;
align-items: center;
flex-direction: column;
.hero {
&__container {
justify-content: flex-start;
position: relative;
width: 100%;
margin-top: 100px;
}
&__desc {
width: 38%;
margin: 50px 0;
color: #bdbdbd;
text-align: justify;
}
}
.container__hero--secondary {
border-left: 1px solid #212121;
display: flex;
justify-content: center;
margin: 5rem 0;
}
.colored {
text-shadow: 0px 0px 10px black;
}
`
const StyledContainer = styled.div`
display: flex;
justify-content: center;
align-items: flex-start;
flex-direction: column;
.decoration {
position: absolute;
&__cross {
left: 50%;
top: 0;
transition: 0.2s;
filter: drop-shadow(0px 0px 15px #ff5252);
&:hover {
transform: rotate(180deg);
transition: 0.2s;
filter: none;
}
}
&__tick {
left: 35%;
bottom: 10%;
transition: 0.2s;
filter: drop-shadow(0px 0px 15px #02d463);
&:hover {
transform: scale(0.9);
transition: 0.2s;
filter: none;
}
}
&__circle {
left: 85%;
top: 30%;
transition: 0.2s;
filter: drop-shadow(0px 0px 15px #00cde2);
&:hover {
transform: scale(1.1);
transition: 0.2s;
filter: none;
}
}
}
`
export default function Hero() {
const data = useStaticQuery(graphql`
query {
site {
siteMetadata {
author
role
}
}
}
`)
const { author, role } = data.site.siteMetadata
return (
<StyledHero id="home">
<Header />
<div className="container hero__container">
<div className="container__hero--secondary container--secondary">
<StyledContainer className="container--primary">
<p className="colored" data-sal="slide-up" data-sal-easing="ease">
Hi, I am
</p>
<h1 data-sal="slide-up" data-sal-delay="100" data-sal-easing="ease">
{author}
</h1>
<h2
data-sal="slide-up"
data-sal-delay="200"
data-sal-easing="ease"
className="hero__sub"
>
{role}
</h2>
<p
data-sal="slide-up"
data-sal-delay="300"
data-sal-easing="ease"
className="hero__desc section__desc"
>
I specialize in designing, building, shipping, and scaling
beautiful, usable products with blazing-fast efficiency.
</p>
<div
data-sal="slide-up"
data-sal-delay="400"
data-sal-easing="ease"
>
<a
href="#contact"
className="btn btn--primary"
onClick={e => {
e.preventDefault()
trackCustomEvent({
category: "Get in touch Button",
action: "Click",
label: "Gatsby Google Analytics Get in touch Button",
})
}}
>
Get in touch
</a>
</div>
<img
className="decoration decoration__cross"
src={cross}
alt="cross"
loading="lazy"
/>
<img
className="decoration decoration__tick"
src={tick}
alt="tick"
loading="lazy"
/>
<img
className="decoration decoration__circle"
src={circle}
alt="circle"
loading="lazy"
/>
</StyledContainer>
</div>
<Board />
</div>
</StyledHero>
)
}
<file_sep>import React, { useEffect } from "react"
import styled from "styled-components"
import axios from "axios"
const StyledContact = styled.section`
display: flex;
justify-content: center;
align-items: center;
background: #111;
padding: 100px 0;
.contact {
&__wrapper {
margin: 50px 0;
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
.btn {
margin-top: 2rem;
}
}
&__desc {
text-align: center;
margin: 50px 0;
color: #bdbdbd;
}
}
.input {
&__field {
display: flex;
flex-direction: column;
label {
color: #333;
margin-bottom: 0.5rem;
text-shadow: 0px 0px 10px black;
font-size: 14px;
}
input,
textarea {
border-radius: 4px;
border: 2px solid #1a1a1a;
height: 60px;
width: 100%;
font-family: "JetBrains Mono Medium";
background: transparent;
color: #02d463;
transition: 0.2s;
outline: none;
font-size: inherit;
padding: 15px;
background: #1a1a1a;
box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.5);
&:focus {
border-color: #02d463;
transition: 0.2s;
}
}
textarea {
height: 200px;
resize: none;
}
&--grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 10px;
width: 50%;
}
&.focus input,
&.focus textarea {
border-color: #02d463;
}
&.focus label {
color: #02d463;
transition: 0.2s;
}
}
&__textarea {
margin-top: 1rem;
width: 50%;
}
}
input[type="submit"] {
font-family: "JetBrains Mono Regular";
cursor: pointer;
font-size: inherit;
background: #02d463 !important;
&:hover {
color: #02d463;
background: transparent !important;
}
}
`
export default function Contact() {
const resetForm = () => {
document.getElementById("contact-form").reset()
}
const handleSubmit = e => {
e.preventDefault()
const name = document.getElementById("name").value
const email = document.getElementById("email").value
const message = document.getElementById("message").value
const success = document.getElementById("success")
const failure = document.getElementById("failure")
axios({
method: "POST",
url: "https://formspree.io/mzbjgjkb",
data: {
name: name,
email: email,
message: message,
},
}).then(response => {
if (response.data.msg === "success") {
success.style.display = "block"
resetForm()
} else if (response.data.msg === "fail") {
failure.style.display = "block"
}
})
}
useEffect(() => {
const inputs = document.querySelectorAll(".input__field-input")
function addcl() {
let parent = this.parentNode
parent.classList.add("focus")
}
function remcl() {
let parent = this.parentNode
if (this.value === "") {
parent.classList.remove("focus")
}
}
inputs.forEach(input => {
input.addEventListener("focus", addcl)
input.addEventListener("blur", remcl)
})
}, [])
return (
<StyledContact id="contact">
<div className="container container--secondary">
<div className="container container--primary">
<h2 data-sal="slide-up" data-sal-easing="ease">
Get in touch
</h2>
<div
data-sal="slide-up"
data-sal-delay="100"
data-sal-easing="ease"
className="contact__desc section__desc"
>
Contact me!
</div>
<span id="success" className="colored" style={{ display: "none" }}>
Message sent!
</span>
<span id="failure" style={{ color: "#FF5252", display: "none" }}>
Message failed to sent!
</span>
<form
onSubmit={handleSubmit}
method="POST"
className="contact__wrapper"
id="contact-form"
>
<div className="input__field--grid">
<div
className="input__field"
data-sal="slide-up"
data-sal-delay="200"
data-sal-easing="ease"
>
<label htmlFor="name">Name</label>
<input
aria-label="Name"
required
className="input__field-input"
id="name"
name="name"
type="text"
autoComplete="off"
/>
</div>
<div
className="input__field"
data-sal="slide-up"
data-sal-delay="300"
data-sal-easing="ease"
>
<label htmlFor="email">Email</label>
<input
aria-label="Email"
required
className="input__field-input"
id="email"
name="email"
type="email"
autoComplete="off"
/>
</div>
</div>
<div
className="input__field input__textarea"
data-sal="slide-up"
data-sal-delay="400"
data-sal-easing="ease"
>
<label htmlFor="message">Message</label>
<textarea
aria-label="Message"
required
className="input__field-input"
id="message"
name="message"
></textarea>
</div>
<div
data-sal="slide-up"
data-sal-delay="500"
data-sal-easing="ease"
>
<input
aria-label="Submit"
type="submit"
value="Submit"
className="btn btn--primary"
/>
</div>
</form>
</div>
</div>
</StyledContact>
)
}
<file_sep>import React, { useEffect } from "react"
import GlobalStyle from "../theme/globalStyle"
import styled from "styled-components"
import Footer from "./footer"
const StyledLayout = styled.div`
display: flex;
flex-direction: column;
min-height: 100vh;
main {
flex-grow: 1;
}
`
const Layout = ({ children }) => {
if (typeof window !== "undefined") {
require("smooth-scroll")('a[href*="#"]')
}
useEffect(() => {
window.addEventListener("scroll", () => {
const isTop = window.scrollY > 200
const nav = document.getElementById("nav")
if (isTop) {
nav.classList.add("scrolled")
} else {
nav.classList.remove("scrolled")
}
})
}, [])
return (
<StyledLayout>
<GlobalStyle />
<main>{children}</main>
<Footer />
</StyledLayout>
)
}
export default Layout
<file_sep>import React from "react"
import styled from "styled-components"
import Head from "../components/head"
import Layout from "../components/layout"
import Header from "../components/header"
const StyledNotFoundPage = styled.div`
margin: 100px auto auto;
text-align: center;
h1 {
margin-top: 50px;
}
p {
margin-top: 25px;
}
`
const NotFoundPage = () => (
<Layout>
<Head title="404 Not Found" />
<Header />
<StyledNotFoundPage className="container container--secondary">
<div className="container container--primary">
<h1>NOT FOUND</h1>
<p>You just hit a route that doesn't exist... the sadness.</p>
</div>
</StyledNotFoundPage>
</Layout>
)
export default NotFoundPage
<file_sep><p align="center">
<img src="https://github.com/sieroniekuggy/personal-site/blob/master/src/images/logo.png" width="100" alt="https://www.sieroniekuggy.co.zw logo" />
</p>
<h1 align="center">
sieroniekuggy.co.zw
</h1>
<p align="center">
This is a project of my new, refreshed website, that is free to use.
</p>
<p align="center">
<a href="https://app.netlify.com/sites/eager-lichterman-b07f67/deploys" target="_blank">
<img src="https://api.netlify.com/api/v1/badges/84b336d8-8c1f-484e-ad19-efabafc468f0/deploy-status" alt="Netlify Status" />
</a>
</p>

### Installation and set up:
1. Install [Node.js](https://nodejs.org)
2. CD to the forked repo
```
cd personal-site
```
3. Install the packages
```
npm install
```
4. Start the development server
```
npm start
```
## How to make the Contact Form work?
[Click here](https://github.com/sieroniekuggy/NodeJs-mail.git)
## ⚠️ Using it as Your Portfolio
As I'm making this repo public for all, you can easily get it and use it how you want. But, there is a must. You need to attribute me. You must leave alone the attribution under the copyright statement ("Created By <NAME>").
I created this website only for myself, for portfolio purposes. Now, you can just download it and use it for your purposes.
You can fork this repository, but please give me proper credit by linking back to my website - [sieroniekuggy.co.zw](https://www.sieroniekuggy.co.zw).
Thank you! ❤️
## ✨ What kind of technologies did I use?
- GatsbyJS
- styled-components
- Contentful
- React Helmet
## Follow me!
[Website](https://www.sieroniekuggy.co.zw) • [Instagram](https://www.instagram.com/sieroniekuggy) • [Twitter](https://www.twitter.com/sieroniekuggy) • [Facebook](https://www.facebook.com/sieroniekuggyofficial)
# personal-site
<file_sep>import React from "react"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
const Project = props => {
return (
<div className="work__box">
<video
alt={props.title}
loop={true}
autoPlay={true}
muted={true}
playsInline={true}
>
<source src={props.bgwebm} type="video/webm" />
<source src={props.bgmp4} type="video/mp4" />
</video>
<div className="work__links">
<div>
<a
href={props.github}
target="_blank"
rel="noopener noreferrer"
title="GitHub"
>
<FontAwesomeIcon icon={["fab", "github"]} className="about__icon" />
</a>
<a
href={props.external}
target="_blank"
rel="noopener noreferrer"
title="External"
>
<FontAwesomeIcon icon="external-link-alt" />
</a>
</div>
<span>{props.title}</span>
</div>
</div>
)
}
export default Project
<file_sep>import React from "react"
import styled from "styled-components"
import BoardBox from "./boardBox"
import pagetifyWebM from "../images/projects/pagetify.webm"
import pagetifyMP4 from "../images/projects/pagetify.mp4"
import schoolifyWebM from "../images/projects/schoolify.webm"
import schoolifyMP4 from "../images/projects/schoolify.mp4"
import dojrzewajWebM from "../images/projects/dojrzewaj.webm"
import dojrzewajMP4 from "../images/projects/dojrzewaj.mp4"
import centrummotoWebM from "../images/projects/centrummoto.webm"
import centrummotoMP4 from "../images/projects/centrummoto.mp4"
const StyledBoard = styled.div`
width: 1010px;
height: 600px;
background: #212121;
border-radius: 10px;
box-shadow: 0px 0px 40px rgba(0, 0, 0, 0.5);
position: absolute;
right: -250px;
bottom: -350px;
padding: 25px;
display: grid;
grid-template-columns: repeat(2, 1fr);
grid-gap: 25px;
.board {
&__wrapper {
width: 100%;
height: 100%;
background: #111;
border-radius: 4px;
position: relative;
}
&__box {
width: 100%;
height: 100%;
position: absolute;
outline: none;
top: -15px;
left: -15px;
filter: drop-shadow(0px 0px 10px rgba(0, 0, 0, 0.5));
}
}
.back {
background-size: cover;
background-position: center;
border-radius: 4px;
}
.front {
background: #222;
width: 100%;
height: 100%;
border-radius: 4px;
display: flex;
justify-content: space-evenly;
align-items: center;
flex-direction: column;
}
video,
.back {
position: absolute;
width: 100%;
height: 100%;
will-change: transform, opacity;
}
`
const Board = () => {
return (
<StyledBoard className="board__container">
<div
data-sal="zoom-in"
data-sal-delay="400"
data-sal-easing="ease"
data-sal-duration="500"
>
<BoardBox
bgwebm={pagetifyWebM}
bgmp4={pagetifyMP4}
title="Pagetify"
url="#!"
/>
</div>
<div
data-sal="zoom-in"
data-sal-delay="500"
data-sal-easing="ease"
data-sal-duration="500"
>
<BoardBox
bgwebm={schoolifyWebM}
bgmp4={schoolifyMP4}
title="Schoolify"
url="#!"
/>
</div>
<div
data-sal="zoom-in"
data-sal-delay="600"
data-sal-easing="ease"
data-sal-duration="500"
>
<BoardBox
bgwebm={dojrzewajWebM}
bgmp4={dojrzewajMP4}
title="dojrzewaj.pl"
url="#!"
/>
</div>
<div
data-sal="zoom-in"
data-sal-delay="700"
data-sal-easing="ease"
data-sal-duration="500"
>
<BoardBox
bgwebm={centrummotoWebM}
bgmp4={centrummotoMP4}
title="Centrum Moto"
url="#!"
/>
</div>
</StyledBoard>
)
}
export default Board
|
d22d116fc8151e66b1e02daab7c0c1ca896dac23
|
[
"JavaScript",
"Markdown"
] | 10
|
JavaScript
|
sieroniekuggy/personal-site
|
6f03550975a316831200edbf3537abb45ea23574
|
76b6d79d79aecdbd8ec4fa9bacddeb2cec7e7948
|
refs/heads/master
|
<file_sep>// Ordinarily, you'd generate this data from markdown files in your
// repo, or fetch them from a database of some kind. But in order to
// avoid unnecessary dependencies in the starter template, and in the
// service of obviousness, we're just going to leave it here.
// This file is called `_posts.js` rather than `posts.js`, because
// we don't want to create an `/blog/posts` route — the leading
// underscore tells Sapper not to do that.
const posts = [
{
title: "February's goal: 20 worshippers on the streets",
slug: "februarys-goal-20-worshiping-in-the-streets",
html: `<img src="/img/princess-street.jpg" style="width: 100%; margin: 16px 0 0" />
<p>Omysoul is a worship tool. Its aim is to gather thousands of people into the streets to worship Jesus.
One phone is used to control the verse displayed on the phone screens of everybody singing. After dusk (which is 3PM
in our Scottish winters) a battery powered projector is also used to throw lyrics against walls.
<p>Join us by the Duke of Wellington Statue on Princess St (<a href="https://www.google.com/maps/place/Wellington,+Edinburgh+EH1+3YY/@55.9536861,-3.1896701,16.77z/data=!4m8!1m2!2m1!1sduke+wellinton+statue,+edinburgh!3m4!1s0x4887c78e53e1243d:0x6f13cbaac7e1a454!8m2!3d55.9534934!4d-3.1891693" target="_blank">Map</a>).<br>
The projector battery only lasts one hour so please come on time:
<h2>Saturday 15th February 5pm</h2>
<p><span style="color: red">Due to high winds and rain tonight's worship is cancelled, please let others know.</span>
<h2>Saturday 22nd February 7pm</h2>
<p>The values of the world have drifted far away from the values of God. It is tempting for Christians to be silent and embarrassed about a
God who is so different. But that's the essence of the word <b>"Holy"</b> is means <b>"different"</b>.
And God is not just "Holy" he is <b>"Holy, Holy, Holy"</b> he is <b>"different, different, different"</b>. And we have been chosen to be:
<blockquote>a <b>holy</b> nation, a <b>peculiar</b> people;</blockquote>
<p>And this is not so we can hide our differentness, but that we should:
<blockquote>... show forth the praises of him who has called us out
of darkness into his marvellous light; <br><i>(1 Peter 2:9)</i></blockquote>
<img src="/img/light.jpg" style="width: 100%; margin: 16px 0 0" />
<p>For Christmas time 2020 we want to see multiple gatherings of tens, hundreds and some of thousands in the streets
of cities and towns around the world. All singing praise to the one who sent his Son into the world to save it from its sin.
<p>A journey of a thousand miles starts with a single step. In January this year we were able to successfully test the technology
out in the street (see picture above). Now in February we have the goal to gather 20 in the street at one time to praise. Ultimately for this to
grow every person that comes must also be a gatherer. Please share this post with friends who are passionate about Jesus. The
goal for March will be 40 people.
<div style="display: flex; align-items: center">
<a href="https://twitter.com/share?ref_src=twsrc%5Etfw"
class="twitter-share-button"
data-size="large"
data-text="Come and worship on the street. Duke of wellington Statue 5pm, Edinburgh, Saturday 15th & 22nd Feb."
data-url="https://omysoul.io/blog/februarys-goal-20-worshiping-in-the-streets"
data-hashtags="omysoul" data-related="omysoul6" data-show-count="false">Tweet</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<div style="width: 8px; height: 2px;"></div>
<div class="fb-share-button"
data-href="https://omysoul.io/blog/februarys-goal-20-worshiping-in-the-streets"
data-layout="button_count">
</div>
</div>
<p><a href="https://twitter.com/omysoul6?ref_src=twsrc%5Etfw" class="twitter-follow-button" data-show-count="false">Follow @omysoul6</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<p><i>Sign up to the newsletter or follow on twitter to be alerted to last minute changes. </i>
`
},
{
title: "Selling the soul - Worship and copyright",
slug: "selling-the-soul-worship-and-copyright",
html: `
<p>The vision of omysoul is to see people out on the street worshiping Jesus. To solve the technical
problems with this I have written an app that allows lyrics to be displayed simultaionously on mobile
phone screens and battery powered projectors.
<img src="/img/princess-street.jpg" style="width: 100%; margin: 16px 0" />
<p>One mobile phone controls which verse is displayed on the projector and other phone
screens. Organising an outdoor worship event is as simple as putting
a post on social media with a location and a time and seeing who turns up.
One problem with this is that nearly all modern worship artists (whose songs we sing in churches) have sold all the rights to their songs
to big secular multinational media conglomerates. I really want the app to be free to use. No passers by is going to whip out credit card
to see song lyrics.
<p>While most Christian artists sing words to the effect:
<ul>
<li>I'm giving it all away, away
<li>I surrender all
<li>Nothing do I withhold
<li>Freely we must give
<li>You can have it all Lord
<li>I'm laying down my rights
</ul>
<p>The reality is that all the rights to these songs are reserved. These worship leaders extract money every time their songs are sung.
They do so in a way that is highly inefficient. What is worse is who the rights
have been sold to: the same media organisations that represent:
<ul>
<li>Rihanna
<li><NAME>
<li>JayZ
<li><NAME>
</ul>
<p>We are relying on the ones pumping out sewage to corrupt the world to provide fresh drinking water for the Church. Our
worship songs have been bought by Mammon and now we need to ask his permission to sing them.
<p>Seporate licences are need for:
<ul>
<li>Sheet music
<li>Lyrics displayed on the projector
<li>Outside performance
<li>Publicly playing music when you own the download
<li>Recording a performance (to put on YouTube)
</ul>
<p>You also need to have a covering organisation and to know the numbers that will be present.
This does not work with the adhoc nature of worship we want to promote with omysoul.
<blockquote>Jesus declared, "Believe me, woman, a time is coming when you will worship the Father
neither on this mountain nor in Jerusalem.<br><i>(John 4:20,21)</i></blockquote>
<p>Worship is meant to be a spontainous part of our lives, something we do wherever we go. Without the need to create a covering
organisation. Currently if two believers want to worship together independantly of their churches the licence costs <b>£39</b> and
that just covers the lyrics.
<h2>Worship as a product</h2>
The Christian Copyright Licensing International (CCLI) is the organisation that deals with the licensing of most Christian music.
They describe their role like this on their website:
<blockquote>It’s about treating content owners and artists fairly, legally,
and honestly while at once discovering new markets for <b>excellent product</b>.</blockquote>
<p>Jesus had something to say about markets and worship:
<blockquote>"Get these out of here! How dare you turn my Father's house into a market!"<br> <i>(John 2:16)</i></blockquote>
<p>There is a different licence for every type of organisation and different licence for every possible use of a song.
When I ask about a suitable licence that allows small numbers of believers from different churches to worship together
at a reasonable price, I understand why I get no answer.
<p>A licence that charged a flat fee per worshipper per song would destroy the need for all the other licences.
CCLI recieves disproportionaly more money from small fellowships. Church plants under 15 people pay <b>36 times</b> more per
head per year than mega churches of 10000. A one off event lasting a week pays <b>25 times</b> more (per song per person) than weekly church meetings.
Songs sung by 14 people in a one off event in the open air cost a staggering <b>450 times</b> more than the
same songs sung in a mega church. The current price structure is a tax on mission and church planting. The pricing structure
also implies a large proportion of the CCLI fee goes to the CCLI as an administration fee and does not reach artists.
<div style="display: flex; justify-content: space-around">
<style>
table {
border-collapse: collapse;
}
th {
color: rgb(226, 124, 0);
font-weight: bold;
padding: 16px 16px;
text-align: left;
}
td
{
padding: 8px 16px;
}
tr:nth-child(2n) td {
background: rgb(247, 247, 247);
}
tr:nth-child(2n+1) td {
background: rgb(217, 217, 217);
}
</style>
<table>
<thead>
<tr><th colspan=2 style="background: rgb(226, 124, 0); color: white; font-weight: normal">Annual Licence</th></tr>
<tr><th>Size</th><th>Annual Cost</th></tr>
</thead>
<tbody>
<tr><td>1-14</td><td>£54.00</td></tr>
<tr><td>15-49</td><td>£78.00</td></tr>
<tr><td>50-99</td><td>£136.00</td></tr>
<tr><td>100-249</td><td>£222.00</td></tr>
<tr><td>250-499</td><td>£308.00</td></tr>
<tr><td>500-999</td><td>£406.00</td></tr>
<tr><td>1,000-1,499</td><td>£498.00</td></tr>
<tr><td>1,500-2,999</td><td>£616.00</td></tr>
<tr><td>3,000-4,999</td><td>£782.00</td></tr>
<tr><td>5,000-9,999</td><td>£1,068.00</td></tr>
</tbody>
</table>
<table>
<thead>
<tr><th colspan=2 style="background: rgb(0, 129, 109);; color: white; font-weight: normal">Event Licence</th></tr>
<tr><th>Size</th><th>Annual Cost</th></tr>
</thead>
<tbody>
<tr><td>1-49</td><td>£39.00</td></tr>
<tr><td>50-99</td><td>£68.00</td></tr>
<tr><td>100-249</td><td>£111.00</td></tr>
<tr><td>250-499</td><td>£154.00</td></tr>
<tr><td>500-999</td><td>£203.00</td></tr>
<tr><td>1,000-1,499</td><td>£249.00</td></tr>
<tr><td>1,500-2,999</td><td>£308.00</td></tr>
<tr><td>3,000-4,999</td><td>£391.00</td></tr>
<tr><td>5,000-9,999</td><td>£534.00</td></tr>
</tbody>
</table>
</div>
<p>Working in computing I find this pricing structure hard to justify for what should be a fairly automated process.
The CCLI collects statistics and money from a pool of users and then distributes the money to the artists according to
the statistics. All the maths can be automated, as can sign up and payments. For Amazon, Google and Microsoft's cloud services
you pay a pretty flat fee. Use one server for one year and you pay the same as using 365 servers for one day.
One person singing a song on 365 days should cost the same as 356 people singing a song on one day.
<p>I approached the company that has bought the rights to most Christian music to see if I they would agree to license
music directly at a rate simular to that the CCLI charges to mega churches. In essence to charge all the users of
my app as if they were all part of a mega church consisting of all the users. The plan I had suggested here, was to use
Amazon affilaite links, to the album tracks of music sung, to generate money from referal fees, to pay the licence fee for the lyrics.
I hated doing this as it felt like a horrible compromise. This was the reply they gave:
<blockquote>[this] won’t suffice to cover the royalty payments for the lyric use.</blockquote>
<blockquote>Thank you for your email. Unfortunately, at this time, we cannot grant you a license for your app.
The royalty payments are dependent on too many outside variables and your reliance on the CCLI rate ignores
that CCLI licensees pay a subscription fee and that the rates are based on the size of the congregation.
If you find a way to <b>monetize</b> your app on more solid variables, I would be happy to review that request.</blockquote>
<p>I really do not want to <b>monitize</b> this app, I hate the idea of selling worship.
<p>There is only one time we see Jesus being physically violent when he came to earth as a human.
There must have been so much he hated about what had become of the world he had created good. But one
thing was too much for him to wait until his second coming to contain his anger.
<img src="/img/cleanse-temple.jpg" style="width: 100%; display: block; margin-top: 16px">
<blockquote>In the temple courts he found men selling cattle, sheep and doves, and others sitting at tables exchanging money.
So he made a whip out of cords, and drove all from the temple area, both sheep and cattle; he scattered the coins of the money changers and overturned their tables.
To those who sold doves he said, "Get these out of here! How dare you turn my Father's house into a market!"
His disciples remembered that it is written: "Zeal for your house will consume me." <i><nobr>(John 2:14-17)</nobr></i></blockquote>
<p>People needed animals to sacrifice to recieve God's forgiveness.
In this way people showed they knew they had broken God's law and diserved death and hell. The animal
death pointed to Jesus, who died on the cross to take the punnishment human sin so they could go free.
<p>People who lived far from the temple could not bring their own animals so they would sell them, travel to the temple and use
the money to buy animals there. However the priest soon found out they had a monoply so they
charged an extortionate price of the animals.
<p>That man corrupts the faith found in the Bible does prove that the Bible is false.
It show that the Bible's diagnosis of the condition of man is true.
That man corrupts religion only proves that he is corrupt not God.
Jesus tackelled corruption and hyprocracy head on he did not loose his faith over it.
<h2>Freedom!!!</h2>
<p>For this reason omysoul wants to opt out of this system. If Mammon paid for a few decades of Christian songs
we may just have to say he can keep them. If God gave the songs he can give us new songs for a new season.
And this time we won't sell them:
<blockquote>He put a new song in my mouth, a hymn of praise to our God.<br> <i>(Psalm 40:2)</i></blockquote>
And these songs will be about God, about mission:
<blockquote>Many will see and fear and put their trust in the LORD.<br> <i>(Psalm 40:3)</i></blockquote>
<p>There is something a bit lazy about Christians
all round the world singing songs only written by a handful of Christians. There is also something dangerous, in
that it is now secular multinations that have the marketing budgets that propel these <b>excellent products</b>
into the Christian music scene. These multinational are pushing their own set of values to which their sub-brands
will have to bend.
<p>Worship Together on the surface looks like an independant site that exists simply to teach people how to find and play new worship songs.
This is how it describes itself:
<blockquote>Worship Together is the best and most <b>comprehensive resource</b> on the web for worship leaders,
worship bands and worship teams.</blockquote>
<p>However it appears from the Capitol Christian Music Group (CCMG) website that a brand called "Worship Together" is actually owned by them.
If this is the same "Worship Together" what appears to be a <b>comprehensive resource</b> for worship leaders may actually be a marketing tool.
Capitol Christian Music Group is owned by EMI. Is the same promotion engine behind Lady Gaga, JayZ, <NAME> and Rhinna
advising our worship leaders about which songs we should sing in out churches.
<p>With omysoul encourage people to sing old songs (hymns) that are no longer under copyright.
We also encourage believers to create
new songs and release them under licences that give permisson for others to sing them and build on them. <NAME> never charged
anyone to sing his songs. Yet worship leaders today are stealing Wesley's lyrics making a few minor changes and putting
their own name at the bottom and collecting royalties.<p>
<h2>Creative Commons Licences</h2>
<p>What is exciting is that licences exist that allow people to write songs and music that others can sing and build upon freely.
<iframe style="display: block; margin: 0 auto;" width="560" height="315" src="https://www.youtube.com/embed/io3BrAQl3so" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<p>We suggest that Creative Commons licences or releasing to public domain are more suitable for worship. The track below is recorded by
a band called Recent Rainfall it was release under a Creative Commons licence. This means I am free to place it on this
website or sing it in the street. I can use it for mission and share it with non-Christians. Non-Christians reading this site
now may even chose to click on it.
Though the track is released under a Creative Commons licence they have also registered the
track with the CCLI. This means no one is obligated to pay to sing the song, but if they happen to sing it in a church that already has
a CCLI licence then Recent Rainfall will get a fair share of the CCLI fee the church paid.
They have laid down their rights. Have a listen:
<audio src="http://edinburghcreationgroup.org/Recent-Rainfall-Declare-Your-Glory.mp3" controls style="margin: 32px auto; display: block">
<p>With omysoul we want to see people collaborate. A songwriter might laydown a vocal track in their quiet time.
The hardware for creating CD quality recordings is now very in expensive. Other
artists can then independantly layer on keys, drums, backing vocals and strings. Below is the story of
how the songs of one rural Chinese girl sing into a dictaphone, fuelled revival and became the worship songs of tens of
millions of people across China.
<iframe style="display: block; margin: 16px auto 0;" width="560" height="315" src="https://www.youtube.com/embed/xa1saiWejjo" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<p>I hope we can create an online tool that makes it easy to align tracks and mixed them. Once people have created something
they are happy with it can be taken to the streets. This way when we hit the streets there is a core group of people
who know how to sing and play a new song. If we record the music which is sung on the street we can then upload it
straight to YouTube without getting take down notices.
<blockquote>Cast your bread upon the waters, for after many days you will find it again. <i>(Ecclesiastes 11:1)</i></blockquote>
<h2>Funding</h2>
<p>People will argue that song writers must be able to make a living. I would agree with this.
But how we raise funds should not compromise the ability of believers to sing praise to God in any and every situation.
Song writers are currently saying every time you worship God with my song you must pay me. This adds friction to worship it means
God does not get glory he otherwise would have got. Amazon found that
a 1 second delay in loading their website would cost them 10% of their profit. Anyone who works on the web knows
that if we make something even slightly more inconvient we will stop it from happening. We are doing exactly what we
should do if wanted to stop God's praise spreading and filling the earth.
<p>Taxing every time a song is sung adds a huge amout of bureaucracy to worship. Even if the cost in money was tiny
the cost in time would still be too high. We need to think about how we fund the creation of worship at its source,
rather than trying to claw back money every time it is used after its creation.
<p>In software everyone knows if you write something great and you charge for it, in a few days time someone else will
do the same thing and release it for free. So we all chose to make what we create free. The open source
community has now created over 100 millions of pieces of software that are free for anyone to copy the code. People can adapt it and learn from
and build their own products with it. By giving away the hanful of thing I write for free I have the benefit of being able
to use the millions of things other people write for free.
These developers are mostly not Christians but they have chosen to give up their rights.
They have worked out that in the end this benefits them. They have discovered the truth of this scripture:
<blockquote>Cast your bread upon the waters, for after many days you will find it again. <i>(Ecclesiastes 11:1)</i></blockquote>
<p>Writing open source has enabled me to collaborate with and learn from some of the best people in my industry.
Its enabled employers to find me and know what I can do. It works for individuals but it also works for big companies.
The code behind Chrome, Firefox, Edge and Safari is open for anyone to copy. Even though these companies have spent
millions developing their browsers they give away most of the code for free and anyone can create their own browser using it.
<p>It seems crazy to me that Christian musicians, behave less generously than non-Christian developers.
The lyrics of Christian songs prove the authors know it is right to give up their rights to futher the gospel.
They just stop short of actually doing it. I think Jesus would have put it like this:
<blockquotes>"You hypocrites"</blockquotes>
<ul>
<li>Large churches that employ fulltime worship leaders should pay them enough that they can live without the need
to collect royalties from lyrics each and every time their songs are sung.
Lyrics to these songs can be released freely as a service to the rest of the church. This allows the most gifted worship leaders
to be professional and work fulltime. Many of these churches teach the principle of tithing. If worship is funded out of
the tithe and offerings it will save the Church vast amount of money compared to selling it to Mammon when it is written
and buying it back every time it is sung.
<li>Crowd funding is a way a song writing worship leader can transition from being amature to fulltime professional. This is
how many YouTubers make money. They start a channel as a hobby, it grows popular. They don't want to put up adverts
so they seek voulenerily contributions from the people that watch their channel. I watch the channel of man building a marble
machine that plays music, he currently has over 6,000 who pay for the content to be produce even though released for free. He is not
Christian but listen to his heart and contrast it with what we see in the church:
<iframe width="560" height="315" style="display: block; margin: 0 auto;" width="560" height="315" src="https://www.youtube.com/embed/2xgWuw3TOJA" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<p>You see bit at the begining where he plays all the different instraments and then puts them together. I think we can do the same thing just with
different people laying down the different tracks in their bedroom. Then we go out with 100 people and perform it in the street.
<li>
</ul>
<h2></h2>
<p>You may think from reading this that I hate all modern Christian music. This is not the case
I owe a lot to it. The vision of omysoul is birthed from the songs I was singing when I got saved in 1995.
These songs prophetically talked about a time when the streets would be filled with people singing about Jesus.
This vision has never left me:
<ul>
<li>I hear they're singing in the streets that Jesus is alive
<li>Open up the doors let the music play, let the streets resound with singing
<li>Bring them from the west, sons and daughters, call them for Your praise
<li>Hallelujah, People everywhere are singing, Hallelujah
</ul>
<p>I would love to see some of these artist joining in the vision of omysoul. They have the cap
<p>I would ask you to pray for Christians artists and to challenge them. We all make compromises in our faith and
we need people who challenge us. No song writer wants to hear when they get to heaven that they have already recieved full reward on earth
for each time their song was sung.
Play (silly laws honey)
How to Evangelise the world
chinese
zero unit cost
publish
`
},
{
title: "Do you remember when it was just the three of us?",
slug: "three-of-us",
html: `
<div class="videoWrapper">
<iframe src="https://www.youtube.com/embed/oyPE7RmquPU" width="560" height="349" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
<p>On thee last Saturday of January 2020 we had the first public openair worship using omysoul with a battery powered projector.
This is a bit of a proof of concept. Two friends and I headed down to the Scottish Parliament to test the worship app.
During the week I had been working on allowing the app to display Bible verses (not just song lyrics).
I wanted to test what it was like to use the app to preach with as well as having the first time using it for worship.</p>
<p>As I am preaching I am controlling which Bible verses appear on the projector screen with my phone.
I can also see notes on those verses to help jog my memory while I am preaching. There are no wires the projector is using
a wifi hotspot on my phone to be online.
<p>None of those present are worship leaders so please excuse our singing. <i>Please pray God will give us some great worship leaders
with a heart to go out (if that is you, please contact via the <a href="/newsletter">newsletter signup</a>).</i></p>
<p>None the less as a technical test it was successful and we had a great time of fellowship and encouragement.
I left a portable sound recorder recording and was really pleased with the quality of the recording (most of the background noise is an air conditioner).
This means if we use songs with no copyright we should be able to do a podcast.</p>
<p>I am hoping that next time I go out I can get the app working so it can display images too. That way I can do a proper presentation.
`
}
].filter((x, i) => i !== 1);
posts.forEach(post => {
post.html = post.html.replace(/^\t{3}/gm, "");
});
export default posts;
|
e301bba5b6a250bc6c56a94c0f4d4a516dda612d
|
[
"JavaScript"
] | 1
|
JavaScript
|
philholden/omysoul-blog
|
66375faf9549912adefc5bc7b8d7c77843297b0f
|
cb0c8daba28ea6d74280a60b2f579e925aca4da4
|
refs/heads/master
|
<file_sep>package com.app.crony;
import android.app.ProgressDialog;
import android.content.Context;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
WebView webview;
ProgressDialog progressBar;
Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
getSupportActionBar().hide(); //hide the title bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
webview = findViewById(R.id.webview);
progressBar = new ProgressDialog(mContext);
progressBar.setMessage("Loading...");
progressBar.setCancelable(true);
progressBar.show();
webview.getSettings().setJavaScriptEnabled(true); // enable javascript
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
// webview.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
//webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setLoadWithOverviewMode(true);
webSettings.setLoadWithOverviewMode(true);
webview.loadUrl("http://bdfinancial.services.twsserver.com/front/");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
progressBar.show();
/*if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
return true;
} else if (url != null && url.startsWith("whatsapp://")) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else {*/
// view.loadUrl(url);
return false;
// }
}
@Override
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});
}
@Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
} else {
super.onBackPressed();
}
}
}
<file_sep>package com.app.crony;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.Window;
import android.view.WindowManager;
public class SplashActivity extends AppCompatActivity {
boolean is_verfied = false;
Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title
getSupportActionBar().hide(); // hide the title bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); //enable full screen
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
goToHomeActivity();
}
private void goToHomeActivity() {
Thread background = new Thread() {
@Override
public void run() {
try {
sleep(2 * 1000);
Intent i = new Intent(getBaseContext(), MainActivity.class);
startActivity(i);
finish();
} catch (Exception e) {
}
}
};
background.start();
}
}
|
c7645970e6e8ceeac03d03109acac1c1f0805ba8
|
[
"Java"
] | 2
|
Java
|
avik1990/WebviewApp
|
fdd3d9cfdc7d188116f51b90b6b94908a64810f0
|
6401939653f6deb4a71560be8b628a3885cfedf3
|
refs/heads/master
|
<repo_name>stanmei/Networking<file_sep>/dist_hc_sys_wins/inc/usercli.h
#ifndef _USERCLI_H
#define _USERCLI_H
int UserCli (int client_sock,char* user_grp,char* user_name,char* user_pswd);
void admin_opers(int client_sock,char* user_grp,char* user_name,char* user_pswd);
void healthcare_opers(int client_sock,char* user_grp,char* user_name,char* user_pswd) ;
void insurance_opers(int client_sock,char* user_grp,char* user_name,char* user_pswd) ;
#endif
<file_sep>/dist_hc_sys_wins/src/usercli.c
/* File : usercli.c
*
* Author : grp1
*
* Desc : this is client user interface functions.
*
*/
#define __WINDOWS
//#define __LINUX
#ifdef __LINUX
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#endif
#ifdef __WINDOWS
#define WIN32_LEAN_AND_MEAN
/***********Winsock**********************/
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/***********End of Winsock**************/
#endif
#include <cJSON.h>
#include <authenuser.h>
#include "user_mannual.h"
#include "usercli.h"
#include "connexch.h"
#define MAX_ARG_NUMS 4
#define MAX_ARG_LEN 64//128
#define MAX_RBUF_SIZE 128//1024
int UserCli (int client_sock,char* user_grp,char* user_name,char* user_pswd) {
// "admin" user group operation
if (!strcmp(user_grp,"admin")) {
admin_opers(client_sock,user_grp,user_name,user_pswd);
}
// "healthcare" user group operation
else if (!strcmp(user_grp,"healthcare")) {
healthcare_opers(client_sock,user_grp,user_name,user_pswd);
}
// "insurance" user group operation
else if (!strcmp(user_grp,"insurance")) {
insurance_opers(client_sock,user_grp,user_name,user_pswd);
}
else {
printf ("Unrecogized user group!\n");
exit(-1);
}
return 0;
}
/*
* admin operations
*/
void admin_opers(int client_sock,char* user_grp,char* user_name,char* user_pswd) {
int valid_op ,ret;
do
{
//char* in_cmd_main = {0};
//char in_cmd_main[MAX_ARG_NUMS]={0}; // wins : incmd_main,valid_op be modifed.maybe caused by overcover...
char in_cmd_main[MAX_ARG_LEN]={0};
//char in_argus[MAX_ARG_LEN][MAX_ARG_NUMS]= {0};
char* in_argus[]= {"NULL","NULL","NULL"};
char in_argus0[MAX_ARG_LEN]= {0};
char in_argus1[MAX_ARG_LEN]= {0};
char in_argus2[MAX_ARG_LEN]= {0};
char in_argus3[MAX_RBUF_SIZE]= {0};
admin_manual(in_cmd_main);
valid_op = 1;
if ( !strcmp(in_cmd_main,"a" ) ) {
strcpy(in_cmd_main,"create_accnt");
admin_create_accnt_manual(in_argus0,in_argus1,in_argus2);
printf("new in_cmd_main(a):%s,valid_op:%d\n",in_cmd_main,valid_op);
valid_op = 1;
} else if (!strcmp(in_cmd_main,"b")) {
strcpy(in_cmd_main,"del_accnt");
admin_del_accnt_manual(in_argus1);
valid_op = 1;
printf("new in_cmd_main(b):%s\n",in_cmd_main);
} else if (!strcmp(in_cmd_main,"c")) {
strcpy(in_cmd_main,"upd_pswd");
strcpy(in_argus0,"users");
strcpy(in_argus2,"password");
modify_manual(in_argus1,in_argus3);
valid_op = 1;
printf("new in_cmd_main(c):%s\n",in_cmd_main);
} else if (!strcmp(in_cmd_main,"d")) {
strcpy(in_cmd_main,"show_list");
qry_manual(in_argus0); //tbl=input;
strcpy(in_argus1 ,"*") ; //item=any;
valid_op = 1;
printf("new in_cmd_main(d):%s\n",in_cmd_main);
} else if (!strcmp(in_cmd_main,"e")) {
strcpy(in_cmd_main,"exit");
valid_op = 1;
//close(client_sock);
//exit(0);
printf("new in_cmd_main(e):%s\n",in_cmd_main);
} else {
printf ("No supported operations\n");
valid_op = 0;
}
printf("new in_cmd_main(-):%s,valid_op:%d \n",in_cmd_main,valid_op);
in_argus[0]= in_argus0;
in_argus[1]= in_argus1;
in_argus[2]= in_argus2;
in_argus[3]= in_argus3;
printf ("User %s input commands '%s' to server, valid op:%d, with argus:%s,%s,%s,%s.\n",user_name,in_cmd_main,valid_op,in_argus[0],in_argus[1],in_argus[2],in_argus[3]);
if (valid_op) {
printf ("User %s prepare to send commands(%s) to server with argus:%s,%s,%s,%s.\n",user_name,in_cmd_main,in_argus[0],in_argus[1],in_argus[2],in_argus[3]);
int ary_argus_len = 4;
ConnTxCjsonnt_clt (client_sock,user_grp,user_name,user_pswd,in_cmd_main,in_argus,ary_argus_len);
printf ("User %s sent commands(%s) to server with argus:%s,%s,%s,%s.\n",user_name,in_cmd_main,in_argus[0],in_argus[1],in_argus[2],in_argus[3]);
// receive ack message from server
char ret_msgs[MAX_RBUF_SIZE]= {0};
ret= ConnRxCjsonnt_clt (client_sock,ret_msgs);
if (ret< 0) {
printf("Failed to receive ack message from server:%s\n",ret_msgs);
}
}
if (!strcmp(in_cmd_main,"exit") )
{
#ifdef __LINUX
close(client_sock);
#endif
#ifdef __WINDOWS
closesocket(client_sock);
WSACleanup();
#endif
exit(0);
}
} while (1) ;
}
/*
* healthcare operations
*/
void healthcare_opers(int client_sock,char* user_grp,char* user_name,char* user_pswd) {
int valid_op ,ret;
do
{
//char* in_cmd_main = {0};
//char in_cmd_main[MAX_ARG_NUMS]={0}; // wins : incmd_main,valid_op be modifed.maybe caused by overcover...
char in_cmd_main[MAX_ARG_LEN]={0};
//char in_argus[MAX_ARG_LEN][MAX_ARG_NUMS]= {0};
char* in_argus[]= {"NULL","NULL","NULL"};
char in_argus0[MAX_ARG_LEN]= {0};
char in_argus1[MAX_ARG_LEN]= {0};
char in_argus2[MAX_ARG_LEN]= {0};
char in_argus3[MAX_RBUF_SIZE]= {0};
healthcare_manual(in_cmd_main);
valid_op = 1;
if (!strcmp(in_cmd_main,"a")) {
strcpy(in_cmd_main,"upd_pswd");
strcpy(in_argus0,"users");
strcpy(in_argus2,"password");
modify_manual(in_argus1,in_argus3);
} else if ( !strcmp(in_cmd_main,"b" ) ) {
strcpy(in_cmd_main,"create_patient");
healthcare_create_accnt_manual(in_argus1,in_argus2,in_argus3); //input: 2-patient_name,3-patient record.
} else if (!strcmp(in_cmd_main,"c")) {
strcpy(in_cmd_main,"show_list");
healthcare_qry_manual(in_argus1); //item=input;
strcpy(in_argus0 ,"patients") ; //tbl=patients;
} else if (!strcmp(in_cmd_main,"d")) {
strcpy(in_cmd_main,"upd_patient");
strcpy(in_argus0,"patients"); // 0-tbl name
strcpy(in_argus2,"record"); // 2-new item name
healthcare_modify_manual(in_argus1,in_argus3);// 1-patient 2-name; 3- new record
} else if (!strcmp(in_cmd_main,"e")) {
strcpy(in_cmd_main,"exit");
//close(client_sock);
//exit(0);
} else {
printf ("No supported operations\n");
valid_op = 0;
}
in_argus[0]= in_argus0;
in_argus[1]= in_argus1;
in_argus[2]= in_argus2;
in_argus[3]= in_argus3;
if (valid_op) {
//printf ("User %s send commands(%s) to server with argus:%s,%s,%s,%s.\n",user_name,in_cmd_main,in_argus[0],in_argus[1],in_argus[2],in_argus[3]);
int ary_argus_len = 4;
ConnTxCjsonnt_clt (client_sock,user_grp,user_name,user_pswd,in_cmd_main,in_argus,ary_argus_len);
// receive ack message from server
char ret_msgs[MAX_RBUF_SIZE]= {0};
ret= ConnRxCjsonnt_clt (client_sock,ret_msgs);
if (ret< 0) {
printf("Failed to receive ack message from server:%s\n",ret_msgs);
}
}
if (!strcmp(in_cmd_main,"exit") )
{
#ifdef __LINUX
close(client_sock);
#endif
#ifdef __WINDOWS
closesocket(client_sock);
WSACleanup();
#endif
exit(0);
}
} while (1) ;
}
/*
* insurance operations
*/
void insurance_opers(int client_sock,char* user_grp,char* user_name,char* user_pswd) {
int valid_op ,ret;
do
{
//char* in_cmd_main = {0};
//char in_cmd_main[MAX_ARG_NUMS]={0}; // wins : incmd_main,valid_op be modifed.maybe caused by overcover...
char in_cmd_main[MAX_ARG_LEN]={0};
//char in_argus[MAX_ARG_LEN][MAX_ARG_NUMS]= {0};
char* in_argus[]= {"NULL","NULL","NULL"};
char in_argus0[MAX_ARG_LEN]= {0};
char in_argus1[MAX_ARG_LEN]= {0};
char in_argus2[MAX_ARG_LEN]= {0};
char in_argus3[MAX_RBUF_SIZE]= {0};
insurance_manual(in_cmd_main);
valid_op = 1;
if (!strcmp(in_cmd_main,"a")) {
strcpy(in_cmd_main,"upd_pswd");
strcpy(in_argus0,"users");
strcpy(in_argus2,"password");
modify_manual(in_argus1,in_argus3);
} else if (!strcmp(in_cmd_main,"b")) {
strcpy(in_cmd_main,"show_list");
healthcare_qry_manual(in_argus1); //item=input;
strcpy(in_argus0 ,"patients") ; //tbl=patients;
} else if (!strcmp(in_cmd_main,"c")) {
strcpy(in_cmd_main,"upd_patient");
strcpy(in_argus0,"patients"); // 0-tbl name
strcpy(in_argus2,"insurance_coverable"); // 2-new item name
healthcare_modify_manual(in_argus1,in_argus3);// 1-patient 2-name; 3- new record
} else if (!strcmp(in_cmd_main,"e")) {
strcpy(in_cmd_main,"exit");
//close(client_sock);
//exit(0);
} else {
printf ("No supported operations\n");
valid_op = 0;
}
in_argus[0]= in_argus0;
in_argus[1]= in_argus1;
in_argus[2]= in_argus2;
in_argus[3]= in_argus3;
if (valid_op) {
//printf ("User %s send commands(%s) to server with argus:%s,%s,%s,%s.\n",user_name,in_cmd_main,in_argus[0],in_argus[1],in_argus[2],in_argus[3]);
int ary_argus_len = 4;
ConnTxCjsonnt_clt (client_sock,user_grp,user_name,user_pswd,in_cmd_main,in_argus,ary_argus_len);
// receive ack message from server
char ret_msgs[MAX_RBUF_SIZE]= {0};
ret= ConnRxCjsonnt_clt (client_sock,ret_msgs);
if (ret< 0) {
printf("Failed to receive ack message from server:%s\n",ret_msgs);
}
}
if (!strcmp(in_cmd_main,"exit") )
{
#ifdef __LINUX
close(client_sock);
#endif
#ifdef __WINDOWS
closesocket(client_sock);
WSACleanup();
#endif
exit(0);
}
} while (1) ;
}
<file_sep>/lab4/tcp/get_file.h
/*
* Please do not edit this file.
* It was generated using rpcgen.
*/
#ifndef _GET_FILE_H_RPCGEN
#define _GET_FILE_H_RPCGEN
#include <rpc/rpc.h>
#ifdef __cplusplus
extern "C" {
#endif
#define GETFILEPROG 0x2fffffff
#define GETFILE_VER 1
#if defined(__STDC__) || defined(__cplusplus)
#define GET_FILE_CONTENT 1
extern char ** get_file_content_1(char *, CLIENT *);
extern char ** get_file_content_1_svc(char *, struct svc_req *);
extern int getfileprog_1_freeresult (SVCXPRT *, xdrproc_t, caddr_t);
#else /* K&R C */
#define GET_FILE_CONTENT 1
extern char ** get_file_content_1();
extern char ** get_file_content_1_svc();
extern int getfileprog_1_freeresult ();
#endif /* K&R C */
#ifdef __cplusplus
}
#endif
#endif /* !_GET_FILE_H_RPCGEN */
<file_sep>/lab1/q4/client_tcp.c
/*******************************************************
* Author : grp1
* Desc : tcp client to send sqrt request to server.
*
* usage mode :
* 1) client_tcp server port data
*
* Client send <data> to server;
* Server response sqrt <data> to client.
* Client print both data.
*
*******************************************************/
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <unistd.h>
#include <math.h>
#define PROTOCOL_TCP 0
#define PROTOCOL_UDP 1
#define PROTOCOL_TYP 0 //daytime server protocol (tcp:0,udp:1)
//user help information
void userhelp (void) ;
unsigned int ack_from_server (char* server_ip,char* msg,int protocol,int port);
int main (int argc, char* argv[]) {
// Input arguments check
if ( argc < 2) {
printf ("Too Few arguments!\n");
userhelp();
exit(-1);
}
if ( argc > 4) {
printf ("Too Many arguments!\n");
userhelp();
exit(-1);
}
int port = atoi(argv[2]);
int msg= atoi(argv[3]);
if (msg<= 0 ) {
printf ("Input data for sqrt should >0!\n");
exit(-1);
}
// Arrary for read daytime,maxmum 2
double read_result=0;
int protocol = PROTOCOL_TYP ;
read_result = ack_from_server(argv[1],(char *)&msg,protocol,port) ;
printf ("Original Input Data : %d ; Result from server : %f ; \n",msg,read_result);
return 0 ;
}
void userhelp () {
printf ("usage: \n");
printf ("client_tcp server port data\n");
}
unsigned int ack_from_server(char* server_ip,char* msg,int protocol,int port) {
/* Read result from server
* 1) <gethostbyname> Get server ip hostnet structure.
* 2) socket
* 3) connect;
* 4) <write>send messages
* 5) <read>
* 6) <close>
*/
//gethostbyname
struct hostent* server = gethostbyname(server_ip);
if ( server== NULL ) {
printf ("gethostbyname return unexpected null!");
exit (-1);
}
//initial server addr for client socket
//sockaddr_in : short sin_family ; short port ; struct addr
struct sockaddr_in server_addr ;
memset (&server_addr,0,sizeof(server_addr)) ;
server_addr.sin_family = AF_INET ;
server_addr.sin_port = htons(port);//PROTOCOL_PORT) ;
memcpy (&server_addr.sin_addr,server->h_addr,server->h_length);
//creat client socket
int client_sock = socket(AF_INET,SOCK_STREAM,0);
if ( client_sock == -1 ) {
printf ("Fail to create client socket.\n");
exit (-1);
}
printf("Creating client socket, protocol %d, %d......\n",protocol,port);
if (protocol == PROTOCOL_TCP ) {
//connect client with server.
printf("Connecting client socket with %s,%d.....\n",server->h_name,ntohs(server_addr.sin_port));
int client_cnnt = connect (client_sock,(struct sockaddr*)&server_addr,sizeof(server_addr));
if ( client_cnnt== -1) {
printf ("Fail to connect with server %d \n",client_cnnt);
}
}
//send message to server
//char* msg="Asking for service";
ssize_t size_tmsg = sendto (client_sock,msg,strlen(msg),0,(struct sockaddr*)&server_addr,(socklen_t)sizeof(struct sockaddr));
if ( size_tmsg==-1 ) {
printf ("Fail to send message to server!\n");
}
printf("Sending client message %s to server %s......\n",msg,server->h_name);
//receive result from server
socklen_t size_rcv = sizeof(server_addr);
unsigned int daytime_rcv = sizeof(server_addr);
ssize_t size_rmsg = recvfrom (client_sock,(char*)&daytime_rcv,sizeof(daytime_rcv),0,(struct sockaddr*)&server_addr,&size_rcv);
// int size_rmsg = read(client_sock,(char*)&daytime_rcv,sizeof(daytime_rcv));
if (size_rmsg==-1) {
printf ("Fail to receive message from server!\n");
}
printf("Received message from server %s , result: %x......\n",server->h_name,daytime_rcv);
close(client_sock);
//return ntohl(daytime_rcv);
return daytime_rcv;
}
<file_sep>/dist_hc_sys_wins/src/userlogin.c
/* File: userlogin.c
*
* Author: grp 1
*
* Desc: user login with grp, username, pswd
*/
#define __WINDOWS
//#define __LINUX
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#define MAX_IN_LEN 64
void GetInputs(char* in,int length,int mask);
int UserLogin (char* grp,char* username,char* pswd) {
printf("User Group:");
GetInputs(grp,MAX_IN_LEN,0);
printf("User Name:");
GetInputs(username,MAX_IN_LEN,0);
printf("Password:");
GetInputs(pswd,MAX_IN_LEN,1);
return 0;
}
//#ifdef __LLINUX
void GetInputs(char* in,int length,int mask) {
char inchar ;
int idx=0;
do
{
inchar=getchar();
//resume blank
if (inchar==' ') {
continue;
}
// backspace
if (inchar=='\b') {
idx--;
continue;
}
// enter
if (inchar=='\n') {
break;
}
// max length limitation
if ( idx>=length-1) {
continue;
}
in[idx] = inchar;
if (mask==1) {
printf("*");
}
idx++;
} while (inchar!='\r') ;
in[idx]='\0';
//printf("\n");
return ;
}
/*
#endif
#ifdef __WINDOWS
void GetInputs(char* in,int length,int mask) {
//char buffer[81];
int i, ch;
for (i = 0; (i < length) && ((ch = getchar()) != EOF)
&& (ch != '\n'); i++)
{
in[i] = (char) ch;
}
// Terminate string with a null character
in[i] = '\0';
sprintf( "Input was: %s\n", in);
}
#endif
*/
<file_sep>/lab4/udp/get_file_proc_srv.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <error.h>
#include <errno.h>
#include <string.h>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#define MAX_BUF_SIZE 256
int filesize (char* file_name) ;
char* tx_buffer;
//char buf_tran[MAX_BUF_SIZE];
char* buf_tran;
//file content pointer
//char** get_file_content_1_svc (char* filename) {
int* get_file_trans_1_svc (char* filename) {
/* notes: use static to avoid unexisted pointer to local var in client
*/
static int max_seq;
// seek file size
int file_size = filesize(filename);
// malloc memory space for file
if(filename!=NULL) { //check wether original existed, free before new allocation.
free(tx_buffer);
tx_buffer=NULL;
}
tx_buffer = malloc((file_size+1) * sizeof(*tx_buffer));
if ( tx_buffer==NULL ) {
printf ("[server] Failed to malloc for tx buffer\n");
return 0 ;
}
// open file
int fd = open(filename,O_RDONLY);
if ( fd < 0 ) {
printf ("[Server] fail to open file: %s;\n",filename);
//free malloc
free(tx_buffer);
close(fd);
exit(-1);
}
// read file conent into buffer
int num_byts = read(fd,tx_buffer,(file_size+1));//sizeof(tx_buffer));
if ( num_byts < 0 ) {
printf ("[server] Fail to read file contents;\n");
//free malloc
free(tx_buffer);
close(fd);
exit(-1);
}
max_seq= ((int)ceil((double)file_size/MAX_BUF_SIZE));
if(num_byts>=0) {
printf("[server] Read file bytes:%d. Seqs num:%d.\n",num_byts,max_seq);
}
//return trans number
return &max_seq;
//return ((int)ceil((double)file_size/MAX_BUF_SIZE));
/*
tx_buffer[num_byts] ='\0';
return &tx_buffer;
*/
}
char** get_file_content_1_svc (char* filename,int seq) {
/*
char** get_file_content_1_svc (tran_seq* tran) {
char* filename=tran.filename;
int seq = tran.seq;
*/
if(buf_tran!=NULL) { //check wether original existed, free before new allocation.
free(buf_tran);
buf_tran=NULL;
}
buf_tran = malloc((MAX_BUF_SIZE+1) * sizeof(*buf_tran));
//printf("[server]Allocate seq buffer.\n");
//pointer
char* ptr= tx_buffer + MAX_BUF_SIZE*seq;
strncpy(buf_tran,ptr,MAX_BUF_SIZE);
//printf("[server]Return file content to client\n");
return &buf_tran;
}
int filesize (char* file_name) {
FILE* fp ;
fp = fopen(file_name,"r");
// Seek file size to transfer
fseek(fp,0,SEEK_END);
int size = ftell(fp); // get current pointer's position as file size.
fseek(fp,0,SEEK_SET);
//close file pointer
fclose(fp);
return size;
}
<file_sep>/dist_hc_sys/client/makefile
CC = gcc
INCLUDES = -I ./inc -I ../conn/inc -I ../lib/cjson/inc
CFLAGS = -g -Wall $(INCLUDES) -pthread
LDFLAGS = -lm
LDPATH = -L ../lib/cjson -L ../conn/src
LIBS = -lcjson
SRCS = ./src/client.c ./src/connserver.c ./src/userlogin.c ./src/authenuser.c
OBJS = ./src/client.o ./src/connserver.o ./src/userlogin.o ./src/authenuser.o ../conn/src/connexch.o
TARGETS = client
all:$(TARGETS)
$(TARGETS): $(OBJS)
$(CC) $(CFLAGS) -o $(TARGETS) $(OBJS) $(LDFLAGS) $(LDPATH) $(LIBS)
clean:
rm -rf ./src/*.o $(TARGETS)
<file_sep>/dist_hc_sys/server/src/sqldbop.c
/* File sqldbop.c
*
* Author : grp1
*
* Desc : sql database opeartions.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <cJSON.h>
#include <sqldbop.h>
#include <mysql/mysql.h>
#define MAX_ROW_MSG_LEN 256
MYSQL* h_conn ; // my sql connection
MYSQL_RES* h_res ; // my sql record
MYSQL_ROW h_row ; // my sql row
char* h_host = "localhost";
char* h_user = "root" ;
char* h_pswd = "<PASSWORD>" ;
char* h_db_name = "myhealthdb" ;
char sql_buf [MAX_SQL_BUF_SIZE] ;
int ExecSql(const char * sql_buf) {
if(mysql_real_query(h_conn,sql_buf,strlen(sql_buf)))
return -1;
return 0;
}
void CreateDb() {
//int ret =0 ;
// init sql connection
h_conn = mysql_init(NULL);
if (h_conn==NULL) {
printf ("Failed to init sql connection!\n");
exit(-1);
}
// connect with sql database to check whetehr already existed.
//int db_existed =0;
if ( mysql_real_connect(h_conn,h_host,h_user,h_pswd,h_db_name,0,NULL,0) != NULL) {
printf ("DB: %s already existed,skip creatation!\n",h_db_name);
mysql_close(h_conn);
return;
}
// Not existed yet. create new db.
if ( mysql_real_connect(h_conn,"127.0.0.1","root","<PASSWORD>","mysql",0,NULL,0) == NULL) {
fprintf(stderr, "Unable connect to mysql db: %s\n",mysql_error(h_conn));
mysql_close(h_conn);
exit (-1);
}
// initilized new database
if (mysql_query(h_conn, "CREATE DATABASE myhealthdb"))
{
fprintf(stderr, "%s\n", mysql_error(h_conn));
mysql_close(h_conn);
exit(-1);
}
h_res = mysql_store_result(h_conn);
// close sql connection
mysql_free_result(h_res);
printf ("created new db: %s.....\n",h_db_name);
mysql_close(h_conn);
printf ("Initialized database done!\n");
}
void CreateUserTbl() {
// init sql connection
h_conn = mysql_init(NULL);
if (h_conn==NULL) {
printf ("Failed to init sql connection[new user tbl]!\n");
exit(-1);
}
if ( mysql_real_connect(h_conn,h_host,h_user,h_pswd,h_db_name,0,NULL,0) == NULL) {
printf ("DB: %s could not be reached!\n",h_db_name);
mysql_close(h_conn);
return;
}
//query whether table exist
sprintf(sql_buf,"use myhealthdb;");
ExecSql(sql_buf);
h_res = mysql_store_result(h_conn);
// close sql connection
mysql_free_result(h_res);
/*
* Create users table
*/
sprintf(sql_buf,"DROP TABLE IF EXISTS users;");
ExecSql(sql_buf);
h_res = mysql_store_result(h_conn);
// close sql connection
mysql_free_result(h_res);
/*
h_res = mysql_store_result(h_conn);
fprintf(stderr, "mysql check user table exists: %s\n", mysql_error(h_conn));
//printf("myhealthdb for table check!\n");
int num_rows = mysql_num_rows(h_res);
printf("Check whether new user table need to be created, row num: %d .....\n",num_rows);
if (num_rows==0) {
*/
printf("Creating user table......\n");
// Create user table
//ExecSql("CREATE TABLE users(grp varchar(24) not null unique,name varchar(24) not null unique,password char(20) not null);");
ExecSql("CREATE TABLE users(grp varchar(24) not null,name varchar(24) not null,password char(20) not null);");
h_res = mysql_store_result(h_conn);
// close sql connection
mysql_free_result(h_res);
ExecSql("INSERT INTO users VALUES('admin','admin','123456');");
h_res = mysql_store_result(h_conn);
// close sql connection
mysql_free_result(h_res);
printf("New user table be created !\n");
/*
* Create patient table
*/
// Create patient record table
ExecSql("DROP TABLE IF EXISTS patients;");
// close sql connection
h_res = mysql_store_result(h_conn);
mysql_free_result(h_res);
ExecSql("CREATE TABLE patients(name varchar(24) not null unique,password char(20) not null,records char(32) not null, insurance_coverable char(20) not null);");
// close sql connection
h_res = mysql_store_result(h_conn);
mysql_free_result(h_res);
ExecSql("INSERT INTO patients VALUES('null','null','null','no');");
h_res = mysql_store_result(h_conn);
// close sql connection
mysql_free_result(h_res);
/*
}
mysql_free_result(h_res);
*/
h_res = mysql_store_result(h_conn);
// close sql connection
mysql_free_result(h_res);
mysql_close(h_conn);
}
// user authentication
int Authenticate(char* grp,char* name, char* passwd) {
// init sql connection
h_conn = mysql_init(NULL);
if (h_conn==NULL) {
printf ("Failed to init sql connection!\n");
exit(-3);
}
// connect with sql database
if (!mysql_real_connect(h_conn,h_host,h_user,h_pswd,h_db_name,0,NULL,0) ) {
printf ("Failed to connect to sql db: %s",h_db_name);
exit (-3);
}
printf ("Connected with sql db: %s\n",h_db_name);
// initilized new database
sprintf(sql_buf, "SELECT password, grp from users where name = '%s' for update;", name);
printf("Authen cmd in sql buffer: %s \n", sql_buf);
if (mysql_query(h_conn, sql_buf)) {
printf("Authen: mysql query fail! \n");
}
h_res = mysql_store_result(h_conn);
int row_num = mysql_num_rows(h_res);
printf("Authen - query returned row numbers : %d \n", row_num);
// returned row elements including: password, grp
h_row = mysql_fetch_row(h_res);
if( h_row == NULL) {
printf("Authen- fetched invalid row! \n");
return -3;
}
if (row_num > 1) {
printf ("Authen- duplicated user be found: %s. \n",name);
return -4 ;
}
if ( strcmp(h_row[0],passwd) ) {
printf ("Authen - unmatched password: %s : %s \n", h_row[0],passwd);
return -1;
}
if ( strcmp(h_row[1],grp)) {
printf ("Authen - unmatched grp : %s : %s \n", h_row[1],grp);
return -2;
}
// close sql connection
mysql_free_result(h_res);
mysql_close(h_conn);
return 0;
}
// user account create
int Create_Accnt (char* grp,char* new_name, char* new_passwd) {
int ret =0 ;
/*
* init sql connection
*/
h_conn = mysql_init(NULL);
if (h_conn==NULL) {
printf ("Failed to init sql connection!\n");
exit(-3);
}
// connect with sql database
if (!mysql_real_connect(h_conn,h_host,h_user,h_pswd,h_db_name,0,NULL,0) ) {
printf ("Failed to connect to sql db: %s",h_db_name);
exit (-3);
}
/* Query whether exist
*/
sprintf(sql_buf, "SELECT * from users where name = '%s' for update;", new_name);
if (mysql_query(h_conn, sql_buf)) {
printf("Authen: mysql query fail! \n");
}
h_res = mysql_store_result(h_conn);
int row_num = mysql_num_rows(h_res);
// close sql connection
mysql_free_result(h_res);
if (row_num==0)
{
/* Insert new account
*/
sprintf(sql_buf,"use myhealthdb;");
ret= ExecSql(sql_buf);
h_res = mysql_store_result(h_conn);
// close sql connection
mysql_free_result(h_res);
sprintf(sql_buf,"INSERT INTO users VALUES('%s','%s','%s');",grp,new_name,new_passwd);
ret= ExecSql(sql_buf);
h_res = mysql_store_result(h_conn);
// close sql connection
mysql_free_result(h_res);
//ExecSql("INSERT INTO users VALUES('admin','admin','123456');");
} else {
ret = 1 ;
printf("The account to be created already existed!\n");
}
/*
* close sql connection
*/
mysql_close(h_conn);
return ret;
}
// delete account
int Delete_Accnt(char* name) {
int ret = 0 ;
/*
* init sql connection
*/
h_conn = mysql_init(NULL);
if (h_conn==NULL) {
printf ("Failed to init sql connection!\n");
exit(-3);
}
// connect with sql database
if (!mysql_real_connect(h_conn,h_host,h_user,h_pswd,h_db_name,0,NULL,0) ) {
printf ("Failed to connect to sql db: %s",h_db_name);
exit (-3);
}
printf ("Connected with sql db: %s\n",h_db_name);
/*
* initilized new database
*/
sprintf(sql_buf,"use myhealthdb;");
ret= ExecSql(sql_buf);
h_res = mysql_store_result(h_conn);
// close sql connection
mysql_free_result(h_res);
sprintf(sql_buf, "SELECT * from users where name = '%s';", name);
if (mysql_query(h_conn, sql_buf)) {
printf("[FAIL] Delete: The user (%s) is not existed in mysql! \n",name);
ret = -1 ;
}
h_res = mysql_store_result(h_conn);
// close sql connection
mysql_free_result(h_res);
//h_res = mysql_store_result(h_conn);
//int row_num = mysql_num_rows(h_res);
sprintf(sql_buf, "DELETE from users where name = '%s';", name);
if (mysql_query(h_conn, sql_buf)) {
//printf("[FAIL] Delete: The user (%s) delete unsuccessfully! \n",name);
fprintf(stderr,"%s \n",mysql_error(h_conn));
ret = -2 ;
}
else {
printf("server: delete user (%s) from table users.\n",name);
}
h_res = mysql_store_result(h_conn);
// close sql connection
mysql_free_result(h_res);
mysql_close(h_conn);
return ret ;//row_num ; //return matched rows
}
// Update account
int Update_Item (char* tbl,char* name,char* new_item,char* new_item_val) {
int ret = 0 ;
/*
* init sql connection
*/
h_conn = mysql_init(NULL);
if (h_conn==NULL) {
printf ("Failed to init sql connection!\n");
exit(-3);
}
// connect with sql database
if (!mysql_real_connect(h_conn,h_host,h_user,h_pswd,h_db_name,0,NULL,0) ) {
printf ("Failed to connect to sql db: %s",h_db_name);
exit (-3);
}
printf ("Connected with sql db: %s\n",h_db_name);
/*
* initilized new database
*/
sprintf(sql_buf, "SELECT * from %s where name = '%s';", tbl,name);
if (mysql_query(h_conn, sql_buf)) {
printf("[FAIL] Delete: The user is not existed in mysql! \n");
ret = -1 ;
}
h_res = mysql_store_result(h_conn);
// close sql connection
mysql_free_result(h_res);
//h_res = mysql_store_result(h_conn);
//int row_num = mysql_num_rows(h_res);
sprintf(sql_buf, "UPDATE %s SET %s ='%s' where name = '%s';", tbl,new_item,new_item_val,name);
if (mysql_query(h_conn, sql_buf)) {
printf("[FAIL] Update : The update item is not success in mysql! \n");
ret = -2 ;
}
else {
printf ("Update password for user (%s). \n",name);
}
h_res = mysql_store_result(h_conn);
// close sql connection
mysql_free_result(h_res);
mysql_close(h_conn);
return ret ;//row_num ; //return matched rows
}
// Update account
int Query_Tbl (char* tbl,char* item,int* tbl_row_num,char* qry_rslt_rows[]) {
int ret = 0 ;
/*
* init sql connection
*/
h_conn = mysql_init(NULL);
if (h_conn==NULL) {
printf ("Failed to init sql connection!\n");
exit(-3);
}
// connect with sql database
if (!mysql_real_connect(h_conn,h_host,h_user,h_pswd,h_db_name,0,NULL,0) ) {
printf ("Failed to connect to sql db: %s",h_db_name);
exit (-3);
}
printf ("Connected with sql db: %s\n",h_db_name);
/*
* Query table
*/
if (!strcmp(item,"*"))
sprintf(sql_buf, "SELECT * from %s;", tbl);
else
sprintf(sql_buf, "SELECT * from %s where name = '%s';", tbl,item);
if (mysql_query(h_conn, sql_buf)) {
printf("[FAIL] Query: The table %s item %s is not existed in mysql! \n",tbl,item);
ret = -1 ;
return ret;
}
h_res = mysql_store_result(h_conn);
int row_num = mysql_num_rows(h_res);
int num_fields = mysql_num_fields(h_res);
int idx=0;
while((h_row = mysql_fetch_row(h_res))){
char qry_row_msg [MAX_ROW_MSG_LEN] ;
memset(qry_row_msg,0,MAX_ROW_MSG_LEN);
for (int i=0; i<num_fields; i++) {
strcat(qry_row_msg,h_row[i]);
strcat(qry_row_msg," ");
}
printf("%s. \n",qry_row_msg);
// strncpy(qry_rslt_rows[idx],qry_row_msg,strlen(qry_row_msg)); //!segmentation error. -> wrong, this is pointer not arrary.
//qry_rslt_rows[idx] = qry_row_msg; -> wrong, pointer be stored.
sprintf(qry_rslt_rows[idx],"%s",qry_row_msg);
idx++;
}
/*
for (int i=0; i<row_num;i++)
printf ("array elements %d : %s \n",i,qry_rslt_rows[i]);
*/
*tbl_row_num = row_num;
// close sql connection
mysql_free_result(h_res);
mysql_close(h_conn);
return ret ;//row_num ; //return matched rows
}
/*
* Healthcare operations
*/
// patients record create
int Create_Patient (char* new_patient_name,char* new_patient_insurance, char* new_patient_record) {
int ret =0 ;
/*
* init sql connection
*/
h_conn = mysql_init(NULL);
if (h_conn==NULL) {
printf ("Failed to init sql connection!\n");
exit(-3);
}
// connect with sql database
if (!mysql_real_connect(h_conn,h_host,h_user,h_pswd,h_db_name,0,NULL,0) ) {
printf ("Failed to connect to sql db: %s",h_db_name);
exit (-3);
}
sprintf(sql_buf,"use myhealthdb;");
ret= ExecSql(sql_buf);
h_res = mysql_store_result(h_conn);
// close sql connection
mysql_free_result(h_res);
/* Query whether exist
*/
sprintf(sql_buf, "SELECT * from patients where name = '%s';", new_patient_name);
if (mysql_query(h_conn, sql_buf)) {
printf("Create patient: mysql query fail! \n");
}
h_res = mysql_store_result(h_conn);
int row_num = mysql_num_rows(h_res);
// close sql connection
mysql_free_result(h_res);
if (row_num==0)
{
/* Insert new patient
*/
sprintf(sql_buf,"INSERT INTO patients VALUES('%s','%s','%s','%s');",new_patient_name,"null",new_patient_record,new_patient_insurance);
ret= ExecSql(sql_buf);
h_res = mysql_store_result(h_conn);
// close sql connection
mysql_free_result(h_res);
//ExecSql("INSERT INTO users VALUES('admin','admin','123456');");
} else {
ret = 1 ;
printf("The account to be created already existed!\n");
}
/*
* close sql connection
*/
mysql_close(h_conn);
return ret;
}
<file_sep>/dist_hc_sys/client/inc/authenuser.h
#ifndef _AUTHENUSER_H
#define _AUTHENUSER_H
int AuthenUser(int client_sock,char* user_grp,char* user_name,char* user_pswd);
//int ConnTx(int sock, cJSON* msg_cjson);
//cJSON* ConnRx(int sock);
int ConnTxCjsonnt_clt (int client_sock,char* user_grp,char* user_name,char* user_pswd,char* cmd,char* ary_arguments[],int ary_len);
int ConnRxCjsonnt_clt (int accept_sock,char* ret_msgs);
#endif
<file_sep>/lab1/q2/makefile
C = gcc
INCLUDES = -I .
CFLAGS = -g -Wall $(INCLUDES)
LDFLAGS =
LDPATH =
TARGET = daytime_client_udp
OBJ = daytime_client_udp.o
all: $(TARGET)
$(TARGET): $(OBJ)
$(CC) $(CFLAGS) -o $(TARGET) $(OBJ) $(LDPATH) $(LDFLAGS)
clean:
rm -rf *.o $(TARGET)
<file_sep>/dist_hc_sys/conn/inc/connexch.h
#ifndef _CONNEXCH_H
#define _CONNEXCH_H
int ConnTx(int socket,cJSON* txmsg);
cJSON* ConnRx(int socket);
int ConnTxCjsonnt_clt (int client_sock,char* user_grp,char* user_name,char* user_pswd,char* cmd,char* ary_arguments[],int ary_len);
int ConnRxCjsonnt_clt (int accept_sock,char* ret_msgs);
int ConnRxCjsonnt_srv (int accept_sock,char* user_grp,char* user_name,char* user_pswd,char* cmd,char* ary_arguments[]) ;
int ConnTxCjsonnt_srv (int accept_sock,int ret_val, char* ret_msg, char* ary_ret_msg[],int ary_ret_len) ;
#endif
<file_sep>/README.md
# Networking
Lab1 : client-server socket (daytime, udp ,tcp).
<file_sep>/dist_hc_sys_wins/src/client.c
/* File name: client.c
*
* Author: grp1
* Desc: This is client main function for distribute healthcare system.It provides client
* commands input and execution for:
* admin, healthcare provider,insurance,patients.
*
* Interaction without gui:
* ./client <server ip> <port>
* user group: <admin/healthcare/insurance/paitents>
* user name: <user name>
* password: <<PASSWORD>>
*
* commands: <user commands>
*
* Notes:
* This is immigration from unix to windows. Reference microsoft example:
* https://msdn.microsoft.com/en-us/library/windows/desktop/bb530741(v=vs.85).aspx
*/
#define __WINDOWS
//#define __LINUX
//Linux specfic
#ifdef __LINUX
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <netdb.h>
#include <netinet/in.h>
#endif
#ifdef __WINDOWS
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
#endif
#include <cJSON.h>
//#include <connserver.h>
#include <userlogin.h>
#include <authenuser.h>
#include <usercli.h>
#define MAX_GRP_LEN 64
#define MAX_USER_NAME_LEN 64
#define MAX_PSWD_LEN 64
#define MAX_RETRY 4
/*******************Winsock************************************/
// Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib
/*
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Mswsock.lib")
#pragma comment (lib, "AdvApi32.lib")
*/
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
int __cdecl main (int argc, char* argv[]) {
if ( argc != 3 ) {
//ClientHelp();
printf ("Abnoraml arguments!\n");
exit(-1);
}
#ifdef __WINDOWS
/*
* Initialize winsock
*/
WSADATA wsaData; //structure containing winsock impl information
SOCKET ConnectSocket = INVALID_SOCKET;
struct addrinfo *result = NULL,
*ptr = NULL,
hints;
int iResult;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
/******************winsock server address****************/
ZeroMemory( &hints, sizeof(hints) );
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port
//int server_port = atoi(argv[2]);
//iResult = getaddrinfo(argv[1], DEFAULT_PORT, &hints, &result);
iResult = getaddrinfo(argv[1], argv[2], &hints, &result);
if ( iResult != 0 ) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();
return 1;
}
/******************End of winsock server address****************/
/******************Connect with server via winsock**************************/
// Attempt to connect to an address until one succeeds
for(ptr=result; ptr != NULL ;ptr=ptr->ai_next) {
// Create a SOCKET for connecting to server
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed with error: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to server.
iResult = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
/******************End of Connect with server via winsock**************************/
#endif
#ifdef __LINUX
struct hostent* server_ip = gethostbyname(argv [1]);
int server_port = atoi(argv[2]);
// Connect with server
int client_sock ;
int ret = 0;
client_sock = ConnServer(server_ip,server_port) ;
if ( client_sock< 0 ) {
printf ("Fail to connect with server!\n");
exit(-1);
} else {
printf ("Connected with server : %s,port:%d through client socket %d........ \n",server_ip->h_name,server_port,client_sock);
}
#endif
// user inter-action
char user_grp [MAX_GRP_LEN] = {0};
char user_name [MAX_USER_NAME_LEN] = {0};
char user_pswd [MAX_PSWD_LEN] = {0};
// return value decleration
int retry_cnt=0,ret=0;
// User authentication
//while (retry_cnt<MAX_RETRY) {
do
{
ret = UserLogin(user_grp,user_name,user_pswd);
if (ret < 0) {
printf ("Abnormal User Inputs, Exit!\n");
exit(-1);
}
printf ("\n");
printf ("Authening with server........\n");
// authentication with server
/*
ret = AuthenUser(client_sock,user_grp,user_name,user_pswd);
*/
ret = AuthenUser(ConnectSocket,user_grp,user_name,user_pswd);
if ( ret<0) {
//printf ("Fail to authentication, please double check user information!\n");
printf ("please double check and retry!\n");
if ( retry_cnt== (MAX_RETRY-1)) {
#ifdef __LINUX
close(ConnectSocket);
#endif
#ifdef __WINDOWS
/***********Winsock cleanup****************/
closesocket(ConnectSocket);
WSACleanup();
#endif
exit(-1);
}
} else {
printf ("Authen success(grp:%s,user name: %s)\n",user_grp,user_name);
printf("----------------------------\n");
printf("\n");
break;
}
printf("----------------------------\n");
retry_cnt++;
} while (retry_cnt<MAX_RETRY) ;
// user commands
ret = UserCli (ConnectSocket,user_grp,user_name,user_pswd);
printf ("Thank you. Bye!\n");
return 0;
}
<file_sep>/lab4/tcp/get_file_proc_srv.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <error.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
int filesize (char* file_name) ;
char* tx_buffer;
//file content pointer
char** get_file_content_1_svc (char* filename) {
// seek file size
int file_size = filesize(filename);
// malloc memory space for file
tx_buffer = malloc((file_size+1) * sizeof(*tx_buffer));
if ( tx_buffer==NULL ) {
printf ("[server] Failed to malloc for tx buffer\n");
return NULL ;
}
// open file
int fd = open(filename,O_RDONLY);
if ( fd < 0 ) {
printf ("[Server] fail to open file: %s;\n",filename);
//free malloc
free(tx_buffer);
close(fd);
exit(-1);
}
// read file conent into buffer
int num_byts = read(fd,tx_buffer,(file_size+1));//sizeof(tx_buffer));
if ( num_byts < 0 ) {
printf ("[server] Fail to read file contents;\n");
//free malloc
free(tx_buffer);
close(fd);
exit(-1);
}
else {
printf("[server] Read file bytes:%d.\n",num_byts);
}
tx_buffer[num_byts] ='\0';
return &tx_buffer;
}
int filesize (char* file_name) {
FILE* fp ;
fp = fopen(file_name,"r");
// Seek file size to transfer
fseek(fp,0,SEEK_END);
int size = ftell(fp); // get current pointer's position as file size.
fseek(fp,0,SEEK_SET);
//close file pointer
fclose(fp);
return size;
}
<file_sep>/lab4/tcp/get_file_client.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <rpc/rpc.h>
#include "get_file.h"
//#define PROTOC tcp
int main(int argc,char* argv[]) {
//client handl
CLIENT *cl = NULL;
// arguments
char* server = NULL;
char* filename = NULL;
char** rx_file_content = NULL;
// Input arguments number check.
if ( argc!=3) {
printf("usage: ./get_file_client <server> <filename>\n");
exit(-1);
}
server = argv[1];
filename = argv[2];
//remove local existed result file for a new trans
int ret = remove(filename);
if ( ret != -1) printf ("Removed existed local %s.\n",filename);
// Create client handle
if ((cl=clnt_create(server,GETFILEPROG,GETFILE_VER,"tcp"))==NULL) {
// Fail to establish connection with server
printf("Fail to establish connection with server %s\n",server);
exit(-1);
}
else {
printf("Establish connection with server %s. \n",server);
}
// Call the remote procedure
rx_file_content = get_file_content_1(filename,cl);
if(rx_file_content==NULL){
printf("Fail to call the remote procedure.\n");
exit(-1);
}
else {
printf("Received file context from server.\n");
}
// Write buffer into file
if (filename!=NULL) {
int fd = open(filename,O_CREAT|O_WRONLY,S_IRWXU);
if (fd<0) {
printf("Fail to open file:%s\n",filename);
exit(-1);
}
write(fd,*rx_file_content,(int) strlen(*rx_file_content));
}
// Destroy handle
clnt_destroy(cl);
return 0;
}
<file_sep>/lab3/server/server_tcp.c
/*************************************************************************
* author : grp 1
*
* desc : tcp iterative server
*
* usage : ./server_tcp <port>
*
* A basic flow for iterative tcp server was as:
* create sock -> bind -> listen ->
* accept -> recv -> send -> close -> (accept)
*
*************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <time.h>
#include <netdb.h>
#include <netinet/in.h>
#define QUESIZE 32 //listen queue size limits
#define MAX_FILE_NAME_LEN 128 //max file name character length
#define MAX_TX_SIZE 512 //max transmit size
#define NUM_HTTP_RESP_CODE 4
/*
* Http default response header declration -- reuse from internet.
*/
// HTTP response status code
#define HTTP_SUCCESS_200 200
#define HTTP_CLIENT_ERR_BAD_REQUEST 400
#define HTTP_CLIENT_ERR_FORBIDDEN 403
#define HTTP_CLIENT_ERR_FILE_NOT_FOUND 404
#define HTTP_HEADER_LEN 64
#define HTTP_REQ_BUF_SIZE 512
#define HTTP_DEF_HTML "index.html"
char g_bad_req_msg[] = "<!DOCTYPE HTML PUBLIC '-//IETF//DTD HTML 2.0//EN'> \r\n \
<html><head> \r\n \
<title>400 Bad Request</title> \r\n \
</head><body> \r\n \
<h1>400 Bad Request</h1> \r\n \
<p>Your browser sent a request that this server could not understand.<br /> \r\n \
</p> \r\n \
<hr> \r\n \
<address>CMPE207 Lab3 Server at 127.0.1.1 Port 80</address> \r\n \
</body></html> \r\n";
char g_forbidden_msg[] = "<!DOCTYPE HTML PUBLIC '-//IETF//DTD HTML 2.0//EN'> \r\n \
<html><head> \r\n \
<title>403 Forbidden</title> \r\n \
</head><body> \r\n \
<h1>403 Forbidden</h1> \r\n \
<p>You don't have permission to access /index.html on this server.<br /> \r\n \
</p> \r\n \
<hr> \r\n \
<address>CMPE-207 Server at localhost Port 80</address> \r\n \
</body></html> \r\n";
char g_not_found_msg[] = "<!DOCTYPE HTML PUBLIC '-//IETF//DTD HTML 2.0//EN'> \r\n \
<html><head> \r\n \
<title>404 NOT FOUND</title> \r\n \
</head><body> \r\n \
<h1>404 NOT FOUND</h1> \r\n \
<p> \r\n \
Your browser sent a request that this server could not find on this server.<br /> \r\n \
</p> \r\n \
<hr> \r\n \
<address>CMPE207 Lab3 Server at localhost Port 80</address> \r\n \
</body></html> \r\n";
/*
* HTTP response header structure
*/
typedef struct http_resp_cntx {
int resp_sts_code ;
const char* head_sts_str ;
char* resp_err_body_str ;
} http_resp_cntx_t ;
http_resp_cntx_t g_ary_http_resp_cntx [] = {
{ HTTP_SUCCESS_200, "HTTP/1.0 200 OK\r\n\r\n", ""},
{ HTTP_CLIENT_ERR_BAD_REQUEST, "HTTP/1.0 400 Bad Request\r\n\r\n", g_bad_req_msg},
{ HTTP_CLIENT_ERR_FORBIDDEN, "HTTP/1.0 403 Forbidden\r\n\r\n",g_forbidden_msg},
{ HTTP_CLIENT_ERR_FILE_NOT_FOUND, "HTTP/1.0 404 Not Found\r\n\r\n",g_not_found_msg}
};
/*
* Function declartion
*/
// user help
void usehelp (void);
// client commands function: isqrt
//double client_cmd_function (int rcv);
int filesize (char* file_name) ;
int sendfile (int tx_sock,char* tx_file_name,int tran_byt_size,int http_sts_code) ;
int parse_tx_file_name (char* tx_file_name,char* rcv_http_req_msg);
void childshandle(int signal);
int main (int argc, char* argv[]) {
// arguments check
if ( argc !=2 ) {
usehelp();
exit(-1) ;
}
printf("-----------Multiprocessor connection-oriented(tcp) server------------------\n");
char tx_file_name [MAX_FILE_NAME_LEN]= {0} ;
char rcv_http_req_msg [HTTP_HEADER_LEN]= {0} ;
//server listening port
int server_port = atoi (argv[1]);
// Create server socket
struct sockaddr_in server ;
memset (&server,0,sizeof(server));
server.sin_family = AF_INET ;
server.sin_port = htons(server_port);
server.sin_addr.s_addr = INADDR_ANY ; //all interfaces
int server_sock = socket(PF_INET,SOCK_STREAM,0) ;
if (server_sock == -1 ) {
printf ("Fail to create server socket!\n");
exit(-1);
}
printf("Create server socket.\n");
// Bind server socket
int bindsock = bind (server_sock,(struct sockaddr *) &server,sizeof(server));
if ( bindsock!=0 ) {
printf ("Fail to bind server socket!\n");
close (server_sock);
exit(-1);
}
printf("Bind server socket.\n");
// listening at server port
printf ("Listening at server port %d ......\n",server_port);
int listensock = listen (server_sock,QUESIZE);
if ( listensock !=0 ) {
printf ("Fail to listening at port %d",server_port);
close (server_sock);
exit(-1);
}
while (1) {
// accept connection
struct sockaddr_in client ;
memset (&client,0,sizeof(client));
socklen_t client_addrlen = sizeof(client) ;
int accept_sock = accept(server_sock,(struct sockaddr*)&client,&client_addrlen);//sizeof(client));
if (accept_sock<0){
printf("Fail to accept client socket!\n");
close (server_sock);
exit(-1);
}
printf ("Accepted at server port %d ......\n",server_port);
/*
* Child process for file transfer with clients
*/
signal(SIGCHLD,childshandle);
int child = fork();
if ( child==0 ) { // child process
printf ("chld process:%d.\n",(int)getpid());
// Receive message from clienBindt ;
//int rcd = 0;
int rx = read (accept_sock,&rcv_http_req_msg,MAX_FILE_NAME_LEN);//sizeof(rcd));
if (rx<0){
printf ("Failt to read from client!\n");
}
int http_sts_code = parse_tx_file_name (tx_file_name,rcv_http_req_msg) ;
// Send result back to client
//int tx = write (accept_sock,&txd,sizeof(txd));
printf ("Received at server port %d , required file name: %s, sts code: %d .....,\n",server_port,tx_file_name,http_sts_code);
int tx = sendfile (accept_sock,tx_file_name,MAX_TX_SIZE,http_sts_code);
if (tx<0){
printf ("Failt to send to client!\n");
close(server_sock);
close(accept_sock);
exit(-1);
}
//printf ("Sent %d at server port %d ......\n",txd,server_port);
close(accept_sock); //child process finish
exit(0);
}
//parent waiting for childs
pid_t pid;
int state;
while ((pid = waitpid(-1, &state, WNOHANG)) > 0){
printf("child_pid: %d finished!\n", pid);
}
close(accept_sock); //parent process finish
}
return 0;
}
void usehelp (void) {
printf ("usage:\n");
printf (" server_tcp <port> \n" );
}
int sendfile (int tx_sock,char* tx_file_name,int tran_byt_size,int http_sts_code) {
int file_size =0 ;
int send_nums ;
/*
* Abnormal http response
*/
printf ("Received file name: %s , http resp code: %d.\n",tx_file_name,http_sts_code);
int sts_idx = -1;
for (;sts_idx<NUM_HTTP_RESP_CODE;sts_idx++)
if (g_ary_http_resp_cntx[sts_idx].resp_sts_code==http_sts_code) break;
send_nums = write(tx_sock,g_ary_http_resp_cntx[sts_idx].head_sts_str,strlen(g_ary_http_resp_cntx[sts_idx].head_sts_str));
if ( g_ary_http_resp_cntx[sts_idx].resp_sts_code!=HTTP_SUCCESS_200){
send_nums = write(tx_sock,g_ary_http_resp_cntx[sts_idx].resp_err_body_str,strlen(g_ary_http_resp_cntx[sts_idx].resp_err_body_str));
printf ("Unsuccessful http request, retrun.\n");
return 0;
}
/*
* Send local file.
*/
// seek file size
file_size = filesize(tx_file_name);
// malloc memory space for file
char* tx_buffer = malloc((file_size+1) * sizeof(*tx_buffer));
if ( tx_buffer==NULL ) {
printf ("Failed to malloc for tx buffer\n");
return -1 ;
}
// open file
int fd = open(tx_file_name,O_RDONLY);
if ( fd < 0 ) {
printf ("Fail to open file: %s;\n",tx_file_name);
//free malloc
free(tx_buffer);
close(fd);
exit(-1);
}
// read file conent into buffer
int num_byts = read(fd,tx_buffer,(file_size+1));//sizeof(tx_buffer));
if ( num_byts < 0 ) {
printf ("Fail to read file contents;\n");
//free malloc
free(tx_buffer);
close(fd);
exit(-1);
}
// Loop to tx buffer content
char* fp_cur = tx_buffer ; //current file pointer
char* fp_end = fp_cur + num_byts -1 ; //end of file pointer
int tx_tran_len = 0 ;
printf("file content (filesize:%d; content size:%d bytes):\n",file_size,num_byts);
//printf("%s",tx_buffer);
while ( fp_cur < fp_end) {
// Check transition size
if ( fp_end - fp_cur < tran_byt_size) {
tx_tran_len = fp_end - fp_cur + 1;
} else {
tx_tran_len = tran_byt_size ;
}
// write tran len into sock
send_nums = write(tx_sock,fp_cur,tx_tran_len);
if ( send_nums != tx_tran_len) {
printf ("Abnormal write length. \n");
//free malloc
free(tx_buffer);
close(fd);
exit(-1);
}
fp_cur +=tx_tran_len;
}
//free malloc
free(tx_buffer);
close(fd);
return 0;
}
int filesize (char* file_name) {
FILE* fp ;
fp = fopen(file_name,"r");
// Seek file size to transfer
fseek(fp,0,SEEK_END);
int size = ftell(fp); // get current pointer's position as file size.
fseek(fp,0,SEEK_SET);
//close file pointer
fclose(fp);
return size;
}
void childshandle(int signal){
pid_t pid;
int state;
while ( (pid=waitpid(-1,&state,WNOHANG))>0)
printf ("pid %d finished\n",pid);
}
int parse_tx_file_name (char* tx_file_name,char* rcv_http_req_msg){
char* elem = NULL;
// First element : GET
elem = strtok(rcv_http_req_msg," ");
printf ("First extracted element from http_req:%s , from : %s;\n",elem,rcv_http_req_msg);
if ( elem == NULL ) {
return HTTP_CLIENT_ERR_BAD_REQUEST;
}
if ( strncasecmp(elem,"GET",strlen("GET"))!=0 ) {
return HTTP_CLIENT_ERR_BAD_REQUEST;
}
//extract tx file name
elem = strtok(NULL," "); //point to next active
printf ("Second extracted element for http_req:%s\n",elem);
//if ( (elem=='\0') || (strncasecmp(elem[0],"HTTP",strlen("HTTP"))!=0) {
if ( elem=='\0') {
return HTTP_CLIENT_ERR_BAD_REQUEST;
}
// check file name
char def_http_html[] = "index.html" ;
if ( (strncasecmp(elem,".",strlen("."))==0) ||
(strncasecmp(elem,"/",strlen("/"))==0) ||
(strncasecmp(elem," ",strlen(" "))==0)
) {
sprintf(tx_file_name,def_http_html,strlen(def_http_html));
} else {
sprintf(tx_file_name,elem,strlen(elem));
}
if (access(tx_file_name,F_OK)!=0) { // File is not existed
return HTTP_CLIENT_ERR_FILE_NOT_FOUND;
} else if (access(tx_file_name,R_OK)!=0) {
return HTTP_CLIENT_ERR_FORBIDDEN;
}
//tx_file_name = elem ;
printf ("Extracted filename for http_req:%s\n",tx_file_name);
return HTTP_SUCCESS_200;
}
/*
void childshandle(int signal);
double client_cmd_function (int rcd){
return sqrt (rcd);
}
*/
<file_sep>/dist_hc_sys/server/src/server.c
/* File: server.c
*
* Author : grp1
*
* Description : Server of distribute healthcare system
* ./server <port>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <netdb.h>
#include <netinet/in.h>
#include <pthread.h>
#include <cJSON.h>
#include <sqldbop.h>
#include <clientopeartion.h>
#define MAX_PTHREADS_NUM 128
#define LISTEN_QUE_LEN 32
void* ClientOperation(void *argument);
int main (int argc, char* argv[]) {
if ( argc !=2 ) {
//userhelp();
printf ("Abnormal arguments!\n");
exit(-1);
}
int server_port = atoi(argv[1]) ;
printf ("Listening on port:%d \n",server_port);
// server socket
int server_sock , accept_sock ;
int ret ;
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = server_port;
server.sin_addr.s_addr = INADDR_ANY;
server_sock = socket(PF_INET,SOCK_STREAM,0);
if ( server_sock < 0 ) {
printf ("Failed to create server socket!");
exit(-1);
}
ret = bind(server_sock,(struct sockaddr*) &server,sizeof(server)) ;
if (ret<0) {
printf ("Failed to bind server socket");
close(server_sock);
exit(-1);
}
printf ("Bind to server_sock: %d\n",server_sock);
// Initialize SQL server
CreateDb() ;
CreateUserTbl() ;
//listening and accept client commands with individule thread
pthread_t srv_pthreads [MAX_PTHREADS_NUM] ={0};
int pth_idx = 0;
while (1) {
// listening client connection
printf("Listening on server_sock : %d \n",server_sock);
ret = listen(server_sock,LISTEN_QUE_LEN);
if (ret<0) {
printf ("Failed to listen on port!\n");
close(server_sock);
exit(-1);
}
//accept clients commands
struct sockaddr_in client;
memset(&client,0,sizeof(client));
socklen_t client_addrlen = sizeof(client);
//printf ("Waiting to create new client socket from server sock %d.\n",server_sock);
accept_sock = accept (server_sock,(struct sockaddr*) &client,&client_addrlen);
if (accept_sock <0) {
printf ("Failed to accept from server!\n");
close(server_sock);
exit(-1);
}
printf ("New accept socket %d from server sock %d.\n",accept_sock,server_sock);
//pthread to deal with client requests
if ( pthread_create(&srv_pthreads[pth_idx++],NULL,&ClientOperation,(void*)&accept_sock) <0) {
printf ("Failed to create pthread!\n");
close (accept_sock);
close (server_sock);
exit(-1);
}
//printf ("Recived message from accept socket %d and create thread %d to process.\n",accept_sock,pth_idx);
if ( pth_idx >=MAX_PTHREADS_NUM-10 )
{
pth_idx=0;
while(pth_idx<MAX_PTHREADS_NUM-10)
{
pthread_join(srv_pthreads[pth_idx++],NULL);
}
pth_idx=0;
}
//wireshar: this will triger fin ack to client.
//close (accept_sock);
}
return 0;
}
<file_sep>/lab2/udp/makefile
C = gcc
INCLUDES = -I .
CFLAGS = -g -Wall $(INCLUDES) -pthread
LDFLAGS = -lm
LDPATH =
TARGET1 = client_udp
TARGET2 = server_udp_iter
TARGET3 = server_udp_mpr
TARGET4 = server_udp_mth
TARGET5 = server_udp_ppr
TARGET6 = server_udp_pth
OBJ1 = client_udp.o
OBJ2 = server_udp_iter.o
OBJ3 = server_udp_mpr.o
OBJ4 = server_udp_mth.o
OBJ5 = server_udp_ppr.o
OBJ6 = server_udp_pth.o
all: $(TARGET1) $(TARGET2) $(TARGET3) $(TARGET4) $(TARGET5) $(TARGET6)
iter: $(TARGET1) $(TARGET2)
mpr: $(TARGET1) $(TARGET3)
mth: $(TARGET1) $(TARGET4)
ppr: $(TARGET1) $(TARGET5)
pth: $(TARGET1) $(TARGET6)
$(TARGET1): $(OBJ1)
$(CC) $(CFLAGS) -o $(TARGET1) $(OBJ1) $(LDPATH) $(LDFLAGS)
$(TARGET2): $(OBJ2)
$(CC) $(CFLAGS) -o $(TARGET2) $(OBJ2) $(LDPATH) $(LDFLAGS)
$(TARGET3): $(OBJ3)
$(CC) $(CFLAGS) -o $(TARGET3) $(OBJ3) $(LDPATH) $(LDFLAGS)
$(TARGET4): $(OBJ4)
$(CC) $(CFLAGS) -o $(TARGET4) $(OBJ4) $(LDPATH) $(LDFLAGS)
$(TARGET5): $(OBJ5)
$(CC) $(CFLAGS) -o $(TARGET5) $(OBJ5) $(LDPATH) $(LDFLAGS)
$(TARGET6): $(OBJ6)
$(CC) $(CFLAGS) -o $(TARGET6) $(OBJ6) $(LDPATH) $(LDFLAGS)
clean:
rm -rf *.o $(TARGET1) $(TARGET2)
<file_sep>/dist_hc_sys/server/inc/clientopeartion.h
#ifndef _CLIENTOPERATION_H
#define CLIENTOPERATION_H
void* ClientOperation(void* argument) ;
//cJSON* ConnRx (int socket);
int ConnRxCjsonnt_srv (int accept_sock,char* user_grp,char* user_name,char* user_pswd,char* cmd,char* ary_arguments[]) ;
int ConnTxCjsonnt_srv (int accept_sock,int ret_val, char* ret_msg, char* ary_ret_msg[],int ary_ret_len) ;
#endif
<file_sep>/dist_hc_sys/server/makefile
CC = gcc
INCLUDES = -I ./inc -I ../conn/inc -I ../lib/cjson/inc -I/usr/include/
CFLAGS = -g -Wall $(INCLUDES) -pthread
LDFLAGS = -lm
LDPATH = -L ../lib/cjson -L ../conn/src -L/usr/lib/x86_64-linux-gnu/
LIBS = -lcjson -lmysqlclient
SRCS = ./src/server.c ./src/clientoperation.c ./src/sqldbop.c
OBJS = ./src/server.o ./src/clientoperation.o ./src/sqldbop.o ../conn/src/connexch.o
TARGETS = server
all:$(TARGETS)
$(TARGETS): $(OBJS)
$(CC) $(CFLAGS) -o $(TARGETS) $(OBJS) $(LDFLAGS) $(LDPATH) $(LIBS)
clean:
rm -rf ./src/*.o $(TARGETS)
<file_sep>/dist_hc_sys/client/src/authenuser.c
/* File : authenuser.c
*
* Author : grp1
*
* Desc : this is client user authtication request to server with cjson format.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <cJSON.h>
#include <authenuser.h>
#define MAX_ARG_LEN 64
#define MAX_RBUF_SIZE 1024
int AuthenUser(int client_sock,char* user_grp,char* user_name,char* user_pswd) {
int ret ;
// send authentication message to client
char* cmd="auth";
char* in_args[]={"NULL","NULL","NULL","NULL"};
printf("Send authentication message to server,grp(%s),user (%s),pswd(%s),cmd(%s),in args: %s,%s.\n",user_grp,user_name,user_pswd,cmd,in_args[0],in_args[1]);
ret = ConnTxCjsonnt_clt (client_sock,user_grp,user_name,user_pswd,cmd,in_args,4);
printf("Waiting for authentication ack message from server.........\n");
if (ret<0) {
printf("Abnormal send to client!\n");
return -1;
}
// receive authetication message from client
//int ret_val=0;
char ret_msgs[MAX_RBUF_SIZE]= {0};
ret= ConnRxCjsonnt_clt (client_sock,ret_msgs);
if (ret< 0) {
printf("Failed authentication with message code:%s",ret_msgs);
return -1;
}
return 0;
}
<file_sep>/lab1/q4/server_tcp.c
/*************************************************************************
* author : grp 1
*
* desc : tcp server ,which response sqrt of client incoming data.
* usage : ./server_tcp <port>
*
*************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <math.h>
#define QUESIZE 32 //listen queue size limits
// user help
void usehelp (void);
// client commands function: isqrt
//double client_cmd_function (int rcv);
int main (int argc, char* argv[]) {
// arguments check
if ( argc !=2 ) {
usehelp();
exit(-1) ;
}
//server listening port
int server_port = atoi (argv[1]);
// Create server socket
struct sockaddr_in server ;
memset (&server,0,sizeof(server));
server.sin_family = AF_INET ;
server.sin_port = htons(server_port);
server.sin_addr.s_addr = INADDR_ANY ; //all interfaces
int server_sock = socket(PF_INET,SOCK_STREAM,0) ;
if (server_sock == -1 ) {
printf ("Fail to create server socket!\n");
exit(-1);
}
printf("Create server socket.\n");
// Bind server socket
int bindsock = bind (server_sock,(struct sockaddr *) &server,sizeof(server));
if ( bindsock!=0 ) {
printf ("Fail to bind server socket!\n");
close (server_sock);
exit(-1);
}
printf("Bind server socket.\n");
while (1) {
// listening at server port
printf ("Listening at server port %d ......\n",server_port);
int listensock = listen (server_sock,QUESIZE);
if ( listensock !=0 ) {
printf ("Fail to listening at port %d",server_port);
close (server_sock);
exit(-1);
}
// accept connection
struct sockaddr_in client ;
memset (&client,0,sizeof(client));
socklen_t client_addrlen = sizeof(client) ;
int accept_sock = accept(server_sock,(struct sockaddr*)&client,&client_addrlen);//sizeof(client));
if (accept_sock<0){
printf("Fail to accept client socket!\n");
close (server_sock);
exit(-1);
}
printf ("Accepted at server port %d ......\n",server_port);
// Receive message from client ;
int rcd = 0;
int rx = read (accept_sock,&rcd,sizeof(rcd));
if (rx<0){
printf ("Failt to read from client!\n");
}
printf ("Received %d at server port %d ......\n",rcd,server_port);
// operation : sqrt
int txd = sqrt( (double) rcd );//client_cmd_function ((double) rcd);
// Send result back to client
int tx = write (accept_sock,&txd,sizeof(txd));
if (tx<0){
printf ("Failt to read from client!\n");
close(server_sock);
close(accept_sock);
exit(-1);
}
//printf ("Sent %d at server port %d ......\n",txd,server_port);
close(accept_sock);
}
return 0;
}
void usehelp (void) {
printf ("usage:\n");
printf (" server_tcp <port> \n" );
}
/*
double client_cmd_function (int rcd){
return sqrt (rcd);
}
*/
<file_sep>/dist_hc_sys/lib/cjson/makefile
CC = gcc
AR = ar
INCLUDES = -I ./inc
CFLAGS = -g -Wall -fPIC $(INCLUDES)
LDFLAGS = -lm
LDPATH =
SRCS = ./src/cJSON.c
OBJS = cJSON.o
TARGETS = libcjson.a
all:$(TARGETS)
$(TARGETS): $(OBJS)
$(AR) rcs $(TARGETS) $(OBJS)
$(OBJS): $(SRCS)
$(CC) $(CFLAGS) -c $(SRCS)
clean:
rm -rf ./src/*.o $(TARGETS)
<file_sep>/lab4/tcp/Readme.txt
Env:
1) install rpcbind
2) run : rpcinfo
check whether portmapper running. If not, add service persmission to binary files with:
sudo setcap 'cap_net_bind_service=+ep' ~/Networking/lab4/bin_tcp_client/client
sudo setcap 'cap_net_bind_service=+ep' ~/Networking/lab4/bin_tcp_client/server
Generate Stubs
./tcp : rpcgen get_file.x
Build:
./tcp : make
two binary files be stored in: ./bin_tcp_server/server ./bin_tcp_client/client
prepare test file:
./bin_tcp_server/test.txt
Run:
./bin_tcp_server : ./server
./bin_tcp_client : ./client localhost test.txt
CHECK:
./bin_tcp_client , a "test.txt" file will be tranfered from server and stored locally.
<file_sep>/lab3/server/makefile
C = gcc
INCLUDES = -I .
CFLAGS = -g -Wall $(INCLUDES) -pthread
LDFLAGS = -lm
LDPATH =
TARGET1 = server_tcp
OBJ1 = server_tcp.o
all: $(TARGET1)
$(TARGET1): $(OBJ1)
$(CC) $(CFLAGS) -o $(TARGET1) $(OBJ1) $(LDPATH) $(LDFLAGS)
clean:
rm -rf *.o rx_*.txt $(TARGET1)
<file_sep>/dist_hc_sys/client/src/client.c
/* File name: client.c
*
* Author: grp1
* Desc: This is client main function for distribute healthcare system.It provides client
* commands input and execution for:
* admin, healthcare provider,insurance,patients.
*
* Interaction without gui:
* ./client <server ip> <port>
* user group: <admin/healthcare/insurance/paitents>
* user name: <user name>
* password: <<PASSWORD>>
*
* commands: <user commands>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <netdb.h>
#include <netinet/in.h>
#include <cJSON.h>
#include <connserver.h>
#include <userlogin.h>
#include <authenuser.h>
#include <usercli.h>
#define MAX_GRP_LEN 64
#define MAX_USER_NAME_LEN 64
#define MAX_PSWD_LEN 64
#define MAX_RETRY 4
int main (int argc, char* argv[]) {
if ( argc != 3 ) {
//ClientHelp();
printf ("Abnoraml arguments!\n");
exit(-1);
}
struct hostent* server_ip = gethostbyname(argv [1]);
int server_port = atoi(argv[2]);
// Connect with server
int client_sock ;
int ret = 0;
client_sock = ConnServer(server_ip,server_port) ;
if ( client_sock< 0 ) {
printf ("Fail to connect with server!\n");
exit(-1);
} else {
printf ("Connected with server : %s,port:%d through client socket %d........ \n",server_ip->h_name,server_port,client_sock);
}
// user inter-action
char user_grp [MAX_GRP_LEN] = {0};
char user_name [MAX_USER_NAME_LEN] = {0};
char user_pswd [MAX_PSWD_LEN] = {0};
// return value decleration
int retry_cnt=0;
// User authentication
//while (retry_cnt<MAX_RETRY) {
do
{
ret = UserLogin(user_grp,user_name,user_pswd);
if (ret < 0) {
printf ("Abnormal User Inputs, Exit!\n");
exit(-1);
}
printf ("\n");
printf ("Authening with server........\n");
// authentication with server
ret = AuthenUser(client_sock,user_grp,user_name,user_pswd);
if ( ret<0) {
//printf ("Fail to authentication, please double check user information!\n");
printf ("please double check and retry!\n");
if ( retry_cnt== (MAX_RETRY-1)) {
close(client_sock);
exit(-1);
}
} else {
printf ("Authen success(grp:%s,user name: %s)\n",user_grp,user_name);
printf("----------------------------\n");
printf("\n");
break;
}
printf("----------------------------\n");
retry_cnt++;
} while (retry_cnt<MAX_RETRY) ;
// user commands
ret = UserCli (client_sock,user_grp,user_name,user_pswd);
printf ("Thank you. Bye!\n");
return 0;
}
<file_sep>/dist_hc_sys_wins/src/connserver.c
/* File : connserver.c
*
* Author : grp1
*
* Desc : Connect with server via tcp.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <netdb.h>
#include <netinet/in.h>
#include <errno.h>
int ConnServer (struct hostent* server_ip,int server_port) {
// build server socket
struct sockaddr_in server;
memset(&server,0,sizeof(server));
server.sin_family= AF_INET;
server.sin_port= server_port;//htons(server_port);
memcpy(&server.sin_addr,server_ip->h_addr,server_ip->h_length); //copy server ip into server structure.
// client socket
int client_sock = socket(AF_INET,SOCK_STREAM,0);
if (client_sock<0) {
printf ("Failed to create client socket------- error code:%s!\n",strerror(errno));
return client_sock;
}
printf ("Created client socket: %d... \n",client_sock);
printf ("Trying to connect with server: %s , port: %d ........... \n",server_ip->h_name, server_port);
// Connect with server
int ret ;
ret = connect(client_sock,(struct sockaddr*) &server,sizeof(server));
if (ret <0) {
printf("Connection error code: %s!\n",strerror(errno));
close(client_sock);
return ret;
}
return client_sock;
}
<file_sep>/lab4/udp/Readme.txt
Env:
1) install rpcbind
2) run : rpcinfo
check whether portmapper running. If not, add service persmission to binary files with:
sudo setcap 'cap_net_bind_service=+ep' ~/Networking/lab4/bin_udp_client/client
sudo setcap 'cap_net_bind_service=+ep' ~/Networking/lab4/bin_udp_client/server
Generate Stubs
./udp : rpcgen -N get_file.x (-N:to support multi args)
Build:
./udp : make
two binary files be stored in: ./bin_udp_server/server ./bin_udp_client/client
prepare test file:
./bin_udp_server/test.txt
Run:
./bin_udp_server : ./server
./bin_udp_client : ./client localhost test.txt
CHECK:
./bin_udp_client , a "test.txt" file will be tranfered from server and stored locally.
<file_sep>/lab1/q4/makefile
C = gcc
INCLUDES = -I .
CFLAGS = -g -Wall $(INCLUDES)
LDFLAGS = -lm
LDPATH =
TARGET1 = client_tcp
TARGET2 = server_tcp
OBJ1 = client_tcp.o
OBJ2 = server_tcp.o
all: $(TARGET1) $(TARGET2)
$(TARGET1): $(OBJ1)
$(CC) $(CFLAGS) -o $(TARGET1) $(OBJ1) $(LDPATH) $(LDFLAGS)
$(TARGET2): $(OBJ2)
$(CC) $(CFLAGS) -o $(TARGET2) $(OBJ2) $(LDPATH) $(LDFLAGS)
clean:
rm -rf *.o $(TARGET1) $(TARGET2)
<file_sep>/lab2/tcp/client_tcp.c
/*******************************************************
* Author : grp1
* Desc : tcp client
*
* usage mode :
* 1) client_tcp server port filename
*
* Client send <file name> to server;
* Server response <data of file> to client.
* Client print both data.
*
*******************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PROTOCOL_TCP 0
#define PROTOCOL_UDP 1
#define PROTOCOL_TYP 0 //daytime server protocol (tcp:0,udp:1)
#define MAX_TRAN_SIZE 512 //max transition size
#define MAX_FILE_NAME_LEN 128 //max file name length
//user help information
void userhelp (void) ;
unsigned int ack_from_server (char* server_ip,char* msg,int protocol,int port);
int main (int argc, char* argv[]) {
// Input arguments check
if ( argc < 2) {
printf ("Too Few arguments!\n");
userhelp();
exit(-1);
}
if ( argc > 4) {
printf ("Too Many arguments!\n");
userhelp();
exit(-1);
}
int port = atoi(argv[2]);
//int msg= atoi(argv[3]);
char* file_name= argv[3];
if (file_name == NULL ) {
printf ("Input filename is invalid!\n");
exit(-1);
}
// Arrary for read daytime,maxmum 2
double read_result=0;
int protocol = PROTOCOL_TYP ;
read_result = ack_from_server(argv[1],file_name,protocol,port) ;
printf ("Original Input filename : %s ; Result from server : %f ; \n",file_name,read_result);
return 0 ;
}
void userhelp () {
printf ("usage: \n");
printf ("client_tcp server port filename\n");
}
unsigned int ack_from_server(char* server_ip,char* msg,int protocol,int port) {
/* Read result from server
* 1) <gethostbyname> Get server ip hostnet structure.
* 2) socket
* 3) connect;
* 4) <write>send messages
* 5) <read>
* 6) <close>
*/
//gethostbyname
struct hostent* server = gethostbyname(server_ip);
if ( server== NULL ) {
printf ("gethostbyname return unexpected null!");
exit (-1);
}
//initial server addr for client socket
//sockaddr_in : short sin_family ; short port ; struct addr
struct sockaddr_in server_addr ;
memset (&server_addr,0,sizeof(server_addr)) ;
server_addr.sin_family = AF_INET ;
server_addr.sin_port = htons(port);//PROTOCOL_PORT) ;
memcpy (&server_addr.sin_addr,server->h_addr,server->h_length);
//creat client socket
int client_sock = socket(AF_INET,SOCK_STREAM,0);
if ( client_sock == -1 ) {
printf ("Fail to create client socket.\n");
exit (-1);
}
printf("Creating client socket, protocol %d, %d......\n",protocol,port);
if (protocol == PROTOCOL_TCP ) {
//connect client with server.
printf("Connecting client socket with %s,%d.....\n",server->h_name,ntohs(server_addr.sin_port));
int client_cnnt = connect (client_sock,(struct sockaddr*)&server_addr,sizeof(server_addr));
if ( client_cnnt== -1) {
printf ("Fail to connect with server %d \n",client_cnnt);
}
}
//send message to server
//char* msg="Asking for service";
ssize_t size_tmsg = sendto (client_sock,msg,strlen(msg),0,(struct sockaddr*)&server_addr,(socklen_t)sizeof(struct sockaddr));
if ( size_tmsg==-1 ) {
printf ("Fail to send message to server!\n");
}
printf("Sending client message: %s, to server %s......\n",msg,server->h_name);
/*
* receive result from server,then write into local file
*/
char file_name[MAX_FILE_NAME_LEN] ="rx_";
strcat(file_name,msg);
int ret = remove(file_name);
if ( ret != -1) printf ("Removed existed rx_file.txt\n");
char rx_buf[MAX_TRAN_SIZE] = {0} ;
int fd = open(file_name,O_CREAT|O_WRONLY,S_IRWXU);
//socklen_t size_rcv = sizeof(server_addr);
//unsigned int daytime_rcv = sizeof(server_addr);
//ssize_t size_rmsg = recvfrom (client_sock,(char*)&daytime_rcv,sizeof(daytime_rcv),0,(struct sockaddr*)&server_addr,&size_rcv);
//int size_rmsg = read(client_sock,(char*)&daytime_rcv,sizeof(daytime_rcv));
printf("Received file : %s contents from server %s ..\n",file_name,server->h_name);
int total_rx =0;
while (1) {
int size_rmsg = read(client_sock,rx_buf,MAX_TRAN_SIZE);
if (size_rmsg==-1) {
printf ("Fail to receive message from server!\n");
close(client_sock);
close(fd);
exit(-1);
}
if (size_rmsg == 0 ) break;
int wsize_rx = write(fd,rx_buf,size_rmsg);
if (wsize_rx != size_rmsg ) {
printf ("Abnormal msg size when write receive message into file!\n");
close(client_sock);
close(fd);
exit(-1);
}
total_rx +=size_rmsg;
//printf("contents: %s \n",rx_buf);
}
printf("Saved into local file : %s , received contents size: %d \n",file_name,total_rx);
close(client_sock);
close(fd);
//return ntohl(daytime_rcv);
return 0;
}
<file_sep>/dist_hc_sys/server/inc/sqldbop.h
#ifndef _SQLDBOP_H
#define _SQLDBOP_H
#define MAX_SQL_BUF_SIZE 1024
// exec sql commands
int ExecSql(const char * sql_buf) ;
// Select database, create it if doesn't existed.
void CreateDb() ;
void CreateUserTbl() ;
// user authentication
int Authenticate(char* grp,char* name, char* passwd) ;
/*
* Account commands
*/
// change password
//int ChangePswd(char* grp, char* name, char* old_pswd, char* new_pswd);
// Create account
int Create_Accnt(char* grp, char* new_name, char* new_passwd);
// Delete account
int Delete_Accnt(char* name) ;
int Update_Item (char* tbl,char* name,char* new_item,char* new_item_val) ;
int Query_Tbl (char* tbl,char* item,int* tbl_row_num,char* qry_rslt_rows[]);
/* Healthcare operations
*/
int Create_Patient (char* new_patient_name,char* new_patient_insurance, char* new_patient_record) ;
/*
* User operations
*/
//int QryRcord(MYSQL* conn, char* patient_name);
/*
* Debugging
*/
void PrintUserTbl ();
#endif
<file_sep>/lab1/q2/daytime_client_udp.c
/*******************************************************
* Author : grp1
* Desc : tcp daytime client
*
* usage mode :
* 1) daytim_client server1
* read day time and print from server1
* 2) daytim_client server1 server2
* read day time and print from server1/server2
* report time difference between two servers
*
* ****************************************************/
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#include <netdb.h>
#include <unistd.h>
#include <time.h>
#define PROTOCOL_PORT 37//13 //daytime server port (tcp:37)
#define PROTOCOL_TCP 0
#define PROTOCOL_UDP 1
#define PROTOCOL_TYP 1 //daytime server protocol (tcp:0,udp:1)
#define NTP_UNIX_TS_OFST 2208988800 //NTP timestamp offset to unix
//user help information
void userhelp (void) ;
unsigned int ack_from_server (char* server_ip,char* msg,int protocol);
int main (int argc, char* argv[]) {
// Input arguments check
if ( argc < 2) {
printf ("Too Few arguments!\n");
userhelp();
exit(-1);
}
if ( argc > 3) {
printf ("Too Many arguments!\n");
userhelp();
exit(-1);
}
char* msg="Asking for daytime service";
// Arrary for read daytime,maxmum 2
long unsigned int read_daytime[2] ={0};
int protocol = PROTOCOL_TYP ;
for (int idx=1;idx<argc;idx++) {
// call daytime service
read_daytime [idx-1] = ack_from_server(argv[idx],msg ,protocol) - NTP_UNIX_TS_OFST ;
printf ("Time from server %d :%lx , %s \n",idx-1,read_daytime[idx-1],ctime((time_t*)&read_daytime[idx-1]));
sleep(2);
}
if ( argc > 2 ) {
printf ("\n");
printf ("Time difference between servers : %lx s \n",read_daytime[1]-read_daytime[0]);
}
return 0 ;
}
void userhelp () {
printf ("usage: \n");
printf ("daytime_client_tcp server1 (server2) \n");
}
unsigned int ack_from_server(char* server_ip,char* msg,int protocol) {
/* Read daytime from server
* 1) <gethostbyname> Get server ip hostnet structure.
* 2) socket
* 3) connect;
* 4) <write>send messages
* 5) <read>
* 6) <close>
*/
//gethostbyname
struct hostent* server = gethostbyname(server_ip);
if ( server== NULL ) {
printf ("gethostbyname return unexpected null!");
exit (-1);
}
//initial server addr for client socket
//sockaddr_in : short sin_family ; short port ; struct addr
struct sockaddr_in server_addr ;
memset (&server_addr,0,sizeof(server_addr)) ;
server_addr.sin_family = AF_INET ;
server_addr.sin_port = htons(PROTOCOL_PORT) ;
memcpy (&server_addr.sin_addr,server->h_addr,server->h_length);
//creat client socket
int dgram_typ = SOCK_DGRAM ;
if (protocol == PROTOCOL_TCP ) {
dgram_typ = SOCK_STREAM;
}
int client_sock = socket(AF_INET,dgram_typ,0);
if ( client_sock == -1 ) {
printf ("Fail to create client socket.\n");
exit (-1);
}
printf("Creating client socket, protocol %d......\n",protocol);
if (protocol == PROTOCOL_TCP ) {
//connect client with server.
printf("Connecting client socket with %s,%d.....\n",server->h_name,ntohs(server_addr.sin_port));
int client_cnnt = connect (client_sock,(struct sockaddr*)&server_addr,sizeof(server_addr));
if ( client_cnnt== -1) {
printf ("Fail to connect with server %d \n",client_cnnt);
}
}
//send message to server
//char* msg="Asking for daytime service";
printf("Sending client message to server %s......\n",server->h_name);
ssize_t size_tmsg = sendto (client_sock,msg,strlen(msg),0,(struct sockaddr*)&server_addr,(socklen_t)sizeof(struct sockaddr));
if ( size_tmsg==-1 ) {
printf ("Fail to send message to server!\n");
}
//receive daytime from server
socklen_t size_rcv = sizeof(server_addr);
unsigned int daytime_rcv = sizeof(server_addr);
ssize_t size_rmsg = recvfrom (client_sock,(char*)&daytime_rcv,sizeof(daytime_rcv),0,(struct sockaddr*)&server_addr,&size_rcv);
// int size_rmsg = read(client_sock,(char*)&daytime_rcv,sizeof(daytime_rcv));
if (size_rmsg==-1) {
printf ("Fail to receive message from server!\n");
}
printf("Received message from server %s , time: %x......\n",server->h_name,daytime_rcv);
close(client_sock);
return ntohl(daytime_rcv);
}
<file_sep>/dist_hc_sys_wins/inc/connserver.h
int ConnServer (struct hostent* serever_ip,int server_port) ;
<file_sep>/lab3/makefile
LIB_DIR =
all:
$(MAKE) -C client
$(MAKE) -C server
clean:
$(MAKE) -C client clean
$(MAKE) -C server clean
<file_sep>/lab4/udp/makefile
C = gcc
INCLUDES = -I .
CFLAGS = -g -Wall $(INCLUDES) -pthread
LDFLAGS = -lm
LDPATH =
TARGET1 = client server
#OBJ1 = client_udp.o
#define rpcgen files
RPC_FILES=get_file.h get_file_xdr.c get_file_svc.c get_file_clnt.c
all: ${RPC_FILES} ${TARGET1}
${RPC_FILES}:
rpcgen -N get_file.x
# client
client: get_file_client.o get_file_clnt.o get_file_xdr.o
$(CC) $(CFLAGS) -o ../bin_udp_client/client get_file_client.o get_file_clnt.o get_file_xdr.o
get_file_client.o:
$(CC) $(CFLAGS) -c get_file_client.c
get_file_clnt.o:
$(CC) $(CFLAGS) -c get_file_clnt.c
get_file_xdr.o:
$(CC) $(CFLAGS) -c get_file_xdr.c
# server
server: get_file_svc.o get_file_proc_srv.o get_file_xdr.o
$(CC) $(CFLAGS) -o ../bin_udp_server/server get_file_proc_srv.o get_file_svc.o get_file_xdr.o $(LDFLAGS)
get_file_svc.o:
$(CC) $(CFLAGS) -c get_file_svc.c
get_file_proc_srv.o:
$(CC) $(CFLAGS) -c get_file_proc_srv.c $(LDFLAGS)
clean:
rm -rf *.o rx_*.txt ../bin_udp_client/client ../bin_udp_server/server
<file_sep>/dist_hc_sys_wins/Readme.txt
Env:
1) windows 8.1
2) ubuntu 16.04 running server.
3) Mysql on ubuntu.
Build:
Eclipse
one binary files be stored in: client
Run:
(ubuntu:./server : ./server <port>)
windows cmd terminal:
./client : ./client <server address> <port>
Check:
This could though two ways:
1) ubuntu running server - rlogin mysql:
use myhealthdb;
Then use mysql commands to show tables status.
2) windows running client - "query" command option in "client".
<file_sep>/dist_hc_sys/Readme.txt
Env:
1) ubuntu 16.04
2) Mysql on ubuntu 16.04.
Build:
./lib/cjson: make
./server : make
./client : make
two binary files be stored in: ./server/server ./client/client
Run:
./server : ./server <port>
./client : ./client <server address> <port>
Check:
This could though two ways:
1) rlogin mysql:
use myhealthdb;
Then use mysql commands to show tables status.
2) "query" command option in "client".
<file_sep>/lab4/udp/get_file_client.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <rpc/rpc.h>
#include "get_file.h"
//#define PROTOC udp
int main(int argc,char* argv[]) {
//client handl
CLIENT *cl = NULL;
// arguments
char* server = NULL;
char* filename = NULL;
char** rx_file_content = NULL;
// Input arguments number check.
if ( argc!=3) {
printf("usage: ./get_file_client <server> <filename>\n");
exit(-1);
}
server = argv[1];
filename = argv[2];
//remove local existed result file for a new trans
int ret = remove(filename);
if ( ret != -1) printf ("Removed existed local %s.\n",filename);
// Create client handle
if ((cl=clnt_create(server,GETFILEPROG,GETFILE_VER,"udp"))==NULL) {
// Fail to establish connection with server
printf("Fail to establish connection with server %s\n",server);
exit(-1);
} else {
printf("Create establish connection with server %s\n",server);
}
// Call the remote procedure
// Write buffer into file
int fd;
if (filename!=NULL) {
fd = open(filename,O_CREAT|O_WRONLY,S_IRWXU);
if (fd<0) {
printf("Fail to open file:%s\n",filename);
exit(-1);
}
}
int max_seq=0;
//printf("[client] Start to call file trans procedure,max_seq:%d.\n",max_seq);
/*notice: this procedure introduced lots debugging efforts due:
*1) x file generted int* instead of expected int return.
*2) int* return required "static" to avoid un-existed pointer to local variable in server side.
*
*/
max_seq = *get_file_trans_1(filename,cl);
int seq_rcv =0;
//printf("[client] Start to call file content procedure,max_seq:%d,seq_rcv:%d.\n",max_seq,seq_rcv);
//tran_seq tran={filename,seq_rcv};
// UDP , write individual seq into file.
while (seq_rcv < max_seq) {
if (rx_file_content!=NULL) {
free(*rx_file_content);
}
//tran.seq=seq_rcv;
rx_file_content = get_file_content_1(filename,seq_rcv,cl);
if(rx_file_content==NULL){
printf("Fail to call the remote procedure.\n");
exit(-1);
}
/*
else {
printf("[client] received seq from remote procedeure\n");
}
*/
write(fd,*rx_file_content,(int) strlen(*rx_file_content));
seq_rcv++;
}
close(fd);
printf("Transfer done,close file.\n");
// Destroy handle
clnt_destroy(cl);
return 0;
}
<file_sep>/dist_hc_sys/client/inc/user_mannual.h
#ifndef _USER_MANNUAL_H
#define _USER_MANNUAL_H
//admin
void admin_manual(char* in);
void healthcare_manual(char* in);
void admin_create_accnt_manual(char* new_usr_grp,char* new_usr_name,char* new_pswd);
void admin_del_accnt_manual(char* del_usr_name);
//healthcare
void healthcare_manual(char* in);
void healthcare_create_accnt_manual(char* new_patient_name,char* new_patient_insurance,char* new_record);
void healthcare_modify_manual(char* item_name,char* new_item);
void healthcare_qry_manual(char* qry_name);
//common
void modify_manual(char* item_name,char* new_item);
void qry_manual(char* qry_usr_name);
void chg_pswd_manual(char* chg_usr_pswd);
void insurance_manual(char* in);
#endif
<file_sep>/lab2/tcp/makefile
C = gcc
INCLUDES = -I .
CFLAGS = -g -Wall $(INCLUDES) -pthread
LDFLAGS = -lm
LDPATH =
TARGET1 = client_tcp
TARGET2 = server_tcp_iter
TARGET3 = server_tcp_mpr
TARGET4 = server_tcp_mth
TARGET5 = server_tcp_ppr
TARGET6 = server_tcp_pth
OBJ1 = client_tcp.o
OBJ2 = server_tcp_iter.o
OBJ3 = server_tcp_mpr.o
OBJ4 = server_tcp_mth.o
OBJ5 = server_tcp_ppr.o
OBJ6 = server_tcp_pth.o
all: $(TARGET1) $(TARGET2) $(TARGET3) $(TARGET4) $(TARGET5) $(TARGET6)
iter: $(TARGET1) $(TARGET2)
mpr: $(TARGET1) $(TARGET3)
mth: $(TARGET1) $(TARGET4)
ppr: $(TARGET1) $(TARGET5)
pth: $(TARGET1) $(TARGET6)
$(TARGET1): $(OBJ1)
$(CC) $(CFLAGS) -o $(TARGET1) $(OBJ1) $(LDPATH) $(LDFLAGS)
$(TARGET2): $(OBJ2)
$(CC) $(CFLAGS) -o $(TARGET2) $(OBJ2) $(LDPATH) $(LDFLAGS)
$(TARGET3): $(OBJ3)
$(CC) $(CFLAGS) -o $(TARGET3) $(OBJ3) $(LDPATH) $(LDFLAGS)
$(TARGET4): $(OBJ4)
$(CC) $(CFLAGS) -o $(TARGET4) $(OBJ4) $(LDPATH) $(LDFLAGS)
$(TARGET5): $(OBJ5)
$(CC) $(CFLAGS) -o $(TARGET5) $(OBJ5) $(LDPATH) $(LDFLAGS)
$(TARGET6): $(OBJ6)
$(CC) $(CFLAGS) -o $(TARGET6) $(OBJ6) $(LDPATH) $(LDFLAGS)
clean:
rm -rf *.o $(TARGET1) $(TARGET2)
<file_sep>/dist_hc_sys/client/src/userlogin.c
/* File: userlogin.c
*
* Author: grp 1
*
* Desc: user login with grp, username, pswd
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#define MAX_IN_LEN 64
void GetInputs(char* in,int length,int mask);
int UserLogin (char* grp,char* username,char* pswd) {
printf("User Group:");
GetInputs(grp,MAX_IN_LEN,0);
printf("User Name:");
GetInputs(username,MAX_IN_LEN,0);
printf("Password:");
GetInputs(pswd,MAX_IN_LEN,1);
return 0;
}
void GetInputs(char* in,int length,int mask) {
char inchar ;
int idx=0;
do
{
inchar=getchar();
//resume blank
if (inchar==' ') {
continue;
}
// backspace
if (inchar=='\b') {
idx--;
continue;
}
// enter
//if (inchar=='\r') {
if (inchar=='\n') {
break;
}
// max length limitation
if ( idx>=length-1) {
continue;
}
in[idx] = inchar;
if (mask==1) {
printf("*");
}
idx++;
} while (inchar!='\r') ;
in[idx]='\0';
//printf("\n");
return ;
}
<file_sep>/lab2/udp/server_udp_ppr.c
/*************************************************************************
* author : grp 1
*
* desc : udp pre-forked concurrent server
*
* usage : ./server_udp <port>
*
* A basic flow for iterative udp server was as:
* create sock -> bind -> recv -> send -> close -> (recv)
*
*************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <errno.h>
#include <netdb.h>
#include <netinet/in.h>
#define QUESIZE 32 //listen queue size limits
#define MAX_FILE_NAME_LEN 128 //max file name character length
#define MAX_TX_SIZE 512 //max transmit size
#define MAX_CHILDS_NUM 16
// user help
void usehelp (void);
// client commands function: isqrt
//double client_cmd_function (int rcv);
int filesize (char* file_name) ;
int sendfile (int tx_sock,char* tx_file_name,int tran_byt_size,struct sockaddr_in* client,socklen_t client_addlen) ;
int main (int argc, char* argv[]) {
// arguments check
if ( argc !=2 ) {
usehelp();
exit(-1) ;
}
printf("-----------Pre fork connectionless(udp) server------------------\n");
//server listening port
int server_port = atoi (argv[1]);
// Create server socket
struct sockaddr_in server ;
memset (&server,0,sizeof(server));
server.sin_family = AF_INET ;
server.sin_port = htons(server_port);
server.sin_addr.s_addr = INADDR_ANY ; //all interfaces
int server_sock = socket(PF_INET,SOCK_DGRAM,0) ;
if (server_sock == -1 ) {
printf ("Fail to create server socket!\n");
exit(-1);
}
printf("Create server socket.\n");
// Bind server socket
int bindsock = bind (server_sock,(struct sockaddr *) &server,sizeof(server));
if ( bindsock!=0 ) {
printf ("Fail to bind server socket!\n");
close (server_sock);
exit(-1);
}
printf("Bind server socket.\n");
//client socket
struct sockaddr_in client ;
memset (&client,0,sizeof(client));
socklen_t client_addrlen = sizeof(client) ;
/*
* Child process for file transfer with clients
*/
int child=0;
for (int idx=0;idx<MAX_CHILDS_NUM;idx++) {
child = fork();
if ( child== 0) {
//connectclient(&server_sock);
printf("child pid: %d\n", (int)getpid());
while (1) {
char tx_file_name [MAX_FILE_NAME_LEN]= {0} ;
int rx = recvfrom (server_sock,tx_file_name,MAX_FILE_NAME_LEN ,0, (struct sockaddr*)&client, &client_addrlen);
if (rx<0){
printf ("Failt to read from client: %s! \n",strerror(errno));
}
// Send result back to client
int tx = sendfile (server_sock,tx_file_name,MAX_TX_SIZE,&client,client_addrlen);
if (tx<0){
printf ("Failt to send to client!\n");
close(server_sock);
exit(-1);
}
}
}
}
//parent waiting for childs
pid_t pid;
int state;
while ((pid = waitpid(-1, &state, WNOHANG)) > 0){
printf("child_pid: %d finished!\n", pid);
}
return 0;
}
void usehelp (void) {
printf ("usage:\n");
printf (" server_udp <port> \n" );
}
int sendfile (int tx_sock,char* tx_file_name,int tran_byt_size,struct sockaddr_in* client,socklen_t client_addlen) {
// seek file size
int file_size = filesize(tx_file_name);
// malloc memory space for file
char* tx_buffer = malloc((file_size+1) * sizeof(*tx_buffer));
if ( tx_buffer==NULL ) {
printf ("Failed to malloc for tx buffer\n");
return -1 ;
}
// open file
int fd = open(tx_file_name,O_RDONLY);
if ( fd < 0 ) {
printf ("Fail to open file: %s;\n",tx_file_name);
//free malloc
free(tx_buffer);
close(fd);
exit(-1);
}
// read file conent into buffer
int num_byts = read(fd,tx_buffer,(file_size+1));//sizeof(tx_buffer));
if ( num_byts < 0 ) {
printf ("Fail to read file contents;\n");
//free malloc
free(tx_buffer);
close(fd);
exit(-1);
}
// Loop to tx buffer content
char* fp_cur = tx_buffer ; //current file pointer
char* fp_end = fp_cur + num_byts -1 ; //end of file pointer
int tx_tran_len = 0 ;
printf("file content (filesize:%d; content size:%d bytes):\n",file_size,num_byts);
//printf("%s",tx_buffer);
int send_nums;
while ( fp_cur < fp_end) {
// Check transition size
if ( fp_end - fp_cur < tran_byt_size) {
tx_tran_len = fp_end - fp_cur + 1;
} else {
tx_tran_len = tran_byt_size ;
}
// write tran len into sock
//int send_nums = write(tx_sock,fp_cur,tx_tran_len);
send_nums = sendto(tx_sock,fp_cur,tx_tran_len,0,(struct sockaddr*) client,client_addlen);
if ( send_nums != tx_tran_len) {
printf ("Abnormal write length. \n");
//free malloc
free(tx_buffer);
close(fd);
exit(-1);
}
fp_cur +=tx_tran_len;
}
send_nums = sendto(tx_sock,fp_cur,0,0,(struct sockaddr*) client,client_addlen); //udp
//free malloc
free(tx_buffer);
close(fd);
return 0;
}
int filesize (char* file_name) {
FILE* fp ;
fp = fopen(file_name,"r");
// Seek file size to transfer
fseek(fp,0,SEEK_END);
int size = ftell(fp); // get current pointer's position as file size.
fseek(fp,0,SEEK_SET);
//close file pointer
fclose(fp);
return size;
}
<file_sep>/dist_hc_sys/client/inc/userlogin.h
int UserLogin(char* user_grp,char* user_name,char* user_pswd);
void GetInputs(char* in,int length);
<file_sep>/dist_hc_sys/server/src/clientoperation.c
/* File : clientoperation.c
*
* Author : grp1
*
* Desc : client operation
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <errno.h>
#include <cJSON.h>
#include <connexch.h>
#include <sqldbop.h>
#include <clientopeartion.h>
#define MAX_USER_LEN 256
#define MAX_ARGS_NUM 2
#define MAX_MSG_ROWS 16
void* ClientOperation(void* argument) {
int accept_sock = *((int*) argument) ;
/*
char name[MAX_USER_LEN] = {0};
char password[MAX_USER_LEN] = {0};
char grp[MAX_USER_LEN] = {0};
char cmd[MAX_USER_LEN] = {0};
char* ary_arguments[] ={"NULL","NULL","NULL"};
char* qry_rslt_rows[MAX_MSG_ROWS] ;
int qry_row_num=0;
*/
/*
* SQL
*/
int ret;
while (1)
{
char name[MAX_USER_LEN] = {0};
char password[MAX_USER_LEN] = {0};
char grp[MAX_USER_LEN] = {0};
char cmd[MAX_USER_LEN] = {0};
char* ary_arguments[] ={"NULL","NULL","NULL"};
char* qry_rslt_rows[MAX_MSG_ROWS] ={NULL};
//char qry_rslt_rows[MAX_USER_LEN][MAX_MSG_ROWS]={NULL};
//qry_rslt_rows [MAX_MSG_ROWS] = (char*) malloc(MAX_MSG_ROWS*MAX_USER_LEN*sizeof(char));
for (int i =0; i<MAX_MSG_ROWS;i++)
qry_rslt_rows[i] = malloc(MAX_USER_LEN*sizeof(char));
int qry_row_num=0;
//char* user_grp={0}, *user_name={0},*user_pswd={0},*cmd={0};
ret= ConnRxCjsonnt_srv (accept_sock,grp,name,password,cmd,ary_arguments);
if ( ret <0 ) {
printf("Abnormal message received from client,exit.\n");
close(accept_sock);
return NULL;
}
//client operations
char ret_msg[MAX_USER_LEN];
//char* ret_msg[];
if ( !strcmp(cmd,"auth") ) {
ret= Authenticate(grp,name,password);
//strcpy(ret_msg,"Authen ack!");
sprintf(ret_msg,"Authen ack!");
printf("authenticat return to client:%d; ret_msg:%s\n",ret,ret_msg);
/* Admins tasks
*/
} else if (!strcmp(cmd,"create_accnt")) {
char* new_grp = ary_arguments[0];
char* new_name= ary_arguments[1];
char* new_passwd= ary_arguments[2];
/*
ret= Authenticate(grp,name,password);
if (ret<0 )
sprintf(ret_msg,"create_accnt %s fail: request from non existed user (grp:%s,name:%s),code:%d !",new_name,grp,name,ret);
else
{
*/
ret= Create_Accnt(new_grp,new_name,new_passwd);
if ( ret < 0 )
sprintf(ret_msg,"create_accnt %s fail to create with code %d!",new_name,ret);
else
sprintf(ret_msg,"create_accnt %s successfully ack!",new_name);
//}
} else if (!strcmp(cmd,"del_accnt")) {
char* del_name= ary_arguments[1];
/*
ret= Authenticate(grp,name,password);
if ( ret>=0 )
*/
ret= Delete_Accnt(del_name);
if ( ret == -1 )
sprintf(ret_msg,"delete_accnt %s fail due non-exist object!",del_name);
else if (ret<0)
sprintf(ret_msg,"delete_accnt %s fail!",del_name);
else
sprintf(ret_msg,"delete_accnt %s successfully ack!",cmd);
} else if ( (!strcmp(cmd,"upd_pswd")) || (!strcmp(cmd,"upd_patient")) ) {
char* upd_tbl = ary_arguments[0];
char* upd_name= ary_arguments[1];
char* upd_item= ary_arguments[2];
char* upd_item_val= ary_arguments[3];
/*
ret= Authenticate(grp,name,password);
if ( ret>=0 )
*/
ret= Update_Item(upd_tbl,upd_name,upd_item,upd_item_val);
if ( ret == -1 )
sprintf(ret_msg,"update_pswd <%s> fail due non-exist object!",upd_name);
else if (ret<0)
sprintf(ret_msg,"update_pswd <%s> fail!",upd_name);
else
sprintf(ret_msg,"update_pswd <%s> successfully ack!",cmd);
} else if (!strcmp(cmd,"show_list")) {
char* qry_tbl= ary_arguments[0];
char* qry_item= ary_arguments[1];
ret=Query_Tbl (qry_tbl,qry_item,&qry_row_num,qry_rslt_rows);
sprintf(ret_msg,"show list ack!");
/*
//printf ("total qry ret rows:%d :\n",qry_row_num);
//for (int i=0; i<qry_row_num;i++)
printf ("%s \n",qry_rslt_rows[0]);
printf ("%s \n",qry_rslt_rows[1]);
*/
printf("\n");
/*
* Healthcare operations
*/
} else if (!strcmp(cmd,"create_patient")) {
char* new_patient_name= ary_arguments[1];
char* new_insurance = ary_arguments[2];
char* new_patient_record= ary_arguments[3];
ret= Create_Patient(new_patient_name,new_patient_record,new_insurance);
if ( ret < 0 )
sprintf(ret_msg,"create_patient %s fail to create with code %d!",new_patient_name,ret);
else
sprintf(ret_msg,"create_patient %s successfully ack!",new_patient_name);
/*
* Exits
*/
} else if (!strcmp(cmd,"exit")) {
ret = 0 ;
//strcpy(ret_msg,"exit!");
sprintf(ret_msg,"exit!");
ConnTxCjsonnt_srv (accept_sock,ret,ret_msg,NULL,0);
return NULL;
} else {
printf("Abnoral commands '%s' be received from clients.\n",cmd);
sprintf(ret_msg,"Abnormal commands '%s'.\n",cmd);
//exit(-1);
}
/*
* Send result back clients.
*/
ret=ConnTxCjsonnt_srv (accept_sock,ret,ret_msg,qry_rslt_rows,qry_row_num);
if (ret <0) {
printf("Abnormal message transmit to client,exit.\n");
close(accept_sock);
exit(-1);
}
/*
else {
printf("[clientopers]Send ack message to client from sock %d,ret_val:%d,ret_msg:[%s].\n",accept_sock,ret,ret_msg);
}
*/
//??? wireshark:this will triger fin-ack to client.
//close(accept_sock);
}
return NULL;
}
<file_sep>/lab4/tcp/makefile
C = gcc
INCLUDES = -I .
CFLAGS = -g -Wall $(INCLUDES) -pthread
LDFLAGS = -lm
LDPATH =
TARGET1 = client server
#OBJ1 = client_tcp.o
#define rpcgen files
RPC_FILES=get_file.h get_file_clnt.c get_file_svc.c get_file_xdr.c
all: ${RPC_FILES} ${TARGET1}
${RPC_FILES}:
rpcgen -N get_file.x
# client
client: get_file_client.o get_file_clnt.o
$(CC) $(CFLAGS) -o ../bin_tcp_client/client get_file_client.o get_file_clnt.o
get_file_client.o:
$(CC) $(CFLAGS) -c get_file_client.c
get_file_clnt.o:
$(CC) $(CFLAGS) -c get_file_clnt.c
# server
server: get_file_svc.o get_file_proc_srv.o
$(CC) $(CFLAGS) -o ../bin_tcp_server/server get_file_proc_srv.o get_file_svc.o
get_file_svc.o:
$(CC) $(CFLAGS) -c get_file_svc.c
get_file_proc_srv.o:
$(CC) $(CFLAGS) -c get_file_proc_srv.c
clean:
rm -rf *.o rx_*.txt $(TARGET1)
<file_sep>/dist_hc_sys/client/src/user_manual.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "user_mannual.h"
#define MAX_USER_NAME_LEN 64
#define MAX_PSWD_LEN 64
#define MAX_RBUF_LEN 256
extern void GetInputs(char* in,int length,int mask);
/*
* Admin user main manual
*/
void admin_manual(char* in){
printf("Please select:\n");
printf("a : create account;\n");
printf("b : delete account;\n");
printf("c : change password;\n");
printf("d : show account list;\n");
printf("e : exit;\n");
//received input option
int rtry_cnt = 0;
do
{
printf(">");
GetInputs(in,2,0);
//printf("input option:%s.\n",in);
if ( !strcmp(in,"a") ||
!strcmp(in,"b") ||
!strcmp(in,"c") ||
!strcmp(in,"d") ||
!strcmp(in,"e") ) {
//printf("valid option:%s.\n",in);
break;
}
else {
rtry_cnt++;
printf("Not valid option,please re-input.\n");
}
} while (rtry_cnt<6);
if ( rtry_cnt>=6) {
printf("Too many retry times,exit.\n");
exit(-1);
}
//printf("valid option,exit manual.\n");
}
/*
* Admin sub manual
*/
void admin_create_accnt_manual(char* new_usr_grp,char* new_usr_name,char* new_pswd){
printf("Please input new account group: ");
GetInputs(new_usr_grp,MAX_USER_NAME_LEN,0);
printf("Please input new account name: ");
GetInputs(new_usr_name,MAX_USER_NAME_LEN,0);
printf("Please input new passowrd: ");
GetInputs(new_pswd,MAX_PSWD_LEN,0);
}
void admin_del_accnt_manual(char* del_usr_name){
printf("Please input account name to be deleted: ");
GetInputs(del_usr_name,MAX_USER_NAME_LEN,0);
}
/*
* healthcare user main manual
*/
void healthcare_manual(char* in){
printf("Please select:\n");
printf("a : change password;\n");
printf("b : create patient;\n");
printf("c : query patient ;\n");
printf("d : update patient record;\n");
printf("e : exit;\n");
//received input option
int rtry_cnt = 0;
do
{
printf(">");
GetInputs(in,2,0);
//printf("input option:%s.\n",in);
if ( !strcmp(in,"a") ||
!strcmp(in,"b") ||
!strcmp(in,"c") ||
!strcmp(in,"d") ||
!strcmp(in,"e") ) {
//printf("valid option:%s.\n",in);
break;
}
else {
rtry_cnt++;
printf("Not valid option,please re-input.\n");
}
} while (rtry_cnt<6);
if ( rtry_cnt>=6) {
printf("Too many retry times,exit.\n");
exit(-1);
}
//printf("valid option,exit manual.\n");
}
/*
* healthcare sub manual
*/
void healthcare_create_accnt_manual(char* new_patient_name,char* new_patient_insurance,char* new_record){
printf("Please input new patient name: ");
GetInputs(new_patient_name,MAX_USER_NAME_LEN,0);
printf("Please input new patient insurance coverage(Y/N): ");
GetInputs(new_patient_insurance,MAX_USER_NAME_LEN,0);
printf("Please input new patient record: ");
GetInputs(new_record,MAX_USER_NAME_LEN,0);
}
void healthcare_qry_manual(char* qry_name){
printf("Please input query patient name : ");
GetInputs(qry_name,MAX_USER_NAME_LEN,0);
}
void healthcare_modify_manual(char* item_name,char* new_item){
printf("Please input patient name to be modified : ");
GetInputs(item_name,MAX_USER_NAME_LEN,0);
printf("Please input new patient record: ");
GetInputs(new_item,MAX_RBUF_LEN,0);
}
/*
* clients: healthcare / insurance
* Function: query account
*/
void modify_manual(char* item_name,char* new_item){
printf("Please input name to be modified : ");
GetInputs(item_name,MAX_USER_NAME_LEN,0);
printf("Please input new item content: ");
GetInputs(new_item,MAX_RBUF_LEN,0);
}
/*
* clients: all
* Function: query account
*/
void qry_manual(char* qry_usr_name){
printf("Please input query name : ");
GetInputs(qry_usr_name,MAX_USER_NAME_LEN,0);
}
/*
* all clients common function
*/
void chg_pswd_manual(char* chg_usr_pswd){
printf("Please input new password : ");
GetInputs(chg_usr_pswd,MAX_PSWD_LEN,0);
}
/*
* insurance user main manual
*/
void insurance_manual(char* in){
printf("Please select:\n");
printf("a : change password;\n");
printf("b : query patient ;\n");
printf("c : update patient record;\n");
printf("e : exit;\n");
//received input option
int rtry_cnt = 0;
do
{
printf(">");
GetInputs(in,2,0);
//printf("input option:%s.\n",in);
if ( !strcmp(in,"a") ||
!strcmp(in,"b") ||
!strcmp(in,"c") ||
!strcmp(in,"e") ) {
//printf("valid option:%s.\n",in);
break;
}
else {
rtry_cnt++;
printf("Not valid option,please re-input.\n");
}
} while (rtry_cnt<6);
if ( rtry_cnt>=6) {
printf("Too many retry times,exit.\n");
exit(-1);
}
//printf("valid option,exit manual.\n");
}
<file_sep>/lab4/udp/get_file.h
/*
* Please do not edit this file.
* It was generated using rpcgen.
*/
#ifndef _GET_FILE_H_RPCGEN
#define _GET_FILE_H_RPCGEN
#include <rpc/rpc.h>
#ifdef __cplusplus
extern "C" {
#endif
struct get_file_content_1_argument {
char *arg1;
int arg2;
};
typedef struct get_file_content_1_argument get_file_content_1_argument;
#define GETFILEPROG 0x2000000
#define GETFILE_VER 1
#if defined(__STDC__) || defined(__cplusplus)
#define GET_FILE_CONTENT 1
extern char ** get_file_content_1(char *, int , CLIENT *);
extern char ** get_file_content_1_svc(char *, int , struct svc_req *);
#define GET_FILE_TRANS 2
extern int * get_file_trans_1(char *, CLIENT *);
extern int * get_file_trans_1_svc(char *, struct svc_req *);
extern int getfileprog_1_freeresult (SVCXPRT *, xdrproc_t, caddr_t);
#else /* K&R C */
#define GET_FILE_CONTENT 1
extern char ** get_file_content_1();
extern char ** get_file_content_1_svc();
#define GET_FILE_TRANS 2
extern int * get_file_trans_1();
extern int * get_file_trans_1_svc();
extern int getfileprog_1_freeresult ();
#endif /* K&R C */
/* the xdr functions */
#if defined(__STDC__) || defined(__cplusplus)
extern bool_t xdr_get_file_content_1_argument (XDR *, get_file_content_1_argument*);
#else /* K&R C */
extern bool_t xdr_get_file_content_1_argument ();
#endif /* K&R C */
#ifdef __cplusplus
}
#endif
#endif /* !_GET_FILE_H_RPCGEN */
<file_sep>/dist_hc_sys/client/src/usercli.c
/* File : usercli.c
*
* Author : grp1
*
* Desc : this is client user interface functions.
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <cJSON.h>
#include <authenuser.h>
#include "user_mannual.h"
#include "usercli.h"
#include "connexch.h"
#define MAX_ARG_NUMS 4
#define MAX_ARG_LEN 128
#define MAX_RBUF_SIZE 1024
int UserCli (int client_sock,char* user_grp,char* user_name,char* user_pswd) {
// "admin" user group operation
if (!strcmp(user_grp,"admin")) {
admin_opers(client_sock,user_grp,user_name,user_pswd);
}
// "healthcare" user group operation
else if (!strcmp(user_grp,"healthcare")) {
healthcare_opers(client_sock,user_grp,user_name,user_pswd);
}
// "insurance" user group operation
else if (!strcmp(user_grp,"insurance")) {
insurance_opers(client_sock,user_grp,user_name,user_pswd);
}
else {
printf ("Unrecogized user group!\n");
exit(-1);
}
return 0;
}
/*
* admin operations
*/
void admin_opers(int client_sock,char* user_grp,char* user_name,char* user_pswd) {
int valid_op ,ret;
do
{
//char* in_cmd_main = {0};
//char in_cmd_main[MAX_ARG_NUMS]={0}; --0502 wins:overflow caused varible value wrong.
char in_cmd_main[MAX_ARG_LEN]={0};
//char in_argus[MAX_ARG_LEN][MAX_ARG_NUMS]= {0};
char* in_argus[]= {"NULL","NULL","NULL"};
char in_argus0[MAX_ARG_LEN]= {0};
char in_argus1[MAX_ARG_LEN]= {0};
char in_argus2[MAX_ARG_LEN]= {0};
char in_argus3[MAX_RBUF_SIZE]= {0};
admin_manual(in_cmd_main);
valid_op = 1;
if ( !strcmp(in_cmd_main,"a" ) ) {
strcpy(in_cmd_main,"create_accnt");
admin_create_accnt_manual(in_argus0,in_argus1,in_argus2);
} else if (!strcmp(in_cmd_main,"b")) {
strcpy(in_cmd_main,"del_accnt");
admin_del_accnt_manual(in_argus1);
} else if (!strcmp(in_cmd_main,"c")) {
strcpy(in_cmd_main,"upd_pswd");
strcpy(in_argus0,"users");
strcpy(in_argus2,"password");
modify_manual(in_argus1,in_argus3);
} else if (!strcmp(in_cmd_main,"d")) {
strcpy(in_cmd_main,"show_list");
qry_manual(in_argus0); //tbl=input;
strcpy(in_argus1 ,"*") ; //item=any;
} else if (!strcmp(in_cmd_main,"e")) {
strcpy(in_cmd_main,"exit");
//close(client_sock);
//exit(0);
} else {
printf ("No supported operations\n");
valid_op = 0;
}
in_argus[0]= in_argus0;
in_argus[1]= in_argus1;
in_argus[2]= in_argus2;
in_argus[3]= in_argus3;
if (valid_op) {
printf ("User %s send commands(%s) to server with argus:%s,%s,%s,%s.\n",user_name,in_cmd_main,in_argus[0],in_argus[1],in_argus[2],in_argus[3]);
int ary_argus_len = 4;
ConnTxCjsonnt_clt (client_sock,user_grp,user_name,user_pswd,in_cmd_main,in_argus,ary_argus_len);
// receive ack message from server
char ret_msgs[MAX_RBUF_SIZE]= {0};
ret= ConnRxCjsonnt_clt (client_sock,ret_msgs);
if (ret< 0) {
printf("Failed to receive ack message from server:%s\n",ret_msgs);
}
}
if (!strcmp(in_cmd_main,"exit") )
{
close(client_sock);
exit(0);
}
} while (1) ;
}
/*
* healthcare operations
*/
void healthcare_opers(int client_sock,char* user_grp,char* user_name,char* user_pswd) {
int valid_op ,ret;
do
{
//char* in_cmd_main = {0};
//char in_cmd_main[MAX_ARG_NUMS]={0}; --0502 wins:overflow caused varible value wrong.
char in_cmd_main[MAX_ARG_LEN]={0};
//char in_argus[MAX_ARG_LEN][MAX_ARG_NUMS]= {0};
char* in_argus[]= {"NULL","NULL","NULL"};
char in_argus0[MAX_ARG_LEN]= {0};
char in_argus1[MAX_ARG_LEN]= {0};
char in_argus2[MAX_ARG_LEN]= {0};
char in_argus3[MAX_RBUF_SIZE]= {0};
healthcare_manual(in_cmd_main);
valid_op = 1;
if (!strcmp(in_cmd_main,"a")) {
strcpy(in_cmd_main,"upd_pswd");
strcpy(in_argus0,"users");
strcpy(in_argus2,"password");
modify_manual(in_argus1,in_argus3);
} else if ( !strcmp(in_cmd_main,"b" ) ) {
strcpy(in_cmd_main,"create_patient");
healthcare_create_accnt_manual(in_argus1,in_argus2,in_argus3); //input: 2-patient_name,3-patient record.
} else if (!strcmp(in_cmd_main,"c")) {
strcpy(in_cmd_main,"show_list");
healthcare_qry_manual(in_argus1); //item=input;
strcpy(in_argus0 ,"patients") ; //tbl=patients;
} else if (!strcmp(in_cmd_main,"d")) {
strcpy(in_cmd_main,"upd_patient");
strcpy(in_argus0,"patients"); // 0-tbl name
strcpy(in_argus2,"records"); // 2-new item name
healthcare_modify_manual(in_argus1,in_argus3);// 1-patient 2-name; 3- new record
} else if (!strcmp(in_cmd_main,"e")) {
strcpy(in_cmd_main,"exit");
//close(client_sock);
//exit(0);
} else {
printf ("No supported operations\n");
valid_op = 0;
}
in_argus[0]= in_argus0;
in_argus[1]= in_argus1;
in_argus[2]= in_argus2;
in_argus[3]= in_argus3;
if (valid_op) {
//printf ("User %s send commands(%s) to server with argus:%s,%s,%s,%s.\n",user_name,in_cmd_main,in_argus[0],in_argus[1],in_argus[2],in_argus[3]);
int ary_argus_len = 4;
ConnTxCjsonnt_clt (client_sock,user_grp,user_name,user_pswd,in_cmd_main,in_argus,ary_argus_len);
// receive ack message from server
char ret_msgs[MAX_RBUF_SIZE]= {0};
ret= ConnRxCjsonnt_clt (client_sock,ret_msgs);
if (ret< 0) {
printf("Failed to receive ack message from server:%s\n",ret_msgs);
}
}
if (!strcmp(in_cmd_main,"exit") )
{
close(client_sock);
exit(0);
}
} while (1) ;
}
/*
* insurance operations
*/
void insurance_opers(int client_sock,char* user_grp,char* user_name,char* user_pswd) {
int valid_op ,ret;
do
{
//char* in_cmd_main = {0};
//char in_cmd_main[MAX_ARG_NUMS]={0}; --0502 wins:overflow caused varible value wrong.
char in_cmd_main[MAX_ARG_LEN]={0};
//char in_argus[MAX_ARG_LEN][MAX_ARG_NUMS]= {0};
char* in_argus[]= {"NULL","NULL","NULL"};
char in_argus0[MAX_ARG_LEN]= {0};
char in_argus1[MAX_ARG_LEN]= {0};
char in_argus2[MAX_ARG_LEN]= {0};
char in_argus3[MAX_RBUF_SIZE]= {0};
insurance_manual(in_cmd_main);
valid_op = 1;
if (!strcmp(in_cmd_main,"a")) {
strcpy(in_cmd_main,"upd_pswd");
strcpy(in_argus0,"users");
strcpy(in_argus2,"password");
modify_manual(in_argus1,in_argus3);
} else if (!strcmp(in_cmd_main,"b")) {
strcpy(in_cmd_main,"show_list");
healthcare_qry_manual(in_argus1); //item=input;
strcpy(in_argus0 ,"patients") ; //tbl=patients;
} else if (!strcmp(in_cmd_main,"c")) {
strcpy(in_cmd_main,"upd_patient");
strcpy(in_argus0,"patients"); // 0-tbl name
strcpy(in_argus2,"insurance_coverable"); // 2-new item name
healthcare_modify_manual(in_argus1,in_argus3);// 1-patient 2-name; 3- new record
} else if (!strcmp(in_cmd_main,"e")) {
strcpy(in_cmd_main,"exit");
//close(client_sock);
//exit(0);
} else {
printf ("No supported operations\n");
valid_op = 0;
}
in_argus[0]= in_argus0;
in_argus[1]= in_argus1;
in_argus[2]= in_argus2;
in_argus[3]= in_argus3;
if (valid_op) {
//printf ("User %s send commands(%s) to server with argus:%s,%s,%s,%s.\n",user_name,in_cmd_main,in_argus[0],in_argus[1],in_argus[2],in_argus[3]);
int ary_argus_len = 4;
ConnTxCjsonnt_clt (client_sock,user_grp,user_name,user_pswd,in_cmd_main,in_argus,ary_argus_len);
// receive ack message from server
char ret_msgs[MAX_RBUF_SIZE]= {0};
ret= ConnRxCjsonnt_clt (client_sock,ret_msgs);
if (ret< 0) {
printf("Failed to receive ack message from server:%s\n",ret_msgs);
}
}
if (!strcmp(in_cmd_main,"exit") )
{
close(client_sock);
exit(0);
}
} while (1) ;
}
<file_sep>/dist_hc_sys_wins/src/connexch.c
/* File: conntx.c
*
* Author: grp1
*
* Desc : this is tx cjson format message via tcp connection.
*
*/
#define __WINDOWS
//#define __LINUX
#ifdef __LINUX
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <errno.h>
#endif
#ifdef __WINDOWS
#define WIN32_LEAN_AND_MEAN
/***********Winsock**********************/
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdlib.h>
#include <stdio.h>
/***********End of Winsock**************/
#endif
#include <cJSON.h>
#define MAX_RBUF_SIZE 1024
int ConnTx (int socket,cJSON* txmsg) {
char* json_str = NULL;
char* txbuf = NULL ;
int ret = 0;
// Allocate memory for tx cjson message.
json_str = cJSON_Print (txmsg);
txbuf = malloc(strlen(json_str)+1) ;
memset (txbuf,0,strlen(json_str));
memcpy (txbuf,json_str,strlen(json_str)) ;
#ifdef __LINUX
int txlen = write(socket,txbuf,strlen(json_str)) ;
if (txlen != strlen(json_str)) {
printf ("Abnormal tx message for socket: %d. \n",socket);
ret = -1;
}
#endif
#ifdef __WINDOWS
int txresult = send(socket,txbuf,strlen(json_str),0) ;
if (txresult == SOCKET_ERROR) {
printf ("Abnormal tx message for socket: %d. \n",socket);
ret = -1;
}
#endif
//debugging
//else {
//printf ("[ConnTx]: send message from socket %d to remote : %s.\n", socket,txbuf);
//}
//cJSON_Delete (txmsg);
cJSON_free(json_str);
free(txbuf);
return ret;
}
cJSON* ConnRx (int socket) {
char rxbuf [MAX_RBUF_SIZE] = {0};
// read from socket
int rxresult;
#ifdef __LINUX
rxresult = read(socket,rxbuf,MAX_RBUF_SIZE);
if ( rxresult < 0 ) {
// printf ("Failed to read, error code : %s \n",strerror(errno));
return NULL ;
}
#endif
#ifdef __WINDOWS
rxresult = recv(socket,rxbuf,MAX_RBUF_SIZE,0);
if ( rxresult < 0 ) {
printf ("Failed to read from socket:%d\n",socket);
return NULL ;
}
#endif
/*
//debugging
else {
printf ("[ConnRx]: send message from socket %d to remote : %s.\n", socket,rxbuf);
}
*/
// Return cjson format message
return cJSON_Parse(rxbuf);
}
/*
*client send and receive function
*/
//int ConnTxCjsonnt_clt (int client_sock,char* user_grp,char* user_name,char* user_pswd,char* cmd,char* ary_arguments[]) {
int ConnTxCjsonnt_clt (int client_sock,char* user_grp,char* user_name,char* user_pswd,char* cmd,char* ary_arguments[],int ary_len) {
cJSON* cjson_txmsg = NULL ;
//printf("[conn] Arguments to be sent from client to server: %s, %s\n",ary_arguments[0],ary_arguments[1]);
// Create cjson txmsg to server
cjson_txmsg = cJSON_CreateObject();
cJSON_AddItemToObject (cjson_txmsg,"grp",cJSON_CreateString(user_grp));
cJSON_AddItemToObject (cjson_txmsg,"name",cJSON_CreateString(user_name));
cJSON_AddItemToObject (cjson_txmsg,"passwd",cJSON_CreateString(user_pswd));
cJSON_AddItemToObject (cjson_txmsg,"cmd",cJSON_CreateString(cmd));
//cJSON_AddItemToObject (cjson_txmsg,"ary_arguments",cJSON_CreateString(ary_arguments));
cJSON* in_args = cJSON_CreateArray() ;
for (int i=0;i<ary_len;i++) {
cJSON_AddItemToArray(in_args,cJSON_CreateString(ary_arguments[i]));
}
/*
cJSON_AddItemToArray(in_args,cJSON_CreateString(ary_arguments[0]));
cJSON_AddItemToArray(in_args,cJSON_CreateString(ary_arguments[1]));
cJSON_AddItemToArray(in_args,cJSON_CreateString(ary_arguments[2]));
*/
cJSON_AddItemToObject (cjson_txmsg,"arguments",in_args);
//debugging-print whole tx cjson message.
char* str_cjson ;
str_cjson = cJSON_Print(cjson_txmsg) ;
printf ("Sending auth message with cjson :%s \n", str_cjson);
// send authen message to server
int ret = ConnTx(client_sock, cjson_txmsg);
if (ret<0) {
printf ("Failed to send cjson message to server\n");
cJSON_Delete (cjson_txmsg);
exit(-1);
}
cJSON_Delete (cjson_txmsg);
return ret;
}
// Client rx cjson message from server
int ConnRxCjsonnt_clt (int accept_sock,char* ret_msgs) {
cJSON* rxmsg_cjson = NULL ;
rxmsg_cjson = ConnRx (accept_sock);
// debug printing
char* str_rxmsg_cjson ;
str_rxmsg_cjson = cJSON_Print(rxmsg_cjson) ;
printf ("Received cjson message: %s \n",str_rxmsg_cjson);
// extract fields from cjson
cJSON* ret_val_json = cJSON_GetObjectItemCaseSensitive(rxmsg_cjson, "return");
cJSON* ary_ret_msgs_json = cJSON_GetObjectItemCaseSensitive(rxmsg_cjson, "ret_msgs");
cJSON* ret_msgs_elem_obj;
int ary_ret_msgs_len = cJSON_GetArraySize(ary_ret_msgs_json) ;
if (ary_ret_msgs_len>0){
for(int idx=0;idx<ary_ret_msgs_len;idx++){
ret_msgs_elem_obj = cJSON_GetArrayItem(ary_ret_msgs_json,idx);
printf("%s",cJSON_GetStringValue(ret_msgs_elem_obj));
}
}
printf("received msg len from server:%d, ret value:;\n",ary_ret_msgs_len);
//printf("received msg len from server:%d, ret value:%d;\n",ary_ret_msgs_len,(int)ret_val_json ->valuedouble);
return (int)ret_val_json ->valuedouble;
}
/*
* server send and receive function
*/
int ConnRxCjsonnt_srv (int accept_sock,char* user_grp,char* user_name,char* user_pswd,char* cmd,char* ary_arguments[]) {
cJSON* rxmsg_cjson = NULL ;
rxmsg_cjson = ConnRx (accept_sock);
//printf("[conn] Arguments to be received from client to server: %s, %s.\n",ary_arguments[0],ary_arguments[1]);
// debugging
char* str_rxmsg_cjson ;
str_rxmsg_cjson = cJSON_Print(rxmsg_cjson) ;
printf ("Received cjson message: %s \n",str_rxmsg_cjson);
// extract fields from cjson message
cJSON* grp_json = cJSON_GetObjectItemCaseSensitive(rxmsg_cjson, "grp");
cJSON* name_json = cJSON_GetObjectItemCaseSensitive(rxmsg_cjson, "name");
cJSON* password_json = cJSON_GetObjectItemCaseSensitive(rxmsg_cjson, "passwd");
cJSON* cmd_json = cJSON_GetObjectItemCaseSensitive(rxmsg_cjson, "cmd");
cJSON* ary_args_json = cJSON_GetObjectItemCaseSensitive(rxmsg_cjson, "arguments");
//cJSON* args_elem_obj;
// extract cjson object into chars
int ary_args_len = cJSON_GetArraySize(ary_args_json) ;
//printf("recived args lengths:%d;\n",ary_args_len);
if (ary_args_len>0) {
for(int idx=0;idx<ary_args_len;idx++){
cJSON* args_elem_obj = cJSON_GetArrayItem(ary_args_json,idx);
//strncpy(ary_arguments[idx],cJSON_GetStringValue(args_elem_obj),strlen(cJSON_GetStringValue(args_elem_obj))); -> wrong,
ary_arguments[idx]=cJSON_GetStringValue(args_elem_obj);
//printf ("args array unit %d :%s.\n",idx,ary_arguments[idx] );
}
}
if(cJSON_IsString(grp_json)) {
strncpy(user_grp, (char *) grp_json->valuestring, strlen((char *) grp_json->valuestring));
//printf("Received user_grp:%s,user_name:%s,user_pswd:%s;\n",user_grp,user_name,user_pswd);
} else {
printf(" Invalid user group format from cJSON message \n");
exit(-1);
}
if(cJSON_IsString(name_json)) {
strncpy(user_name, (char *) name_json->valuestring, strlen((char *) name_json->valuestring));
} else {
printf(" Invalid user name format from cJSON message \n");
exit(-1);
}
if(cJSON_IsString(password_json)) {
strncpy(user_pswd, (char *) password_json->valuestring, strlen((char *) password_json->valuestring));
printf("Received passwd:%s.\n",user_pswd);
} else {
printf(" Invalid user password format from cJSON message \n");
exit(-1);
}
if(cJSON_IsString(cmd_json)) {
strncpy(cmd, (char *) cmd_json->valuestring, strlen((char *) cmd_json->valuestring));
//strcpy(cmd, (char *) cmd_json->valuestring);
printf("Received cmd:%s (%s).\n",cmd,(char *) cmd_json->valuestring);
} else {
printf(" Invalid user cmd format from cJSON message \n");
exit(-1);
}
return 0;
}
int ConnTxCjsonnt_srv (int accept_sock,int ret_val, char* ret_msg, char* ary_ret_msg[],int ary_ret_len) {
cJSON* ret_msg_json = cJSON_CreateObject ();
//char* ret_msg = "authenticaiton";
cJSON_AddNumberToObject(ret_msg_json,"return",ret_val);
cJSON_AddItemToObject(ret_msg_json,"message",cJSON_CreateString(ret_msg));
//arrary
cJSON* qry_rows = cJSON_CreateArray() ;
for(int i=0;i<ary_ret_len;i++) {
cJSON_AddItemToArray(qry_rows,cJSON_CreateString(ary_ret_msg[i]));
//printf("[ConnTxCjsonnt_srv] ary_ret_msg idx: %d, msg: %s.\n",i,ary_ret_msg[i]);
}
cJSON_AddItemToObject (ret_msg_json,"ret_arrary",qry_rows);
int tx_num = ConnTx (accept_sock,ret_msg_json);
// debugging
char* str_txmsg_cjson ;
str_txmsg_cjson = cJSON_Print(ret_msg_json) ;
printf ("Transmit cjson message: %s \n",str_txmsg_cjson);
cJSON_Delete (ret_msg_json);
if (tx_num <0 ) exit(-1);
return 0;
}
|
f71e457bb328e7e9fb6e0162f3afec0590963d8f
|
[
"Markdown",
"C",
"Text",
"Makefile"
] | 49
|
C
|
stanmei/Networking
|
19660f54a4c369340439c7c93c47233493ce5e52
|
ab59fb17f33bb9b8171de23d6096a8aadc85f15a
|
refs/heads/master
|
<repo_name>kktsvetkov/ShrinkPress<file_sep>/src/Reframe_PhpDoc.php
<?php
namespace ShrinkPress\Evolve;
class Reframe_PhpDoc extends Reframe
{
function reframeFunction($function, $filename)
{
$d = self::extractPackages($filename);
return array(
'method' => $function,
'class' => $d[1],
'namespace' => $ns = join('\\', $d),
'full' => $ns . '\\' . $d[1] . '::' . $function
);
}
function reframeClass($class, $filename)
{
$d = self::extractPackages($filename);
return array(
'class' => $class,
'namespace' => $ns = join('\\', $d),
'full' => $ns . '\\' . $class
);
}
function reframeGlobal($global, $filename)
{
$d = self::extractPackages($filename);
return array(
'global' => $global,
'class' => $d[1],
'namespace' => $ns = join('\\', $d),
'full' => $ns . '\\' . $d[1] . '::$' . $global
);
}
static $known = array();
static function extractPackages($filename)
{
if (!empty(self::$known[ $filename ]))
{
return self::$known[ $filename ];
}
$result = array('WordPress', 'Core');
$doccomment = substr(file_get_contents($filename), 0, 1024);
if (preg_match('~\s*\*\s+@package\s+(.+)\s+\*~Uis', $doccomment, $R))
{
$result[0] = $R[1];
}
if (preg_match('~\s*\*\s+@subpackage\s+(.+)\s+\*~Uis', $doccomment, $R))
{
$result[1] = $R[1];
}
if (empty($result[1]))
{
$result[1] = $result[0];
}
return self::$known[ $filename ] = $result;
}
}
<file_sep>/lint.php
<?php
include __DIR__ . '/vendor/autoload.php';
chdir(__DIR__ . '/reduced');
\ShrinkPress\Evolve\Linter::$ok = '*';
\ShrinkPress\Evolve\Linter::all();
echo "\n";
<file_sep>/src/Core.php
<?php
namespace ShrinkPress\Evolve;
class Core
{
static function isCoreFunction($function)
{
$function = (string) $function;
return !empty(self::coreFunctions[ $function ]);
}
static function isCoreClass($function)
{
return false;
}
const coreFunctions = array(
/* Core extension */
'class_exists' => 1,
'debug_backtrace' => 2,
'define' => 3,
'defined' => 4,
'error_reporting' => 5,
'extension_loaded' => 6,
'func_get_arg' => 7,
'func_get_args' => 8,
'func_num_args' => 9,
'function_exists' => 10,
'gc_enabled' => 11,
'get_class' => 12,
'get_class_methods' => 13,
'get_defined_constants' => 14,
'get_object_vars' => 15,
'get_resource_type' => 16,
'is_a' => 17,
'is_subclass_of' => 18,
'method_exists' => 19,
'restore_error_handler' => 20,
'set_error_handler' => 21,
'strcasecmp' => 22,
'strcmp' => 23,
'strlen' => 24,
'strncmp' => 25,
'trigger_error' => 26,
'zend_version' => 27,
/* standard extension */
'abs' => 28,
'addcslashes' => 29,
'addslashes' => 30,
'array_change_key_case' => 31,
'array_column' => 32,
'array_combine' => 33,
'array_diff' => 34,
'array_diff_assoc' => 35,
'array_diff_key' => 36,
'array_fill' => 37,
'array_fill_keys' => 38,
'array_filter' => 39,
'array_flip' => 40,
'array_intersect' => 41,
'array_intersect_assoc' => 42,
'array_intersect_key' => 43,
'array_key_exists' => 44,
'array_keys' => 45,
'array_map' => 46,
'array_merge' => 47,
'array_merge_recursive' => 48,
'array_pop' => 49,
'array_push' => 50,
'array_rand' => 51,
'array_reduce' => 52,
'array_replace_recursive' => 53,
'array_reverse' => 54,
'array_search' => 55,
'array_shift' => 56,
'array_slice' => 57,
'array_splice' => 58,
'array_sum' => 59,
'array_unique' => 60,
'array_unshift' => 61,
'array_values' => 62,
'array_walk' => 63,
'arsort' => 64,
'asort' => 65,
'assert' => 66,
'base64_decode' => 67,
'base64_encode' => 68,
'base_convert' => 69,
'basename' => 70,
'bin2hex' => 71,
'bindec' => 72,
'call_user_func' => 73,
'call_user_func_array' => 74,
'ceil' => 75,
'chmod' => 76,
'chr' => 77,
'clearstatcache' => 78,
'closedir' => 79,
'compact' => 80,
'constant' => 81,
'copy' => 82,
'count' => 83,
'crc32' => 84,
'current' => 85,
'decbin' => 86,
'dechex' => 87,
'dirname' => 88,
'disk_free_space' => 89,
'doubleval' => 90,
'end' => 91,
'error_get_last' => 92,
'error_log' => 93,
'escapeshellarg' => 94,
'explode' => 95,
'extract' => 96,
'fclose' => 97,
'feof' => 98,
'fflush' => 99,
'fgets' => 100,
'file' => 101,
'file_exists' => 102,
'file_get_contents' => 103,
'file_put_contents' => 104,
'filemtime' => 105,
'fileowner' => 106,
'fileperms' => 107,
'filesize' => 108,
'floatval' => 109,
'flock' => 110,
'floor' => 111,
'flush' => 112,
'fopen' => 113,
'fread' => 114,
'fseek' => 115,
'fsockopen' => 116,
'fstat' => 117,
'ftell' => 118,
'ftruncate' => 119,
'fwrite' => 120,
'get_html_translation_table' => 121,
'getenv' => 122,
'gethostbyaddr' => 123,
'gethostbyname' => 124,
'getimagesize' => 125,
'gettype' => 126,
'glob' => 127,
'header' => 128,
'header_remove' => 129,
'headers_sent' => 130,
'hexdec' => 131,
'html_entity_decode' => 132,
'htmlentities' => 133,
'htmlspecialchars' => 134,
'http_build_query' => 135,
'ignore_user_abort' => 136,
'image_type_to_mime_type' => 137,
'implode' => 138,
'in_array' => 139,
'inet_ntop' => 140,
'inet_pton' => 141,
'ini_get' => 142,
'ini_get_all' => 143,
'ini_set' => 144,
'intval' => 145,
'ip2long' => 146,
'iptcparse' => 147,
'is_array' => 148,
'is_bool' => 149,
'is_callable' => 150,
'is_dir' => 151,
'is_file' => 152,
'is_float' => 153,
'is_int' => 154,
'is_integer' => 155,
'is_nan' => 156,
'is_null' => 157,
'is_numeric' => 158,
'is_object' => 159,
'is_readable' => 160,
'is_resource' => 161,
'is_scalar' => 162,
'is_string' => 163,
'is_uploaded_file' => 164,
'is_writable' => 165,
'is_writeable' => 166,
'join' => 167,
'key' => 168,
'krsort' => 169,
'ksort' => 170,
'log' => 171,
'log10' => 172,
'ltrim' => 173,
'max' => 174,
'md5' => 175,
'md5_file' => 176,
'microtime' => 177,
'min' => 178,
'mkdir' => 179,
'move_uploaded_file' => 180,
'mt_rand' => 181,
'natcasesort' => 182,
'next' => 183,
'number_format' => 184,
'ob_clean' => 185,
'ob_end_clean' => 186,
'ob_end_flush' => 187,
'ob_get_clean' => 188,
'ob_get_flush' => 189,
'ob_get_length' => 190,
'ob_get_level' => 191,
'ob_start' => 192,
'opendir' => 193,
'ord' => 194,
'pack' => 195,
'parse_str' => 196,
'parse_url' => 197,
'pathinfo' => 198,
'phpinfo' => 199,
'phpversion' => 200,
'pow' => 201,
'prev' => 202,
'printf' => 203,
'quoted_printable_decode' => 204,
'rand' => 205,
'range' => 206,
'rawurlencode' => 207,
'readdir' => 208,
'readfile' => 209,
'realpath' => 210,
'register_shutdown_function' => 211,
'reset' => 212,
'rewind' => 213,
'rmdir' => 214,
'round' => 215,
'rtrim' => 216,
'scandir' => 217,
'serialize' => 218,
'set_time_limit' => 219,
'setcookie' => 220,
'sha1' => 221,
'sha1_file' => 222,
'shell_exec' => 223,
'shuffle' => 224,
'sizeof' => 225,
'sleep' => 226,
'sort' => 227,
'sprintf' => 228,
'stat' => 229,
'str_ireplace' => 230,
'str_pad' => 231,
'str_repeat' => 232,
'str_replace' => 233,
'str_split' => 234,
'strcspn' => 235,
'stream_context_create' => 236,
'stream_context_get_options' => 237,
'stream_context_set_option' => 238,
'stream_get_contents' => 239,
'stream_get_meta_data' => 240,
'stream_get_wrappers' => 241,
'stream_set_chunk_size' => 242,
'stream_set_read_buffer' => 243,
'stream_set_timeout' => 244,
'stream_socket_client' => 245,
'strip_tags' => 246,
'stripcslashes' => 247,
'stripos' => 248,
'stripslashes' => 249,
'stristr' => 250,
'strnatcasecmp' => 251,
'strpbrk' => 252,
'strpos' => 253,
'strrchr' => 254,
'strrev' => 255,
'strripos' => 256,
'strrpos' => 257,
'strspn' => 258,
'strstr' => 259,
'strtok' => 260,
'strtolower' => 261,
'strtoupper' => 262,
'strtr' => 263,
'strval' => 264,
'substr' => 265,
'substr_count' => 266,
'substr_replace' => 267,
'sys_get_temp_dir' => 268,
'tempnam' => 269,
'touch' => 270,
'trim' => 271,
'uasort' => 272,
'ucfirst' => 273,
'ucwords' => 274,
'uksort' => 275,
'umask' => 276,
'uniqid' => 277,
'unlink' => 278,
'unpack' => 279,
'unserialize' => 280,
'urldecode' => 281,
'urlencode' => 282,
'usort' => 283,
'version_compare' => 284,
'vsprintf' => 285,
'wordwrap' => 286,
/* SPL extension */
'spl_autoload_register' => 287,
'spl_object_hash' => 288,
/* date extension */
'checkdate' => 289,
'date' => 290,
'date_create' => 291,
'date_create_immutable_from_format' => 292,
'date_default_timezone_set' => 293,
'gmdate' => 294,
'gmmktime' => 295,
'mktime' => 296,
'strftime' => 297,
'strtotime' => 298,
'time' => 299,
'timezone_identifiers_list' => 300,
'timezone_offset_get' => 301,
'timezone_open' => 302,
'timezone_transitions_get' => 303,
/* libxml extension */
'libxml_clear_errors' => 304,
'libxml_disable_entity_loader' => 305,
'libxml_get_last_error' => 306,
/* openssl extension */
'openssl_decrypt' => 307,
'openssl_encrypt' => 308,
'openssl_get_cipher_methods' => 309,
'openssl_x509_parse' => 310,
/* pcre extension */
'preg_match' => 311,
'preg_match_all' => 312,
'preg_quote' => 313,
'preg_replace' => 314,
'preg_replace_callback' => 315,
'preg_split' => 316,
/* zlib extension */
'gzdecode' => 317,
'gzdeflate' => 318,
'gzencode' => 319,
'gzinflate' => 320,
'gzuncompress' => 321,
/* ctype extension */
'ctype_digit' => 322,
/* curl extension */
'curl_close' => 323,
'curl_errno' => 324,
'curl_error' => 325,
'curl_exec' => 326,
'curl_getinfo' => 327,
'curl_init' => 328,
'curl_multi_add_handle' => 329,
'curl_multi_close' => 330,
'curl_multi_exec' => 331,
'curl_multi_info_read' => 332,
'curl_multi_init' => 333,
'curl_multi_remove_handle' => 334,
'curl_setopt' => 335,
'curl_version' => 336,
/* hash extension */
'hash' => 337,
'hash_algos' => 338,
'hash_file' => 339,
'hash_final' => 340,
'hash_init' => 341,
'hash_update' => 342,
/* fileinfo extension */
'finfo_close' => 343,
'finfo_file' => 344,
'finfo_open' => 345,
'mime_content_type' => 346,
/* gd extension */
'imagealphablending' => 347,
'imagecopy' => 348,
'imagecopyresampled' => 349,
'imagecreatefromgif' => 350,
'imagecreatefromjpeg' => 351,
'imagecreatefrompng' => 352,
'imagecreatefromstring' => 353,
'imagecreatetruecolor' => 354,
'imagedestroy' => 355,
'imagegif' => 356,
'imagejpeg' => 357,
'imagepng' => 358,
'imagerotate' => 359,
'imagesavealpha' => 360,
'imagesx' => 361,
'imagesy' => 362,
'imagetypes' => 363,
/* iconv extension */
'iconv' => 364,
'iconv_mime_decode' => 365,
/* json extension */
'json_decode' => 366,
'json_encode' => 367,
/* mbstring extension */
'mb_check_encoding' => 368,
'mb_convert_encoding' => 369,
'mb_detect_encoding' => 370,
'mb_detect_order' => 371,
'mb_get_info' => 372,
'mb_internal_encoding' => 373,
'mb_list_encodings' => 374,
'mb_strtolower' => 375,
/* mysqli extension */
'mysqli_affected_rows' => 376,
'mysqli_character_set_name' => 377,
'mysqli_close' => 378,
'mysqli_connect_errno' => 379,
'mysqli_connect_error' => 380,
'mysqli_errno' => 381,
'mysqli_error' => 382,
'mysqli_fetch_array' => 383,
'mysqli_fetch_field' => 384,
'mysqli_fetch_object' => 385,
'mysqli_free_result' => 386,
'mysqli_get_client_info' => 387,
'mysqli_get_server_info' => 388,
'mysqli_init' => 389,
'mysqli_insert_id' => 390,
'mysqli_more_results' => 391,
'mysqli_next_result' => 392,
'mysqli_num_fields' => 393,
'mysqli_ping' => 394,
'mysqli_query' => 395,
'mysqli_real_connect' => 396,
'mysqli_real_escape_string' => 397,
'mysqli_select_db' => 398,
'mysqli_set_charset' => 399,
/* SimpleXML extension */
'simplexml_load_string' => 400,
/* exif extension */
'exif_imagetype' => 401,
'exif_read_data' => 402,
/* tokenizer extension */
'token_get_all' => 403,
/* xml extension */
'utf8_decode' => 404,
'utf8_encode' => 405,
'xml_error_string' => 406,
'xml_get_current_byte_index' => 407,
'xml_get_current_column_number' => 408,
'xml_get_current_line_number' => 409,
'xml_get_error_code' => 410,
'xml_parse' => 411,
'xml_parse_into_struct' => 412,
'xml_parser_create' => 413,
'xml_parser_create_ns' => 414,
'xml_parser_free' => 415,
'xml_parser_set_option' => 416,
'xml_set_character_data_handler' => 417,
'xml_set_default_handler' => 418,
'xml_set_element_handler' => 419,
'xml_set_end_namespace_decl_handler' => 420,
'xml_set_object' => 421,
'xml_set_start_namespace_decl_handler' => 422,
/* mcrypt extension */
'mcrypt_create_iv' => 423,
/* xdiff extension */
'xdiff_string_diff' => 424,
/* FPM extension */
'fastcgi_finish_request' => 425,
/* OPcache extension */
'opcache_invalidate' => 426,
/* Apache extension */
'apache_get_modules' => 427,
/* Ignore extension */
'debug' => 428,
/* Dunno what happened, didn't detected those as internal */
'fputs' => -1,
'socket_set_option' => -1,
'socket_last_error' => -1,
'socket_strerror' => -1,
'socket_close' => -1,
'socket_create' => -1,
'socket_connect' => -1,
'socket_read' => -1,
'socket_write' => -1,
'socket_getsockname' => -1,
'socket_bind' => -1,
'socket_listen' => -1,
'socket_accept' => -1,
'sscanf' => -1,
'is_long' => -1,
'decoct' => -1,
'getcwd' => -1,
'dl' => -1,
'PclErrorCode' => -1,
'PclErrorString' => -1,
'is_link' => -1,
'gzopen' => -1,
'gzputs' => -1,
'gzclose' => -1,
'getdate' => -1,
'Chr' => -1,
'gzread' => -1,
'Ord' => -1,
'PclError' => -1,
'PclErrorReset' => -1,
'gzwrite' => -1,
'rename' => -1,
'php_uname' => -1,
'gd_info' => -1,
'exec' => -1,
'php_sapi_name' => -1,
'mysql_get_client_info' => -1,
'chdir' => -1,
'chgrp' => -1,
'chown' => -1,
'posix_getpwuid' => -1,
'filegroup' => -1,
'posix_getgrgid' => -1,
'fileatime' => -1,
'dir' => -1,
'ftp_ssl_connect' => -1,
'ftp_connect' => -1,
'ftp_login' => -1,
'ftp_pasv' => -1,
'ftp_get_option' => -1,
'ftp_set_option' => -1,
'ftp_fget' => -1,
'ftp_fput' => -1,
'ftp_pwd' => -1,
'ftp_chdir' => -1,
'ftp_site' => -1,
'ftp_chmod' => -1,
'ftp_rename' => -1,
'ftp_delete' => -1,
'ftp_rmdir' => -1,
'ftp_nlist' => -1,
'ftp_mdtm' => -1,
'ftp_size' => -1,
'ftp_mkdir' => -1,
'ftp_systype' => -1,
'ftp_rawlist' => -1,
'ftp_close' => -1,
'ssh2_connect' => -1,
'ssh2_auth_password' => -1,
'ssh2_auth_pubkey_file' => -1,
'ssh2_sftp' => -1,
'ssh2_exec' => -1,
'stream_set_blocking' => -1,
'ssh2_sftp_realpath' => -1,
'ssh2_sftp_rename' => -1,
'ssh2_sftp_unlink' => -1,
'ssh2_sftp_rmdir' => -1,
'ssh2_sftp_mkdir' => -1,
'mysql_get_server_info' => -1,
'date_default_timezone_get' => -1,
'natsort' => -1,
'sodium_crypto_sign_verify_detached' => -1,
'setlocale' => -1,
'crypt' => -1,
'mail' => -1,
'imap_rfc822_parse_adrlist' => -1,
'property_exists' => -1,
'filter_var' => -1,
'idn_to_ascii' => -1,
'escapeshellcmd' => -1,
'popen' => -1,
'pclose' => -1,
'ctype_alnum' => -1,
'openssl_pkcs7_sign' => -1,
'openssl_error_string' => -1,
'get_magic_quotes_runtime' => -1,
'set_magic_quotes_runtime' => -1,
'chunk_split' => -1,
'quoted_printable_encode' => -1,
'gethostname' => -1,
'rawurldecode' => -1,
'openssl_pkey_get_private' => -1,
'openssl_get_md_methods' => -1,
'openssl_sign' => -1,
'openssl_pkey_free' => -1,
'openssl_pkey_get_details' => -1,
'openssl_private_encrypt' => -1,
'settype' => -1,
'socket_set_blocking' => -1,
'var_export' => -1,
'stream_socket_enable_crypto' => -1,
'each' => -1,
'is_executable' => -1,
'socket_set_timeout' => -1,
'chop' => -1,
'socket_get_status' => -1,
'json_last_error' => -1,
'mb_stripos' => -1,
'imageantialias' => -1,
'imagecolorallocatealpha' => -1,
'imageistruecolor' => -1,
'imagecolorstotal' => -1,
'imagetruecolortopalette' => -1,
'ob_get_contents' => -1,
'htmlspecialchars_decode' => -1,
'libxml_use_internal_errors' => -1,
'simplexml_import_dom' => -1,
'count_chars' => -1,
'array_count_values' => -1,
'is_double' => -1,
'json_last_error_msg' => -1,
'rsort' => -1,
'mysql_set_charset' => -1,
'mysql_query' => -1,
'mysql_result' => -1,
'mysql_select_db' => -1,
'mysql_real_escape_string' => -1,
'mysql_error' => -1,
'mysql_free_result' => -1,
'mysql_connect' => -1,
'mysql_ping' => -1,
'mysql_errno' => -1,
'mysql_affected_rows' => -1,
'mysql_insert_id' => -1,
'mysql_fetch_object' => -1,
'mysql_client_encoding' => -1,
'mysql_num_fields' => -1,
'mysql_fetch_field' => -1,
'mysql_close' => -1,
);
}
<file_sep>/src/ScanFunctions.php
<?php
namespace ShrinkPress\Evolve;
use PhpParser\Node;
class ScanFunctions extends Inspect
{
protected $parser;
protected $findFunctions;
protected $hasCalls;
protected $hasHooks;
function __construct(Parse $parser)
{
parent::__construct(Inspect::skipFolders, Inspect::skipFiles);
$this->parser = $parser;
$this->findFunctions = new FindFunction;
$this->hasCalls = new HasCalls;
$this->hasCalls->exitOnFirstMatch = true;
$this->hasHooks = new HasHooks;
$this->hasHooks->exitOnFirstMatch = true;
$try = 0;
do {
echo "Try: ", ++$try, "\n";
$changes = $this->inspectFolder('');
} while ($changes);
}
protected $empty = array();
function inspectFile($filename)
{
// we looked at this file before,
// there are no functions inside it
//
if (!empty($this->empty[ $filename ]))
{
return false;
}
$code = file_get_contents( $filename );
$nodes = $this->parser->parse($code);
$nodes = $this->parser->traverse($this->findFunctions, $nodes);
if (!$nodes)
{
echo "(0) {$filename}\n";
$this->empty[ $filename ] = 1;
return false;
}
echo '(', count($nodes), ") {$filename}\n";
$changed = 0;
foreach ($nodes as $node)
{
// does it have other things that
// are about to change inside it ?
//
if ($this->hasMoreInside($node))
{
echo "SKIP {$node->name}()\n";
continue;
}
$f = $this->findFunctions->extract($node);
$f['filename'] = $filename;
if (!$m = Reframe::getFunction($f))
{
echo "MISSING REFRAME ", json_encode($f), "\n";
continue;
}
print_r($f);
print_r($m);
$f = Code::extractDefinition($code, $f);
Move::moveFunction($f, $m);
Git::commit("{$f['function']}() moved to {$m['full']}()");
Replace::replaceFunction($this->parser, $f, $m, 'replaceCall');
Replace::replaceFunction($this->parser, $f, $m, 'replaceHook');
Git::commit("{$f['function']}() replaced with {$m['full']}()");
// read the source code again, file might
// have been changed in the mean time when
// the hooks and calls were being converted
//
$code = file_get_contents( $filename );
Code::extractDefinition($code, $f);
file_put_contents($filename, $code);
Git::commit("drop {$f['function']}()");
file_put_contents(
'functions.csv',
"{$f['function']}, {$m['full']}, {$filename}:{$f['startLine']}\n",
FILE_APPEND
);
$changed = true;
break;
}
return $changed
? Inspect::INSPECT_STOP
: false;
}
/**
* Check if there are any references to other things that are about to change
*/
function hasMoreInside(Node $node)
{
// calls ?
//
if ($this->parser->traverse($this->hasCalls, [$node]))
{
return true;
}
// hooks ?
//
if ($this->parser->traverse($this->hasHooks, [$node]))
{
return true;
}
return false;
}
}
<file_sep>/src/HasSuperGlobals.php
<?php
namespace ShrinkPress\Evolve;
use PhpParser\Node;
class HasSuperGlobals extends VisitorAbstract
{
const ignore = array(
'HTTP_RAW_POST_DATA',
'PHP_SELF',
);
function leaveNode(Node $node)
{
if (!$node instanceof Node\Expr\ArrayDimFetch)
{
return;
}
if (!$node->var instanceof Node\Expr\Variable)
{
return;
}
if ('GLOBALS' == (string) $node->var->name)
{
$globalName = '';
if ($node->dim instanceof Node\Expr\Variable)
{
$globalName = (string) $node->dim->name;
} else
if ($node->dim instanceof Node\Scalar\String_)
{
$globalName = (string) $node->dim->value;
}
if (in_array($globalName, self::ignore))
{
return;
}
return $this->push( $globalName );
}
}
}
<file_sep>/README.md
# ShrinkPress: Break WordPress Apart
*A refactoring experiment by KT*
**Decompose WordPress to all its building blocks and put it up again as a modern and fast PHP7 project.**
My goal is to see how fast WordPress will become if it follows a better code
structure that resembles more a PHP7 project other than a PHP4 one converted
to PHP5 (as it is now).
## Roadmap
Here's what I want to do:
* no more includes, use autoloading (better with composer)
* no more loose functions, move them to static methods
* organise wp-includes into separate libs/packages
* extract packages from WP to allow to use them as separate libraries
* no more globals, use registry (or singleton)
* no more loose bundled 3rd-party libs, use composer and move them out
* no more default filters, load them only when they are needed
* take deprecated functions out into a "migration" plugin
* take non-essential core features and move them to plugins
* take out xmlrpc to a plugin
* take out wp-emojis to a plugin
The result must be compatible with existing plugins and themes, although with
some assistance via some sort of a migration tool.
Use [wp-dev tests](https://github.com/WordPress/wordpress-develop/tree/master/tests/phpunit) to validate the result as well.
## Bundled Packages in WordPress
Let's try and list libraries bundled inside WordPress:
* **Requests** https://github.com/rmccue/Requests
* **AtomLib** this is not even used internally, it is only left for backwards compatibility
<file_sep>/src/Parse.php
<?php
namespace ShrinkPress\Evolve;
use PhpParser\ParserFactory;
use PhpParser\NodeTraverser;
use PhpParser\NodeVisitorAbstract;
class Parse
{
protected $parser;
protected $traverser;
function __construct()
{
$this->traverser = new NodeTraverser;
$this->parser = (new ParserFactory)
->create(ParserFactory::PREFER_PHP7);
}
function parse($code)
{
return $this->parser->parse($code);
}
function traverse(NodeVisitorAbstract $visitor, array $nodes)
{
$this->traverser->addVisitor( $visitor );
$this->traverser->traverse( $nodes );
$this->traverser->removeVisitor( $visitor );
return !empty($visitor->result)
? $visitor->result
: null;
}
}
<file_sep>/TODO.md
# ShrinkPress TODO
* use PhpParser: https://github.com/nikic/PHP-Parser/blob/master/doc/2_Usage_of_basic_components.markdown#node-traversation
* clone from this WordPress repo: https://github.com/WordPress/WordPress/tree/5.4-branch
* try the shrinking on all releases since 4.9
* function stats: 2412 functions! (without wp-admin), 2834 functions! (total)
* remove "wp_" prefix, when in namespaces there is little chance of name clashes
* WordPress' own component organisation: https://make.wordpress.org/core/components/
* Load default-filters only when they are needed, not always; perhaps add a "DefaultFilters" class in each package ?
* create list of bundled libs/packages and their versions in each WP release
```
<exclude>
<!-- Third party library exclusions. -->
<directory suffix=".php">src/wp-includes/ID3</directory>
<directory suffix=".php">src/wp-includes/IXR</directory>
<directory suffix=".php">src/wp-includes/random_compat</directory>
<directory suffix=".php">src/wp-includes/Requests</directory>
<directory suffix=".php">src/wp-includes/SimplePie</directory>
<directory suffix=".php">src/wp-includes/Text</directory>
<file>src/wp-admin/includes/class-ftp*</file>
<file>src/wp-admin/includes/class-pclzip.php</file>
<file>src/wp-admin/includes/deprecated.php</file>
<file>src/wp-admin/includes/ms-deprecated.php</file>
<file>src/wp-includes/atomlib.php</file>
<file>src/wp-includes/class-IXR.php</file>
<file>src/wp-includes/class-json.php</file>
<file>src/wp-includes/class-phpass.php</file>
<file>src/wp-includes/class-phpmailer.php</file>
<file>src/wp-includes/class-pop3.php</file>
<file>src/wp-includes/class-requests.php</file>
<file>src/wp-includes/class-simplepie.php</file>
<file>src/wp-includes/class-smtp.php</file>
<file>src/wp-includes/class-snoopy.php</file>
<file>src/wp-includes/deprecated.php</file>
<file>src/wp-includes/ms-deprecated.php</file>
<file>src/wp-includes/pluggable-deprecated.php</file>
<file>src/wp-includes/rss.php</file>
</exclude>
```
* WTF?! there are require/require_once from inside functions, like require_wp_db()
* Phase 2 thing: cook the doccomment with the new stuff, so that the comments reflect the new changed code, e.g. instead of `@globalvar $wpdb"` make it `@see ShrinkPress/DB/Last::$db`
* look for performance-related ideas: https://petitions.classicpress.net/?view=most-wanted
* Autoloading WordPress:
https://core.trac.wordpress.org/ticket/36335
https://github.com/mikeschinkel/autoloading-wordpress
* https://composer.rarst.net/
* https://github.com/Modius22/FreshPress/tree/master
* https://github.com/codepotent/update-manager
* is it possible to make plugins have composer.json dependencies ? and install them upon installing the plugins.
* create a shrinkpress_pudding plugin for reporting number of included files, declared classes and functions
* https://github.com/magento/composer -- Magento's own composer extension
## Phase 1
* reduced, limited set of changes
* still do all of the main changes: functions, classes, globals
* no core plugin extraction
* classes are only moved to composer packages, class-map loaded, NOT renamed
* functions are moved as static methods to classes, NOT renamed
* globals are copied to static properties, with same name, NOT removed
* leave includes "as is", we are going to rely just on them being reduced
* exclude wp-admin/ !
* only wp-includes and root folder files
* no need for migration plugin
## Phase 2
* rename methods
* rename classes
* remove globals
* extract internal components as separate libs
## Phase 3
* extract core parts as plugins
* plugins dependencies
* alternative updates/downloads
* composer dependencies downloads
## Types of PHP files in WordPress
Different files have different roles, and then need to be parsed and unparsed
differently. There are files with similar characteristics, which can be treated
the same, and then there are special files, one of their kind, that need special
treatment.
Being backwards-compatible WordPress does not seem to delete old files, so a
file-based process would seem to work on different versions of the project.
* wp-admin/ controllers: pages loaded in the admin panel;
* external classes
* wp-includes/default-constants.php
* wp-includes/default-filters.php where filters are added in bulk
* wp-includes/pluggable.php with fallback function definitions
* wp-includes/pluggable-deprecated.php: fallback function definitions that are deprecated
* wp-includes/blocks/ block definitions
* wp-includes/compat.php: polyfills for different PHP versions
* wp-includes/widgets/ widget definitions
* deprecated file
## Types of operations
When starting to shrink, what type of operations will be needed
* define a package: create composer package inside the project for hosting moved classes, migrated functions into class methods, and migrated globals into static vars
* replace class: replace a class name with a new one for all original class occurrences; files will receive "use" statements for the class so that only the basic className is used inside the code
* move class: out of wp-includes or wp-admin/wp-includes, without renaming it, and put it under a package (library) WITHOUT using a new namespace;
* migrate class: like moving a class, but use a new className and put it under a namespace; afterwards replace all class occurrences in the code
* replace function: replace a function with a new static method in all direct call occurrences and all hook references.
* migrate function: replace a function with a static class method in all original function occurrences; files will receive "use" statements for the class hosting the static method, so that only the basic className is used along with the method in the code
* migrate global: replace a global var with a static class property in all original global var occurrences; files will receive "use" statements for the class hosting the static property to make it so that only the basic className is used inside the code
* drop include: after all the migration check the modified files to find if there are empty ones, and if there are, remove all include/include_once/require/require_once occurences for these files
## Shrinking: Classes
- see https://getcomposer.org/doc/04-schema.md#classmap
- put all of the classes in a folder and let composer scan for them when "dumpautoload"-ing; in this way any reference to that class will be served by composer autoload_classmap.php map.
- perhaps use multiple folders, so that still the classes are organised by their purpose;
- explore if it is a good idea to rename the old classes under the new namespace composer packages schema, and then just use class_alias() as compatibility for the old classes.
## Shrinking: Functions
1. find all functions, plus
+ files in which they are defined
+ starting and ending line
+ what other functions they are calling (exclude internal)
+ where are these functions called from (file, line, caller)
+ doccomment of the function
2. create the shrink map by assigning:
* namespace (package)
* className (+ classFile)
* method
3. sort functions by number of other functions they call, ascending
- in this way there will be no functions left behind, we are
always going to shrink only functions that have 0 other
not-yet-shrank functions called;
- because of this add_action and do_filter and other popular
functions will be shrank last
4. replace functions from sorted list
- insert them to the new class (and file)
- remove them from the original file
- add them to the compatibility file
- replace all occurrences with the new class method
<file_sep>/src/Replace.php
<?php
namespace ShrinkPress\Evolve;
class Replace
{
const marker = '%SHRINKPRESSREPLACE%';
static function replaceFunction(Parse $parser, array $f, array $m, $replaceFunc)
{
$inside = ('replaceCall' == $replaceFunc)
? HasInside::$has['calls']
: HasInside::$has['hooks'];
if (empty($inside[ $f['function'] ]))
{
return false;
}
foreach ($inside[ $f['function'] ] as $filename => $i)
{
echo "D0.{$replaceFunc} {$f['function']}() in {$filename}\n";
$code = file_get_contents( $filename );
$nodes = $parser->parse($code);
$replace = ('replaceCall' == $replaceFunc)
? new ReplaceCalls($f['function'])
: new ReplaceHooks($f['function']);
if ($matches = $parser->traverse($replace, $nodes))
{
$lines = explode("\n", $code);
foreach ($matches as $line)
{
$lines[ $line-1 ] = Code::$replaceFunc(
$lines[ $line-1 ],
$f['function'],
self::marker
);
}
$code = join("\n", $lines);
}
$code = str_replace(self::marker, '\\' . $m['full'], $code);
file_put_contents($filename, $code);
}
return true;
}
static function replaceGlobalStatement(Parse $parser, array $g, array $m, $code)
{
return $code;
}
}
<file_sep>/src/VisitorAbstract.php
<?php
namespace ShrinkPress\Evolve;
use PhpParser\NodeVisitorAbstract;
abstract class VisitorAbstract extends NodeVisitorAbstract
{
public $exitOnFirstMatch = false;
public $result = array();
function beforeTraverse(array $nodes)
{
$this->result = array();
}
function push($result)
{
$this->result[] = $result;
if ($this->exitOnFirstMatch)
{
// return NodeTraverser::STOP_TRAVERSAL;
return 2;
}
return;
}
function afterTraverse(array $nodes)
{
if (!$this->exitOnFirstMatch)
{
rsort($this->result);
}
}
}
<file_sep>/src/Inspect.php
<?php
namespace ShrinkPress\Evolve;
abstract class Inspect
{
protected $skipFolders = array();
const skipFolders = array(
'.git',
'wp-content',
'wp-admin/css',
'wp-admin/images',
'wp-admin/js',
'wp-includes/js',
// Composer::vendors . '/composer',
Composer::vendors,
'wp-includes/sodium_compat',
);
protected $skipFiles = array();
const skipFiles = array(
'wp-config.php',
'wp-config-sample.php',
'wp-admin/includes/noop.php',
// Composer::vendors . '/autoload.php',
);
function __construct(array $skipFolders = null, array $skipFiles = null)
{
$this->skipFolders = $skipFolders
? $skipFolders
: self::skipFolders;
$this->skipFiles = $skipFiles
? $skipFiles
: self::skipFiles;
}
function inspectFolder($folder)
{
$full = getcwd() . '/' . $folder;
if (!is_dir($full))
{
throw new \InvalidArgumentException(
'Argument $folder must be an existing folder,'
. " '{$folder}' is not ({$full})"
);
}
$dir = new \DirectoryIterator( $full );
foreach ($dir as $found)
{
if ($found->isDot())
{
continue;
}
$local = str_replace( getcwd() . '/', '', $found->getPathname() );
if ($found->isDir())
{
if (!in_array( $local, $this->skipFolders ))
{
if (self::INSPECT_STOP == $this->inspectFolder($local))
{
return self::INSPECT_STOP;
}
}
continue;
}
if (in_array( $local, $this->skipFiles ))
{
continue;
}
if ('php' != \pathinfo($local, PATHINFO_EXTENSION))
{
continue;
}
if (self::INSPECT_STOP == $this->inspectFile($local))
{
return self::INSPECT_STOP;
}
}
return self::INSPECT_OK;
}
const INSPECT_OK = 0;
const INSPECT_STOP = 2;
abstract function inspectFile($filename);
}
<file_sep>/src/HasCalls.php
<?php
namespace ShrinkPress\Evolve;
use PhpParser\Node;
class HasCalls extends VisitorAbstract
{
function leaveNode(Node $node)
{
if (!$node instanceof Node\Expr\FuncCall)
{
return;
}
if (!$node->name instanceOf Node\Name)
{
return;
}
$functionName = (string) $node->name;
if (Core::isCoreFunction( $functionName ))
{
return;
}
return $this->push($functionName);
}
}
<file_sep>/src/ReplaceHooks.php
<?php
namespace ShrinkPress\Evolve;
use PhpParser\Node;
use PhpParser\NodeVisitorAbstract;
class ReplaceHooks extends NodeVisitorAbstract
{
const callback_functions = array(
'add_filter' => 1,
'has_filter' => 1,
'remove_filter' => 1,
'add_action' => 1,
'has_action' => 1,
'remove_action' => 1,
);
public $find = '';
function __construct($find)
{
$this->find = (string) $find;
}
public $result = array();
function beforeTraverse(array $nodes)
{
$this->result = array();
}
function leaveNode(Node $node)
{
if (!$node instanceof Node\Expr\FuncCall)
{
return;
}
if (!$node->name instanceOf Node\Name)
{
return;
}
$caller = $node->name->__toString();
if (empty(self::callback_functions[ $caller ]))
{
return;
}
$arg_pos = self::callback_functions[ $caller ];
if (empty($node->args[ $arg_pos ]))
{
return;
}
if (!$node->args[ $arg_pos ]->value instanceof Node\Scalar\String_)
{
return;
}
$callback = $node->args[ $arg_pos ]->value->value;
if ($this->find != $callback)
{
return;
}
$this->result[] = $node->getLine();
}
function afterTraverse(array $nodes)
{
rsort($this->result);
}
}
<file_sep>/src/Reframe_Proto.php
<?php
namespace ShrinkPress\Evolve;
class Reframe_Proto extends Reframe
{
function reframeFunction($function, $filename)
{
$n = self::protoPackage($filename);
return array(
'method' => $function,
'class' => $n['class'],
'namespace' => $n['ns'],
'full' => $n['ns'] . '\\' . $n['class'] . '::' . $function
);
}
function reframeClass($class, $filename)
{
$n = self::protoPackage($filename);
return array(
// 'class' => $n['class'],
'class' => $class,
'namespace' => $n['ns'],
'full' => $n['ns'] . '\\' . $n['class']
);
}
function reframeGlobal($global, $filename)
{
$n = self::protoPackage($filename);
return array(
'global' => $global,
'class' => $n['class'],
'namespace' => $n['ns'],
'full' => $n['ns'] . '\\' . $n['class'] . '::$' . $global
);
}
private static function classify($string)
{
$string = pathinfo($string, PATHINFO_FILENAME);
$string = join('_', array_map('ucfirst', explode('-', $string)));
$string = join('\\', array_map('ucfirst', explode('\\', $string)));
$string = join('\\', array_map('ucfirst', explode('.', $string)));
$string = str_replace('Wp_', '', $string);
$string = str_replace('Class_', '', $string);
return 'WordPress\\' . $string;
}
private static function protoPackage($file)
{
$full = self::classify( $file );
$chunks = explode('\\', $full);
if (2 == count($chunks))
{
$chunks[2] = $chunks[1];
}
return array(
'class' => array_pop($chunks),
'ns' => join('\\', $chunks),
);
}
}
<file_sep>/src/Project.php
<?php
namespace ShrinkPress\Evolve;
class Project
{
protected $wordPressFolder = '';
function __construct($wordPressFolder)
{
chdir($this->wordPressFolder = $wordPressFolder);
}
function run()
{
$methods = get_class_methods($this);
foreach ($methods as $i => $method)
{
if (0 !== strpos($method, 'task_'))
{
unset($methods[$i]);
}
}
sort($methods);
foreach($methods as $i => $method)
{
echo (1 + $i), '. ', $method, "()\n";
$this->$method();
}
}
function task_0000_wipe()
{
// wipe the slate clean before starting
//
Git::checkout();
Composer::wipeComposer();
CsvLog::clean('functions.csv');
CsvLog::clean('globals.csv');
}
function task_0100_load()
{
$this->parser = new Parse;
}
function task_0200_start()
{
// start with .gitignore and .gitattributes
//
Git::dotGit();
// fresh copy of composer
//
Composer::plantComposer();
}
function task_0300_inside()
{
// learn what is inside
//
new HasInside($this->parser);
}
function task_0400_globals()
{
new ScanGlobals($this->parser);
}
function task_0500_classes()
{
}
function task_0600_functions()
{
// new ScanFunctions($this->parser);
}
function task_0700_remove_includes()
{
}
function task_0800_delete_old_files()
{
}
}
<file_sep>/src/Linter.php
<?php
namespace ShrinkPress\Evolve;
class Linter
{
const no_syntax_errors = 'No syntax errors detected in %s';
static $ok = '';
static function getLintError($php)
{
$file = trim($php);
$output = shell_exec('php -l ' . $file);
$no_syntax_errors = sprintf(self::no_syntax_errors, $file);
if (trim($output) != $no_syntax_errors)
{
throw new \RuntimeException($output);
}
echo self::$ok;
}
static function lintVendors($folder)
{
if (!is_dir($folder))
{
return false;
}
$dir = opendir($folder);
while (false !== ($file = readdir($dir)))
{
if (0 === strpos($file, '.'))
{
continue;
}
$full = $folder . '/' . $file;
if (is_dir($full))
{
self::lintVendors($full);
continue;
}
self::getLintError($full);
}
closedir($dir);
}
static function lintGitModified()
{
exec('git status', $output);
foreach($output as $line)
{
if (preg_match('~^modified\:\s+(.+\.php)$~Uis', trim($line), $R))
{
self::getLintError($R[1]);
}
}
}
static function all()
{
self::lintGitModified();
self::lintVendors( Composer::vendors );
}
}
<file_sep>/src/Reframe.php
<?php
namespace ShrinkPress\Evolve;
abstract class Reframe
{
const reframeClass = Reframe_Proto::class;
// const reframeClass = Reframe_Migrate::class;
// const reframeClass = Reframe_PhpDoc::class;
static private $instance;
static private function instance()
{
if (!isset(self::$instance))
{
$class = self::reframeClass;
self::$instance = new $class;
}
return self::$instance;
}
final static function getFunction(array $f)
{
return self::instance()->reframeFunction($f['function'], $f['filename']);
}
abstract function reframeFunction($function, $filename);
final static function getClass(array $c)
{
return self::instance()->reframeClass($c['class'], $c['filename']);
}
abstract function reframeClass($class, $filename);
final static function getGlobal(array $g)
{
return self::instance()->reframeGlobal($g['global'], $g['filename']);
}
abstract function reframeGlobal($global, $filename);
}
<file_sep>/src/HasInside.php
<?php
namespace ShrinkPress\Evolve;
class HasInside extends Inspect
{
protected $parser;
protected $inspectors = array();
static $has = array();
const inside_json = 'inside.json';
function __construct(Parse $parser)
{
parent::__construct(Inspect::skipFolders, Inspect::skipFiles);
$this->parser = $parser;
$this->inspectors = array(
'calls' => new HasCalls,
'hooks' => new HasHooks,
'super_globals' => new HasSuperGlobals,
'globals' => new HasGlobalsStatements,
);
if (file_exists(self::inside_json))
{
echo "* Restoring from ", self::inside_json, "\n";
self::$has = json_decode(
file_get_contents(self::inside_json),
true
);
} else
{
echo "* Generating ", self::inside_json, "\n";
$this->inspectFolder('');
file_put_contents(
self::inside_json,
json_encode(self::$has,
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
));
}
}
function inspectFile($filename)
{
echo "> {$filename}\n";
$code = file_get_contents( $filename );
$nodes = $this->parser->parse($code);
foreach ($this->inspectors as $type => $inspector)
{
if (!$found = $this->parser->traverse($inspector, $nodes))
{
continue;
}
foreach ($found as $match)
{
if (empty(self::$has[$type][$match][$filename]))
{
self::$has[$type][$match][$filename] = 1;
} else
{
self::$has[$type][$match][$filename]++;
}
}
}
}
}
<file_sep>/evolve.php
<?php
include __DIR__ . '/vendor/autoload.php';
ini_set('xdebug.max_nesting_level', 3000);
$p = new \ShrinkPress\Evolve\Project(__DIR__ . '/reduced');
$p->run();
<file_sep>/src/Migration.php
<?php
namespace ShrinkPress\Evolve;
class Migration
{
static function getFunction(array $f)
{
$function = (string) $f['function'];
if (empty(self::migrateFunctions[ $function ]))
{
// dummy proto packages based on filename
//
// return Proto::getFunction($f);
return phpDocPackages::getFunction($f);
}
$m = self::migrateFunctions[ $function ];
return array(
'method' => $m[0],
'class' => $m[1],
'namespace' => $m[2],
'full' => "{$m[2]}\\{$m[1]}::{$m[0]}"
);
}
/**
* method, class, namespace
*/
const migrateFunctions = array(
'export_add_js' => array('add_js', 'Export', 'ShrinkPress\\Admin'),
'get_cli_args' => array('get_cli_args', 'Console', 'ShrinkPress\\Admin'),
'wp_nav_menu_max_depth' => array('max_depth', 'Menu', 'ShrinkPress\\Admin'),
'do_activate_header' => array('activate_header', 'Activate', 'ShrinkPress\\Activate'),
// wp-admin/includes/class-pclzip.php
// 'PclZipUtilPathReduction' => array('UtilPathReduction', 'Paths', 'ShrinkPress\\PclZip'),
// wp-includes/l10n.php
'get_locale' => array('get_locale', 'L10N', 'ShrinkPress\\I18N'),
'get_user_locale' => array('get_user_locale', 'L10N', 'ShrinkPress\\I18N'),
'determine_locale' => array('determine_locale', 'L10N', 'ShrinkPress\\I18N'),
'is_rtl' => array('is_rtl', 'L10N', 'ShrinkPress\\I18N'),
'switch_to_locale' => array('switch_to_locale', 'L10N', 'ShrinkPress\\I18N'),
'restore_previous_locale' => array('restore_previous', 'L10N', 'ShrinkPress\\I18N'),
'restore_current_locale' => array('restore_current', 'L10N', 'ShrinkPress\\I18N'),
'is_locale_switched' => array('is_switched', 'L10N', 'ShrinkPress\\I18N'),
'translate' => array('translate', 'T9N', 'ShrinkPress\\I18N'),
'translate_nooped_plural' => array('translate_nooped_plural', 'T9N', 'ShrinkPress\\I18N'),
'translate_with_gettext_context' => array('translate_with_gettext_context', 'T9N', 'ShrinkPress\\I18N'),
'__' => array('__', 'T9N', 'ShrinkPress\\I18N'),
'_e' => array('_e', 'T9N', 'ShrinkPress\\I18N'),
'_x' => array('_x', 'T9N', 'ShrinkPress\\I18N'),
'_ex' => array('_ex', 'T9N', 'ShrinkPress\\I18N'),
'_n' => array('_n', 'T9N', 'ShrinkPress\\I18N'),
'_nx' => array('_nx', 'T9N', 'ShrinkPress\\I18N'),
'_n_noop' => array('_n_noop', 'T9N', 'ShrinkPress\\I18N'),
'_nx_noop' => array('_nx_noop', 'T9N', 'ShrinkPress\\I18N'),
'esc_attr__' => array('esc_attr__', 'HTML', 'ShrinkPress\\I18N\\T9N'),
'esc_attr_e' => array('esc_attr_e', 'HTML', 'ShrinkPress\\I18N\\T9N'),
'esc_attr_x' => array('esc_attr_x', 'HTML', 'ShrinkPress\\I18N\\T9N'),
'esc_html__' => array('esc_html__', 'HTML', 'ShrinkPress\\I18N\\T9N'),
'esc_html_e' => array('esc_html_e', 'HTML', 'ShrinkPress\\I18N\\T9N'),
'esc_html_x' => array('esc_html_x', 'HTML', 'ShrinkPress\\I18N\\T9N'),
'load_textdomain' => array('load', 'TextDomain', 'ShrinkPress\\I18N\\T9N'),
'unload_textdomain' => array('unload', 'TextDomain', 'ShrinkPress\\I18N\\T9N'),
'load_default_textdomain' => array('load_default', 'TextDomain', 'ShrinkPress\\I18N\\T9N'),
'load_plugin_textdomain' => array('load_plugin', 'TextDomain', 'ShrinkPress\\I18N\\T9N'),
'load_muplugin_textdomain' => array('load_muplugin', 'TextDomain', 'ShrinkPress\\I18N\\T9N'),
'load_theme_textdomain' => array('load_theme', 'TextDomain', 'ShrinkPress\\I18N\\T9N'),
'load_child_theme_textdomain' => array('load_child_theme', 'TextDomain', 'ShrinkPress\\I18N\\T9N'),
'load_script_textdomain' => array('load_script', 'TextDomain', 'ShrinkPress\\I18N\\T9N'),
'is_textdomain_loaded' => array('is_loaded', 'TextDomain', 'ShrinkPress\\I18N\\T9N'),
'_load_textdomain_just_in_time' => array('_load_just_in_time', 'TextDomain', 'ShrinkPress\\I18N\\T9N'),
'get_translations_for_domain' => array('get_translations', 'TextDomain', 'ShrinkPress\\I18N\\T9N'),
'wp_dropdown_languages' => array('dropdown_languages', 'UI', 'ShrinkPress\\I18N'),
'before_last_bar' => array('before_last_bar', 'UI', 'ShrinkPress\\I18N'),
'translate_user_role' => array('translate_user_role', 'UI', 'ShrinkPress\\I18N'),
'wp_get_pomo_file_data' => array('get_file_data', 'PoMo', 'ShrinkPress\\I18N'),
'wp_get_installed_translations' => array('get_installed_translations', 'PoMo', 'ShrinkPress\\I18N'),
'get_available_languages' => array('get_available_languages', 'PoMo', 'ShrinkPress\\I18N'),
'_get_path_to_translation_from_lang_dir' => array('_get_path_to_translation_from_lang_dir', 'PoMo', 'ShrinkPress\\I18N'),
'_get_path_to_translation' => array('_get_path_to_translation', 'PoMo', 'ShrinkPress\\I18N'),
'load_script_translations' => array('load_script_translations', 'PoMo', 'ShrinkPress\\I18N'),
);
}
<file_sep>/git.php
<?php
class shrinkpress_git
{
const source_repo = '<EMAIL>:WordPress/WordPress';
const source_folder = 'wordpress/';
const reduced_repo = '<EMAIL>:shrinkpress/reduced.git';
const reduced_folder = 'reduced/';
function __construct(array $argv)
{
array_shift($argv);
$cmd = array_shift($argv);
switch($cmd)
{
case 'source':
$this->source( $argv );
break;
case 'reduced':
$this->reduced( $argv );
break;
case 'export':
$this->export( $argv );
break;
default:
echo "[!] Unknown command\n";
break;
}
}
protected function shell($cmd)
{
echo "> {$cmd}\n";
shell_exec($cmd);
}
protected function source(array $argv)
{
$folder = __DIR__ . '/' . self::source_folder;
$cmd = 'git clone ' . self::source_repo . '.git '
. escapeshellcmd($folder);
$this->shell($cmd);
$wp_config = __DIR__ . '/source/wp-config.php';
if (file_exists($wp_config))
{
copy($wp_config, $folder . '/wp-config.php');
}
chdir($folder);
$this->shell( 'git pull' );
}
protected function reduced(array $argv)
{
$folder = __DIR__ . '/' . self::reduced_folder;
$cmd = 'git clone ' . self::reduced_repo . '.git '
. escapeshellcmd($folder);
$this->shell($cmd);
chdir($folder);
$this->shell( 'git pull' );
}
protected function export(array $argv)
{
$tag = array_shift($argv);
if (!$tag)
{
die("[!] No tag\n");
}
$source = __DIR__ . '/' . self::source_folder;
$reduced = __DIR__ . '/' . self::reduced_folder;
chdir($source);
$this->shell('git checkout ' . $tag);
chdir($reduced);
$this->shell('git branch from-' . $tag);
$this->shell('git push --set-upstream origin from-' . $tag);
$this->shell('git checkout from-' . $tag);
$this->shell('rm -rf *.html *.txt *.php wp-admin/ wp-content/ wp-includes/');
$this->shell('cp -R ' . $source . '* .');
$this->shell('git add *');
$this->shell('git add .gitignore');
$this->shell('git commit -m "Exporting from ' . $tag . '"');
}
}
new shrinkpress_git($argv);
<file_sep>/src/Git.php
<?php
namespace ShrinkPress\Evolve;
class Git
{
static function checkout()
{
shell_exec('git checkout -- .');
}
static function commit($msg)
{
Linter::all();
echo "Git: {$msg}\n";
}
static function dotGit()
{
// .gitignore
//
file_put_contents(
'.gitignore',
join("\n", array(
'/composer.lock',
'/wp-config.php',
)
));
self::commit('Adding .gitignore');
// .gitattributes
//
;
}
}
<file_sep>/src/ScanGlobals.php
<?php
namespace ShrinkPress\Evolve;
use PhpParser\Node;
class ScanGlobals
{
protected $parser;
protected $hasGlobals;
function __construct(Parse $parser)
{
$this->parser = $parser;
$this->hasGlobals = new HasGlobalsStatements;
$this->hasGlobals->pushNode = true;
$this->hasGlobals->exitOnFirstMatch = false;
foreach (HasInside::$has['globals'] as $global => $files)
{
$this->replaceGlobal($global, $files);
}
}
function replaceGlobal($global, array $files)
{
echo "G {$global}, ", count($files), " files\n";
$g = array(
'global' => $global,
// hack to group all statements
// point to the same class
//
'filename' => "wordpress/{$global}.php",
);
if (!$m = Reframe::getGlobal($g))
{
echo "MISSING REFRAME ", json_encode($g), "\n";
return false;
}
print_r($g);
print_r($m);
Move::moveGlobalStatement($g, $m);
Git::commit("\${$g['global']} moved to {$m['full']}");
foreach ($files as $filename => $occurences)
{
$code = file_get_contents( $filename );
$nodes = $this->parser->parse($code);
$nodes = $this->parser->traverse($this->hasGlobals, $nodes);
if (!$nodes)
{
echo "(0) {$filename}\n";
return false;
}
foreach ($nodes as $node)
{
$g = $this->extractStatement($node);
if ($global != $g['global'])
{
continue;
}
$g['filename'] = $filename;
$code = $this->replaceGlobalStatement($g, $m, $code);
CsvLog::append('globals.csv', array(
$global,
$m['full'],
$filename . ':' . $node->getStartLine()
));
}
}
Git::commit("{$g['global']}() replaced with {$m['full']}()");
}
function extractStatement(Node $node)
{
$f = array(
'global' => (string) $node->name,
'startLine' => $node->getStartLine(),
'endLine' => $node->getEndLine(),
'docCommentLine' => 0,
);
if ($docComment = $node->getDocComment())
{
$f['docCommentLine'] = $docComment->getLine();
}
return $f;
}
function replaceGlobalStatement(array $g, array $m, $code)
{
$lines = explode("\n", $code);
$line = $lines[ $g['startLine']-1 ];
$tokens = token_get_all('<?php ' . trim($line));
array_shift($tokens);
$seek = '$' . $g['global'];
$modified = array();
foreach ($tokens as $token)
{
if (!empty($token[0]))
{
if (382 == $token[0])
{
continue;
}
if (320 == $token[0])
{
if ($seek == $token[1])
{
continue;
}
}
}
$oken = is_scalar($token) ? $token : $token[1];
$modified[] = $oken;
}
if (array('global', ';') == $modified)
{
$modified = array();
}
$modified[] = "{$seek} = {$m['class']}::\${$m['global']};\n";
$lines[ $g['startLine']-1 ] = join(' ', $modified);
$code = join("\n", $lines);
$code = Code::addUse($code, $m['namespace'], $m['class']);
return $code;
}
}
<file_sep>/src/ComposerPhar.php
<?php
namespace ShrinkPress\Evolve;
class ComposerPhar
{
const url = 'https://getcomposer.org/composer.phar';
static function get()
{
$local = __DIR__ . '/../composer.phar';
if (!file_exists($local))
{
shell_exec(
'curl -s ' . self::url
. ' -O ' . escapeshellcmd($local)
);
if (!file_exists($local))
{
throw new \RuntimeException(
'Unable to download composer.phar'
);
}
}
return realpath($local);
}
static function dumpautoload()
{
$composer_phar = self::get();
shell_exec(
'php ' . escapeshellcmd($composer_phar) . ' dumpautoload'
);
}
}
<file_sep>/src/HasGlobalsStatements.php
<?php
namespace ShrinkPress\Evolve;
use PhpParser\Node;
class HasGlobalsStatements extends VisitorAbstract
{
public $pushNode = false;
protected $is_global = false;
function enterNode(Node $node)
{
if ($node instanceof Node\Stmt\Global_)
{
$this->is_global = true;
}
}
function leaveNode(Node $node)
{
if ($node instanceof Node\Stmt\Global_)
{
$this->is_global = false;
}
if ($this->is_global)
{
if ($node instanceof Node\Expr\Variable)
{
$globalName = (string) $node->name;
if (!in_array($globalName, HasSuperGlobals::ignore))
{
$this->push(
$this->pushNode
? $node
: $globalName
);
}
}
}
}
}
<file_sep>/src/HasHooks.php
<?php
namespace ShrinkPress\Evolve;
use PhpParser\Node;
class HasHooks extends VisitorAbstract
{
const callback_functions = array(
'add_filter' => 1,
'has_filter' => 1,
'remove_filter' => 1,
'add_action' => 1,
'has_action' => 1,
'remove_action' => 1,
);
function leaveNode(Node $node)
{
if (!$node instanceof Node\Expr\FuncCall)
{
return;
}
if (!$node->name instanceOf Node\Name)
{
return;
}
$caller = $node->name->__toString();
if (empty(self::callback_functions[ $caller ]))
{
return;
}
$arg_pos = self::callback_functions[ $caller ];
if (empty($node->args[ $arg_pos ]))
{
return;
}
if (!$node->args[ $arg_pos ]->value instanceof Node\Scalar\String_)
{
return;
}
$callback = $node->args[ $arg_pos ]->value->value;
if (Core::isCoreFunction($callback))
{
return;
}
return $this->push($callback);
}
}
<file_sep>/src/Move.php
<?php
namespace ShrinkPress\Evolve;
class Move
{
static function classNameToFilename($fullClassName)
{
$c = explode('\\', $fullClassName);
$topLevel = array_shift($c);
$library = array_shift($c);
$filename = Composer::vendors
. '/' . strtolower($topLevel)
. '/' . strtolower($library)
. '/src/' . join('/', $c) . '.php';
return $filename;
}
static function createClass(array $s, $classFilename)
{
if (file_exists($classFilename))
{
throw new \RuntimeException(
'Class file already exists: '
. $classFilename
);
}
if (!file_exists($dir = dirname($classFilename)))
{
mkdir($dir, 02777, true);
}
$code = array(
'<?php ',
'',
'namespace ' . $s['namespace'] . ';',
'',
'class ' . $s['class'],
'{',
'}',
''
);
file_put_contents($classFilename, join("\n", $code));
$d = explode('/src/', $dir);
Composer::addPsr4($s['namespace'], $d['0']);
Composer::updateComposer();
}
static function moveFunction(array $f, array $m)
{
$fullClassName = $m['namespace'] . '\\' . $m['class'];
$classFilename = self::classNameToFilename($fullClassName);
if (!file_exists($classFilename))
{
self::createClass($m, $classFilename);
}
$renamed = Code::renameMethod($f['code'], $f['function'], $m['method']);
self::insertMethod(
(!empty($f['docComment'])
? $f['docComment']
: '') . $renamed,
$classFilename);
}
static function insertMethod($methodCode, $classFilename)
{
if (!file_exists($classFilename))
{
throw new \InvalidArgumentException(
'Class file not found: '
. $classFilename
);
}
$code = file_get_contents($classFilename);
$methodCode = Code::tabify($methodCode);
$className = pathinfo($classFilename, PATHINFO_FILENAME);
$code = Code::injectCode($code,
array('class', $className, '{'),
"\n" . $methodCode . "\n"
);
file_put_contents($classFilename, $code);
}
static function moveGlobalStatement(array $g, array $m)
{
$fullClassName = $m['namespace'] . '\\' . $m['class'];
$classFilename = self::classNameToFilename($fullClassName);
if (!file_exists($classFilename))
{
self::createClass($m, $classFilename);
}
$code = file_get_contents( $classFilename );
$code = Code::injectCode(
$code,
array('class', $m['class'], '{'),
"\n\tstatic \${$m['global']};\n"
);
file_put_contents($classFilename, $code);
}
}
<file_sep>/src/Code.php
<?php
namespace ShrinkPress\Evolve;
class Code
{
static function tabify($code)
{
$code = str_replace("\n", "\n\t" , $code);
$code = "\t" . rtrim($code, "\t");
return $code;
}
static function extractByLines($code, $fromLine, $toLine)
{
$lines = explode("\n", $code);
$total = count($lines);
if ($fromLine > $total || $fromLine < 1)
{
throw new \InvalidArgumentException(
"Invalid \$fromLine {$fromLine}, total number of lines is {$total} "
);
}
if ($toLine > $total || $toLine < 1)
{
throw new \InvalidArgumentException(
"Invalid \$toLine {$toLine}, total number of lines is {$total} "
);
}
$found = '';
for ($i = $fromLine; $i < $toLine+1; $i++)
{
$found .= $lines[ $i - 1 ] . "\n";
unset($lines[ $i - 1 ]);
}
return array($found, join("\n", $lines));
}
static function extractDefinition(&$code, array $e)
{
$c = self::extractByLines($code, $e['startLine'], $e['endLine']);
$e['code'] = $c[0];
$code = $c[1];
if ($e['docCommentLine'])
{
$b = self::extractByLines($code,
$e['docCommentLine'], $e['startLine']-1);
$e['docComment'] = $b[0];
$code = $b[1];
}
return $e;
}
static function injectCode($code, array $seek, $inject)
{
$tokens = token_get_all($code);
$modified = array();
$last = array();
foreach ($tokens as $token)
{
$oken = is_scalar($token) ? $token : $token[1];
$modified[] = $oken;
// skip T_WHITESPACE
//
if (382 == $token[0])
{
continue;
}
array_push($last, $oken);
if (count($last) > count($seek))
{
array_shift($last);
}
if ($seek == $last)
{
$modified[] = $inject;
}
}
return join('', $modified);
}
static function renameMethod($code, $from, $to)
{
if ($from == $to)
{
return $code;
}
$tokens = token_get_all( '<?php ' . $code);
array_shift($tokens);
$code = '';
$seek = array( 'function', (string) $from );
$last = array();
foreach ($tokens as $i => $token)
{
$oken = is_scalar($token) ? $token : $token[1];
// ignore whitespace
//
if (382 != $token[0])
{
array_push($last, $oken);
if (count($last) > count($seek))
{
array_shift($last);
}
}
if ($seek == $last)
{
$oken = (string) $to;
}
$code .= $oken;
}
return $code;
}
static function addUse($code, $classOrNamespace, $as = '')
{
$seek = array(379, 378, 382);
$tokens = token_get_all($code);
$modified = array();
$last = array();
foreach ($tokens as $i => $token)
{
$oken = is_scalar($token) ? $token : $token[1];
$modified[] = $oken;
array_push($last, $token[0]);
if (count($last) > count($seek))
{
array_shift($last);
}
if ($seek == $last)
{
$space = array_pop($modified);
$modified[] = "\n" . 'use '
. $classOrNamespace
. ($as ? " as {$as}" : '')
. ';';
$modified[] = $space;
}
}
return join('', $modified);
}
static function replaceHook($code, $function, $method)
{
$tokens = token_get_all( '<?php ' . $code);
array_shift($tokens);
$modified = array();
foreach ($tokens as $i => $token)
{
$oken = is_scalar($token) ? $token : $token[1];
if (323 == $token[0])
{
if ($oken == "'{$function}'")
{
$oken = "'{$method}'";
} else
if ($oken == "\"{$function}\"")
{
$oken = "\"{$method}\"";
}
}
$modified[] = $oken;
}
return join('', $modified);
}
static function replaceCall($code, $function, $method)
{
$tokens = token_get_all( '<?php ' . $code);
array_shift($tokens);
$modified = array();
foreach ($tokens as $i => $token)
{
$oken = is_scalar($token) ? $token : $token[1];
if (319 == $token[0])
{
if ($function == $oken)
{
$oken = $method;
}
}
$modified[] = $oken;
}
return join('', $modified);
}
}
<file_sep>/src/ReplaceCalls.php
<?php
namespace ShrinkPress\Evolve;
use PhpParser\Node;
use PhpParser\NodeVisitorAbstract;
class ReplaceCalls extends NodeVisitorAbstract
{
public $find = '';
function __construct($find)
{
$this->find = (string) $find;
}
public $result = array();
function beforeTraverse(array $nodes)
{
$this->result = array();
}
function leaveNode(Node $node)
{
if (!$node instanceof Node\Expr\FuncCall)
{
return;
}
if (!$node->name instanceOf Node\Name)
{
return;
}
$functionName = (string) $node->name;
if ($this->find != $functionName)
{
return;
}
$this->result[] = $node->getLine();
}
function afterTraverse(array $nodes)
{
rsort($this->result);
}
}
<file_sep>/src/FindFunction.php
<?php
namespace ShrinkPress\Evolve;
use PhpParser\Node;
use PhpParser\NodeVisitorAbstract;
class FindFunction extends NodeVisitorAbstract
{
public $result = array();
function beforeTraverse(array $nodes)
{
$this->result = array();
}
function leaveNode(Node $node)
{
if (!$node instanceof Node\Stmt\Function_)
{
return;
}
$this->result[] = $node;
}
function extract(Node $node)
{
$f = array(
'function' => (string) $node->name,
'startLine' => $node->getStartLine(),
'endLine' => $node->getEndLine(),
'docCommentLine' => 0,
);
if ($docComment = $node->getDocComment())
{
$f['docCommentLine'] = $docComment->getLine();
}
return $f;
}
}
<file_sep>/src/Composer.php
<?php
namespace ShrinkPress\Evolve;
class Composer
{
const vendors = 'shrinkpress-vendors';
const source = array(
'name' => 'shrinkpress/shrinkpress',
'description' => 'ShrinkPress: Break WordPress Apart',
'type' => 'project',
'license' => 'GPL-2.0-or-later',
'require' => array(
'php' => '>=7.0.0',
),
'config' => array(
'vendor-dir' => self::vendors,
),
'autoload' => array(
'psr-4' => array(),
),
);
static $psr4 = array();
static function addPsr4($namespace, $folder)
{
if ($ns = rtrim($namespace, '\\'))
{
$namespace = $ns . '\\';
}
self::$psr4[ $namespace ] = $folder;
}
static function updateComposer()
{
$data = self::source;
$data['autoload']['psr-4'] = (object) self::$psr4;
// not changed since last update ?
//
static $last;
if (!empty($last) && $last == $data)
{
// return false;
}
$last = $data;
file_put_contents(
'composer.json',
json_encode(
$data,
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
));
ComposerPhar::dumpautoload();
return true;
}
static function plantComposer()
{
self::updateComposer();
$code = file_get_contents('wp-settings.php');
$code = Code::injectCode($code, array(
'define', '(', "'WPINC'", ',', "'wp-includes'", ')', ';'
), join("\n", array(
'',
'',
'/** @see shrinkpress */',
'require ABSPATH . \'/'
. self::vendors
. '/autoload.php\';',
)));
file_put_contents('wp-settings.php', $code);
}
static function wipeComposer()
{
shell_exec('rm composer.json');
shell_exec('rm -rf ' . self::vendors);
}
}
<file_sep>/src/CsvLog.php
<?php
namespace ShrinkPress\Evolve;
class CsvLog
{
static function clean($filename)
{
if (!file_exists($filename))
{
return false;
}
return unlink($filename);
}
static function append($filename, array $data)
{
$fp = fopen($filename, 'a+');
fputcsv($fp, $data);
fclose($fp);
}
}
|
3aa5e7b591f4d8e157c6c1826f0280eb54e78891
|
[
"Markdown",
"PHP"
] | 32
|
PHP
|
kktsvetkov/ShrinkPress
|
4bbec20c3ccd1055f8653995db0524090f832b9a
|
662577c7cc4a9b8243a7d5ff69cb0fdb191001df
|
refs/heads/master
|
<repo_name>roccosta/automacao<file_sep>/login_wifi/login_wifi/features/step_definitions/login_wifi.rb
Dado(/^que eu acesse a url de login$/) do
visit('https://guest.santander.com.br/sites/SANTANDER/wlc_login.html?switch_url=https://1.1.1.3/login.html&ap_mac=18:8b:9d:69:a0:f0&client_mac=ac:bc:32:b2:58:03&wlan=GSBPARTNER&redirect=https://www.apple.com/br/')
end
Quando(/^eu preencher o campo de email$/) do
fill_in('username', :with => '<EMAIL>')
end
Quando(/^preencher a senha$/) do
fill_in('password', :with => '<PASSWORD>')
end
Quando(/^clicar no botão submit$/) do
click_on('Submit')
end
#Então(/^devo visualizar a tela de sucesso no login$/) do3
# binding.pry
# pending # Write code here that turns the phrase above into concrete actions
#end<file_sep>/SantanderSite-master/SantanderSitePrism/features/pages/search_agency.rb
class SearchAgencyNear < SitePrism::Section
element :nearTab, "#OpcaoBuscaAgenProxima"
element :cep, "#refCep"
element :search, :css,"#BuscaAgenProximaForm > ul.botoes > li.alignR > a > img"
element :address, "#refEndereco"
end
class SearchAgencyNeighborhood < SitePrism::Section
element :neighborhoodTab, "#OpcaoBuscaAgenBairro"
element :selectState, "#localizacaoEstado"
element :selectCity, "#localizacaoCidade"
element :selectNeighborhood, "#localizacaoBairro"
element :search, :css,"#BuscaAgenBairro > table > tbody > tr > td > ul.botoes > li.alignR > a > img"
end
class SearchAgencyNumber < SitePrism::Section
element :numberTab, "#OpcaoBuscaAgenNumero"
element :agencyNumber, "#txNumeroAgencia"
element :search, :css,"#BuscaAgenNumero > table > tbody > tr > td > ul > li.alignR > a > img"
end
class SearchAgencyRoute < SitePrism::Section
element :routeTab, "#OpcaoBuscaAgenRota"
element :cepOrigin, "#refCepOrigem"
element :cepDestiny, "#refCepDestino"
element :addressOrigin, "#refEnderecoOrigem"
element :addressDestiny, "#refEnderecoDestino"
element :searchOrigin, :css,"#BuscaAgenRotaOrigemForm > ul.botoes > li.alignR > a > img"
element :searchDestiny, :css,"#BuscaAgenRotaDestinoForm > ul.botoes > li.alignR > a > img"
element :searchWay, :css, "#BuscaAgenRotaOK > ul > li > a > img"
end
class SearchAgency < SitePrism::Page
section :near, SearchAgencyNear, "#ctBuscaAgencia"
section :neighborhood, SearchAgencyNeighborhood, '#ctBuscaAgencia'
section :number, SearchAgencyNumber, '#ctBuscaAgencia'
section :route, SearchAgencyRoute, '#ctBuscaAgencia'
element :iframe, "iframe"
end
<file_sep>/SantanderSite-master/SantanderSitePrism/features/pages/app.rb
#Page-Factory Pattern
class App
def home
Home.new
end
def agency
Agency.new
end
def searchAgency
SearchAgency.new
end
end
<file_sep>/SantanderSite-master/Santander/features/pages/home.rb
class Home
include Capybara::DSL
def url
visit "http://www.santander.com.br"
end
end
<file_sep>/SantanderSite-master/SantanderSitePrism/features/step_definitions/agency_steps.rb
Quando(/^eu buscar agência pelo CEP$/) do
@app.agency.click_something("Agência")
@app.agency.click_something("Clique aqui")
@app.agency.last_window
within_frame(@app.searchAgency.iframe) do
@app.searchAgency.near.cep.set ADDRESS['NEAR']['CEP']
@app.searchAgency.near.search.click
@app.searchAgency.near.address.select(ADDRESS['NEAR']['ADDRESS'])
end
end
Quando(/^eu buscar agência no bairro$/) do
@app.agency.click_something("Agência")
@app.agency.click_something("Clique aqui")
@app.agency.last_window
within_frame(@app.searchAgency.iframe) do
@app.searchAgency.neighborhood.neighborhoodTab.click
@app.searchAgency.neighborhood.selectState.select(ADDRESS['NEIGHBORHOOD']['STATE'])
@app.searchAgency.neighborhood.selectCity.select(ADDRESS['NEIGHBORHOOD']['CITY'])
@app.searchAgency.neighborhood.selectNeighborhood.select(ADDRESS['NEIGHBORHOOD']['NEIGHBORHOOD'])
@app.searchAgency.neighborhood.search.click
end
end
Quando(/^eu buscar agência pelo número$/) do
@app.agency.click_something("Agência")
@app.agency.click_something("Clique aqui")
@app.agency.last_window
within_frame(@app.searchAgency.iframe) do
@app.searchAgency.number.numberTab.click
@app.searchAgency.number.agencyNumber.set ADDRESS['NUMBER']['AGENCY_NUMBER']
@app.searchAgency.number.search.click
end
end
Quando(/^eu buscar agência pela rota de origem e rota de destino$/) do
@app.agency.click_something("Agência")
@app.agency.click_something("Clique aqui")
@app.agency.last_window
within_frame(@app.searchAgency.iframe) do
@app.searchAgency.route.routeTab.click
@app.searchAgency.route.cepOrigin.set ADDRESS['ROUTE']['CEP_ORIGIN']
sleep 1
@app.searchAgency.route.searchOrigin.click
@app.searchAgency.route.addressOrigin.select ADDRESS['ROUTE']['ADDRESS_ORIGIN']
@app.searchAgency.route.cepDestiny.set ADDRESS['ROUTE']['CEP_DESTINY']
sleep 1
@app.searchAgency.route.searchDestiny.click
@app.searchAgency.route.addressDestiny.select ADDRESS['ROUTE']['ADDRESS_DESTINY']
@app.searchAgency.route.searchWay.click
end
end
Então(/^aparecerá as agências disponíveis do CEP$/) do
page.has_content?(ADDRESS['NEAR']['VERIFY_AGENCY'])
end
Então(/^aparecerá as agências disponíveis do bairro$/) do
page.has_content?(ADDRESS['NEIGHBORHOOD']['VERIFY_AGENCY'])
end
Então(/^aparecerá a agência solicitada$/) do
page.has_content?(ADDRESS['NUMBER']['VERIFY_AGENCY'])
end
Então(/^aparecerá as agências disponíveis no caminho entre as rotas$/) do
page.has_content?(ADDRESS['ROUTE']['VERIFY_AGENCY'])
end
<file_sep>/praticando_1512/features/step_definitions/steps.rb
Dado(/^que eu acesse o facebook$/) do
visit('https://www.facebook.com/')
end
Quando(/^eu preencher os campos de cadastro$/) do
# binding.pry
@email1 = FFaker::Internet.email
@fname = FFaker::Name.first_name
@lname = FFaker::Name.last_name
@pass = <PASSWORD>.password
@bday = Faker::Date.birthday(18,200).strftime("%d/%m/%Y")
fill_in('firstname', :with => @fname)
fill_in('lastname', :with => @lname)
fill_in('reg_email__', :with => @email1)
fill_in('reg_email_confirmation__', :with => @email1)
fill_in('reg_passwd__', :with => <PASSWORD>)
select('23', :from => 'birthday_day')
select('Fev', :from => 'birthday_month')
select('1986', :from => 'birthday_year')
choose('u_0_i')
end
Quando(/^clicar em Abrir uma conta$/) do
click_button('u_0_e')
end
Então(/^primeiro cadastro completo$/) do
sleep(15)
end
=begin
@bday = Faker::Date.birthday(18,65)
strftime("%d/%m/%Y")
=end<file_sep>/dojo2/features/step_definitions/questionario.rb
Dado(/^que eu acesse o Questionário$/) do
@start = Home.new
@start.home.load
end
Quando(/^eu preencher o nome com "([^"]*)"$/) do |nome|
# binding.pry
@start.proxima.botao.click
@start.formulario.nome.set nome
end
Quando(/^preencher o email com "([^"]*)"$/) do |email|
@start.formulario.email.set email
end
Quando(/^preencher os demais campos$/) do
@start.formulario.radio_button_1
@start.formulario.checkbox_filmes
@start.formulario.personagem.set Faker::StarWars.character
@start.formulario.seta.click
@start.formulario.radio_button_2
end
Quando(/^clicar no botão de enviar$/) do
sleep(1)
@start.formulario.enviar.click
end
Então(/^devo visualizar uma confirmação de envio$/) do
expect(page.has_content?('Obrigado por responder as perguntas!')).to be true
sleep(2)
end<file_sep>/SantanderSite-master/SantanderSitePrism/features/step_definitions/home_steps.rb
Dado(/^que eu esteja na home do site Santander$/) do
@app = App.new
@app.home.load
end
<file_sep>/santander_siteprism/features/step_definitions/steps1.rb
Quando(/^eu preencher o campo de cpf$/) do
@app.classes.frmlgn.cpf.set LOGIN['LOGIN']['CPF']
end
Quando(/^clicar no botão ok$/) do
@app.classes.frmlgn.btnok.click
end
Quando(/^eu preencher o campo de senha$/) do
@app.classes2.iframeP do |frame1|
@app.classes2.iframeM do |frame2|
frame2.rml.click
end
end
@app.classes2.iframeP do |frame1|
@app.classes2.iframeM do |frame2|
frame2.txtSenha.set LOGIN['LOGIN']['SENHA']
end
end
end
Quando(/^clicar no botão continuar$/) do
@app.classes2.iframeP do |frame1|
@app.classes2.iframeM do |frame2|
frame2.btnconf.click
end
end
end
Então(/^confirmo que estou logado no Internet Banking$/) do
expect(page.has_content?(LOGIN['CHECK']['VERIFY_CONTENT'])).to be true
sleep(15)
end<file_sep>/SantanderSite-master/SantanderSitePrism/features/pages/agency.rb
class Agency < SitePrism::Page
def last_window
page.driver.browser.switch_to.window(page.driver.browser.window_handles.last)
end
def click_something(link)
click_link(link)
end
end
<file_sep>/santander_siteprism/features/pages/classes.rb
class Loginib < SitePrism::Section
element :cpf, "#cfp"
element :btnok, "#formularioFisica > fieldset > ul > li.logBRsub > input"
end
class TelaSenha < SitePrism::Page
element :rml, '#splash-10000-remind-me-later'
element :txtSenha, '#txtSenha'
element :btnconf, '#divBotoes > a.botaoVermelho.floatRight'
end
class FrameLogin < SitePrism::Page
section :frmlgn, Loginib, '#panel1'
end
class FrameLogin2 < SitePrism::Page
iframe :iframeP, TelaSenha, '#Principal'
iframe :iframeM, TelaSenha, '#MainFrame'
end
class FrameLogin3 < SitePrism::Page
element :txt, 'Principais Transações'
end<file_sep>/SantanderSite-master/Santander/features/pages/agency.rb
class Agency
include Capybara::DSL
def last_window
page.driver.browser.switch_to.window(page.driver.browser.window_handles.last)
end
def click_something(link)
click_link(link)
end
def click_search_postalcode
within_frame(find("iframe")) do
find(:css,'#BuscaAgenProximaForm > ul.botoes > li.alignR > a > img').click
end
end
def click_search_neighborhood
within_frame(find("iframe")) do
find(:css,'#BuscaAgenBairro > table > tbody > tr > td > ul.botoes > li.alignR > a > img').click
end
end
def click_search_agencyNumber
within_frame(find("iframe")) do
find(:css,'#BuscaAgenNumero > table > tbody > tr > td > ul > li.alignR > a > img').click
end
end
def click_search_agencyOrigin
within_frame(find("iframe")) do
find(:css,'#BuscaAgenRotaOrigemForm > ul.botoes > li.alignR > a > img').click
end
end
def click_search_agencyDestiny
within_frame(find("iframe")) do
find(:css,'#BuscaAgenRotaDestinoForm > ul.botoes > li.alignR > a > img').click
end
end
def click_search_agencyRoute
within_frame(find("iframe")) do
find(:css,'#BuscaAgenRotaOK > ul > li > a > img').click
end
end
def click_agency_neighborhood
last_window
within_frame(find("iframe")) do
find("#OpcaoBuscaAgenBairro").click
end
end
def click_agency_number
last_window
within_frame(find("iframe")) do
find("#OpcaoBuscaAgenNumero").click
end
end
def click_agency_route
last_window
within_frame(find("iframe")) do
find("#OpcaoBuscaAgenRota").click
end
end
def fill_cep
last_window
within_frame(find("iframe")) do
fill_in "refCep", :with => "04534011"
end
end
def fill_cep_origin
last_window
within_frame(find("iframe")) do
fill_in "refCepOrigem", :with => "04534011"
end
end
def fill_cep_destiny
last_window
within_frame(find("iframe")) do
fill_in "refCepDestino", :with => "03582040"
end
end
def fill_agency_number
last_window
within_frame(find("iframe")) do
fill_in "txNumeroAgencia", :with => "1174"
end
end
def select_address
within_frame(find("iframe")) do
find('#refEndereco').find(:xpath,'option[2]').select_option
end
end
def select_address_origin
within_frame(find("iframe")) do
find('#refEnderecoOrigem').find(:xpath,'option[2]').select_option
end
end
def select_address_destiny
within_frame(find("iframe")) do
find('#refEnderecoDestino').find(:xpath,'option[2]').select_option
end
end
def select_data
within_frame(find("iframe")) do
find('#localizacaoEstado').find(:xpath,'option[2]').select_option
find('#localizacaoCidade').find(:xpath,'option[2]').select_option
find('#localizacaoBairro').find(:xpath,'option[2]').select_option
end
end
def verify_content_postalcode
page.has_content?('1744 - SELECT ITAIM BIBI-SP')
end
def verify_content_neighborhood
page.has_content?('1556 - BOSQUE-RIO BRANCO-AC')
end
def verify_content_agencyNumber
page.has_content?('1174 - SANTO ANGELO - RS')
end
def verify_content_agencyRoute
page.has_content?('1744 - SELECT ITAIM BIBI-SP')
end
end
<file_sep>/Praticando_Santander/features/step_definitions/steps1.rb
Dado(/^que eu acesse o Internet Banking do Santander$/) do
visit('https://www.santander.com.br/')
end
Quando(/^eu preencher o campo de cpf$/) do
fill_in('txtCPF', :with => '35476510850')
end
Quando(/^clicar no botão ok$/) do
find("#formularioFisica > fieldset > ul > li.logBRsub > input").click
end
Quando(/^eu preencher o campo de senha$/) do
binding.pry
within_frame('Principal') do
within_frame('MainFrame') do
# binding.pry
click_link('Lembrar mais tarde')
end
end
within_frame('Principal') do
within_frame('MainFrame') do
fill_in('txtSenha', :with => '<PASSWORD>')
end
end
end
Quando(/^clicar no botão continuar$/) do
within_frame('Principal') do
within_frame('MainFrame') do
find(:xpath, "//*[@id='divBotoes']/a[1]").click
end
end
end
Então(/^confirmo que estou logado no Internet Banking$/) do
if page.should have_content('Principais Transações') == true
puts " Estava no site do Santander"
else
puts " Não estava no site do Santander"
end
sleep(15)
end<file_sep>/SantanderSite-master/SantanderSitePrism/features/support/env.rb
require 'rspec'
require 'yaml'
require 'selenium/webdriver'
require 'capybara/dsl'
require 'pry'
require 'report_builder'
require 'site_prism'
include Capybara::DSL
ENVIRONMENT = (YAML.load_file('./features/config/environment.yml'))
ADDRESS = (YAML.load_file('./features/fixtures/address.yml'))
Capybara.register_driver :selenium do |app|
Capybara::Selenium::Driver.new(app, :browser => :chrome)
end
Capybara.configure do |config|
config.current_driver = :selenium
config.default_max_wait_time = 3
window = Capybara.current_session.driver.browser.manage.window
window.resize_to(1280, 840)
# Capybara.page.driver.browser.manage.window.maximize
end
ReportBuilder.configure do |config|
config.json_path = 'cucumber_sample/logs'
config.report_path = 'my_test_report'
config.report_types = [:json, :html]
config.report_tabs = [:overview, :features, :scenarios, :errors]
config.report_title = 'My Test Results'
config.compress_images = false
config.additional_info = {browser: 'Chrome', environment: 'Production'}
end
<file_sep>/SantanderSite-master/Santander/features/step_definitions/home_steps.rb
Dado(/^que eu estou na home do site Santander$/) do
Home.new.url
end<file_sep>/README.md
# automacao
Projetos de Automação
<file_sep>/form_siteprism/cadastramento_steps.rb
Dado(/^que estou na lista de alunos$/) do
element_exists("* text:'Agenda'")
end
Quando(/^eu clicar no botao de adicionar aluno$/) do
touch("* id:'novo_aluno'")
end
Quando(/^preencher o nome$/) do
query("* formulario_nome")
keyboard_enter_text("<NAME>");
end
Quando(/^preencher o endereco$/) do
query("* formulario_endereco")
keyboard_enter_text("<NAME>, 195");
end
Quando(/^preencher o telefone$/) do
query("* formulario_telefone")
keyboard_enter_text("+5511947370009");
end
Quando(/^preencher o site$/) do
query("* formulario_site")
keyboard_enter_text("www.google.com.br");
end
Quando(/^preencher a nota$/) do
query("* id:'formulario_nota'", setProgress:5);
end
Quando(/^tirar uma foto do aluno$/) do
sleep(5)
# touch("* id:'formulario_botao_foto'")
end
Quando(/^clicar no botao de confirmar$/) do
touch("* id:'menu_formulario_ok'")
end
Entao(/^devo ver o aluno cadastrado na lista principal$/) do
sleep(15)
end
=begin
clicar em botao
touch("* id:'btnCalcular'")
preencher campo texto
query("* id:'txtLado1'", setText:"3")
enter_text "* id:'txtLado1'", "3"
existencia de elemento
element_exists("* text:’texto'")
query("* id:'formulario_botao_foto'",
id do botao de novo aluno novo_aluno
query("* id:'formulario_nota'",
=end<file_sep>/santander_siteprism/features/pages/app.rb
#Page-Factory Pattern
class App
def home
Home.new
end
def classes
FrameLogin.new
end
def classes2
FrameLogin2.new
end
def classes3
FrameLogin3.new
end
end<file_sep>/santander_siteprism/features/step_definitions/home.rb
Dado(/^que eu acesse o Internet Banking do Santander$/) do
@app = App.new
@app.home.load
end<file_sep>/SantanderSite-master/Santander/features/step_definitions/agency_steps.rb
Quando(/^eu clicar no menu inferior Agências$/) do
Agency.new.click_something("Agência")
end
Quando(/^clicar no link "([^"]*)"$/) do |link|
Agency.new.click_something(link)
end
Quando(/^preencher o campo CEP$/) do
Agency.new.fill_cep
sleep 2
end
Quando(/^preencher o CEP de origem$/) do
Agency.new.fill_cep_origin
sleep 2
end
Quando(/^preencher o CEP de destino$/) do
Agency.new.fill_cep_destiny
sleep 2
end
Quando(/^clicar no botão para buscar agência pelo CEP$/) do
Agency.new.click_search_postalcode
end
Quando(/^clicar no botão para buscar agência pelo bairro$/) do
Agency.new.click_search_neighborhood
end
Quando(/^clicar no botão para buscar agência pela rota de origem$/) do
Agency.new.click_search_agencyOrigin
end
Quando(/^clicar no botão para buscar agência pela rota de destino$/) do
Agency.new.click_search_agencyDestiny
end
Quando(/^clicar no botão para buscar agências no caminho$/) do
Agency.new.click_search_agencyRoute
end
Quando(/^selecionar um endereço$/) do
Agency.new.select_address
end
Quando(/^selecionar um endereço da rota de origem$/) do
Agency.new.select_address_origin
end
Quando(/^selecionar um endereço da rota de destino$/) do
Agency.new.select_address_destiny
end
Então(/^aparecerá as agências disponíveis do CEP$/) do
Agency.new.verify_content_postalcode
end
Então(/^aparecerá as agências disponíveis do bairro$/) do
Agency.new.verify_content_neighborhood
end
Então(/^aparecerá a agência solicitada$/) do
Agency.new.verify_content_agencyNumber
end
Então(/^aparecerá as agências disponíveis no caminho entre as rotas$/) do
Agency.new.verify_content_agencyRoute
end
Quando(/^clicar na aba para buscar agência no bairro$/) do
Agency.new.click_agency_neighborhood
end
Quando(/^selecionar os dados obrigatórios$/) do
Agency.new.select_data
end
Quando(/^clicar na aba para buscar agência pelo número$/) do
Agency.new.click_agency_number
end
Quando(/^preencher os dados obrigatórios$/) do
Agency.new.fill_agency_number
end
Quando(/^clicar no botão para buscar agência pelo número$/) do
Agency.new.click_search_agencyNumber
end
Quando(/^clicar na aba para buscar agência por minha rota$/) do
Agency.new.click_agency_route
sleep 2
end
<file_sep>/form_siteprism/features/pages/start.rb
class Home < SitePrism::Page
set_url ENVIRONMENT['URL']['HOME']
def home
Home.new
end
def elementos
Objetos.new
end
end<file_sep>/SantanderSite-master/SantanderSitePrism/features/pages/home.rb
class Home < SitePrism::Page
set_url ENVIRONMENT['URL']['HOME']
end
<file_sep>/Praticando_Itau/features/step_definitions/steps1.rb
Dado(/^que eu acesse o Internet Banking do itau$/) do
visit('https://www.itau.com.br/')
end
Quando(/^eu preencher os campos de agência e conta$/) do
# Insira Agência e Conta
fill_in('campo_agencia', :with => 'AAAA')
fill_in('campo_conta', :with => 'CCCCCD')
end
Quando(/^clicar no botão acessar$/) do
find("#header>div.formLogin>div.loginBtn>a").click
end
Quando(/^eu clicar no nome do usuario$/) do
find("#MSGBordaEsq>table>tbody>tr:nth-child(3)>td>table>tbody>tr>td>table>tbody>tr>td.MSGTexto8>a").click
end
Quando(/^preencher a senha clicando nos botões$/) do
# Insira sua senha neste array
@senha = ['1','2','3','4','5','6']
@par1 = find('#TecladoFlutuanteBKL>form:nth-child(1)>table>tbody>tr:nth-child(2)>td:nth-child(2)>table:nth-child(8)>tbody>tr>td:nth-child(1)>strong').text.split("")
@par2 = find('#TecladoFlutuanteBKL>form:nth-child(1)>table>tbody>tr:nth-child(2)>td:nth-child(2)>table:nth-child(8)>tbody>tr>td:nth-child(2)>strong').text.split("")
@par3 = find('#TecladoFlutuanteBKL>form:nth-child(1)>table>tbody>tr:nth-child(2)>td:nth-child(2)>table:nth-child(8)>tbody>tr>td:nth-child(3)>strong').text.split("")
@par4 = find('#TecladoFlutuanteBKL>form:nth-child(1)>table>tbody>tr:nth-child(2)>td:nth-child(2)>table:nth-child(8)>tbody>tr>td:nth-child(4)>strong').text.split("")
@par5 = find('#TecladoFlutuanteBKL>form:nth-child(1)>table>tbody>tr:nth-child(2)>td:nth-child(2)>table:nth-child(8)>tbody>tr>td:nth-child(5)>strong').text.split("")
@senha.each do |x|
if x == @par1[0] || x == @par1[5] then
find("#TecladoFlutuanteBKL>form:nth-child(1)>table>tbody>tr:nth-child(2)>td:nth-child(2)>table:nth-child(8)>tbody>tr>td:nth-child(1)>a>img").click
end
if x == @par2[0] || x == @par2[5] then
find("#TecladoFlutuanteBKL>form:nth-child(1)>table>tbody>tr:nth-child(2)>td:nth-child(2)>table:nth-child(8)>tbody>tr>td:nth-child(2)>a>img").click
end
if x == @par3[0] || x == @par3[5] then
find("#TecladoFlutuanteBKL>form:nth-child(1)>table>tbody>tr:nth-child(2)>td:nth-child(2)>table:nth-child(8)>tbody>tr>td:nth-child(3)>a>img").click
end
if x == @par4[0] || x == @par4[5] then
find("#TecladoFlutuanteBKL>form:nth-child(1)>table>tbody>tr:nth-child(2)>td:nth-child(2)>table:nth-child(8)>tbody>tr>td:nth-child(4)>a>img").click
end
if x == @par5[0] || x == @par5[5] then
find("#TecladoFlutuanteBKL>form:nth-child(1)>table>tbody>tr:nth-child(2)>td:nth-child(2)>table:nth-child(8)>tbody>tr>td:nth-child(5)>a>img").click
end
end
end
Quando(/^clicar no botao ok$/) do
find("#TecladoFlutuanteBKL>form:nth-child(1)>table>tbody>tr:nth-child(2)>td:nth-child(2)>table:nth-child(9)>tbody>tr>td:nth-child(3)>a>img").click
end
Então(/^confirmo que estou logado no Internet Banking do Itau$/) do
if page.should have_content('Home | Conta Corrente') == true
puts " Estava no site do Itau"
else
puts " Não estava no site do Itau"
end
sleep(15)
end<file_sep>/form_siteprism/features/pages/objetos.rb
class Objetos < SitePrism::Page
element :nome, "#mG61Hd>div>div.freebirdFormviewerViewFormContent>div.freebirdFormviewerViewItemList>div:nth-child(1)>div.freebirdFormviewerViewItemsTextItemWrapper>div>div.quantumWizTextinputPaperinputMainContent.exportContent>div>div.quantumWizTextinputPaperinputInputArea>input"
element :email, "#mG61Hd>div>div.freebirdFormviewerViewFormContent>div.freebirdFormviewerViewItemList>div:nth-child(2)>div.quantumWizTextinputPapertextareaEl.modeLight.freebirdFormviewerViewItemsTextLongText.freebirdThemedInput>div.quantumWizTextinputPapertextareaMainContent.exportContent>div.quantumWizTextinputPapertextareaContentArea.exportContentArea>textarea"
element :dd1, "#mG61Hd > div > div.freebirdFormviewerViewFormContent > div.freebirdFormviewerViewItemList > div:nth-child(3) > div.quantumWizMenuPaperselectEl.docssharedWizSelectPaperselectRoot.freebirdFormviewerViewItemsSelectSelect.freebirdThemedSelectDarkerDisabled > div:nth-child(1) > div.quantumWizMenuPaperselectDropDown.exportDropDown"
element :sim1, :xpath, "//*[@id='mG61Hd']/div/div[2]/div[2]/div[3]/div[2]/div[2]/div[3]"
element :nao1, :xpath, "//*[@id='mG61Hd']/div/div[2]/div[2]/div[3]/div[2]/div[2]/div[4]"
element :dd2, "#mG61Hd > div > div.freebirdFormviewerViewFormContent > div.freebirdFormviewerViewItemList > div:nth-child(4) > div.quantumWizMenuPaperselectEl.docssharedWizSelectPaperselectRoot.freebirdFormviewerViewItemsSelectSelect.freebirdThemedSelectDarkerDisabled > div:nth-child(1) > div.quantumWizMenuPaperselectDropDown.exportDropDown"
element :sim2, :xpath, "//*[@id='mG61Hd']/div/div[2]/div[2]/div[4]/div[2]/div[2]/div[3]"
element :nao2, :xpath, "//*[@id='mG61Hd']/div/div[2]/div[2]/div[4]/div[2]/div[2]/div[4]"
element :cbs1, :xpath, "//*[@id='mG61Hd']/div/div[2]/div[2]/div[5]/div[2]/div[1]/div/label/div/div[1]/div[2]"
element :cbn1, :xpath, "//*[@id='mG61Hd']/div/div[2]/div[2]/div[5]/div[2]/div[2]/div/label/div/div[1]/div[2]"
element :cbs2, :xpath, "//*[@id='mG61Hd']/div/div[2]/div[2]/div[6]/div[2]/div[1]/div/label/div/div[1]/div[2]"
element :cbn2, :xpath, "//*[@id='mG61Hd']/div/div[2]/div[2]/div[6]/div[2]/div[2]/div/label/div/div[1]/div[2]"
element :enviar, "#mG61Hd > div > div.freebirdFormviewerViewFormContent > div.freebirdFormviewerViewNavigationNavControls > div.freebirdFormviewerViewNavigationButtonsAndProgress > div > div > content > span"
def randomize_drop_down(x)
y = "dd" + x.to_s
w = random_select = 1 + rand(2)
send(y).click
if w == 1
send('sim' + x.to_s).click
else
send('nao' + x.to_s).click
end
end
def randomize_check_box(x)
@number = Faker::Number.number(1)
if @number % 2 == 0
send('cbs' + x.to_s).click
else
send('cbn' + x.to_s).click
end
end
end<file_sep>/praticando_1612/features/step_definitions/steps.rb
Dado(/^que eu acesse o Google$/) do
visit('https://google.com.br')
end
Quando(/^pesquiso pelo site do uol$/) do
fill_in('q', :with => 'uol.com.br')
end
Quando(/^entro no link$/) do
click_link('UOL - O melhor conteúdo')
end
Então(/^confirmo que estou no site do UOL$/) do
if page.should have_content('UOL - O melhor conteúdo') == true
puts " Estava no site da UOL"
else
puts " Não estava no site da UOL"
end
end
Dado(/^que eu acesse a pagina de economia do UOL$/) do
click_link('Economia')
end
Quando(/^comparo se o valor do dolar é menor que (\d+),(\d+)$/) do |v_fix, cot|
$v_fix = "3.60"
$cot = find(:xpath, "//*[@id='cambio']/ul/li[1]/p[2]").text.last(5)
puts $v_fix
puts $cot
binding.pry
end
Então(/^finalizo a execução com uma mensagem com o resultado da comparação$/) do
expect($cot).to be < $v_fix
puts " Funcionou "
end<file_sep>/form_siteprism/features/step_definitions/form.rb
Dado(/^que eu acesse o formulário$/) do
@objetos = Home.new
@objetos.home.load
end
Quando(/^eu preencher os campos do formulário$/) do
@objetos.elementos.nome.set Faker::Name.name_with_middle
@objetos.elementos.email.set Faker::Internet.email
@objetos.elementos.randomize_drop_down(1)
@objetos.elementos.randomize_drop_down(2)
@objetos.elementos.randomize_check_box(1)
@objetos.elementos.randomize_check_box(2)
end
Quando(/^clicar no botão enviar$/) do
@objetos.elementos.enviar.click
end
Então(/^confirmo que a resposta foi registrada$/) do
expect(page.has_content?(DADOS['CHECK']['VERIFY_CONTENT'])).to be true
sleep(5)
end<file_sep>/dojo2/features/pages/start.rb
class Home < SitePrism::Page
set_url ENVIRONMENT['URL']['HOME']
def home
Home.new
end
def formulario
Formulario.new
end
def proxima
Proxima.new
end
end<file_sep>/praticando_1512/features/step_definitions/steps2.rb
Dado(/^que eu acessar o facebook$/) do
visit('https://www.facebook.com/')
end
Quando(/^eu preencher os campos de login$/) do
fill_in('email', :with => '<EMAIL>')
fill_in('pass', :with => '<PASSWORD>')
end
Quando(/^clicar em Entrar$/) do
click_button('u_0_l')
end
Então(/^vejo meu perfil$/) do
sleep(2)
end
Dado(/^que eu esteja logado no Facebook$/) do
visit('https://www.facebook.com/')
end
Quando(/^eu clicar no menu de configurações$/) do
# binding.pry
find("#userNavigationLabel").click
end
Quando(/^clicar em sair$/) do
click_link('Sair')
end
Então(/^vejo a tela inicial do Facebook$/) do
sleep(15)
end
=begin
Botao de entrar no face: u_0_l
Botão do menu do face: //*[@id="userNavigationLabel"]
Botão de sar do face: show_me_how_logout_1
=end<file_sep>/Walmart/features/step_definitions/steps1.rb
Dado(/^que eu acesse o Walmart$/) do
visit('https://www.walmart.com.br')
end
Quando(/^eu pesquisar "([^"]*)"$/) do |arg1|
$arg1 = 'TV 32'
fill_in('ft', :with => $arg1)
find("#site-topbar>div.wraper-right-icons>form>button").click
end
Quando(/^adicionar ao carrinho$/) do
# binding.pry
find("#product-list>section>ul>li.column.item-0.shelf-product-item").click
find("#buybox-Walmart>div.content.content-Walmart>div>div.buy-button-wrapper>button").click
find('#navegaCarrinho').click
sleep(10)
end
Então(/^confirmo que a TV está no carrinho$/) do
visit('https://www2.walmart.com.br/checkout/content/carrinho/')
page.should have_content("TV")
page.should have_content("32")
end<file_sep>/santander_siteprism/features/pages/home.rb
class Home < SitePrism::Page
set_url ENVIRONMENT['URL']['HOME']
end
|
e33e7feb5a3348ee35d96abbc777ee45e8c4348a
|
[
"Markdown",
"Ruby"
] | 30
|
Ruby
|
roccosta/automacao
|
e89389b9bd6a5a9ceeddaed4f8c05bc8260331de
|
9f27c8fa5ca6498b804970c447ce29956dce8b12
|
refs/heads/master
|
<repo_name>robotics-4-all/2020_riot_mde_thanos_manolis<file_sep>/riot_mde/codegen/README.md
# Folder codegen
The parser will fill this folder with source code, generated from the templates.<file_sep>/README.md
# riot_mde
A library for modelling devices (supported by [RIOT](https://github.com/RIOT-OS/RIOT)) and their connections, providing auto generated source code.
riot_mde provides a DSL (Domain Specific Language) for defining devices and connections between them. The DSL has been built using [textX](https://github.com/textX/textX) and through custom parsers the defined models are then used to generate code and diagrams.
Usage
-----
```
usage: riot_mde [-h] [--connections CONNECTIONS]
arguments:
-h, --help show this help message and exit
--connections CONNECTIONS
Filename of a connection specification.
```
### Code generation
Currently only devices that exist in folder [supported_devices](riot_mde/supported_devices) are supported.
After the definition of the devices and their connection has been done
the source code could be generated by
```
$ riot_mde --connections connection.con
```
The file connection.con should be located in folder [test_connections](test_connections).
The result of this command is a C file with name of the connection file and a Makefile, both located to the folder [codegen](riot_mde/codegen).
Installation
--------------------
To install this repo:
$ git clone https://github.com/robotics-4-all/2020_riot_mde_thanos_manolis
$ python setup.py install
<file_sep>/requirements.txt
textX==2.3.0
Jinja2==3.0.1
plantuml==0.3.0<file_sep>/riot_mde/img_export/README.md
# Folder img_export
This folder is empty because the parser will generate .pu and .png files (containing a visualization of the models and meta-models).<file_sep>/riot_mde/definitions.py
"""paths"""
import os
REPO_PATH = os.path.abspath(os.getcwd())
CODE_PATH = REPO_PATH + "/riot_mde"
SUPPORTED_DEVICES = CODE_PATH + "/supported_devices/"
META_MODELS = CODE_PATH + "/meta-models/"
IMG_EXPORT = CODE_PATH + "/img_export/"
TEMPLATES = CODE_PATH + "/templates/"
CODEGEN = CODE_PATH + "/codegen/" <file_sep>/riot_mde/hw_conns_plantuml.py
#!/usr/bin/env python
"""
hw_conns_plantuml.py
Script that generates PlantUML text from textX models
"""
# PlantUML generation for connection model
def generate_plantuml_connections(model, filename):
f = open(filename, "w")
tmp = '@startuml\n' + \
'\nskinparam componentStyle rectangle' + \
'\nskinparam linetype ortho' + \
'\nskinparam NoteFontSize 15' + \
'\nskinparam NoteFontStyle italics' + \
'\nskinparam RectangleFontSize 16\n' + \
'\n!define T2 \\t\\t' + \
'\n!define T5 \\t\\t\\t\\t\\t' + \
'\n!define NL2 \\n\\n' + \
'\n!define NL4 \\n\\n\\n\\n\n\n'
f.write(tmp)
tmp = 'component [NL4 T5 **' + str(model.connections[0].board.device) + \
'** T5 NL4] as ' + str(model.connections[0].board.device) + ' #FFF9C2\n'
f.write(tmp)
for i in range(len(model.connections)):
tmp = 'component [' + (i%4 < 2)*'NL4 T2' + (i%4 >= 2)*'NL2 T5' + \
' **' + str(model.connections[i].peripheral.device) + \
'** ' + (i%4 < 2)*'T2 NL4' + (i%4 >= 2)*'T5 NL2' + \
'] as ' + str(model.connections[i].peripheral.device) + \
' #CAE2C8\n'
f.write(tmp)
f.write('\n')
note_directions = ['top', 'bottom', 'right', 'left']
for i in range(len(model.connections)):
tmp = 'note ' + note_directions[i%4] + ' of ' + \
str(model.connections[i].peripheral.device) + \
' : topic - "' + str(model.connections[i].com_endpoint.topic[:-1]) + '"\n'
f.write(tmp)
f.write('\n')
pin_directions = ['le', 'ri', 'up', 'down']
for i in range(len(model.connections)):
for j in range(len(model.connections[i].hw_conns)):
if model.connections[i].hw_conns[j].type == 'gpio':
tmp = str(model.connections[i].board.device) + \
' "**' + str(model.connections[i].hw_conns[j].peripheral_int) + \
'**" #--' + str(pin_directions[i]) + '--# "**' + \
str(model.connections[i].hw_conns[j].board_int) + \
'**" ' + str(model.connections[i].peripheral.device) + \
(i%4 < 2) * ' : \\t\\t\\t\\t' + '\n'
elif model.connections[i].hw_conns[j].type == 'i2c':
tmp = ''
for k in range(2):
tmp = tmp + str(model.connections[i].board.device) + \
' "**' + str(model.connections[i].hw_conns[j].peripheral_int[k]) + \
'**" #--' + str(pin_directions[i]) + '--# "**' + \
str(model.connections[i].hw_conns[j].board_int[k]) + \
'**" ' + str(model.connections[i].peripheral.device) + \
(i%4 < 2) * ' : \\t\\t\\t\\t' + '\n'
f.write(tmp)
for j in range(len(model.connections[i].power_conns)):
tmp = str(model.connections[i].board.device) + \
' "**' + str(model.connections[i].power_conns[j].peripheral_power) + \
'**" #--' + str(pin_directions[i]) + '--# "**' + \
str(model.connections[i].power_conns[j].board_power) + \
'**" ' + str(model.connections[i].peripheral.device) + \
(i%4 < 2) * ' : \\t\\t\\t\\t' + '\n'
f.write(tmp)
f.write('\n')
f.write('\nhide @unlinked\n@enduml')
f.close()<file_sep>/setup.py
#!/usr/bin/env python
from os import path
from codecs import open
from setuptools import setup, find_packages
__version__ = '0.0.1'
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
# get the dependencies and installs
with open(path.join(here, 'requirements.txt'), encoding='utf-8') as f:
all_reqs = f.read().split('\n')
requirements = [x.strip() for x in all_reqs if 'git+' not in x]
dependency_links = [x.strip().replace('git+', '')
for x in all_reqs if x.startswith('git+')]
setup(
name="riot_mde",
version=__version__,
description="A package for modeling real-time IoT systems",
url="https://github.com/robotics-4-all/2020_riot_mde_thanos_manolis",
long_description=long_description,
long_description_content_type="text/markdown",
license='MIT',
author="<NAME>",
author_email="<EMAIL>",
classifiers=[
"License :: OSI Approved :: MIT License",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
],
install_requires=requirements,
entry_points={
'console_scripts': [
'riot_mde = riot_mde.parser:main'
]
},
py_modules=['riot_mde.parser', 'riot_mde.model_2_plantuml', 'riot_mde.hw_conns_plantuml', 'riot_mde.definitions'],
packages=find_packages(),
dependency_links=dependency_links,
python_requires='>=3.6'
)<file_sep>/example/example1.c
#include <time.h>
#include "shell.h"
#include "msg.h"
#include "fmt.h"
#include "xtimer.h"
#include "string.h"
/* Peripheral includes */
#include "srf04.h"
#include "srf04_params.h"
#include "bme680.h"
#include "bme680_params.h"
#include "ws281x.h"
#include "ws281x_params.h"
/* MQTT-S includes */
#include "net/emcute.h"
#include "net/ipv6/addr.h"
#ifndef EMCUTE_ID
#define EMCUTE_ID ("gertrud")
#endif
#define EMCUTE_PORT (1885)
#define EMCUTE_ADDRESS ("fd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b")
#define NUMOFSUBS (16U)
#define TOPIC_MAXLEN (64U)
msg_t queue[8];
static emcute_sub_t subscriptions[NUMOFSUBS];
static char topics[NUMOFSUBS][TOPIC_MAXLEN];
char stack1[THREAD_STACKSIZE_DEFAULT];
char stack2[THREAD_STACKSIZE_DEFAULT];
char stack3[THREAD_STACKSIZE_DEFAULT];
char stack_mqtt[THREAD_STACKSIZE_DEFAULT];
void *emcute_thread(void *arg)
{
(void)arg;
emcute_run(EMCUTE_PORT, EMCUTE_ID);
return NULL; // should never be reached
}
/*
* Function to get qos level
*/
unsigned get_qos(int qos)
{
switch (qos)
{
case 1:
return EMCUTE_QOS_1;
case 2:
return EMCUTE_QOS_2;
default:
return EMCUTE_QOS_0;
}
}
/*
* Function that connects to the MQTT-SN gateway
*
* - param addr MQTT-SN Gateway IP address
* - param port MQTT-SN Gateway Port
*/
int con(char *addr, int port)
{
sock_udp_ep_t gw = {.family = AF_INET6, .port = EMCUTE_PORT};
gw.port = port;
/* parse address */
if (ipv6_addr_from_str((ipv6_addr_t *)&gw.addr.ipv6, addr) == NULL)
{
printf("error parsing IPv6 address\n");
return 1;
}
if (emcute_con(&gw, true, NULL, NULL, 0, 0) != EMCUTE_OK)
{
printf("error: unable to connect to [%s]:%i\n", addr, port);
return 1;
}
printf("Successfully connected to gateway at [%s]:%i\n", addr, port);
return 0;
}
/*
* Function that disconnects from the MQTT-SN gateway
*/
int discon(void)
{
int res = emcute_discon();
if (res == EMCUTE_NOGW)
{
puts("error: not connected to any broker");
return 1;
}
else if (res != EMCUTE_OK)
{
puts("error: unable to disconnect");
return 1;
}
puts("Disconnect successful");
return 0;
}
/*
* Function that publishes a message to a topic
*
* - param topic Topic in which to publish
* - param data Message to be published
* - param qos Quality of service
*/
int pub(char *topic, char *data, int qos)
{
emcute_topic_t t;
unsigned flags = EMCUTE_QOS_0;
/* parse QoS level */
flags |= get_qos(qos);
/* Get topic id */
t.name = topic;
if (emcute_reg(&t) != EMCUTE_OK)
{
puts("error: unable to obtain topic ID");
return 1;
}
/* Publish data */
if (emcute_pub(&t, data, strlen(data), flags) != EMCUTE_OK)
{
printf("error: unable to publish data to topic '%s [%i]'\n",
t.name, (int)t.id);
return 1;
}
printf("published %s on topic %s\n", data, topic);
return 0;
}
int sub(char *topic, int qos, void *func)
{
unsigned flags = EMCUTE_QOS_0;
/* parse QoS level */
flags |= get_qos(qos);
/* find empty subscription slot */
unsigned i = 0;
for (; (i < NUMOFSUBS) && (subscriptions[i].topic.id != 0); i++) {}
if (i == NUMOFSUBS)
{
puts("error: no memory to store new subscriptions");
return 1;
}
subscriptions[i].cb = func;
strcpy(topics[i], topic);
subscriptions[i].topic.name = topics[i];
if (emcute_sub(&subscriptions[i], flags) != EMCUTE_OK) {
printf("error: unable to subscribe to %s\n", topic);
return 1;
}
printf("Now subscribed to %s\n", topic);
return 0;
}
/*
* [ srf04 sensor ]
* This function gets a sensor measurement with frequency 5 Hz
* and publishes it to topic 'srf04.data'.
*/
void *send_srf04(void *arg)
{
(void) arg;
/* Name of the topic */
char topic[32];
sprintf(topic, "srf04.data");
/* Allocate memory for the message to be published */
char *msg = malloc(128);
/* Fix port parameter for digital sensor */
srf04_params_t my_params;
/* PINS */
my_params.trigger = GPIO_PIN( 0, 13 );
my_params.echo = GPIO_PIN( 0, 14 );
/* Initialize gpio and interrupt */
srf04_t dev;
if (srf04_init(&dev, &my_params) == SRF04_OK)
printf("SRF04 sensor connected\n");
else
printf("Failed to connect to SRF04 sensor\n");
/* Print sensor output with frequency 5 Hz */
while (true)
{
/* Get a sensor measurement */
int dist = srf04_get_distance(&dev);
if (dist == SRF04_ERR_INVALID)
{
printf("Error: No valid measurement is available\n");
}
else if (dist == SRF04_ERR_MEASURING)
{
printf("Error: measurement is in progress\n");
}
else
{
/* Create a message to be published */
sprintf(msg, "{id: 1, SRF04 "
"Output: [Distance]: %.2f cm}\n",
(float)dist / 10);
printf("%s", msg);
/* Publish to the topic */
pub(topic, msg, 0);
}
/* Sleep for 0.2 seconds */
xtimer_msleep( 1000 / 5 );
}
return NULL;
}
/*
* [ bme680 sensor ]
* This function gets a sensor measurement with frequency 2 Hz
* and publishes it to topic 'bme680.data'.
*/
void *send_bme680(void *arg)
{
(void) arg;
/* Name of the topic */
char topic[32];
sprintf(topic, "bme680.data");
/* Allocate memory for the message to be published */
char *msg = malloc(128);
bme680_t dev[BME680_NUMOF];
bme680_params_t myparams[BME680_NUMOF];
memcpy(&myparams, &bme680_params, sizeof(bme680_params_t));
for (unsigned i = 0; i < BME680_NUMOF; i++)
{
BME680_SENSOR(&dev[i]).amb_temp = 25;
myparams[i].intf.i2c.addr = 0x76;
printf("Initialize BME680 sensor %u ... ", i);
if (bme680_init(&dev[i], &myparams[i]) != BME680_OK)
puts("failed");
else
puts("OK");
}
/* Print sensor output with frequency 2 Hz */
while (true)
{
struct bme680_field_data data;
for (unsigned i = 0; i < BME680_NUMOF; i++)
{
/* trigger one measuerment */
bme680_force_measurement(&dev[i]);
/* get the duration for the measurement */
int duration = bme680_get_duration(&dev[i]);
/* wait for the duration */
xtimer_msleep(duration);
/* read the data */
int res = bme680_get_data(&dev[i], &data);
if (res == 0 && dev[i].sensor.new_fields)
{
/* Create a message to be published */
sprintf(msg, "{id: 2, BME680 Output: ");
#ifndef MODULE_BME680_FP
sprintf(msg + strlen(msg),
"[Temp] = %02d.%02d C, "
"[Pressure] = %" PRIu32 " Pa, "
"[Humidity] = %02" PRIu32 ".%03" PRIu32 " %%",
data.temperature / 100, data.temperature % 100,
data.pressure, data.humidity / 1000, data.humidity % 1000);
/* Avoid using measurements from an unstable heating setup */
if (data.status & BME680_GASM_VALID_MSK)
sprintf(msg + strlen(msg),
", [Gas] = %" PRIu32 " ohms", data.gas_resistance);
#else
sprintf(msg + strlen(msg),
"[Temp] = %.2f C, "
"[Pressure] = %.2f Pa, "
"[Humidity] %.3f %%",
data.temperature, data.pressure, data.humidity);
/* Avoid using measurements from an unstable heating setup */
if (data.status & BME680_GASM_VALID_MSK)
sprintf(msg + strlen(msg),
", [Gas] = %.0f ohms", data.gas_resistance);
#endif
sprintf(msg + strlen(msg), "}\n");
printf("%s", msg);
/* Publish to the topic */
pub(topic, msg, 0);
}
else if (res == 0)
printf("[bme680]: no new data\n");
else
printf("[bme680]: read data failed with reason %d\n", res);
}
/* Sleep for 0.5 seconds */
xtimer_msleep( 1000 / 2 );
}
return NULL;
}
/*
* [ ws281x actuator ]
* This function implements the action that the actuator will do in the event of a
* published message in the topic that it listens to (ws281x.data).
*/
void ws281x_on_pub(const emcute_topic_t *topic, void *data, size_t len)
{
char *msg = (char *)data;
printf("### got publication for topic '%s' [%i] ###\n",
topic->name, (int)topic->id);
for (size_t i = 0; i < len; i++) {
printf("%c", msg[i]);
}
puts("");
/* Array to store splitted RGB values (as strings) */
char **rgb_str = malloc(3 * sizeof(char*));
for (int i = 0; i < 3; i++)
rgb_str[i] = malloc(2 * sizeof(char));
/* Array to store splitted RGB values (as integers) */
int *rgb = malloc(3 * sizeof(int));
ws281x_t dev;
ws281x_params_t my_params;
memcpy(&my_params, ws281x_params, sizeof(ws281x_params_t));
int init;
/* Connected input pin */
my_params.pin = GPIO_PIN( 0, 0 );
/* Number of LEDs to light up */
my_params.numof = 12U;
uint8_t buf[my_params.numof * WS281X_BYTES_PER_DEVICE];
my_params.buf = buf;
if ( (init = ws281x_init(&dev, &my_params)) != 0 )
printf("WS281X initialization failed with error code %d\n", init);
else
printf("WS281X actuator initialized\n");
/* Split message to RGB */
for (int i = 0; i < 3; i++)
{
memcpy( rgb_str[i], &msg[2*i], 2 );
rgb[i] = (int)strtol(rgb_str[i], NULL, 16);
}
/* Store RGB values in a data structure */
color_rgb_t colors = { .r = rgb[0], .g = rgb[1], .b = rgb[2] };
for (uint16_t i = 0; i < dev.params.numof; i++)
ws281x_set(&dev, i, colors);
ws281x_write(&dev);
}
void *receive_ws281x(void *arg)
{
(void) arg;
/* Name of the topic */
char topic[32];
sprintf(topic, "ws281x.data");
sub(topic, 0, ws281x_on_pub);
return NULL;
}
int main(void)
{
printf("This application runs on %s\n", RIOT_BOARD);
/* Initialize our subscription buffers */
memset(subscriptions, 0, (NUMOFSUBS * sizeof(emcute_sub_t)));
/* Start the emcute thread */
thread_create(stack_mqtt, sizeof(stack_mqtt),
THREAD_PRIORITY_MAIN - 1,
0,
emcute_thread,
NULL, "emcute");
/* Try to connect to the gateway */
if (con(EMCUTE_ADDRESS, EMCUTE_PORT))
printf("Couldn't connect to broker. The measurements will just be printed instead.\n");
/* Start the srf04 thread*/
thread_create(stack1, sizeof(stack1),
THREAD_PRIORITY_MAIN - 1,
THREAD_CREATE_STACKTEST,
send_srf04,
NULL, "srf04");
/* Start the bme680 thread*/
thread_create(stack2, sizeof(stack2),
THREAD_PRIORITY_MAIN - 1,
THREAD_CREATE_STACKTEST,
send_bme680,
NULL, "bme680");
/* Start the ws281x thread*/
thread_create(stack3, sizeof(stack3),
THREAD_PRIORITY_MAIN - 1,
THREAD_CREATE_STACKTEST,
receive_ws281x,
NULL, "ws281x");
return 0;
}<file_sep>/riot_mde/supported_devices/README.md
# Folder supported_devices
This folder contains the description of the supported boards and peripherals.<file_sep>/riot_mde/parser.py
#!/usr/bin/env python
"""parser.py"""
# textX imports
from textx.export import metamodel_export, model_export, PlantUmlRenderer
from textx import metamodel_from_file
# PlantUML Imports
from riot_mde import model_2_plantuml
from riot_mde import hw_conns_plantuml
# Jinja imports
import codecs
import jinja2
from os.path import join, dirname
from pathlib import Path
import os
import sys
import argparse
import pydot
import shutil
from riot_mde.definitions import *
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
fsloader = jinja2.FileSystemLoader(TEMPLATES)
env = jinja2.Environment(loader=fsloader)
def parse_args() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser()
# Add arguments
parser.add_argument("--connections",
help="Filename of a connection specification.")
return parser.parse_args()
def main():
cl_args = parse_args()
connection_conf_filename = cl_args.connections
if connection_conf_filename.endswith(".con"):
connection_conf = connection_conf_filename.removesuffix('.con')
else:
sys.exit("Connection file should end with '.con'")
# Create a list of supported boards
supported_boards = []
directory = os.fsencode(SUPPORTED_DEVICES + 'boards')
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".hwd"):
supported_boards.append(filename[:-4])
continue
else:
continue
# Create a list of supported peripherals
supported_peripherals = []
directory = os.fsencode(SUPPORTED_DEVICES + 'peripherals')
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".hwd"):
supported_peripherals.append(filename[:-4])
continue
else:
continue
""" Parse info from connections meta-model """
# Get meta-model from language description
connections_mm = metamodel_from_file(META_MODELS + '/connections.tx')
# Export meta-model to PlantUML (.pu) and then png
# metamodel_export(connections_mm, IMG_EXPORT + 'connections_mm.pu', renderer=PlantUmlRenderer())
# os.system('plantuml -DPLANTUML_LIMIT_SIZE=8192 ' + IMG_EXPORT + 'connections_mm.pu')
# Construct connection model from a specific file
connection_model = connections_mm.model_from_file(
'test_connections/' + connection_conf_filename)
# Export model to PlantUML (.pu) and then png
hw_conns_plantuml.generate_plantuml_connections(connection_model, IMG_EXPORT + connection_conf + 'a.pu')
os.system('plantuml -DPLANTUML_LIMIT_SIZE=8192 ' + IMG_EXPORT + connection_conf + 'a.pu')
model_2_plantuml.generate_plantuml_connections(connection_model, IMG_EXPORT + connection_conf + 'b.pu')
os.system('plantuml -DPLANTUML_LIMIT_SIZE=8192 ' + IMG_EXPORT + connection_conf + 'b.pu')
""" Parse info from device meta-model """
# Get meta-model from language description
devices_mm = metamodel_from_file(META_MODELS + '/devices.tx')
# Export meta-model to PlantUML (.pu) and then png
# metamodel_export(devices_mm, IMG_EXPORT + 'devices_mm.pu', renderer=PlantUmlRenderer())
# os.system('plantuml -DPLANTUML_LIMIT_SIZE=8192 ' + IMG_EXPORT + 'devices_mm.pu')
# Check if a hardware configuration file exists for each given board/peripheral
all_hwd_exist = True
for device in connection_model.includes:
# Construct device model from a specific file
if device.name in supported_boards:
continue
elif device.name in supported_peripherals:
continue
else:
print("No configuration file for device " + device.name + " found!")
all_hwd_exist = False
if all_hwd_exist == False:
sys.exit("You need to create configuration (.hwd) file(s) for the devices(s) mentioned above ...")
device_models = {}
# Create a model for each device used (board/peripheral)
for device in connection_model.includes:
# Construct device model from a specific file
if device.name in supported_boards:
device_models[device.name] = devices_mm.model_from_file(
SUPPORTED_DEVICES + '/boards/' + device.name + '.hwd')
elif device.name in supported_peripherals:
device_models[device.name] = devices_mm.model_from_file(
SUPPORTED_DEVICES + '/peripherals/' + device.name + '.hwd')
# Export model to dot and png
# model_export(device_models[device.name], IMG_EXPORT + device.name + '.dot')
# (graph,) = pydot.graph_from_dot_file(
# IMG_EXPORT + device.name + '.dot')
# graph.write_png(IMG_EXPORT + device.name + '.png')
""" Produce source code from templates """
# Load C template
template1 = env.get_template(
'base.c.tmpl')
# Load Makefile template
template2 = env.get_template(
'Makefile.tmpl')
peripheral_name_tmp = {}
peripheral_type_tmp = {}
id_tmp = {}
frequency_tmp = {}
module_tmp = {}
args_tmp = {}
topic_tmp = {}
num_of_peripherals_tmp = len(connection_model.connections)
# Name of board
board_name_tmp = connection_model.connections[0].board.device
if board_name_tmp == 'esp32_wroom_32':
board_name_tmp = 'esp32-wroom-32'
elif board_name_tmp == 'wemos_d1_mini':
board_name_tmp = 'esp8266-esp-12x'
# Wifi credentials
wifi_ssid_tmp = connection_model.connections[0].com_endpoint.wifi_ssid[:-1]
wifi_passwd_tmp = connection_model.connections[0].com_endpoint.wifi_passwd[:-1]
for i in range(len(connection_model.connections)):
# Parse info from the created models
address_tmp = connection_model.connections[i].com_endpoint.addr
id_tmp[i] = i + 1
mqtt_port = connection_model.connections[i].com_endpoint.port
peripheral_name_tmp[i] = connection_model.connections[i].peripheral.device
peripheral_type_tmp[peripheral_name_tmp[i]] = device_models[peripheral_name_tmp[i]].type
module_tmp[i] = connection_model.connections[i].peripheral.device
topic_tmp[i] = connection_model.connections[i].com_endpoint.topic[:-1]
# Publishing frequency (always convert to Hz)
# If not given, default value is 1Hz
if( hasattr(connection_model.connections[i].com_endpoint.freq, 'val') ):
frequency_tmp[i] = connection_model.connections[i].com_endpoint.freq.val
frequency_unit = connection_model.connections[i].com_endpoint.freq.unit
if (frequency_unit == "khz"):
frequency_tmp[i] = (10**3) * frequency_tmp[i]
elif (frequency_unit == "mhz"):
frequency_tmp[i] = (10**6) * frequency_tmp[i]
elif (frequency_unit == "ghz"):
frequency_tmp[i] = (10**9) * frequency_tmp[i]
else:
frequency_tmp[i] = 1
# Hardware connection args
args_tmp[i] = {}
if (connection_model.connections[i].hw_conns[0].type == 'gpio'):
for hw_conn in connection_model.connections[i].hw_conns:
args_tmp[i][hw_conn.peripheral_int] = (hw_conn.board_int).split("_",1)[1]
elif (connection_model.connections[i].hw_conns[0].type == 'i2c'):
args_tmp[i]["sda"] = (connection_model.connections[i].hw_conns[0].board_int[0]).split("_",1)[1]
args_tmp[i]["scl"] = (connection_model.connections[i].hw_conns[0].board_int[1]).split("_",1)[1]
args_tmp[i]["slave_address"] = connection_model.connections[i].hw_conns[0].slave_addr
if(connection_model.connections[i].peripheral.device == 'bme680'):
module_tmp[i] = module_tmp[i] + '_i2c'
# Check if a template exists for each given peripheral
all_tmpl_exist = True
for peripheral in peripheral_name_tmp.values():
file = TEMPLATES + peripheral + '.c.tmpl'
if os.path.isfile(file) == False:
print("No template for peripheral " + peripheral + " found!")
all_tmpl_exist = False
if peripheral_type_tmp[peripheral] == 'sensor':
shutil.copyfile(TEMPLATES + 'unsupported_sensor.txt', file)
elif peripheral_type_tmp[peripheral] == 'actuator':
shutil.copyfile(TEMPLATES + 'unsupported_actuator.txt', file)
if all_tmpl_exist == False:
sys.exit('\nA template for each one of the peripheral(s) mentioned above' + \
'\nwas created. You need to fill it with appropriate code ...')
# C template
rt = template1.render(address=address_tmp,
id=id_tmp,
port=mqtt_port,
peripheral_name=peripheral_name_tmp,
peripheral_type=peripheral_type_tmp,
args=args_tmp,
topic=topic_tmp,
frequency=frequency_tmp,
num_of_peripherals = num_of_peripherals_tmp,
templates = TEMPLATES)
ofh = codecs.open(CODEGEN + connection_conf + ".c", "w", encoding="utf-8")
ofh.write(rt)
ofh.close()
# Makefile template
rt = template2.render(connection_conf=connection_conf,
module=module_tmp,
board_name=board_name_tmp,
wifi_ssid=wifi_ssid_tmp,
wifi_passwd=<PASSWORD>)
ofh = codecs.open(CODEGEN + 'Makefile', "w", encoding="utf-8")
ofh.write(rt)
ofh.close()
if __name__ == '__main__':
main()
<file_sep>/example/Makefile
# name of your application
APPLICATION = example1
# If no BOARD is found in the environment, use this default:
BOARD ?= esp32-wroom-32
# This has to be the absolute path to the RIOT base directory:
RIOTBASE ?= $(HOME)/RIOT
# Include Peripheral and FMT module
USEMODULE += srf04
USEMODULE += bme680_i2c
USEMODULE += ws281x
USEMODULE += fmt
USEMODULE += xtimer
# Comment this out to disable code in RIOT that does safety checking
# which is not needed in a production environment but helps in the
# development process:
DEVELHELP ?= 1
# Change this to 0 show compiler invocation lines by default:
QUIET ?= 1
# Include packages that pull up and auto-init the link layer.
# NOTE: 6LoWPAN will be included if IEEE802.15.4 devices are present
USEMODULE += gnrc_netdev_default
USEMODULE += auto_init_gnrc_netif
# Specify the mandatory networking modules for IPv6
USEMODULE += gnrc_ipv6_default
# Include MQTT-SN
USEMODULE += emcute
# Add also the shell, some shell commands
USEMODULE += shell
USEMODULE += shell_commands
USEMODULE += ps
# For testing we also include the ping6 command and some stats
USEMODULE += gnrc_icmpv6_echo
# Optimize network stack to for use with a single network interface
USEMODULE += gnrc_netif_single
# Connect board to wifi
USEMODULE += esp_wifi
CFLAGS += -DESP_WIFI_SSID=\"Wifi_2.4GHz\"
CFLAGS += -DESP_WIFI_PASS=\"<PASSWORD>?\"
# Give specific ID to this MQTT node
CFLAGS += -DEMCUTE_ID=\"example1\"
include $(RIOTBASE)/Makefile.include<file_sep>/riot_mde/model_2_plantuml.py
#!/usr/bin/env python
"""
model_2_plantuml.py
Script that generates PlantUML text from textX models
"""
# PlantUML generation for connection model
def generate_plantuml_connections(model, filename):
f = open(filename, "w")
f.write('@startuml\nset namespaceSeparator .\n\n\n')
f.write('class connections.SYSTEM {\n}\n\n\n')
for i in range(len(model.includes)):
tmp = 'class connections.INCLUDE_' + str(i) + \
' {\n name: str=\'' + model.includes[i].name + \
'\'\n}\n\n\n'
f.write(tmp)
for i in range(len(model.connections)):
tmp = 'class connections.CONNECTION_' + str(i) + \
' {\n name: ' + model.connections[i].name + \
'\n}\n\n\n'
f.write(tmp)
tmp = 'class connections.BOARD_' + str(i) + \
' {\n device: str=\'' + model.connections[i].board.device + '\'\n' + \
' number: int=' + str(model.connections[i].board.number) + '\n}\n\n\n'
f.write(tmp)
tmp = 'class connections.PERIPHERAL_' + str(i) + \
' {\n device: str=\'' + model.connections[i].peripheral.device + '\'\n' + \
' number: int=' + str(model.connections[i].peripheral.number) + '\n}\n\n\n'
f.write(tmp)
for j in range(len(model.connections[i].power_conns)):
tmp = 'class connections.POWER_CONNECTION_' + str(i) + '_' + str(j) + \
' {\n board_power: str=\'' + model.connections[i].power_conns[j].board_power + '\'\n' + \
' peripheral_power: str=\'' + str(model.connections[i].power_conns[j].peripheral_power) + \
'\'\n}\n\n\n'
f.write(tmp)
for j in range(len(model.connections[i].hw_conns)):
if model.connections[i].hw_conns[j].type == 'gpio':
tmp = 'class connections.GPIO_' + str(i) + '_' + str(j) + \
' {\n type: str=\'' + model.connections[i].hw_conns[j].type + '\'\n' + \
' board_int: str=\'' + model.connections[i].hw_conns[j].board_int + '\'\n' + \
' peripheral_int: str=\'' + str(model.connections[i].hw_conns[j].peripheral_int) + \
'\'\n}\n\n\n'
f.write(tmp)
elif model.connections[i].hw_conns[j].type == 'i2c':
tmp = 'class connections.I2C_' + str(i) + \
' {\n type: str=\'' + model.connections[i].hw_conns[j].type + '\'\n' + \
' board_int: list=[\'' + \
model.connections[i].hw_conns[j].board_int[0] + '\',\'' + \
model.connections[i].hw_conns[j].board_int[1]+ '\']\n' + \
' peripheral_int: list=[\'' + \
model.connections[i].hw_conns[j].peripheral_int[0] + '\',\'' + \
model.connections[i].hw_conns[j].peripheral_int[1]+ '\']\n' + \
' slave_addr: int=' + str(model.connections[i].hw_conns[j].slave_addr) + \
'\n}\n\n\n'
f.write(tmp)
elif model.connections[i].hw_conns[j].type == 'pwm':
tmp = 'class connections.PWM_' + str(i) + '_' + str(j) + \
' {\n type: str=\'' + model.connections[i].hw_conns[j].type + '\'\n' + \
' board_int: str=\'' + model.connections[i].hw_conns[j].board_int + '\'\n' + \
' peripheral_int: str=\'' + str(model.connections[i].hw_conns[j].peripheral_int) + \
'\'\n}\n\n\n'
f.write(tmp)
elif model.connections[i].hw_conns[j].type == 'spi':
tmp = 'class connections.SPI_' + str(i) + '_' + str(j) + \
' {\n type: str=\'' + model.connections[i].hw_conns[j].type + '\'\n' + \
' board_int: str=\'' + model.connections[i].hw_conns[j].board_int + '\'\n' + \
' peripheral_int: str=\'' + str(model.connections[i].hw_conns[j].peripheral_int) + \
'\'\n}\n\n\n'
f.write(tmp)
elif model.connections[i].hw_conns[j].type == 'uart':
tmp = 'class connections.UART_' + str(i) + '_' + str(j) + \
' {\n type: str=\'' + model.connections[i].hw_conns[j].type + '\'\n' + \
' board_int: str=\'' + model.connections[i].hw_conns[j].board_int + '\'\n' + \
' peripheral_int: str=\'' + str(model.connections[i].hw_conns[j].peripheral_int) + '\'\n' + \
' baudrate: int=' + str(model.connections[i].hw_conns[j].baudrate) + '\n}\n\n\n'
f.write(tmp)
tmp = 'class connections.COM_ENDPOINT_' + str(i) + \
' {\n topic: str=\'' + model.connections[i].com_endpoint.topic[:-1] + '\'\n' + \
' addr: str=\'' + model.connections[i].com_endpoint.addr + '\'\n' + \
' port: int=' + str(model.connections[i].com_endpoint.port) + '\n}\n\n\n'
f.write(tmp)
msg_entries = ''
for j in range(len(model.connections[i].com_endpoint.msg.msg_entries)):
msg_entries += '\'' + model.connections[i].com_endpoint.msg.msg_entries[j] + '\','
msg_entries = msg_entries[:-1]
tmp = 'class connections.MSG_ENTRIES_' + str(i) + \
' {\n msg_entries: list=[' + msg_entries + ']' + '\n}\n\n\n'
f.write(tmp)
if( hasattr(model.connections[i].com_endpoint.freq, 'val') ):
tmp = 'class connections.FREQUENCY_' + str(i) + \
' {\n val: int=' + str(model.connections[i].com_endpoint.freq.val) + '\n' + \
' unit: str=\'' + model.connections[i].com_endpoint.freq.unit + \
'\'\n}\n\n\n'
f.write(tmp)
# Relations
for i in range(len(model.includes)):
tmp = 'connections.SYSTEM *-- "includes:' + str(i) + \
'" connections.INCLUDE_' + str(i) + '\n'
f.write(tmp)
for i in range(len(model.connections)):
tmp = 'connections.SYSTEM *-- "connections:' + str(i) + \
'" connections.CONNECTION_' + str(i) + '\n'
f.write(tmp)
tmp = 'connections.CONNECTION_' + str(i) + \
' *-- "board" connections.BOARD_' + str(i) + '\n'
f.write(tmp)
tmp = 'connections.CONNECTION_' + str(i) + \
' *-- "peripheral" connections.PERIPHERAL_' + str(i) + '\n'
f.write(tmp)
for j in range(len(model.connections[i].power_conns)):
tmp = 'connections.CONNECTION_' + str(i) + ' *-- "power_conns:' + str(j) + \
'" connections.POWER_CONNECTION_' + str(i) + '_' + str(j) + '\n'
f.write(tmp)
for j in range(len(model.connections[i].hw_conns)):
if model.connections[i].hw_conns[j].type == 'gpio':
tmp = 'connections.CONNECTION_' + str(i) + ' *-- "hw_conns:' + str(j) + \
'" connections.GPIO_' + str(i) + '_' + str(j) + '\n'
f.write(tmp)
elif model.connections[i].hw_conns[j].type == 'i2c':
tmp = 'connections.CONNECTION_' + str(i) + ' *-- "hw_conns:' + str(j) + \
'" connections.I2C_' + str(i) + '\n'
f.write(tmp)
elif model.connections[i].hw_conns[j].type == 'pwm':
tmp = 'connections.CONNECTION_' + str(i) + ' *-- "hw_conns:' + str(j) + \
'" connections.PWM_' + str(i) + '_' + str(j) + '\n'
f.write(tmp)
elif model.connections[i].hw_conns[j].type == 'spi':
tmp = 'connections.CONNECTION_' + str(i) + ' *-- "hw_conns:' + str(j) + \
'" connections.SPI_' + str(i) + '_' + str(j) + '\n'
f.write(tmp)
elif model.connections[i].hw_conns[j].type == 'uart':
tmp = 'connections.CONNECTION_' + str(i) + ' *-- "hw_conns:' + str(j) + \
'" connections.UART_' + str(i) + '_' + str(j) + '\n'
f.write(tmp)
tmp = 'connections.CONNECTION_' + str(i) + \
' *-- "com_endpoint" connections.COM_ENDPOINT_' + str(i) + '\n'
f.write(tmp)
tmp = 'connections.COM_ENDPOINT_' + str(i) + \
' *-- "msg" connections.MSG_ENTRIES_' + str(i) + '\n'
f.write(tmp)
if( hasattr(model.connections[i].com_endpoint.freq, 'val') ):
tmp = 'connections.COM_ENDPOINT_' + str(i) + \
' *-- "freq" connections.FREQUENCY_' + str(i) + '\n'
f.write(tmp)
f.write('\n@enduml')
f.close()
|
9bf643ef68544248e08140212c9b8a7aaac6203e
|
[
"Markdown",
"Makefile",
"Python",
"Text",
"C"
] | 12
|
Markdown
|
robotics-4-all/2020_riot_mde_thanos_manolis
|
d795f710b7c405db9bd7921b01a52c80b5a20b03
|
93b8232eee390da3298e2cfa73f83183cdf45e55
|
refs/heads/master
|
<file_sep>package com.bbrv.app.domain;
public final class Views {
public interface IdText{}
public interface FullFields extends IdText{}
}
<file_sep><img src="https://img.shields.io/badge/backend-spring--boot-green"/> <img src="https://img.shields.io/badge/front-vuejs-yellow"/>
# To-do-list
## Тестовое приложение c использованием:
### Backend
- Java 1.8
- Spring Boot
- Spring Data JPA
- PostgreSQL
- Maven
### Frontend (CDN)
- Vue
- Vue resource
- Vuetify
## Как запустить
1. Установить PostgreSQL.
2. Сконфигурировать подключение к БД в файле application.properties.
3. Запустить mvn install.
4. Запустить mvn spring-boot:run.

|
521cc119e43225ba9458bb712fbadf9905c1519c
|
[
"Markdown",
"Java"
] | 2
|
Java
|
mr-and/todo-spring-vuejs
|
c4b0e70ec4477053c0968dc4e78c3a1a705d98f3
|
5c8e1c33a47905d9f937bdda3013c56699552f68
|
refs/heads/master
|
<repo_name>ZhaoguoZhu/IAM_Handwriting_Recognition<file_sep>/Main.py
from Data_Preprocessing import prepare_data
from Loading_and_Normalize import normalize_pixels
from Model_Evaluation import eval_model
from Data_Preprocessing import prepare_data
from tensorflow.keras.preprocessing.image import load_img, img_to_array
from numpy import asarray
def exe():
TrainX, TrainY, TestX, TestY = prepare_data()
'''
TrainX, TrainY, TestX, TestY= list(), list(), list(), list()
image = load_img("words/a01/a01-000u/a01-000u-00-00.png", target_size=(32, 128), color_mode="grayscale")
image = img_to_array(image)
TrainX.append(image)
TestX.append(image)
arr = [1,2]
TrainY.append(arr)
TestY.append(arr)
TrainX = asarray(TrainX)
print(type(TrainX))
print(TrainX)
TrainY = asarray(TrainY)
print(type(TrainY))
print(TrainY)
TestX = asarray(TestX)
TestY = asarray(TestY)
'''
TrainX, TestX = normalize_pixels(TrainX, TestX)
eval_model(TrainX, TrainY, TestX, TestY)
exe()
<file_sep>/README.md
# Handwriting Recognition with customed Keras model
## Contribution
Author: <NAME> <br/>
Institute: College of Arts and Sciences, Boston University<br/>
Instructor and Supervisor: Dr. <NAME> <br/>
E-mail: <EMAIL>
## Introduction
This python project is a pipeline inspiration of Handwriting Recognition challenge from IAM dataset website. The customed HWTRModel consists of 7 Convolutional layers(CNN), 4 Recurrent Neural Network layers(RNN) and Connectionist Temporal Classification loss calculation and decoding layer(CTC). The neural network walk through is in the following format:
* Pass in the images in grayscale format with only one color channel activated and a shape of 32x128
* 7 CNN layers provide a feature mapping to a sequence of size 32x256
* 4 RNN layers provide a feature mapping to a sequence of size 32x80 with each column represents the possibility of one of the 80 characters in English word (26 lower case; 26 upper case; 26 signs and marks; one space character; one None character)
* A CTC layer which either calculates the loss value given the matrix or decodes the 32x80 matrix with best path and word beam search decoding then providing a predicted result of size that might vary based on the actual size of the predicted word
Caution: This project waits for further modification since some of the implementation is inefficient and incomplete. For instance, the customed model has no ['accuracy'] metrics implemented due to the fact that keras.model.compile() metrics accuracy compares the output with input by looking at the word as a whole part. If even one single character within the word is predicted wrong, the accuracy will be zero. Please wait for further update for better performances which will turn this pipeline into a machine that can solve real life handwriting recognition problem.
## File Desciption
### Two Dictionary python files:
These two function return two dictionary that will support the data preprocessing:
* Key = filename -> value = word. Sample: "a01-000u-00-00.png" -> "A" (String -> String)
* Key = character -> value = integer representation. Sample: "A" -> 7 (String -> int)
The integer representation will vary each time the function compile
### Data_Preprocessing.py:
Iterate through words/ directory and transforming them into shape of 32x128 grayscale images and then turn them into numpy arrays which will be stored in TrainX and TestX numpy arrays. After finding the corresponding word of a image through the first dictionary, iterate through every single character and turn them into integer representation and store them in an array of fixed size of length of 32 by looking into the second dictionary. For example: "a01-000u-00-00.png" -> "A" -> [7,0,0,0,...,0].
### Loading_Normalize.py:
As we know a color activation can vary from 0 to 255. For easy training purposes, we transform each pixel from range 255 to range 1 in float type.
### HWTRModel.py and Model_Evaluation.py:
The first python file consists of the model described in introduction and customed method including fit(), predict(), summary(), compile() and most importantly the custom_ctc_loss_function() that return the loss in model compiling. Model_Evaluation will initiate the model, train the model and save the model.
Model saved can be used for prediction already but user have to write a python file to load the model locally since this project is yet incompleted.
### main.py:
run python main.py and you are ready to go.
## Future goals:
* Custom accuracy metrics
* Improve accuracy by adding epochs, dropout, data augmentation, shifting optimizer
* Adding Validation dataset and K-fold cross validation feature to check overfitting intensity
## References:
\[1\] [IAM Handwriting Database](http://www.fki.inf.unibe.ch/databases/iam-handwriting-database)
\[2\] [Sequence Modeling with CTC](https://distill.pub/2017/ctc/)
\[3\] [CTC Model](https://github.com/ysoullard/CTCModel)
\[4\] [Simple HTR](https://github.com/githubharald/SimpleHTR)
<file_sep>/HWTRModel.py
# Filename: HWTRModel.py
# Author: <NAME> <<EMAIL>>
# Description: A (very basic) handwriting transcription module.
import os
import numpy as np
import tensorflow as tf
from contextlib import redirect_stdout
from tensorflow.keras import backend as K
from tensorflow.keras import Model
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.utils import Progbar
from tensorflow.keras.callbacks import CSVLogger, TensorBoard, ModelCheckpoint
from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
from tensorflow.keras.constraints import MaxNorm
from tensorflow.keras.layers import Conv2D, Bidirectional, LSTM, Dense
from tensorflow.keras.layers import Input, MaxPooling2D, Reshape
class HWTRModel:
def __init__(self,input_dims,universe_of_discourse):
self.input_dims = input_dims
self.universe_of_discourse = universe_of_discourse
self.nn = hwtr
# These are to use the ctc decode functionality outlined at:
# https://www.tensorflow.org/api_docs/python/tf/keras/backend/ctc_decode
self.beam_width = 10
self.top_paths = 1
self.greedy = False
self.model = None
def summary(self):
return self.model.summary()
def compile(self, learning_rate=None):
'''
Override defined tf compile.
'''
outs = self.nn(self.input_dims, self.universe_of_discourse, learning_rate)
inputs, outputs, optimizer = outs
# create and compile
self.model = Model(inputs=inputs, outputs=outputs)
self.model.compile(optimizer=optimizer, loss=HWTRModel.custom_ctc_loss_function, metrics=['accuracy'])
def predict(self,x_val,batch_size=32,verbose=0,steps=1,callbacks=None,max_queue_size=10,
workers=1,
decode_using_ctc=True):
'''
Custom predict definition
'''
out = self.model.predict(x=x_val, batch_size=batch_size, verbose=verbose, steps=steps,
callbacks=callbacks, max_queue_size=max_queue_size)
if not decode_using_ctc:
# Return negative log probabilities if decoding is not desired.
return np.log(out)
steps_done = 0
batch_size = int(np.ceil(len(out) / steps))
input_length = len(max(out, key=len))
prediction, probabilities = [], []
while steps_done < steps:
index = steps_done * batch_size
until = index + batch_size
x_test = np.asarray(out[index:until])
x_test_len = np.asarray([input_length for _ in range(len(x_test))])
# See: https://www.tensorflow.org/api_docs/python/tf/keras/backend/ctc_decode
decode, log = tf.keras.backend.ctc_decode(np.asarray(out[index:until]),np.asarray([input_length for _ in range(len(x_test))]),
greedy=self.greedy,beam_width=self.beam_width,top_paths=self.top_paths)
probabilities.extend([np.exp(r) for r in log])
decode = [[[int(p) for p in x if p != -1] for x in y] for y in decode]
prediction.extend(np.swapaxes(decode, 0, 1))
steps_done += 1
return (prediction, probabilities)
def fit(self, x,
y,
batch_size=32,
epochs=1,
verbose=1,
callbacks=None,
validation_split=0.0,
validation_data=None,
shuffle=False,
class_weight=None,
sample_weight=None,
initial_epoch=0,
steps_per_epoch=None,
validation_steps=None,
validation_batch_size=None,
validation_freq=1,
max_queue_size=10,
workers=1,
use_multiprocessing=False):
self.model.fit(x,y, verbose = verbose)
def evaluate(self,
x,
y,
batch_size=32,
verbose=1,
sample_weight=None,
steps=None,
callbacks=None,
max_queue_size=10,
workers=1,
use_multiprocessing=False,
return_dict=False,
):
return self.model.evaluate(x, y, verbose = verbose)
def save(self,filepath,
overwrite=True,
include_optimizer=True,
save_format=None,
signatures=None,
options=None):
self.model.save(filepath = filepath)
def custom_ctc_loss_function(y_true, y_pred, *kwargs):
'''
CTC loss computation. Borrowed from the CTCModel.py file
with minor modifications.
'''
if len(y_true.shape) > 2:
y_true = tf.squeeze(y_true)
input_length = tf.math.reduce_sum(y_pred, axis=-1, keepdims=False)
input_length = tf.math.reduce_sum(input_length, axis=-1, keepdims=True)
label_length = tf.math.count_nonzero(y_true, axis=-1, keepdims=True, dtype="int64")
loss = tf.keras.backend.ctc_batch_cost(y_true, y_pred, input_length, label_length)
loss = tf.reduce_mean(loss)
return loss
def hwtr(input_dims, d_model, learning_rate):
'''
HWTR pipeline definition.
Copied from the original definition in Draft.py
'''
input_data = Input(name="input", shape=input_dims)
cnn = Reshape((input_dims[0] // 2, input_dims[1] // 2, input_dims[2] * 4))(input_data)
cnn = Conv2D(filters=32, kernel_size=5, activation = 'relu', strides=1, padding="same")(input_data)
cnn = Conv2D(filters=32, kernel_size=5, activation = 'relu',strides=1, padding="same")(cnn)
cnn = Conv2D(filters=32, kernel_size=5, activation = 'relu',strides=1, padding="same")(cnn)
cnn = Conv2D(filters=32, kernel_size=5, activation = 'relu',strides=1, padding="same")(cnn)
cnn = Conv2D(filters=64, kernel_size=3, activation = 'relu',strides=1, padding="same")(cnn)
cnn = Conv2D(filters=64, kernel_size=3, activation = 'relu',strides=1, padding="same")(cnn)
cnn = Conv2D(filters=8, kernel_size=3, activation = 'relu',strides=1, padding="same")(cnn)
cnn = MaxPooling2D(pool_size=(2,2), strides=2, padding="valid")(cnn)
reshape = Reshape((32,256))(cnn)
rnn = Bidirectional(LSTM(256, input_shape = (32, 256), activation = 'relu', return_sequences=True))(reshape)
rnn = Bidirectional(LSTM(256, activation = 'relu', return_sequences=True))(rnn)
rnn = Bidirectional(LSTM(32, activation = 'relu', return_sequences=True))(rnn)
rnn = Bidirectional(LSTM(80, activation = 'relu', return_sequences=True))(rnn)
output_data = Dense(units=d_model, activation="softmax", name="lstm_output_matrix")(rnn)
optimizer = RMSprop(learning_rate=learning_rate)
return (input_data, output_data, optimizer)
<file_sep>/Model_Evaluation.py
import HWTRModel as ht
from numpy import std, mean
def summarize_performance(scores):
print("Accuracy: mean=%.3f std=%.3f, n=%d" % (mean(scores)*100, std(scores)*100, len(scores)))
#pyplot.boxplot(scores)
#pyplot.show()
def eval_model(x_train, y_train, x_test, y_test):
scores = list()
model = ht.HWTRModel(input_dims=(32,128,1), universe_of_discourse=80)
model.compile(learning_rate=0.001)
model.fit(x_train, y_train)
#model.save("final_model.h5")
#pred,_ = model.predict(x_test, decode_using_ctc=True)
#print(pred)
_, acc = model.evaluate(x_test, y_test, verbose=1)
scores.append(acc)
summarize_performance(scores)
<file_sep>/Characters_Dictionary.py
def Dict():
Path = "words.txt"
Dictionary = dict()
Representation = 1
with open(Path) as f:
contents = f.readlines()
len_of_contents = len(contents)
for i in range(len_of_contents):
contents[i] = contents[i].split()[-1]
for j in contents:
for k in j:
if k in Dictionary:
None
else:
Dictionary[k] = Representation
Representation += 1
Dictionary[' '] = 79
Dictionary[None] = 80
return Dictionary
<file_sep>/Data_preprocessing.py
from Characters_Dictionary import Dict
from Filename_To_Words_Dictionary import DictY
from os import listdir
from tensorflow.keras.preprocessing.image import load_img
from tensorflow.keras.preprocessing.image import img_to_array
from numpy import save, asarray
from random import random
def prepare_data():
D1, D2 = Dict(), DictY()
directory = "words/"
TrainX, TrainY, TestX, TestY= list(), list(), list(), list()
for sub1 in listdir(directory):
for sub2 in listdir(directory + sub1 + '/'):
for files in listdir(directory + sub1 + '/' + sub2 + '/'):
path = directory + sub1 + '/' + sub2 + '/' + files
filename = files[:-4]
photo = load_img(path,color_mode="grayscale", target_size=(32, 128))
photo = img_to_array(photo)
word_corresponding = D2.get(filename)
label = [0] *32
for i in range(len(word_corresponding)):
label[i] = D1.get(word_corresponding[i])
label = asarray(label)
if random()<0.5:
TestX.append(photo)
TestY.append(label)
else:
TrainX.append(photo)
TrainY.append(label)
TrainSample = asarray(TrainX)
#print(type(TrainSample))
#print(TrainSample)
TrainLabel = asarray(TrainY)
#print(type(TrainLabel))
#print(TrainLabel)
TestSample = asarray(TestX)
TestLabel = asarray(TestY)
'''
print(TrainSample.shape, TrainLabel.shape)
print(TestSample.shape, TestLabel.shape)
save('32x128_GrayscaleTrS.npy', TrainSample)
save('32x128_GrayscaleTrL.npy', TrainLabel)
save('32x128_GrayscaleTeS.npy', TestSample)
save('32x128_GrayscaleTeL.npy', TestLabel)
'''
return TrainSample, TrainLabel, TestSample, TestLabel
<file_sep>/Loading_and_Normalize.py
import numpy as np
def normalize_pixels(train, test):
train_scale = train.astype('float32')
test_scale = test.astype('float32')
train_scale = train_scale / 255.0
test_scale = test_scale / 255.0
return train_scale, test_scale
<file_sep>/Filename_To_Words_Dictionary.py
def DictY():
Path = "words.txt"
dic = dict()
with open(Path) as f:
content = f.readlines()
length = len(content)
for i in range(length):
content[i] = content[i].split()
for i in range(len(content)):
dic[content[i][0]] = content[i][-1]
return dic
|
aeee64081d1b5dcca139c039c95cff155fcaf95f
|
[
"Markdown",
"Python"
] | 8
|
Python
|
ZhaoguoZhu/IAM_Handwriting_Recognition
|
7820022c865befaeb6ad17cb28b2b6973eeccbeb
|
aadcdec1e020c557a2b2e7c574684c216b0d3412
|
refs/heads/master
|
<repo_name>A-Lawrence-Reynolds/webapi-challenge<file_sep>/projects/projectRouter.js
const db = require(`../data/helpers/projectModel`);
const dbTwo = require(`../data/helpers/actionModel`);
const router = require("express").Router();
router.get(`/`, (req, res) => {
db.get()
.then(projects => {
res.status(200).json(projects);
})
.catch(err => {
console.log("error", err);
res
.status(500)
.json({ error: "The projects information could not be retrieved." });
});
});
router.get(`/:id`, (req, res) => {
const id = req.params.id;
db.get(id)
.then(project => {
res.status(200).json(project);
})
.catch(err => {
console.log("error", err);
res
.status(500)
.json({ error: "The project information could not be retrieved." });
});
});
router.post(`/`, (req, res) => {
db.insert(req.body)
.then(newPost => {
res.status(200).json(newPost);
})
.catch(err => {
console.log("error", err);
res
.status(500)
.json({ error: "The projects information could not be added." });
});
});
router.put(`/:id`, (req, res) => {
const update = req.body;
const overwrite = req.params.id;
db.update(overwrite, update)
.then(updatedProject => {
res.status(200).json(updatedProject);
})
.catch(err => {
console.log("error", err);
res
.status(500)
.json({ error: "The projects information could not be updated." });
});
});
router.delete(`/:id`, (req, res) => {
const id = req.params.id;
db.remove(id)
.then(removed => {
res.status(200).json(removed);
})
.catch(err => {
console.log("error", err);
res
.status(500)
.json({ error: "The projects information could not be deleted." });
});
});
router.get(`/:id/actions`, (req, res) => {
const id = req.params.id;
db.getProjectActions(id)
.then(projectActions => {
res.status(200).json(projectActions);
})
.catch(err => {
console.log("error", err);
res
.status(500)
.json({ error: "The projects actions could not be retrieved." });
});
});
router.post(`/:id/actions`, (req, res) => {
dbTwo
.insert(req.body)
.then(newAction => {
res.status(200).json(newAction);
})
.catch(err => {
console.log("error", err);
res
.status(500)
.json({ error: "The actions information could not be created." });
});
});
module.exports = router;
|
f0c28f5efa6e43d5ee98287d311ad20f129169d3
|
[
"JavaScript"
] | 1
|
JavaScript
|
A-Lawrence-Reynolds/webapi-challenge
|
cd73221f0b06e7b59fb6c3c0a8ae1032b0cc23fe
|
17a1efbb702826f95d91bc070ab9d64f9392452a
|
refs/heads/master
|
<repo_name>JasonHarrer/PythonFun_FuncsIntermediateI<file_sep>/randint.py
import random
def randInt(min=0, max=100):
# if min > max in any situation, we will swap them.
if(min > max):
return round(random.random() * (min - max) + max)
return round(random.random() * (max - min) + min)
print(randInt())
print(randInt(max=50))
print(randInt(min=50))
print(randInt(min=50, max=500))
print(randInt(min=150, max=25))
print(randInt(min=-14, max=-7))
print(randInt(max=-12))
print(randInt(12, 12))
|
da0e4dde06ec2a0047220088f7a9bb8091e26d44
|
[
"Python"
] | 1
|
Python
|
JasonHarrer/PythonFun_FuncsIntermediateI
|
874f6dd3ea7cf5a76e01dc51e4c2cc04bfce9225
|
3db7a564b0a7f721b81703d5674bd52e8b03c117
|
refs/heads/master
|
<file_sep>CREATE DATABASE testdb
CREATE TABLE user({
usid SERIAL PRIMARY KEY,
fname name,
mname name,
lname name,
email varchar,
phone bigint,
"role" varchar,
"address" varchar,
editable boolean,
})<file_sep>import { Router } from 'express';
import { getUser, createUser, updateUser, deleteUser} from '../controllers/users'
const router = Router();
router.get('/', getUser);
router.post('/', createUser);
router.patch('/:id', updateUser);
router.delete('/:id', deleteUser);
export default router;
<file_sep>import { RequestHandler } from 'express';
import { userlist } from '../assets/constant/users'
import { pool } from '../database/db'
export const createUser: RequestHandler = async function(req, res, next) {
try {
if( ['fname', 'mname', 'lname', 'email', 'phone', 'role', 'address'].every(el => el in req.body && req.body[el]) ) {
if( !req.body.hasOwnProperty('editable') ) req.body['editable'] = false;
// req.body['id'] = Math.floor(Math.random() * Date.now())
// userlist.push(req.body);
const { fname, mname, lname, email, phone, role, address} = req.body;
const newUser = await pool.query(
"INSERT INTO userr(fname,lname, mname, role, address,email, phone) VALUES($1, $2, $3, $4, $5, $6, $7) RETURNING *",
[ fname,lname, mname, role, address,email, phone]);
console.log( newUser.rows)
// if(newUser && newUser.user.rows)
res.status(200).send({msg: 'User Created', users: newUser.rows});
// res.status(404).send({msg: 'User Created', users: newUser});
} else {
res.status(400).send({msg: 'Bad Request'})
}
} catch (error) {
console.error(error);
res.status(500).send({msg: error})
}
}
export const getUser: RequestHandler = async function(req, res, next) {
try {
// userlist.map((el:any) => {
// el['id'] = Math.floor(Math.random() * Date.now())
// });
const newUser = await pool.query(
"SELECT * FROM userr"
)
res.status(200).send({users: newUser.rows});
} catch (error) {
console.error(error);
res.status(500).send({msg: error})
}
}
export const updateUser: RequestHandler = function(req, res, next) {
if(req.params.id ) {
let isUpdated: boolean = false;
userlist.map((el:any, i) => {
if(el.id == +req.params.id) {
for(let key in req.body) {
el[key] = req.body[key]
}
isUpdated = true;
}
});
isUpdated ? res.status(200).send({users: userlist}) : res.status(404).send({msg: "Resource not found"})
} else {
res.status(400).send({msg: 'Bad Request'})
}
}
export const deleteUser: RequestHandler = function(req, res, next) {
if(req.params.id ) {
let isDeleted: boolean = false;
userlist.map((el:any, i) => {
if(el.id == +req.params.id) {
userlist.splice(i, 1);
isDeleted = true;
}
});
isDeleted ? res.status(200).send({users: userlist}) : res.status(404).send({msg: "Resource not found"})
} else {
res.status(400).send({msg: 'Bad Request'})
}
}<file_sep>import express, { Request, Response, NextFunction} from 'express';
import cors from 'cors';
import { Sequelize } from 'sequelize'
import userRoutes from './routes/users'
const app = express();
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }))
app.use('/users', userRoutes);
database: "testdb"
const sequelize = new Sequelize('testdb', 'postgres', '<PASSWORD>',
{
host: 'localhost',
dialect: 'postgres',
port: 5432
})
sequelize.authenticate().then(() => {
console.log('Connection has been established successfully.')
}).catch(err => {
console.error('Unable to connect to the database:', err)
})
// sequelize.sync({ alter: true })
/* .then(function (instance) {
return instance.updateAttributes({ syncedAt: sequelize.fn('NOW') })
}) */
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
res.status(500).json({ msg: err.message })
})
app.listen(5000);<file_sep>export const userlist = [
{
"fname": "Aman",
"mname": "Kumar",
"lname": "Gupta",
"email": "<EMAIL>",
"phone": 9170026480,
"role": "IT",
"address": "Noida",
"editable": false
},
{
"fname": "Kamal",
"mname": "Kant",
"lname": "Gautam",
"email": "<EMAIL>",
"phone": 9170026480,
"role": "QA",
"address": "Mohali",
"editable": false
},
{
"fname": "Mahesh",
"mname": "Kumar",
"lname": "Sharma",
"email": "<EMAIL>",
"phone": 9695026480,
"role": "Apps",
"address": "Noida",
"editable": false
},
{
"fname": "Ram",
"mname": "Lal",
"lname": "Singh",
"email": "<EMAIL>",
"phone": 7905026480,
"role": "Finance",
"address": "Mohali",
"editable": false
},
{
"fname": "Manoj",
"mname": "Singh",
"lname": "Arya",
"email": "<EMAIL>",
"phone": 9612026480,
"role": "HR",
"address": "Noida",
"editable": false
}
]
|
6943d26e4cd6bbdcb6801b1c2064c8ab79556d3c
|
[
"SQL",
"TypeScript"
] | 5
|
SQL
|
iharshks/assignment-backend
|
270f943973beb8116571d9bd435643a6ce791791
|
dfe95f86f19ed18861cd33d632a52fbce9e49b0f
|
refs/heads/master
|
<repo_name>donMichaelL/hello-docker<file_sep>/mqtt_client.py
import time
import paho.mqtt.publish as publish
print "That's One Small Step For Man, One giant Leap for Mankind"
# for i in range(0, 10):
# print i
# publish.single("airsoul", "%s This is a new Message" %(i), hostname="172.16.17.32",
# port=1883, client_id="", keepalive=60, will=None, auth=None, tls=None)
# time.sleep(1)
<file_sep>/Dockerfile
FROM resin/rpi-raspbian:wheezy
RUN apt-get update && apt-get install -y \
python2.7 python-dev python-pip
RUN pip install paho-mqtt
COPY . /app
CMD ["python", "/app/mqtt_client.py"]
|
21a4a3919154798970cf1f55574c2ad49eedb6da
|
[
"Python",
"Dockerfile"
] | 2
|
Python
|
donMichaelL/hello-docker
|
bd9737439a2f6e2b44dddcd6c5d64d84e2130e1f
|
5e181fcfbe2fa18ecc24f8a4998b203918bb9f66
|
refs/heads/master
|
<file_sep>console.log('I am working')
// Use document.querySelector to grab a DOM Node (HTML Element)
const headerText = document.querySelector('.title')
//.innerText controls the text displayed by the element
headerText.innerText = '<NAME>'
//.style allows you to set the style attribute directly
headerText.style = 'color: red; text-decoration: underline;'
//You can also dig in to set specific style properties.
//These are seen as inline styles so they override anything in your linked .css file
headerText.style.fontSize = '16px'
headerText.style.fontSize = '32px'
//.classList gives you a list of all classes assigned to that element.
//You can access .add, .remove, and .toggle methods to modify this list
headerText.classList.add('dark-mode')
// const dynamicDiv = document.getElementById('dynamic-div')
//You can set innerHtml directly as well
// dynamicDiv.innerHTML = `
// <ul>
// <li>One</li>
// <li>Two</li>
// <li>Three</li>
// </ul>
// `
const storyButton = document.getElementById('story-button')
const availableColors = ['red', 'blue', 'rebeccapurple', 'orange', 'tomato']
function changeColor(e) {
//Default behavior of a form tag is to reload the page, this prevents that
e.preventDefault()
//This prevents the event from bubbling up the DOM
e.stopPropagation()
console.log('I got clicked')
const content = document.querySelector('.content-hold')
const colorInput = document.getElementById('color-input')
//When we access an input element, we can access the .value property to check what has been typed into the element
//In this case we are checking if our input matches one of the available colors defined above.
if (availableColors.includes(colorInput.value)) {
//If what the user typed in is an available color, we set the background css property of our content div to be what they typed in.
content.style.background = colorInput.value
} else {
alert('Invalid color')
}
colorInput.value = ''
}
//This is how we connect our button to the changeColor function
//.addEventListener takes two arguments: the event we want to listen for and a callback function to be invoked when the event happens
storyButton.addEventListener('click', changeColor)
const content = document.querySelector('.story-hold')
content.addEventListener('click', () => {
console.log('CLICKED ON CONTENT HOLD')
})
// storyButton.addEventListener('mouseenter', () => {
// console.log('The mouse entered')
// })
document.getElementById('part-button').addEventListener('click', (e) => {
e.stopPropagation()
const input = document.getElementById('part-input')
//We first check if the user has typed anything into our input box
if (input.value) {
//We use .createElement to make a new <li> element and then assign it various attributes
const newLi = document.createElement('li')
//We set the innerText to match what the user types
newLi.innerText = input.value
//We give the option to delete an item that the user created by double clicking on it
newLi.addEventListener('dblclick', () => {
console.log(newLi.parentNode)
newLi.remove()
})
//We need a place to put our <li> so we grab the <ol> with an id of part-list
const list = document.getElementById('part-list')
//We use the .appendChild method to attach our <li> as a child of the <ol>
list.appendChild(newLi)
//This resets the value of the input box
input.value = ''
// This relates to the next part, we first check if an empty field notification has been previously displayed
// If it has we remove it
const notification = document.getElementById('empty-field-notification')
if (notification) {
notification.remove()
}
} else {
// We want to give some feedback if the user has not typed anything in.
// We first check if the notification has already been displayed
const notification = document.getElementById('empty-field-notification')
// If it has not, we go about creating a new one
if (!notification) {
// We use .createElement to make a new <p>
const newP = document.createElement('p')
// We set the .innerText to reflect what we want the notification to say
newP.innerText = 'Please input a story'
// We give it a class of .notification (this has already been set up in our .css file)
newP.classList.add('notification')
// We also assign it an id of empty-field-notification so we can easily find it later.
newP.setAttribute('id', 'empty-field-notification')
// We need a place to put our notification so we grab the container and then append our notification to it.
const container = document.querySelector('.part-form')
container.appendChild(newP)
}
}
console.log('YOU CLICKED THE THING GOOD JOB')
})
|
c9fdd0038e5b067e425b98dda2448e83a92be83b
|
[
"JavaScript"
] | 1
|
JavaScript
|
dm-wr4/javascript-4-lecture
|
9a511200bdbba3ae7c131935924fbd65c7e63ebe
|
5ee1956dcaa69e503f75fcfe2d7b048ae1105f96
|
refs/heads/master
|
<repo_name>berkantoptas/BBM104-Interface<file_sep>/Appointment.java
import java.util.Date;
public class Appointment
{
public int appointmentID;
public int duration;
public Date appointmentDate = new Date();
public int userID1;
public int userID2;
}
<file_sep>/User.java
public class User
{
public int userID;
public String userName;
}
<file_sep>/README.md
# BBM104-Interface
Hacettepe University Computer Engineering BBM104 - Fourth Assignment
#2. Software Using Documentation
##2.1. Software Usage
Program starts “Main.java” class. The input file is given as an argument. input.txt file is the our argument file.(args[0]=input.txt)
##2.2. Error Messages
Program doesn’t have any error messages. Because advisors said that not give wrong input.
#3.Software Design Notes
##3.1. Desctiption of the program
###3.1.1. Problem
In this experiment, I am expected to develop a dedicated Agenda application, like Google Calendar or other popular calendar applications. Agenda system consist of users, professional meetings, personal or professional appointments, resting time activities such as attending events or courses. There will be saving, arranging, attending, cancelling and listing commands in the Agenda system.
##3.2. System Chart
Input : input.txt
Programs : Main.java
App.java
Anniversary.java
Birthday.java
Meeting.java
Appointment.java
Event.java
Concert.java
Theater.java
Sport.java
Course.java
User.java
NotFoundException.java
DuplicatedIDException.java
Output : output.txt
##3.3. Algorithm
1. Program takes 1 argument (args[0]=input.txt)
2. Call runApp function with argument.
2.1. By calling runApp function input.txt file will read and parse.
2.1.1 Also by calling runApp function there will be create output.txt.
##REFERENCES
http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/
https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
http://www.mkyong.com/java/java-date-and-calendar-examples/
Lecture notes of BBM102 http://web.cs.hacettepe.edu.tr/~bbm102/
http://stackoverflow.com/
|
18760d3a68c3f49371d7ae4d534ab2f1cfcff190
|
[
"Markdown",
"Java"
] | 3
|
Java
|
berkantoptas/BBM104-Interface
|
b0f9b454bb9fc2ffeddbf4dbbb14e37edf4dc728
|
e72d6bb6f1fb2ee3517a36595e75a698fb5e46b0
|
refs/heads/master
|
<file_sep><?php
/**
* 40/40 Prayer Vigil Widget.
*
* This contains the widget code for the 40/40 Prayer Vigil plug-in.
*
* @author <NAME> <<EMAIL>>
* @package FortyFortyPlugin
* @version $Id: 4040-widget.php 566175 2012-07-01 20:01:05Z danielsummers $
*/
class FortyForty_Widget extends WP_Widget {
/**
* Constructor.
*/
public function __construct() {
parent::__construct( '4040_widget', 'FortyForty_Widget',
array( description => __( "Displays the current day or hour's prayer guide", 'fortyforty_plugin' ) ) );
}
/**
* Display the widget.
*
* @see WP_Widget::widget()
*
* @param array $args Widget arguments
* @param array $instance Options from the database
*/
public function widget( $args, $instance ) {
// If the guide is blank, do not display this widget.
$fortyForty = new FortyForty();
$guide = $fortyForty->PrayerGuide();
if ( empty( $guide ) )
return;
$title = apply_filters( 'widget_title', $instance[ 'title' ] );
echo $args [ 'before_widget' ];
if ( ! empty( $title ) )
echo $args [ 'before_title' ] . $title . $args[ 'after_title' ];
echo $guide . $args [ 'after_widget' ];
}
/**
* Update the widget's options.
*
* @see WP_Widget::update()
*
* @param array $new_instance The new values being updated
* @param array $old_instance The previous values
*/
public function update( $new_instance, $old_instance ) {
return array( title => strip_tags( $new_instance[ 'title' ] ) );
}
/**
* Display a form to update the widget's options.
*
* @see WP_Widget::form()
*
* @param array $instance The previous values for this widget
*/
public function form( $instance ) {
$title = ( isset( $instance[ 'title' ] ) )
? $instance[ 'title' ]
: __( '40/40 Prayer Vigil', 'fortyforty_plugin' ); ?>
<p>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>"
name="<?php echo $this->get_field_name( 'title' ); ?>" type="text"
value="<?php echo esc_attr( $title ); ?>" />
</p><?php
}
}
add_action( 'widgets_init', create_function( '', 'register_widget( "FortyForty_widget" );' ) );
<file_sep><?php
/**
* 40/40 Prayer Vigil - Main Logic.
*
* This class contains the guts of the plug-in. You should not need to edit this file.
*
* @author <NAME> <<EMAIL>>
* @package FortyFortyPlugin
* @version $Id: 4040-class.php 566175 2012-07-01 20:01:05Z danielsummers $
*/
class FortyForty {
/** Version. */
const FORTYFORTY_VERSION = '2012.0';
/** Web service URL home. */
const URL_HOME = 'http://services.djs-consulting.com/FortyForty';
//
// Plugin options
//
const PLUGIN_OPTION_SET = 'fortyforty_prayer_vigil';
const YEAR = 'year';
const LANGUAGE = 'language';
const SCRIPTURE_VERSION = 'scripture_version';
const TYPE = 'type';
const OVERLAP = 'overlap';
const DEBUG_DATE = 'debug_date';
const DEBUG_NUMBER = 'debug_number';
const PLUGIN_VERSION = 'version';
/** @var mixed $_options Option Array. */
private $_options = '';
//
// Cache
//
const CACHE_OPTION_SET = 'fortyforty_cache';
const CACHE_DATE = 'date';
const CACHE_NUMBER = 'number';
const CACHE_CONTENT = 'content';
/** @var mixed $_cache Cache Array. */
private $_cache = '';
/**
* Gets or sets the year for the prayer guide.
*
* @param string $year The year to set (optional).
* @return mixed The year for the prayer guide (get) or the current instance (set).
*/
public function Year( $year = '--' ) {
if ( '--' == $year ) return $this->_options[ FortyForty::YEAR ];
$this->_options[ FortyForty::YEAR ] = $year; return $this;
}
/**
* Gets or sets the language for the prayer guide.
*
* @param string $language The language to set (optional).
* @return mixed The language for the prayer guide (get) or the current instance (set).
*/
public function Language( $language = '--' ) {
if ( '--' == $language ) return $this->_options[ FortyForty::LANGUAGE ];
$this->_options[ FortyForty::LANGUAGE ] = $language; return $this;
}
/**
* Gets or sets the Scripture version for the prayer guide.
*
* @param string $version The Scripture version to set (optional).
* @return mixed The Scripture version for the prayer guide (get) or the current instance (set).
*/
public function ScriptureVersion( $version = '--' ) {
if ( '--' == $version ) return $this->_options[ FortyForty::SCRIPTURE_VERSION ];
$this->_options[ FortyForty::SCRIPTURE_VERSION ] = $version; return $this;
}
/**
* Gets or sets the type (hour or day) for the prayer guide.
*
* @param string $type The type to set (optional).
* @return mixed The type for the prayer guide (get) or the current instance (set).
*/
public function Type( $type = '--' ) {
if ( '--' == $type ) return $this->_options[ FortyForty::TYPE ];
$this->_options[ FortyForty::TYPE ] = $type; return $this;
}
/**
* Gets or sets the overlap period where the plugin will show content.
*
* @param string $overlap The overlap to set (optional).
* @return mixed The overlap in days (get) or the current instance (set).
*/
public function Overlap( $overlap = '--' ) {
if ( '--' == $overlap ) return $this->_options[ FortyForty::OVERLAP ];
$this->_options[ FortyForty::OVERLAP ] = $overlap; return $this;
}
/**
* Gets or sets the date that the plugin is forced to display (used for debugging).
*
* @param string $debugDate The debug date/time to set (optional).
* @return mixed The debug date (get) or the current instance (set).
*/
public function DebugDate( $debugDate = '--' ) {
if ( '--' == $debugDate ) return $this->_options[ FortyForty::DEBUG_DATE ];
$this->_options[ FortyForty::DEBUG_DATE ] = $debugDate; return $this;
}
/**
* Gets or sets the day/hour number that the plugin is forced to display (used for debugging).
*
* @param string $debugNumber The debug number to set (optional).
* @return mixed The debug number (get) or the current instance (set).
*/
public function DebugNumber( $debugNumber = '--' ) {
if ( '--' == $debugNumber ) return $this->_options[ FortyForty::DEBUG_NUMBER ];
$this->_options[ FortyForty::DEBUG_NUMBER ] = $debugNumber; return $this;
}
/**
* Gets or sets the version of this plugin.
*
* @param string $version The version to set (optional).
* @param mixed The version of the plugin (get) or the current instance (set).
*/
public function Version( $version = '--' ) {
if ( '--'== $version ) return $this->_options[ FortyForty::PLUGIN_VERSION ];
$this->_options[ FortyForty::PLUGIN_VERSION ] = $version; return $this;
}
/**
* FortyForty Constructor.
*
* @return FortyForty A FortyForty object properly initialized.
*/
public function __construct() {
// Determine if we've already obtained today's date.
$this->_options = get_option( FortyForty::PLUGIN_OPTION_SET );
if ( '' == $this->_options ) {
// New installation - add the options
$this->_options = array();
$this->Year ( '2012' )
->Language ( 'en' )
->ScriptureVersion ( 'hcsb' )
->Type ( 'day' )
->Overlap ( '30' )
->DebugDate ( '' )
->DebugNumber ( '' )
->Version ( FortyForty::FORTYFORTY_VERSION );
update_option( FortyForty::PLUGIN_OPTION_SET, $this->_options );
}
// Populate the cache.
$this->_cache = get_option( FortyForty::CACHE_OPTION_SET );
}
/**
* Display the prayer guide.
*
* @return string The text of the prayer guide.
*/
public function PrayerGuide() {
$guideDateTime = $this->GetCurrentDateTime();
if ( ! $this->IsWithinRange( $guideDateTime ) ) {
return '';
}
if ( is_array( $this->_cache ) && $this->_cache[ FortyForty::CACHE_DATE ] == $guideDateTime )
return $this->_cache[ FortyForty::CACHE_CONTENT ];
$guideNumber = $this->GetNumber( $guideDateTime );
if ( is_array ($this->_cache ) && $this->_cache[ FortyForty::CACHE_NUMBER ] == $guideNumber )
return $this->_cache[ FortyForty::CACHE_CONTENT ];
$content = $this->HttpGet( sprintf( '/PrayerGuide/html/%s/%s/%s/%s/%s', $this->Year(), $this->Language(),
strtoupper( $this->ScriptureVersion() ), $this->Type(), $guideNumber ) );
$this->_cache = array(
FortyForty::CACHE_DATE => $guideDateTime,
FortyForty::CACHE_NUMBER => $guideNumber,
FortyForty::CACHE_CONTENT => $content);
update_option( FortyForty::CACHE_OPTION_SET, $this->_cache );
return $content;
}
/**
* Get the current date/time.
*
* @return string The date or date/time for the prayer guide.
*/
private function GetCurrentDateTime() {
if ( ! empty( $this->_options[ FortyForty::DEBUG_DATE ] ) )
return $this->DebugDate();
$currentTime = new DateTime( current_time( 'mysql' ) );
return ( 'hour' == $this->Type() )
? $currentTime->format( 'Y-m-d H:00:00' )
: $currentTime->format( 'Y-m-d' );
}
/**
* Is the current date/time within the range to display?
*
* @param string $guideDateTime The guide date/time.
* @return boolean True if the date is within the display range, false if not.
*/
private function IsWithinRange( $guideDateTime ) {
// If we have a guide number forced, we're in the range.
if ( ! empty( $this->_options[ FortyForty::DEBUG_NUMBER ] ) )
return true;
$startDate = ( 'hour' == $this->Type() ) ? new DateTime( '2012-11-02' ) : new DateTime( '2012-09-26' );
$startRange = $startDate->sub( DateInterval::createFromDateString( sprintf( '%s days', $this->Overlap() ) ) );
$endDate = new DateTime( '2012-11-04' );
$endRange = $endDate->add( DateInterval::createFromDateString( sprintf( '%s days', $this->Overlap() ) ) );
$date = new DateTime( $guideDateTime );
return ( ( $date >= $startRange ) && ( $date <= $endRange ) );
}
/**
* Get the day or hour number for the date/time.
*
* @param string $guideDateTime The date or date/time for the prayer guide.
* @return string The number for the prayer guide.
*/
private function GetNumber( $guideDateTime ) {
if ( ! empty( $this->_options[ FortyForty::DEBUG_NUMBER ] ) )
return $this->DebugNumber();
return FortyForty::HttpGet( sprintf( '/Number/%s/%s', ucfirst( $this->Type() ), $guideDateTime ) );
}
/**
* Return the content of an HTTP GET request.
*
* @param string $url The request URL (not including the root URL).
* @return string The response.
*/
private static function HttpGet( $url ) {
return file_get_contents( FortyForty::URL_HOME . $url );
}
/**
* Get a list of options from the web service.
*
* @param string $url The URL for the option list.
* @param string $tag The XML tag for the option.
* @return array The options in id/value pairs.
*/
public static function GetOptionList( $url, $tag ) {
$doc = new DOMDocument();
$doc->loadXML(FortyForty::HttpGet( $url ) );
$optionList = array();
foreach ( $doc->getElementsByTagName( $tag ) as $elt )
$optionList[] = array(
'id' => ( '' == $elt->getAttribute("id") ) ? $elt->textContent : $elt->getAttribute( 'id' ),
'value' => $elt->textContent
);
return $optionList;
}
}<file_sep><?php
/*
Plugin Name: 40/40 Prayer Vigil
Plugin URI: http://techblog.djs-consulting.com/category/programming/wordpress/plug-ins
Description: Displays the daily or hourly prayer guides for the 40/40 Prayer Vigil or 40/40 Campaña de Oración.
Version: 2012.0
Author: <NAME>
Author URI: http://techblog.djs-consulting.com
This plug-in provides a widget to display either the daily or hourly prayer guides. For more information on the 40/40
Prayer Vigil, created by the Ethics and Religious Liberty Commission of the Southern Baptist Convention, see
http://erlc.com/4040.
*/
// Assemble the pieces to make one coherent plug-in.
$dir = dirname( __FILE__ );
require_once( $dir . '/4040-class.php' );
require_once( $dir . '/4040-widget.php' );
require_once( $dir . '/4040-options.php' );
<file_sep><?php
/**
* 40/40 Prayer Vigil - Settings Administration.
*
* This file contains the logic necessary to allow the user to configure their display of the prayer guides.
*
* @author <NAME> <<EMAIL>>
* @package FortyFortyPlugin
* @version $Id: 4040-options.php 566175 2012-07-01 20:01:05Z danielsummers $
*/
/**
* Register the 40/40 Prayer Vigil options page.
*/
function fortyforty_plugin_menu() {
add_options_page( __( '40/40 Prayer Vigil Options', 'fortyforty_plugin' ),
__( '40/40 Prayer Vigil', 'fortyforty_plugin' ), 'manage_options', '4040-prayer-vigil',
'fortyforty_plugin_options' );
}
/**
* Register the options with the settings API.
*/
function fortyforty_register_settings() {
$menuSlug = '4040-prayer-vigil';
$optionGroup = sprintf( '%s_main', FortyForty::PLUGIN_OPTION_SET );
register_setting( $menuSlug, FortyForty::PLUGIN_OPTION_SET, 'fortyforty_validate_options' );
add_settings_section( $optionGroup, __( 'Options', 'fortyforty_plugin' ), sprintf( '%s_text', $optionGroup ),
$menuSlug );
// Regular settings.
add_settings_field( FortyForty::YEAR, __( 'Year', 'fortyforty_plugin' ), 'fortyforty_option_year', $menuSlug,
$optionGroup );
add_settings_field( FortyForty::LANGUAGE, __( 'Language', 'fortyforty_plugin' ), 'fortyforty_option_language',
$menuSlug, $optionGroup );
add_settings_field( FortyForty::SCRIPTURE_VERSION, __( 'Scripture Version', 'fortyforty_plugin' ),
'fortyforty_option_scripture_version', $menuSlug, $optionGroup );
add_settings_field( FortyForty::TYPE, __( 'Prayer Guide Type', 'fortyforty_plugin' ), 'fortyforty_option_type',
$menuSlug, $optionGroup );
add_settings_field( FortyForty::OVERLAP, __( 'Days to Overlap', 'fortyforty_plugin' ), 'fortyforty_option_overlap',
$menuSlug, $optionGroup );
// Debugging settings.
$debugGroup = sprintf( '%s_debug', FortyForty::PLUGIN_OPTION_SET );
add_settings_section( $debugGroup, __( 'Debugging', 'fortyforty_plugin' ), sprintf( '%s_text', $debugGroup ),
$menuSlug );
add_settings_field( FortyForty::DEBUG_DATE, __( 'Force Date or Date/Time', 'fortyforty_plugin' ),
'fortyforty_option_debug_date', $menuSlug, $debugGroup );
add_settings_field( FortyForty::DEBUG_NUMBER, __( 'Force Day/Hour Number', 'fortyforty_plugin' ),
'fortyforty_option_debug_number', $menuSlug, $debugGroup );
}
add_action( 'admin_menu', 'fortyforty_plugin_menu' );
add_action( 'admin_init', 'fortyforty_register_settings' );
/**
* Handle the option administration for this plugin.
*/
function fortyforty_plugin_options() {
if ( !current_user_can( 'manage_options' ) ) {
wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
}
?>
<div class="wrap">
<h2><?php _e( '40/40 Prayer Vigil', 'fortyforty_plugin' ); ?></h2>
<form method="post" action="options.php"><?php
settings_fields( '4040-prayer-vigil' );
do_settings_sections( '4040-prayer-vigil' ); ?>
<br />
<?php submit_button(); ?>
<p>
<strong><?php _e( 'NOTE', 'fortyforty_plugin' ); ?>:</strong>
<?php _e( "The plugin caches the current day's or hour's results.", 'fortyforty_plugin' );
_e( 'To force a refresh, just save this page with no changes', 'fortyforty_plugin' ); ?>
</p>
<p>
<strong><?php _e( 'NOTE', 'fortyforty_plugin' ); ?>:</strong>
<?php _e( 'Invalid values in the form above will be silently translated to valid ones.', 'fortyforty_plugin' ); ?>
</p>
</form>
<p>
<small>
<?php _e( 'Version', 'fortyforty_plugin' ); ?>: <code><?php echo FortyForty::FORTYFORTY_VERSION; ?></code>
</small>
</p>
</div>
<?php
}
/**
* Text to display before the setting group.
*/
function fortyforty_prayer_vigil_main_text() {
// Nothing to say here...
}
/**
* Text to display before the debug setting group.
*/
function fortyforty_prayer_vigil_debug_text() {
echo '<p>';
_e( 'These options can be used to force a particular date/time or number to be displayed.', 'fortyforty_plugin' );
_e( 'If they are not valid, they will be blanked when the page is saved.', 'fortyforty_plugin' );
echo '<br />';
_e( '(The "Number" setting overrides the "Date/Time" setting.)', 'fortyforty_plugin' );
echo '</p>';
}
/**
* Display options for the YEAR setting.
*/
function fortyforty_option_year() {
fortyforty_option_dropdown( FortyForty::YEAR, FortyForty::GetOptionList( '/List/Year', 'year' ) );
}
/**
* Display options for the LANGUAGE setting.
*/
function fortyforty_option_language() {
fortyforty_option_dropdown( FortyForty::LANGUAGE, FortyForty::GetOptionList( '/List/Language', 'language' ) );
}
/**
* Display options for the SCRIPTURE_VERSION setting.
*/
function fortyforty_option_scripture_version() {
fortyforty_option_dropdown( FortyForty::SCRIPTURE_VERSION, FortyForty::GetOptionList( '/List/Version', 'version' ) );
}
/**
* Display options for the TYPE setting.
*/
function fortyforty_option_type() {
fortyforty_option_dropdown( FortyForty::TYPE, array(
array (
'id' => 'day',
'value' => 'Daily (40 Days)' ),
array(
'id' => 'hour',
'value' => 'Hourly (40 Hours)')
));
}
/**
* Display options for the OVERLAP setting.
*/
function fortyforty_option_overlap() {
fortyforty_option_input( FortyForty::OVERLAP, 2 );
}
/**
* Display options for the DEBUG_DATE setting.
*/
function fortyforty_option_debug_date() {
fortyforty_option_input(FortyForty::DEBUG_DATE, 20); ?> <code>YYYY-MM-DD</code> <?php
_e( 'or' ); ?> <code>YYYY-MM-DD HH:MM:SS</code><?php
}
/**
* Display options for the DEBUG_NUMBER setting.
*/
function fortyforty_option_debug_number() {
fortyforty_option_input( FortyForty::DEBUG_NUMBER, 2 );
}
/**
* Generate a dropdown list from a list of options.
*
* @param string $optionName The name of the option.
* @param array $listOptions The possible selections for the option.
*/
function fortyforty_option_dropdown( $optionName, $listOptions ) {
$pluginOptions = get_option( FortyForty::PLUGIN_OPTION_SET ); ?>
<select size="1" id="fortyforty_option_<?php echo $optionName; ?>"
name="<?php printf( "%s[%s]", FortyForty::PLUGIN_OPTION_SET, $optionName ); ?>">
<?php
foreach ( $listOptions as $option ) { ?>
<option value="<?php echo $option[ 'id' ]; ?>" <?php
if ( $option[ 'id' ] == $pluginOptions[ $optionName ] ) echo 'selected="selected"';
?>><?php echo $option[ 'value' ]; ?></option><?php
}
?>
</select><?php
}
/**
* Generate an input element for the given option.
*
* @param string $optionName The name of the option.
* @param int $inputSize The size of the input box.
*/
function fortyforty_option_input( $optionName, $inputSize ) {
$pluginOptions = get_option( FortyForty::PLUGIN_OPTION_SET ); ?>
<input type="text" size="<?php echo $inputSize; ?>" id="fortyforty_option_<?php echo $optionName; ?>"
name="<?php printf( "%s[%s]", FortyForty::PLUGIN_OPTION_SET, $optionName ); ?>"
value="<?php echo $pluginOptions[ $optionName ]; ?>" /><?php
}
/**
* Validate the options from the user.
*
* @param array $input The options from the page.
*/
function fortyforty_validate_options( $input ) {
// Clear the cache.
update_option( FortyForty::CACHE_OPTION_SET, array() );
// Update the options.
$options = get_option( FortyForty::PLUGIN_OPTION_SET );
$options[ FortyForty::YEAR ] = $input[ FortyForty::YEAR ];
$options[ FortyForty::LANGUAGE ] = $input[ FortyForty::LANGUAGE ];
$options[ FortyForty::SCRIPTURE_VERSION ] = $input[ FortyForty::SCRIPTURE_VERSION ];
$options[ FortyForty::TYPE ] = $input[ FortyForty::TYPE ];
$options[ FortyForty::OVERLAP ] = fortyforty_plugin_validate_overlap( $input[ FortyForty::OVERLAP ] );
$options[ FortyForty::DEBUG_DATE ] = fortyforty_plugin_validate_debug_date( $input[ FortyForty::DEBUG_DATE ],
$input[ FortyForty::TYPE ] );
$options[ FortyForty::DEBUG_NUMBER ] = fortyforty_plugin_validate_debug_number( $input[ FortyForty::DEBUG_NUMBER ] );
return $options;
}
/**
* Validate the overlap.
*
* @param string $inputOverlap The value input by the user.
* @return string The overlap to set.
*/
function fortyforty_plugin_validate_overlap( $inputOverlap ) {
if ( is_numeric( $inputOverlap ) ) {
$overlap = ( $inputOverlap + 0) / 1;
if ( ( -1 < $overlap ) && ( 61 > $overlap ) ) {
return "$overlap";
}
}
add_action( 'admin_notices', create_function( '', sprintf( 'echo \'<div class="error"><p>%s</p></div>\';',
__( 'WARNING: "Overlap" value must be between 0 and 60; value set to 30.', 'fortyforty_plugin' ))));
return '30';
}
/**
* Validate the debug date.
*
* @param string $inputDate The value input by the user.
* @param string $type The prayer guide type.
* @return string The debug date, properly formatted.
*/
function fortyforty_plugin_validate_debug_date( $inputDate, $type ) {
if ( empty( $inputDate ) )
return '';
try {
$date = new DateTime( $inputDate );
return ( 'hour' == $type )
? $date->format( 'Y-m-d H:00:00' )
: $date->format( 'Y-m-d' );
} catch (Exception $exception) {
// Invalid date; we'll catch that below.
}
add_action( 'admin_notices', create_function('', sprintf( 'echo \'<div class="error"><p>%s</p></div>\';',
__( 'WARNING: "Force Date or Date/Time" was not valid; value cleared.', 'fortyforty_plugin' ))));
return '';
}
/**
* Validate the debug number.
*
* @param string $inputNumber The value input by the user.
* @return string The number to set.
*/
function fortyforty_plugin_validate_debug_number( $inputNumber ) {
if ( is_numeric( $inputNumber ) ) {
$number = ( $inputNumber + 0) / 1;
if ( ( -1 < $number ) && ( 42 > $number ) ) {
return "$number";
}
}
add_action( 'admin_notices', create_function( '', sprintf( 'echo \'<div class="error"><p>%s</p></div>\';',
__( 'WARNING: "Force Day/Hour Number" must be between 0 and 41; value cleared.', 'fortyforty_plugin' ))));
return '';
}
<file_sep>=== 40/40 Prayer Vigil ===
Contributors: danielsummers
Tags: prayer, guide
Requires at least: 3.2
Tested up to: 3.4.1
Stable tag: 2012.0
This plugin provides the daily or hourly prayer guides for the 40/40 Prayer Vigil (English) and 40/40 Campaña de
Oración (Español).
== Description ==
This plugin utilizes a web service from DJS Consulting (http://services.djs-consulting.com/FortyForty) to display the
current day or hour's suggested prayer guide for the 40/40 Prayer Vigil. The "40/40" part means that you can pray for
either 40 days or 40 hours. For days, the 2012 vigil runs from September 26th through November 4th; for hours, it runs
from 4pm on November 2nd through 7am on November 4th.
This plugin utilizes your blog's local date/time to display the current guide as the vigil is proceeding. It caches
the results, so there should be next to no extra work for the page displays on your blog. You can select the language,
the version that is used for the Scripture links, and the number of days before and after the actual vigil that the
widget will be displayed.
== Installation ==
Unzip the archive, and upload the "4040-prayer-vigil" directory to your wp-content/plugins directory. Once activated,
the widget will be available for use, and the options page should appear under the "Settings" menu.
This plugin requires PHP 5, libxml, and a server that can make outbound web (HTTP) requests and does not block
services.djs-consulting.com.
== Frequently Asked Questions ==
= How Can I Know What It Looks Like Before the Vigil Begins? =
On the options page, there are settings that will force the guide to display for a particular date or date/time, or for
a day or hour number. Select one of those to set, and you can see the results. Be sure to clear them when you are
done, so you won't miss the actual guides once the vigil begins!
= Can I Change the Styling? =
Yes. The div tag containing the guide has the id attribute of "FortyFortyPrayerGuide". You can create CSS based on
that ID, and it will style the guide the way you like. To see the tags to style, you can enable the debugging settings
described above and view the source, or you can go to
http://services.djs-consulting.com/FortyForty/PrayerGuide/html/2012/en/ESV/day/1 for a sample.
== Changelog ==
= 2012.0 =
Initial release
|
3d57e7148a843375edc34b4e96da5dcd203cb818
|
[
"Text",
"PHP"
] | 5
|
PHP
|
WPPlugins/4040-prayer-vigil
|
72158b1dec84378410fc8ced35a3d2029a2a730b
|
8fe261c89bd6309544ca6561dd9c4556b8eb208f
|
refs/heads/main
|
<repo_name>TonyJem/SubclassingUIButton<file_sep>/SubclassingUIButton/SubclassingUIButton/MysteryButton.swift
import UIKit
enum ButtonSuprise: Int {
case Square = 0, Star, Circle, Cake
func basicDescription() -> String {
// This function returns a basic description of the enumeration.
switch self {
case .Square:
return "Square"
case .Star:
return "Star"
case .Circle:
return "Circle"
case .Cake:
return "Cake"
}
}
}
extension ButtonSuprise {
static var caseCount: Int {
return 4
}
static func randomSuprise() -> ButtonSuprise {
let randomValue = Int(arc4random_uniform(UInt32(caseCount)))
return self.init(rawValue: randomValue)!
}
}
class MysteryButton: UIButton {
// Holds the filename of the mystery image
var imageName: String = ""
// Each image is worth varying points. This variable stores that value.
var value: Int = 0
// This bool determines if the button has been tapped. A user can't tap the same button twice.
var beenTapped: Bool = false
// This optional stores the result of our random object generation.
var suprise: ButtonSuprise? = nil
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// The resetMe function sets up the values for this button. It is
// called here when the button first appears and is also called
// from the main ViewController when all the buttons have been tapped
// and the app is reset.
self.resetMe()
}
func showImage() {
self.setBackgroundImage(UIImage(named: self.imageName), for: UIControl.State.normal)
self.layer.borderWidth = 0.0
self.beenTapped = true
}
func resetMe() {
self.value = 0
self.beenTapped = false
self.suprise = ButtonSuprise.randomSuprise()
self.backgroundColor = UIColor.clear
self.setBackgroundImage(UIImage(named: "button"), for: UIControl.State.normal)
if let thisSuprise = suprise {
switch thisSuprise {
case .Square:
self.value = 10
self.imageName = "square"
case .Star:
self.value = 15
self.imageName = "star"
case .Circle:
self.value = 20
self.imageName = "circle"
case .Cake:
self.value = 50
self.imageName = "cake"
}
}
}
}
<file_sep>/SubclassingUIButton/SubclassingUIButton/ViewController.swift
import UIKit
class ViewController: UIViewController {
// Outlet to the score label in Interface Builder.
@IBOutlet weak var scoreLabel: UILabel!
// Outlet to the object name label in Interface Builder.
@IBOutlet weak var objectFoundLabel: UILabel!
// Variables to record the current score. How many buttons have been tapped
// and the maximum number of buttons available.
var score: Int = 0
var numberOfButtons: Int = 15
var buttonCounter: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Update the display
self.updateDisplayWithObjectText(lastObjectFound: nil)
}
@IBAction func buttonTapped(sender: MysteryButton) {
if !sender.beenTapped {
buttonCounter += 1
sender.showImage()
score+=sender.value
self.updateDisplayWithObjectText(lastObjectFound: sender.suprise!.basicDescription())
}
if buttonCounter == numberOfButtons {
self.resetSuprises()
}
}
func updateDisplayWithObjectText(lastObjectFound: String?) {
self.scoreLabel.text = "Score: \(score)"
if let objectName = lastObjectFound {
self.objectFoundLabel.text = objectName
} else {
self.objectFoundLabel.text = ""
}
}
func resetSuprises() {
var arrayOfButtons = [MysteryButton]()
for subview in self.view.subviews {
if (subview is MysteryButton) {
arrayOfButtons.append(subview as! MysteryButton)
}
}
for button in arrayOfButtons {
button.resetMe()
}
score = 0
buttonCounter = 0
self.updateDisplayWithObjectText(lastObjectFound: nil)
}
}
<file_sep>/README.md
# SubclassingUIButton
Done By Tutorial:
http://www.lunapip.com/programming/subclassing-uibutton-in-swift-tutorial/
|
0842ece50069280a02b1cdf385a69f05af8f5b25
|
[
"Swift",
"Markdown"
] | 3
|
Swift
|
TonyJem/SubclassingUIButton
|
fb84752a5dd26a395d813c152dea317c7a3bb3c2
|
8cd83c5e2b98d6f00af22615c0171494d97ca01b
|
refs/heads/master
|
<file_sep>__version__ = "0.1.1"
from .core import *
|
03ebfc6c4474e4b9330bd02fc7752ea3c2e0a879
|
[
"Python"
] | 1
|
Python
|
albertvillanova/ghapi
|
9279bb5eaafb218e4a074071275a484d5c0f4f52
|
8ad474ef21b5d621fed3d3de47885996ec2b3b5a
|
refs/heads/master
|
<repo_name>manilajs/certificate-generator<file_sep>/generate.rb
#!/usr/bin/env ruby
def slugify(str, salt)
require 'digest'
Digest::SHA1.hexdigest(salt + str)
end
def xhtml2pdf(input, output)
system "xhtml2pdf #{input} #{output} 1>&2"
end
template = File.read('template/index.html')
output = []
salt = "<PASSWORD>-"
STDIN.read.split("\n").each do |line|
lname, fname, email, company = line.split(/[,\t]/)
name = [fname, lname].join(' ')
slug = slugify(email, salt)
html = template.gsub('{{ name }}', name)
out = "#{slug}.pdf"
tmp = "template/_tmp.html"
File.open(tmp, 'w') { |f| f.write html }
output << [lname, fname, email, company, out].join("\t")
xhtml2pdf "template/_tmp.html", "pdf/#{out}"
File.unlink tmp
end
puts output.join("\n")
<file_sep>/README.md
Certificate of Attendance generator
===================================
$ brew install xhtml2pdf
And install pdftk.
Make pdfs in pdf/, and outputs a slugged csv for Mailchimp
$ ruby generate.rb < file.csv > out.csv
How to use
----------
1. Make .csv of name,email pairs
2. Run the tool
3. Import the output .csv to Mailchimp (to add the slugs)
4. Put PDFs in https://github.com/manilajs/certificates repo (branch gh-pages)
5. Make a Mailchimp email campaign using the PDFs as mergetags
<file_sep>/Makefile
sample.pdf:
xhtml2pdf template/index.html sample.pdf
|
07317a348bb01a2950e6f617870c606c773fc9dc
|
[
"Markdown",
"Ruby",
"Makefile"
] | 3
|
Ruby
|
manilajs/certificate-generator
|
622d4890a83ae61c1b6d09ae6f17820c351ab86e
|
12d61d5ef7ac37fda580691e2217e1e5c123ed52
|
refs/heads/master
|
<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 Auxiliador_jogo_da_forca
{
public partial class Form1 : Form
{
public Dictionary<int, string[]> PossiveisPalavras = new Dictionary<int, string[]>();
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
/*Dictionary<int, string> AgoraMelhorPossivelLetra = new Dictionary<int, string>();
var relogio = System.Diagnostics.Stopwatch.StartNew();
for (int x = 0;x < 10000000; x++)
{
AgoraMelhorPossivelLetra.Add(x, "a");
}
relogio.Stop();
MessageBox.Show($"{relogio.ElapsedMilliseconds}");
List<string> teste = new List<string>();
relogio = System.Diagnostics.Stopwatch.StartNew();
for (int x = 0; x < 10000000; x++)
{
teste.Add("a");
}
relogio.Stop();
MessageBox.Show($"{relogio.ElapsedMilliseconds}");
//AgoraMelhorPossivelLetra.Add('a', 2);*/
Procurar_Palavra.Procurar(textBox1.Text);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox1.Items.Clear();
try
{
listBox1.Items.AddRange(PossiveisPalavras[Convert.ToInt32(comboBox1.Text)-1]);
}
catch { }
}
}
}
<file_sep>using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace Auxiliador_jogo_da_forca
{
class Procurar_Palavra
{
public static void Procurar (string Texto)
{
string[] Linhas = System.IO.File.ReadAllLines(Directory.GetCurrentDirectory()+"\\dicionario.txt"); //Nao recomendo para dicionarios grandes. Para arquivo grandes recomendo dividir em pedacos
string PalavraLowerCase;
string PedacoLowerCase;
int PosicaoPedaco = 0; // Index da array do texto separado a ser procurado. existe como funcionar sem isso porem, nao recomendo
char[] LetrasErradas;
char[] LetrasContidas;
Dictionary<int, string[]> PalvrasCompativeis = new Dictionary<int, string[]>();
Dictionary<char, int> MelhorPossivelLetra = new Dictionary<char, int>(); // Dicionario das letras que mais apareceram nos "buracos"
Form1 frm = (Form1)Application.OpenForms["Form1"];
LetrasErradas = frm.textBox2.Text.ToCharArray();
LetrasContidas = SepararLetrasContidas(Texto);
List<string> Melhor_Palavra = new List<string>(); // Dicionario Das palavras que se encaixam
Dictionary<char, int> AgoraMelhorPossivelLetra = new Dictionary<char, int>(); // Dicionario das letras que apareceram nos "buracos" (letra,vezes)
foreach (string Pedaco in Texto.Split(' '))
{
Melhor_Palavra.Clear();
foreach (string Palavra in Linhas)
{
if (Pedaco.Length != Palavra.Length) continue;
PalavraLowerCase = Palavra.ToLower();
PedacoLowerCase = Pedaco.ToLower();
bool Adicionado = false;
bool LetraAdicionada = false;
for (int x =0; x != PedacoLowerCase.Length;x++) // Esse codigo pode e deve ser melhor optimizado para maiores dicionarios, eu so nao sei como
{
if (LetrasErradas.Contains(PalavraLowerCase[x]))
{
if (Adicionado == true) Melhor_Palavra.Remove(PalavraLowerCase);
if (LetraAdicionada == true) AgoraMelhorPossivelLetra.Clear();
break;
}
if (PedacoLowerCase[x].Equals('?') && !LetrasContidas.Contains(PalavraLowerCase[x]) )
{
LetraAdicionada = true;
if (AgoraMelhorPossivelLetra.ContainsKey(PalavraLowerCase[x]))
{
AgoraMelhorPossivelLetra[PalavraLowerCase[x]] = AgoraMelhorPossivelLetra[PalavraLowerCase[x]] + 1;
}
else
{
AgoraMelhorPossivelLetra.Add(PalavraLowerCase[x], 1);
}
continue;
}
if (PedacoLowerCase[x].Equals(PalavraLowerCase[x]))
{
if (Adicionado == false)
{
Melhor_Palavra.Add(PalavraLowerCase);
Adicionado = true;
}
continue;
}
else
{
if (Adicionado == true) Melhor_Palavra.Remove(PalavraLowerCase);
if (LetraAdicionada == true) AgoraMelhorPossivelLetra.Clear();
break;
}
}
MelhorPossivelLetra = MesclarDicionarios(MelhorPossivelLetra, AgoraMelhorPossivelLetra);
}
PalvrasCompativeis.Add(PosicaoPedaco, Melhor_Palavra.ToArray());
PosicaoPedaco++;
}
frm.PossiveisPalavras = PalvrasCompativeis;
frm.comboBox1.Items.Clear();
foreach (int k in Enumerable.Range(1, PosicaoPedaco))
{
frm.comboBox1.Items.Add(k);
}
frm.listBox1.Items.Clear();
frm.listBox1.Items.AddRange(PalvrasCompativeis[0]);
frm.comboBox1.Text = "1";
if (MaiorValorChar(MelhorPossivelLetra) != "\0")
frm.label2.Text = "Melhor escolha de letra possivel : " + MaiorValorChar(MelhorPossivelLetra);
else
frm.label2.Text = "Palavra nao existe no dicionario";
}
private static string MaiorValorChar(Dictionary<char, int> dicionario)
{
KeyValuePair<char, int> Maior = new KeyValuePair<char, int>();
foreach (KeyValuePair<char, int> Valor in dicionario)
{
if (Valor.Value > Maior.Value) Maior = Valor;
}
return Maior.Key.ToString();
}
private static char[] SepararLetrasContidas(string texto)
{
char[] chartexto = texto.ToCharArray();
string temp = "";
foreach(char p in chartexto)
{
if (!temp.Contains(p.ToString()) && !p.Equals('?'))
{
temp += p.ToString();
}
}
return temp.ToCharArray();
}
private static Dictionary<char,int> MesclarDicionarios(Dictionary<char,int> dicionario0, Dictionary<char, int> dicionario1)
{
Dictionary<char, int> Resultado = new Dictionary<char, int>();
foreach (KeyValuePair<char,int> atual in dicionario0)
{
if(Resultado.ContainsKey(atual.Key))
{
Resultado[atual.Key] = Resultado[atual.Key] + atual.Value;
}
else
{
Resultado.Add(atual.Key,atual.Value);
}
}
foreach (KeyValuePair<char, int> atual in dicionario1)
{
if (Resultado.ContainsKey(atual.Key))
{
Resultado[atual.Key] = Resultado[atual.Key] + atual.Value;
}
else
{
Resultado.Add(atual.Key, atual.Value);
}
}
return Resultado;
}
}
}
|
7cc26bc9580d1f3b45dd45837e4ea9dc4e046191
|
[
"C#"
] | 2
|
C#
|
PedroReboli/Axiliador_de_jogo_da_forca
|
5a58ad4c235ed48b17e43d71996d72d6e3409790
|
195ce2acb9c1f9d2644c3a47a2047ddd9cc01aa4
|
refs/heads/master
|
<file_sep>use `lotus`;
delimiter ;
create function `col_len`(`tbl` varchar(20), `col` varchar(20)) returns integer
return (select character_maximum_length from information_schema.columns
where table_schema = database() and upper(table_name) = upper(`tbl`)
and upper(column_name) = upper(`col`));
--
create function `prod_col_len`(`col` varchar(20)) returns integer return `col_len`('product', `col`);--
--
create function `prod_name_len`() returns integer return `prod_col_len`('name');
--
create function `prod_desc_len`() returns integer return `prod_col_len`('desc');
<file_sep># mysql-creating-web-pages
<file_sep>mysql -u root -p
-- root
use `lotus`;
delimiter ;
drop function if exists `product_details`;
delimiter $$
create function `product_details`(`p_id` varchar(10))
returns varchar(1000)
begin
declare `html` varchar(1000) default `header`('', 'Detail');
declare `name` varchar(10) default '';
declare `desc` varchar(20) default '';
declare `id` integer default -1;
declare `found` bool default true;
declare `error` bool default false;
declare continue handler for not found set `found` = false;
if is_empty(`p_id`) then
set `html` = concat(`html`, '<p class="error">Product id is required</p>');
set `error` = true;
elseif is_char(`p_id`) then
set `html` = concat(`html`, '<p class="error">Product id: ', p_id, ', is not a number</p>');
set `error` = true;
end if;
if not `error` then
select p.id, p.name, p.desc into `id`, `name`, `desc` from product p
where p.actv and p.id = p_id;
if `found` then
set `html` = concat(`html`, '<h3>Product Details</h3>');
set `html` = concat(`html`, '<p>Product Id</p>');
set `html` = concat(`html`, '<div>', `id`, '</div>');
set `html` = concat(`html`, '<p>Product Name</p>');
set `html` = concat(`html`, '<div>', `name`, '</div>');
set `html` = concat(`html`, '<p>Product Description</p>');
set `html` = concat(`html`, '<div>', `desc`, '</div>');
set `html` = concat(`html`, '<br/>[<a href="edit?id=', `p_id`, '">Edit</a>]');
set `html` = concat(`html`, ' [<a href="delete?id=', `p_id`, '">Delete</a>]');
else
set `html` = concat(`html`, '<p class="warn">No such product found with given id: ', p_id ,'</p>');
end if;
end if;
return `html`;
end$$
delimiter ;
select `product_details`(1);
<file_sep>use `lotus`;
delimiter ;
drop function if exists `is_post`;
create function `is_post`(`method` varchar(6)) returns boolean return upper(`method`) = 'POST';
delimiter ;
drop function if exists `link_add`;
create function `link_add`() returns varchar(3) return 'add';
delimiter ;
drop function if exists `link_list`;
create function `link_list`() returns varchar(4) return 'list';
delimiter ;
drop function if exists `is_add`;
create function `is_add`(`link` varchar(4)) returns boolean return `link_add`() = `link`;
delimiter ;
drop function if exists `is_list`;
create function `is_list`(`link` varchar(4)) returns boolean return `link_list`() = `link`;
delimiter ;
drop function if exists `header`;
delimiter $$
create function `header`(`link` varchar(6), `title` varchar(15))
returns varchar(500)
begin
declare `html` varchar(500) default '';
set `html` = concat(`html`, '<style>');
set `html` = concat(`html`, '.error{color:red;border:1px solid red;}');
set `html` = concat(`html`, '.success{color:green;border:1px solid green;}');
set `html` = concat(`html`, '.warn{color:orange;border:1px solid orange;}');
set `html` = concat(`html`, '.warn,.success,.error{padding:3px 5px;}');
set `html` = concat(`html`, 'input[type=text]{width:180px;}');
set `html` = concat(`html`, 'input[type=reset],input[type=submit]{width:185px;}');
set `html` = concat(`html`, '</style>');
set `html` = concat(`html`, '<title>', `title`,'</title>');
set `html` = concat(`html`, '<table><tr><td>');
if not `is_add`(`link`) then
set `html` = concat(`html`, '[ <a href="', `link_add`() ,'">');
end if;
set `html` = concat(`html`, 'Add Product');
if not `is_add`(`link`) then
set `html` = concat(`html`, '</a> ] ');
end if;
set `html` = concat(`html`, '</td><td>');
if not `is_list`(`link`) then
set `html` = concat(`html`, '| [ <a href="', `link_list`() ,'">');
end if;
set `html` = concat(`html`, 'List all Product');
if not `is_list`(`link`) then
set `html` = concat(`html`, '</a> ]');
end if;
set `html` = concat(`html`, '</td></tr></table>');
return `html`;
end$$
delimiter ;
select header(null);
---
delimiter ;
drop function if exists is_char;
create function is_char(str varchar(100)) returns boolean return str not regexp '^[0-9]+$';
select is_char('123'), is_char(''), is_char(null), is_char('fg'), is_char('123sd');
----
drop function if exists is_empty;
create function is_empty(str varchar(100)) returns boolean return str is null or 0 = length(trim(str));
<file_sep>mysql -u root -p;
use lotus;
delimiter ;
drop procedure if exists `edit_product`;
delimiter $$
create procedure `edit_product`(
in `id` varchar(10),
in `name` varchar(100),
in `desc` varchar(500),
in `method` varchar(6),
out `html` varchar(2000)
)
begin
declare cnt integer;
declare err boolean default false;
declare `post` boolean default `is_post`(`method`);
declare fnd boolean default true;
declare `p_name` varchar(10);
declare `p_desc` varchar(20);
declare continue handler for not found set fnd = false;
set `html` = '<h3>Edit Product Details</h3>';
select p.name, p.desc into p_name, p_desc from product p where p.id = `id` and p.actv;
if `is_empty`(`id`) then
set `html` = concat(`html`, error_op(), 'Product Id is required', alert_cl());
set err = true;
elseif not fnd then
set `html` = concat(`html`, warn_op(), 'Product with Id: ', `id`, ' does not exist', alert_cl());
set err = true;
else
set `html` = concat(`html`, '<form action="edit" method="post">');
-- product id starts here
set `html` = concat(`html`, '<p>Product Id</p>');
set `html` = concat(`html`, '<div><input type="text" name="id" readonly="" value="', `id`, '"/></div>');
-- product id ends here
-- product name starts here
set `html` = concat(`html`, '<p>Product Name</p>');
set `html` = concat(`html`, '<div><input type="text" name="name" autofocus="" value="');
if `post` then
if `name` is not null then
set `html` = concat(`html`, `name`);
end if;
else
if `p_name` is not null then
set `html` = concat(`html`, `p_name`);
end if;
end if;
set `html` = concat(`html`, '"/></div>');
select count(p.name) into cnt from product p where p.name = upper(trim(`name`)) and p.id <> `id`;
if `post` then
if `is_empty`(`name`) then
set `html` = concat(`html`, error_op(), 'Product Name is required', alert_cl());
set err = true;
elseif 0 < cnt then
set `html` = concat(`html`, error_op(), 'Product Name is duplicate', alert_cl());
set err = true;
elseif length(`name`) > `prod_name_len`() then
set `html` = concat(`html`, error_op(), 'Product name is too long', alert_cl());
set err = true;
end if;
end if;
-- product name ends here
-- product desc starts here
set `html` = concat(`html`, '<p>Product Desc</p>');
set `html` = concat(`html`, '<div><input type="text" name="desc" value="');
if `post` then
if `desc` is not null then
set `html` = concat(`html`, `desc`);
end if;
else
if `p_desc` is not null then
set `html` = concat(`html`, `p_desc`);
end if;
end if;
set `html` = concat(`html`, '"/></div>');
select count(p.desc) into cnt from product p where p.desc = upper(trim(`desc`)) and p.id <> `id`;
if `post` then
if `is_empty`(`desc`) then
set `html` = concat(`html`, error_op(), 'Product desc is required', alert_cl());
set err = true;
elseif 0 < cnt then
set `html` = concat(`html`, error_op(), 'Product desc is duplicate', alert_cl());
set err = true;
elseif length(`desc`) > `prod_desc_len`() then
set `html` = concat(`html`, error_op(), 'Product desc is too long', alert_cl());
set err = true;
end if;
end if;
-- product desc ends here
set `html` = concat(`html`, '<br/><input type="reset"/>');
set `html` = concat(`html`, '<br/><input type="submit" value="Update"/>');
set `html` = concat(`html`, '</form>');
end if;
if `fnd` and `post` and not `err` then
update product p set p.name = upper(trim(`name`)), p.desc = upper(trim(`desc`)) where p.actv and p.id = `id`;
set `html` = concat (success_op(), 'Product details were updated', alert_cl(), `html`);
end if;
set `html` = concat(`header`('Edit', 'Edit Product Details'), `html`, `footer`());
end$$
<file_sep>drop database if exists `lotus`;
create database `lotus`;
use `lotus`;
drop table if exists `product`;
create table `product`(
`id` integer,
`name` varchar(10),
`desc` varchar(20),
`actv` boolean
);
select * from `product`;
<file_sep>mysql -u root -p
--root
use `lotus`;
delimiter ;
drop procedure if exists `save_product`;
delimiter $$
create procedure `save_product`(
in `id` varchar(100),
in `name` varchar(100),
in `desc` varchar(500),
in `method` varchar(6),
out `html` varchar(1000)
)
begin
declare cnt integer;
declare err boolean default false;
declare `posted` boolean default `is_post`(`method`);
declare `title` varchar(15) default 'New Product';
set `html` = concat('<form action="', `link_add`(), '" method="post">');
-- product id starts here
set `html` = concat(`html`, '<p>Product Id</p>');
set `html` = concat(`html`, '<div><input type="text" name="id" autofocus="" value="');
if `id` is not null then
set `html` = concat(`html`, `id`);
end if;
set `html` = concat(`html`, '"/></div>');
if `posted` then
select count(p.id) into cnt from product p where p.id = `id`;
if is_empty(`id`) then
set `html` = concat(`html`, '<p class="error">Product id is required</p>');
set err = true;
elseif is_char(`id`) then
set `html` = concat(`html`, '<p class="error">Product id is not a number</p>');
set err = true;
elseif 0 < cnt then
set `html` = concat(`html`, '<p class="error">Product id is duplicate</p>');
set err = true;
end if;
end if;
-- product id ends here
-- product name starts here
set `html` = concat(`html`, '<p>Product Name</p>');
set `html` = concat(`html`, '<div><input type="text" name="name" value="');
if `name` is not null then
set `html` = concat(`html`, `name`);
end if;
set `html` = concat(`html`, '"/></div>');
if `posted` then
select count(p.name) into cnt from product p where p.name = upper(trim(`name`));
if is_empty(`name`) then
set `html` = concat(`html`, '<p class="error">Product name is required</p>');
set err = true;
elseif length(`name`) > `prod_name_len`() then
set `html` = concat(`html`, '<p class="error">Product name is too long</p>');
set err = true;
elseif 0 < cnt then
set `html` = concat(`html`, '<p class="error">Product name is duplicate</p>');
set err = true;
end if;
end if;
-- product name ends here
-- product desc starts here
set `html` = concat(`html`, '<p>Product desc</p>');
set `html` = concat(`html`, '<div><input type="text" name="desc" value="');
if `desc` is not null then
set `html` = concat(`html`, `desc`);
end if;
set `html` = concat(`html`, '"/></div>');
if `posted` then
select count(p.desc) into cnt from product p where p.desc = upper(trim(`desc`));
if is_empty(`desc`) then
set `html` = concat(`html`, '<p class="error">Product desc is required</p>');
set err = true;
elseif length(`desc`) > `prod_desc_len`() then
set `html` = concat(`html`, '<p class="error">Product desc is too long</p>');
set err = true;
elseif 0 < cnt then
set `html` = concat(`html`, '<p class="error">Product desc is duplicate</p>');
set err = true;
end if;
end if;
-- product desc ends here
set `html` = concat(`html`, '<br/><div><input type="reset"/><input type="submit"/></div></form>');
if `posted` and not err then
insert into product values (`id`, upper(trim(`name`)), upper(trim(`desc`)), true);
commit;
set `html` = concat(`header`(`link_add`(), `title`), '<p class="success">Product details were saved</p>', `html`);
else
set `html` = concat(`header`(`link_add`(), `title`), `html`);
end if;
end$$
delimiter ;
call save_product(2, 'parle.', 'biscuits.', 'post', @html);
select @html;
<file_sep>use `lotus`;
delimiter ;
drop function if exists `list_products`;
delimiter $$
create function `list_products`()
returns varchar(1000)
begin
declare `html` varchar(1000) default `header`(`link_list`(), 'List');
declare `name` varchar(10);
declare `id` integer;
declare `found` bool default false;
declare `quit` bool default false;
declare `reader` cursor for select p.id, p.name from product p where actv;
declare continue handler for not found set `quit` = true;
set `html` = concat(`html`, '<h3>Products List</h3>');
set `html` = concat(`html`, '<ol>');
open `reader`;
`cycle`: loop
fetch `reader` into `id`, `name`;
if `quit` then
leave `cycle`;
end if;
set `found` = true;
set `html` = concat(`html`, '<li><a href="details?id=', `id`, '">', `name`, '</a></li>');
end loop `cycle`;
close `reader`;
set `html` = concat(`html`, '</ol>');
if not `found` then
set `html` = concat(`html`, '<p class="warn">No products found</p>');
end if;
return `html`;
end$$
delimiter ;
select `list_products`();
<file_sep>delimiter ;
drop function if exists alert_op;
create function alert_op(`level` varchar(10)) returns varchar(100) return concat('<div class="alert alert-', `level` ,'" role="alert">');
drop function if exists error_op;
create function error_op() returns varchar(100) return alert_op('danger');
drop function if exists warn_op;
create function warn_op() returns varchar(100) return alert_op('warning');
drop function if exists success_op;
create function success_op() returns varchar(100) return alert_op('success');
drop function if exists alert_cl;
create function alert_cl() returns varchar(10) return '</div>';
|
435bf78a79ceb289b87fe65d5cbbbb144a6286bb
|
[
"Markdown",
"SQL"
] | 9
|
SQL
|
arvind-sql-corner/mysql-creating-web-pages
|
977f5211fcd647badaf899b8a87f099814a55dfa
|
bb6723cab1f3e6861cfe03b9e117e8aba3580687
|
refs/heads/master
|
<repo_name>KidBrookes/randDNA<file_sep>/src/rdna.hpp
#include <random>
#include <iostream>
#include <string>
using namespace std;
string randDNA(int seed, string bases, int n){
string letter ="";
int min =0;
int max =bases.size() -1;
mt19937 dna1(seed);
uniform_int_distribution<int> range(min,max);
if(bases == ""){
return "";
}
for(int i=0; i<n;i++){
letter += bases[range(dna1)];
}
return letter;
}
|
03db2f6ea40bca370f18688816af4dabfbd11373
|
[
"C++"
] | 1
|
C++
|
KidBrookes/randDNA
|
822d6970f732cccb1ff19e2ab700d57dc2472ba2
|
cbc4d69eb58c7b86f64e30b552aedd0e11184d4d
|
refs/heads/master
|
<repo_name>BlackOroogu/PythonEverybody<file_sep>/Week4/conditionals/scores.py
score = raw_input("Please enter Score: ")
theScore = 0.0
try:
theScore = float(score)
except ValueError:
print "ERROR: Value '{0}' is not a float number.".format(score)
exit()
if theScore > 1.0 or theScore < 0.0:
print "ERROR: Value '{0}' is out of range.\nAccepted values are in range [0.0 .. 1.0]".format(score)
quit()
if theScore >= 0.9:
strScore = 'A'
elif theScore >= 0.8:
strScore = 'B'
elif theScore >= 0.7:
strScore = 'C'
elif theScore >= 0.6:
strScore = 'D'
else:
strScore = 'F'
print strScore
<file_sep>/Week4/conditionals/pay.py
hrs = raw_input("Enter Hours:")
rt = raw_input("Enter Rate:")
worked = 0
rate = 0
# Check if input is valid, quit with error code 100 if it is not
try:
worked = float(hrs)
rate = float(rt)
except ValueError:
print "Not a float value"
quit(100)
# overtime settings
overtimeStart = 40
overtimePay = rate * 1.5
if hrs <= 40:
pay = worked * rate
else:
pay = overtimeStart * rate + (worked - overtimeStart) * overtimePay
print str(pay)
<file_sep>/Week4/conditionals/conditionals.py
import sys
inString = raw_input("Got somethng to say?")
try:
howMuch = int(inString)
except ValueError:
print "Not a number"
exit(100)
print "You said:", inString
<file_sep>/Week2/my.py
# Simple text output
import sys
print(sys.version)
# Store string literal for latter use
theStr = "You should never underestimate the predictability of stupidity."
# Get padding width for quote 'author'
padWidth = len(theStr)
# Print all
print theStr, '\n', "-- Bullet Tooth Tony".rjust(len(theStr)-1)
|
86baa0258b330341d9e2b8c98edefb47412c2f90
|
[
"Python"
] | 4
|
Python
|
BlackOroogu/PythonEverybody
|
25042ece0061b58d4069c19c65b910facfa2f160
|
5f9b901b85b94d6f6224e375d6436c0f58c3f586
|
refs/heads/main
|
<file_sep># RobOT: Robustness-Oriented Testing for Deep Learning Systems published at ICSE 2021
See the <a href="https://arxiv.org/pdf/2102.05913.pdf" target="_blank">ICSE2021 paper</a> for more details.
## Prerequisite (Py3.6 & Tf2)
The code are run successfully using Python 3.6 and Tensorflow 2.2.0.
We recommend using conda to install the tensorflow-gpu environment
```shell
conda create -n tf2-gpu tensorflow-gpu==2.2.0
conda activate tf2-gpu
```
Checking installed environments
```shell
conda env list
```
to run the code in jupyter, you should add the kernel in jupyter notebook
```
pip install ipykernel
python -m ipykernel install --name tf2-gpu
```
then start jupyter notebook for experiments
```
jupyter notebook
```
## Files
- MNIST - experiments for MNIST dataset.
- Cifar - experimnets for CIFAR-10 dataset.
metrics.py contains proposed metrics FOL.
train_model.py is to train the DNN model.
attack.py contains FGSM and PGD attack.
gen_adv.py is to generate adversarial inputs for test selection and robustness evaluation. You could also use toolbox like <a href="https://github.com/cleverhans-lab/cleverhans" target="_blank">cleverhans</a> for test case generation.
select_retrain.py is to select high-quality test cases for model retraining.
For testing method (DeepXplore, DLFuzz, ADAPT), we use the code repository <a href="https://github.com/kupl/ADAPT" target="_blank">ADAPT</a>.
## Coming soon
More details would be included soon.
<file_sep>from tensorflow import keras
import random
import tensorflow as tf
import numpy as np
import time
import os
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
except RuntimeError as e:
print(e)
def load_mnist(path="./mnist.npz"):
f = np.load(path)
x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test']
f.close()
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
return x_train, x_test, y_train, y_test
path = "./mnist.npz"
x_train, x_test, y_train, y_test = load_mnist(path)
model = keras.models.load_model("./Lenet5_mnist.h5")
seeds = random.sample(list(range(x_train.shape[0])), 1000)
images = x_train[seeds]
labels = y_train[seeds]
# some training samples is static, i.e., grad=<0>, hard to generate.
seeds_filter = []
gen_img = tf.Variable(images)
with tf.GradientTape() as g:
loss = keras.losses.categorical_crossentropy(labels, model(gen_img))
grads = g.gradient(loss, gen_img)
fols = np.linalg.norm((grads.numpy()+1e-20).reshape(images.shape[0], -1), ord=2, axis=1)
seeds_filter = np.where(fols > 1e-3)[0]
start_t = time.time()
lr = 0.1
total_sets = []
for idx in seeds_filter:
# delta_t = time.time() - start_t
# if delta_t > 300:
# break
img_list = []
tmp_img = images[[idx]]
orig_img = tmp_img.copy()
orig_norm = np.linalg.norm(orig_img)
img_list.append(tf.identity(tmp_img))
logits = model(tmp_img)
orig_index = np.argmax(logits[0])
target = keras.utils.to_categorical([orig_index], 10)
label_top5 = np.argsort(logits[0])[-5:]
folMAX = 0
epoch = 0
while len(img_list) > 0:
gen_img = img_list.pop(0)
for _ in range(2):
gen_img = tf.Variable(gen_img)
with tf.GradientTape(persistent=True) as g:
loss = keras.losses.categorical_crossentropy(target, model(gen_img))
grads = g.gradient(loss, gen_img)
fol = tf.norm(grads+1e-20)
g.watch(fol)
logits = model(gen_img)
obj = fol - logits[0][orig_index]
dl_di = g.gradient(obj, gen_img)
del g
gen_img = gen_img + dl_di * lr * (random.random() + 0.5)
gen_img = tf.clip_by_value(gen_img, clip_value_min=0, clip_value_max=1)
with tf.GradientTape() as t:
t.watch(gen_img)
loss = keras.losses.categorical_crossentropy(target, model(gen_img))
grad = t.gradient(loss, gen_img)
fol = np.linalg.norm(grad.numpy()) # L2 adaption
distance = np.linalg.norm(gen_img.numpy() - orig_img) / orig_norm
if fol > folMAX and distance < 0.5:
folMAX = fol
img_list.append(tf.identity(gen_img))
gen_index = np.argmax(model(gen_img)[0])
if gen_index != orig_index:
total_sets.append((fol, gen_img.numpy(), labels[idx]))
fols = np.array([item[0] for item in total_sets])
advs = np.array([item[1].reshape(28,28,1) for item in total_sets])
labels = np.array([item[2] for item in total_sets])
np.savez('./FOL_Fuzz.npz', advs=advs, labels=labels, fols=fols)
<file_sep>from tensorflow import keras
import tensorflow as tf
from tensorflow.keras.datasets import cifar10
import numpy as np
from attack import FGSM, PGD
import os
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# preprocess cifar dataset
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train = x_train/255
x_test = x_test/255
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
# load your model
model = keras.models.load_model("./cifar10_resnet20_model.h5")
fgsm = FGSM(model, ep=0.01, isRand=True)
pgd = PGD(model, ep=0.01, epochs=10, isRand=True)
# generate adversarial examples at once.
advs, labels, fols, ginis = fgsm.generate(x_train, y_train)
np.savez('./FGSM_TrainFull.npz', advs=advs, labels=labels, fols=fols, ginis=ginis)
advs, labels, fols, ginis = pgd.generate(x_train, y_train)
np.savez('./PGD_TrainFull.npz', advs=advs, labels=labels, fols=fols, ginis=ginis)
advs, labels, _, _ = fgsm.generate(x_test, y_test)
np.savez('./FGSM_Test.npz', advs=advs, labels=labels)
advs, labels, _, _ = pgd.generate(x_test, y_test)
np.savez('./PGD_Test.npz', advs=advs, labels=labels)<file_sep>from tensorflow import keras
import tensorflow as tf
import numpy as np
## Metrics for quality evaluation for massive test cases.
def gini(model, x):
"""
Different from the defination in DeepGini paper (deepgini = 1 - ginis), the smaller the ginis here, the larger the uncertainty.
shape of x: [batch_size, width, height, channel]
"""
x = tf.Variable(x)
preds = model(x).numpy()
ginis = np.sum(np.square(preds), axis=1)
return ginis
def fol_Linf(model, x, xi, ep, y):
"""
x: perturbed inputs, shape of x: [batch_size, width, height, channel]
xi: initial inputs, shape of xi: [batch_size, width, height, channel]
ep: L_inf bound
y: ground truth, one hot vectors, shape of y: [batch_size, N_classes]
"""
x, target = tf.Variable(x), tf.constant(y)
fols = []
with tf.GradientTape() as tape:
loss = keras.losses.categorical_crossentropy(target, model(x))
grads = tape.gradient(loss, x)
grad_norm = np.linalg.norm(grads.numpy().reshape(x.shape[0], -1), ord=1, axis=1)
grads_flat = grads.numpy().reshape(x.shape[0], -1)
diff = (x.numpy() - xi).reshape(x.shape[0], -1)
for i in range(x.shape[0]):
i_fol = -np.dot(grads_flat[i], diff[i]) + ep * grad_norm[i]
fols.append(i_fol)
return np.array(fols)
def fol_L2(model, x, y):
"""
x: perturbed inputs, shape of x: [batch_size, width, height, channel]
y: ground truth, one hot vectors, shape of y: [batch_size, N_classes]
"""
x, target = tf.Variable(x), tf.constant(y)
with tf.GradientTape() as tape:
loss = keras.losses.categorical_crossentropy(target, model(x))
grads = tape.gradient(loss, x)
grads_norm_L2 = np.linalg.norm(grads.numpy().reshape(x.shape[0], -1), ord=2, axis=1)
return grads_norm_L2
def zol(model, x, y):
"""
x: perturbed inputs, shape of x: [batch_size, width, height, channel]
y: ground truth, one hot vectors, shape of y: [batch_size, N_classes]
"""
x, target = tf.Variable(x), tf.constant(y)
loss = keras.losses.categorical_crossentropy(target, model(x))
loss.numpy().reshape(-1)
return loss
def robustness(model, x, y):
"""
x: perturbed inputs, shape of x: [batch_size, width, height, channel]
y: ground truth labels, shape of y: [batch_size]
"""
return np.sum(np.argmax(model(x), axis=1) == y) / y.shape[0]
<file_sep>from tensorflow import keras
import tensorflow as tf
import numpy as np
import random
from tensorflow.keras.callbacks import ModelCheckpoint
import os
os.environ["CUDA_VISIBLE_DEVICES"]="0"
# Suppress the GPU memory
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
except RuntimeError as e:
print(e)
def select(foscs, n, s='best', k=1000):
"""
n: the number of selected test cases.
s: strategy, ['best', 'kmst', 'gini']
k: for KM-ST, the number of ranges.
"""
ranks = np.argsort(foscs)
# we choose test cases with small and large fols.
if s == 'best':
h = n//2
return np.concatenate((ranks[:h],ranks[-h:]))
# we choose test cases with small and large fols.
elif s == 'kmst':
index = []
section_w = len(ranks) // k
section_nums = n // section_w
indexes = random.sample(list(range(k)), section_nums)
for i in indexes:
block = ranks[i*section_w: (i+1)*section_w]
index.append(block)
return np.concatenate(np.array(index))
# This is for gini strategy. There is little different from DeepGini paper. See function ginis() in metrics.py
else:
return ranks[:n]
def load_mnist(path="./mnist.npz"):
"""
preprocessing for MNIST dataset, values are normalized to [0,1].
y_train and y_test are one-hot vectors.
"""
f = np.load(path)
x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test']
f.close()
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
return x_train, x_test, y_train, y_test
x_train, x_test, y_train, y_test = load_mnist(path="./mnist.npz")
# Load the generated adversarial inputs for training. FGSM and PGD.
with np.load("./FGSM_TrainFull.npz") as f:
fgsm_train, fgsm_train_labels, fgsm_train_fols, fgsm_train_ginis = f['advs'], f['labels'], f['fols'], f['ginis']
with np.load("./PGD_TrainFull.npz") as f:
pgd_train, pgd_train_labels, pgd_train_fols, pgd_train_ginis= f['advs'], f['labels'], f['fols'], f['ginis']
# Load the generated adversarial inputs for testing. FGSM and PGD.
with np.load("./FGSM_Test.npz") as f:
fgsm_test, fgsm_test_labels = f['advs'], f['labels']
with np.load("./PGD_Test.npz") as f:
pgd_test, pgd_test_labels = f['advs'], f['labels']
# Mix the adversarial inputs
fp_train = np.concatenate((fgsm_train, pgd_train))
fp_train_labels = np.concatenate((fgsm_train_labels, pgd_train_labels))
fp_train_fols = np.concatenate((fgsm_train_fols, pgd_train_fols))
fp_train_ginis = np.concatenate((fgsm_train_ginis, pgd_train_ginis))
fp_test = np.concatenate((fgsm_test, pgd_test))
fp_test_labels = np.concatenate((fgsm_test_labels, pgd_test_labels))
sNums = [600*i for i in [1,2,3,4,6,8,10,12,16,20]]
strategies = ['best', 'kmst', 'gini']
acc_clean = [[] for i in range(len(strategies))]
acc_fp = [[] for i in range(len(strategies))]
for num in sNums:
for i in range(len(strategies)):
s = strategies[i]
# model save path
model_path = "./checkpoint/best_Lenet5_MIX_%d_%s.h5" % (num, s)
model = keras.models.load_model("./Lenet5_mnist.h5")
checkpoint = ModelCheckpoint(filepath=model_path, monitor='val_accuracy', verbose=0, save_best_only=True)
callbacks = [checkpoint]
if s == 'gini':
indexes = select(fp_train_ginis, num, s=s)
else:
indexes = select(fp_train_fols, num, s=s)
selectAdvs = fp_train[indexes]
selectAdvsLabels = fp_train_labels[indexes]
x_train_mix = np.concatenate((x_train, selectAdvs),axis=0)
y_train_mix = np.concatenate((y_train, selectAdvsLabels),axis=0)
# model retraining
model.fit(x_train_mix, y_train_mix, epochs=10, batch_size=64, verbose=0, callbacks=callbacks,
validation_data=(fp_test, fp_test_labels))
best_model = keras.models.load_model(model_path)
_, aclean = best_model.evaluate(x_test, y_test, verbose=0)
_, afp = best_model.evaluate(fp_test, fp_test_labels, verbose=0)
acc_clean[i].append(aclean)
acc_fp[i].append(afp)
<file_sep>from tensorflow import keras
import tensorflow as tf
import numpy as np
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
except RuntimeError as e:
print(e)
def Lenet5():
input_tensor = keras.layers.Input(shape=(28, 28, 1))
x = keras.layers.Convolution2D(6, (5, 5), activation='relu', padding='same', name='block1_conv1')(input_tensor)
x = keras.layers.MaxPooling2D(pool_size=(2, 2), name='block1_pool1')(x)
x = keras.layers.Convolution2D(16, (5, 5), activation='relu', padding='same', name='block2_conv1')(x)
x = keras.layers.MaxPooling2D(pool_size=(2, 2), name='block2_pool1')(x)
x = keras.layers.Flatten(name='flatten')(x)
x = keras.layers.Dense(120, activation='relu', name='fc1')(x)
x = keras.layers.Dense(84, activation='relu', name='fc2')(x)
x = keras.layers.Dense(10, name='before_softmax')(x)
x = keras.layers.Activation('softmax', name='redictions')(x)
return keras.models.Model(input_tensor, x)
def load_mnist(path="./mnist.npz"):
f = np.load(path)
x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test']
f.close()
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
return x_train, x_test, y_train, y_test
path = "./mnist.npz"
x_train, x_test, y_train, y_test = load_mnist(path)
lenet5 = Lenet5()
lenet5.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
lenet5.fit(x_train, y_train, epochs=10, batch_size=64)
lenet5.evaluate(x_test, y_test)
lenet5.save("./Lenet5_mnist.h5")
<file_sep>from tensorflow import keras
import tensorflow as tf
import numpy as np
class FGSM:
"""
We use FGSM to generate a batch of adversarial examples.
"""
def __init__(self, model, ep=0.01, isRand=True):
"""
isRand is set True to improve the attack success rate.
"""
self.isRand = isRand
self.model = model
self.ep = ep
def generate(self, x, y, randRate=1):
"""
x: clean inputs, shape of x: [batch_size, width, height, channel]
y: ground truth, one hot vectors, shape of y: [batch_size, N_classes]
"""
fols = []
target = tf.constant(y)
xi = x.copy()
if self.isRand:
x = x + np.random.uniform(-self.ep * randRate, self.ep * randRate, x.shape)
x = np.clip(x, 0, 1)
x = tf.Variable(x)
with tf.GradientTape() as tape:
loss = keras.losses.categorical_crossentropy(target, self.model(x))
grads = tape.gradient(loss, x)
delta = tf.sign(grads)
x_adv = x + self.ep * delta
x_adv = tf.clip_by_value(x_adv, clip_value_min=xi-self.ep, clip_value_max=xi+self.ep)
x_adv = tf.clip_by_value(x_adv, clip_value_min=0, clip_value_max=1)
idxs = np.where(np.argmax(self.model(x_adv), axis=1) != np.argmax(y, axis=1))[0]
print("SUCCESS:", len(idxs))
x_adv, xi, target = x_adv.numpy()[idxs], xi[idxs], target.numpy()[idxs]
x_adv, target = tf.Variable(x_adv), tf.constant(target)
preds = self.model(x_adv).numpy()
ginis = np.sum(np.square(preds), axis=1)
with tf.GradientTape() as tape:
loss = keras.losses.categorical_crossentropy(target, self.model(x_adv))
grads = tape.gradient(loss, x_adv)
grad_norm = np.linalg.norm(grads.numpy().reshape(x_adv.shape[0], -1), ord=1, axis=1)
grads_flat = grads.numpy().reshape(x_adv.shape[0], -1)
diff = (x_adv.numpy() - xi).reshape(x_adv.shape[0], -1)
for i in range(x_adv.shape[0]):
i_fol = -np.dot(grads_flat[i], diff[i]) + self.ep * grad_norm[i]
fols.append(i_fol)
return x_adv.numpy(), target.numpy(), np.array(fols), ginis
class PGD:
"""
We use PGD to generate a batch of adversarial examples. PGD could be seen as iterative version of FGSM.
"""
def __init__(self, model, ep=0.01, step=None, epochs=10, isRand=True):
"""
isRand is set True to improve the attack success rate.
"""
self.isRand = isRand
self.model = model
self.ep = ep
if step == None:
self.step = ep/6
self.epochs = epochs
def generate(self, x, y, randRate=1):
"""
x: clean inputs, shape of x: [batch_size, width, height, channel]
y: ground truth, one hot vectors, shape of y: [batch_size, N_classes]
"""
fols = []
target = tf.constant(y)
xi = x.copy()
if self.isRand:
x = x + np.random.uniform(-self.ep * randRate, self.ep * randRate, x.shape)
x = np.clip(x, 0, 1)
x_adv = tf.Variable(x)
for i in range(self.epochs):
with tf.GradientTape() as tape:
loss = keras.losses.categorical_crossentropy(target, self.model(x_adv))
grads = tape.gradient(loss, x_adv)
delta = tf.sign(grads)
x_adv.assign_add(self.step * delta)
x_adv = tf.clip_by_value(x_adv, clip_value_min=xi-self.ep, clip_value_max=xi+self.ep)
x_adv = tf.clip_by_value(x_adv, clip_value_min=0, clip_value_max=1)
x_adv = tf.Variable(x_adv)
idxs = np.where(np.argmax(self.model(x_adv), axis=1) != np.argmax(y, axis=1))[0]
print("SUCCESS:", len(idxs))
x_adv, xi, target = x_adv.numpy()[idxs], xi[idxs], target.numpy()[idxs]
x_adv, target = tf.Variable(x_adv), tf.constant(target)
preds = self.model(x_adv).numpy()
ginis = np.sum(np.square(preds), axis=1)
with tf.GradientTape() as tape:
loss = keras.losses.categorical_crossentropy(target, self.model(x_adv))
grads = tape.gradient(loss, x_adv)
grad_norm = np.linalg.norm(grads.numpy().reshape(x_adv.shape[0], -1), ord=1, axis=1)
grads_flat = grads.numpy().reshape(x_adv.shape[0], -1)
diff = (x_adv.numpy() - xi).reshape(x_adv.shape[0], -1)
for i in range(x_adv.shape[0]):
i_fol = -np.dot(grads_flat[i], diff[i]) + self.ep * grad_norm[i]
fols.append(i_fol)
return x_adv.numpy(), target.numpy(), np.array(fols), ginis
<file_sep>from tensorflow import keras
import tensorflow as tf
import numpy as np
from attack import FGSM, PGD
import os
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
def load_mnist(path="./mnist.npz"):
f = np.load(path)
x_train, y_train = f['x_train'], f['y_train']
x_test, y_test = f['x_test'], f['y_test']
f.close()
x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
return x_train, x_test, y_train, y_test
path = "./mnist.npz"
x_train, x_test, y_train, y_test = load_mnist(path)
# load your model
model = keras.models.load_model("./Lenet5_mnist.h5")
fgsm = FGSM(model, ep=0.3, isRand=True)
pgd = PGD(model, ep=0.3, epochs=10, isRand=True)
# generate adversarial examples at once.
advs, labels, fols, ginis = fgsm.generate(x_train, y_train)
np.savez('./FGSM_TrainFull.npz', advs=advs, labels=labels, fols=fols, ginis=ginis)
advs, labels, fols, ginis = pgd.generate(x_train, y_train)
np.savez('./PGD_TrainFull.npz', advs=advs, labels=labels, fols=fols, ginis=ginis)
advs, labels, _, _ = fgsm.generate(x_test, y_test)
np.savez('./FGSM_Test.npz', advs=advs, labels=labels)
advs, labels, _, _ = pgd.generate(x_test, y_test)
np.savez('./PGD_Test.npz', advs=advs, labels=labels)<file_sep>import tensorflow as tf
import numpy as np
from tensorflow import keras
from tensorflow.keras.layers import Dense, Conv2D, BatchNormalization, Activation
from tensorflow.keras.layers import AveragePooling2D, Input, Flatten
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler
from tensorflow.keras.callbacks import ReduceLROnPlateau
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.regularizers import l2
from tensorflow.keras.models import Model
from tensorflow.keras.datasets import cifar10
import os
os.environ["CUDA_VISIBLE_DEVICES"]="0"
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
except RuntimeError as e:
print(e)
# hyper-parameters for training resnet-20
batch_size = 64
epochs = 150
data_augmentation = True
num_classes = 10
depth = 20
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
input_shape = x_train.shape[1:]
def lr_schedule(epoch):
lr = 1e-3
if epoch > 130:
lr *= 0.5e-3
elif epoch > 110:
lr *= 1e-3
elif epoch > 80:
lr *= 1e-2
elif epoch > 50:
lr *= 1e-1
print('Learning rate: ', lr)
return lr
def resnet_layer(inputs,
num_filters=16,
kernel_size=3,
strides=1,
activation='relu',
batch_normalization=True,
conv_first=True):
conv = Conv2D(num_filters,
kernel_size=kernel_size,
strides=strides,
padding='same',
kernel_initializer='he_normal',
kernel_regularizer=l2(1e-4))
x = inputs
if conv_first:
x = conv(x)
if batch_normalization:
x = BatchNormalization()(x)
if activation is not None:
x = Activation(activation)(x)
else:
if batch_normalization:
x = BatchNormalization()(x)
if activation is not None:
x = Activation(activation)(x)
x = conv(x)
return x
def resnet_v1(input_shape, depth, num_classes=10):
"""
Stacks of 2 x (3 x 3) Conv2D-BN-ReLU
Last ReLU is after the shortcut connection.
At the beginning of each stage, the feature map size is halved (downsampled)
by a convolutional layer with strides=2, while the number of filters is
doubled. Within each stage, the layers have the same number filters and the
same number of filters.
Features maps sizes:
stage 0: 32x32, 16
stage 1: 16x16, 32
stage 2: 8x8, 64
The Number of parameters is approx the same as Table 6 of [a]:
ResNet20 0.27M
ResNet32 0.46M
ResNet44 0.66M
ResNet56 0.85M
ResNet110 1.7M
# Arguments
input_shape (tensor): shape of input image tensor
depth (int): number of core convolutional layers
num_classes (int): number of classes (CIFAR10 has 10)
# Returns
model (Model): Keras model instance
"""
if (depth - 2) % 6 != 0:
raise ValueError('depth should be 6n+2 (eg 20, 32, 44 in [a])')
# Start model definition.
num_filters = 16
num_res_blocks = int((depth - 2) / 6)
inputs = Input(shape=input_shape)
x = resnet_layer(inputs=inputs)
# Instantiate the stack of residual units
for stack in range(3):
for res_block in range(num_res_blocks):
strides = 1
if stack > 0 and res_block == 0: # first layer but not first stack
strides = 2 # downsample
y = resnet_layer(inputs=x,
num_filters=num_filters,
strides=strides)
y = resnet_layer(inputs=y,
num_filters=num_filters,
activation=None)
if stack > 0 and res_block == 0: # first layer but not first stack
# linear projection residual shortcut connection to match
# changed dims
x = resnet_layer(inputs=x,
num_filters=num_filters,
kernel_size=1,
strides=strides,
activation=None,
batch_normalization=False)
x = keras.layers.add([x, y])
x = Activation('relu')(x)
num_filters *= 2
# Add classifier on top.
# v1 does not use BN after last shortcut connection-ReLU
x = AveragePooling2D(pool_size=8)(x)
y = Flatten()(x)
outputs = Dense(num_classes,
activation='softmax',
kernel_initializer='he_normal')(y)
# Instantiate model.
model = Model(inputs=inputs, outputs=outputs)
return model
model = resnet_v1(input_shape=input_shape, depth=depth)
model.compile(loss='categorical_crossentropy',
optimizer=Adam(lr=lr_schedule(0)),
metrics=['accuracy'])
print(model.summary())
# Prepare model model saving directory.
save_dir = os.path.join(os.getcwd(), 'saved_models')
model_name = 'cifar10_resnet20_model.{epoch:03d}.h5'
if not os.path.isdir(save_dir):
os.makedirs(save_dir)
filepath = os.path.join(save_dir, model_name)
# Prepare callbacks for model saving and for learning rate adjustment.
checkpoint = ModelCheckpoint(filepath=filepath,
monitor='val_accuracy',
verbose=1,
save_best_only=True,
mode='auto')
lr_scheduler = LearningRateScheduler(lr_schedule)
lr_reducer = ReduceLROnPlateau(factor=np.sqrt(0.1),
cooldown=0,
patience=5,
min_lr=0.5e-6)
callbacks = [checkpoint, lr_reducer, lr_scheduler]
# Run training, with or without data augmentation.
if not data_augmentation:
print('Not using data augmentation.')
model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
validation_data=(x_test, y_test),
shuffle=True,
callbacks=callbacks)
else:
print('Using real-time data augmentation.')
# This will do preprocessing and realtime data augmentation:
datagen = ImageDataGenerator(
rotation_range=10,
# randomly shift images horizontally
width_shift_range=0.1,
# randomly shift images vertically
height_shift_range=0.1,
# set range for random shear
horizontal_flip=True)
datagen.fit(x_train)
# Fit the model on the batches generated by datagen.flow().
history = model.fit_generator(datagen.flow(x_train, y_train, batch_size=batch_size),
validation_data=(x_test, y_test),
epochs=epochs, verbose=1,
callbacks=callbacks,
steps_per_epoch= x_train.shape[0] // batch_size)
# Score trained model.
scores = model.evaluate(x_test, y_test, verbose=1)
print('Test loss:', scores[0])
print('Test accuracy:', scores[1])<file_sep>from tensorflow import keras
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# %matplotlib inline
import os
os.environ["CUDA_VISIBLE_DEVICES"]="0"
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
except RuntimeError as e:
print(e)
# Load the generated adversarial inputs for Robustness evaluation.
with np.load("./FGSM_Test.npz") as f:
fgsm_test, fgsm_test_labels = f['advs'], f['labels']
with np.load("./PGD_Test.npz") as f:
pgd_test, pgd_test_labels = f['advs'], f['labels']
fp_test = np.concatenate((fgsm_test, pgd_test))
fp_test_labels = np.concatenate((fgsm_test_labels, pgd_test_labels))
sNums = [500*i for i in [2,4,8,12,20]]
strategies = ['best', 'kmst', 'gini']
acc_pure = [[] for i in range(len(strategies))]
acc_fp = [[] for i in range(len(strategies))]
for num in sNums:
for i in range(len(strategies)):
s = strategies[i]
model_path = "./checkpoint/best_Resnet_MIX_%d_%s.h5" % (num, s)
best_model = keras.models.load_model(model_path)
lfp, afp = best_model.evaluate(fp_test, fp_test_labels, verbose=0)
acc_fp[i].append(afp)
colormap = ['r','limegreen', 'dodgerblue']
plt.figure(figsize=(8,6))
x = [i/max(sNums) for i in sNums]
for i in range(len(strategies)):
plt.plot(x, acc_fp[i],'o-', label=strategies[i], color=colormap[i], linewidth=3, markersize=8)
plt.title("CIFAR-ATTACK", fontsize=20)
plt.xlabel("# Percentage of test cases", fontsize=20)
plt.ylabel("Robustness", fontsize=20)
plt.xticks(x, [1,2,4,6,10],fontsize=15)
plt.yticks(fontsize=15)
plt.legend(fontsize=15)
fig = plt.gcf()
fig.savefig('./cifar_attack_robustness.pdf')
<file_sep>from tensorflow import keras
import tensorflow as tf
import numpy as np
from tensorflow.keras.datasets import cifar10
from tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler
from tensorflow.keras.callbacks import ReduceLROnPlateau
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.regularizers import l2
import random
import os
os.environ["CUDA_VISIBLE_DEVICES"]="0"
# Suppress the GPU memory
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
except RuntimeError as e:
print(e)
def lr_schedule_retrain(epoch):
lr = 1e-4
if epoch > 25:
lr *= 1e-1
print('Learning rate: ', lr)
return lr
def select(foscs, n, s='best', k=1000):
"""
n: the number of selected test cases.
s: strategy, ['best', 'kmst', 'gini']
k: for KM-ST, the number of ranges.
"""
ranks = np.argsort(foscs)
# we choose test cases with small and large fols.
if s == 'best':
h = n//2
return np.concatenate((ranks[:h],ranks[-h:]))
# we choose test cases with small and large fols.
elif s == 'kmst':
index = []
section_w = len(ranks) // k
section_nums = n // section_w
indexes = random.sample(list(range(k)), section_nums)
for i in indexes:
block = ranks[i*section_w: (i+1)*section_w]
index.append(block)
return np.concatenate(np.array(index))
# This is for gini strategy. There is little different from DeepGini paper. See function ginis() in metrics.py
else:
return ranks[:n]
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
# convert class vectors to binary class matrics
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
x_train = x_train/255
x_test = x_test/255
# Load the generated adversarial inputs for training. FGSM and PGD.
with np.load("./FGSM_TrainFull.npz") as f:
fgsm_train, fgsm_train_labels, fgsm_train_fols, fgsm_train_ginis = f['advs'], f['labels'], f['fols'], f['ginis']
with np.load("./PGD_TrainFull.npz") as f:
pgd_train, pgd_train_labels, pgd_train_fols, pgd_train_ginis= f['advs'], f['labels'], f['fols'], f['ginis']
# Load the generated adversarial inputs for testing. FGSM and PGD.
with np.load("./FGSM_Test.npz") as f:
fgsm_test, fgsm_test_labels = f['advs'], f['labels']
with np.load("./PGD_Test.npz") as f:
pgd_test, pgd_test_labels = f['advs'], f['labels']
# Mix the adversarial inputs
fp_train = np.concatenate((fgsm_train, pgd_train))
fp_train_labels = np.concatenate((fgsm_train_labels, pgd_train_labels))
fp_train_fols = np.concatenate((fgsm_train_fols, pgd_train_fols))
fp_train_ginis = np.concatenate((fgsm_train_ginis, pgd_train_ginis))
fp_test = np.concatenate((fgsm_test, pgd_test))
fp_test_labels = np.concatenate((fgsm_test_labels, pgd_test_labels))
sNums = [500*i for i in [2,4,8,12,20]]
strategies = ['best', 'kmst', 'gini']
for num in sNums:
print(num)
for i in range(len(strategies)):
s = strategies[i]
model_path = "./checkpoint/best_Resnet_MIX_%d_%s.h5" % (num, s)
checkpoint = ModelCheckpoint(filepath=model_path, monitor='val_accuracy', verbose=1, save_best_only=True)
lr_scheduler = LearningRateScheduler(lr_schedule_retrain)
lr_reducer = ReduceLROnPlateau(factor=np.sqrt(0.1), cooldown=0, patience=5, min_lr=0.5e-6)
callbacks = [checkpoint, lr_reducer, lr_scheduler]
if s == 'gini':
indexes = select(fp_train_ginis, num, s=s)
else:
indexes = select(fp_train_fols, num, s=s)
selectAdvs = fp_train[indexes]
selectAdvsLabels = fp_train_labels[indexes]
x_train_mix = np.concatenate((x_train, selectAdvs),axis=0)
y_train_mix = np.concatenate((y_train, selectAdvsLabels),axis=0)
# load old model
model = keras.models.load_model("./saved_models/cifar10_resnet20_model.h5")
# model.fit(x_train_mix, y_train_mix, epochs=40, batch_size=64, verbose=1, callbacks=callbacks,
# validation_data=(fp_test, fp_test_labels))
datagen = ImageDataGenerator(rotation_range=10, width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True)
datagen.fit(x_train_mix)
batch_size = 64
history = model.fit_generator(datagen.flow(x_train_mix, y_train_mix, batch_size=batch_size),
validation_data=(fp_test, fp_test_labels),
epochs=40, verbose=1,
callbacks=callbacks,
steps_per_epoch= x_train_mix.shape[0] // batch_size)
|
0e0100b43a8d0c94c4878a8daa5dcecd0a7eeca0
|
[
"Markdown",
"Python"
] | 11
|
Markdown
|
yangzhou6666/RobOT
|
20970b2719fa795dc5ac6fca78b2f1c0931f3211
|
d8c03dd6651e52d12abfc7c70a3dd072162283b1
|
refs/heads/master
|
<repo_name>thomas-smith123/upper-copmuter<file_sep>/qwewq/qwewqDlg.cpp
// qwewqDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "qwewq.h"
#include "qwewqDlg.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// 用于应用程序“关于”菜单项的 CAboutDlg 对话框
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// 对话框数据
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CqwewqDlg 对话框
CqwewqDlg::CqwewqDlg(CWnd* pParent /*=NULL*/)
: CDialogEx(CqwewqDlg::IDD, pParent)
, m_EditReceive(_T(""))
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}
void CqwewqDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDC_MSCOMM1, m_mscomm);
DDX_Text(pDX, IDC_EDIT1, m_EditReceive);
DDX_Control(pDX, IDC_COMBO1, m_combol1);
DDX_Control(pDX, IDC_COMBO2, m_combol2);
DDX_Control(pDX, IDC_COMBO3, m_combol3);
DDX_Control(pDX, IDC_COMBO4, m_combol4);
DDX_Control(pDX, IDC_COMBO5, m_combol5);
DDX_Control(pDX, IDC_EDIT2, m_EditSend);
DDX_Control(pDX, IDC_EDIT1, m_cEditReceive);
}
BEGIN_MESSAGE_MAP(CqwewqDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_BN_CLICKED(IDC_BUTTON_OPEN, &CqwewqDlg::OnBnClickedButtonOpen)
ON_BN_CLICKED(IDC_BUTTON_CLOSE, &CqwewqDlg::OnBnClickedButtonClose)
ON_CBN_SELCHANGE(IDC_COMBO1, &CqwewqDlg::OnCbnSelchangeCombo1)
ON_EN_CHANGE(IDC_EDIT1, &CqwewqDlg::OnEnChangeEdit1)
ON_CBN_SELCHANGE(IDC_COMBO2, &CqwewqDlg::OnCbnSelchangeCombo2)
ON_BN_CLICKED(IDC_BUTTON1, &CqwewqDlg::OnBnClickedButton1)
ON_BN_CLICKED(IDC_BUTTON2, &CqwewqDlg::OnBnClickedButton2)
ON_WM_SIZE()
END_MESSAGE_MAP()
// CqwewqDlg 消息处理程序
BOOL CqwewqDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// 将“关于...”菜单项添加到系统菜单中。
// IDM_ABOUTBOX 必须在系统命令范围内。
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
HICON m_hIcon1 = AfxGetApp()->LoadIcon(IDI_ICON1);
HICON m_hIcon2 = AfxGetApp()->LoadIcon(IDI_ICON2);
SetIcon(m_hIcon1, TRUE); // 设置大图标
SetIcon(m_hIcon2, FALSE); // 设置小图标
// TODO: 在此添加额外的初始化代码
((CComboBox*)GetDlgItem(IDC_COMBO2))->SetCurSel(0);
((CComboBox*)GetDlgItem(IDC_COMBO1))->SetCurSel(0);
((CComboBox*)GetDlgItem(IDC_COMBO3))->SetCurSel(0);
((CComboBox*)GetDlgItem(IDC_COMBO4))->SetCurSel(3);
((CComboBox*)GetDlgItem(IDC_COMBO5))->SetCurSel(0);
CImage myImage;
myImage.Load(_T("d:\\bs\\qwewq\\qwewq\\qwewq\\res\\nuc.bmp"));
CRect rect;
/* CWnd *pWnd = GetDlgItem(IDC_STATIC); // (这是在此资源创建的类的内部, 若是在外部, 可先通过获得CMainFrame的指针, 再通过pMianFrame->GetDlgItem(IDCk_MY_PIC)来获取)
CDC *pDC = pWnd->GetDC();
pWnd->GetClientRect(&rect);
pDC->SetStretchBltMode(STRETCH_HALFTONE);
myImage.Draw(pDC->m_hDC, rect);*/
long lReg;
HKEY hKey;
DWORD MaxValueLength;
DWORD dwValueNumber;
lReg = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
0, KEY_QUERY_VALUE, &hKey);
if (lReg != ERROR_SUCCESS) //成功时返回ERROR_SUCCESS,
{
//MessageBox(TEXT("未自动找到串口!\nOpen Registry Error!\n"));
return FALSE;
}
lReg = RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, NULL, NULL,
&dwValueNumber, &MaxValueLength, NULL, NULL, NULL);
if (lReg != ERROR_SUCCESS) //没有成功
{
//MessageBox(TEXT("未自动找到串口!\nGetting Info Error!\n"));
return FALSE;
}
TCHAR *pValueName, *pCOMNumber;
DWORD cchValueName, dwValueSize = 10;
for (int i = 0; i < dwValueNumber; i++)
{
cchValueName = MaxValueLength + 1;
dwValueSize = 10;
pValueName = (TCHAR*)VirtualAlloc(NULL, cchValueName, MEM_COMMIT, PAGE_READWRITE);
lReg = RegEnumValue(hKey, i, pValueName,
&cchValueName, NULL, NULL, NULL, NULL);
if ((lReg != ERROR_SUCCESS) && (lReg != ERROR_NO_MORE_ITEMS))
{
//MessageBox(TEXT("未自动找到串口!\nEnum Registry Error or No More Items!\n"));
return FALSE;
}
pCOMNumber = (TCHAR*)VirtualAlloc(NULL, 6, MEM_COMMIT, PAGE_READWRITE);
lReg = RegQueryValueEx(hKey, pValueName, NULL,
NULL, (LPBYTE)pCOMNumber, &dwValueSize);
if (lReg != ERROR_SUCCESS)
{
//MessageBox(TEXT("未自动找到串口!\nCan not get the name of the port"));
return FALSE;
}
CString str(pCOMNumber);
int len=str.GetLength();
str = str.Right(len - 3);
((CComboBox*)GetDlgItem(IDC_COMBO1))->SetCurSel(_ttoi(str)-1);//把获取的值加入到ComBox控件中
VirtualFree(pValueName, 0, MEM_RELEASE);
VirtualFree(pCOMNumber, 0, MEM_RELEASE);
}
//CRect rect;
GetClientRect(&rect); //取客户区大小
Old.x=rect.right-rect.left;
Old.y=rect.bottom-rect.top;
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CqwewqDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
}
}
// 如果向对话框添加最小化按钮,则需要下面的代码
// 来绘制该图标。对于使用文档/视图模型的 MFC 应用程序,
// 这将由框架自动完成。
void CqwewqDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // 用于绘制的设备上下文
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// 使图标在工作区矩形中居中
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// 绘制图标
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialogEx::OnPaint();
}
}
//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CqwewqDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
BEGIN_EVENTSINK_MAP(CqwewqDlg, CDialogEx)
ON_EVENT(CqwewqDlg, IDC_MSCOMM1, 1, CqwewqDlg::OnCommMscomm1, VTS_NONE)
END_EVENTSINK_MAP()
void CqwewqDlg::OnCommMscomm1()
{
// TODO: ÔÚ´Ë´¦Ìí¼ÓÏûÏ¢´¦Àí³ÌÐò´úÂë
static unsigned int cnt = 0;
VARIANT variant_inp;
COleSafeArray safearryay_inp;
long len,k;
unsigned int data[1024]={0};
byte rxdata[1024];
CString stremp;
if(m_mscomm.get_CommEvent() == 2)
{
cnt++;
variant_inp = m_mscomm.get_Input();
safearryay_inp = variant_inp;
len = safearryay_inp.GetOneDimSize();
for(k=0;k<len;k++)
{
safearryay_inp.GetElement(&k,rxdata+k);
}
for (k=0;k<len;k++)
{
stremp.Format(_T("%c"),*(rxdata+k));
m_EditReceive += stremp;
CString temp=_T("\n");
m_EditReceive += temp;
}
}
UpdateData(FALSE);
GetDlgItem(IDC_EDIT1)->SendMessage(WM_VSCROLL, MAKEWPARAM(SB_BOTTOM,0),0);//滚动条自动下翻
}
void CqwewqDlg::OnBnClickedButtonOpen()
{
int p,q;
CString a;
// TODO: ÔÚ´ËÌí¼Ó¿Ø¼þ֪ͨ´¦Àí³ÌÐò´úÂë
if(m_mscomm.get_PortOpen())//如果串口是打开的,则行关闭串口
{
m_mscomm.put_PortOpen(FALSE);
}
p=m_combol1.GetCurSel();//get port
q=m_combol2.GetCurSel();
m_mscomm.put_CommPort(p+1);//选择COM1 m_mscomm.put_InBufferSize(1024); //接收缓冲区
m_mscomm.put_OutBufferSize(1024);//发送缓冲区
m_mscomm.put_InputLen(0);//设置当前接收区数据长度为0,表示全部读取
m_mscomm.put_InputMode(1);//以二进制方式读写数据
m_mscomm.put_RThreshold(1);//接收缓冲区有1个及1个以上字符时,将引发接收数据的OnComm
int selectedPos = m_combol2.GetCurSel();
//m_combol2.GetLBText
CString str;
int m_Combo_BOTELV = GetDlgItemInt(IDC_COMBO2);
str.Format(_T("%d,"), m_Combo_BOTELV);
CString m_Combo_JIAOYANWEI, m_Combo_SHUJUWEI, m_Combo_TINGZHIWEI;
GetDlgItemText(IDC_COMBO3, m_Combo_JIAOYANWEI);
GetDlgItemText(IDC_COMBO4, m_Combo_SHUJUWEI);
GetDlgItemText(IDC_COMBO5, m_Combo_TINGZHIWEI);
str = str + m_Combo_JIAOYANWEI+_T(",")+ m_Combo_SHUJUWEI+_T(",")+ m_Combo_TINGZHIWEI;
m_mscomm.put_Settings(str);//波特率,无校验,个数据位,个停止位
// m_mscomm.put_Settings(_T("9600,n,8,1"));//波特率9600无检验位,8个数据位,1个停止位
if(!m_mscomm.get_PortOpen())//如果串口没有打开则打开
{
m_mscomm.put_PortOpen(TRUE);//打开串口
AfxMessageBox(_T("串口打开成功"));
}
else
{
m_mscomm.put_OutBufferCount(0);
AfxMessageBox(_T("串口打开失败"));
}
}
void CqwewqDlg::OnBnClickedButtonClose()
{
// TODO: ÔÚ´ËÌí¼Ó¿Ø¼þ֪ͨ´¦Àí³ÌÐò´úÂë
m_mscomm.put_PortOpen(FALSE);//关闭串口
AfxMessageBox(_T("串口已关闭"));
}
void CqwewqDlg::OnCbnSelchangeCombo1()
{
// TODO: ÔÚ´ËÌí¼Ó¿Ø¼þ֪ͨ´¦Àí³ÌÐò´úÂë
int nIndex = m_combol1.GetCurSel();
CString strCBText;
m_combol1.GetLBText( nIndex, strCBText);
}
void CqwewqDlg::OnEnChangeEdit1()
{
// TODO: Èç¹û¸Ã¿Ø¼þÊÇ RICHEDIT ¿Ø¼þ£¬Ëü½«²»
// ·¢ËÍ´Ë֪ͨ£¬³ý·ÇÖØÐ´ CDialogEx::OnInitDialog()
// º¯Êý²¢µ÷Óà CRichEditCtrl().SetEventMask()£¬
// ͬʱ½« ENM_CHANGE ±êÖ¾¡°»ò¡±ÔËËãµ½ÑÚÂëÖС£
// TODO: ÔÚ´ËÌí¼Ó¿Ø¼þ֪ͨ´¦Àí³ÌÐò´úÂë
}
void CqwewqDlg::OnCbnSelchangeCombo2()
{
// TODO: ÔÚ´ËÌí¼Ó¿Ø¼þ֪ͨ´¦Àí³ÌÐò´úÂë
}
void CqwewqDlg::OnBnClickedButton1()
{
// TODO: ÔÚ´ËÌí¼Ó¿Ø¼þ֪ͨ´¦Àí³ÌÐò´úÂë
UpdateData(true);//读取编辑框内容
CByteArray hexdata;
CString sText,a=0;
m_EditSend.GetWindowText(sText);
// if(this->IsDlgButtonChecked(IDC_CHECK2))
// {
// int len=String2Hex(sText,hexdata);
// sText=hexdata;
// }
//m_mscomm.put_Output(COleVariant(sText));
if(this->IsDlgButtonChecked(IDC_CHECK1))
{
if(this->IsDlgButtonChecked(IDC_CHECK2))
{
int len=String2Hex(sText,hexdata); //此处返回的len可以用于计算发送了多少个十六进制数
m_mscomm.put_Output(COleVariant(hexdata));
m_mscomm.put_Output(COleVariant(a+"\r\n"));
}
else
{
// int len=String2Hex(sText,hexdata); //此处返回的len可以用于计算发送了多少个十六进制数
m_mscomm.put_Output(COleVariant(sText+"\r\n"));
}
}
else
{
if(this->IsDlgButtonChecked(IDC_CHECK2))
{
int len=String2Hex(sText,hexdata); //此处返回的len可以用于计算发送了多少个十六进制数
m_mscomm.put_Output(COleVariant(hexdata));
}
else
{
// int len=String2Hex(sText,hexdata); //此处返回的len可以用于计算发送了多少个十六进制数
m_mscomm.put_Output(COleVariant(sText));
}
}
// m_mscomm.put_Output(COleVariant(sText+"\r\n"));
// else
// m_mscomm.put_Output(COleVariant(sText));
// m_mscomm.put_Output(COleVariant(m_EditSend));//发送数据
UpdateData(false);//更新编辑框内容
}
BOOL CqwewqDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: ÔÚ´ËÌí¼ÓרÓôúÂëºÍ/»òµ÷ÓûùÀà
if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_RETURN)
{
// 如果消息是键盘按下事件,且是Entert键,执行以下代码(什么都不做,你可以自己添加想要的代码)
return TRUE;
}
return CDialogEx::PreTranslateMessage(pMsg);
}
void CqwewqDlg::OnBnClickedButton2()
{
// TODO: ÔÚ´ËÌí¼Ó¿Ø¼þ֪ͨ´¦Àí³ÌÐò´úÂë
GetDlgItem(IDC_EDIT1)->GetWindowText(m_EditReceive);
GetDlgItem(IDC_EDIT1)->SetWindowText(_T(""));
}
int CqwewqDlg::String2Hex(CString str, CByteArray &senddata)
{
int hexdata,lowhexdata;
int hexdatalen=0;
int len=str.GetLength();
senddata.SetSize(len/2);
for(int i=0;i<len;)
{
char lstr,hstr=str[i];
if(hstr==' ')
{
i++;
continue;
}
i++;
if(i>=len)
break;
lstr=str[i];
hexdata=ConvertHexChar(hstr);
lowhexdata=ConvertHexChar(lstr);
if((hexdata==16)||(lowhexdata==16))
break;
else
hexdata=hexdata*16+lowhexdata;
i++;
senddata[hexdatalen]=(char)hexdata;
hexdatalen++;
}
senddata.SetSize(hexdatalen);
return hexdatalen;
}
char CqwewqDlg::ConvertHexChar(char ch)
{
if((ch>='0')&&(ch<='9'))
return ch-0x30;
else if((ch>='A')&&(ch<='F'))
return ch-'A'+10;
else if((ch>='a')&&(ch<='f'))
return ch-'a'+10;
else return (-1);
}
void CqwewqDlg::OnSize(UINT nType, int cx, int cy)
{
CDialogEx::OnSize(nType, cx, cy);
// TODO: ÔÚ´Ë´¦Ìí¼ÓÏûÏ¢´¦Àí³ÌÐò´úÂë
if(nType==SIZE_RESTORED||nType==SIZE_MAXIMIZED)
{
resize();
}
}
void CqwewqDlg::resize()
{
float fsp[2];
POINT Newp; //获取现在对话框的大小
CRect recta;
GetClientRect(&recta); //取客户区大小
Newp.x=recta.right-recta.left;
Newp.y=recta.bottom-recta.top;
fsp[0]=(float)Newp.x/Old.x;
fsp[1]=(float)Newp.y/Old.y;
CRect Rect;
int woc;
CPoint OldTLPoint,TLPoint; //左上角
CPoint OldBRPoint,BRPoint; //右下角
HWND hwndChild=::GetWindow(m_hWnd,GW_CHILD); //列出所有控件
while(hwndChild)
{
woc=::GetDlgCtrlID(hwndChild);//取得ID
GetDlgItem(woc)->GetWindowRect(Rect);
ScreenToClient(Rect);
OldTLPoint = Rect.TopLeft();
TLPoint.x = long(OldTLPoint.x*fsp[0]);
TLPoint.y = long(OldTLPoint.y*fsp[1]);
OldBRPoint = Rect.BottomRight();
BRPoint.x = long(OldBRPoint.x *fsp[0]);
BRPoint.y = long(OldBRPoint.y *fsp[1]);
Rect.SetRect(TLPoint,BRPoint);
GetDlgItem(woc)->MoveWindow(Rect,TRUE);
hwndChild=::GetWindow(hwndChild, GW_HWNDNEXT);
}
Old=Newp;
}<file_sep>/qwewq/ReadMe.txt
================================================================================
MICROSOFT 基础类库: qwewq 项目概述
===============================================================================
应用程序向导已为您创建了这个 qwewq 应用程序。此应用程序不仅演示 Microsoft 基础类的基本使用方法,还可作为您编写应用程序的起点。
本文件概要介绍组成 qwewq 应用程序的每个文件的内容。
qwewq.vcxproj
这是使用应用程序向导生成的 VC++ 项目的主项目文件。
它包含生成该文件的 Visual C++ 的版本信息,以及有关使用应用程序向导选择的平台、配置和项目功能的信息。
qwewq.vcxproj.filters
这是使用“应用程序向导”生成的 VC++ 项目筛选器文件。
它包含有关项目文件与筛选器之间的关联信息。在 IDE 中,通过这种关联,在特定节点下以分组形式显示具有相似扩展名的文件。例如,“.cpp”文件与“源文件”筛选器关联。
qwewq.h
这是应用程序的主要头文件。它包括其他项目特定的头文件(包括 Resource.h),并声明 CqwewqApp 应用程序类。
qwewq.cpp
这是包含应用程序类 CqwewqApp 的主要应用程序源文件。
qwewq.rc
这是程序使用的所有 Microsoft Windows 资源的列表。它包括 RES 子目录中存储的图标、位图和光标。此文件可以直接在 Microsoft Visual C++ 中进行编辑。项目资源位于 2052 中。
res\qwewq.ico
这是用作应用程序图标的图标文件。此图标包括在主要资源文件 qwewq.rc 中。
res\qwewq.rc2
此文件包含不在 Microsoft Visual C++ 中进行编辑的资源。您应该将不可由资源编辑器编辑的所有资源放在此文件中。
/////////////////////////////////////////////////////////////////////////////
应用程序向导创建一个对话框类:
qwewqDlg.h,qwewqDlg.cpp - 对话框
这些文件包含 CqwewqDlg 类。该类定义应用程序主对话框的行为。该对话框的模板位于 qwewq.rc 中,该文件可以在 Microsoft Visual C++ 中进行编辑。
/////////////////////////////////////////////////////////////////////////////
其他功能:
ActiveX 控件
应用程序包括对使用 ActiveX 控件的支持。
打印及打印预览支持
应用程序向导已通过从 MFC 库调用 CView 类中的成员函数,生成了用于处理打印、打印设置和打印预览命令的代码。
/////////////////////////////////////////////////////////////////////////////
其他标准文件:
StdAfx.h,StdAfx.cpp
这些文件用于生成名为 qwewq.pch 的预编译头 (PCH) 文件和名为 StdAfx.obj 的预编译类型文件。
Resource.h
这是标准头文件,它定义新的资源 ID。
Microsoft Visual C++ 读取并更新此文件。
qwewq.manifest
应用程序清单文件供 Windows XP 用来描述应用程序
对特定版本并行程序集的依赖性。加载程序使用此
信息从程序集缓存加载适当的程序集或
从应用程序加载私有信息。应用程序清单可能为了重新分发而作为
与应用程序可执行文件安装在相同文件夹中的外部 .manifest 文件包括,
也可能以资源的形式包括在该可执行文件中。
/////////////////////////////////////////////////////////////////////////////
其他注释:
应用程序向导使用“TODO:”指示应添加或自定义的源代码部分。
如果应用程序在共享的 DLL 中使用 MFC,则需要重新发布这些 MFC DLL;如果应用程序所用的语言与操作系统的当前区域设置不同,则还需要重新发布对应的本地化资源 MFC100XXX.DLL。有关这两个主题的更多信息,请参见 MSDN 文档中有关 Redistributing Visual C++ applications (重新发布 Visual C++ 应用程序)的章节。
/////////////////////////////////////////////////////////////////////////////
<file_sep>/qwewq/qwewqDlg.h
// qwewqDlg.h : 头文件
//
#pragma once
#include "mscomm1.h"
#include "afxwin.h"
// CqwewqDlg 对话框
class CqwewqDlg : public CDialogEx
{
// 构造
public:
CqwewqDlg(CWnd* pParent = NULL); // 标准构造函数
// 对话框数据
enum { IDD = IDD_QWEWQ_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
HICON m_hIcon;
// 生成的消息映射函数
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
CMscomm1 m_mscomm;
DECLARE_EVENTSINK_MAP()
void OnCommMscomm1();
afx_msg void OnBnClickedButtonOpen();
afx_msg void OnBnClickedButtonClose();
CString m_EditReceive;
afx_msg void OnCbnSelchangeCombo1();
CComboBox m_combol1;
afx_msg void OnEnChangeEdit1();
afx_msg void OnCbnSelchangeCombo2();
CComboBox m_combol2;
CComboBox m_combol3;
CComboBox m_combol4;
CComboBox m_combol5;
CEdit m_EditSend;
afx_msg void OnBnClickedButton1();
virtual BOOL PreTranslateMessage(MSG* pMsg);
afx_msg void OnBnClickedButton2();
int String2Hex(CString str, CByteArray &senddata);
char ConvertHexChar(char ch);
//void OnBnClickedCheckAutosend()
CEdit m_cEditReceive;
afx_msg void OnSize(UINT nType, int cx, int cy);
POINT Old;
void resize();
};
|
08bc94081bbf5da5ad6a7cf6ef1360bb6ef50486
|
[
"Text",
"C++"
] | 3
|
C++
|
thomas-smith123/upper-copmuter
|
b3a3da3b5fb22acf89173910b12d782a4873a632
|
7b8aee1cf46242072fce140b52fc39e2dd29cbd0
|
refs/heads/main
|
<repo_name>jorgelisboa/RPG-app<file_sep>/app/src/main/java/com/example/rpgsimpletoken/SheetFactory.java
package com.example.rpgsimpletoken;
public class SheetFactory {
private String dndSheet = "CREATE TABLE dnd ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "name VARCHAR(20) UNIQUE NOT NULL, "
+ "strength VARCHAR(2) NOT NULL, "
+ "dexterity VARCHAR(2) NOT NULL, "
+ "constitution VARCHAR(2) NOT NULL, "
+ "wisdom VARCHAR(2) NOT NULL, "
+ "intelligence VARCHAR(2) NOT NULL), "
+ "charisma VARCHAR(2) NOT NULL);";
String cyberpunksheet = "CREATE TABLE dnd ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "name VARCHAR(20) UNIQUE NOT NULL, "
+ "body VARCHAR(2) NOT NULL, "
+ "reflex VARCHAR(2) NOT NULL, "
+ "tech VARCHAR(2) NOT NULL, "
+ "charisma VARCHAR(2) NOT NULL, "
+ "intelligence VARCHAR(2) NOT NULL);";
public String makeSheet(String sheet) {
if (sheet.equals("cyberpunk")) {
return cyberpunksheet;
}
return dndSheet;
}
}
<file_sep>/settings.gradle
rootProject.name = "RPG Simple Token"
include ':app'
<file_sep>/app/src/main/java/com/example/rpgsimpletoken/RpgDatabase.java
package com.example.rpgsimpletoken;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
public class RpgDatabase extends SQLiteOpenHelper {
MenuActivity menuActivity = new MenuActivity();
public RpgDatabase(@Nullable Context context, int version) {
super(context, "DB", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String dndSheet = "CREATE TABLE dnd ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "name VARCHAR(20) UNIQUE NOT NULL, "
+ "strength VARCHAR(2) NOT NULL, "
+ "dexterity VARCHAR(2) NOT NULL, "
+ "constitution VARCHAR(2) NOT NULL, "
+ "wisdom VARCHAR(2) NOT NULL, "
+ "intelligence VARCHAR(2) NOT NULL, "
+ "charisma VARCHAR(2) NOT NULL);";
String fateSheet = "CREATE TABLE dnd ("
+ "_id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "name VARCHAR(20) UNIQUE NOT NULL, "
+ "body VARCHAR(2) NOT NULL, "
+ "reflex VARCHAR(2) NOT NULL, "
+ "tech VARCHAR(2) NOT NULL, "
+ "charisma VARCHAR(2) NOT NULL, "
+ "intelligence VARCHAR(2) NOT NULL);";
db.execSQL(fateSheet);
db.execSQL(dndSheet);
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
db.execSQL("PRAGMA foreign_keys=ON"); //FK Enable
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public boolean fateSheet(String name,
String body,
String reflex,
String tech,
String charisma,
String intelligence) {
SQLiteDatabase database = getWritableDatabase();
//Pass the values to the "insert"
ContentValues valores = new ContentValues();
valores.put("_id", (byte[]) null);
valores.put("name", name);
valores.put("body", body);
valores.put("reflex", reflex);
valores.put("tech", tech);
valores.put("charisma", charisma);
valores.put("intelligence", intelligence);
//Trying to insert
if (database.insert("fateSheet",null, valores) != -1){
database.close();
return true;
}else{
database.close();
return false;
}
}
public boolean dndSheet(String name,
String strength,
String dexterity,
String constitution,
String wisdom,
String intelligence,
String charisma) {
SQLiteDatabase database = getWritableDatabase();
//Pass the values to the "insert"
ContentValues valores = new ContentValues();
valores.put("_id", (byte[]) null);
valores.put("name", name);
valores.put("strength", strength);
valores.put("dexterity", dexterity);
valores.put("constitution", constitution);
valores.put("wisdom", wisdom);
valores.put("intelligence", intelligence);
valores.put("charisma", charisma);
//Trying to insert
if (database.insert("dndSheet",null, valores) != -1){
database.close();
return true;
}else{
database.close();
return false;
}
}
}
<file_sep>/README.md
# Design-Patterns-Training
<h4>This repository will be used to make a RPG app. So I'm trying to use everything that I can here like:</h4>
<ul>
<li>OOP</li>
<li>Clean Code</li>
<li>Kotlin (if possible)</li>
<li>Design Patterns(if possible)</li>
<li>some NF to Databases</li>
<li>SQLite</li>
</ul>
<hr>
<h4>What the app will do:</h4>
<ul>
<li>Crate character sheets</li>
<li>Create bags for itens</li>
<li>Add itens</li>
<li>Connection with your friends</li>
<li>Dices (3d if we can)</li>
<li>Some grid for the campaings</li>
</ul>
|
3fcd33823ca66f16193f4b2a7aefb7a0b52d9460
|
[
"Markdown",
"Java",
"Gradle"
] | 4
|
Java
|
jorgelisboa/RPG-app
|
ba76094cb87b7c7339c2361480b1bb1dd0a9a3e2
|
0fa47b776d7376614160615dbddec0271096af89
|
refs/heads/master
|
<file_sep>package main
import (
"math"
)
// func main() {
// fmt.Println(maxSubArray([]int{-2, 1, -3, 4, -1, 2, 1, -5, 4}))
// }
func maxSubArray(nums []int) int {
lenNums := len(nums)
if lenNums == 0 {
return 0
} else if lenNums == 1 {
return nums[0]
}
maxSoFar := math.MinInt32
maxEndingHere := 0
for i := 0; i < lenNums; i++ {
maxEndingHere += nums[i]
if maxSoFar < maxEndingHere {
maxSoFar = maxEndingHere
}
if maxEndingHere < 0 {
maxEndingHere = 0
}
}
return maxSoFar
}
<file_sep>package main
// func main() {
// }
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
leftDepth := maxDepth(root.Left)
rightDepth := maxDepth(root.Right)
if leftDepth > rightDepth {
return 1 + leftDepth
}
return 1 + rightDepth
}
<file_sep>package main
import (
"math"
)
// func main() {
// fmt.Println(reverse(-123))
// }
func reverse(x int) int {
isNegative := false
tempVar := x
if x < 0 {
isNegative = true
tempVar = -x
}
newNum := 0
for tempVar > 0 {
digit := tempVar % 10
if !isNegative && (newNum > math.MaxInt32/10 || newNum*10 > math.MaxInt32-digit) {
return 0
} else if isNegative && (-newNum < math.MinInt32/10 || -newNum*10 < math.MinInt32+digit) {
return 0
}
newNum = newNum*10 + digit
tempVar /= 10
}
if isNegative {
newNum = -newNum
}
return newNum
}
<file_sep>package main
func main() {
}
func twoSum2(numbers []int, target int) []int {
start, end := 0, len(numbers)-1
for start < end {
if numbers[start]+numbers[end] == target {
return []int{start + 1, end + 1}
} else if numbers[start]+numbers[end] > target {
end--
} else {
start++
}
}
return nil
}
<file_sep>package main
func main() {
}
func getIntersectionNode(headA, headB *ListNode) *ListNode {
if headA == nil || headB == nil {
return nil
}
headALen, headBLen, temp := 0, 0, headA
for temp.Next != nil {
headALen++
temp = temp.Next
}
for temp = headB; temp.Next != nil; {
headBLen++
temp = temp.Next
}
startA, startB := headA, headB
for headALen < headBLen && startA != nil {
startA = startA.Next
headALen++
}
for headBLen < headALen && startB != nil {
startB = startB.Next
headBLen++
}
if startA == nil || startB == nil {
return nil
}
for startA != nil && startB != nil {
if startA == startB {
return startA
}
startA = startA.Next
startB = startB.Next
}
return nil
}
<file_sep>package main
// func main() {
// fmt.Println(searchInsert([]int{1, 3}, 2))
// }
func searchInsert(nums []int, target int) int {
if len(nums) == 0 {
return 0
}
low, high := 0, len(nums)-1
mid := 0
for low < high {
mid = low + ((high - low) / 2)
if nums[mid] == target {
return mid
} else if nums[mid] > target {
high = mid - 1
} else if nums[mid] < target {
low = mid + 1
}
}
if nums[mid] < target {
for mid < len(nums) && nums[mid] < target {
if mid+1 < len(nums) && nums[mid+1] > target {
return mid + 1
}
mid++
}
return mid
}
for mid > 0 && nums[mid] > target {
if mid-1 >= 0 && nums[mid-1] < target {
return mid
}
mid--
}
return mid
}
<file_sep>package main
import (
"strings"
)
// func main() {
// fmt.Println(isPalindrome2("0P"))
// }
func isPalindrome2(s string) bool {
lenStr := len(s)
if lenStr == 0 {
return true
}
i, j := 0, lenStr-1
tempStr := strings.ToLower(s)
for i <= j {
if !((tempStr[i] >= 97 && tempStr[i] <= 122) || (tempStr[i] >= 48 && tempStr[i] <= 57)) {
i++
continue
} else if !((tempStr[j] >= 97 && tempStr[j] <= 122) || (tempStr[j] >= 48 && tempStr[j] <= 57)) {
j--
continue
}
if tempStr[i] != tempStr[j] {
return false
}
i++
j--
}
return true
}
<file_sep>package main
// func main() {
// }
//TreeNode2 Tree Node
type TreeNode2 struct {
Val int
Left *TreeNode2
Right *TreeNode2
}
func isSymmetric(root *TreeNode2) bool {
if root == nil {
return true
}
return isSymmetricTrees(root.Left, root.Right)
}
func isSymmetricTrees(left *TreeNode2, right *TreeNode2) bool {
if left == nil && right == nil {
return true
} else if left == nil || right == nil {
return false
} else {
return left.Val == right.Val && isSymmetricTrees(left.Left, right.Right) && isSymmetricTrees(left.Right, right.Left)
}
}
<file_sep>package main
import "fmt"
// [,"top","getMin","push","top","getMin","pop","getMin"]
// [,[],[],[],[],[],[],[2147483647],[],[],[-2147483648],[],[],[],[]]
func main() {
obj := Constructor()
obj.Push(2147483646)
obj.Push(2147483646)
obj.Push(2147483647)
fmt.Println(obj.Top())
obj.Pop()
fmt.Println(obj.GetMin())
obj.Pop()
fmt.Println(obj.GetMin())
obj.Pop()
obj.Push(2147483647)
fmt.Println(obj.Top())
fmt.Println(obj.GetMin())
obj.Push(-2147483648)
fmt.Println(obj.Top())
fmt.Println(obj.GetMin())
obj.Pop()
fmt.Println(obj.GetMin())
}
//MinStack struct
type MinStack struct {
top int
stack []int
minStack []int
}
//Constructor ** initialize your data structure here. */
func Constructor() MinStack {
var obj MinStack
return obj
}
//Push function for stacj
func (this *MinStack) Push(x int) {
this.stack = append(this.stack, x)
if this.top == 0 || (this.top > 0 && this.GetMin() > x) {
this.minStack = append(this.minStack, x)
} else {
this.minStack = append(this.minStack, this.GetMin())
}
this.top++
}
//Pop function for stack
func (this *MinStack) Pop() {
if this.top > 0 {
this.minStack = this.minStack[0 : this.top-1]
this.stack = this.stack[0 : this.top-1]
this.top--
}
}
//Top returns Top element in stack
func (this *MinStack) Top() int {
return this.stack[this.top-1]
}
//GetMin return min element in stack
func (this *MinStack) GetMin() int {
return this.minStack[this.top-1]
}
<file_sep>package main
// func main() {
// fmt.Println(twoSum([]int{4, 2, 3}, 6))
// }
func twoSum(nums []int, target int) []int {
mapArr := make(map[int]int)
for index, value := range nums {
val, ok := mapArr[value]
if ok {
return []int{val, index}
}
mapArr[target-value] = index
}
return nil
}
<file_sep>package main
// func main() {
// }
func minDepth(root *TreeNode) int {
if root == nil {
return 0
}
minLeft, minRight := minDepth(root.Left), minDepth(root.Right)
if minLeft == 0 || minRight == 0 {
return minLeft + minRight + 1
}
return 1 + min(minLeft, minRight)
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
<file_sep>package main
import "fmt"
func main() {
fmt.Println(checkPossibility([]int{1, 2, 1, 4, 0}))
}
func checkPossibility(nums []int) bool {
pos := -1
for i := 1; i < len(nums); i++ {
if nums[i-1] > nums[i] {
if pos != -1 {
return false
}
pos = i - 1
}
}
return pos == -1 || (pos == len(nums)-2) || pos == 0 || (nums[pos-1] <= nums[pos+1]) || nums[pos] <= nums[pos+2]
}
<file_sep>package main
import (
"strings"
)
// func main() {
// fmt.Println(lengthOfLastWord("test test "))
// }
func lengthOfLastWord(s string) int {
newStr := strings.TrimSpace(s)
lenStr := len(newStr)
if lenStr == 0 {
return 0
}
var i int
spaceExist := false
for i = lenStr - 1; i > 0; i-- {
if newStr[i] == 32 {
spaceExist = true
break
}
}
if spaceExist {
return lenStr - 1 - i
}
return lenStr
}
<file_sep>package main
import "fmt"
// func main() {
// fmt.Println(isPalindrome(101))
// }
func isPalindrome(x int) bool {
// tempVar := x
if x < 0 || (x > 0 && x%10 == 0) {
return false
}
var result int = 0
// var dig int
for result < x {
// dig = tempVar % 10
result = (result * 10) + (x % 10)
x = x / 10
fmt.Println(x, result)
}
fmt.Println(x, result)
return result == x || result/10 == x
}
<file_sep>package main
// func main() {
// fmt.Println(climbStairs(4))
// }
var memo map[int]int = make(map[int]int)
func climbStairs(n int) int {
res, ok := memo[n]
if ok {
return res
}
if n <= 2 {
memo[n] = n
return n
}
memo[n] = climbStairs(n-1) + climbStairs(n-2)
return memo[n]
}
<file_sep>package main
import (
"strconv"
)
// func main() {
// fmt.Println(addBinary("1111", "100"))
// }
func addBinary(a string, b string) string {
if len(a) == 0 {
return b
} else if len(b) == 0 {
return a
}
var longerStringLen int
if len(a) > len(b) {
longerStringLen = len(a)
} else {
longerStringLen = len(b)
}
result := make([]int, longerStringLen+1)
var carry = 0
k := longerStringLen
var i, j int
for i, j = len(a)-1, len(b)-1; i >= 0 && j >= 0; {
first, _ := strconv.Atoi(string(a[i]))
second, _ := strconv.Atoi(string(b[j]))
sum := first + second + carry
result[k] = (sum % 2)
carry = sum / 2
i--
j--
k--
}
if carry == 1 && i < 0 && j < 0 {
result[k] = 1
} else {
if i >= 0 {
for i >= 0 {
first, _ := strconv.Atoi(string(a[i]))
sum := first + carry
result[k] = (sum % 2)
carry = sum / 2
i--
k--
}
} else if j >= 0 {
for j >= 0 {
first, _ := strconv.Atoi(string(b[j]))
sum := first + carry
result[k] = (sum % 2)
carry = sum / 2
j--
k--
}
}
}
if carry == 1 {
result[k] = 1
}
resultStr := ""
for i = 0; i < len(result); i++ {
if resultStr == "" && result[i] == 0 {
continue
}
resultStr += strconv.Itoa(result[i])
}
if len(resultStr) == 0 && len(result) > 0 {
return "0"
}
return resultStr
}
<file_sep>package main
// func main() {
// fmt.Println(mySqrt(2))
// }
func mySqrt(x int) int {
if x == 0 || x == 1 {
return x
}
var mid int = x / 2
var sq int
var sq1 int
for i := 1; i <= mid; i++ {
sq = i * i
sq1 = (i + 1) * (i + 1)
if sq == x {
return i
} else if sq < x && sq1 > x {
return i
} else if sq < x && sq1 == x {
return i + 1
}
}
return 0
}
<file_sep>package main
// func main() {
// var a *ListNode
// fmt.Println(a)
// }
//ListNode Definition for singly-linked list.
type ListNode struct {
Val int
Next *ListNode
}
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil && l2 == nil {
return nil
} else if l1 == nil {
return l2
} else if l2 == nil {
return l1
}
var head *ListNode
if l1.Val < l2.Val {
head = l1
l1 = l1.Next
} else {
head = l2
l2 = l2.Next
}
tail := head
for l1 != nil && l2 != nil {
if l1.Val < l2.Val {
tail.Next = l1
l1 = l1.Next
} else {
tail.Next = l2
l2 = l2.Next
}
tail = tail.Next
}
for l1 != nil {
tail.Next = l1
l1 = l1.Next
tail = tail.Next
}
for l2 != nil {
tail.Next = l2
l2 = l2.Next
tail = tail.Next
}
return head
}
<file_sep>package main
// func main() {
// fmt.Println(sortedArrayToBST([]int{-10, -3, 0, 5, 9}))
// }
func sortedArrayToBST(nums []int) *TreeNode {
var res TreeNode
if len(nums) == 0 {
return nil
} else if len(nums) == 1 {
res.Val = nums[0]
res.Left, res.Right = nil, nil
return &res
}
mid := len(nums) / 2
res.Val = nums[mid]
res.Left = sortedArrayToBST(nums[0:mid])
res.Right = sortedArrayToBST(nums[mid+1:])
return &res
}
<file_sep>package main
import "fmt"
// func main() {
// merge([]int{4, 5, 6, 0, 0, 0}, 3, []int{1, 2, 3}, 3)
// }
func merge(nums1 []int, m int, nums2 []int, n int) {
resultLen, i, j := m+n-1, m-1, n-1
for i >= 0 && j >= 0 {
if nums1[i] > nums2[j] {
nums1[resultLen] = nums1[i]
i--
resultLen--
} else {
nums1[resultLen] = nums2[j]
j--
resultLen--
}
}
for j >= 0 {
nums1[resultLen] = nums2[j]
j--
resultLen--
}
fmt.Println(nums1)
}
<file_sep>package main
// func main() {
// fmt.Println(removeElement([]int{3, 2, 2, 3}, 3))
// }
func removeElement(nums []int, val int) int {
if len(nums) == 0 || (len(nums) == 1 && nums[0] == val) {
return 0
}
for i := 0; i < len(nums); {
if nums[i] == val {
nums = append(nums[:i], nums[i+1:]...)
continue
}
i++
}
return len(nums)
}
|
ceec5a43e06e8221707d1af489d0f8fa4e785606
|
[
"Go"
] | 21
|
Go
|
MAK131990/leetcode_easy
|
a4031287ca91830ca9f5e561e6baebaac9e7b0d7
|
dbf0ac9e6f2306da86da2316436dee6ca5d302a7
|
refs/heads/master
|
<file_sep># lagouSpider
爬取拉勾网职位信息,存Mysql数据库
<file_sep>
import scrapy
from lagouSpider.items import LagouspiderItem
from scrapy import FormRequest
import time
import random
import json
class lagouSpider(scrapy.Spider):
name = "lagouSpider"
headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36',
'Referer': 'https://www.lagou.com/jobs/list_python?labelWords=&fromSearch=true&suginput=',
}
allowed_domains = ["lagou.com"]
# url地址
base_url = u'https://www.lagou.com/jobs/positionAjax.json?'# px=default&city=%E6%B7%B1%E5%9C%B3&needAddtionalResult=false
# 页码
page = 1
def start_requests(self):
# 请求第一页数据
yield FormRequest(self.base_url, headers=self.headers,
formdata={
'needAddtionalResult': 'false',
'first': 'true',
'pn': str(self.page),
'kd': 'python',
'city': '深圳'
}, callback=self.parse)
def parse(self, response):
print(response.body)
item = LagouspiderItem()
# 解析
data = json.loads(response.body.decode('utf-8'))
result = data['content']['positionResult']['result'] # 职位信息
result_size = data['content']['positionResult']['resultSize'] # 每页条数
total_count = data['content']['positionResult']['totalCount'] # 总条数
for position in result: # 封装item字段
item['position_name'] = position['positionName']
item['city'] = position['city']
item['salary'] = position['salary']
item['work_year'] = position['workYear']
item['company_full_name'] = position['companyFullName']
item['finance_stage'] = position['financeStage']
item['create_time'] = position['createTime']
yield item
time.sleep(random.randint(10, 30)) # 设置每个请求的间隔时间
if int(result_size) == 15:
allpage = int(total_count) / int(result_size) + 1 # 总页数
if self.page < allpage:
self.page += 1
print('正在请求第 %s 页数据' % self.page)
if self.page % 5 == 0:
time.sleep(20) # 防止被禁
yield FormRequest(self.base_url, headers=self.headers,
formdata={
'needAddtionalResult': 'false',
'first': 'false',
'pn': str(self.page),
'kd': 'python',
'city': '深圳'
}, callback=self.parse)
<file_sep># -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class LagouspiderItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
# 标题
position_name = scrapy.Field()
# 工作地址
city = scrapy.Field()
# 薪水待遇
salary = scrapy.Field()
# 工作经验
work_year = scrapy.Field()
# 公司名称
company_full_name = scrapy.Field()
# 融资情况
finance_stage = scrapy.Field()
# 发布时间
create_time = scrapy.Field()
pass
<file_sep># -*- coding: utf-8 -*-
import pymysql
from lagouSpider.items import LagouspiderItem
from lagouSpider import settings
class MySqlPipeline(object):
def __init__(self):
# 建立数据库链接
self.connect = pymysql.connect(
host=settings.MYSQL_HOSTS,
port=settings.MYSQL_PORT,
db=settings.MYSQL_DB,
user=settings.MYSQL_USER,
passwd=settings.MYSQL_PASSWORD,
charset='utf8',
use_unicode=True)
self.cursor = self.connect.cursor()
def process_item(self, item, spider):
if isinstance(item, LagouspiderItem):
position_name = item['position_name']
company_full_name = item['company_full_name']
city = item['city']
ret = self.select_title(position_name, company_full_name, city)
if ret[0] == 1:
print('已经存在')
pass
else:
salary = item['salary']
work_year = item['work_year']
finance_stage = item['finance_stage']
create_time = item['create_time']
self.insert_course(position_name, city, salary, work_year, company_full_name, finance_stage, create_time)
print("存入一条数据" + position_name)
def insert_course(self, position_name, city, salary, work_year, company_full_name, finance_stage, create_time):
data = {
'position_name': position_name,
'city': city,
'salary': salary,
'work_year': work_year,
'company_full_name': company_full_name,
'finance_stage': finance_stage,
'create_time': create_time
}
table = 'logoujob'
keys = ', '.join(data.keys())
values = ', '.join(['%s'] * len(data))
sql = 'INSERT INTO {table}({keys}) VALUES ({values})'.format(table=table, keys=keys, values=values)
try:
self.cursor.execute(sql, tuple(data.values()))
self.connect.commit()
except Exception as e:
self.connect.rollback()
self.connect.close()
def select_title(self, position_name, company_full_name, city):
sql = 'select exists (select 1 from logoujob where position_name = %(position_name)s ' \
'and company_full_name = %(company_full_name)s and city = %(city)s );'
value = {
'position_name': position_name,
'city': city,
'company_full_name': company_full_name
}
self.cursor.execute(sql, value)
return self.cursor.fetchall()[0]
|
012ac56ab50932edc54ba8d0e15cea5ab167e7cc
|
[
"Markdown",
"Python"
] | 4
|
Markdown
|
kyle-zeng/lagouSpider
|
8d21a133edbc8b751b1acdb3c59f615ade21e09a
|
5decb3be79ccf53f919d7144863eaf01ed917d47
|
refs/heads/master
|
<repo_name>GusZimmerman/NODDIanalysis<file_sep>/RUGBY_DTITK_pipeline.sh
#!/bin/sh
#------------------------DTITK processing pipeline----------------------
#--------Written by <NAME>, 2016, Edited by <NAME>, 2017--------
#-----------------------<EMAIL>------------------------
echo "Beginning DTITK pipeline"
module load fsl/5.0.10
module load mricroGL
subj=`cat subjects.txt`
cwd=`pwd`
echo "Adding dtitk to user environment"
export DTITK_ROOT=/apps/software/dtitk/2.3.1/
export PATH=$PATH:$DTITK_ROOT/bin:$DTITK_ROOT/utilities:$DTITK_ROOT/scripts:$DTITK_ROOT/lib:$DTITK_ROOT/include
echo "Creating dtitk files"
mkdir ./DTITK
for f in ${subj};do
fsl_to_dtitk ${f}/dti;
cp ${f}/dti_dtitk.nii.gz DTITK/${f}_dtitk.nii.gz;done
echo "Making DTITK directory and copying files over"
cd DTITK/;
for i in *_dtitk.nii.gz;do
echo ${i};done>DTI_subjs.txt;
cp /group/tbi/ERANET/Scripts/MedLegal_Tracts_DTITK/* .
echo "Bootstrapping data"
export DTITK_ROOT=/apps/software/dtitk/2.3.1/
export PATH=$PATH:$DTITK_ROOT/bin:$DTITK_ROOT/utilities:$DTITK_ROOT/scripts:$DTITK_ROOT/lib:$DTITK_ROOT/include
dti_template_bootstrap ixi_aging_template.nii.gz DTI_subjs.txt;
echo "Complete-now performing rigid registration"
dti_rigid_population mean_initial.nii.gz DTI_subjs.txt EDS 3;
echo "Complete-now performing affine registration"
dti_affine_population mean_initial.nii.gz DTI_subjs.txt EDS 3;
echo "Complete"
TVtool -in mean_affine3.nii.gz -tr;
echo "Creating mask for diffeomorphic registration"
BinaryThresholdImageFilter mean_affine3_tr.nii.gz mask.nii.gz 0.01 100 1 0;
echo "Running Diffeomorphic registration"
dti_diffeomorphic_population mean_affine3.nii.gz DTI_subjs_aff.txt mask.nii.gz 0.002;
echo "Complete"
echo "Making images 1mm isotropic"
dti_warp_to_template_group DTI_subjs.txt mean_diffeomorphic_initial6.nii.gz 1 1 1;
echo "Combining the affine and diffeomorphic registrations"
for f in *_dtitk.nii.gz;do echo ${f/.nii.gz/};done>DTI_subjects_combined.txt;
for f in `cat DTI_subjects_combined.txt`;do dfRightComposeAffine -aff ${f}.aff -df ${f}_aff_diffeo.df.nii.gz -out ${f}_combined.df.nii.gz;done
echo "Rigid registration to IITmeantensor256-MNI space"
dti_rigid_reg IITmean_tensor_256.nii mean_diffeomorphic_initial6.nii.gz EDS 4 4 4 0.001;
echo "Affine registration to IITmeantensor256"
dti_affine_reg IITmean_tensor_256.nii mean_diffeomorphic_initial6.nii.gz EDS 4 4 4 0.001 1;
echo "Diffeomorphic registration to IITmeantensor 256"
dti_diffeomorphic_reg IITmean_tensor_256.nii mean_diffeomorphic_initial6_aff.nii.gz IITmean_tensor_mask_256.nii.gz 1 6 0.002;
dfRightComposeAffine -aff mean_diffeomorphic_initial6.aff -df mean_diffeomorphic_initial6_aff_diffeo.df.nii.gz -out mean_combined.df.nii.gz;
echo "Transforming subjects from native to standard space"
for f in `cat DTI_subjects_combined.txt`;do dfComposition -df2 ${f}_combined.df.nii.gz -df1 mean_combined.df.nii.gz -out ${f}_to_standard.df.nii.gz;done;
for f in `cat DTI_subjects_combined.txt`;do deformationSymTensor3DVolume -in ${f}.nii.gz -trans ${f}_to_standard.df.nii.gz -target IITmean_tensor_256.nii -out ${f}_to_standard.nii.gz;done;
echo "Creating 4d file of all subjects registrations to standard space for QC"
fslmerge -t all_subjs_to_standard_tensor.nii.gz *_to_standard.nii.gz;
echo "Creating mean tensor image for subjects"
for f in *_to_standard.nii.gz;do echo ${f};done>DTI_subjs_normalised256.txt;
TVMean -in DTI_subjs_normalised256.txt -out mean_final_high_res.nii.gz;
echo "Creating mean FA image for all subjects"
TVtool -in mean_final_high_res.nii.gz -fa;
cp mean_final_high_res_fa.nii.gz mean_FA.nii.gz;
tbss_skeleton -i mean_FA.nii.gz -o mean_FA_skeleton;
echo "Creating individuals FA maps normalised to standard space"
for f in `cat DTI_subjs_normalised256.txt`;do TVtool -in ${f} -fa;TVtool -in ${f} -tr;done;
echo "Creating MD maps normalised to standard space"
for f in `cat DTI_subjs_normalised256.txt`; do MDsubj=${f%_to_standard.nii.gz}; fslmaths ${MDsubj}_to_standard_tr.nii.gz -div 3 ${MDsubj}_to_standard_md.nii.gz;done;
fslmerge -t all_FA.nii.gz *_to_standard_fa.nii.gz;
echo "Creating TBSS directories for TBSS prcoessing step 4 and statistics"
mkdir TBSS;
mkdir TBSS/FA;
mkdir TBSS/stats;
cp IITmean_tensor_256.nii TBSS/FA/target.nii.gz;
cp all_FA.nii.gz TBSS/stats/;
cp mean_FA* TBSS/stats/;
fslmaths all_FA -max 0 -Tmin -bin mean_FA_mask -odt char;
cp mean_FA_mask.nii.gz TBSS/stats/;
cd TBSS/;
tbss_4_prestats 0.2;
echo "Done-Ready for TBSS or signle subject statistics"
done
<file_sep>/README.md
# NODDIanalysis
Scripts for initial NODDI analysis tailored for RUGBY study data.
Requires FSL, Freesurfer, DTITK.
<file_sep>/RUGBY_NODDI_pipeline.sh
#!/bin/sh
#RUGBY_NODDI_pipeline_Freesurfer.sh
#
#SBATCH --job-name=DTIFIT_Freesurfer
#SBATCH --ntasks=1
#
#
#SBATCH --partition=long
#SBATCH --mem=8
#
#-----------------RUGBY DTIFIT Processing steps-------------------
#-----------------Script created by <NAME> Oct 2017-----------
#----------------<EMAIL>-------------------
dcm2niix -z y -o ${1} -f ${1}_%p scans;
#-z y for compression to nii.gz, -o output, -f filename (Subj_Scantype), location of DICOMS.
cp scans/*NODDI_90dir_9b0_multishell*.nii.gz ${1}.nii.gz;
cp scans/*NODDI_90dir_9b0_multishell*.bvec ${1}.bvec;
cp scans/*NODDI_90dir_9b0_multishell*.bval ${1}.bval;
cp scans/*NODDI_b0_reversed.nii.gz P2A_b0.nii.gz;
cp scans/*MPRAGE_ADNI_P2.nii.gz ${1}_T1.nii.gz;
echo create A2P_b0 ${1}
fslroi ${1}.nii.gz A2P_b0 0 1
fslmerge -t A2P_P2A_b0 A2P_b0 P2A_b0
printf "0 -1 0 0.09144\n0 1 0 0.09144\n" > acqparams.txt
echo topup ${1}
topup --imain=A2P_P2A_b0 --datain=acqparams.txt --config=b02b0.cnf --out=my_topup_results --iout=my_hifi_b0
echo fslmaths ${1}
fslmaths my_hifi_b0 -Tmean my_hifi_b0
## Freesurfer ReconAll (creates a skull-stripped brain)
recon-all -subject ${1} -sd /group/tbi/RUGBY/DTI/${1} -i ${1}_T1.nii.gz -all -qcache
#recon-all -subject ${1} -i ${1}_T1.nii.gz -autorecon1
#can add T2 flair?
# Convert from FREESURFER space back to native anatomical space
mri_vol2vol --mov ${1}/mri/brainmask.mgz --targ ${1}/mri/rawavg.mgz --regheader --o ${1}/mri/brainmask-in-rawavg.mgz --no-save-reg
# convert freesurfer mgz output brainmask to nii
mri_convert -ot nii ${1}/mri/brainmask-in-rawavg.mgz ${1}/mri/brainmask.nii.gz
# Register T1 data to NODDI data for the first time, remember filter (duplication)
flirt -in ${1}/mri/brainmask.nii.gz -ref ${1}.nii.gz -out T1toNODDIbrain.nii.gz -omat T1toNODDI.mat -dof 6
# Extracting mask from T1 freesurfer output
fslmaths T1toNODDIbrain.nii.gz -thr 0 -bin ${1}_mask1.nii.gz
echo creating index
echo `fslinfo ${1}.nii.gz` > numvolumes.txt
vol=`grep -E -o -w "dim4.{0,4}" numvolumes.txt| sed 's/^.* //'`
indx=""
for ((i=1; i<=${vol}; i+=1)); do indx="$indx 1"; done
echo $indx > index.txt
echo eddy correcting ${1}
eddy_openmp --imain=${1}.nii.gz --mask=${1}_mask1.nii.gz --acqp=acqparams.txt --index=index.txt --bvecs=${1}.bvec --bvals=${1}.bval --topup=my_topup_results --repol --out=eddy_corrected_data;
# After eddy, register again T1 to NODDI, should be a better registration
flirt -in ${1}/mri/brainmask.nii.gz -ref eddy_corrected_data.nii.gz -out my_hifi_b0_brain.nii.gz -omat T1toEDDY.mat -dof 6
# After eddy, custom node that extracts mask from T1 freesurfer output
fslmaths my_hifi_b0_brain.nii.gz -thr 0 -bin my_hifi_b0_brain_mask.nii.gz
# MASK eddy output by FINAL T1 BRAIN MASK (T1 registered to eddy corrected NODDI)?
echo dtifit ${1}
dtifit --data=eddy_corrected_data.nii.gz --out=dti --mask=my_hifi_b0_brain_mask --bvecs=eddy_corrected_data.eddy_rotated_bvecs --bvals=${1}.bval -w;
mkdir /group/tbi/RUGBY/NODDI/${1};
echo Extracting post-processing files for ${1}
cp my_hifi_b0_brain_mask.nii.gz /group/tbi/RUGBY/NODDI/${1}/;
cp eddy_corrected_data.nii.gz /group/tbi/RUGBY/NODDI/${1}/NODDI_DWI.nii.gz;
cp ${1}.bval /group/tbi/RUGBY/NODDI/${1}/NODDI_protocol.bval;
cp ${1}.bvec /group/tbi/RUGBY/NODDI/${1}/NODDI_protocol.bvec;
gunzip /group/tbi/RUGBY/NODDI/${1}/my_hifi_b0_brain_mask.nii.gz;
gunzip /group/tbi/RUGBY/NODDI/${1}/NODDI_DWI.nii.gz;
cd ${cwd};
done
|
15e5bb285075bfabb1fc5413a6f1a7f9e90d7873
|
[
"Markdown",
"Shell"
] | 3
|
Shell
|
GusZimmerman/NODDIanalysis
|
4ffc985e14a6f7e6a5a3495d684fbc85872ac394
|
b93e9ca27d8e99e155004e1bfb3aa106daef3fbb
|
refs/heads/master
|
<file_sep>select * from t_user;
drop table t_user;
create table t_user(
id int primary key not null,
name varchar2(20),
password varchar2(20)
);
insert into t_user(id,name,password) values(1,'gejian','123');
commit;<file_sep>package com.gejian.service;
import java.util.List;
import com.gejian.entity.User;
public interface UserService {
public List<User> findAllUsers();
public User findUserById(int id);
public void insertUser(User user);
public void updateUser(User user);
}
<file_sep>package com.gejian.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisSqlSessionFactory {
private static SqlSessionFactory sqlSessionFactory;
private static final Properties PROPERTIES=new Properties();
static{
try{
InputStream is=DataSourceFactory.class.getResourceAsStream("/com/gejian/conf/application.properties");
PROPERTIES.load(is);
}catch(Exception e){
e.printStackTrace();
}
}
public static SqlSessionFactory getSqlSessionFactory(){
if(sqlSessionFactory==null){
InputStream inputStream=null;
try{
inputStream=Resources.getResourceAsStream("mybatis-config.xml");
sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
}catch(Exception e){
e.printStackTrace();
}finally{
if(inputStream!=null){
try{
inputStream.close();
}catch(Exception e){}
}
}
}
return sqlSessionFactory;
}
public static SqlSession getSqlSession(){
return getSqlSessionFactory().openSession();
}
public static Connection getConnection(){
String driver=PROPERTIES.getProperty("jdbc.driverClassName");
String url=PROPERTIES.getProperty("jdbc.url");
String username=PROPERTIES.getProperty("jdbc.username");
String password=PROPERTIES.getProperty("jdbc.password");
Connection conn=null;
try{
Class.forName(driver);
conn=DriverManager.getConnection(url, username, password);
}catch(Exception e){
throw new RuntimeException();
}
return conn;
}
}
<file_sep>This program is to test Mybatis framework,it does some easy CRUD operations.
|
1783fb5c4861950c5f2a22246492e9172f26a372
|
[
"Java",
"SQL",
"Markdown"
] | 4
|
SQL
|
yixiqiuyu/mybatis2
|
d6804d3bd64b70b183f2c40a851fd578698ed3a8
|
0e19ba5a9f8a13e8a89523d1c2846e5b0626b337
|
refs/heads/master
|
<file_sep>import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Login from '../components/login';
import * as accountActions from '../actions/account';
function mapStateToProps(state) {
return {
counter: state.counter
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(accountActions, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Login);
<file_sep>import { connect } from 'react-redux';
import Dashboard from '../components/dashboard';
function mapStateToProps(/* state */) {
return {};
}
export default connect(mapStateToProps)(Dashboard);
<file_sep>import {FETCH_MEMBER_DATA} from '../actions/const';
const initState = {
isFetching: false,
items: []
};
export default function (state=initState, action) {
switch(action.type) {
case `${FETCH_MEMBER_DATA}_PENDING`:
return Object.assign({},state,{isFetching: true});
case `${FETCH_MEMBER_DATA}_FULFILLED`:
return Object.assign({},state,{isFetching: false, items: action.payload.data});
default:
return state
}
}
<file_sep>
// Member
export const FETCH_MEMBER_DATA = "FETCH_MEMBER_DATA";
// Account
export const LOGIN = "LOGIN";
<file_sep>import React from 'react';
import { Route } from 'react-router';
import App from '../containers/App';
import Login from '../containers/Login';
import Member from '../containers/Member';
export default (
<div>
<Route path="/" component={Login} />
<Route path="/board" component={App}>
<Route path="/member" component={Member} />
</Route>
</div>
);
|
d5817e2161a971abfa790fd73c157db6d8d093b6
|
[
"JavaScript"
] | 5
|
JavaScript
|
myblue/redux-startkit
|
009e3dd25af33cd26e0637499bec8852fe68287e
|
d7cce5e71b431d47744ce78f8b11d194837ada71
|
refs/heads/master
|
<repo_name>macrozone/furbius<file_sep>/app/lib/diff.js
Meteor.startup(function(){
/* the function */
_.mixin({
shallowDiff: function(a,b) {
return _.omit(a, function(v,k) { return b[k] === v; })
},
diff: function(a,b) {
var r = {};
_.each(a, function(v,k) {
if(b[k] === v) return;
// but what if it returns an empty object? still attach?
r[k] = _.isObject(v)
? _.diff(v, b[k])
: v
;
});
return r;
}
});
});
|
0cdf02cf107c3534d1077200e47315ec1297107d
|
[
"JavaScript"
] | 1
|
JavaScript
|
macrozone/furbius
|
1234511d3d9dcd29c2c8ca38d2de734b994fa90d
|
2037f8d47705b727f4e29dabc038fbcb5a094d15
|
refs/heads/main
|
<file_sep>// 1. Comenzamos a hacer la comparación de elementos adyacentes
// 2. Repetimos hasta tener una pasada completa sin ningún swap
#include <stdio.h>
void cambiar_pos(int *n1, int *n2)
{
int temp = *n1;
*n1 = *n2;
*n2 = temp;
}
void bubbleSort(int vector_entrada[], int n)
{
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (vector_entrada[j] > vector_entrada[j + 1])
{
cambiar_pos(&vector_entrada[j], &vector_entrada[j + 1]);
}
}
}
}
int print_array(int vector_entrada[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d, ", vector_entrada[i]);
printf("\nFin del ordenamiento\n");
}
int main(int argc, char const *argv[])
{
int vector_entrada[] = {80, 20, 74, 98, 21, 73, 39, 64, 14, 83};
int n = sizeof(vector_entrada) / sizeof(vector_entrada[0]);
bubbleSort(vector_entrada, n);
print_array(vector_entrada, n);
printf("\n");
return 0;
}
<file_sep>// Para crear una Queue debemos seguir los siguientes pasos:
// Crear un pointer para saber que hay en front y rear
// Colocar estos valores en -1 al inicializar
// Incrementar en 1 el valor de “rear” cuando agregamos un elemento
// Retornar el valor de front al quitar un elemento e incrementar en 1 el valor de front a usar dequeue.
// Antes de agregar un elemento revisar si hay espacios
// Antes de remover un elemento revisamos que existan elementos
// Asegurarnos de que al remover todos los elementos resetear nuestro front y rear a -1 y agregar el valor de 0 a Front al hacer nuestro primer enqueue
#include <stdio.h>
#define SIZE 5
int values[SIZE], front = -1, rear = -1;
void enQueue(int value)
{
if (rear == SIZE - 1)
printf("Nuestro queue está lleno\n");
else
{
if (front == -1)
front = 0;
rear++;
values[rear] = value;
printf("Se insertó el valor %d correctamente\n", value);
}
}
void deQueue()
{
if (front == -1)
printf("Nuestro queue está vacío\n");
else
{
printf("Se eliminó el valor %d\n", values[front]);
front++;
if (front > rear)
front = rear = -1;
}
}
int main(int argc, char const *argv[])
{
enQueue(1); // Se insertó el valor 1 correctamente
enQueue(2); // Se insertó el valor 2 correctamente
enQueue(3); // Se insertó el valor 3 correctamente
enQueue(4); // Se insertó el valor 4 correctamente
enQueue(5); // Se insertó el valor 5 correctamente
deQueue(); // Se eliminó el valor 1
deQueue(); // Se eliminó el valor 2
deQueue(); // Se eliminó el valor 3
deQueue(); // Se eliminó el valor 4
deQueue(); // Se eliminó el valor 5
enQueue(6); // Se insertó el valor 6 correctamente
return 0;
}
<file_sep>array = [
3, 94, 86, 82, 90,
10, 87, 36, 61, 8,
17, 15, 22, 10, 23,
78, 25, 2, 30, 45,
98, 43, 98, 59, 53,
57, 2, 64, 1, 41,
32, 58, 19, 99, 60,
74, 48, 80, 44, 25,
68, 1, 89, 77, 60,
25, 99, 30, 76, 32,
57, 82, 52, 44, 72,
87, 34, 87, 65, 30,
54, 6, 31, 33, 44,
44, 42, 82, 90, 17,
9, 98, 28, 86, 69,
3, 17, 8, 45, 98,
12, 47, 95, 43, 72,
39, 41, 82, 74, 56,
65, 79, 50, 26, 67,
100, 24, 67, 38, 57
]
def merge(array1, array2):
merged_array = []
i1 = 0
i2 = 0
while i1 < len(array1) and i2 < len(array2):
if array1[i1] < array2[i2]:
merged_array.append(array1[i1])
if i1 == len(array1) - 1:
for x2 in array2[i2:]:
merged_array.append(x2)
return merged_array
i1 += 1
else:
merged_array.append(array2[i2])
if i2 == len(array2) - 1:
for x1 in array1[i1:]:
merged_array.append(x1)
return merged_array
i2 += 1
def merge_sort(array):
if len(array) == 1:
return array
else:
m = int(len(array) / 2)
array1 = array[:m]
array2 = array[m:]
sorted_array1 = merge_sort(array1)
sorted_array2 = merge_sort(array2)
return merge(sorted_array1, sorted_array2)
print(array)
sorted_array = merge_sort(array)
print(sorted_array)
<file_sep># Curso Básico de Algoritmos
<p align='center'>
<img src='https://static.platzi.com/media/achievements/badge-algoritmos-c236ef79-8ebb-44c9-b0c0-9f233d6ce18b.png' alt='logo_curso_basico_algoritmos_platzi' width='100px' />
</p>
Avance del [Curso Básico de Algoritmos](https://platzi.com/clases/algoritmos/) de Platzi
Mis apuntes: https://www.notion.so/Curso-B-sico-de-Algoritmos-a4c68fccb558419184bfcf64712f6e77
|
3833c64caefffa8d088b2f0cec52482d51a1f501
|
[
"Markdown",
"C",
"Python"
] | 4
|
C
|
cristianiniguez/curso_basico_algoritmos
|
9ee254b7a977732ef567f6922306c6cf718e07a9
|
a01314873471541c20c8cf0b8053523a151afa50
|
refs/heads/master
|
<repo_name>custom-components/sensor.yandex_maps<file_sep>/custom_components/yandex_maps/sensor.py
"""
A platform which give you the time it will take to drive.
For more details about this component, please refer to the documentation at
https://github.com/custom-components/sensor.yandex_maps
"""
import logging
import re
import aiohttp
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.helpers.entity import Entity
coords_re = re.compile(r'-?\d{1,2}\.\d{1,6},\s?-?\d{1,3}\.\d{1,6}')
__version__ = '0.0.6'
CONF_NAME = 'name'
CONF_START = 'start'
CONF_DESTINATION = 'destination'
ICON = 'mdi:car'
BASE_URL = 'https://yandex.ru/geohelper/api/v1/router?points={}~{}'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_NAME): cv.string,
vol.Required(CONF_START): cv.string,
vol.Required(CONF_DESTINATION): cv.string,
})
_LOGGER = logging.getLogger(__name__)
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None): # pylint: disable=unused-argument
"""Setup sensor platform."""
name = config['name']
start = config['start']
destination = config['destination']
async_add_entities(
[YandexMapsSensor(hass, name, start, destination)], True)
class YandexMapsSensor(Entity):
"""YandexMap Sensor class"""
def __init__(self, hass, name, start, destination):
self.hass = hass
self._state = None
self._name = name
self._start = start
self._destination = destination
self.attr = {}
_LOGGER.debug('Initialized sensor %s with %s, %s', self._name, self._start, self._destination)
async def async_update(self):
"""Update sensor."""
_LOGGER.debug('%s - Running update', self._name)
try:
url = BASE_URL.format(self.start, self.destination)
_LOGGER.debug('Requesting url %s', url)
async with aiohttp.ClientSession() as client:
async with client.get(url) as resp:
assert resp.status == 200
info = await resp.json()
self._state = info.get('direct', {}).get('time')
self.attr = {
'mapurl': info.get('direct', {}).get('mapUrl'),
'jamsrate': info.get('jamsRate'),
'jamsmeasure': info.get('jamsMeasure')
}
except Exception as error: # pylint: disable=broad-except
_LOGGER.debug('%s - Could not update - %s', self._name, error)
@classmethod
def is_coord(cls, data: str) -> bool:
return bool(coords_re.fullmatch(data))
@property
def start(self):
return self.point_to_coords(self._start)
@property
def destination(self):
return self.point_to_coords(self._destination)
def point_to_coords(self, point: str) -> str:
if YandexMapsSensor.is_coord(point):
return point
state = self.hass.states.get(point)
if state:
latitude = state.attributes.get('latitude')
longitude = state.attributes.get('longitude')
if latitude and longitude:
return "{},{}".format(longitude, latitude)
else:
raise AttributeError
@property
def name(self):
"""Name."""
return self._name
@property
def state(self):
"""State."""
return self._state
@property
def icon(self):
"""Icon."""
return ICON
@property
def unit_of_measurement(self):
"""unit_of_measurement."""
return 'мин'
@property
def extra_state_attributes(self):
"""Attributes."""
return self.attr
<file_sep>/README.md
# sensor.yandex_maps
[![BuyMeCoffee][buymecoffeebedge]][buymecoffee]
[](https://github.com/custom-components/custom_updater)
_A platform which give you the time it will take to drive._
**Data is fetched from yandex.ru.**
![example][exampleimg]
## Installation
To get started put `/custom_components/yandex_maps/sensor.py` here:
`<config directory>/custom_components/yandex_maps/sensor.py`
## Example configuration.yaml
```yaml
sensor:
platform: yandex_maps
start: 'device_tracker.my_phone'
destination: '29.361133,54.991133'
name: Time to work
```
## Configuration variables
key | type | description
:--- | :--- | :---
**platform (Required)** | string | The platform name.
**start (Required)** | string | ID of an entity which have `latitude` and `longitude` attributes, or GPS coordinates like `'29.361133,54.991133'`.
**destination (Required)** | string | ID of an entity which have `latitude` and `longitude` attributes, or GPS coordinates like `'29.361133,54.991133'`.
**name (Required)** | string | Name of the sensor.
***
[exampleimg]: example.png
[buymecoffee]: https://www.buymeacoffee.com/ludeeus
[buymecoffeebedge]: https://camo.githubusercontent.com/cd005dca0ef55d7725912ec03a936d3a7c8de5b5/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6275792532306d6525323061253230636f666665652d646f6e6174652d79656c6c6f772e737667
|
a2c78b7e12b04273f4684f58fdf5ddc4e1f6f63f
|
[
"Markdown",
"Python"
] | 2
|
Python
|
custom-components/sensor.yandex_maps
|
bdd76a8cc448afdef35fac9b53cb600cc63ae145
|
47f197e6eb667364f2ab78891e9ddc2ee81948b5
|
refs/heads/master
|
<file_sep># WPU Open Graph Cache
Ensure Open Graph Cache is Fresh
Features :
---
* Clear og cache after post publication.
* Clear og cache for old posts via a cronjob.
How to install :
---
* Put this folder to your wp-content/plugins/ folder.
* Activate the plugin in "Plugins" admin section.
<file_sep><?php
/*
Plugin Name: WPU Open Graph Cache
Plugin URI: https://github.com/Darklg/WPUtilities
Description: Ensure Open Graph Cache is Fresh
Version: 0.1
Author: Darklg
Author URI: http://darklg.me/
License: MIT License
License URI: http://opensource.org/licenses/MIT
*/
if (!defined('ABSPATH')) {
return;
}
class WPUOGCache {
private $cache_key = 'wpuogcache_cleared';
private $cron_key = 'wpuogcache_clearposts';
public function __construct() {
add_action('init', array(&$this,
'init'
));
add_action('save_post', array(&$this,
'clearPostCache'
), 90, 2);
add_action($this->cron_key, array(&$this,
'clearPosts'
));
}
public function init() {
if (!wp_next_scheduled($this->cron_key)) {
wp_schedule_event(time(), 'hourly', $this->cron_key);
}
}
public function clearPosts() {
$wpq_latest_posts = new WP_Query(array(
'posts_per_page' => 5,
'meta_query' => array(
array(
'key' => $this->cache_key,
'compare' => 'NOT EXISTS'
)
)
));
while ($wpq_latest_posts->have_posts()) {
$wpq_latest_posts->the_post();
$this->clearCacheForUrl(get_the_ID(), get_permalink());
}
wp_reset_postdata();
}
public function clearPostCache($post_id, $post) {
$post_status = get_post_status($post);
if ($post_status == 'publish') {
$this->clearCacheForUrl($post_id, get_permalink($post_id));
}
}
public function clearCacheForUrl($id, $url) {
$response = wp_remote_post('https://graph.facebook.com/', array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'blocking' => false,
'headers' => array(),
'body' => array(
'id' => $url,
'scrape' => 'true'
)
));
update_post_meta($id, $this->cache_key, '1');
}
}
$WPUOGCache = new WPUOGCache();
|
19f7190ef15fb8604d834169c39589a1ce610155
|
[
"Markdown",
"PHP"
] | 2
|
Markdown
|
WordPressUtilities/wpuogcache
|
34f7dd42cd2a53f546daaf17c7b897fe0b14efff
|
ef9f618f130ea16986adde38ea59faa2137c23f3
|
refs/heads/main
|
<repo_name>otator/books-wep-app<file_sep>/public/app.js
'use strict';
// alert("Working fine");
$('#form-container').hide();
$('#update-button').on('click', function(){
$('#form-container').toggle();
// alert('clicked');
});
let showMenu = true;
// to hide select button from details page
$('#select-button').hide();
$('#menu-bar').on('click', function(){
$('#menu').slideToggle(1000,function(){
showMenu =!showMenu;
if(!showMenu){
for(let i=50;i>=0; i--)
$('#menu-bar').animate({'margin-left':`${i}px`},25);
}
});
});<file_sep>/README.md
# books-wep-app<file_sep>/data/migrations/1614769416158-lab14.md
# create a lab14 database
CREATE DATABASE lab14;
# use the schema.sql and seed.sql file in the lab folder to populate new database from the terminal
psql -f /data/schema.sql -d lab14
psql -f /data/seed.sql -d lab14
# verify that the lab-14 DB if it has contents:
SELECT COUNT(*) FROM books;
# creating a copy of the database to normalize it:
CREATE DATABASE lab14_normal WITH TEMPLATE lab14;
# Database Migration
# create a second table in the lab14_normal database named authors.
CREATE TABLE AUTHORS (id SERIAL PRIMARY KEY, name VARCHAR(255));
# This query will use a simple subquery to retrieve unique author values from the books table and insert each one into the authors table in the name column.
INSERT INTO authors(name) SELECT DISTINCT author FROM books;
# Confirm the success of this command by typing
SELECT COUNT(*) FROM authors;
# add a column to the books table named author_id.
ALTER TABLE books ADD COLUMN author_id INT;
# This query will prepare a connection between the two tables. It works by running a subquery for every row in the books table. The subquery finds the author row that has a name matching the current book's author value. The id of that author row is then set as the value of the author_id property in the current book row.
UPDATE books SET author_id=author.id FROM (SELECT * FROM authors) AS author WHERE books.author = author.name;
# modify the books table by removing the column named author.
ALTER TABLE books DROP COLUMN author;
# modify the data type of the author_id in the books table, setting it as a foreign key which references the primary key in the authors table.
ALTER TABLE books ADD CONSTRAINT fk_authors FOREIGN KEY (author_id) REFERENCES authors(id);
|
4d451a7ad6e90d400ba5d285b7ca53b823800a89
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
otator/books-wep-app
|
d6a7dec38dafcac3975300cb699dfb1a22b4690a
|
9d93b9115f37d5cae2bef39758d53d21d6faa034
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
"""
Created on Thu Dec 19 16:48:40 2019
@author: SUPERMAN
"""
import cv2
import numpy as np
import os
#path =
fol= ['training', 'testing', 'validation']
classes = ['forehand_openstands','forehand_volley','forehead_slice','kick_service','slice_service', 'smash']
for path in fol:
for clss in classes:
paths = "/home/devil/Documents/orbitShifters/framed_data/"+path+"/"+clss+"/"""
print('links',paths)
li = os.listdir(paths)
print(len(li))
for image in li:
img = cv2.imread(paths+image)
if img is None:
print(type(img))
os.remove(paths+image)
print(paths+image)
<file_sep>import os
import cv2
class Frame_(object):
def FrameCapture(self, path, video_arr):
print(video_arr)
count = 0
for i in range(len(video_arr)):
path_ = path + video_arr[i]
print(path_)
vidObj = cv2.VideoCapture(path_)
success = 1
while success:
success, image = vidObj.read()
cv2.imwrite("/home/devil/Documents/orbitShifters/frames/frame%d.jpg" % count, image)
print(count)
count += 1
def frame_checker(self, path):
for image in os.listdir(path):
delete = False
try:
Image = cv2.imread(path+image)
if Image is None:
delete = True
except:
print("Except")
delete = True
if delete:
print("[INFO] deleting Image {}".format(path+image))
os.remove(path+image)
if __name__ == '__main__':
filepath = "/home/devil/Documents/orbitShifters/sampleVideos/"
path_ima = "/home/devil/Documents/orbitShifters/frames/"
video_arr = []
for video in os.listdir(filepath):
video_arr.append(video)
c = Frame_()
c.FrameCapture(filepath, video_arr)
c.frame_checker(path_ima)
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 12 11:34:25 2019
@author: saireddy
"""
import numpy as np
import os
import cv2
def change_img_to_npy(path, new_path):
for i, img in enumerate(os.listdir(path)):
try:
if img is not None:
color = cv2.imread(path+img, cv2.IMREAD_COLOR)
np.save(new_path+"{}.npy".format(str(i)), color)
print("INFO [], SUCESSS............")
except:
print("Except")
if __name__ == "__main__":
path = "/home/saireddy/Action/TrainImages/goalresized/"
new_path = "/home/saireddy/Action/TrainImages/newgoal/"
change_img_to_npy(path, new_path)
def numpy_to_csv(path, path_train):
Train_data = []
for data_train in os.listdir(path_train):
array_train = np.load(path_train+data_train, allow_pickle = True)
Train_data.append(array_train)
arr = []
for i in range(len(Train_data)):
data = Train_data[i].reshape((50*50*3, -1))
arr.append(data)
with open(path, 'w') as fdata:
try:
for i in range(len(Train_data)):
print(i)
for j in range(arr[1].shape[0]):
if j != ((50*50*3) - 1):
fdata.write("{:.1f},".format(int(arr[i][j][0])))
elif j == ((50*50*3) - 1):
print("Hii", i)
fdata.write("{:.1f}\n".format(int(arr[i][j][0])))
except:
raise "ValueError:Sorry Proper Numpy array was not found"
if __name__ == "__main__":
path = "/home/saireddy/Action/TrainImages/file.csv"
path_train = "/home/saireddy/Action/TrainImages/newgoal/"
numpy_to_csv(path, path_train)
import pandas as pd
names = ["column{}".format(i) for i in range(0, ((50*50*3) - 1))]
data_set = pd.read_csv("/home/saireddy/Action/TrainImages/file.csv", header = None)
label = ["{}".format("goal") for i in range(0, data_set.shape[0])]
data_set['labels'] = label
data_set.to_csv("/home/saireddy/Action/TrainImages/Train.csv", index = False)
data = pd.read_csv("/home/saireddy/Action/ValImages/Test.csv", header = None)<file_sep>from keras import applications
from keras.models import Model, Sequential
from keras.layers import Dense, Input, BatchNormalization
from keras.layers.pooling import GlobalAveragePooling2D, GlobalAveragePooling1D
from keras.layers.recurrent import LSTM
from keras.layers.wrappers import TimeDistributed
from keras.optimizers import Nadam, SGD, Adam
#from keras.preprocessing.image import ImageDataGenerator
from keras.layers.convolutional_recurrent import ConvLSTM2D
from keras.layers import Conv3D, Conv2D, MaxPool2D, Flatten, Dropout, Lambda
import os
import numpy as np
import keras.backend as K
from keras.preprocessing.image import img_to_array, load_img
import pandas as pd
from ImageGenerator_v2 import ImageDataGenerator
train_data_dir = "/home/saireddy/Action/TrainImages"
validation_data_dir = "/home/saireddy/Action/ValImages"
def obtain_datagen(datagen, train_path):
return datagen.flow_from_directory(train_path, class_mode='binary',
target_size=(320, 180), classes = ['goal', 'FreeKick'],
batch_size=8, frames_per_step=2)
datagen = ImageDataGenerator(
rescale=1./ 225,
shear_range=0.2,
zoom_range=0.2)
train_generator = obtain_datagen(datagen, train_data_dir)
validation_generator = obtain_datagen(datagen, validation_data_dir)
frames = 2
img_width = 320
img_height = 180
channels = 3
model = Sequential()
model.add(TimeDistributed(Conv2D(5, 2, 2,activation='relu'
,border_mode='valid'),
input_shape = (frames, img_width, img_height, channels)))
print(model.output_shape)
model.add(TimeDistributed(Flatten()))
print(model.output_shape)
#model.add(Dropout(0.5, input_shape = (16, 30)))
model.add(LSTM(3, return_sequences=False))
print(model.output_shape)
model.add(Dense(2, activation = 'sigmoid'))
model.summary()
optimizer = SGD(lr=0.01)
loss = 'sparse_categorical_crossentropy'
model.compile(loss=loss,optimizer=optimizer, metrics=['accuracy'])
history = model.fit_generator(train_generator,
steps_per_epoch=80,
epochs=50,
validation_data=validation_generator,
validation_steps=40)
model.save("/home/saireddy/Action/LRCNN2.h5")
######Testing-----------------*****************
score = model.evaluate(X_train, y_train, steps=10)
print("Accuracyloss:-", score[0])
print("AccuracyScore",score[1] )
import matplotlib.pyplot as plt
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 14 17:46:47 2019
@author: saireddy
"""
import cv2
import numpy as np
from keras.models import load_model
model = load_model("/home/saireddy/Action/LRCNN.h5")
model.summary()
classes = ['goal', 'FreeKick']
cap = cv2.VideoCapture("/home/saireddy/Action/Input.mp4")
FILE_OUTPUT = "/home/saireddy/Action/Trail3.avi"
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
out = cv2.VideoWriter(FILE_OUTPUT, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'),
10, (frame_width, frame_height))
count = 0
#Q = deque(maxlen= "size")
while cap.isOpened():
_, frame = cap.read()
pos_frame = cap.get(cv2.CAP_PROP_POS_FRAMES)
if frame is not None:
output = frame.copy()
frame_count = ("Frames:{}".format(count))
count= count + 1
else:
print("sorry frames was ****completed****")
break
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
resized = cv2.resize(frame, ((360//2)*2, 640//2), interpolation = cv2.INTER_CUBIC)
frame1 = resized.reshape(1, 2, 320, 180, 3)
pred_array = model.predict(frame1)
print(pred_array)
result = classes[np.argmax(pred_array)]
score = float("%0.2f" % (max(pred_array[0]) * 100))
text1 = ("Activity:{} |".format(result))
cv2.putText(output, text1, (35, 50), cv2.FONT_HERSHEY_PLAIN, 1.25, (255, 255, 255), 2)
cv2.rectangle(output, (20, 30), (590, 60), color=(0, 255, 0), thickness=2)
text = ("Score:{} |".format(score))
cv2.putText(output, text, (290, 50), cv2.FONT_HERSHEY_PLAIN, 1.25, (255, 255, 255), 2)
cv2.putText(output, frame_count, (450, 50), cv2.FONT_HERSHEY_PLAIN, 1.25, (0, 255, 155), 2)
print(f'Result: {result}, Score: {score}')
cv2.imshow("frame", output)
out.write(output)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()<file_sep>import cv2
import time
import numpy as np
import math
import numpy as np
from scipy.spatial import distance
import matplotlib.pyplot as plt
__author__ = "<NAME>"
cap = cv2.VideoCapture(0)
#cap = cv2.VideoCapture("/home/saireddy/Desktop/walk.mp4")
cascade = cv2.CascadeClassifier("/home/saireddy/Action/LSTM+CNN/haarcascade_frontalface_alt.xml")
#fps = cap.get(cv2.CAP_PROP_FPS)
#print ("Frames per second :{0}".format(fps))
FILE_OUTPUT = "/home/saireddy/Desktop/output2.mp4"
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
out = cv2.VideoWriter(FILE_OUTPUT, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'),
10, (frame_width, frame_height))
spee = []
Distance = []
cex = []
cey = []
D = []
s = []
prev = []
def dist(centroid):
for i in range(len(centroid)-1):
print(centroid)
dst = distance.euclidean(centroid[i], centroid[i+1])
#dst = (dst)//0.03
D.append(dst)
return dst
#print("INFO[]... Please Enter **Width and Height in same Shape**")
#width = int(input("INFO[] Enter the width of the window:-"))
#height = int(input("INFO[] Enter the height of the window:-"))
centroid = []
while cap.isOpened():
_, image = cap.read()
if image is None:
break
#resize= cv2.resize(image, (width, height), interpolation = cv2.INTER_CUBIC)
#image = resize.reshape(width, height, 3)
#image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#image = cv2.GaussianBlur(image, (5, 5), 0)
#diff = cv2.absdiff(first_frame, image)
#cv2.imshow("diff", diff)
body = cascade.detectMultiScale(image, 1.3, 1)
for (x, y, w, h) in body:
rect = cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
if True:
ceX = int(x+w/2)
ceY = int(y+h/2)
cex.append(ceX)
cey.append(ceY)
#print("Centoid", (ceX, ceY))
print("length:-", len(centroid))
if len(centroid) < 3:
print("Appended", len(centroid))
centroid.append((ceX, ceY))
else:
print("Length of the Centroid:-", len(centroid))
continue
if len(centroid) == 2:
print("distance:", (dist(centroid)/30)*(3.6))
cv2.putText(image, "distance:- {} km/hr".format(str((dist(centroid)/30)*3.6)), (x-25 , y-25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
cv2.circle(image, (int(x+w/2), int(y+h/2)), 5, (0, 255, 255), -1)
cv2.putText(image, "centroid", (int(x+w/2) - 25, int(y+h/2) - 25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
else:
print("Passed")
continue
if len(centroid) > 2:
centroid.remove(centroid[0])
else:
print("Removed:-", centroid.remove(centroid[0]))
continue
cv2.imshow("image", image)
out.write(image)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
out.release()
cv2.destroyAllWindows()
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 2 09:50:29 2019
@author: saireddy
"""
import cv2
import argparse
import numpy as np
from scipy.spatial import distance
import matplotlib.pyplot as plt
ap = argparse.ArgumentParser()
ap.add_argument('-c', '--config',
help = 'path to yolo config file', default='/home/saireddy/Desktop/Dark/darknet/Data/yolov3-tiny.cfg')
ap.add_argument('-w', '--weights',
help = 'path to yolo pre-trained weights', default='/home/saireddy/Desktop/Dark/darknet/backup2/yolov3-tiny_100.weights')
ap.add_argument('-cl', '--classes',
help = 'path to text file containing class names',default='/home/saireddy/Desktop/Dark/darknet/Data/obj.names')
args = ap.parse_args()
# Get names of output layers, output for YOLOv3 is ['yolo_16', 'yolo_23']
def getOutputsNames(net):
layersNames = net.getLayerNames()
return [layersNames[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# Darw a rectangle surrounding the object and its class name
def draw_pred(img, class_id, confidence, x, y, x_plus_w, y_plus_h):
label = str(classes[class_id])
color = COLORS[class_id]
cv2.rectangle(img, (x,y), (x_plus_w,y_plus_h), color, 2)
cv2.putText(img, label, (x-10,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
# Define a window to show the cam stream on it
window_title= "Rubiks Detector"
cv2.namedWindow(window_title, cv2.WINDOW_NORMAL)
# Load names classes
classes = None
with open(args.classes, 'r') as f:
classes = [line.strip() for line in f.readlines()]
print(classes)
#Generate color for each class randomly
COLORS = np.random.uniform(0, 255, size=(len(classes), 3))
# Define network from configuration file and load the weights from the given weights file
net = cv2.dnn.readNet(args.weights,args.config)
# Define video capture for default cam
cap = cv2.VideoCapture('/home/saireddy/Desktop/Dark/darknet/red.mp4')
FILE_OUTPUT = "/home/saireddy/Desktop/output3.mp4"
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
out = cv2.VideoWriter(FILE_OUTPUT, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'),
10, (frame_width, frame_height))
spee = []
Distance = []
cex = []
cey = []
D = []
s = []
prev = []
def dist(centroid):
for i in range(len(centroid)-1):
print(centroid)
dst = distance.euclidean(centroid[i], centroid[i+1])
#dst = (dst)//0.03
D.append(dst)
return dst
print("INFO[]... Please Enter **Width and Height in same Shape**")
#width = int(input("INFO[] Enter the width of the window:-"))
#height = int(input("INFO[] Enter the height of the window:-"))
width = 680
height = 680
centroid = []
#while cv2.waitKey(1) < 0:
while cap.isOpened():
hasframe, image = cap.read()
#image=cv2.resize(image, (620, 480))
if image is None:
break
resize= cv2.resize(image, (width, height), interpolation = cv2.INTER_CUBIC)
image = resize.reshape(width, height, 3)
blob = cv2.dnn.blobFromImage(image, 1.0/255.0, (416,416), [0,0,0], True, crop=False)
Width = image.shape[1]
Height = image.shape[0]
net.setInput(blob)
outs = net.forward(getOutputsNames(net))
class_ids = []
confidences = []
boxes = []
conf_threshold = 0.5
nms_threshold = 0.4
#print(len(outs))
# In case of tiny YOLOv3 we have 2 output(outs) from 2 different scales [3 bounding box per each scale]
# For normal normal YOLOv3 we have 3 output(outs) from 3 different scales [3 bounding box per each scale]
# For tiny YOLOv3, the first output will be 507x6 = 13x13x18
# 18=3*(4+1+1) 4 boundingbox offsets, 1 objectness prediction, and 1 class score.
# and the second output will be = 2028x6=26x26x18 (18=3*6)
for out in outs:
#print(out.shape)
for detection in out:
#each detection has the form like this [center_x center_y width height obj_score class_1_score class_2_score ..]
scores = detection[5:]#classes scores starts from index 5
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.9:
center_x = int(detection[0] * Width)
center_y = int(detection[1] * Height)
w = int(detection[2] * Width)
h = int(detection[3] * Height)
x = center_x - w / 2
y = center_y - h / 2
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([x, y, w, h])
# apply non-maximum suppression algorithm on the bounding boxes
indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)
#print(x, y, w, h)
for i in indices:
i = i[0]
box = boxes[i]
x = box[0]
y = box[1]
w = box[2]
h = box[3]
draw_pred(image, class_ids[i], confidences[i], round(x), round(y), round(x+w), round(y+h))
if True:
ceX = int(x+w/2)
ceY = int(y+h/2)
cex.append(ceX)
cey.append(ceY)
print("Centoid", (ceX, ceY))
print("length:-", len(centroid))
if len(centroid) < 3:
print("Appended", len(centroid))
centroid.append((ceX, ceY))
else:
print("Length of the Centroid:-", len(centroid))
continue
if len(centroid) == 2:
#print("speed:", (dist(centroid)/30)*(3.6)
speed = (dist(centroid)/30)*3.6
if speed < 40:
print("speed:-", speed)
cv2.putText(image, "speed:- %.2f km/hr" % (speed), (int(x-25) , int(y-25)),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
#cv2.circle(image, (int(x+w/2), int(y+h/2)), 5, (0, 255, 255), -1)
#cv2.putText(image, "centroid", (int(x+w/2) - 25, int(y+h/2) - 25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
else:
pass
else:
print("Passed")
continue
if len(centroid) > 2:
centroid.remove(centroid[0])
else:
print("Removed:-", centroid.remove(centroid[0]))
continue
# Put efficiency information.
t, _ = net.getPerfProfile()
label = 'Inference time: %.2f ms' % (t * 1000.0 / cv2.getTickFrequency())
cv2.putText(image, label, (0, 15), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0))
cv2.imshow(window_title, image)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
cap.release()
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 19 02:36:51 2019
@author: saireddy
"""
__author__ = "<NAME>"
from keras import applications
from keras.models import Model, Sequential
from keras.layers import Dense, Input, BatchNormalization
from keras.layers.pooling import GlobalAveragePooling2D, GlobalAveragePooling1D
from keras.layers.recurrent import LSTM
from keras.layers.wrappers import TimeDistributed
from keras.optimizers import Nadam, SGD, Adam, RMSprop
#from keras.preprocessing.image import ImageDataGenerator #2D DATA
from keras.layers.convolutional_recurrent import ConvLSTM2D
from keras.layers import Conv3D, Conv2D, MaxPool2D, Flatten, Dropout, Lambda, ZeroPadding2D
import os
import numpy as np
import keras.backend as K
from keras.preprocessing.image import img_to_array, load_img
import pandas as pd
from Generator import ImageDataGenerator ##3D DATA
from keras import regularizers
from keras.callbacks import ModelCheckpoint, LearningRateScheduler, TensorBoard, EarlyStopping
from Mail import MailSender
datagen = ImageDataGenerator(
rescale = 1./255,
featurewise_center=True,
samplewise_center=True,
rotation_range=40, width_shift_range=0.3,
height_shift_range=0.2,
shear_range=0.4, zoom_range=[0.2, 0.5],
channel_shift_range=0.0, fill_mode='nearest',
cval=0.0, horizontal_flip=True, vertical_flip=True,
data_format=None)
frames = 6
train_generator = datagen.flow_from_directory("/home/saireddy/Action/Tennis/TrainImages", class_mode='categorical',
target_size=(320, 180),
classes = ['backhand', 'smash'],
batch_size=8, frames_per_step=frames)
validation_generator = datagen.flow_from_directory("/home/saireddy/Action/Tennis/ValImages", class_mode='categorical',
target_size=(320, 180),
classes = ['backhand', 'smash'],
batch_size=8, frames_per_step=frames)
test_generator = datagen.flow_from_directory("/home/saireddy/Action/Tennis/TestImages", class_mode='categorical',
target_size=(320, 180),
classes = ['backhand', 'smash'],
batch_size=8, frames_per_step=frames)
img_width = 320
img_height = 180
channels = 3
dropout = 0.5
batch_size = 8
print(batch_size, frames, img_width, img_height, channels)
#MODEL .........-----------**************************##
model = Sequential()
###CONV LAYER
model.add(TimeDistributed(Conv2D(3, 5, 1,activation='relu'
,border_mode='same'),
input_shape = (frames, img_width, img_height, channels)))
print(model.output_shape)
model.add(Dropout(dropout))
###CONV2
model.add(TimeDistributed(MaxPool2D((2,2))))
model.add(BatchNormalization())
model.add(TimeDistributed(ZeroPadding2D(1)))
model.add(TimeDistributed(Conv2D(5, 5, 1,activation='relu'
,border_mode='same')))
print(model.output_shape)
###CONV3
model.add(Dropout(dropout))
#model.add(TimeDistributed(MaxPool2D((2,2))))
model.add(BatchNormalization())
#model.add(TimeDistributed(ZeroPadding2D(1)))
model.add(TimeDistributed(Conv2D(7, 5, 1,activation='relu'
,border_mode='same')))
##CONV 4
model.add(TimeDistributed(MaxPool2D((2,2))))
#model.add(BatchNormalization())
model.add(TimeDistributed(ZeroPadding2D(1)))
model.add(TimeDistributed(Conv2D(13, 5, 1,activation='relu'
,border_mode='same')))
###CONV 5
model.add(BatchNormalization())
model.add(Dropout(dropout))
print(model.output_shape)
#model.add(TimeDistributed(ZeroPadding2D(1)))
model.add(TimeDistributed(Conv2D(17, 5, 1,activation='relu'
,border_mode='same')))
####CONV 6
model.add(TimeDistributed(MaxPool2D((2,2))))
#model.add(BatchNormalization())
model.add(TimeDistributed(ZeroPadding2D(1)))
model.add(TimeDistributed(Conv2D(20, 5, 1,activation='relu'
,border_mode='same')))
###CONV 7
model.add(Dropout(dropout))
#model.add(BatchNormalization())
model.add(TimeDistributed(MaxPool2D((2,2))))
model.add(TimeDistributed(Conv2D(23, 3, 1,activation='relu'
,border_mode='same')))
###conv 8
model.add(TimeDistributed(Conv2D(27, 3, 1,activation='relu'
,border_mode='same')))
####CONV 9
model.add(Dropout(dropout))
model.add(BatchNormalization())
model.add(TimeDistributed(MaxPool2D((2,2))))
model.add(TimeDistributed(Conv2D(32, 3, 1,activation='relu'
,border_mode='same')))
###conv 10
model.add(TimeDistributed(Conv2D(35, 3, 1,activation='relu'
,border_mode='same')))
####FLATTEN LAYER
model.add(TimeDistributed(Flatten()))
print(model.output_shape)
model.add(Dropout(dropout))
####LSTM LAYER
model.add(LSTM(10, return_sequences=False))
###DENSE LAYER1
model.add(Dropout(dropout))
print(model.output_shape)
model.add(BatchNormalization())
model.add(Dropout(dropout))
model.add(Dense(500, activation='relu'))
####DENSE LAYER2
model.add(BatchNormalization())
model.add(Dropout(dropout))
model.add(Dense(250, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(dropout))
#####DENSE LAYER3
model.add(Dense(150, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(dropout))
####OUTPUT LAYER
model.add(Dense(2 , activation = 'softmax'))
model.summary()
# Train the model for a specified number of epochs.
optimizer = SGD(lr=0.005, decay=1e-6/8, momentum=0.88, nesterov=True)
#optimizer = RMSprop(lr=0.005, rho=0.8, epsilon=1e-10, decay=1e-10)
#optimizer = Adam(lr = 0.001, beta_1=0.8, beta_2=0.999,epsilon=None,decay=0.0, amsgrad=True)
model.compile(loss= ['categorical_crossentropy'],
optimizer=optimizer,
metrics = ['accuracy'])
checkpoint = ModelCheckpoint("/home/saireddy/Action/Tennis/LRCNNTennis.h5", monitor='val_acc', verbose=1,
save_best_only=True, save_weights_only=False, mode='auto', period=1)
#early = EarlyStopping(monitor='val_acc', min_delta=0, patience=15, verbose=1, mode='auto')
epochs = 10
num = int(input("INFO[] ENTER NUMBER WHICH YOU NEED TO DIVIDE:-"))
for epoch in range(epochs):
history = model.fit_generator(train_generator, steps_per_epoch = 1,
epochs=1, validation_data=validation_generator,
validation_steps = 1, verbose=1,
callbacks = [checkpoint])
if (epoch)%num == 0:
val_acc = history.history['val_acc']
val_acc = val_acc[-1]
acc = history.history['acc']
acc = acc[-1]
mail = MailSender("Message", "<EMAIL>", "<PASSWORD>", "<EMAIL>", 47, val_acc, acc, epoch, num)
mail.mailsend()
# Evaluate the model with the eval dataset.
score = model.evaluate_generator(test_generator, steps = 2)
import matplotlib.pyplot as plt
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
print('Test loss:', score[0])
print('Test accuracy:', score[1])
<file_sep>#!/usr/bin/env python
# coding: utf-8
# In[1]:
import tensorflow as tf
# In[7]:
from tensorflow.keras import applications
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Dense, Input, BatchNormalization
from tensorflow.keras.layers import GlobalAveragePooling2D, GlobalAveragePooling1D
from tensorflow.keras.layers import LSTM
from tensorflow.keras.layers import TimeDistributed
from tensorflow.keras.optimizers import Nadam, SGD, Adam, RMSprop
#from tensorflow.keras.preprocessing.image import ImageDataGenerator #2D DATA
from tensorflow.keras.layers import ConvLSTM2D
from tensorflow.keras.layers import Conv3D, Conv2D, MaxPool2D, Flatten, Dropout, Lambda, ZeroPadding2D
import os
import numpy as np
import tensorflow.keras.backend as K
from tensorflow.keras.preprocessing.image import img_to_array, load_img
import pandas as pd
from Generator import ImageDataGenerator ##3D DATA
from tensorflow.keras import regularizers
from tensorflow.keras.callbacks import ModelCheckpoint, LearningRateScheduler, TensorBoard, EarlyStopping
import matplotlib.pyplot as plt
#from Mail import MailSender
# In[3]:
datagen = ImageDataGenerator(
rescale = 1./255,
featurewise_center=True,
samplewise_center=True,
rotation_range=40, width_shift_range=0.3,
height_shift_range=0.2,
shear_range=0.4, zoom_range=[0.2, 0.5],
channel_shift_range=0.0, fill_mode='nearest',
cval=0.0, horizontal_flip=True,
vertical_flip=True,data_format=None)
frames = 6
train_generator = datagen.flow_from_directory("/home/saireddy/Action/Tennis/TrainImages", class_mode='categorical',
target_size=(320, 180),
classes = ['backhand', 'smash'],
batch_size=8, frames_per_step=frames)
validation_generator = datagen.flow_from_directory("/home/saireddy/Action/Tennis/ValImages", class_mode='categorical',
target_size=(320, 180),
classes = ['backhand', 'smash'],
batch_size=8, frames_per_step=frames)
test_generator = datagen.flow_from_directory("/home/saireddy/Action/Tennis/TestImages", class_mode='categorical',
target_size=(320, 180),
classes = ['backhand', 'smash'],
batch_size=8, frames_per_step=frames)
img_width = 320
img_height = 180
channels = 3
dropout = 0.5
batch_size = 8
print(batch_size, frames, img_width, img_height, channels)
#MODEL .........-----------**************************##
### tennis function for model architecture
def tennis(n_model=Sequential()):
model = n_model
###CONV LAYER
model.add(TimeDistributed(Conv2D(3, 5, 1,activation='relu',padding='same'),
input_shape = (frames, img_width, img_height, channels)))
print(model.output_shape)
model.add(Dropout(dropout))
###CONV 2
model.add(TimeDistributed(MaxPool2D((2,2))))
model.add(BatchNormalization())
model.add(TimeDistributed(ZeroPadding2D(1)))
model.add(TimeDistributed(Conv2D(5, 5, 1,activation='relu'
,padding='same')))
print(model.output_shape)
###CONV 3
model.add(Dropout(dropout))
model.add(BatchNormalization())
model.add(TimeDistributed(Conv2D(7, 5, 1,activation='relu'
,padding='same')))
##CONV 4
model.add(TimeDistributed(MaxPool2D((2,2))))
model.add(TimeDistributed(ZeroPadding2D(1)))
model.add(TimeDistributed(Conv2D(13, 5, 1,activation='relu'
,padding='same')))
###CONV 5
model.add(BatchNormalization())
model.add(Dropout(dropout))
print(model.output_shape)
model.add(TimeDistributed(Conv2D(17, 5, 1,activation='relu'
,padding='same')))
####CONV 6
model.add(TimeDistributed(MaxPool2D((2,2))))
model.add(TimeDistributed(ZeroPadding2D(1)))
model.add(TimeDistributed(Conv2D(20, 5, 1,activation='relu'
,padding='same')))
###CONV 7
model.add(Dropout(dropout))
model.add(TimeDistributed(MaxPool2D((2,2))))
model.add(TimeDistributed(Conv2D(23, 3, 1,activation='relu'
,padding='same')))
###conv 8
model.add(TimeDistributed(Conv2D(27, 3, 1,activation='relu'
,padding='same')))
####CONV 9
model.add(Dropout(dropout))
model.add(BatchNormalization())
model.add(TimeDistributed(MaxPool2D((2,2))))
model.add(TimeDistributed(Conv2D(32, 3, 1,activation='relu'
,padding='same')))
###conv 10
model.add(TimeDistributed(Conv2D(35, 3, 1,activation='relu'
,padding='same')))
####FLATTEN LAYER
model.add(TimeDistributed(Flatten()))
print(model.output_shape)
model.add(Dropout(dropout))
####LSTM LAYER
model.add(LSTM(10, return_sequences=False))
###DENSE LAYER1
model.add(Dropout(dropout))
print(model.output_shape)
model.add(BatchNormalization())
model.add(Dropout(dropout))
model.add(Dense(500, activation='relu'))
####DENSE LAYER2
model.add(BatchNormalization())
model.add(Dropout(dropout))
model.add(Dense(250, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(dropout))
#####DENSE LAYER3
model.add(Dense(150, activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(dropout))
####OUTPUT LAYER
model.add(Dense(2 , activation = 'softmax'))
return model.summary(), model
model, mainmodel=tennis(n_model=Sequential())
# Train the model for a specified number of epochs.
optimizer = SGD(lr=0.005, decay=1e-6/8, momentum=0.88, nesterov=True)
mainmodel.compile(loss= ['categorical_crossentropy'],
optimizer=optimizer,
metrics = ['accuracy'])
checkpoint = ModelCheckpoint("/home/saireddy/Action/Tennis/LRCNNTennis.h5", monitor='val_acc', verbose=1,
save_best_only=True, save_weights_only=False, mode='auto', period=1)
history = mainmodel.fit_generator(train_generator, steps_per_epoch = 1,
epochs=1, validation_data=validation_generator,
validation_steps = 1,verbose=1,callbacks = [checkpoint])
# Evaluate the model with the eval dataset.
score = model.evaluate_generator(test_generator, steps = 2)
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
print('Test loss:', score[0])
print('Test accuracy:', score[1])
# ##### Required Comments
# In[ ]:
### conv3 comment layers
#model.add(TimeDistributed(MaxPool2D((2,2))))
#model.add(TimeDistributed(ZeroPadding2D(1)))
### conv4 comment layers
#model.add(BatchNormalization())
### conv5 comment layers
#model.add(TimeDistributed(ZeroPadding2D(1)))
### con6 comment layers
#model.add(BatchNormalization())
### con7 comment layers
#model.add(BatchNormalization())
#optimizer = RMSprop(lr=0.005, rho=0.8, epsilon=1e-10, decay=1e-10)
#optimizer = Adam(lr = 0.001, beta_1=0.8, beta_2=0.999,epsilon=None,decay=0.0, amsgrad=True)
#early = EarlyStopping(monitor='val_acc', min_delta=0, patience=15, verbose=1, mode='auto')
|
7b8bb9e6359b181865d39af68547dacbef8e6b36
|
[
"Python"
] | 9
|
Python
|
saichandrareddy1/CONVLSTM
|
5dde5996442ec5f911d4f237c53ec69807a922d8
|
32aef4ee5bf704b27a898f1370d52904a50160e2
|
refs/heads/master
|
<file_sep>import java.util.Scanner;
public class MyMain {
// Calculates the median of the three inputs
public static int median(int a, int b, int c) {
int qw = Math.max(a, b);
int we = Math.max(a, c);
int er = Math.max(b, c);
int rt = Math.min(qw, we);
int ty = Math.min(we, er);
int median1 = Math.min(rt, ty);
return median1;
}
// Returns the input with the larger absolute value
public static int magnitude(int a, int b) {
int a1 = Math.abs(a);
int b1 = Math.abs(b);
int magnitude1 = Math.max(a1, b1);
if (a < 0)
if (a1 > b1)
magnitude1 = magnitude1 *-1;
else if (b < 0)
if (b1 > a1)
magnitude1 = magnitude1 *-1;
else
magnitude1 = magnitude1;
return magnitude1;
}
// Returns the "c" value from the Pythagorean theorem "a^2 + b^2 = c^2",
// where "a" and "b" are the inputs to the method
public static double pythagoras(int a, int b) {
int bnm = 2;
double yu = Math.pow(a, bnm);
double ui = Math.pow(b, bnm);
double jkl = (yu + ui);
double pythagoras1 = Math.sqrt(jkl);
return pythagoras1;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("What math command would you like to carry out?");
String dsa = scan.next();
String runmedian = "median";
String runmagnitude = "magnitude";
String runpythagoras = "pythagoras";
boolean runmedian1 = (runmedian).equals(dsa);
if (runmedian1 == true)
System.out.println("What is integer a?");
int intame = scan.nextInt();
System.out.println("What is integer b?");
int intbme = scan.nextInt();
System.out.println("What is integer c?");
int intcme = scan.nextInt();
int runmedian2 = median(intame, intbme, intcme);
boolean runmagnitude1 = (runmagnitude).equals(dsa);
if (runmagnitude1 == true)
System.out.println("What is integer a?");
int intama = scan.nextInt();
System.out.println("What is integer b?");
int intbma = scan.nextInt();
int runmagnitude2 = magnitude(intama, intbma);
boolean runpythagoras1 = (runpythagoras).equals(dsa);
if (runpythagoras1 == true)
System.out.println("What is integer a?");
int intap = scan.nextInt();
System.out.println("What is integer b?");
int intbp = scan.nextInt();
double runpythagoras2 = pythagoras(intap, intbp);
}
}
|
2714bbd9378709d0e193e478ec3ccac94b1aa038
|
[
"Java"
] | 1
|
Java
|
apcs-assignments-fall2020/calculator-bot-Kiran-O
|
3726b5a6c58ee577b2dba9a17f4cdf77440d655c
|
1a39c76d50eba456a1ee20ea343fb4b7beb78c69
|
refs/heads/master
|
<repo_name>MarcJ786/springadvtestcontainers<file_sep>/src/test/resources/insertPersonen.sql
insert into personen(voornaam, familienaam) values ('Joe','Dalton');<file_sep>/src/main/resources/application.properties
spring.datasource.url=jdbc:mysql://localhost/eendatabase?serverTimezone=UTC
spring.datasource.username=cursist
spring.datasource.password=<PASSWORD>
spring.test.database.replace=none
spring.datasource.hikari.transaction-isolation=TRANSACTION_READ_COMMITTED
spring.jpa.generate-ddl=true
|
6f4831ec5040b19dcc6c9661721fea1dd4a1231c
|
[
"SQL",
"INI"
] | 2
|
SQL
|
MarcJ786/springadvtestcontainers
|
f2eea4f7b3c1e643cf25ba12f0961e01c4c47866
|
dde77c334e27a9440a79a23ddde596226f3fe55e
|
refs/heads/master
|
<repo_name>Harshitha3111999/edyst-s19-create-your-own-pokemon<file_sep>/backend/app.py
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
import os
app = Flask(__name__)
basedir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'pokemon.db')
db = SQLAlchemy(app)
class pokemon(db.Model):
id = db.Column("pokemon_id",db.Integer, unique=True, nullable=False, primary_key=True)
name = db.Column(db.String(50), unique=True, nullable=False, primary_key=False)
sprite = db.Column(db.String(500), unique=True, nullable=False, primary_key=False)
f = db.Column(db.String(20), unique=False, nullable=False, primary_key=False)
b = db.Column(db.String(20), unique=False, nullable=False, primary_key=False)
d = db.Column(db.String(20), unique=False, nullable=False, primary_key=False)
def __init__(self, id,name,sprite,f,b,d):
self.id=id
self.name=name
self.sprite=sprite
self.f=f
self.b=b
self.d=d
@app.route("/api/pokemon", methods=["POST"])
def create():
id=0
data=request.get_json()
if pokemon.query.filter(pokemon.name==data["pokemon"]["name"]).first():
return "<h1>the data given is already exists(search through name)</h1>"
pokemone=pokemon.query.all()
for length in pokemone:
id=id+1
pokemondata = pokemon(id+1,data['pokemon']['name'],data['pokemon']['sprite'],data['pokemon']['cardColours']['fg'], data['pokemon']['cardColours']['bg'], data['pokemon']['cardColours']['desc'])
db.session.add(pokemondata)
db.session.commit()
return get(id+1)
@app.route("/api/pokemon/<int:id>", methods=["DELETE"])
def delete(id):
if id<=0:
return "<h1>give correct details</h1>"
result = pokemon.query.filter_by(id=id).first()
if result == None:
return "<h1>There is no pokemon with specified ID so details cannot be deleted</h1>",404
data = get(id)
db.session.delete(result)
db.session.commit()
return data
@app.route("/api/pokemon/<int:id>",methods=["GET"])
def get(id) :
if id<=0:
return "<h1>give correct details</h1>"
result = pokemon.query.filter(pokemon.id == id).first()
if result == None:
return '<h1>No pokemon with the specified ID found</h1>'
else:
data={}
data['pokemon'] = {}
data['pokemon']['id']=result.id
data['pokemon']['name']=result.name
data['pokemon']['sprite']=result.sprite
data['pokemon']['cardColours']={}
data['pokemon']['cardColours']['fg']=result.f
data['pokemon']['cardColours']['bg']=result.b
data['pokemon']['cardColours']['desc']=result.d
return jsonify(data)
@app.route("/api/pokemon/<int:id>", methods=["PATCH"])
def update(id):
if id<=0:
return "<h1>give correct details</h1>"
data = request.get_json()
if data["pokemon"] == {}:
return "<h1>Atleast one field must be</h1>"
else:
result = pokemon.query.filter(pokemon.id == id).first()
if result == None:
return "<h1>There is no pokemon with specified ID </h1>"
for key in data['pokemon'].keys():
if key == 'name':
result.name = data['pokemon']['name']
if key == 'sprite' :
result.sprite = data['pokemon']['sprite']
if key == 'cardColours' :
result.fg = data['pokemon']['cardColours']['fg']
result.bg = data['pokemon']['cardColours']['bg']
result.desc = data['pokemon']['cardColours']['desc']
db.session.commit()
return get(id)
if __name__ == '__main__':
db.create_all()
app.run(host='localhost', port=8006, debug=True)<file_sep>/backend/requirements.txt
Click==7.0
Flask==1.0.2
Flask-SQLAlchemy==2.4.0
itsdangerous==1.1.0
Jinja2==2.10.1
MarkupSafe==1.1.1
SQLAlchemy==1.3.3
Werkzeug==0.15.2
<file_sep>/backend/tests/test.py
import unittest
import json
import sys
sys.path.append('../')
from app import db, app
class test(unittest.TestCase):
@classmethod
def setUpClass(self):
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///'
self.app = app.test_client()
db.create_all()
@classmethod
def tearDownClass(self):
db.drop_all()
def Create(self):
print("Creating New Pokemon")
send = {
"pokemon": {
"name": "test-pokemon",
"sprite": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/test.png",
"cardColours": {
"fg": "#111111",
"bg": "#222222",
"desc": "#333333"
}
}
}
recieve = {
"pokemon": {
"cardColours": {
"fg": "#111111",
"bg": "#222222",
"desc": "#333333"
}
"id":1,
"name": "test-pokemon",
"sprite": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/test.png",
}
}
self.app.post("http://localhost:8006/api/pokemon", data=json.dumps(send),
content_type='application/json')
original= self.app.get("http://localhost:8006/api/pokemon")
print(original)
self.assertEqual(recieve, json.loads(original.data))
print("Create Pokemon Test Successful")
def Get(self):
print("Reading Pokemon Details")
send = {
"pokemon": {
"name": "test-pokemon",
"sprite": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/test.png",
"cardColours": {
"fg": "#111111",
"bg": "#222222",
"desc": "#333333"
}
}
}
recieve = {
"pokemon": {
"cardColours": {
"fg": "#111111",
"bg": "#222222",
"desc": "#333333"
}
"id": 1,
"name": "test-pokemon",
"sprite": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/test.png",
}
}
self.app.post("http://localhost:8006/api/pokemon", data=json.dumps(send),
content_type='application/json')
original = self.app.get("http://localhost:8006/api/pokemon/1")
print(original)
self.assertEqual(recieve, json.loads(original.data))
print("View Pokemon Test Successful")
def Delete(self):
print("Deleting Pokemon Details")
create_send = {
"pokemon": {
"name": "test-pokemon",
"sprite": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/test.png",
"cardColours": {
"fg": "#111111",
"bg": "#222222",
"desc": "#333333"
}
}
}
delete_recieve = {
"pokemon": {
"cardColours": {
"fg": "#111111",
"bg": "#222222",
"desc": "#333333"
}
"id": 1,
"name": "test-pokemon",
"sprite": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/test.png",
}
}
self.app.post("http://localhost:8006/api/pokemon", data=json.dumps(create_send),content_type='application/json')
original = self.app.delete("http://localhost:8006/api/pokemon/1")
print(original)
self.assertEqual(delete_recieve, json.loads(original.data))
print("Delete Pokemon Test Successful")
def test_Update(self):
print("Updating Pokemon Details")
create_send = {
"pokemon": {
"name": "test-pokemon",
"sprite": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/test.png",
"cardColours": {
"fg": "#111111",
"bg": "#222222",
"desc": "#333333"
}
}
}
update_send ={
"pokemon": {
"name": "real-charmender"
}
}
update_recieve = {
"pokemon": {
"cardColours": {
"fg": "#111111",
"bg": "#222222",
"desc": "#333333"
}
"id": 1,
"name": "real-charmender",
"sprite": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/test.png",
}
}
self.app.post("http://localhost:8006/api/pokemon", data=json.dumps(create_send),content_type='application/json')
original = self.app.patch("http://localhost:8006/api/pokemon/1"')
print(original)
self.assertEqual(update_recieve, json.loads(original.data))
print("Pokemon Details Updated")
print("Updating Pokemon Test Successful")
if __name__ == '__main__':
unittest.main()
|
7279cc535cbe4cc5e3a22f6c3724777450072f08
|
[
"Python",
"Text"
] | 3
|
Python
|
Harshitha3111999/edyst-s19-create-your-own-pokemon
|
5bfb0888a0445a1747740bbc091a6c0fdcbf754d
|
e3c4b0243054adecc93f1bb7ef93b8ea890acdb9
|
refs/heads/master
|
<file_sep><?php
//--------------------------------------------------
// Setup
require_once('../html-filter.php');
header('Content-Type: text/plain; charset=UTF-8');
//--------------------------------------------------
// Get nodes
$mode = 'html5';
require_once(dirname(__FILE__) . '/' . $mode . '.php');
//--------------------------------------------------
// Check config
$filter = new html_filter(array(
'nodes' => $nodes,
));
$filter->config_check();
//--------------------------------------------------
// Printout children
$output = '';
function list_format($list, $indent = ' ') {
$list = implode(', ', $list);
$list = wordwrap($list, 75, "\n", false);
$list = preg_replace('/^/m', $indent, $list);
return $list;
}
foreach ($nodes as $node_name => $node_info) {
if (is_array($node_info)) {
sort($node_info['children']);
if (count($node_info['children']) > 0) {
$children = list_format($node_info['children']);
} else {
$children = ' N/A';
}
$output .= $node_name . ':' . "\n" . $children . "\n\n";
}
}
echo $output;
//--------------------------------------------------
// Save
file_put_contents(dirname(__FILE__) . '/' . $mode . '.txt', $output);
?><file_sep><?php
//--------------------------------------------------
// Setup
require_once('../html-filter.php');
header('Content-Type: text/plain; charset=UTF-8');
//--------------------------------------------------
// Test
function test_path($id, $ext = 'html') {
return './' . str_pad(intval($id), 3, '0', STR_PAD_LEFT) . '.' . $ext;
}
$test_id = intval(isset($_GET['id']) ? $_GET['id'] : 0);
$test_path = test_path($test_id);
if (!is_file($test_path)) {
$test_id = 1;
$test_path = test_path($test_id);
}
$test_html = file_get_contents($test_path);
//--------------------------------------------------
// Filter
$filter = new html_filter();
$filter->config_check();
$output_html = $filter->process($test_html);
//--------------------------------------------------
// Output
$output = rtrim($test_html) . "\n\n";
$output .= '--------------------------------------------------' . "\n\n";
$output .= rtrim($output_html) . "\n\n";
$output .= '--------------------------------------------------' . "\n\n";
foreach ($filter->errors_get() as $error) {
$output .= $error . "\n";
}
echo $output;
//--------------------------------------------------
// Save
file_put_contents(test_path($test_id, 'txt'), $output);
?><file_sep><?php
// https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content_categories
$categories = array(
'metadata' => array('base', 'command', 'link', 'meta', 'noscript', 'script', 'style', 'title'),
'phrasing' => array('a', 'abbr', 'audio', 'b', 'bdo', 'br', 'button', 'canvas', 'cite', 'code', 'command', 'datalist', 'del', 'dfn', 'em', 'embed', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'map', 'mark', 'math', 'meter', 'noscript', 'object', 'output', 'progress', 'q', 'ruby', 'samp', 'script', 'select', 'small', 'span', 'strong', 'sub', 'sup', 'svg', 'textarea', 'time', 'var', 'video', 'wbr', '#text'),
'flow' => array('a', 'abbr', 'address', 'article', 'aside', 'audio', 'b', 'bdo', 'bdi', 'blockquote', 'br', 'button', 'canvas', 'cite', 'code', 'command', 'data', 'datalist', 'del', 'details', 'dfn', 'div', 'dl', 'em', 'embed', 'fieldset', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'main', 'map', 'mark', 'math', 'menu', 'meter', 'nav', 'noscript', 'object', 'ol', 'output', 'p', 'pre', 'progress', 'q', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'span', 'strong', 'sub', 'sup', 'svg', 'table', 'template', 'textarea', 'time', 'ul', 'var', 'video', 'wbr', '#text'),
'section' => array('article', 'aside', 'nav', 'section'),
);
$nodes = array(
//--------------------------------------------------
// Main
'html' => array(
'alternative' => 'div',
'void' => false,
'children' => array('head', 'body'),
'exclusions' => array(),
'attributes' => array(
'lang' => array('type' => 'lang', 'default' => 'en'),
'manifest' => array('type' => 'url', 'default' => NULL, 'protocols' => array('#local', 'http', 'https')),
'xmlns' => array('type' => 'url', 'default' => NULL, 'protocols' => array('http', 'https')),
),
),
'head' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['metadata'],
'exclusions' => array(),
'attributes' => array(),
),
'body' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array(),
'attributes' => array(),
),
//--------------------------------------------------
// Meta
'base' => array(
'alternative' => 'span',
'void' => true,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'link' => array(
'alternative' => 'span',
'void' => true,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'style' => array(
'alternative' => 'span',
'void' => false,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'script' => array(
'alternative' => 'span',
'void' => false,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'noscript' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array('noscript'),
'attributes' => array(),
),
'title' => array(
'alternative' => 'span',
'void' => false,
'children' => array('#text'),
'exclusions' => array(),
'attributes' => array(),
),
'meta' => array(
'alternative' => 'span',
'void' => true,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
//--------------------------------------------------
// Structure
'article' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array(),
'attributes' => array(),
),
'aside' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array(),
'attributes' => array(),
),
'nav' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array(),
'attributes' => array(),
),
'section' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array(),
'attributes' => array(),
),
'footer' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array('header', 'footer'),
'attributes' => array(),
),
'dialog' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array(),
'attributes' => array(),
),
//--------------------------------------------------
// Content
'div' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array(),
'attributes' => array(),
),
'p' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'blockquote' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array(),
'attributes' => array(),
),
'address' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array('address', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hgroup', 'article', 'aside', 'nav', 'section', 'header', 'footer'),
'attributes' => array(),
),
//--------------------------------------------------
// Headings
'h1' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'h2' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'h3' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'h4' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'h5' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'h6' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'header' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array('header', 'footer'),
'attributes' => array(),
),
//--------------------------------------------------
// Lists
'ol' => array(
'alternative' => 'div',
'void' => false,
'children' => array('li'),
'exclusions' => array(),
'attributes' => array(),
),
'ul' => array(
'alternative' => 'div',
'void' => false,
'children' => array('li'),
'exclusions' => array(),
'attributes' => array(),
),
'li' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array(),
'attributes' => array(),
),
'dl' => array(
'alternative' => 'div',
'void' => false,
'children' => array('dt', 'dd'),
'exclusions' => array(),
'attributes' => array(),
),
'dt' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array('header', 'footer', 'article', 'aside', 'nav', 'section', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hgroup'),
'attributes' => array(),
),
'dd' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array(),
'attributes' => array(),
),
//--------------------------------------------------
// Table
'table' => array(
'alternative' => 'div',
'void' => false,
'children' => array('caption', 'colgroup', 'thead', 'tbody', 'tfoot', 'tr'),
'exclusions' => array(),
'attributes' => array(),
),
'caption' => array(
'alternative' => 'div',
'void' => false,
'children' =>$categories['flow'],
'exclusions' => array(),
'attributes' => array(),
),
'colgroup' => array(
'alternative' => 'div',
'void' => false,
'children' => array('col'),
'exclusions' => array(),
'attributes' => array(),
),
'col' => array(
'alternative' => 'div',
'void' => true,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'thead' => array(
'alternative' => 'div',
'void' => false,
'children' => array('tr'),
'exclusions' => array(),
'attributes' => array(),
),
'tbody' => array(
'alternative' => 'div',
'void' => false,
'children' => array('tr'),
'exclusions' => array(),
'attributes' => array(),
),
'tfoot' => array(
'alternative' => 'div',
'void' => false,
'children' => array('tr'),
'exclusions' => array(),
'attributes' => array(),
),
'tr' => array(
'alternative' => 'div',
'void' => false,
'children' => array('th', 'td'),
'exclusions' => array(),
'attributes' => array(),
),
'th' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'td' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array(),
'attributes' => array(),
),
//--------------------------------------------------
// Form
'form' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array('form'),
'attributes' => array(),
),
'fieldset' => array(
'alternative' => 'div',
'void' => false,
'children' => array_merge($categories['flow'], array('legend')),
'exclusions' => array(),
'attributes' => array(),
),
'legend' => array(
'alternative' => 'div',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'label' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array('label'),
'attributes' => array(),
),
'input' => array(
'alternative' => 'span',
'void' => true,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'keygen' => array(
'alternative' => 'span',
'void' => true,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'details' => array(
'alternative' => 'span',
'void' => false,
'children' => array_merge($categories['flow'], array('summary')),
'exclusions' => array(),
'attributes' => array(),
),
'command' => array(
'alternative' => 'span',
'void' => true,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'summary' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'meter' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array('meter'),
'attributes' => array(),
),
'progress' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array('progress'),
'attributes' => array(),
),
'select' => array(
'alternative' => 'span',
'void' => false,
'children' => array('option', 'optgroup'),
'exclusions' => array(),
'attributes' => array(),
),
'optgroup' => array(
'alternative' => 'span',
'void' => false,
'children' => array('option'),
'exclusions' => array(),
'attributes' => array(),
),
'option' => array(
'alternative' => 'span',
'void' => false,
'children' => array('#text'),
'exclusions' => array(),
'attributes' => array(),
),
'datalist' => array(
'alternative' => 'span',
'void' => false,
'children' => array_merge($categories['phrasing'], array('option')),
'exclusions' => array(),
'attributes' => array(),
),
'textarea' => array(
'alternative' => 'span',
'void' => false,
'children' => array('#text'),
'exclusions' => array(),
'attributes' => array(),
),
'button' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'output' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
//--------------------------------------------------
// Elements
'img' => array(
'alternative' => 'span',
'void' => true,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'map' => array(
'alternative' => 'span',
'void' => false,
'children' => array('area'),
'exclusions' => array(),
'attributes' => array(),
),
'area' => array(
'alternative' => 'span',
'void' => true,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'audio' => array(
'alternative' => 'span',
'void' => false,
'children' => array('source', 'track'),
'exclusions' => array('audio', 'video'),
'attributes' => array(),
),
'canvas' => array(
'alternative' => 'span',
'void' => false,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'svg' => array(
'alternative' => 'span',
'void' => false,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'figure' => array(
'alternative' => 'span',
'void' => false,
'children' => array_merge($categories['flow'], array('figcaption')),
'exclusions' => array(),
'attributes' => array(),
),
'figcaption' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['flow'],
'exclusions' => array(),
'attributes' => array(),
),
'video' => array(
'alternative' => 'span',
'void' => false,
'children' => array('source', 'track'),
'exclusions' => array('audio', 'video'),
'attributes' => array(),
),
'object' => array(
'alternative' => 'span',
'void' => false,
'children' => array('param'),
'exclusions' => array(),
'attributes' => array(),
),
'embed' => array(
'alternative' => 'span',
'void' => true,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'param' => array(
'alternative' => 'span',
'void' => true,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'source' => array(
'alternative' => 'span',
'void' => true,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'track' => array(
'alternative' => 'span',
'void' => true,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'iframe' => array(
'alternative' => 'span',
'void' => false,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'menu' => array(
'alternative' => 'span',
'void' => false,
'children' => array_merge($categories['flow'], array('li', 'menu', 'menuitem', 'hr')),
'exclusions' => array(),
'attributes' => array(),
),
'menuitem' => array(
'alternative' => 'span',
'void' => false,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
//--------------------------------------------------
// Breaks
'hr' => array(
'alternative' => 'span',
'void' => true,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'br' => array(
'alternative' => 'span',
'void' => true,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
'wbr' => array(
'alternative' => 'span',
'void' => true,
'children' => array(),
'exclusions' => array(),
'attributes' => array(),
),
//--------------------------------------------------
// Phrase
'a' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'], // Putting a div inside a link is just wrong (even if valid).
'exclusions' => array(),
'attributes' => array(
'href' => array('type' => 'url', 'default' => '#', 'protocols' => array('#local', 'http', 'https')),
),
),
'span' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'abbr' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'cite' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'code' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'dfn' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array('dfn'),
'attributes' => array(),
),
'em' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'kbd' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'mark' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'q' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
's' => array(
'alternative' => 'span',
'void' => false,
'children' => array('#text'),
'exclusions' => array(),
'attributes' => array(),
),
'small' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'samp' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'strong' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'sub' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'sup' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'time' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array('time'),
'attributes' => array(),
),
'var' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'pre' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'ins' => array(
'alternative' => 'span',
'void' => false,
'children' => array('#text'),
'exclusions' => array(),
'attributes' => array(),
),
'del' => array(
'alternative' => 'span',
'void' => false,
'children' => array('#text'),
'exclusions' => array(),
'attributes' => array(),
),
'u' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'b' => 'strong',
'i' => 'em',
//--------------------------------------------------
// Formatting
'bdi' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'bdo' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(
'dir' => array('type' => 'list', 'default' => 'auto', 'values' => array('ltr', 'rtl', 'auto')),
),
),
'ruby' => array(
'alternative' => 'span',
'void' => false,
'children' => array('rp', 'rt'),
'exclusions' => array(),
'attributes' => array(),
),
'rp' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
'rt' => array(
'alternative' => 'span',
'void' => false,
'children' => $categories['phrasing'],
'exclusions' => array(),
'attributes' => array(),
),
);
?><file_sep><?php
class html_filter {
protected $config = array();
protected $errors = array();
protected $dom_src = NULL;
protected $dom_dst = NULL;
public function __construct($config = array()) {
$this->setup($config);
}
protected function setup($config) {
//--------------------------------------------------
// Default config
$this->config = array_merge(array(
'nodes' => dirname(__FILE__) . '/nodes/html5.php',
'unrecognised_node' => 'div',
'unrecognised_attribute' => NULL,
), $this->config, $config);
//--------------------------------------------------
// Config: nodes
if (is_string($this->config['nodes'])) {
$this->config['nodes'] = $this->node_config_get($this->config['nodes']);
}
//--------------------------------------------------
// Config: Fallback node
$node_name = $this->config['unrecognised_node'];
if (!isset($this->config['nodes'][$node_name])) {
exit('Unrecognised fallback node "' . $node_name . '"');
}
}
private function node_config_get($path) {
$nodes = array();
require($path);
return $nodes;
}
public function config_check() {
foreach ($this->config['nodes'] as $node_name => $node_config) {
if (is_string($node_config)) {
continue;
}
if (!array_key_exists('void', $node_config)) exit('The node "' . $node_name . '" is missing the "void" boolean');
if (!is_bool($node_config['void'])) exit('The node "' . $node_name . '" has an invalid "void" boolean');
if (!array_key_exists('children', $node_config)) exit('The node "' . $node_name . '" is missing the "children" array');
if (!is_array($node_config['children'])) exit('The node "' . $node_name . '" has an invalid "children" array');
if (!array_key_exists('exclusions', $node_config)) exit('The node "' . $node_name . '" is missing the "exclude" array');
if (!is_array($node_config['exclusions'])) exit('The node "' . $node_name . '" has an invalid "exclude" array');
if (!array_key_exists('attributes', $node_config)) exit('The node "' . $node_name . '" is missing the "attributes" array');
if (!is_array($node_config['attributes'])) exit('The node "' . $node_name . '" has an invalid "attributes" array');
foreach ($node_config['attributes'] as $attr_name => $attr_config) {
if (!array_key_exists('type', $attr_config)) exit('The node "' . $node_name . '" attribute "' . $attr_name . '" type is required.');
if (!array_key_exists('default', $attr_config)) exit('The node "' . $node_name . '" attribute "' . $attr_name . '" default is required.');
}
}
}
public function errors_get() {
return $this->errors;
}
public function process($html) {
//--------------------------------------------------
// Documents
$this->dom_src = new DOMDocument();
$this->dom_dst = new DOMDocument();
libxml_use_internal_errors(true);
libxml_clear_errors();
$this->dom_src->loadHTML($html, LIBXML_NONET); // Disable net access, but also miraculously whitespace is preserved more often.
foreach (libxml_get_errors() as $error) {
$this->errors[] = 'LibXML Error: ' . trim($error->message) . ' (line ' . $error->line . ')';
}
libxml_clear_errors();
//--------------------------------------------------
// Copy nodes
foreach ($this->dom_src->childNodes as $node) {
if ($node->nodeType === XML_DOCUMENT_TYPE_NODE) { // DOM contains multiple <html> nodes???
continue;
}
$new = $this->process_node(strtolower($node->nodeName), $node);
if ($new) {
$this->dom_dst->appendChild($new);
}
}
//--------------------------------------------------
// Compile HTML
$output = '';
$bodies = $this->dom_dst->getElementsByTagName('body');
if ($bodies->length == 1) {
foreach ($bodies->item(0)->childNodes as $child) {
$output .= $this->dom_dst->saveXML($child, LIBXML_NOEMPTYTAG);
}
}
foreach ($this->config['nodes'] as $node_name => $node_config) {
if (is_array($node_config) && $node_config['void']) {
$output = str_ireplace('></' . $node_name . '>', ' />', $output);
}
}
//--------------------------------------------------
// Return
return $output;
}
protected function process_node($node_name, $node_src, $node_exclusions = array()) {
//--------------------------------------------------
// Node type
if ($node_src->nodeType === XML_TEXT_NODE) {
return $this->dom_dst->createTextNode($node_src->nodeValue);
} else if (!isset($this->config['nodes'][$node_name])) {
$this->errors[] = 'Unrecognised node "' . $node_name . '" (' . $node_src->nodeType . ')';
if ($this->config['unrecognised_node']) {
$node_name = $this->config['unrecognised_node'];
} else {
return NULL;
}
}
$node_config = $this->config['nodes'][$node_name];
if (is_string($node_config)) {
$node_name = $node_config;
$node_config = $this->config['nodes'][$node_name];
}
//--------------------------------------------------
// Exclusions (e.g. a label cannot contain a label)
$node_exclusions = array_merge($node_exclusions, $node_config['exclusions']);
//--------------------------------------------------
// New
$node_dst = $this->dom_dst->createElement($node_name);
//--------------------------------------------------
// Attributes
$attributes = array();
if ($node_src->hasAttributes()) {
foreach ($node_src->attributes as $attribute) {
//--------------------------------------------------
// Config
$attr_name = $attribute->name;
if (isset($node_config['attributes'][$attr_name])) {
$attr_config = $node_config['attributes'][$attr_name];
} else if ($attr_name == 'class') {
$attr_config = array('type' => 'class');
} else {
$this->errors[] = 'Unrecognised attribute "' . $attr_name . '" on node "' . $node_name . '"';
if ($this->config['unrecognised_attribute']) {
$attr_config = array('type' => $this->config['unrecognised_attribute']);
} else {
$attr_config = array('type' => NULL);
}
}
//--------------------------------------------------
// Value
$attr_value = $attribute->value;
if ($attr_config['type'] == 'url') {
$attr_value = $this->filter_url($attr_value, $attr_config);
} else if ($attr_config['type'] == 'class') {
$attr_value = $this->filter_class($attr_value, $attr_config);
} else if ($attr_config['type'] === NULL) {
$attr_value = NULL;
} else {
$this->errors[] = 'Unrecognised attribute type "' . $attr_config['type'] . '" for "' . $attr_name . '" on node "' . $node_name . '"';
}
//--------------------------------------------------
// Apply
if ($attr_value !== NULL) {
$node_dst->setAttribute($attr_name, $attr_value);
$attributes[] = $attr_name;
}
}
}
foreach ($node_config['attributes'] as $attr_name => $attr_config) {
if ($attr_config['default'] !== NULL && !in_array($attr_name, $attributes)) {
$node_dst->setAttribute($attr_name, $attr_config['default']);
}
}
//--------------------------------------------------
// Children
if ($node_src->hasChildNodes()) {
foreach ($node_src->childNodes as $child) {
if ($child->nodeType === XML_CDATA_SECTION_NODE) {
continue; // Probably some CSS from a <style> tag... with nasty JS as well, e.g. background: url("javascript:alert('XSS')");
}
if ($child->nodeType === XML_COMMENT_NODE) {
continue;
}
$child_name_lower = strtolower($child->nodeName);
$child_name_safe = NULL;
if (!in_array($child_name_lower, $node_config['children'])) {
$this->errors[] = 'Cannot allow "' . $child_name_lower . '" as a child of "' . $node_name . '".';
} else if (in_array($child_name_lower, $node_exclusions)) { // The ['exclusions'] allows nodes like <form> and <label> to not include any children of the same name, with no need to alter their ['children'] from a simple $categories['flow'].
$this->errors[] = 'Cannot allow "' . $child_name_lower . '", as it has been excluded from a parent node.';
} else {
$child_name_safe = $child_name_lower;
}
if ($child_name_safe === NULL) {
if (isset($this->config['nodes'][$child_name_lower])) {
$child_name_alternative = $this->config['nodes'][$child_name_lower]['alternative']; // Allow the node to specify an appropriate alternative (e.g. span or div)
if (!in_array($child_name_alternative, $node_config['children']) || in_array($child_name_alternative, $node_exclusions)) {
$this->errors[] = 'Cannot allow "' . $child_name_alternative . '" as an alternative child for "' . $child_name_lower . '".';
} else {
$child_name_safe = $child_name_alternative;
}
}
}
if ($child_name_safe === NULL) { // Last ditch attempt to find something, but some nodes don't allow any children (e.g. <br />)
if (in_array('div', $node_config['children'])) {
$child_name_safe = 'div';
} else if (in_array('span', $node_config['children'])) {
$child_name_safe = 'span';
}
}
if ($child_name_safe !== NULL) {
$new = $this->process_node($child_name_safe, $child, $node_exclusions);
if ($new) {
$node_dst->appendChild($new);
}
}
}
}
//--------------------------------------------------
// Return
return $node_dst;
}
protected function filter_url($url, $attr_config) {
if (isset($attr_config['protocols']) && is_array($attr_config['protocols'])) {
$protocols = $attr_config['protocols'];
} else {
$protocols = array();
}
if (($pos = strpos($url, ':')) !== false) {
$protocol = substr($url, 0, $pos);
if ($protocol != '#local' && in_array($protocol, $protocols)) {
return $url;
}
} else if (substr($url, 0, 2) == '//') {
return NULL; // Must specify protocol
} else if (in_array('#local', $protocols)) {
return $url; // TODO: Can we still check for absolute ("/path/") or relative ("./path", "../path" or "path/") links?
}
return NULL;
}
protected function filter_class($input) {
$output = array();
foreach (explode(' ', $input) as $class) {
$class = trim($class);
if (preg_match('/^-?[_a-zA-Z][_a-zA-Z0-9\-]*$/', $class)) {
$output[] = $class;
}
}
return implode(' ', $output);
}
}
?><file_sep>
# HTML Filter
A very basic PHP based HTML filter, using [DOMDocument::loadHTML](http://php.net/manual/en/domdocument.loadhtml.php) to parse the HTML.
It creates a new DOMDocument by simply copying across the valid nodes and attributes.
There are no dependencies, and was built to filter the output from a WYSIWYG editor.
By default it blocks all style attributes (should be in the style sheet, ref CSP headers), and attributes related to JavaScript (e.g. onclick).
---
## Alternatives
A pretty similar list to the ones found on the HTML Purifier [comparison page](http://htmlpurifier.org/comparison):
[HTML Purifier](http://htmlpurifier.org/) - Does everything, probably the best choice.
[HTML Tidy](http://tidy.sourceforge.net/) - Not a filter, very good at cleaning up markup though.
[HTML Safe](http://pear.php.net/package/HTML_Safe) - Uses black lists, and the [XML_HTMLSax3](http://pear.php.net/package/XML_HTMLSax3/) parser.
[htmLawed](http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/) - Uses regexp in hl_tag() to parse HTML.
[Kses](http://sourceforge.net/projects/kses/) - Uses regexp in kses_split() to parse HTML.
[OWASP HTML Sanitizer](https://www.owasp.org/index.php/OWASP_Java_HTML_Sanitizer_Project) - Java based
|
e7b0344283aa1fe8f55164a960a87ee1e5688225
|
[
"Markdown",
"PHP"
] | 5
|
PHP
|
craigfrancis/html-filter
|
666a485321ebdc1f1a471256473a11c698fa7044
|
85e249917fb841667893f208b6a80f222576711b
|
refs/heads/master
|
<file_sep>package entity.demo.proyecto;
import jakarta.persistence.metamodel.ListAttribute;
import jakarta.persistence.metamodel.SetAttribute;
import jakarta.persistence.metamodel.SingularAttribute;
import jakarta.persistence.metamodel.StaticMetamodel;
import javax.annotation.processing.Generated;
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Titulo.class)
public abstract class Titulo_ extends entity.demo.proyecto.Entidad_ {
public static volatile SingularAttribute<Titulo, String> codigo;
public static volatile SingularAttribute<Titulo, String> anyoInicio;
public static volatile SingularAttribute<Titulo, String> anyoFin;
public static volatile SetAttribute<Titulo, Episodio> episodioTituloSet;
public static volatile SingularAttribute<Titulo, Rating> rating;
public static volatile SingularAttribute<Titulo, TipoTitulo> tipoTitulo;
public static volatile SingularAttribute<Titulo, String> nombre;
public static volatile SetAttribute<Titulo, Genero> generoSet;
public static volatile SingularAttribute<Titulo, Boolean> paraAdultos;
public static volatile SingularAttribute<Titulo, Integer> tiempo;
public static volatile SetAttribute<Titulo, TituloSinonimo> tituloSinonimoSet;
public static volatile SetAttribute<Titulo, Episodio> episodioPadreTituloSet;
public static volatile SingularAttribute<Titulo, String> nombreOriginal;
public static volatile SingularAttribute<Titulo, Long> tituloId;
public static volatile ListAttribute<Titulo, PersonaTitulo> personaTituloList;
public static final String CODIGO = "codigo";
public static final String ANYO_INICIO = "anyoInicio";
public static final String ANYO_FIN = "anyoFin";
public static final String EPISODIO_TITULO_SET = "episodioTituloSet";
public static final String RATING = "rating";
public static final String TIPO_TITULO = "tipoTitulo";
public static final String NOMBRE = "nombre";
public static final String GENERO_SET = "generoSet";
public static final String PARA_ADULTOS = "paraAdultos";
public static final String TIEMPO = "tiempo";
public static final String TITULO_SINONIMO_SET = "tituloSinonimoSet";
public static final String EPISODIO_PADRE_TITULO_SET = "episodioPadreTituloSet";
public static final String NOMBRE_ORIGINAL = "nombreOriginal";
public static final String TITULO_ID = "tituloId";
public static final String PERSONA_TITULO_LIST = "personaTituloList";
}
<file_sep>package controllerCSV.demo.proyecto;
import dto.demo.proyecto.TitleCrewDTO;
import entity.demo.proyecto.Titulo;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Persistence;
import repositorio.demo.proyecto.PersonaRepositorio;
import repositorio.demo.proyecto.PersonaTituloRepositorio;
import repositorio.demo.proyecto.TituloRepositorio;
import java.io.File;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PersistirTituloPersona {
EntityManager entityManager = Persistence.createEntityManagerFactory("myPersistence")
.createEntityManager();
Controlador.DTOParser dtoParser = new Controlador.DTOParser();
public void ingresarDDBB(){
try{
entityManager.getTransaction().begin();
File titleCrewOutput = new File("C:\\Users\\Sergio_Mendez_G\\Documents\\newFiles\\title.crew.tsv1");
List<TitleCrewDTO> titleCrewDTOList = dtoParser.parse(TitleCrewDTO.class, titleCrewOutput);
PersonaRepositorio personaRepositorio = new PersonaRepositorio(entityManager);
TituloRepositorio tituloRepositorio = new TituloRepositorio(entityManager);
PersonaTituloRepositorio personaTituloRepositorio = new PersonaTituloRepositorio(entityManager, personaRepositorio);
titleCrewDTOList.stream().forEach(dto -> {
Titulo titulo = tituloRepositorio.buscarTItuloPorCodigo(dto.getTconst());
if (titulo != null) {
personaTituloRepositorio.actualizarDirectores(titulo, dto.directorsToArray());
personaTituloRepositorio.actualizarEscritores(titulo, dto.writersToArray());
}
});
entityManager.getTransaction().commit();
}catch (Exception ex) {
Logger.getLogger("Main").log(Level.SEVERE, "Error", ex);
entityManager.getTransaction().rollback();
} finally {
entityManager.close();
}
}
}
<file_sep>package controllerCSV.demo.proyecto;
import ConvertorDTO.demo.proyecto.RatingDTOConverter;
import dto.demo.proyecto.TitleRatingDTO;
import entity.demo.proyecto.Rating;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Persistence;
import repositorio.demo.proyecto.RatingRepositorio;
import repositorio.demo.proyecto.TituloRepositorio;
import java.io.File;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PersistirTituloRating {
EntityManager entityManager = Persistence.createEntityManagerFactory("myPersistence")
.createEntityManager();
Controlador.DTOParser dtoParser = new Controlador.DTOParser();
public void ingresarTituloDDBB(){
File titleRatingOutput = new File("C:\\Users\\Sergio_Mendez_G\\Documents\\newFiles\\title.ratings.tsv1");
try{
entityManager.getTransaction().begin();
TituloRepositorio tituloRepositorio = new TituloRepositorio(entityManager);
RatingDTOConverter ratingDTOConverter = new RatingDTOConverter();
RatingRepositorio ratingRepositorio = new RatingRepositorio(entityManager);
List<TitleRatingDTO> ratingDTOList = dtoParser.parse(TitleRatingDTO.class, titleRatingOutput);
ratingDTOList.stream()
.forEach(ratingNuevo->{
Rating rating = ratingDTOConverter.convertir(ratingNuevo);
rating.setRatingTitulo(tituloRepositorio.buscarTItuloPorCodigo(ratingNuevo.getTconst()));
ratingRepositorio.crearOActualizarRating(rating);
});
entityManager.getTransaction().commit();
}catch (Exception ex) {
Logger.getLogger("Main").log(Level.SEVERE, "Error", ex);
entityManager.getTransaction().rollback();
} finally {
entityManager.close();
}
}
}
<file_sep>package ConvertorDTO.demo.proyecto;
import dto.demo.proyecto.TitleBasicsDTO;
import entity.demo.proyecto.Genero;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class GeneroDTOConverter implements Converter<List<Genero>, TitleBasicsDTO> {
@Override
public List<Genero> convertir(TitleBasicsDTO dto) {
List<Genero> generoList = Stream.of(dto.getGenres().split(","))
.map(nombresGeneros ->{
Genero genero = new Genero();
genero.setNombre(nombresGeneros);
return genero;
}).collect(Collectors.toList());
return generoList;
}
}
<file_sep>package ConvertorDTO.demo.proyecto;
import dto.demo.proyecto.TitleBasicsDTO;
import entity.demo.proyecto.Titulo;
import java.util.Optional;
public class TituloDTOConverter implements Converter<Titulo, TitleBasicsDTO> {
@Override
public Titulo convertir(TitleBasicsDTO dto) {
Titulo titulo = new Titulo();
titulo.setCodigo(dto.getTconst());
titulo.setNombre(dto.getPrimaryTitle());
titulo.setNombreOriginal(dto.getOriginalTitle());
titulo.setAnyoInicio(dto.getStartYear());
titulo.setAnyoFin(dto.getEndYear());
Optional.ofNullable(dto.getIsAdult())
.map(Integer::valueOf)
.map(paraAdultos -> paraAdultos == 1)
.ifPresentOrElse(titulo::setParaAdultos, () -> titulo.setParaAdultos(false));
Optional.ofNullable(this.convertirValor(dto.getRuntimeMinutes()))
.map(Integer::valueOf)
.ifPresent(titulo::setTiempo);
return titulo;
}
}
<file_sep>package entity.demo.proyecto;
import jakarta.persistence.metamodel.SetAttribute;
import jakarta.persistence.metamodel.SingularAttribute;
import jakarta.persistence.metamodel.StaticMetamodel;
import javax.annotation.processing.Generated;
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Genero.class)
public abstract class Genero_ extends entity.demo.proyecto.Entidad_ {
public static volatile SingularAttribute<Genero, String> descripcion;
public static volatile SetAttribute<Genero, Titulo> tituloset;
public static volatile SingularAttribute<Genero, Long> generoId;
public static volatile SingularAttribute<Genero, String> nombre;
public static final String DESCRIPCION = "descripcion";
public static final String TITULOSET = "tituloset";
public static final String GENERO_ID = "generoId";
public static final String NOMBRE = "nombre";
}
<file_sep>package entity.demo.proyecto;
import jakarta.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import lombok.extern.java.Log;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
@Entity
@Table(name="rating")
@Data
@DynamicInsert
@DynamicUpdate
@SelectBeforeUpdate
@EqualsAndHashCode(of ="iD", callSuper = false)
@ToString(of = "iD")
public class Rating extends Entidad {
@Id
@GeneratedValue (strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long iD;
@Column(name = "codigo")
private String codigo;
@Column(name = "promedio")
private Double promedio;
@Column(name = "numero_votos")
private Integer numeroVotos;
@OneToOne
@JoinColumn(name = "titulo_id")
private Titulo ratingTitulo;
}
<file_sep>package ConvertorDTO.demo.proyecto;
public interface Converter <T, D> {
T convertir(D d);
default String convertirValor(String valor) {
if (valor == null || valor.equalsIgnoreCase("N")) {
return null;
}
return valor;
}
}
<file_sep>package entity.demo.proyecto;
import jakarta.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
@Entity
@Table(name = "episodio")
@Data
@EqualsAndHashCode(of = "episodioId", callSuper = false)
@ToString(of = "episodioId")
@DynamicInsert
@DynamicUpdate
@SelectBeforeUpdate
public class Episodio extends Entidad {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(name = "episodio_id")
private Long episodioId;
@Column(name = "codigo_titulo")
private String codigoTitulo;
@Column(name = "codigo_padre_titulo_id")
private String CodigoPadreTituloId;
@Column(name = "numero_episodio")
private int numeroEpisodio;
@Column(name="numero_temporada")
private int numeroTemporada;
@ManyToOne
@JoinColumn(name = "titulo_id")
private Titulo episodioTitulo;
@ManyToOne
@JoinColumn(name = "titulo_id", insertable = false, updatable = false)
private Titulo episodioPadreTitulo;
}
<file_sep>package entity.demo.proyecto;
import jakarta.persistence.metamodel.SingularAttribute;
import jakarta.persistence.metamodel.StaticMetamodel;
import javax.annotation.processing.Generated;
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(PersonaTitulo.class)
public abstract class PersonaTitulo_ {
public static volatile SingularAttribute<PersonaTitulo, Integer> tipoRelacion;
public static volatile SingularAttribute<PersonaTitulo, Persona> persona;
public static volatile SingularAttribute<PersonaTitulo, Long> tituloId;
public static volatile SingularAttribute<PersonaTitulo, Titulo> titulo;
public static volatile SingularAttribute<PersonaTitulo, Long> personaId;
public static final String TIPO_RELACION = "tipoRelacion";
public static final String PERSONA = "persona";
public static final String TITULO_ID = "tituloId";
public static final String TITULO = "titulo";
public static final String PERSONA_ID = "personaId";
}
<file_sep>package entity.demo.proyecto;
import jakarta.persistence.metamodel.SingularAttribute;
import jakarta.persistence.metamodel.StaticMetamodel;
import javax.annotation.processing.Generated;
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(TituloSinonimo.class)
public abstract class TituloSinonimo_ extends entity.demo.proyecto.Entidad_ {
public static volatile SingularAttribute<TituloSinonimo, Long> tituloSinonimoId;
public static volatile SingularAttribute<TituloSinonimo, String> tipo;
public static volatile SingularAttribute<TituloSinonimo, Boolean> original;
public static volatile SingularAttribute<TituloSinonimo, String> leguaje;
public static volatile SingularAttribute<TituloSinonimo, String> region;
public static volatile SingularAttribute<TituloSinonimo, String> nombre;
public static volatile SingularAttribute<TituloSinonimo, Integer> linea;
public static volatile SingularAttribute<TituloSinonimo, String> atributos;
public static volatile SingularAttribute<TituloSinonimo, Titulo> tituloSinonimos;
public static final String TITULO_SINONIMO_ID = "tituloSinonimoId";
public static final String TIPO = "tipo";
public static final String ORIGINAL = "original";
public static final String LEGUAJE = "leguaje";
public static final String REGION = "region";
public static final String NOMBRE = "nombre";
public static final String LINEA = "linea";
public static final String ATRIBUTOS = "atributos";
public static final String TITULO_SINONIMOS = "tituloSinonimos";
}
<file_sep>package entity.demo.proyecto;
import jakarta.persistence.*;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;
import java.util.List;
import java.util.Set;
@Entity
@Table(name = "titulo")
@Data
@EqualsAndHashCode(of = "tituloId", callSuper = false)
@ToString(of = "tituloId")
@SelectBeforeUpdate
@DynamicUpdate
@DynamicInsert
public class Titulo extends Entidad{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "titulo_id")
private Long tituloId;
@Column(name = "codigo")
private String codigo;
@Column(name = "nombre")
private String nombre;
@Column(name = "nombre_original")
private String nombreOriginal;
@Column(name = "para_adultos")
private boolean paraAdultos;
@Column(name = "anyo_nacimiento")
private String anyoInicio;
@Column(name = "anyo_fin")
private String anyoFin;
@Column(name = "tiempo")
private Integer tiempo;
@OneToMany(mappedBy = "titulo")
private List<PersonaTitulo> personaTituloList;
@OneToOne(mappedBy = "ratingTitulo")
private Rating rating;
@OneToMany(mappedBy = "tituloSinonimos")
private Set<TituloSinonimo> tituloSinonimoSet;
@OneToMany(mappedBy = "episodioTitulo")
private Set<Episodio> episodioTituloSet;
@OneToMany(mappedBy = "episodioPadreTitulo")
private Set<Episodio> episodioPadreTituloSet;
@ManyToMany
@JoinTable(
name = "titulo_genero",
joinColumns = @JoinColumn(name = "titulo_id", referencedColumnName = "titulo_id"),
inverseJoinColumns = @JoinColumn(name = "genero_id", referencedColumnName = "genero_id")
)
private Set<Genero> generoSet;
@ManyToOne
@JoinColumn(name = "tipo_titulo_id")
private TipoTitulo tipoTitulo;
}
<file_sep>package repositorio.demo.proyecto;
import entity.demo.proyecto.Persona;
import entity.demo.proyecto.Persona_;
import jakarta.persistence.EntityManager;
import jakarta.persistence.NoResultException;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
public class PersonaRepositorio {
private final EntityManager entityManager;
public PersonaRepositorio(EntityManager entityManager) {
this.entityManager = entityManager;
}
public Persona buscarPersonaPorCodigo(String codigo) {
var builder = this.entityManager.getCriteriaBuilder();
CriteriaQuery<Persona> personaQuery = builder.createQuery(Persona.class);
Root<Persona> root = personaQuery.from(Persona.class);
personaQuery.where(
builder.equal(root.get(Persona_.codigo), codigo)
);
try {
return this.entityManager.createQuery(personaQuery).getSingleResult();
} catch (NoResultException ex) {
}
return null;
}
public void crearOActualizarPersona(Persona personaNuevo){
Persona persona = this.buscarPersonaPorCodigo(personaNuevo.getCodigo());
if (persona==null){
this.entityManager.persist(personaNuevo);
}else {
persona.setNombre(personaNuevo.getNombre());
persona.setAnyoNacimiento(personaNuevo.getAnyoNacimiento());
persona.setAnyoFallecimiento(personaNuevo.getAnyoFallecimiento());
persona.setProfesionSet(persona.getProfesionSet());
this.entityManager.merge(persona);
}
}
}<file_sep>package repositorio.demo.proyecto;
import entity.demo.proyecto.Episodio;
import entity.demo.proyecto.Episodio_;
import jakarta.persistence.EntityManager;
import jakarta.persistence.NoResultException;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
public class EpisodioRepositorio {
private final EntityManager entityManager;
public EpisodioRepositorio(EntityManager entityManager) {
this.entityManager = entityManager;
}
public Episodio buscarEpisodioPorId(Long episodioId) {
var builder = this.entityManager.getCriteriaBuilder();
CriteriaQuery<Episodio> episodioQuery = builder.createQuery(Episodio.class);
Root<Episodio> root = episodioQuery.from(Episodio.class);
episodioQuery.where(
builder.equal(root.get(Episodio_.episodioId), episodioId)
);
try {
return this.entityManager.createQuery(episodioQuery).getSingleResult();
} catch (NoResultException ex) {
}
return null;
}
public void crearOActualizarEpisodio(Episodio episodioNuevo){
Episodio episodio = this.buscarEpisodioPorId(episodioNuevo.getEpisodioId());
if (episodio == null){
this.entityManager.persist(episodioNuevo);
}else{
episodio.setNumeroEpisodio(episodioNuevo.getNumeroEpisodio());
episodio.setNumeroTemporada(episodioNuevo.getNumeroTemporada());
this.entityManager.merge(episodio);
}
}
}
<file_sep>package ConvertorDTO.demo.proyecto;
import dto.demo.proyecto.NameBasicsDTO;
import entity.demo.proyecto.Profesion;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ProfesionConverterDTO implements Converter<List<Profesion>, NameBasicsDTO> {
@Override
public List<Profesion> convertir(NameBasicsDTO dto){
List<Profesion> profesionList = Stream.of(dto.getPrimaryProfession().split(","))
.map(nombresProfesiones ->{
Profesion profesion = new Profesion();
profesion.setNombre(nombresProfesiones);
return profesion;
}).collect(Collectors.toList());
return profesionList;
}
}
<file_sep>package controllerCSV.demo.proyecto;
import ConvertorDTO.demo.proyecto.TipoTituloDTOConverter;
import ConvertorDTO.demo.proyecto.TituloDTOConverter;
import ConvertorDTO.demo.proyecto.TituloSinonimoDTOConverter;
import dto.demo.proyecto.TitleAkasDTO;
import dto.demo.proyecto.TitleBasicsDTO;
import entity.demo.proyecto.TipoTitulo;
import entity.demo.proyecto.Titulo;
import entity.demo.proyecto.TituloSinonimo;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Persistence;
import repositorio.demo.proyecto.TipoTituloRepositorio;
import repositorio.demo.proyecto.TituloRepositorio;
import repositorio.demo.proyecto.TituloSinonimoRepositorio;
import java.io.File;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PersistirTituloSinonimo {
EntityManager entityManager = Persistence.createEntityManagerFactory("myPersistence")
.createEntityManager();
Controlador.DTOParser dtoParser = new Controlador.DTOParser();
public void ingresarTituloDDBB(){
try{
entityManager.getTransaction().begin();
File titleBasicsOuput = new File("C:\\Users\\Sergio_Mendez_G\\Documents\\newFiles\\title.basics.tsv1");
File titleAKASOuput = new File("C:\\Users\\Sergio_Mendez_G\\Documents\\newFiles\\title.akas.tsv1");
TituloRepositorio tituloRepositorio = new TituloRepositorio(entityManager);
TituloSinonimoRepositorio tituloSinonimoRepositorio = new TituloSinonimoRepositorio(entityManager);
TituloSinonimoDTOConverter tituloSinonimoDTOConverter = new TituloSinonimoDTOConverter();
List<TitleAkasDTO> titleAkasDTOList = dtoParser.parse(TitleAkasDTO.class, titleAKASOuput);
titleAkasDTOList.stream()
.forEach(tituloSinonimoNuevo->{
TituloSinonimo tituloSinonimo = tituloSinonimoDTOConverter.convertir(tituloSinonimoNuevo);
tituloSinonimo.setTituloSinonimos(tituloRepositorio.buscarTItuloPorCodigo(tituloSinonimoNuevo.getTitleId()));
tituloSinonimoRepositorio.crearOActualizarTItuloSinonimo(tituloSinonimo);
});
entityManager.getTransaction().commit();
}catch (Exception ex) {
Logger.getLogger("Main").log(Level.SEVERE, "Error", ex);
entityManager.getTransaction().rollback();
} finally {
entityManager.close();
}
}
}
<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 dto.demo.proyecto;
import com.opencsv.bean.CsvBindByName;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
*
* @author Sergio_Mendez_G
*/
@Getter
@Setter
@ToString
public class TitleBasicsDTO {
@CsvBindByName
private String tconst;
@CsvBindByName
private String titleType;
@CsvBindByName
private String primaryTitle;
@CsvBindByName
private String originalTitle;
@CsvBindByName
private String isAdult;
@CsvBindByName
private String startYear;
@CsvBindByName
private String endYear;
@CsvBindByName
private String runtimeMinutes;
@CsvBindByName
private String genres;
}
<file_sep>package repositorio.demo.proyecto;
import entity.demo.proyecto.TituloSinonimo;
import entity.demo.proyecto.TituloSinonimo_;
import jakarta.persistence.EntityManager;
import jakarta.persistence.NoResultException;
import jakarta.persistence.criteria.CriteriaQuery;
import jakarta.persistence.criteria.Root;
public class TituloSinonimoRepositorio {
private final EntityManager entityManager;
public TituloSinonimoRepositorio(EntityManager entityManager) {
this.entityManager = entityManager;
}
public TituloSinonimo buscarTItuloSinonimoPorId(Long tituloSinonimoId) {
var builder = this.entityManager.getCriteriaBuilder();
CriteriaQuery<TituloSinonimo> tituloSinonimoCriteriaQuery = builder.createQuery(TituloSinonimo.class);
Root<TituloSinonimo> root = tituloSinonimoCriteriaQuery.from(TituloSinonimo.class);
tituloSinonimoCriteriaQuery.where(
builder.equal(root.get(TituloSinonimo_.tituloSinonimoId), tituloSinonimoId)
);
try {
return this.entityManager.createQuery(tituloSinonimoCriteriaQuery).getSingleResult();
} catch (NoResultException ex) {
}
return null;
}
public void crearOActualizarTItuloSinonimo(TituloSinonimo tituloSinonimoNuevo){
TituloSinonimo tituloSinonimo = this.buscarTItuloSinonimoPorId(tituloSinonimoNuevo.getTituloSinonimoId());
if (tituloSinonimo == null){
this.entityManager.persist(tituloSinonimoNuevo);
}else{
tituloSinonimo.setLinea(tituloSinonimoNuevo.getLinea());
tituloSinonimo.setNombre(tituloSinonimoNuevo.getNombre());
tituloSinonimo.setRegion(tituloSinonimoNuevo.getRegion());
tituloSinonimo.setLeguaje(tituloSinonimoNuevo.getLeguaje());
tituloSinonimo.setTipo(tituloSinonimoNuevo.getTipo());
tituloSinonimo.setAtributos(tituloSinonimoNuevo.getAtributos());
tituloSinonimo.setOriginal(tituloSinonimoNuevo.isOriginal());
this.entityManager.merge(tituloSinonimo);
}
}
}
<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 dto.demo.proyecto;
import com.opencsv.bean.CsvBindByName;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
*
* @author Sergio_Mendez_G
*/
@Setter
@Getter
@ToString
public class TitleRatingDTO {
@CsvBindByName
private String tconst;
@CsvBindByName
private String averageRating;
@CsvBindByName
private String numVotes;
}
<file_sep>package entity.demo.proyecto;
import jakarta.persistence.metamodel.SetAttribute;
import jakarta.persistence.metamodel.SingularAttribute;
import jakarta.persistence.metamodel.StaticMetamodel;
import javax.annotation.processing.Generated;
@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Profesion.class)
public abstract class Profesion_ extends entity.demo.proyecto.Entidad_ {
public static volatile SingularAttribute<Profesion, String> descripcion;
public static volatile SingularAttribute<Profesion, Long> profesionId;
public static volatile SingularAttribute<Profesion, String> nombre;
public static volatile SetAttribute<Profesion, Persona> personaSet;
public static final String DESCRIPCION = "descripcion";
public static final String PROFESION_ID = "profesionId";
public static final String NOMBRE = "nombre";
public static final String PERSONA_SET = "personaSet";
}
|
96390e7e1a78156d372b73dbf765f6f77b09dbb7
|
[
"Java"
] | 20
|
Java
|
sergiomendez1998/proyectoJavaWebFinal
|
92d0bdd8a6fc8cb454b69a2690168c2e075a15e6
|
757be8e0e006db0f71b19af48cc8ada773fe4733
|
refs/heads/master
|
<file_sep># short-pyspark
short scripts and functions using pyspark
<file_sep>import sys
import datetime
from pyspark.sql import SparkSession, HiveContext
from pyspark.sql.functions import col
from pyspark.sql.types import *
sc = SparkSession.builder \
.appName("XML Converter to Fermat") \
.config("spark.sql.warehouse.dir", "/user/hive/warehouse") \
.enableHiveSupport() \
.getOrCreate()
props = {}
with open(sys.argv[1], "r") as f:
for line in f:
(key, val) = line.split(":")
props[key] = str(val).rstrip()
def flatten_df(nested):
flat_cols = [c[0] for c in nested.dtypes if c[1][:6] != 'struct']
nested_cols = [c[0] for c in nested.dtypes if c[1][:6] == 'struct']
flat_df = nested.select(flat_cols + [col(nc + '.' + c).alias(nc + '_' + c) for nc in nested_cols for c in nested.select(nc + '.*').columns])
return flat_df
schema = StructType([StructField('ValueDate', LongType())])
value_date = sc.read.format('com.databricks.spark.xml') \
.options(rowTag="root") \
.load(props['source_path'], schema=schema)
partition = value_date.collect()[0][0]
#partition = datetime.datetime.now().strftime("%Y%m%d")
exposure = sc.read.format('com.databricks.spark.xml') \
.options(rootTag='ArrayOfExposures') \
.options(rowTag='Exposure') \
.load(props['source_path'])
flat_exposure = flatten_df(exposure)
limit = sc.read.format('com.databricks.spark.xml') \
.options(rootTag='ArrayOfLimits') \
.options(rowTag='Limit') \
.load(props['source_path'])
flat_limit = flatten_df(limit)
if props['target_type'] == "JSON":
flat_exposure.coalesce(1).write.format("json").save(props['dest_path'] + "/exposure_" + str(partition))
flat_limit.coalesce(1).write.format("json").save(props['dest_path'] + "/limit_" + str(partition))
elif props['target_type'] == "HIVE":
flat_exposure.registerTempTable("tmp_exposure")
sc.sql(
"INSERT OVERWRITE TABLE " + props['dest_table'] + "_exposure PARTITION(valueDate = " + str(partition) + ") SELECT * FROM tmp_exposure")
flat_limit.registerTempTable("tmp_limit")
sc.sql(
"INSERT OVERWRITE TABLE " + props[
'dest_table'] + "_limit PARTITION(valueDate = " + str(partition) + ") SELECT * FROM tmp_limit")
else:
print("Missing/Wrong target_type value (Ex.: HIVE or JSON)")
<file_sep>from pyspark.sql import SparkSession
import pyspark.sql.types as T
from pyspark.sql import Window
from pyspark.sql.functions import last
import sys
def load_trades(spark):
data = [
(10, 1546300800000, 37.50, 100.000),
(10, 1546300801000, 37.51, 100.000),
(20, 1546300804000, 12.67, 300.000),
(10, 1546300807000, 37.50, 200.000),
]
schema = T.StructType(
[
T.StructField("id", T.LongType()),
T.StructField("timestamp", T.LongType()),
T.StructField("price", T.DoubleType()),
T.StructField("quantity", T.DoubleType()),
]
)
return spark.createDataFrame(data, schema)
def load_prices(spark):
data = [
(10, 1546300799000, 37.50, 37.51),
(10, 1546300802000, 37.51, 37.52),
(10, 1546300806000, 37.50, 37.51),
]
schema = T.StructType(
[
T.StructField("id", T.LongType()),
T.StructField("timestamp", T.LongType()),
T.StructField("bid", T.DoubleType()),
T.StructField("ask", T.DoubleType()),
]
)
return spark.createDataFrame(data, schema)
def fill(trades, prices):
"""
Combine the sets of events and fill forward the value columns so that each
row has the most recent non-null value for the corresponding id. For
example, given the above input tables the expected output is:
+---+-------------+-----+-----+-----+--------+
| id| timestamp| bid| ask|price|quantity|
+---+-------------+-----+-----+-----+--------+
| 10|1546300799000| 37.5|37.51| null| null|
| 10|1546300800000| 37.5|37.51| 37.5| 100.0|
| 10|1546300801000| 37.5|37.51|37.51| 100.0|
| 10|1546300802000|37.51|37.52|37.51| 100.0|
| 20|1546300804000| null| null|12.67| 300.0|
| 10|1546300806000| 37.5|37.51|37.51| 100.0|
| 10|1546300807000| 37.5|37.51| 37.5| 200.0|
+---+-------------+-----+-----+-----+--------+
:param trades: DataFrame of trade events
:param prices: DataFrame of price events
:return: A DataFrame of the combined events and filled.
"""
res = trades.select('id','timestamp',lit(None).alias('bid'),lit(None).alias('ask'),'price','quantity').union(prices.select('id','timestamp','bid','ask',lit(None).alias('price'),lit(None).alias('quantity')))
window = Window.partitionBy('id').orderBy('timestamp').rowsBetween(-sys.maxsize, 0)
filled_bid = last(res['bid'], ignorenulls=True).over(window)
filled_ask = last(res['ask'], ignorenulls=True).over(window)
filled_price = last(res['price'], ignorenulls=True).over(window)
filled_quantity = last(res['quantity'], ignorenulls=True).over(window)
res = res.withColumn('temp_bid', filled_bid).drop("bid").withColumnRenamed("temp_bid","bid")
res = res.withColumn('temp_ask', filled_ask).drop("ask").withColumnRenamed("temp_ask","ask")
res = res.withColumn('temp_price', filled_price).drop("price").withColumnRenamed("temp_price","price")
res = res.withColumn('temp_quantity', filled_quantity).drop("quantity").withColumnRenamed("temp_quantity","quantity")
res = res.sort("timestamp",ascending=True)
filled_bid = last(res['bid'], ignorenulls=True).over(window)
filled_ask = last(res['ask'], ignorenulls=True).over(window)
filled_price = last(res['price'], ignorenulls=True).over(window)
filled_quantity = last(res['quantity'], ignorenulls=True).over(window)
res = res.withColumn('temp_bid', filled_bid).drop("bid").withColumnRenamed("temp_bid","bid")
res = res.withColumn('temp_ask', filled_ask).drop("ask").withColumnRenamed("temp_ask","ask")
res = res.withColumn('temp_price', filled_price).drop("price").withColumnRenamed("temp_price","price")
res = res.withColumn('temp_quantity', filled_quantity).drop("quantity").withColumnRenamed("temp_quantity","quantity")
res = res.sort("timestamp",ascending=True)
return res
raise NotImplementedError()
def pivot(trades, prices):
"""
Pivot and fill the columns on the event id so that each row contains a
column for each id + column combination where the value is the most recent
non-null value for that id. For example, given the above input tables the
expected output is:
+---+-------------+-----+-----+-----+--------+------+------+--------+-----------+------+------+--------+-----------+
| id| timestamp| bid| ask|price|quantity|10_bid|10_ask|10_price|10_quantity|20_bid|20_ask|20_price|20_quantity|
+---+-------------+-----+-----+-----+--------+------+------+--------+-----------+------+------+--------+-----------+
| 10|1546300799000| 37.5|37.51| null| null| 37.5| 37.51| null| null| null| null| null| null|
| 10|1546300800000| null| null| 37.5| 100.0| 37.5| 37.51| 37.5| 100.0| null| null| null| null|
| 10|1546300801000| null| null|37.51| 100.0| 37.5| 37.51| 37.51| 100.0| null| null| null| null|
| 10|1546300802000|37.51|37.52| null| null| 37.51| 37.52| 37.51| 100.0| null| null| null| null|
| 20|1546300804000| null| null|12.67| 300.0| 37.51| 37.52| 37.51| 100.0| null| null| 12.67| 300.0|
| 10|1546300806000| 37.5|37.51| null| null| 37.5| 37.51| 37.51| 100.0| null| null| 12.67| 300.0|
| 10|1546300807000| null| null| 37.5| 200.0| 37.5| 37.51| 37.5| 200.0| null| null| 12.67| 300.0|
+---+-------------+-----+-----+-----+--------+------+------+--------+-----------+------+------+--------+-----------+
:param trades: DataFrame of trade events
:param prices: DataFrame of price events
:return: A DataFrame of the combined events and pivoted columns.
"""
suf = ["bid","ask","price","quantity"]
i = 0
base = fill(trades, prices)
ids = base.select('id').distinct().collect()
while i < int(len(ids)):
for s in suf:
colname = str(ids[int(i)][0]) + "_" + s
base = base.withColumn(colname, F.col(s))
i += 1
return base
raise NotImplementedError()
if __name__ == "__main__":
spark = SparkSession.builder.master("local[*]").getOrCreate()
trades = load_trades(spark)
trades.show()
prices = load_prices(spark)
prices.show()
fill(trades, prices).show()
pivot(trades, prices).show()
<file_sep>import sys
import logging
import ast
from pyspark.sql import SparkSession
from pyspark.sql.types import *
sc = SparkSession.builder \
.appName("NDOD - Convert files") \
.config("spark.sql.warehouse.dir", "/user/hive/warehouse") \
.config("hive.exec.dynamic.partition", "true") \
.config("hive.exec.dynamic.partition.mode", "nonstrict") \
.enableHiveSupport() \
.getOrCreate()
def main ():
logger = logging.getLogger('py4j')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
props = {}
#Read the argument file and segregate the properties.
with open(sys.argv[1], "r") as f:
for line in f:
(key, val) = line.split("=")
props[key] = str(val)
# Use the field properties to read the input file
fields = ast.literal_eval(props["fields"])
partition = str(props["partition"]).rstrip()
schema = StructType([StructField(field_name, StringType(), True) for field_name in fields])
#df = sqlContext.createDataFrame(sc.emptyRDD(), schema)
content = []
#read the input data file and tranform it to fields separated by comma to create the dataframe
for l in open(sys.argv[2], "r"):
value = ""
ct = 0
for i in list(fields):
ct += 1
sp = fields[i].split(",")[0]
ep = fields[i].split(",")[1]
value += "'" + l[int(sp):int(ep)] + "'"
if ct < len(list(fields)):
value += ","
content.append(value)
#create the dataframe from content
df = sc.createDataFrame(list(map(lambda x: x.split(','), content[1:-1])), schema=schema)
logger.info("###### Processing file " + sys.argv[2] + " with HEADER " + content[0])
logger.info("###### Will be added " + str(df.count()) + "registers to table " + str(props["htable"]).rstrip() + " partitioned by " + partition)
df.registerTempTable("tmp_content")
partition_val = df.select(str(partition)).collect()
logger.info("###### Partition value -> " + partition_val[0][0])
#sc.sql("INSERT OVERWRITE TABLE " + props['htable'] + " PARTITION(" + str(partition) + "=" + partition_val[0][0] + ") SELECT * FROM tmp_content")
df.write.mode("overwrite").insertInto(props["htable"])
#sc.sql(
# "CREATE TABLE " + props['htable'] + "AS SELECT * FROM tmp_content")
main()
<file_sep>#!/bin/bash
parallelism = `wc -l tables.lst`
function popStack(){
: ${1?'Missing stack name'}
# check if array not void
local pointerStack=$(<$pointerStackFile)
[ $pointerStack -ge $initialSizeStack ] && return 1
eval "$1"=${listOfTables[$pointerStack]}
(( pointerStack=$pointerStack+1))
echo $pointerStack > $pointerStackFile
return 0
}
function doSqoop(){
local id=$1 # this id should be unique betwween all the instances of doSqoop
local sqoopCmd=`sed '$id!d' tables.lst`
local logFileSummary=$databaseBaseDir/process_$id-summary.log
local logFileRaw=$databaseBaseDir/process_$id-raw.log
echo -e "\n\n############################# `date` Starting new execution #############################" >> $logFileSummary
while true; do
# get the name of the next table to sqoop
popStack $sqoopCmd
[ $? -ne 0 ] && break
echo "[`date`] Executing command -- $sqoopCmd" | tee -a $logFileSummary $logFileRaw
#sqoop import -D mapreduce.job.queuename=$queue -D mapreduce.job.ubertask.enable=true --connect "jdbc:sqlserver://$origServer:1433; database=$origDatabase; username=myUser; password=<PASSWORD>" --hive-import --hive-database $hiveDatabase --fields-terminated-by '\t' --null-string '' --null-non-string '' -m 1 --outdir $dirJavaGeneratedCode --query "select a.* from $origTable a where \$CONDITIONS" --target-dir $targetTmpHdfsDir/$myTable --hive-table $myTable >> $logFileRaw 2>> $logFileRaw
exec $sqoopCmd
echo "Tail of : $logFileRaw" >> $logFileSummary
tail -6 $logFileRaw >> $logFileSummary
done
echo -e "\n############################# `date` Ending execution #############################" >> $logFileSummary
}
for i in `seq $parallelism`; do
sleep 0.1 # to avoid subprocesses to pop the stack at the same time
(doSqoop $i) &
if i > 10
sleep 2m
done
wait<file_sep>import sys
import logging
import threading
from pyspark import SparkSession
import pyspark.sql
sc = SparkSession.builder \
.appName("sqlImport - Diff Schema") \
.config("spark.sql.warehouse.dir", "/user/hive/warehouse") \
.enableHiveSupport() \
.getOrCreate()
def getTableSchema (ctx, src_table):
sch_table = ctx.table(src_table)
schema = sch_table.printSchema()
return [i.name for i in schema.fields]
def alterHiveTable (hive_table):
tbl_source = hive_table
def execValidation (hostname, portnumber, dbtable, user, password, htable):
logger = logging.getLogger(os.path.basename(__file__))
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
#sc.read.jdbc("CONNECTION_STRING", "TABLE", properties={"user":"repl","password":"<PASSWORD>"})
hive_table = htable
db_table = dbtable
sqldf = sc.read \
.format("jdbc") \
.option("url", "jdbc:oracle:thin:"+user+"/"+password+"@//"+hostname+":"+portnumber+"/SID") \
.option("dbtable", dbtable) \
.option("user", user) \
.option("password", <PASSWORD>) \
.option("driver", "oracle.jdbc.driver.OracleDriver") \
.load()
hivedf = sc.sql("SELECT + FROM " + hive_table + "LIMIT 1")
hive_schema = getTableSchema(hivedf, hive_table)
db_schema = getTableSchema(sqldf, db_table)
logger.info('Comparing columns...')
if hive_schema < db_schema:
logger.warn('Table columns DO NOT match!')
alterHiveTable(hive_table)
logger.info('Hive schema validation finished!!')
def main():
logger = logging.getLogger(os.path.basename(__file__))
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
tbl_args = {}
with open(sys.argv[1], "r") as f:
for line in f:
(hostname, portnumber, user, dbtable, user, password, htable) = line.split(":")
threading.Thread(target=execValidation, args=(hostname, portnumber, user, dbtable, user, password, htable)).start()
|
0e63bec03596a90270f4b4fb489dd22ff9ec0fb1
|
[
"Markdown",
"Python",
"Shell"
] | 6
|
Markdown
|
halenyuri/short-pyspark
|
1b5ffd9056f409f1c39f7b61a571068552619746
|
bfe82d97099348ddd6ab447be5aec76d9abe1009
|
refs/heads/master
|
<file_sep>var http = require('http')
var async = require('async')
require('string_format')
var AWS = require('aws-sdk')
var lambda = new AWS.Lambda({"region":"us-east-1"})
module.exports.get = (event, context, callback) => {
var eventJSON = {}
var tasks = [];
tasks = [
getHeroComics(event.hero1["id"],event.hero1["comicAmount"]),
getHeroComics(event.hero2["id"],event.hero2["comicAmount"]),
];
async.parallel(tasks, function(error,data){
if(error){
console.log(error);
callback(error);
} else {
var finalResponse =[]
for(let index =0; index < data.length; index++){
var currentPayload = JSON.parse(data[index].Payload)
finalResponse.push(currentPayload)
}
// Loop through the smaller array so that the process is shorter
if(finalResponse[0].length < finalResponse[1].length){
var commonComics = getCommon(finalResponse[0],finalResponse[1])
} else {
var commonComics = getCommon(finalResponse[1],finalResponse[0])
}
callback(null,commonComics)
}
});
};
function getCommon(series1, series2){
commonSeries = []
for(var key in series1){
if (key in series2){
commonSeries.push({
id:key,
title:series1[key]
});
}
}
return commonSeries
}
var getHeroComics = function(heroId,comicAmount) {
return (function(callback){
var lambdaParams = {
FunctionName : 'mejorge-dev-get-hero-comics',
InvocationType : 'RequestResponse',
Payload: '{"hero":' + heroId + ',"comicAmount":' + comicAmount + '}'
}
lambda.invoke(lambdaParams, function(error,data){
if(error){
callback(error)
} else{
callback(null,data)
}
})
})
}
<file_sep>var http = require('http')
var async = require('async')
require('string_format')
var AWS = require('aws-sdk')
var lambda = new AWS.Lambda({"region":"us-east-1"})
module.exports.get = (event, context, callback) => {
var url = "http://gateway.marvel.com/v1/public/characters";
var pubKey = "b8dc1a3d05d7593f780bbe8d41bcfd7a";
var ts = "1505721483"
var hashKey = "<KEY>";
var limit = 1;
var finalUrl = url + "?apikey=" + pubKey + "&ts=" + ts + "&hash=" + hashKey + "&limit=" + limit;
http.get(finalUrl, (res) => {
res.setEncoding('utf8');
var responseData = "";
res.on("data", (data) => {
responseData += data;
})
res.on("end", (data) => {
var heroesAmount = JSON.parse(responseData).data.total;
tasks = getHeroesTasks(heroesAmount);
async.parallel(tasks, function(error,data){
if(error){
console.log(error);
callback(error);
} else {
var finalResponse =[]
for(let index =0; index < data.length; index++){
var currentPayload = JSON.parse(data[index].Payload)
finalResponse = finalResponse.concat(currentPayload[0])
}
callback(null,finalResponse)
}
});
});
});
};
var getHeroesTasks = function (heroesAmount) {
tasks = []
for(let i=0;i<=Math.ceil(heroesAmount/100);i++){
tasks.push(function(callback){
var lambdaParams = {
FunctionName : 'mejorge-dev-get-hero-page',
InvocationType : 'RequestResponse',
Payload: '{"page":"' + i + '"}'
}
lambda.invoke(lambdaParams, function(error,data){
if(error){
callback(error)
} else{
callback(null,data)
}
})
})
}
return tasks;
}
<file_sep>var http = require('http');
var async = require('async');
require('string_format');
var AWS = require('aws-sdk');
var s3 = new AWS.S3();
var lambda = new AWS.Lambda({"region":"us-east-1"});
var dynamodb = new AWS.DynamoDB({"region":"us-east-1"});
var tableName = "mejorge-marvel-log";
var bucketName = "mejorge-hero-info";
var UUID = require('uuid-js');
var itemData = {};
module.exports.get = (event, context, callback) => {
itemData = {
"Id":UUID.create(),
"StartTime":new Date().getTime(),
"Character1":event.hero1.id,
"Character2":event.hero2.id,
"SingleQuantity": Math.ceil(event.hero1.comicAmount/100) + Math.ceil(event.hero2.comicAmount/100)
};
var objectKey = getKeyFromIds(event.hero1.id, event.hero2.id);
logLambdaDataToDynamo(itemData);
checkIfObjectExists(objectKey, function(exists){
if(exists){
obtainCommonFromBucket(objectKey, callback);
} else {
obtainCommonFromApi(event.hero1, event.hero2, callback);
}
});
};
function saveResultsOnBucket(results, objectKey, callback){
var params = {
Body: JSON.stringify(results),
Bucket: bucketName,
Key: objectKey,
ACL: "public-read",
ContentType: "application/json",
};
s3.putObject(params, function(err, data) {
if (err){
callback(err);
} else {
callback(null, results);
}
});
}
function obtainCommonFromBucket(objectKey, callback){
var params = {
Bucket: bucketName,
Key: objectKey,
};
s3.getObject(params, function(err, data) {
if (err){
console.log(err, err.stack);
callback(err);
} else {
response = JSON.parse(data.Body.toString('utf-8'));
callback(null, response);
}
});
}
function obtainCommonFromApi (hero1, hero2, callback){
var lambdaParams = {
FunctionName : 'mejorge-dev-get-comics-from-api',
InvocationType : 'RequestResponse',
Payload: '{"hero1":' + JSON.stringify(hero1) + ',"hero2":' + JSON.stringify(hero2) + '}'
}
lambda.invoke(lambdaParams, function(error,data){
if(error){
callback(error)
} else{
objectKey = getKeyFromIds(hero1.id, hero2.id);
saveResultsOnBucket(JSON.parse(data.Payload), objectKey, callback);
}
})
}
function checkIfObjectExists (objectKey, callback) {
var params = {
Bucket: bucketName,
Key: objectKey
};
s3.headObject(params, function(err, data) {
if (err) {
callback(false);
} else {
callback(true);
}
});
}
function logLambdaDataToDynamo(data){
item = {
"Id":{
S:'' + data["Id"]
},
"StartTime":{
S:'' + data["StartTime"]
},
"EndTime":{
S:'' + new Date().getTime(),
},
"SingleQuantity":{
N:'' + data["SingleQuantity"]
},
"Character1":{
S:'' + data["Character1"]
},
"Character2":{
S:"" + data["Character2"]
},
//"MemoryReserved":{
//N:data["MemoryReserved"]
//},
//"MemoryUsed":{
//N:data["MemoryUsed"]
//}
};
var params = {
Item: item,
TableName: "mejorge-marvel-log",
ReturnConsumedCapacity: "TOTAL"
};
dynamodb.putItem(params, function(err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
});
}
function getKeyFromIds(id1, id2){
return id1 < id2
? id1 + "-" + id2 + "-comics.json"
: id2 + "-" + id1 + "-comics.json"
}
<file_sep>var http = require('http')
module.exports.get = (event, context, callback) => {
var url = "http://gateway.marvel.com/v1/public/characters";
var pubKey = "b8dc1a3d05d7593f780bbe8d41bcfd7a";
var ts = "1505721483"
var hashKey = "<KEY>";
var limit = event.limit ? event.limit : 100;
var page = event.page ? event.page : 0;
var offset = (page*limit)+1;
var finalUrl = url + "?apikey=" + pubKey + "&ts=" + ts + "&hash=" + hashKey + "&limit=" + limit + "&offset=" + offset;
http.get(finalUrl, (res) => {
res.setEncoding('utf8');
var responseData = "";
res.on("data", (data) => {
responseData += data;
})
res.on("end", (data) => {
var heroes = JSON.parse(responseData).data.results
var heroesRes = [];
heroesRes.push(heroes.map(
function(evt){
return {
"name":evt.name,
"id":evt.id,
"comicAmount":evt.comics.available,
"seriesAmount":evt.series.available
}
})
)
callback(null, heroesRes);
});
});
};
<file_sep>var http = require('http')
module.exports.get = (event, context, callback) => {
var url = "http://gateway.marvel.com/v1/public/characters/" + event.hero + "/series";
var pubKey = "b8dc1a3d05d7593f780bbe8d41bcfd7a";
var ts = "1505721483"
var hashKey = "<KEY>";
var limit = event.limit ? event.limit : 100;
var page = event.page ? event.page : 0;
var offset = (page*limit)+1;
var finalUrl = url + "?apikey=" + pubKey + "&ts=" + ts + "&hash=" + hashKey + "&limit=" + limit + "&offset=" + offset;
http.get(finalUrl, (res) => {
res.setEncoding('utf8');
var responseData = "";
res.on("data", (data) => {
responseData += data;
})
res.on("end", (data) => {
var series = JSON.parse(responseData).data.results
var seriesRes = {};
series.map(
function(evt){
seriesRes[evt.id] = evt.title
}
)
callback(null, seriesRes);
});
});
};
<file_sep>var http = require('http')
var async = require('async')
require('string_format')
var AWS = require('aws-sdk')
var lambda = new AWS.Lambda({"region":"us-east-1"})
module.exports.get = (event, context, callback) => {
tasks = []
for(let i=1;i<=Math.ceil(event.comicAmount/100);i++){
tasks.push(function(callback){
var lambdaParams = {
FunctionName : 'mejorge-dev-get-comic-page',
InvocationType : 'RequestResponse',
Payload: '{"hero":' + event.hero + ',"page":' + (i-1) + '}'
}
lambda.invoke(lambdaParams, function(error,data){
if(error){
callback(error)
} else{
callback(null,data)
}
})
})
}
async.parallel(tasks, function(error,data){
if(error){
console.log(error);
callback(error);
} else {
var finalResponse = {}
for(let index =0; index < data.length; index++){
var currentPayload = JSON.parse(data[index].Payload)
for(let id in currentPayload){
finalResponse[id] = currentPayload[id]
}
}
callback(null,finalResponse)
}
});
};
|
2f34079da10147cec2d691de554bab82d9d62ddc
|
[
"JavaScript"
] | 6
|
JavaScript
|
ElMejorge/marvel_heroes_lambdas
|
d191c04f7898e875b3f33e8a275b4321319cccd6
|
b55607a352d8ef915e8a1c69f9419255fcd7528c
|
refs/heads/master
|
<file_sep>def downloadEnergyData():
import urllib.request
print('Beginning file download ...')
url = "https://data.london.gov.uk/download/smartmeter-energy-use-data-in-london-households/3527bf39-d93e-4071-8451-df2ade1ea4f2/Power-Networks-LCL-June2015(withAcornGps).zip"
#urllib.request.urlretrieve(url, './data.zip')
urllib.request.urlretrieve(url, './Power-Networks-LCL-June2015(withAcornGps).zip')<file_sep>def importEnergyData():
# It is assumed at this stage that Power-Networks-LCL-June2015(withAcornGps).zip has been downloaded from
# data.london.gov.uk/dataset/smartmeter-energy-use-data-in-london-households
from zipfile import ZipFile
with ZipFile('Power-Networks-LCL-June2015(withAcornGps).zip', 'r') as zip:
print("The zip file contains ...")
zip.printdir() # Prints contents of the zip file.
# extracting all the files
print("Extracting the csv file ...")
zip.extractall()
print('Finished extracting csv file.')
# 'ToU' time of use
# 'Std' standard
# Split the large .csv file containing all the data into smaller csv files
# containing data specific to a specific year and a specific month.
print('Creating monthly data files ...')
with open("Power-Networks-LCL-June2015(withAcornGps)v2.csv") as file, open('data.csv', "w") as ofile:
# Create a dictionary to store file handles with tuple keys (year, month).
fileList = {}
# Read the CSV header.
line = next(file)
for line in file:
year = line[14:18]
month = line[19:21]
# Grab the file handle associate with this year, month pair.
resp = fileList.get((year, month))
if resp == None:
# File has not been created for this year, month pair.
# So create it and store in the dictionary.
fname = 'data_' + year + month + '.csv'
print('Creating ', fname, " ...")
fym = open(fname, "w")
fileList[(year, month)] = (fym, fname)
xf = fym
else:
xf = resp[0]
xf.write(line)
# Close all the files that were created based on year, month pair. This will force
# a flush of any remaining items left in the stream.
for x in fileList:
fileList[x][0].close()
from cleanAndProcessEnergyData import cleanAndProcessEnergyData
print('Clean and aggregate monthly data ...' )
xFileList = {}
for key, val in fileList.items():
infile = val[1]
print('Processing ', infile)
outfile = val[1][0:-4] + "_proc.csv"
cleanAndProcessEnergyData(infile, outfile)
print('Created ', outfile)
xFileList[key] = (infile, outfile)
import pandas as pd
dfs = pd.DataFrame(xFileList)
dfs = dfs.transpose()
dfs.reset_index(inplace = True)
dfs.columns = ["year", "month", "raw", "processed"]
# Serialize the file directory.
dfs.to_csv("./fileList.csv", index = False)
<file_sep>def multiEventPlotter(dfxlst, title, col = "total", labels = None):
import matplotlib.pyplot as plt
plt.figure(figsize=(12,4))
handles = []
for idx, dfx in enumerate(dfxlst):
if labels != None:
h, = plt.plot(dfx["time"],dfx[col], label = labels[idx])
else:
h, = plt.plot(dfx["time"],dfx[col])
handles.append(h)
plt.grid()
if labels != None: plt.legend(loc = 'best', handles = handles)
plt.xticks(rotation='vertical')
plt.title(title)
plt.xlabel("time stamp")
plt.ylabel("Energy Consumption (kW-h)")
plt.show()<file_sep># SmartMeter Energy Consumption in London Households
This project demonstrates how Python is used in the processing and visualization of SmartMeter Energy Consumption Data from the Low Carbon London project. The majority of the data processing makes use of the Pandas module. The visualization is undertaken with multi-line plots created using the Matplotlib module. The project was initiated by and undertaken with the help of <NAME> (https://www.linkedin.com/in/michael-blackmon-b4431263).
The Low Carbon London project was led by UK Power Networks, a company that owns and maintains electricity cables and lines across London, the South East and East of England. As part of the LCL project, energy consumption readings were taken for a sample of 5,567 London Households between November 2011 and February 2014.
The line plot shown below demonstrates typical graphical output that can be generated once the data has been cleaned and aggregated. It depicts the average energy consumption at a given time stamp for a sample of months (January through July for 2013).

The summer months (April through July) demonstrate a tendency for the peak of the energy consumption to occur at approximately the same time as sunset (data available from http://www.timeanddate.com). However, the same trend cannot be observed as strongly for the winter months (January through March), which all peak at roughly the same time stamp (19:15). Sunset for the winter months takes place much earlier in the day. It is conjectured that electrical draws associated with heating and cooking are less subject to time variation during the winter months and might explain the lack of variability in the time stamp of the peak energy consumption.
## Data Source
The SmartMeter data has been made available on the following site.
https://data.london.gov.uk/dataset/smartmeter-energy-use-data-in-london-households
This site allows the viewer to download a zip file of size 783 MB that contains an 11.3 GB CSV(comma seperated values) file with 167 million rows of data. The CSV file contains measurements of energy consumption in kW-h taken every half hour for each customer over a period of about two years. Furthermore, each customer is assigned an 'Acorn' designation together with a prosperity category based on the 'Acorn' designation. Acorn (developed by CACI Ltd in the UK) segments UK postcodes and neighborhoods into 6 Categories, 18 Groups and 62 types, three of which are not private households. By analyzing significant social factors and population behavior, it provides precise information and in-depth understanding of the different types of people (https://en.wikipedia.org/wiki/Acorn_(demographics)).
The unzipping of the downloaded file can be achieved using standard operating system utilities. However, it can also be undertaken with Python code by using the ZipFile module. This is illustrated by the following code taken from ```importEnergyData.py```.
```python
from zipfile import ZipFile
with ZipFile('Power-Networks-LCL-June2015(withAcornGps).zip', 'r') as zip:
print("Extracting the csv file ...")
zip.extractall()
```
There is a challenge in cleaning and aggregating the data so that either the total or mean energy usage (taken over all participating customers) can be calculated and thence visualized. Most notably, the sheer size of the data does not lend itself to successful in-memory manipulation using Pandas. Therefore, the first step in processing the data is to split it into 28 separate CSV files, each representing energy consumption data for all registered customers for each month of each year (Nov 2011 - Feb 2014). The Python code required to do this is contained in the top half of the file ```importEnergyData.py``` (line 27).
## Data Cleaning
Once the data has been split into bit-size pieces, the next challenge is to clean the data. The Python code required to do this is contained in the file ```cleanAndProcessEnergyData.py```, which contains an eponymous function that accepts one of the 28 uncleaned and unaggregated monthly CSV files and outputs a cleaned and aggregated version that can then be used for additional calculations and/or visualization.
The data cleaning operations include:
* Dropping rows that contain null and NaN values
* Eliminating duplicate rows (corresponding to duplicate SmartMeter reports)
* Elimination of Time-of-Use data.
Time-of-Use metering entails the employment of an array of energy rates based on the time of day in which the energy is being consumed. It is elminated in order to prevent the time-dependent energy tariff from influencing the fundamental daily trends shown by the energy consumption data.
## Data Aggregation
The remainder of the Python code contained in ```cleanAndProcessEnergyData.py``` is devoted to grouping energy consumption records by timestamp in order to calculate the total and mean energy consumption (per timestamp) over all customers for any given day.
An elegant way to this is to use a Pandas pivot table to collect energy sums and measurement counts based on grouping the meter reports by both timestamp and prosperity group. The pivot table is a two-dimensional equivalent to the Pandas groupby functionality.
```Python
# Construct a pivot table for the sums.
# fill_value = 0.0 provides for a meaningful value to be inserted for the case in which
# no measurement reports are made for a particular grouping.
xdf1 = pd.pivot_table(xdf, values=["energy"], index=["time"], columns=["prosperity group"], \
aggfunc= np.sum, fill_value = 0.0)
xdf1["total"] = xdf1.sum(axis = 1)
# Construct a pivot table for the counts.
# fill_value = 1 helps us to avoid a divide by zero error for the case in which no measuremet
# reports are made for a particular grouping.
xdf2 = pd.pivot_table(xdf, values=["energy"], index=["time"], columns=["prosperity group"], \
aggfunc= len, fill_value = 1)
xdf2["total"] = xdf2.sum(axis = 1)
```
The sum of the energy sums and their associated counts are also calculated in each respective Pandas dataframe. The ```axis=1``` argument ensures that summation is peformed across the columns for any given row. The two tables are subsequently inner-joined in order for mean energy usage to be calculated. The join operation is performed on equivalence of the index of each dataframe using the Pandas dataframe ```.join(...)``` function.
With the use of standard Pandas column operations, it is a straightforward task to perform a calculation of mean usage at a given time point (i) for all customers within a specific prosperity group and (ii) for the totality of customers over all prosperity groups.
## Average energy consumption for a given month
The data cleaning and aggregation operations result in the creation of 28 CSV files, each of which is labeled by month and year. For example, the CSV file containing data for July 2013 is ```data_201307_proc.csv```. Each file contains total and mean energy consumption taken over all the customers for timestamps taken every half hour in a given month.
The list of all files that are produced in this way is given in another CSV file called ```fileList.csv```, which is created during the execution of ```importEnergyData.py```. This CSV file also contains 'year' and 'month' integer fields associated with each file. It can be imported into a dataframe in order to facilitate an analysis that loops over a number of months.
```Python
dfsfile = pd.read_csv("./fileList.csv")
fname = dfsfile[(dfsfile["month"]==1) & (dfsfile["year"]==2013)]["processed"].iloc[0]
```
The following example demonstrates the calculation of the average of the mean energy consumptions at a given time of day, where the average is taken over all days during January 2013.
```Python
df012013 = pd.read_csv(fname)
df012013_ave = df012013.groupby(["time"]).mean()
df012013_ave.reset_index(inplace = True)
```
The code snippet above is taken from ```monthlyAnalysis.py``` which calculates average energy consumptions for the first seven months of 2013 in preparation for data vizualization in the form of the multi-line plot seen at the beginning of this readme.
## Monthly Visualization
The execution of ```monthlyAnalysis.py``` produces seven dataframes, each corresponding to one the first seven months of 2013. A multiline plot can depict the averge energy consumption at various points of the day for each of the featured months. This is achieved with the help of another Python function ```multiEventPlotter(...)```, which takes as input a list of dataframes and plots a quantity of interest vs. timestamp for each of the featured dataframes, together with user-specified labels.
The following code demonstrates how this is done for the case of monthly average energy consumption for the first seven months of 2013.
```Python
labs = ["2013-01", "2013-02", "2013-03", "2013-04", "2013-05", "2013-06", "2013-07"]
dflist = [df012013_ave, df022013_ave, df032013_ave, df042013_ave, df052013_ave, df062013_ave, df072013_ave]
multiEventPlotter(dflist, "Average Monthly Energy Consumption", col = "mean", labels = labs)
```
The ```multiEventPlotter(...)``` function uses basic plotting and labeling functions from Matplotlib.
<file_sep>def cleanAndProcessEnergyData(infile, outfile):
import pandas as pd
import numpy as np
from numpy import NaN
xdf = pd.read_csv(infile, header = None, low_memory=False, \
names = ["user", "tariff", "time", "energy", "acorn group", "prosperity group"])
# Filter out the time-of-use customers.
xdf = xdf[xdf["tariff"]=='Std']
# Replace any string "Null" values with NaN, so that dropna will
# remove the affected lines.
xdf.replace(["Null"],value = NaN, inplace = True)
# Any blanks or NaN values ?
xdf.dropna(inplace=True)
# Remove any duplicates, using columns 0 through 3 for the identification of
# duplicates.
xdf.drop_duplicates(["user", "time", "energy", "acorn group"], inplace = True, keep = 'last')
# The following ensures data consistency in the energy consumption column.
xdf["energy"] = xdf["energy"].astype(float)
# Construct a pivot table for the sums.
xdf1 = pd.pivot_table(xdf, values=["energy"], index=["time"], columns=["prosperity group"], \
aggfunc= np.sum, fill_value = 0.0)
xdf1.columns = [aa[1] for aa in xdf1.columns]
xdf1["total"] = xdf1.sum(axis = 1)
# Construct a pivot table for the counts.
# fill_value = 1 helps us to avoid a divide by zero error.
xdf2 = pd.pivot_table(xdf, values=["energy"], index=["time"], columns=["prosperity group"], \
aggfunc= len, fill_value = 1)
xdf2.columns = [aa[1] for aa in xdf2.columns]
xdf2["total"] = xdf2.sum(axis = 1)
# The right suffix is intentionally labeled 'mean' even
# though (at this point) the column represents a count.
xdf = xdf1.join(xdf2, rsuffix='_mean', how = 'inner')
# Rename the first half of the columns.
# Note that the calculation x/2 produces a float value.
# Perform a process based on the first half of the columns.
# Adding one to the total number of columns and then dividing
# by 2 will prevent spurious instances of rounding down due to
# a divide by two being marginally less than the exact value.
ncols = int((len(xdf.columns) + 1)/2)
for idx, cn in enumerate(xdf.columns[0:ncols]):
xdf[cn+"_mean"] = xdf[cn] / xdf[cn+"_mean"]
xdf.rename(columns = {"total_mean":"mean"}, inplace = True)
xdf.index.name = 'timestamp'
# Create day, month, time columns.
xdf.insert(0, 'year', xdf.index.map(lambda row: int(row[0:4])))
xdf.insert(0, 'month', xdf.index.map(lambda row: int(row[5:7])))
xdf.insert(0, 'day', xdf.index.map(lambda row: int(row[8:10])))
xdf.insert(0, 'time', xdf.index.map(lambda row: row[11:16]))
xdf.fillna(value = 0.0, inplace = True)
xdf.to_csv(outfile)
<file_sep>import pandas as pd
dfsfile = pd.read_csv("./fileList.csv")
from multiEventPlotter import *
fname = dfsfile[(dfsfile["month"]==1) & (dfsfile["year"]==2013)]["processed"].iloc[0]
df012013 = pd.read_csv(fname)
fname = dfsfile[(dfsfile["month"]==2) & (dfsfile["year"]==2013)]["processed"].iloc[0]
df022013 = pd.read_csv(fname)
fname = dfsfile[(dfsfile["month"]==3) & (dfsfile["year"]==2013)]["processed"].iloc[0]
df032013 = pd.read_csv(fname)
fname = dfsfile[(dfsfile["month"]==4) & (dfsfile["year"]==2013)]["processed"].iloc[0]
df042013 = pd.read_csv(fname)
fname = dfsfile[(dfsfile["month"]==5) & (dfsfile["year"]==2013)]["processed"].iloc[0]
df052013 = pd.read_csv(fname)
fname = dfsfile[(dfsfile["month"]==6) & (dfsfile["year"]==2013)]["processed"].iloc[0]
df062013 = pd.read_csv(fname)
fname = dfsfile[(dfsfile["month"]==7) & (dfsfile["year"]==2013)]["processed"].iloc[0]
df072013 = pd.read_csv(fname)
df012013_ave = df012013.groupby(["time"]).mean()
df012013_ave.reset_index(inplace = True)
df022013_ave = df022013.groupby(["time"]).mean()
df022013_ave.reset_index(inplace = True)
df032013_ave = df032013.groupby(["time"]).mean()
df032013_ave.reset_index(inplace = True)
df042013_ave = df042013.groupby(["time"]).mean()
df042013_ave.reset_index(inplace = True)
df052013_ave = df052013.groupby(["time"]).mean()
df052013_ave.reset_index(inplace = True)
df062013_ave = df062013.groupby(["time"]).mean()
df062013_ave.reset_index(inplace = True)
df072013_ave = df072013.groupby(["time"]).mean()
df072013_ave.reset_index(inplace = True)
labs = ["2013-01", "2013-02", "2013-03", "2013-04", "2013-05", "2013-06", "2013-07"]
dflist = [df012013_ave, df022013_ave, df032013_ave, df042013_ave, df052013_ave, df062013_ave, df072013_ave]
multiEventPlotter(dflist, "Average Monthly Energy Consumption", col = "mean", labels = labs)
|
4a993757fc301a687a4857a54f8b77e9814d073f
|
[
"Markdown",
"Python"
] | 6
|
Python
|
JerryGreenough/SmartMeter-Energy-Consumption-Data-in-London-Households
|
0bf45b6a1b62604739b91b5aa3b3f85a52a7415e
|
c11c7913018a884a202ea2a64ccf46a8d74b2e9f
|
refs/heads/master
|
<repo_name>ThiThu/mcv_product<file_sep>/src/com/codegym/model/Product.java
package com.codegym.model;
public class Product {
private int id;
private String title;
private String author;
private String summary;
public Product() {
}
public Product(int id, String title, String author, String summary) {
this.id = id;
this.author=author;
this.title=title;
this.summary=summary;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public void put(int id, Product product) {
}
}
<file_sep>/src/com/codegym/service/ProductServiceImpl.java
package com.codegym.service;
import com.codegym.model.Product;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ProductServiceImpl implements ProductService {
private static Map<Integer, Product> product;
static {
product = new HashMap<>();
product.put(1, new Product(1, "đắc nhân tâm", "<NAME> Carnegie", "Đắc nhân tâm là một quyển sách nhằm tự giúp bản thân bán chạy nhất từ trước đến nay."));
product.put(2, new Product(2, "Khi Lỗi Thuộc Về Những Vì Sao", "<NAME>", " Khi lỗi thuộc về những vì sao là tác phẩm thương tâm và tham vọng nhất của <NAME>, khám phá một cách khéo léo nét hài hước, li kỳ, và bi thảm của việc sống và việc yêu"));
}
@Override
public List<Product> findAll() {
return new ArrayList<>(product.values());
}
@Override
public void save(Product product) {
product.put(product.getId(), product);
}
@Override
public Product findById(int id) {
return product.get(id);
}
@Override
public void update(int id, Product product) {
product.put(id, product);
}
@Override
public void remove(int id) {
product.remove(id);
}
}
|
f67775d8458754ac0caabd89dcb18b7e813efeff
|
[
"Java"
] | 2
|
Java
|
ThiThu/mcv_product
|
e4e2ede189a5886461dfee7f074e3f995af5db46
|
a030c3ca5cc8ee8ae0bc6d8b97a77c1b895d41f2
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class KillPlayer : MonoBehaviour
{
[SerializeField]Transform spawnPoint;
private Animator animator;
public float deathTime;
bool damaged = false;
bool attacking = false;
void OnCollisionEnter2D(Collision2D col)
{
if(col.transform.CompareTag("Hero")){
animator = col.gameObject.GetComponent<Animator>();
animator.SetBool("Damaged", true);
StartCoroutine(kill(col));
}
}
public IEnumerator kill(Collision2D col){
yield return new WaitForSeconds(deathTime);
col.transform.position = spawnPoint.position;
damaged = false;
animator.SetBool("Damaged", false);
}
}
<file_sep>Knightfall is a 2D sprite-based metroidvania involving the adventure of a amnesiac bandit struggling to remember his past and rectify his previous wrongs.
I'm currently in the process of building the game using self-taught Unity knowledge and experience gained from on-campus courses and clubs.
Implentation:
Knightfall is fully created using the Unity Engine. All code is written in C# and all assets are free from the Unity Asset Store.<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyHP : MonoBehaviour
{
public Animator anim;
public int maxHealth = 100;
int currentHealth = 100;
// Start is called before the first frame update
void Start()
{
currentHealth = maxHealth;
}
public void takeDamage(int damage)
{
currentHealth -= damage;
anim.SetTrigger("Hurt");
if (currentHealth <= 0)
{
Die();
}
}
public void Die()
{
Debug.Log("Enemy died!");
anim.SetBool("IsDead", true);
this.gameObject.layer = 11;
//GetComponent<Collider2D>().enabled = false;
//GetComponent<CircleCollider2D>().enabled = false;
this.enabled = false;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour {
public CharacterController2D controller;
public Animator animator;
public float runSpeed = 40f;
float horizontalMovement = 0f;
bool jump = true;
bool crouch = false;
bool attack = false;
void Update () {
horizontalMovement = Input.GetAxisRaw("Horizontal") * runSpeed;
animator.SetFloat("Speed", Mathf.Abs(horizontalMovement));
if (Input.GetButtonDown("Jump")) {
jump = true;
animator.SetBool("IsJumping", true);
}
if (Input.GetButtonDown("Crouch")) {
crouch = true;
} else if (Input.GetButtonUp("Crouch")) {
crouch = false;
}
if (Input.GetButtonDown("Attack")) {
attack = true;
animator.SetBool("IsAttacking", true);
} else if (Input.GetButtonUp("Attack")) {
attack = false;
animator.SetBool("IsAttacking", false);
}
}
public void OnLanding () {
animator.SetBool("IsJumping", false);
}
void FixedUpdate () {
controller.Move(horizontalMovement * Time.fixedDeltaTime, crouch, jump);
jump = false;
}
}
|
9656cdf3bffb709d1911b33c19b9cd6c4ac6c594
|
[
"C#",
"Text"
] | 4
|
C#
|
PlextorKun/Knightfall
|
a6e0458b774a3b55f02cedffa1b4195e1e0d1b7d
|
02fae59a3d78c4065d6df2129ff1e4d781a6543d
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.