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/develop | <repo_name>cchervitz/universal-client<file_sep>/java/src/main/java/com/kaazing/client/universal/JMSClientSubscription.java
/**
* Kaazing Inc., Copyright (C) 2016. All rights reserved.
*/
package com.kaazing.client.universal;
import java.io.IOException;
import java.io.Serializable;
import javax.jms.BytesMessage;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
/**
* Contains information specific to JMS subscriptions
* @author romans
*
*/
public class JMSClientSubscription extends ClientSubscription {
private final MessageProducer producer;
private final MessageConsumer consumer;
private boolean opened=true;
private final Session session;
private String clientId;
public JMSClientSubscription(String clientId, String subscriptionIdentifier, Session session, MessageProducer producer, MessageConsumer consumer) {
super(subscriptionIdentifier);
this.producer=producer;
this.consumer=consumer;
this.session=session;
this.clientId=clientId;
}
@Override
public void sendMessage(Serializable message) throws ClientException {
BytesMessage bytesMessage;
try {
bytesMessage = session.createBytesMessage();
} catch (JMSException e) {
throw new ClientException("Subscription: "+this.getSubscriptionIdentifier()+" - Cannot create a BytesMessage for an object " + message.toString(), e);
}
try {
bytesMessage.writeBytes(Utils.serialize(message));
} catch (JMSException e) {
throw new ClientException("Subscription: "+this.getSubscriptionIdentifier()+" - Cannot write bytes to set the payload of a BytesMessage for an object " + message.toString(), e);
} catch (IOException e) {
throw new ClientException("Subscription: "+this.getSubscriptionIdentifier()+" - Cannot serialize an object " + message.toString(), e);
}
if (clientId!=null){
try {
bytesMessage.setStringProperty("clientId", clientId);
} catch (JMSException e) {
throw new ClientException("Subscription: "+this.getSubscriptionIdentifier()+" - Cannot set a string property client id to "+clientId+" for an object " + message.toString(), e);
}
}
try {
producer.send(bytesMessage);
JMSUniversalClient.LOGGER.debug("Sent message ["+message.toString()+"] to subscription to "+this.getSubscriptionIdentifier());
} catch (JMSException e) {
throw new ClientException("Subscription: "+this.getSubscriptionIdentifier()+" - Cannot sent and object message for an object " + message.toString(), e);
}
}
@Override
public void disconnect() throws ClientException {
if (opened){
try {
this.producer.close();
} catch (JMSException e) {
throw new ClientException("Subscription: "+this.getSubscriptionIdentifier()+" - Error closing producer.",e);
}
try {
this.consumer.close();
} catch (JMSException e) {
throw new ClientException("Subscription: "+this.getSubscriptionIdentifier()+" - Error closing consumer.",e);
}
opened=false;
}
}
}
<file_sep>/java/src/main/java/com/kaazing/client/universal/MessagesListener.java
/**
* Kaazing Inc., Copyright (C) 2016. All rights reserved.
*/
package com.kaazing.client.universal;
import java.io.Serializable;
/**
* Listener for the messages received by Universal Client
* @author romans
*
*/
public interface MessagesListener {
/**
* Called when message is received
* @param message body of the message
*/
public void onMessage(Serializable message);
}
<file_sep>/java/src/main/java/com/kaazing/client/universal/ClientException.java
/**
* Kaazing Inc., Copyright (C) 2016. All rights reserved.
*/
package com.kaazing.client.universal;
/**
* Contains the exception reported by Universal Client
* @author romans
*
*/
public class ClientException extends Exception {
/**
*
*/
private static final long serialVersionUID = 3071666188376628792L;
public ClientException(String text, Throwable t){
super(text, t);
}
public ClientException(String text){
super(text);
}
public ClientException(Throwable t){
super(t);
}
}
<file_sep>/java/src/main/java/com/kaazing/client/universal/UniversalClientProtocol.java
package com.kaazing.client.universal;
public enum UniversalClientProtocol {
amqp,
jms
}
<file_sep>/java/src/main/java/com/kaazing/client/universal/ClientSubscription.java
/**
* Kaazing Inc., Copyright (C) 2016. All rights reserved.
*/
package com.kaazing.client.universal;
import java.io.Serializable;
/**
* Contains information about subscription
* @author romans
*
*/
public abstract class ClientSubscription {
private final String subscriptionIdentifier;
/**
* Construct the subscription object. The constructor should be overwritten by the implementation classes.
* @param subscriptionIdentifier Identification of the subscription that is automatically generated when subscription is created.
*/
public ClientSubscription(String subscriptionIdentifier){
this.subscriptionIdentifier=subscriptionIdentifier;
}
/**
* Sends the message over established subscription to the publishing point
* @param message message to send
* @throws ClientException indicates that error occurred
*/
public abstract void sendMessage(Serializable message) throws ClientException;
/**
* Closes both publishing and subscription endpoints
* @throws ClientException indicates that error occurred
*/
public abstract void disconnect() throws ClientException;
public String getSubscriptionIdentifier() {
return subscriptionIdentifier;
}
}
| a3df434a769b725cae94a186ecaf0c031107a9bd | [
"Java"
] | 5 | Java | cchervitz/universal-client | 1f3840d3d899b5fc45772709ed85040b529810bb | 3da0aae7fcf71b4c730b8f574402e11314af9846 |
refs/heads/master | <file_sep>from selenium.webdriver.common.by import By
class HomePage:
def __init__(self, driver):
self.driver = driver
lnk_shop = (By.CSS_SELECTOR, "a[href*='shop']")
txt_name = (By.NAME, "name")
txt_email = (By.NAME, "email")
def click_shopItems(self):
self.driver.find_element(*HomePage.lnk_shop).click()
def enter_name(self, name):
self.driver.find_element(*HomePage.txt_name).send_keys(name)
def enter_email(self, email):
self.driver.find_element(*HomePage.txt_email).send_keys(email)<file_sep>from selenium.webdriver.common.by import By
class ShopPage:
def __init__(self, driver):
self.driver = driver
btn_checkout = (By.CSS_SELECTOR, "a[class*='btn-primary']")
def click_CheckOut(self):
self.driver.find_element(*ShopPage.btn_checkout).click()<file_sep>import pytest
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
def pytest_addoption(parser):
parser.addoption(
"--browser_name", action="store", default="chrome"
)
@pytest.fixture(scope="class")
def setup(request):
print("start run tcs")
browser = request.config.getoption("browser_name")
if browser == "chrome":
driver = webdriver.Chrome(ChromeDriverManager().install())
elif browser == "firefox":
driver = webdriver.Firefox(executable_path=GeckoDriverManager().install())
driver.maximize_window()
driver.implicitly_wait(10)
request.cls.driver = driver
yield
print("close tc")
driver.close()
driver.quit()<file_sep>import pytest
@pytest.mark.usefixtures("setup")
class BasePage:
pass
<file_sep>class AccountData:
Account_Data = [{"name":"user1", "email":"email1"}, {"name":"user2", "email":"email2"}]
<file_sep>class TestData:
BASE_URL = "https://app.hubspot.com/login"
<file_sep>[pytest]
addopts = --html=../reports/report.html<file_sep>import time
import pytest
from datatest.AccountData import AccountData
from pages.BasePage import BasePage
from pages.HomePage import HomePage
from pages.ShopPage import ShopPage
class TestFirst(BasePage):
@pytest.mark.smoke_all
def test_01(self):
self.driver.get("https://rahulshettyacademy.com/angularpractice/")
print(self.driver.title)
print(self.driver.current_url)
homePage = HomePage(self.driver)
time.sleep(3)
homePage.enter_name("khuong")
homePage.enter_email("<EMAIL>")
time.sleep(3)
homePage.click_shopItems()
@pytest.mark.regression_all
def test_02(self):
self.driver.get("https://rahulshettyacademy.com/angularpractice/")
print(self.driver.title)
print(self.driver.current_url)
homePage = HomePage(self.driver)
shopPage = ShopPage(self.driver)
time.sleep(3)
homePage.enter_name("khuong")
homePage.enter_email("<EMAIL>")
time.sleep(3)
homePage.click_shopItems()
shopPage.click_CheckOut()
time.sleep(3)
@pytest.mark.dataset
def test_03(self, getAccoutData):
self.driver.get("https://rahulshettyacademy.com/angularpractice/")
print(self.driver.title)
print(self.driver.current_url)
homePage = HomePage(self.driver)
shopPage = ShopPage(self.driver)
time.sleep(3)
homePage.enter_name(getAccoutData["name"])
homePage.enter_email(getAccoutData["email"])
time.sleep(3)
homePage.click_shopItems()
shopPage.click_CheckOut()
time.sleep(3)
@pytest.fixture(params=AccountData.Account_Data)
def getAccoutData(self, request):
return request.param | 79801d246b71354a57996efa62c3007883f99dc5 | [
"Python",
"INI"
] | 8 | Python | tnkhuong/pythonselenium | 5d4173d63833e9b6c6561becbbce5bd1d9c9e5f2 | bac4aa3193e2ca88682b11e1dbc6ae97cf8719ee |
refs/heads/master | <repo_name>majieforest/Udacity-DisasterResponsePipeline<file_sep>/models/train_classifier.py
import sys
import nltk
import numpy as np
nltk.download(['punkt', 'wordnet'])
from nltk.tokenize import word_tokenize, RegexpTokenizer
from nltk.stem import WordNetLemmatizer
import pandas as pd
from sqlalchemy import create_engine
import pickle
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestClassifier
from sklearn.multioutput import MultiOutputClassifier
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.metrics import classification_report
def load_data(database_filepath):
name = 'sqlite:///' + database_filepath
engine = create_engine(name)
df = pd.read_sql_table('Disasters', con=engine)
X = df['message'].values
#Y = df[df.columns[5:]]
Y = df.iloc[:,5:]
#print(Y.keys())
#print(df.head())
return X, Y
def tokenize(text):
tokens = word_tokenize(text)
lemmatizer = WordNetLemmatizer()
clean_tokens = []
for tok in tokens:
clean_tok = lemmatizer.lemmatize(tok).lower().strip()
clean_tokens.append(clean_tok)
return clean_tokens
def build_model(X_train,Y_train):
print("Building pipeline")
pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTransformer()),
('clf', MultiOutputClassifier(RandomForestClassifier()))
])
parameters = {'clf__estimator__min_samples_split': [2, 7]}
model_pipeline = GridSearchCV(estimator=pipeline, param_grid=parameters)
model_pipeline.fit(X_train,Y_train)
return model_pipeline
def evaluate_model(model, X_test, Y_test, category_names):
print("Model Evaluation")
y_pred = model.predict(X_test)
print(classification_report(Y_test, y_pred, target_names=Y_test.keys()))
def train_model(X,Y):
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2)
print('Building model...')
model = build_model(X_train,Y_train)
print('Fitting model')
model.fit(X_train, Y_train)
print('Evaluating model')
evaluate_model(model,X_test, Y_test,Y.keys())
return model
def export_model(model,model_filepath):
pickle.dump(model, open(model_filepath, 'wb'))
def main():
if len(sys.argv) == 3:
database_filepath, model_filepath = sys.argv[1:]
print('Loading data...\n DATABASE: {}'.format(database_filepath))
X, Y = load_data(database_filepath)
model = train_model(X, Y)
print('Saving model...\n MODEL: {}'.format(model_filepath))
export_model(model, model_filepath)
print('Trained model saved!')
else:
print('Please provide the filepath of the disaster messages database '\
'as the first argument and the filepath of the pickle file to '\
'save the model to as the second argument. \n\nExample: python '\
'train_classifier.py ../data/DisasterResponse.db classifier.pkl')
if __name__ == '__main__':
main()<file_sep>/README.md
# Disaster Response Pipeline Project
### Project Components:
#### 1. process_data.py: Data cleaning pipeline
This script does the following :
Loads the messages and categories datasets
Merges the two datasets
Cleans the data
Stores it in a SQLite database
#### 2.train_classifier.py: Machine learning pipeline
This script does the following :
Loads data from the SQLite database
Splits the dataset into training and test sets
Builds a text processing and machine learning pipeline
Trains and tunes a model using GridSearchCV
Outputs results on the test set
Exports the final model as a pickle file
#### 3. run.py: Flask app
This script is contains the app and the user interface used to predict results and display them.
#### 4. templates: folder containing the html templates
### Instructions:
#### Run the following commands in the project's root directory to set up your database and model.
To run ETL pipeline that cleans data and stores in database
python data/process_data.py data/disaster_messages.csv data/disaster_categories.csv data/DisasterResponse.db
To run ML pipeline that trains classifier and saves
python models/train_classifier.py data/DisasterResponse.db models/classifier.pkl
Run the following command in the app's directory to run your web app. python run.py
Go to http://0.0.0.0:3001/
| a2ae7acfac4f2099091757b6f254e28d664ee617 | [
"Markdown",
"Python"
] | 2 | Python | majieforest/Udacity-DisasterResponsePipeline | df3c5d994c9b7fe0f180a6384c402a25e639ed89 | 0d612d69701724943d30147da35d09dda543627b |
refs/heads/master | <repo_name>Alyanorno/3D-project<file_sep>/stuff.h
#pragma once
#include <vector>
#include <fstream>
#include <string>
#include <iostream>
#include <sstream>
#include <random>
#include <functional>
#define GLFW_DLL
#include "GL\include\glew.h"
#include "GL\include\glfw.h"
#include "glm\glm.hpp"
#include "glm\gtc\matrix_transform.hpp"
#include "glm\gtc\matrix_inverse.hpp"
void Initialize( int argc, char** argv );
void Update();
class exit_success : std::exception {};
struct Texture
{
Texture() {}
Texture( std::string _name )
{ LoadBmp( _name, false ); }
void Set( int _size, int _width, int _height )
{
width = _width;
height = _height;
t.resize( _size );
}
unsigned char& operator[]( int n ) { return t[n]; }
std::vector<unsigned char> t;
int width, height;
GLuint gl;
void LoadBmp( std::string name, bool toGraphicCard = true );
};
struct Model
{
void Set( int _number )
{
number = _number;
vertexs.resize( number * 3 );
normals.resize( number * 3 );
textureCoordinates.resize( number * 2 );
}
void LoadObj( std::string name );
int number;
std::vector<float> vertexs, normals, textureCoordinates;
glm::vec3 position;
GLuint shader;
GLuint Vao;
GLuint Vbo[3]; // Vertexs, Normals and Texture Coordinates
};
struct HeightMap
{
void Load( Texture& t, Texture& blending );
std::vector<float>& operator[]( int i ) { return heights[i]; }
int size() { return heights.size(); }
std::vector< std::vector<float> > heights;
float square_size;
// graphic part
std::vector<float> vertexs, normals, textureCoordinates, textureBlending;
std::vector<GLuint> indices;
GLuint shader;
GLuint Vbo[5]; // Vertexs, Normals, Texture Coordinates, Texture Blending and Indices
GLuint Vao;
int width() { return heights[0].size(); }
int height() { return heights.size(); }
};
template < int max_size, class Policy >
struct ParticleSystem : public Policy
{
ParticleSystem() : Policy(), size(0) {}
void Load()
{
glGenBuffers( 1, &Vbo );
glBindBuffer( GL_ARRAY_BUFFER, Vbo );
glBufferData( GL_ARRAY_BUFFER, max_size * 3 * sizeof(float), &positions[0], GL_DYNAMIC_DRAW );
glGenVertexArrays( 1, &Vao );
glBindVertexArray( Vao );
glEnableVertexAttribArray( 0 );
glBindBuffer( GL_ARRAY_BUFFER, Vbo );
glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, 0 );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glBindVertexArray( 0 );
glDisableVertexAttribArray( 0 );
}
void Emit( int amount, glm::vec3 direction = glm::vec3( 0, 0, 0 ) )
{
if( size + amount > max_size )
amount = max_size - size;
for( int i(0); i < amount; i++ )
positions[ i + size ] = Policy::AddParticle( i + size, direction );
size += amount;
}
void Update()
{
for( int i(0); i < size; i++ )
if( Policy::Remove( i, positions[i] ) )
{
positions[i] = positions[--size];
Policy::Move( i, size );
}
Policy::Update( positions, size );
// TODO: Find better way to do this
glBindBuffer( GL_ARRAY_BUFFER, Vbo );
glBufferData( GL_ARRAY_BUFFER, max_size * 3 * sizeof(float), &positions[0], GL_DYNAMIC_DRAW );
// auto data = glMapBuffer( GL_ARRAY_BUFFER, GL_WRITE_ONLY );
// glUnmapBuffer( GL_ARRAY_BUFFER );
}
GLuint shader, Vao, Vbo;
float particle_size;
glm::vec3 positions[max_size];
int size;
};
struct Snow
{
Snow() : range( -100, 100 )
{
std::random_device t;
number_generator.seed( t() );
}
glm::vec3 AddParticle( int _i, glm::vec3 _direction )
{
return position + glm::vec3( range( number_generator ), 0, range( number_generator ) );
}
bool Remove( int _i, glm::vec3 _position )
{
if( _position.y < -100 )
return true;
else
return false;
}
void Move( int _to, int _from )
{}
void Update( glm::vec3 _positions[], int _size )
{
for( int i(0); i < _size; i++ )
_positions[i] += glm::vec3( 0.f, -0.1f, 0.f );
}
std::mt19937 number_generator;
std::uniform_real_distribution<float> range;
glm::vec3 position;
};
static const int fire_max_size = 1000;
struct Fire
{
Fire() : range( -5, 5 )
{
std::random_device t;
number_generator.seed( t() );
}
glm::vec3 AddParticle( int _i, glm::vec3 _direction )
{
directions[_i] = glm::normalize( glm::vec3( range( number_generator ), range( number_generator ), range( number_generator ) ) ) / 10.f;
return position + glm::vec3( range( number_generator ), range( number_generator ), range( number_generator ) );
}
float L( float x ) { return x > 0 ? x: -x; }
float L( glm::vec3 x ) { return glm::dot( x, x ); }
bool Remove( int _i, glm::vec3 _position )
{
int max = 75;
if( L( _position.x - position.x ) < -max || L( _position.x - position.x ) > max )
return true;
else if( L( _position.y - position.y ) < -max || L( _position.y - position.y ) > max )
return true;
else if( L( _position.z - position.z ) < -max || L( _position.z - position.z ) > max )
return true;
else
return false;
}
void Move( int _to, int _from )
{
directions[_to] = directions[_from];
}
void Update( glm::vec3 _positions[], int _size )
{
for( int i(0); i < _size; i++ )
{
// Alignment
glm::vec3 alignment( 0.f, 0.f, 0.f );
float alignment_count(0);
// Cohesion
glm::vec3 cohesion( 0.f, 0.f, 0.f );
float cohesion_count(0);
// Separation
glm::vec3 separation( 0.f, 0.f, 0.f );
float separation_count(0);
int l = i - 50;
l = l < 0 ? 0: l;
int stop = i + 50;
stop = stop > _size ? _size: stop;
for(; l < stop; l++ )
{
if( i == l )
continue;
float distance = glm::distance( _positions[i], _positions[l] );
// Alignment
if( distance < 10.f )
{
alignment += directions[l];
alignment_count++;
}
// Cohesion
if( distance < 100.f )
{
cohesion += _positions[l];
cohesion_count++;
}
// Separation
if( distance < 2.f )
{
separation += _positions[l] - _positions[i];
separation_count++;
}
}
// Alignment
if( alignment_count )
directions[i] += glm::normalize( alignment / alignment_count ) * 0.005f;
// Cohesion
if( cohesion_count )
{
glm::vec3 t = cohesion / cohesion_count;
t = t - _positions[i];
if( L( t ) > 0.001f )
{
t = glm::normalize( t );
directions[i] += t * 0.0005f;
}
}
// Separation
if( separation_count )
{
glm::vec3 t = separation * -1.f / separation_count;
if( L( t ) > 0.001f )
{
t = glm::normalize( t );
directions[i] += t * 0.05f;
}
}
//directions[i] += glm::vec3( 0.f, -0.0001f, 0.f );
directions[i] = glm::normalize( directions[i] ) * 0.1f;
_positions[i] += directions[i];
}
}
glm::vec3 directions[fire_max_size];
std::mt19937 number_generator;
std::uniform_real_distribution<float> range;
glm::vec3 position;
int size;
};
enum ShaderType { Vertex, Fragment, Geometry };
GLuint LoadShader( std::string name, ShaderType type );
<file_sep>/stuff.cpp
#include "stuff.h"
std::vector< Texture > textures;
Model model;
HeightMap height_map;
ParticleSystem< 10000, Snow > snow;
ParticleSystem< fire_max_size, Fire > fire;
struct
{
GLuint texture;
GLuint shader;
int width, height;
GLuint framebuffer;
} shadow;
struct
{
GLuint texture;
GLuint shader;
GLuint Vao, Vbo[2];
int size;
} skyBox;
GLuint restart_number = 100000;
glm::vec3 translation( 0.f, 0.f, 0.f ), rotation( 0.f, 0.f, 0.f );
GLuint CreateShader( std::string vertex, std::string fragment, std::string geometry = "" )
{
GLuint vertexShader = LoadShader( vertex, Vertex );
GLuint fragmentShader = LoadShader( fragment, Fragment );
GLuint geometryShader;
if( geometry.size() > 0 )
geometryShader = LoadShader( geometry, Geometry );
GLuint result = glCreateProgram();
glAttachShader( result, vertexShader );
glAttachShader( result, fragmentShader );
if( geometry.size() > 0 )
glAttachShader( result, geometryShader );
glLinkProgram( result );
GLint e;
glGetProgramiv( result, GL_LINK_STATUS, &e );
if( e == GL_FALSE ) {
int l, t;
glGetProgramiv( result, GL_INFO_LOG_LENGTH, &l );
char* error = new char[l];
glGetProgramInfoLog( result, l, &t, error );
std::string err( error );
delete error;
throw err;
}
return result;
}
void Initialize( int argc, char** argv )
{
if( !glfwInit() )
throw std::string( "Failed to initialize glfw" );
glfwOpenWindowHint( GLFW_OPENGL_VERSION_MAJOR, 3 );
glfwOpenWindowHint( GLFW_OPENGL_VERSION_MINOR, 3 );
glfwOpenWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
glfwOpenWindow( 1600, 900, 0, 0, 0, 0, 0, 0, GLFW_WINDOW );
glewExperimental = GL_TRUE;
glewInit();
glfwSetWindowTitle( "Hej!" );
glEnable( GL_DEPTH_TEST );
glEnable( GL_CULL_FACE );
glEnable( GL_BLEND );
glEnable( GL_TEXTURE_CUBE_MAP );
glEnable( GL_TEXTURE_CUBE_MAP_SEAMLESS );
glEnable( GL_PRIMITIVE_RESTART );
glPrimitiveRestartIndex( restart_number );
glCullFace( GL_BACK );
glFrontFace( GL_CCW );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glDepthFunc( GL_LESS );
glClearColor( 0.5f, 0.5f, 0.5f, 1.f );
shadow.width = 1024;
shadow.height = 1024;
glGenTextures( 1, &shadow.texture );
glActiveTexture( GL_TEXTURE0 );
glBindTexture( GL_TEXTURE_2D, shadow.texture );
glTexImage2D( GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, shadow.width, shadow.height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, 0);
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
// glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
// glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
// glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
// glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER );
GLfloat border_colour[] = { 1.f, 0.f, 0.f, 0.f };
glTexParameterfv( GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border_colour );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS );
glGenFramebuffers( 1, &shadow.framebuffer );
glBindFramebuffer( GL_FRAMEBUFFER, shadow.framebuffer );
glDrawBuffer( GL_NONE ); // No color
// glFramebufferTexture( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, shadow.texture, 0 );
glFramebufferTexture2D( GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, shadow.texture, 0 );
if( glCheckFramebufferStatus( GL_FRAMEBUFFER ) != GL_FRAMEBUFFER_COMPLETE )
throw std::string( "Failed to initialize shadow map" );
glBindFramebuffer( GL_FRAMEBUFFER, 0 );
shadow.shader = CreateShader( "shadow.vertex", "shadow.fragment" );
model.position = glm::vec3( 50.f, 75.f, 0.f );
model.LoadObj( "bth.obj" );
model.shader = CreateShader( "model.vertex", "model.fragment" );
height_map.shader = CreateShader( "height_map.vertex", "height_map.fragment" );
height_map.square_size = 10.f;
height_map.Load( Texture( "heightMap.bmp" ), Texture( "blendMap.bmp" ) );
snow.shader = CreateShader( "particles.vertex", "particles.fragment", "particles.geometry" );
snow.position = glm::vec3( 0.f, 100.f, 0.f );
snow.particle_size = 1.f;
snow.Load();
fire.shader = snow.shader;
fire.position = glm::vec3( 50.f, 75.f, -50.f );
fire.Load();
textures.push_back( Texture() );
textures[0].LoadBmp( "bthBmp.bmp" );
textures.push_back( Texture() );
textures[1].LoadBmp( "texture2.bmp" );
textures.push_back( Texture() );
textures[2].LoadBmp( "snow.bmp" );
textures.push_back( Texture() );
textures[3].LoadBmp( "fire.bmp" );
textures.push_back( Texture() );
textures[4].LoadBmp( "t1.bmp" );
textures.push_back( Texture() );
textures[5].LoadBmp( "t2.bmp" );
textures.push_back( Texture() );
textures[6].LoadBmp( "t3.bmp" );
textures.push_back( Texture() );
textures[7].LoadBmp( "t4.bmp" );
textures.push_back( Texture() );
textures[8].LoadBmp( "t5.bmp" );
textures.push_back( Texture() );
textures[9].LoadBmp( "t6.bmp" );
// Load sky box
skyBox.shader = CreateShader( "skyBox.vertex", "skyBox.fragment" );
std::string names[] = { "skyBoxLeft.bmp", "skyBoxRight.bmp", "skyBoxTop.bmp", "skyBoxBottom.bmp", "skyBoxFront.bmp", "skyBoxBack.bmp" };
int i = 6;
glGenTextures( 1, &skyBox.texture );
glBindTexture( GL_TEXTURE_CUBE_MAP, skyBox.texture );
#define TABLE \
FOO( GL_TEXTURE_CUBE_MAP_NEGATIVE_Z ); \
FOO( GL_TEXTURE_CUBE_MAP_POSITIVE_Z ); \
FOO( GL_TEXTURE_CUBE_MAP_NEGATIVE_Y ); \
FOO( GL_TEXTURE_CUBE_MAP_POSITIVE_Y ); \
FOO( GL_TEXTURE_CUBE_MAP_NEGATIVE_X ); \
FOO( GL_TEXTURE_CUBE_MAP_POSITIVE_X ); \
#define FOO( TYPE ) \
textures.push_back( Texture( names[--i] ) ); \
glTexImage2D( TYPE, 0, GL_RGB8, textures.back().width, textures.back().height, 0, GL_BGR, GL_UNSIGNED_BYTE, &textures.back().t[0] );
TABLE
#undef FOO
#undef TABLE
glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
float vertexs[] =
{
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, -1.0,
};
GLuint indices[] =
{
0, 1, 2, 2, 3, 0,
3, 2, 6, 6, 7, 3,
7, 6, 5, 5, 4, 7,
4, 0, 3, 3, 7, 4,
0, 1, 5, 5, 4, 0,
1, 5, 6, 6, 2, 1,
};
skyBox.size = sizeof(indices) / sizeof(GLuint);
glGenBuffers( 2, skyBox.Vbo );
glBindBuffer( GL_ARRAY_BUFFER, skyBox.Vbo[0] );
glBufferData( GL_ARRAY_BUFFER, sizeof(vertexs), &vertexs[0], GL_STATIC_DRAW );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, skyBox.Vbo[1] );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), &indices[0], GL_STATIC_DRAW );
glGenVertexArrays( 1, &skyBox.Vao );
glBindVertexArray( skyBox.Vao );
glEnableVertexAttribArray( 0 );
glBindBuffer( GL_ARRAY_BUFFER, skyBox.Vbo[0] );
glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, 0 );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
glBindVertexArray( 0 );
glDisableVertexAttribArray( 0 );
}
void Update()
{
snow.Emit( 1 );
snow.Update();
fire.Emit( 1 );
fire.Update();
// Input stuff
if( glfwGetKey( GLFW_KEY_ESC ) )
throw exit_success();
int m_x, m_y;
glfwGetMousePos( &m_x, &m_y );
int width, height;
glfwGetWindowSize( &width, &height );
// Rotate camera depending on mouse pos
if( !glfwGetKey( GLFW_KEY_LCTRL ) )
{
if( m_x > width / 2 || m_x < width / 2 )
{
rotation.y += (m_x - width / 2) * 0.1f;
}
if( m_y > height / 2 || m_y < height / 2 )
{
rotation.x += (m_y - height / 2) * 0.1f;
}
glfwSetMousePos( width / 2, height / 2 );
}
glm::mat4 rotationMatrix( glm::mat4( 1.f ) );
rotationMatrix = glm::rotate( rotationMatrix, rotation.x, glm::vec3( 1.f, 0.f, 0.f ) );
rotationMatrix = glm::rotate( rotationMatrix, rotation.y, glm::vec3( 0.f, 1.f, 0.f ) );
rotationMatrix = glm::rotate( rotationMatrix, rotation.z, glm::vec3( 0.f, 0.f, 1.f ) );
float speed = 0.5f;
if( glfwGetKey('W') && glfwGetKey('S') )
{}
else if( glfwGetKey('W') )
{
glm::vec4 t( 0.f, 0.f, 1.f, 1.f );
t = t * rotationMatrix * speed;
translation.x += t.x;
translation.y += t.y;
translation.z += t.z;
}
else if( glfwGetKey('S') )
{
glm::vec4 t( 0.f, 0.f, 1.f, 1.f );
t = t * rotationMatrix * speed;
translation.x -= t.x;
translation.y -= t.y;
translation.z -= t.z;
}
if( glfwGetKey('A') && glfwGetKey('D') )
{}
else if( glfwGetKey('A') )
{
glm::vec4 t( 1.f, 0.f, 0.f, 1.f );
t = t * rotationMatrix * speed;
translation.x += t.x;
translation.y += t.y;
translation.z += t.z;
}
else if( glfwGetKey('D') )
{
glm::vec4 t( 1.f, 0.f, 0.f, 1.f );
t = t * rotationMatrix * speed;
translation.x -= t.x;
translation.y -= t.y;
translation.z -= t.z;
}
static bool lock_space = false;
if( glfwGetKey( GLFW_KEY_SPACE ) )
{
if( !lock_space )
translation.y -= 10.f;
lock_space = true;
}
else
lock_space = false;
// Calculate y coordinate depending on height map
int map_x, map_z;
float square_size = height_map.square_size;
map_x = (height_map.height() * square_size * 0.5 - translation.x) / square_size;
map_z = (height_map.width() * square_size * 0.5 + translation.z) / square_size;
if( map_x > 0 && map_x < height_map.height() - 1 )
if( map_z > 0 && map_z < height_map.width() - 1 )
{
std::vector<float>& v( height_map.vertexs );
int pos = map_z * height_map.width() + map_x;
pos *= 3;
glm::vec3 v0 = glm::vec3( v[pos+0], v[pos+1], v[pos+2] );
glm::vec3 v1 = glm::vec3( v[pos+3], v[pos+4], v[pos+5] );
pos += height_map[0].size() * 3;
glm::vec3 v2 = glm::vec3( v[pos+0], v[pos+1], v[pos+2] );
glm::vec3 n = glm::cross( v2 - v0, v1 - v0 );
n = glm::normalize( n );
float tx = n.x * ( -translation.x - v0.x );
float tz = n.z * ( -translation.z - v0.z );
// float y = ( n.x * ( translation.x - v0.x ) + n.z * ( translation.z - v0.z ) ) / - n.y + v0.y;
float y = ( tx + tz ) / -n.y + v0.y;
// float d = - glm::dot( translation - v0, normal ) / glm::dot( glm::vec3( 0, 1, 0 ), normal );
// float p = translation.y + d * 1;
if( translation.y > -y - 5.f - 5.f )
translation.y = - y - 5.f;
}
glm::mat4 viewMatrix( glm::mat4( 1.f ) );
viewMatrix = rotationMatrix * glm::translate( viewMatrix, translation );
static float angle = 45; // degres
angle += 0.1f;
if( angle > 360 )
angle = 0;
glm::mat4 modelMatrix( glm::mat4( 1.0f ) );
modelMatrix = glm::translate( modelMatrix, model.position );
modelMatrix = glm::rotate( modelMatrix, angle, glm::vec3( 0.f, 1.f, 0.f ) );
// Draw to Shadow Map
glBindFramebuffer( GL_FRAMEBUFFER, shadow.framebuffer );
glClear( GL_DEPTH_BUFFER_BIT );
glm::vec3 eye( 0.01f, 0.01f, 200.01f ), centre( 0.f, 0.f, 0.f ), up( 0.f, 0.f, 1.f );
//glm::mat4 shadowProjectionViewMatrix = glm::perspective( 45.f, (float)shadow.width / (float)shadow.height, 1.f, 1000.f ) * glm::lookAt( glm::vec3( glm::vec4( eye, 1.f ) * glm::inverse( viewMatrix ) ), centre, up );
// Move from [-1,1] -> [0,1]
// shadowProjectionViewMatrix = shadowProjectionViewMatrix * glm::mat4( 0.5f, 0.f, 0.f, 0.f, 0.f, 0.5f, 0.f, 0.f, 0.f, 0.f, 0.5f, 0.f, 0.5f, 0.5f, 0.5f, 1.0f );
// Move to camera space
//shadowProjectionViewMatrix = glm::inverse( shadowProjectionViewMatrix ) * projectionMatrix * viewMatrix;
glm::mat4 shadowProjectionViewMatrix = glm::mat4( 0.5f, 0.f, 0.f, 0.f, 0.f, 0.5f, 0.f, 0.f, 0.f, 0.f, 0.5f, 0.f, 0.5f, 0.5f, 0.5f, 1.0f ) * glm::perspective( 45.f, (float)shadow.width / (float)shadow.height, 1.f, 500.f ) * glm::lookAt( eye, centre, up );
glViewport( 0, 0, shadow.width, shadow.height );
glEnableVertexAttribArray( 0 );
glCullFace( GL_FRONT );
glUseProgram( shadow.shader );
glUniformMatrix4fv( glGetUniformLocation( shadow.shader, "projectionViewMatrix" ), 1, GL_FALSE, &shadowProjectionViewMatrix[0][0] );
glBindVertexArray( height_map.Vao );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, height_map.Vbo[4] );
glDrawElements( GL_TRIANGLE_STRIP, height_map.indices.size(), GL_UNSIGNED_INT, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
glBindVertexArray( 0 );
glm::mat4 temp = shadowProjectionViewMatrix * modelMatrix;
glUniformMatrix4fv( glGetUniformLocation( shadow.shader, "projectionViewMatrix" ), 1, GL_FALSE, &temp[0][0] );
glBindVertexArray( model.Vao );
glDrawArrays( GL_TRIANGLES, 0, model.vertexs.size() );
glBindVertexArray( 0 );
glUseProgram( 0 );
glCullFace( GL_BACK );
glDisableVertexAttribArray( 0 );
glFlush();
glFinish();
glBindFramebuffer( GL_FRAMEBUFFER, 0 );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
glViewport( 0, 0, width, height );
float nearClip = 1.0f, farClip = 1000.f, fovDeg = 45.f, aspect = (float)width / (float)height;
glm::mat4 modelViewMatrix;
glm::mat3 normalInverseTranspose;
glm::mat4 projectionMatrix = glm::perspective(fovDeg, aspect, nearClip, farClip);
glm::vec4 lightPosition = glm::vec4( 0.f, 200.f, 0.f, 1.f );
//Draw Model
glEnableVertexAttribArray( 0 );
glEnableVertexAttribArray( 1 );
glEnableVertexAttribArray( 2 );
normalInverseTranspose = glm::inverseTranspose( (glm::mat3)viewMatrix * (glm::mat3)modelMatrix );
glUseProgram( model.shader );
glUniformMatrix4fv( glGetUniformLocation( model.shader, "modelMatrix" ), 1, GL_FALSE, &modelMatrix[0][0] );
glUniformMatrix4fv( glGetUniformLocation( model.shader, "viewMatrix" ), 1, GL_FALSE, &viewMatrix[0][0] );
glUniformMatrix3fv( glGetUniformLocation( model.shader, "normalInverseTranspose"), 1, GL_FALSE, &normalInverseTranspose[0][0] );
glUniformMatrix4fv( glGetUniformLocation( model.shader, "projectionMatrix"), 1, GL_FALSE, &projectionMatrix[0][0] );
glUniformMatrix4fv( glGetUniformLocation( model.shader, "shadowProjectionViewMatrix"), 1, GL_FALSE, &shadowProjectionViewMatrix[0][0] );
glUniform1fv( glGetUniformLocation( model.shader, "lightPosition"), 3, &lightPosition[0] );
glUniform1i( glGetUniformLocation( model.shader, "textureSampler" ), 0 );
glUniform1i( glGetUniformLocation( model.shader, "shadowMap" ), 1 );
glActiveTexture( GL_TEXTURE0 + 0 );
glBindTexture( GL_TEXTURE_2D, textures[0].gl );
glActiveTexture( GL_TEXTURE0 + 1 );
glBindTexture( GL_TEXTURE_2D, shadow.texture );
glBindVertexArray( model.Vao );
glDrawArrays( GL_TRIANGLES, 0, model.vertexs.size() );
glBindVertexArray( 0 );
glBindTexture( GL_TEXTURE_2D, 0 );
glUseProgram(0);
glDisableVertexAttribArray( 2 );
glDisableVertexAttribArray( 1 );
glDisableVertexAttribArray( 0 );
// Draw Height Map
glEnableVertexAttribArray( 0 );
glEnableVertexAttribArray( 1 );
glEnableVertexAttribArray( 2 );
glEnableVertexAttribArray( 3 );
normalInverseTranspose = glm::inverseTranspose( (glm::mat3)viewMatrix );
glUseProgram( height_map.shader );
glUniformMatrix4fv( glGetUniformLocation( height_map.shader, "viewMatrix" ), 1, GL_FALSE, &viewMatrix[0][0] );
glUniformMatrix3fv( glGetUniformLocation( height_map.shader, "normalInverseTranspose"), 1, GL_FALSE, &normalInverseTranspose[0][0] );
glUniformMatrix4fv( glGetUniformLocation( height_map.shader, "projectionMatrix"), 1, GL_FALSE, &projectionMatrix[0][0] );
glUniformMatrix4fv( glGetUniformLocation( height_map.shader, "shadowProjectionViewMatrix"), 1, GL_FALSE, &shadowProjectionViewMatrix[0][0] );
glUniform1fv( glGetUniformLocation( height_map.shader, "lightPosition"), 3, &lightPosition[0] );
glUniform1i( glGetUniformLocation( height_map.shader, "textureSampler" ), 0 );
glUniform1i( glGetUniformLocation( height_map.shader, "textureSampler2" ), 1 );
glUniform1i( glGetUniformLocation( height_map.shader, "shadowMap" ), 2 );
glActiveTexture( GL_TEXTURE0 + 0 );
// 4-9
static int frame = 0;
const static int frame_speed = 30;
frame++;
if( frame/frame_speed > 10 )
frame = 0;
int t;
if( frame/frame_speed > 5 )
t = 9 - frame/frame_speed + 5;
else
t = 4 + frame/frame_speed;
glBindTexture( GL_TEXTURE_2D, textures[ t ].gl );
glActiveTexture( GL_TEXTURE0 + 1 );
glBindTexture( GL_TEXTURE_2D, textures[1].gl );
glActiveTexture( GL_TEXTURE0 + 2 );
glBindTexture( GL_TEXTURE_2D, shadow.texture );
glBindVertexArray( height_map.Vao );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, height_map.Vbo[4] );
glDrawElements( GL_TRIANGLE_STRIP, height_map.indices.size(), GL_UNSIGNED_INT, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
glBindVertexArray( 0 );
glBindTexture( GL_TEXTURE_2D, 0 );
glUseProgram(0);
glDisableVertexAttribArray( 3 );
glDisableVertexAttribArray( 2 );
glDisableVertexAttribArray( 1 );
glDisableVertexAttribArray( 0 );
// Draw particle system Snow
glEnableVertexAttribArray( 0 );
glUseProgram( snow.shader );
glUniformMatrix4fv( glGetUniformLocation( snow.shader, "viewMatrix" ), 1, GL_FALSE, &viewMatrix[0][0] );
glUniformMatrix4fv( glGetUniformLocation( snow.shader, "projectionMatrix"), 1, GL_FALSE, &projectionMatrix[0][0] );
glUniform1fv( glGetUniformLocation( snow.shader, "size"), 1, &snow.particle_size );
glUniform1i( glGetUniformLocation( snow.shader, "textureSampler" ), 0 );
glActiveTexture( GL_TEXTURE0 );
glBindTexture( GL_TEXTURE_2D, textures[2].gl );
glBindVertexArray( snow.Vao );
glDrawArrays( GL_POINTS, 0, snow.size );
glBindVertexArray( 0 );
glBindTexture( GL_TEXTURE_2D, 0 );
glUseProgram(0);
glDisableVertexAttribArray( 0 );
// Draw particle system Fire
glEnableVertexAttribArray( 0 );
glUseProgram( fire.shader );
glUniformMatrix4fv( glGetUniformLocation( fire.shader, "viewMatrix" ), 1, GL_FALSE, &viewMatrix[0][0] );
glUniformMatrix4fv( glGetUniformLocation( fire.shader, "projectionMatrix"), 1, GL_FALSE, &projectionMatrix[0][0] );
glUniform1fv( glGetUniformLocation( fire.shader, "size"), 1, &snow.particle_size );
glUniform1i( glGetUniformLocation( fire.shader, "textureSampler" ), 0 );
glActiveTexture( GL_TEXTURE0 );
glBindTexture( GL_TEXTURE_2D, textures[3].gl );
glBindVertexArray( fire.Vao );
glDrawArrays( GL_POINTS, 0, fire.size );
glBindVertexArray( 0 );
glBindTexture( GL_TEXTURE_2D, 0 );
glUseProgram(0);
glDisableVertexAttribArray( 0 );
// Draw sky box
glEnableVertexAttribArray( 0 );
glCullFace( GL_FRONT );
glDepthFunc( GL_LEQUAL );
modelViewMatrix = viewMatrix;
glm::mat4 projectionViewMatrix( glm::mat4( 1.0f ) );
projectionViewMatrix = projectionMatrix * rotationMatrix;
glUseProgram( skyBox.shader );
glUniformMatrix4fv( glGetUniformLocation( skyBox.shader, "projectionViewMatrix"), 1, GL_FALSE, &projectionViewMatrix[0][0] );
glUniform1i( glGetUniformLocation( skyBox.shader, "textureSampler" ), 0 );
glActiveTexture( GL_TEXTURE0 );
glBindTexture( GL_TEXTURE_CUBE_MAP, skyBox.texture );
glBindVertexArray( skyBox.Vao );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, skyBox.Vbo[1] );
glDrawElements( GL_TRIANGLES, skyBox.size, GL_UNSIGNED_INT, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
glBindVertexArray( 0 );
glBindTexture( GL_TEXTURE_2D, 0 );
glUseProgram(0);
glDepthFunc( GL_LESS );
glCullFace( GL_BACK );
glDisableVertexAttribArray( 0 );
glfwSwapBuffers();
}
void Texture::LoadBmp( std::string name, bool toGraphicCard )
{
std::fstream in;
in.open( name.c_str(), std::ios::in | std::ios::binary );
if( !in.is_open() )
throw std::string( "Failed to open file: " + name );
unsigned int offset, width, height, size;
unsigned short bits_per_pixel;
in.seekg( sizeof( short ) * 3 + sizeof( int ) );
in.read( (char*)&offset, sizeof( offset) );
in.seekg( in.tellp() + (std::fstream::pos_type)sizeof( int ) );
in.read( (char*)&width, sizeof( width ) );
in.read( (char*)&height, sizeof( height ) );
in.seekg( in.tellp() + (std::fstream::pos_type)sizeof( short ) );
in.read( (char*)&bits_per_pixel, sizeof( bits_per_pixel ) );
assert( bits_per_pixel == 24 ); // only supports 24 bits
size = bits_per_pixel * width * height;
Set( size, width, height );
in.seekg( offset );
in.read( (char*)&(t[0]), size );
in.close();
if( toGraphicCard )
{
glGenTextures( 1, &gl );
glBindTexture( GL_TEXTURE_2D, gl );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB8, width, height, 0, GL_BGR, GL_UNSIGNED_BYTE, &t[0] );
}
}
template< class T > T To( std::string in )
{
std::istringstream ss( in );
T t;
ss >> t;
return t;
}
void Tokenize( std::string line, std::vector< std::string >& result, char delim = ' ' )
{
std::stringstream ss( line );
while( getline( ss, line, delim ) )
result.push_back( line );
}
void Model::LoadObj( std::string name )
{
std::fstream in;
in.open( name.c_str(), std::ios::in );
if( !in.is_open() )
throw std::string( "Failed to open file: " + name );
std::vector<float> t_vertexs, t_normals, t_textureCoordinates;
std::vector<unsigned int> faces;
while( !in.eof() )
{
std::string line;
getline( in, line );
if( !line.size() )
continue;
if( line[0] == 'v' ) {
std::vector< std::string > t;
Tokenize( line, t );
if( line[1] == 't' )
// Texture Coordinate
for( int i(1); i < t.size(); i++ )
t_textureCoordinates.push_back( To< float >( t[i] ) );
else if( line[1] == 'n' )
// Normal
for( int i(1); i < t.size(); i++ )
t_normals.push_back( To< float >( t[i] ) );
else
// Vertex
for( int i(1); i < t.size(); i++ )
t_vertexs.push_back( To< float >( t[i] ) );
} else if( line[0] == 'f' ) {
// Face
std::vector< std::string > t;
Tokenize( line, t );
for( int i(1); i < t.size(); i++ ) {
std::vector< std::string > y;
Tokenize( t[i], y, '/' );
assert( y.size() == 3 ); //only supports triangles
for( int j(0); j < y.size(); j++ )
faces.push_back( To< unsigned int >( y[j] ) );
}
}
}
in.close();
Set( faces.size() / 3 );
for( int i(0); i < faces.size() / 3; i++ )
{
for( int j(0); j < 3; j++ )
{
vertexs[ i * 3 + j ] = t_vertexs[ ( faces[ i * 3 + 0 ] - 1 ) * 3 + j ];
normals[ i * 3 + j ] = t_normals[ ( faces[ i * 3 + 2 ] - 1 ) * 3 + j ];
}
for( int j(0); j < 2; j++ )
textureCoordinates[ i * 2 + j ] = t_textureCoordinates[ ( faces[ i * 3 + 1 ] - 1 ) * 2 + j ];
}
glGenBuffers( 3, Vbo );
glBindBuffer( GL_ARRAY_BUFFER, Vbo[0] );
glBufferData( GL_ARRAY_BUFFER, vertexs.size() * sizeof(float), &vertexs[0], GL_STATIC_DRAW );
glBindBuffer( GL_ARRAY_BUFFER, Vbo[1] );
glBufferData( GL_ARRAY_BUFFER, normals.size() * sizeof(float), &normals[0], GL_STATIC_DRAW );
glBindBuffer( GL_ARRAY_BUFFER, Vbo[2] );
glBufferData( GL_ARRAY_BUFFER, textureCoordinates.size() * sizeof(float), &textureCoordinates[0], GL_STATIC_DRAW );
glGenVertexArrays( 1, &Vao );
glBindVertexArray( Vao );
// Vertex, normal, texture
glEnableVertexAttribArray( 0 );
glEnableVertexAttribArray( 1 );
glEnableVertexAttribArray( 2 );
glBindBuffer( GL_ARRAY_BUFFER, Vbo[0] );
glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, 0 );
glBindBuffer( GL_ARRAY_BUFFER, Vbo[1] );
glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 0, 0 );
glBindBuffer( GL_ARRAY_BUFFER, Vbo[2] );
glVertexAttribPointer( 2, 2, GL_FLOAT, GL_FALSE, 0, 0 );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glBindVertexArray( 0 );
glDisableVertexAttribArray( 2 );
glDisableVertexAttribArray( 1 );
glDisableVertexAttribArray( 0 );
}
void HeightMap::Load( Texture& t, Texture& blending )
{
if( t.height != blending.height || t.width != blending.width )
throw std::string( "Error when loading heightmap, incorrect blending map proportions" );
heights.reserve( t.height );
textureBlending.reserve( t.height * t.width * 3 );
for( int i(0); i < t.height; i++ )
{
heights.push_back( std::vector<float>() );
heights.back().reserve( t.width );
for( int l(0); l < t.width; l++ )
{
int temp = (i * t.width + l) * 3; // three channels (rgb)
heights[i].push_back( ((unsigned int)t[temp] + (unsigned int)t[temp+1] + (unsigned int)t[temp+2]) / 3.f );
textureBlending.push_back( (float)blending[temp+0] / 256 );
textureBlending.push_back( (float)blending[temp+1] / 256 );
textureBlending.push_back( (float)blending[temp+2] / 256 );
}
}
// Calculate vertex positions and texture coordinates
float x = - (heights.size() * square_size * 0.5);
float y = 0.f;
float z = heights.size() * square_size * 0.5;
vertexs.reserve( t.width * t.height * 3 );
textureCoordinates.reserve( t.height * t.width * 2 );
std::vector< std::vector<float> >& h( heights );
for( int i(0); i < h.size(); i++ )
{
for( int l(0); l < h[i].size(); l++ )
{
// Smoothing
if( i != 0 && i != h.size() - 1 )
if( l != 0 && l != h[i].size() - 1 )
{
h[i][l] = (h[i][l] + h[i][l+1] + h[i][l-1] + h[i+1][l] + h[i+1][l+1] + h[i+1][l-1] + h[i-1][l] + h[i-1][l+1] + h[i-1][l-1]) / 9.f;
}
vertexs.push_back( x + l * square_size );
vertexs.push_back( y + h[i][l] );
vertexs.push_back( z - i * square_size );
textureCoordinates.push_back( i );
textureCoordinates.push_back( l );
}
}
// Calculate normals
normals.reserve( (t.width - 1 * 2) * (t.height - 1) * 3 );
for( int i(0); i < heights.size(); i++ )
{
int width = heights[i].size();
for( int l(0); l < width; l++ )
{
int t = (i * width + l) * 3;
std::vector<float>& v( vertexs );
bool missing_after = (t + width * 3 > v.size() - 1 ) || (t + 3 >= (i + 1) * width * 3);
bool missing_before = (t - width * 3 <= 0 ) || (t - 3 < i * width * 3);
if( !missing_after && !missing_before )
{
glm::vec3 vec( v[t], v[t+1], v[t+2] );
glm::vec3 vec1( v[t-3], v[t-2], v[t-1] );
glm::vec3 vec2( v[t-width*3], v[t-width*3+1], v[t-width*3+2] );
glm::vec3 vec3( v[t+3], v[t+4], v[t+5] );
glm::vec3 vec4( v[t+width*3], v[t+width*3+1], v[t+width*3+2] );
glm::vec3 t1 = vec1 - vec;
glm::vec3 t2 = vec2 - vec;
glm::vec3 t3 = vec3 - vec;
glm::vec3 t4 = vec4 - vec;
glm::vec3 n;
if( t1 == t2 && t3 == t4 )
n = glm::vec3( 0.f, 1.f, 0.f );
else if( t1 == t2 )
n = glm::cross( t3, t4 );
else if( t3 == t4 )
n = glm::cross( t1, t2 );
else
n = (glm::cross( vec1 - vec, vec2 - vec ) + glm::cross( vec3 - vec, vec4 - vec )) / 2.f;
if( n == glm::vec3( 0.f, 0.f, 0.f ) )
n = glm::vec3( 0.f, 1.f, 0.f );
else
n = glm::normalize( n );
normals.push_back( n.x );
normals.push_back( n.y );
normals.push_back( n.z );
}
else if( !missing_after )
{
glm::vec3 vec( v[t], v[t+1], v[t+2] );
glm::vec3 vec1( v[t+3], v[t+4], v[t+5] );
glm::vec3 vec2( v[t+width*3], v[t+width*3+1], v[t+width*3+2] );
glm::vec3 t1 = vec1 - vec;
glm::vec3 t2 = vec2 - vec;
glm::vec3 n;
if( t1 == t2 )
n = glm::vec3( 0.f, 1.f, 0.f );
else
n = glm::cross( t1, t2 );
if( n == glm::vec3( 0.f, 0.f, 0.f ) )
n = glm::vec3( 0.f, 1.f, 0.f );
else
n = glm::normalize( n );
normals.push_back( n.x );
normals.push_back( n.y );
normals.push_back( n.z );
}
else if( !missing_before )
{
glm::vec3 vec( v[t], v[t+1], v[t+2] );
glm::vec3 vec1( v[t-3], v[t-2], v[t-1] );
glm::vec3 vec2( v[t-width*3], v[t-width*3+1], v[t-width*3+2] );
glm::vec3 t1 = vec1 - vec;
glm::vec3 t2 = vec2 - vec;
glm::vec3 n;
if( t1 == t2 )
n = glm::vec3( 0.f, 1.f, 0.f );
else
n = glm::cross( t1, t2 );
if( n == glm::vec3( 0.f, 0.f, 0.f ) )
n = glm::vec3( 0.f, 1.f, 0.f );
else
n = glm::normalize( n );
normals.push_back( n.x );
normals.push_back( n.y );
normals.push_back( n.z );
}
else
{
normals.push_back( 0.f );
normals.push_back( 1.f );
normals.push_back( 0.f );
}
}
}
// Calculate indices
// Upperst and lowest is width * 2, the rest requres 2 indices per point so (height-2) * width * 2 and then plus extra for restart drawing number + height - 1
indices.reserve( t.width * 2 + (t.height - 2) * t.width * 2 + t.height - 1 );
for( int i(0); i < t.height - 1; i++ )
{
if( i != 0 )
indices.push_back( restart_number );
indices.push_back( i * t.width );
indices.push_back( i * t.width + 1 );
indices.push_back( i * t.width + t.width );
indices.push_back( i * t.width + t.width + 1 );
for( int l(2); l < t.width; l++ )
{
indices.push_back( i * t.width + t.width + l );
indices.push_back( i * t.width + l );
}
}
glGenBuffers( 5, Vbo );
glBindBuffer( GL_ARRAY_BUFFER, Vbo[0] );
glBufferData( GL_ARRAY_BUFFER, vertexs.size() * sizeof(float), &vertexs[0], GL_STATIC_DRAW );
glBindBuffer( GL_ARRAY_BUFFER, Vbo[1] );
glBufferData( GL_ARRAY_BUFFER, normals.size() * sizeof(float), &normals[0], GL_STATIC_DRAW );
glBindBuffer( GL_ARRAY_BUFFER, Vbo[2] );
glBufferData( GL_ARRAY_BUFFER, textureCoordinates.size() * sizeof(float), &textureCoordinates[0], GL_STATIC_DRAW );
glBindBuffer( GL_ARRAY_BUFFER, Vbo[3] );
glBufferData( GL_ARRAY_BUFFER, textureBlending.size() * sizeof(float), &textureBlending[0], GL_STATIC_DRAW );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, Vbo[4] );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(int), &indices[0], GL_STATIC_DRAW );
glGenVertexArrays( 1, &Vao );
glBindVertexArray( Vao );
// Vertex, normal, texture
glEnableVertexAttribArray( 0 );
glEnableVertexAttribArray( 1 );
glEnableVertexAttribArray( 2 );
glEnableVertexAttribArray( 3 );
glBindBuffer( GL_ARRAY_BUFFER, Vbo[0] );
glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, 0 );
glBindBuffer( GL_ARRAY_BUFFER, Vbo[1] );
glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 0, 0 );
glBindBuffer( GL_ARRAY_BUFFER, Vbo[2] );
glVertexAttribPointer( 2, 2, GL_FLOAT, GL_FALSE, 0, 0 );
glBindBuffer( GL_ARRAY_BUFFER, Vbo[3] );
glVertexAttribPointer( 3, 3, GL_FLOAT, GL_FALSE, 0, 0 );
glBindBuffer( GL_ARRAY_BUFFER, 0 );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 );
glBindVertexArray( 0 );
glDisableVertexAttribArray( 3 );
glDisableVertexAttribArray( 2 );
glDisableVertexAttribArray( 1 );
glDisableVertexAttribArray( 0 );
}
GLuint LoadShader( std::string name, ShaderType type )
{
std::fstream in( name.c_str() );
std::string program( ( std::istreambuf_iterator<char>( in ) ), std::istreambuf_iterator<char>() );
in.close();
GLuint shader;
switch( type )
{
case Vertex:
shader = glCreateShader( GL_VERTEX_SHADER );
break;
case Fragment:
shader = glCreateShader( GL_FRAGMENT_SHADER );
break;
case Geometry:
shader = glCreateShader( GL_GEOMETRY_SHADER );
break;
}
assert( shader );
const char* ptr = program.c_str();
glShaderSource( shader, 1, &ptr, 0 );
glCompileShader( shader );
int e;
glGetShaderiv( shader, GL_COMPILE_STATUS, &e );
if( !e ) {
int l, t;
glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &l );
char* error = new char[l];
glGetShaderInfoLog( shader, l, &t, error );
std::cout << std::endl << error;
std::string err( "Error in " + name + ": " + error );
delete error;
throw err;
}
return shader;
}
<file_sep>/main.cpp
#include <fstream>
#include <string>
#include "stuff.h"
std::ofstream out;
int main( int argc, char** argv )
{
out.open( "log.txt" );
try {
Initialize( argc, argv );
while( true )
Update();
} catch( std::string error ) {
out << error << std::endl;
} catch( exit_success e ) {
}
glfwTerminate();
out.close();
exit( EXIT_SUCCESS );
};
| 27535c86f55f42168bbc2151646bfa284128c2ae | [
"C++"
] | 3 | C++ | Alyanorno/3D-project | 2457772be43b90570093cf021e7df74016a1fbb2 | 9e12505d8b26e52ea32fcab65b3d6c083119be19 |
refs/heads/master | <repo_name>alistairmackinnon/imdb-scraper<file_sep>/scraper.py
from bs4 import BeautifulSoup
import requests
import pprint as pp
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
url = 'https://www.imdb.com/chart/top?ref_=nv_mv_250'
driver.get(url)
driver.close()
"""
resp = requests.get(url)
html = BeautifulSoup(resp.text)
items = html.find_all('td',{'class':'titleColumn'})
chart = {}
for item in items:
item = item.text
values = item.split()
position = values[0].replace('.','')
title = ' '.join(values[1:-1])
year = values[-1].replace('(','').replace(')','')
chart[int(position)] = {'title': title, 'year': int(year)}
print('Pick a chart position:')
choice = int(input())
result = chart[choice]
print(f"In position {choice}, is \"{title}\", made in {year}")
#item = item.find_all('a')
"""<file_sep>/readme.md
### Pythom webscraper for IMDB
| c7d3f7b663f13a12152cbc2523136e4c71566271 | [
"Markdown",
"Python"
] | 2 | Python | alistairmackinnon/imdb-scraper | 72f80a87632ba144347be4a35a1d28b4fc689aa4 | 8499b805b742b81eaf1c3b4c6b407cd16872dd2c |
refs/heads/main | <file_sep>This project was part of my coursework at NJIT.
## Subject: CS 631 - Database Management Systems Design.
The focus of this project was writing strong SQL Queries. UI was not the main focus of the project.
This folder contains the following:
1) Problem Statement : It defines the original problem.
2) Relational Schema: This is the relational schema diagram of the public library database as defined in the problem statement.
3) User Guide: Constains explanations and working project screenshots.
4) Create_Table.sql : Queries to create tables.
5) Populate_Table.sql: Queries to populate tables.
6) If the above two .sql files fail to execute, then run library.sql file. This executes all the tables required for librarymanagement.
7) Program_queries.sql: Queries mentioned in Deliverable 3 Problem statement.
8) librarymanagement.py: Python code for front end.
## Prerequites
1) XAMPP server PHPMyAdmin for MySQL. Get Free access to a PHPMyAdmin on [Pro Free Host](https://profreehost.com/)
2) Python 3.x
## Instructions to run
1) Clone this repository on your computer.
2) Create a New database on your MySQL backend.
3) Run queries Create_Table.sql and Populate_Table.sql on your newly created Database or run library.sql for all the tables on your database.
4) Change the query connection parameters from lines 7 through 11 in the librarymanagement.py file. Add your database and user information.
5) Run the librarymanagement.py program.
### Next Steps for the project:
To create a proper web UI and host it on Google Cloud
<file_sep>-- phpMyAdmin SQL Dump
-- version 5.1.0
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: May 03, 2021 at 05:38 PM
-- Server version: 10.4.18-MariaDB
-- PHP Version: 7.3.27
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `library`
--
-- --------------------------------------------------------
--
-- Table structure for table `admin`
--
CREATE TABLE `admin` (
`name` varchar(255) NOT NULL,
`id` int(2) UNSIGNED NOT NULL,
`code` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `admin`
--
INSERT INTO `admin` (`name`, `id`, `code`) VALUES
('Francis', 24, '152018'),
('Joyce', 42, '151011');
-- --------------------------------------------------------
--
-- Table structure for table `authors`
--
CREATE TABLE `authors` (
`PID` int(10) UNSIGNED NOT NULL,
`DOCID` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `authors`
--
INSERT INTO `authors` (`PID`, `DOCID`) VALUES
(1, 1),
(2, 3),
(2, 4),
(3, 1),
(5, 2);
-- --------------------------------------------------------
--
-- Table structure for table `book`
--
CREATE TABLE `book` (
`DOCID` int(10) UNSIGNED NOT NULL,
`ISBN` char(17) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `book`
--
INSERT INTO `book` (`DOCID`, `ISBN`) VALUES
(1, '999-3-16-188870-0'),
(2, '960-9-16-141910-0'),
(3, '938-3-10-146510-0'),
(4, ''),
(5, '978-3-15-148410-0');
-- --------------------------------------------------------
--
-- Table structure for table `borrowing`
--
CREATE TABLE `borrowing` (
`BOR_NO` int(11) NOT NULL,
`BDTIME` datetime DEFAULT NULL,
`RDTIME` datetime DEFAULT NULL,
`DUEDATE` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `borrowing`
--
INSERT INTO `borrowing` (`BOR_NO`, `BDTIME`, `RDTIME`, `DUEDATE`) VALUES
(1, '2012-12-03 00:00:00', '2012-12-05 00:00:00', '2012-12-23 00:00:00'),
(2, '2012-12-04 00:00:00', NULL, '2012-12-24 00:00:00'),
(3, '2012-12-05 00:00:00', NULL, '2012-12-25 00:00:00'),
(4, '2012-12-06 00:00:00', '2012-12-15 00:00:00', '2012-12-26 00:00:00'),
(5, '2012-12-07 00:00:00', NULL, '2012-12-27 00:00:00'),
(6, '2012-12-03 00:00:00', '2012-12-05 00:00:00', '2012-12-23 00:00:00'),
(7, '2012-12-04 00:00:00', '2021-05-03 10:56:48', '2012-12-24 00:00:00'),
(8, '2012-12-05 00:00:00', NULL, '2012-12-25 00:00:00'),
(9, '2012-12-06 00:00:00', '2012-12-15 00:00:00', '2012-12-26 00:00:00'),
(10, '2012-12-07 00:00:00', NULL, '2012-12-27 00:00:00'),
(15, '2021-05-03 10:55:00', NULL, '2021-06-02 10:55:00'),
(16, '2021-05-03 10:55:56', NULL, '2021-06-02 10:55:56');
-- --------------------------------------------------------
--
-- Table structure for table `borrows`
--
CREATE TABLE `borrows` (
`BOR_NO` int(11) NOT NULL,
`RID` int(11) DEFAULT NULL,
`DOCID` int(11) UNSIGNED NOT NULL,
`BID` int(11) UNSIGNED NOT NULL,
`COPYNO` int(11) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `borrows`
--
INSERT INTO `borrows` (`BOR_NO`, `RID`, `DOCID`, `BID`, `COPYNO`) VALUES
(7, 1, 1, 1, 3),
(10, 1, 4, 2, 5),
(16, 1, 2, 1, 2),
(8, 2, 2, 1, 2),
(15, 2, 1, 1, 1),
(6, 4, 1, 1, 1),
(9, 6, 3, 2, 4);
-- --------------------------------------------------------
--
-- Table structure for table `branch`
--
CREATE TABLE `branch` (
`BID` int(10) UNSIGNED NOT NULL,
`LNAME` varchar(30) NOT NULL,
`LOCATION` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `branch`
--
INSERT INTO `branch` (`BID`, `LNAME`, `LOCATION`) VALUES
(1, 'Jersey City', '121, Grant St, Jersey City, NJ'),
(2, 'Newark', '555 Washington St, Newark, NJ'),
(3, 'Trenton', '345 Franklin Ave, Trenton, NJ'),
(4, 'Edison', '234, MLK St, Edison, NJ');
-- --------------------------------------------------------
--
-- Table structure for table `chairs`
--
CREATE TABLE `chairs` (
`PID` int(11) UNSIGNED NOT NULL,
`DOCID` int(11) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `chairs`
--
INSERT INTO `chairs` (`PID`, `DOCID`) VALUES
(1, 3),
(5, 4),
(4, 5),
(2, 7),
(7, 9);
-- --------------------------------------------------------
--
-- Table structure for table `copy`
--
CREATE TABLE `copy` (
`DOCID` int(10) UNSIGNED NOT NULL,
`COPYNO` int(10) UNSIGNED NOT NULL,
`BID` int(10) UNSIGNED NOT NULL,
`POSITION` varchar(10) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `copy`
--
INSERT INTO `copy` (`DOCID`, `COPYNO`, `BID`, `POSITION`) VALUES
(1, 1, 1, 'SA-Q-124'),
(1, 3, 1, 'SQ-G-123'),
(2, 2, 1, 'SB-K-5223'),
(3, 4, 2, 'SD-F-4563'),
(4, 5, 2, 'DE-G-3456');
-- --------------------------------------------------------
--
-- Table structure for table `document`
--
CREATE TABLE `document` (
`DOCID` int(10) UNSIGNED NOT NULL,
`TITLE` varchar(45) NOT NULL,
`PDATE` date DEFAULT NULL,
`PUBLISHERID` int(11) UNSIGNED DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `document`
--
INSERT INTO `document` (`DOCID`, `TITLE`, `PDATE`, `PUBLISHERID`) VALUES
(1, 'To Kill a Mockingbird', '1999-12-03', 1),
(2, '<NAME> and the Philosophers Stone', '1999-12-04', 2),
(3, 'The Lord of the Rings', '1999-12-05', 3),
(4, 'The Great Gatsby', '1999-12-06', 1),
(5, 'Pride and Prejudice', '1999-12-07', 2),
(6, 'The Diary Of A Young Girl', '1999-12-08', 5),
(7, 'The Book Thief', '1999-12-09', 4),
(8, 'The Power of Habit', '1999-12-10', 2),
(9, 'High Performance Habits', '1999-12-11', 3),
(11, '<NAME>', '2020-04-12', 4);
-- --------------------------------------------------------
--
-- Table structure for table `gedits`
--
CREATE TABLE `gedits` (
`DOCID` int(10) UNSIGNED NOT NULL,
`ISSUE_NO` int(11) UNSIGNED NOT NULL,
`PID` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `gedits`
--
INSERT INTO `gedits` (`DOCID`, `ISSUE_NO`, `PID`) VALUES
(1, 1, 1),
(3, 2, 3),
(5, 3, 7),
(7, 4, 2),
(9, 5, 5);
-- --------------------------------------------------------
--
-- Table structure for table `journal_issue`
--
CREATE TABLE `journal_issue` (
`DOCID` int(10) UNSIGNED NOT NULL,
`ISSUE_NO` int(10) UNSIGNED NOT NULL,
`SCOPE` varchar(45) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `journal_issue`
--
INSERT INTO `journal_issue` (`DOCID`, `ISSUE_NO`, `SCOPE`) VALUES
(1, 1, 'POLITICS'),
(3, 2, 'TECH'),
(5, 3, 'BIOLOGY'),
(7, 4, 'SOCIAL'),
(9, 5, 'TECH');
-- --------------------------------------------------------
--
-- Table structure for table `journal_volume`
--
CREATE TABLE `journal_volume` (
`DOCID` int(10) UNSIGNED NOT NULL,
`VOLUME_NO` int(11) NOT NULL,
`EDITOR` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `journal_volume`
--
INSERT INTO `journal_volume` (`DOCID`, `VOLUME_NO`, `EDITOR`) VALUES
(1, 6, 2),
(3, 2, 4),
(5, 2, 1),
(6, 2, 4),
(7, 7, 7),
(9, 6, 6);
-- --------------------------------------------------------
--
-- Table structure for table `person`
--
CREATE TABLE `person` (
`PID` int(10) UNSIGNED NOT NULL,
`PNAME` varchar(45) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `person`
--
INSERT INTO `person` (`PID`, `PNAME`) VALUES
(1, 'Darshan'),
(2, 'Alex'),
(3, 'Ketki'),
(4, 'Jasneek'),
(5, 'Thomas'),
(6, 'Ravi'),
(7, 'Ashley');
-- --------------------------------------------------------
--
-- Table structure for table `proceedings`
--
CREATE TABLE `proceedings` (
`DOCID` int(10) UNSIGNED NOT NULL,
`CDATE` date DEFAULT NULL,
`CLOCATION` varchar(45) DEFAULT NULL,
`CEDITOR` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `proceedings`
--
INSERT INTO `proceedings` (`DOCID`, `CDATE`, `CLOCATION`, `CEDITOR`) VALUES
(3, '1989-09-07', 'New York', 'Noah'),
(4, '2000-02-18', 'San Diego', 'Maxwell'),
(5, '2000-01-20', 'Houston', 'Elijah'),
(7, '1999-12-03', 'Miami', 'Liam'),
(9, '1999-12-22', 'Chicago', 'Benjamin');
-- --------------------------------------------------------
--
-- Table structure for table `publisher`
--
CREATE TABLE `publisher` (
`PUBLISHERID` int(9) UNSIGNED NOT NULL,
`PUBNAME` varchar(45) NOT NULL,
`ADDRESS` varchar(200) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `publisher`
--
INSERT INTO `publisher` (`PUBLISHERID`, `PUBNAME`, `ADDRESS`) VALUES
(1, 'Bloomberg ', '123 Central Ave Newark, NJ'),
(2, 'Harper ', '234 Broad St, Jersey City, NJ'),
(3, 'Wiley ', '345 Newark Ave, Elizabeth, NJ'),
(4, 'Pearson', '456 North Street, West Orange, NJ'),
(5, 'Penguin', '678 Grove St, Newport, NJ');
-- --------------------------------------------------------
--
-- Table structure for table `reader`
--
CREATE TABLE `reader` (
`RID` int(11) NOT NULL,
`RTYPE` varchar(128) DEFAULT NULL,
`RNAME` varchar(128) DEFAULT NULL,
`RADDRESS` varchar(128) DEFAULT NULL,
`PHONE_NO` bigint(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `reader`
--
INSERT INTO `reader` (`RID`, `RTYPE`, `RNAME`, `RADDRESS`, `PHONE_NO`) VALUES
(1, 'Student', '<NAME>', '1804, Greenwich Village, New York, NY', 9917890704),
(2, 'Senior Citizen', '<NAME>', 'George Washington\'s Mount Vernon, Mount Vernon, VA', 9217320899),
(3, 'Student', '<NAME>', 'Milk Street, Boston, MA', 9717060490),
(4, 'Staff', '<NAME>', '', 1017350726),
(5, 'Senior Citizen', '<NAME>', 'Boston, MA', 9917221003),
(6, 'Senior Citizen', '<NAME>', 'Monticello, VA', 9417430726),
(7, 'Student', '<NAME>', '<NAME>\'s Montpelier, Montpelier Station, VA', 9317510636),
(8, 'Staff', '<NAME>', 'Bedford, NY', 1217450529);
-- --------------------------------------------------------
--
-- Table structure for table `reservation`
--
CREATE TABLE `reservation` (
`RES_NO` int(11) NOT NULL,
`DTIME` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `reservation`
--
INSERT INTO `reservation` (`RES_NO`, `DTIME`) VALUES
(1, '2012-12-05 00:00:00'),
(2, '2012-12-06 00:00:00'),
(3, '2012-12-09 00:00:00');
-- --------------------------------------------------------
--
-- Table structure for table `reserves`
--
CREATE TABLE `reserves` (
`RESERVATION_NO` int(11) NOT NULL,
`RID` int(11) DEFAULT NULL,
`DOCID` int(11) UNSIGNED NOT NULL,
`COPYNO` int(11) UNSIGNED NOT NULL,
`BID` int(11) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `reserves`
--
INSERT INTO `reserves` (`RESERVATION_NO`, `RID`, `DOCID`, `COPYNO`, `BID`) VALUES
(2, 3, 3, 4, 2),
(3, 4, 1, 1, 1),
(1, 7, 4, 5, 2);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `admin`
--
ALTER TABLE `admin`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `authors`
--
ALTER TABLE `authors`
ADD PRIMARY KEY (`PID`,`DOCID`),
ADD KEY `DOCID_idx` (`DOCID`);
--
-- Indexes for table `book`
--
ALTER TABLE `book`
ADD PRIMARY KEY (`DOCID`);
--
-- Indexes for table `borrowing`
--
ALTER TABLE `borrowing`
ADD PRIMARY KEY (`BOR_NO`);
--
-- Indexes for table `borrows`
--
ALTER TABLE `borrows`
ADD PRIMARY KEY (`BOR_NO`,`DOCID`,`COPYNO`,`BID`),
ADD KEY `RID` (`RID`),
ADD KEY `DOCID` (`DOCID`,`COPYNO`,`BID`);
--
-- Indexes for table `branch`
--
ALTER TABLE `branch`
ADD PRIMARY KEY (`BID`);
--
-- Indexes for table `chairs`
--
ALTER TABLE `chairs`
ADD PRIMARY KEY (`DOCID`,`PID`),
ADD KEY `PID` (`PID`);
--
-- Indexes for table `copy`
--
ALTER TABLE `copy`
ADD PRIMARY KEY (`DOCID`,`COPYNO`,`BID`),
ADD UNIQUE KEY `COPYNO` (`COPYNO`),
ADD KEY `fk_Copy_bid` (`BID`);
--
-- Indexes for table `document`
--
ALTER TABLE `document`
ADD PRIMARY KEY (`DOCID`),
ADD KEY `PUBLISHERID` (`PUBLISHERID`);
--
-- Indexes for table `gedits`
--
ALTER TABLE `gedits`
ADD PRIMARY KEY (`DOCID`,`ISSUE_NO`,`PID`),
ADD KEY `PID` (`PID`);
--
-- Indexes for table `journal_issue`
--
ALTER TABLE `journal_issue`
ADD PRIMARY KEY (`DOCID`,`ISSUE_NO`),
ADD UNIQUE KEY `ISSUE_NO` (`ISSUE_NO`);
--
-- Indexes for table `journal_volume`
--
ALTER TABLE `journal_volume`
ADD PRIMARY KEY (`DOCID`);
--
-- Indexes for table `person`
--
ALTER TABLE `person`
ADD PRIMARY KEY (`PID`);
--
-- Indexes for table `proceedings`
--
ALTER TABLE `proceedings`
ADD PRIMARY KEY (`DOCID`);
--
-- Indexes for table `publisher`
--
ALTER TABLE `publisher`
ADD PRIMARY KEY (`PUBLISHERID`);
--
-- Indexes for table `reader`
--
ALTER TABLE `reader`
ADD PRIMARY KEY (`RID`);
--
-- Indexes for table `reservation`
--
ALTER TABLE `reservation`
ADD PRIMARY KEY (`RES_NO`);
--
-- Indexes for table `reserves`
--
ALTER TABLE `reserves`
ADD PRIMARY KEY (`RESERVATION_NO`,`DOCID`,`COPYNO`,`BID`),
ADD KEY `RID` (`RID`),
ADD KEY `DOCID` (`DOCID`,`COPYNO`,`BID`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `borrowing`
--
ALTER TABLE `borrowing`
MODIFY `BOR_NO` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17;
--
-- AUTO_INCREMENT for table `branch`
--
ALTER TABLE `branch`
MODIFY `BID` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `copy`
--
ALTER TABLE `copy`
MODIFY `COPYNO` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT for table `document`
--
ALTER TABLE `document`
MODIFY `DOCID` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
--
-- AUTO_INCREMENT for table `journal_issue`
--
ALTER TABLE `journal_issue`
MODIFY `ISSUE_NO` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `person`
--
ALTER TABLE `person`
MODIFY `PID` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `publisher`
--
ALTER TABLE `publisher`
MODIFY `PUBLISHERID` int(9) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `reader`
--
ALTER TABLE `reader`
MODIFY `RID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT for table `reservation`
--
ALTER TABLE `reservation`
MODIFY `RES_NO` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `authors`
--
ALTER TABLE `authors`
ADD CONSTRAINT `DOCID` FOREIGN KEY (`DOCID`) REFERENCES `book` (`DOCID`),
ADD CONSTRAINT `PID` FOREIGN KEY (`PID`) REFERENCES `person` (`PID`);
--
-- Constraints for table `book`
--
ALTER TABLE `book`
ADD CONSTRAINT `book_ibfk_1` FOREIGN KEY (`DOCID`) REFERENCES `document` (`DOCID`),
ADD CONSTRAINT `book_ibfk_2` FOREIGN KEY (`DOCID`) REFERENCES `document` (`DOCID`);
--
-- Constraints for table `borrows`
--
ALTER TABLE `borrows`
ADD CONSTRAINT `borrows_ibfk_1` FOREIGN KEY (`BOR_NO`) REFERENCES `borrowing` (`BOR_NO`),
ADD CONSTRAINT `borrows_ibfk_2` FOREIGN KEY (`RID`) REFERENCES `reader` (`RID`),
ADD CONSTRAINT `borrows_ibfk_3` FOREIGN KEY (`BOR_NO`) REFERENCES `borrowing` (`BOR_NO`),
ADD CONSTRAINT `borrows_ibfk_4` FOREIGN KEY (`RID`) REFERENCES `reader` (`RID`),
ADD CONSTRAINT `borrows_ibfk_5` FOREIGN KEY (`BOR_NO`) REFERENCES `borrowing` (`BOR_NO`),
ADD CONSTRAINT `borrows_ibfk_6` FOREIGN KEY (`RID`) REFERENCES `reader` (`RID`),
ADD CONSTRAINT `borrows_ibfk_7` FOREIGN KEY (`BOR_NO`) REFERENCES `borrowing` (`BOR_NO`),
ADD CONSTRAINT `borrows_ibfk_8` FOREIGN KEY (`RID`) REFERENCES `reader` (`RID`),
ADD CONSTRAINT `borrows_ibfk_9` FOREIGN KEY (`DOCID`,`COPYNO`,`BID`) REFERENCES `copy` (`DOCID`, `COPYNO`, `BID`);
--
-- Constraints for table `chairs`
--
ALTER TABLE `chairs`
ADD CONSTRAINT `chairs_ibfk_1` FOREIGN KEY (`PID`) REFERENCES `person` (`PID`),
ADD CONSTRAINT `chairs_ibfk_2` FOREIGN KEY (`DOCID`) REFERENCES `proceedings` (`DOCID`);
--
-- Constraints for table `copy`
--
ALTER TABLE `copy`
ADD CONSTRAINT `fk_Copy_bid` FOREIGN KEY (`BID`) REFERENCES `branch` (`BID`),
ADD CONSTRAINT `fk_Copy_docid` FOREIGN KEY (`DOCID`) REFERENCES `document` (`DOCID`);
--
-- Constraints for table `document`
--
ALTER TABLE `document`
ADD CONSTRAINT `PUBLISHERID` FOREIGN KEY (`PUBLISHERID`) REFERENCES `publisher` (`PUBLISHERID`);
--
-- Constraints for table `gedits`
--
ALTER TABLE `gedits`
ADD CONSTRAINT `gedits_ibfk_1` FOREIGN KEY (`PID`) REFERENCES `person` (`PID`),
ADD CONSTRAINT `gedits_ibfk_2` FOREIGN KEY (`PID`) REFERENCES `person` (`PID`),
ADD CONSTRAINT `gedits_ibfk_3` FOREIGN KEY (`PID`) REFERENCES `person` (`PID`),
ADD CONSTRAINT `gedits_ibfk_4` FOREIGN KEY (`DOCID`,`ISSUE_NO`) REFERENCES `journal_issue` (`DOCID`, `ISSUE_NO`);
--
-- Constraints for table `journal_issue`
--
ALTER TABLE `journal_issue`
ADD CONSTRAINT `journal_issue_ibfk_1` FOREIGN KEY (`DOCID`) REFERENCES `journal_volume` (`DOCID`);
--
-- Constraints for table `journal_volume`
--
ALTER TABLE `journal_volume`
ADD CONSTRAINT `journal_volume_ibfk_1` FOREIGN KEY (`DOCID`) REFERENCES `document` (`DOCID`);
--
-- Constraints for table `proceedings`
--
ALTER TABLE `proceedings`
ADD CONSTRAINT `proceedings_ibfk_1` FOREIGN KEY (`DOCID`) REFERENCES `document` (`DOCID`),
ADD CONSTRAINT `proceedings_ibfk_2` FOREIGN KEY (`DOCID`) REFERENCES `document` (`DOCID`);
--
-- Constraints for table `reserves`
--
ALTER TABLE `reserves`
ADD CONSTRAINT `reserves_ibfk_1` FOREIGN KEY (`RESERVATION_NO`) REFERENCES `reservation` (`RES_NO`),
ADD CONSTRAINT `reserves_ibfk_2` FOREIGN KEY (`RID`) REFERENCES `reader` (`RID`),
ADD CONSTRAINT `reserves_ibfk_3` FOREIGN KEY (`RESERVATION_NO`) REFERENCES `reservation` (`RES_NO`),
ADD CONSTRAINT `reserves_ibfk_4` FOREIGN KEY (`RID`) REFERENCES `reader` (`RID`),
ADD CONSTRAINT `reserves_ibfk_5` FOREIGN KEY (`RESERVATION_NO`) REFERENCES `reservation` (`RES_NO`),
ADD CONSTRAINT `reserves_ibfk_6` FOREIGN KEY (`RID`) REFERENCES `reader` (`RID`),
ADD CONSTRAINT `reserves_ibfk_7` FOREIGN KEY (`DOCID`,`COPYNO`,`BID`) REFERENCES `copy` (`DOCID`, `COPYNO`, `BID`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>import mysql.connector as mc
from tkinter import ttk
from tkinter import *
import tkinter as tk
from tkinter import Tk, Text, TOP, BOTH, X, N, LEFT
from datetime import datetime, timedelta
conn = mc.connect(
host="127.0.0.1",
user="root",
password = "",
database="library")
def getTable(tableName):
output1.delete(0.0,END)
try:
QueryString="Select * from "+ tableName.upper()
cursor=conn.cursor()
cursor.execute(QueryString)
result= cursor.fetchall()
resultString=""
for r in result:
resultString+="\n"+str(r)
except BaseException as e:
resultString="Some Error Occured. Could not fetch Search Results. "+ str(e)
cursor=None
output1.insert(END, resultString)
class FirstScreen(tk.Tk):
def __init__(self,*args,**kwargs):
tk.Tk.__init__(self,*args,**kwargs)
container=tk.Frame(self)
container.pack(side="top",fill="both",expand=True)
container.grid_rowconfigure(0,weight=1)
container.grid_columnconfigure(0,weight=1)
self.frames={}
for F in (StartPage,ReaderPage,AdminPage,AddReader):
frame =F(container,self)
self.frames[F] = frame
frame.grid(row=0,column=0,sticky="nsew")
self.show_frame(StartPage)
def show_frame(self,cont):
frame=self.frames[cont]
frame.tkraise()
def get_page(self, page_class):
return self.frames[page_class]
class StartPage(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
h = Scrollbar(self, orient = 'horizontal')
h.pack(side = BOTTOM, fill = X)
self.controller=controller
MMlabel10=Label(self, text=" " )
MMlabel10.pack()
MMlabel11=Label(self, text=" " )
MMlabel11.pack()
MMlabel1=Label(self, text=" Enter Your Reader Card Number: " )
MMlabel1.pack()
MMSearchQuery_textBox1 = Entry(self, width =20 )
MMSearchQuery_textBox1.pack()
MMbtn1=Button (self, text="Reader Menu", width =10,height=2, command=lambda:controller.show_frame(ReaderPage)) #command=popupReader
MMbtn1.pack()
MMlabel12=Label(self, text=" " )
MMlabel12.pack()
MMlabel13=Label(self, text=" " )
MMlabel13.pack()
self.MMlabel2=Label(self, text="Enter Your Admin ID: " )
self.MMlabel2.pack()
self.MMSearchQuery_textBox2 = Entry(self, width =20 )
self.MMSearchQuery_textBox2.pack()
self.MMlabel3=Label(self, text="Enter password " )
self.MMlabel3.pack()
self.MMSearchQuery_textBox3 = Entry(self, width =20 )
self.MMSearchQuery_textBox3.pack()
self.MMbtn1=Button (self, text="Admin Menu", width =10,height=2,command=self.popupadmin)
self.MMbtn1.pack()
quit=Button (self, text="Exit", width =10,height=2,command=FirstScreen.destroy)
quit.pack()
def popupReader():
popup =tk.Tk()
popup.wm_title("Login Success")
popup.eval('tk::PlaceWindow . center')
label= ttk.Label(popup, text="Login Success! Welcome Reader")
label.pack()
Btn = ttk.Button(popup, text="Okay", command=popup.destroy)
Btn.pack()
popup.geometry("300X300")
popup.mainloop()
def popupadmin(self):
id=self.MMSearchQuery_textBox2.get()
code=self.MMSearchQuery_textBox3.get()
QueryString="SELECT EXISTS (SELECT * FROM admin WHERE id = "+id+ " AND code = "+str(code)+ ");"
try:
cursor=conn.cursor()
cursor.execute(QueryString)
result= cursor.fetchall()
result = [item[0] for item in result]
if str(result[0])=="1":
print("aa")
self.controller.show_frame(AdminPage)
else:
popup =tk.Tk()
popup.wm_title("Login Success")
popup.eval('tk::PlaceWindow . center')
label2= ttk.Label(popup, text="Login Unsuccessful")
label2.pack()
Btn2 = ttk.Button(popup, text="Okay", command=popup.destroy)
Btn2.pack()
popup.geometry("300X300")
popup.mainloop()
except BaseException as e:
resultString="Some Error Occured. Could not fetch Search Results. "+ str(e)
cursor=None
class ReaderPage(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
back1=Button (self, text="Exit", width =10,height=2,command=lambda:controller.show_frame(StartPage))
back1.pack(side=LEFT)
q1label0=Label(self, text="###### Document Search ######" )
q1label0.pack()
q1label1=Label(self, text="Enter DOCID/Publisher:", width=20)
q1label1.pack()
self.q1SearchQuery_textBox1 = Entry(self, width =20 )
self.q1SearchQuery_textBox1.pack()
q1label2=Label(self, text="Enter Title", width=20 )
q1label2.pack()
self.q1SearchQuery_textBox2 = Entry(self, width =20 )
self.q1SearchQuery_textBox2.pack()
self.q1btn1=Button (self, text="Search Document", width =20,height=2 ,command=self.searchDocument)
self.q1btn1.pack()
ttk.Separator(self).pack()
########## QUERY2 ############
q2label1=Label(self, text="###### Document Checkout, Return and Reservation ######" )
q2label1.pack()
q2label2=Label(self, text="Enter DOCID", width=20 )
q2label2.pack()
self.q2SearchQuery_textBox1 = Entry(self, width =20 )
self.q2SearchQuery_textBox1.pack()
q2label3=Label(self, text="Enter BranchID", width=20 )
q2label3.pack()
self.q2SearchQuery_textBox2 = Entry(self, width =20 )
self.q2SearchQuery_textBox2.pack()
q2label4=Label(self, text="Enter CopyNo", width=20 )
q2label4.pack()
self.q2SearchQuery_textBox3 = Entry(self, width =20 )
self.q2SearchQuery_textBox3.pack()
q2label5=Label(self, text="Enter ReadID" , width=20)
q2label5.pack()
self.q2SearchQuery_textBox4 = Entry(self, width =20 )
self.q2SearchQuery_textBox4.pack()
self.q2btn1=Button (self, text="Checkout", width =10,height=2 ,command=self.checkout)
self.q2btn1.pack()
self.q2btn2=Button (self, text="Return", width =10,height=2 ,command=self.returnDoc)
self.q2btn2.pack()
self.q2btn3=Button (self, text="Reserve", width =10,height=2 ,command=self.reserve)
self.q2btn3.pack()
ttk.Separator(self).pack()
q3label1=Label(self, text="###### Check Status ######" )
q3label1.pack()
q3label2=Label(self, text="Enter Reader ID", width=20 )
q3label2.pack()
self.q3SearchQuery_textBox1 = Entry(self, width =20 )
self.q3SearchQuery_textBox1.pack()
self.output1 = Text(self, width=75, height=20, wrap=WORD)
self.q3btn1=Button(self, text="Get Details", width =10,height=2 ,command=self.getStatus)
self.q3btn1.pack()
q3label4=Label(self, text="###### Publisher Details ######" )
q3label4.pack()
q3label4=Label(self, text="Publish Name", width=20 )
q3label4.pack()
self.q3SearchQuery_textBox4 = Entry(self, width =20 )
self.q3SearchQuery_textBox4.pack()
self.q3btn4=Button(self, text="Get Details", width =10,height=2 ,command=self.getPublisherDetails)
self.q3btn4.pack()
self.output1 = Text(self, width=75, height=20, wrap=WORD)
self.output1.pack()
def getPublisherDetails(self):
self.output1.delete(0.0,END)
Name = self.q3SearchQuery_textBox4.get()
QueryString="select DOCID,TITLE from document where PUBLISHERID =(select publisherid from publisher where pubname=\'"+Name+"\');"
try:
cursor=conn.cursor()
cursor.execute(QueryString)
result= cursor.fetchall()
resultString=""
for r in result:
resultString+="\n"+str(r)
except BaseException as e:
resultString="Some Error Occured. Could not fetch Search Results. "+ str(e)
cursor=None
if(resultString==""):
print("empty")
print(resultString)
self.output1.insert(END, resultString)
def getStatus(self):
self.output1.delete(0.0,END)
RID = self.q3SearchQuery_textBox1.get()
QueryString="SELECT b1.DOCID, b1.COPYNO, b1.BID, CASE WHEN b2.RDTIME is NULL THEN 'Not Available' ELSE 'Available' END AS STATUS FROM BORROWS b1, BORROWING b2 WHERE b2.BOR_NO = b1.BOR_NO AND b1.DOCID in (SELECT r.DOCID FROM RESERVES r where r.RID ="+RID+ ");"
try:
cursor=conn.cursor()
cursor.execute(QueryString)
result= cursor.fetchall()
resultString=""
for r in result:
print(str(r))
resultString+="\n"+str(r)
except BaseException as e:
resultString="Some Error Occured. Could not fetch Search Results. "+ str(e)
cursor=None
if(resultString==""):
print("empty")
print(resultString)
self.output1.insert(END, resultString)
def searchDocument(self):
self.output1.delete(0.0,END)
SearchQuery1= self.q1SearchQuery_textBox1.get()
SearchQuery2= self.q1SearchQuery_textBox2.get()
QueryString = "Select * from DOCUMENT where"
if len(SearchQuery1)>0:
QueryString +=" DOCID ="+SearchQuery1+" OR PublisherID = "+SearchQuery1
if len(SearchQuery2)>0:
if SearchQuery1!="":
QueryString +=" OR Title = '"+SearchQuery2+"'"
else:
QueryString +=" Title = '"+SearchQuery2+"'"
try:
cursor=conn.cursor()
cursor.execute(QueryString)
result= cursor.fetchall()
resultString=""
for r in result:
resultString+="\n"+str(r)
except:
resultString="Some Error Occured. Could not fetch Search Results"
cursor=None
self.output1.insert(0.0, "Search Results\n"+resultString)
def reserve(self):
self.output1.delete(0.0,END)
RID = self.q2SearchQuery_textBox4.get()
DocID= self.q2SearchQuery_textBox1.get()
BID = self.q2SearchQuery_textBox2.get()
CopyNO= self.q2SearchQuery_textBox3.get()
Dtime = datetime.now().isoformat()
#QueryString = "Update BORROWING Set RDTIME =\'"+Rdate+"\' Where BOR_NO=(Select BOR_NO from BORROWS where RID ="+RID+" and DOCID="+DocID+" and BID="+BID+" and COPYNO="+CopyNO+");"
QueryString = "INSERT INTO RESERVATION (DTIME) VALUES(\'"+Dtime+"\');INSERT INTO RESERVES (RESERVATION_NO,RID,DOCID,BID,COPYNO) VALUES((SELECT MAX(RES_NO) FROM RESERVATION ),"+RID+","+DocID+","+BID+","+CopyNO+");"
try:
cursor=conn.cursor()
cursor.execute(QueryString)
conn.commit()
#result= cursor.fetchall()
cursor=None
resultString="Reserved"
# for r in result:
# resultString+="\n"+str(r)
except BaseException as e:
resultString="Some Error Occured. Could not fetch Search Results. "+ str(e)
cursor=None
self.output1.insert(END, resultString)
def checkout(self):
self.output1.delete(0.0,END)
RID = self.q2SearchQuery_textBox4.get()
DocID= self.q2SearchQuery_textBox1.get()
BID = self.q2SearchQuery_textBox2.get()
CopyNO= self.q2SearchQuery_textBox3.get()
Bdate = datetime.now().isoformat()
DueDate = (datetime.now()+timedelta(days=30)).isoformat()
QueryString = "INSERT INTO BORROWING (BDTIME,RDTIME,DUEDATE) VALUES(\'"+Bdate+"\',NULL,\'"+DueDate+"\');"
QueryString += "INSERT INTO BORROWS (BOR_NO,RID,DOCID,BID,COPYNO) VALUES((SELECT MAX(BOR_NO) FROM BORROWING ),"+RID+","+DocID+","+BID+","+CopyNO+");";
#QueryString += "Select * from BORROWS;"
try:
cursor=conn.cursor()
cursor.execute(QueryString)
conn.commit()
result= cursor.fetchall()
resultString="Query Inserted. Checkout Complete."
#for r in result:
# resultString+="\n"+str(r)
except BaseException as e:
resultString="Some Error Occured. Could not fetch Search Results. "+ str(e)
cursor=None
self.output1.insert(END, resultString)
def returnDoc(self):
self.output1.delete(0.0,END)
RID = self.q2SearchQuery_textBox4.get()
DocID= self.q2SearchQuery_textBox1.get()
BID = self.q2SearchQuery_textBox2.get()
CopyNO= self.q2SearchQuery_textBox3.get()
Rdate = datetime.now().isoformat()
#QueryString = "Update BORROWING Set RDTIME =\'"+Rdate+"\' Where BOR_NO=(Select BOR_NO from BORROWS where RID ="+RID+" and DOCID="+DocID+");"
QueryString = "Update BORROWING Set RDTIME =\'"+Rdate+"\' Where BOR_NO=(Select BOR_NO from BORROWS where RID ="+RID+" and DOCID="+DocID+" and BID="+BID+" and COPYNO="+CopyNO+");"
#QueryString +="Select * from BORROWS;"
try:
cursor=conn.cursor()
cursor.execute(QueryString)
conn.commit()
#result= cursor.fetchall()
resultString="Returned"
# for r in result:
# resultString+="\n"+str(r)
except BaseException as e:
resultString="Some Error Occured. Could not fetch Search Results. "+ str(e)
cursor=None
self.output1.insert(END, resultString)
class AdminPage(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
self.output2 = Text(self, width=75, height=20, wrap=WORD)
back2=Button (self, text="Exit", width =10,height=2,command=lambda:controller.show_frame(StartPage))
back2.pack(side=LEFT)
t2q1label0=Label(self, text="###### Add a Document Copy ######" )
t2q1label0.pack()
t2q1label1=Label(self, text="Enter Title:" )
t2q1label1.pack()
self.t2q1SearchQuery_textBox1 = Entry(self, width =20 )
self.t2q1SearchQuery_textBox1.pack()
t2q1label2=Label(self, text="Enter Published Date in (YYYY-MM-DD) Format Only" )
t2q1label2.pack()
self.t2q1SearchQuery_textBox2 = Entry(self, width =20 )
self.t2q1SearchQuery_textBox2.pack()
t2q1label3=Label(self, text="Enter Published ID" )
t2q1label3.pack()
self.t2q1SearchQuery_textBox3 = Entry(self, width =20 )
self.t2q1SearchQuery_textBox3.pack()
self.t2q1btn1=Button (self, text="Add Document", width =10,height=2 ,command=self.addDocument)
self.t2q1btn1.pack()
ttk.Separator(self).pack()
########## QUERY2 ############
t2q2label0=Label(self, text="###### Get top N borrowed Books ######" )
t2q2label0.pack()
t2q2label1=Label(self, text="Enter N:" )
t2q2label1.pack()
self.t2q2SearchQuery_textBox1 = Entry(self, width =20 )
self.t2q2SearchQuery_textBox1.pack()
self.t2q2btn1=Button (self, text="Fetch", width =10,height=2 ,command=self.getNBorrowed)
self.t2q2btn1.pack()
ttk.Separator(self).pack()
########## QUERY3 ############
t2q3label0=Label(self, text="###### Average Fines from Each Branch ######" )
t2q3label0.pack()
t2q3label1=Label(self, text="Enter Start Date (YYYY-MM-DD format only):" )
t2q3label1.pack()
self.t2q3SearchQuery_textBox1 = Entry(self, width =20 )
self.t2q3SearchQuery_textBox1.pack()
t2q3label2=Label(self, text="Enter End Date (YYYY-MM-DD format only):" )
t2q3label2.pack()
self.t2q3SearchQuery_textBox2 = Entry(self, width =20 )
self.t2q3SearchQuery_textBox2.pack()
self.t2q3btn1=Button (self, text="Calculate", width =10,height=2 ,command=self.getAvgFine)
self.t2q3btn1.pack()
ttk.Separator(self).pack()
t2q3label3=Label(self, text="###### ADD READER ######" )
t2q3label3.pack()
self.t2q3btn3=Button (self, text="ADD reader", width =10,height=2 ,command=lambda:controller.show_frame(AddReader))
self.t2q3btn3.pack()
#self.output2 = Text(self, width=75, height=20, wrap=WORD)
self.output2.pack()
def addDocument(self):
self.output2.delete(0.0,END)
Title = self.t2q1SearchQuery_textBox1.get()
PDate = self.t2q1SearchQuery_textBox2.get()
PublisherID = self.t2q1SearchQuery_textBox3.get()
QueryString = "INSERT INTO `DOCUMENT`( `TITLE`, `PDATE`, `PUBLISHERID`) VALUES (\'"+Title+"\',\'"+PDate+"\',"+PublisherID+");"
try:
cursor=conn.cursor()
cursor.execute(QueryString)
conn.commit()
#result= cursor.fetchall()
resultString="Inserted"
# for r in result:
# resultString+="\n"+str(r)
except BaseException as e:
resultString="Some Error Occured. Could not fetch Search Results. "+ str(e)
cursor=None
self.output2.insert(END, resultString)
def getAvgFine(self):
self.output2.delete(0.0,END)
StartDate = self.t2q3SearchQuery_textBox1.get()
EndDate = self.t2q3SearchQuery_textBox2.get()
QueryString = "Select b3.LNAME, b3.BID, Avg(IF(b2.bdtime between '"+StartDate+"' and '"+EndDate+"' and b2.RDTIME is NULL and DATEDIFF(CURRENT_DATE, b2.BDTIME)>30, DATEDIFF(CURRENT_DATE, b2.BDTIME)*0.2,NULL)) from BORROWS b1, BORROWING b2 ,BRANCH b3 WHERE b1.BOR_NO=b2.BOR_NO and b1.BID = b3.BID Group By b3.BID"
try:
cursor=conn.cursor()
cursor.execute(QueryString)
result= cursor.fetchall()
resultString=""
for r in result:
resultString+="\n"+str(r)
except BaseException as e:
resultString="Some Error Occured. Could not fetch Search Results. "+ str(e)
cursor=None
self.output2.insert(END, resultString)
def getNBorrowed(self):
self.output2.delete(0.0,END)
N = self.t2q2SearchQuery_textBox1.get()
QueryString = "Select b.DOCID , d.TITLE, count(b.BOR_NO) from BORROWS b, DOCUMENT d Where b.DOCID= d.DOCID GROUP BY d.DOCID ORDER BY count(b.BOR_NO) desc LIMIT "+N
try:
cursor=conn.cursor()
cursor.execute(QueryString)
result= cursor.fetchall()
resultString=""
for r in result:
resultString+="\n"+str(r)
except BaseException as e:
resultString="Some Error Occured. Could not fetch Search Results. "+ str(e)
cursor=None
self.output2.insert(END, resultString)
class AddReader(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
self.output3 = Text(self, width=75, height=20, wrap=WORD)
t2q1label6=Label(self, text="###### Add a Reader Details ######" )
t2q1label6.pack()
t2q1label7=Label(self, text="Reader Type " )
t2q1label7.pack()
self.Rtype = Entry(self, width =20 )
self.Rtype.pack()
t2q1label8=Label(self, text="Reader Name" )
t2q1label8.pack()
self.RName = Entry(self, width =20 )
self.RName.pack()
t2q1label9=Label(self, text="Reader Address" )
t2q1label9.pack()
self.RAddress = Entry(self, width =20 )
self.RAddress.pack()
t2q1label10=Label(self, text="Reader Phone number" )
t2q1label10.pack()
self.RPNo = Entry(self, width =20 )
self.RPNo.pack()
self.t2q1btn1=Button (self, text="Add Document", width =10,height=2 ,command=self.addReaderDetails)
self.t2q1btn1.pack()
self.output3.pack()
back2=Button (self, text="Exit", width =10,height=2,command=lambda:controller.show_frame(AdminPage))
back2.pack()
ttk.Separator(self).pack()
def addReaderDetails(self):
self.output3.delete(0.0,END)
type = self.Rtype.get()
name = self.RName.get()
address = self.RAddress.get()
Pno = self.RPNo.get()
QueryString="Insert into reader(RTYPE,RNAME,RADDRESS,PHONE_NO) values(\'"+type+"\',\'"+name+"\',\'"+address+"\',"+Pno+")"
try:
cursor=conn.cursor()
cursor.execute(QueryString)
conn.commit()
resultString="Inserted"
except BaseException as e:
resultString="Some Error Occured. Could not fetch Search Results. "+ str(e)
cursor=None
self.output3.insert(END, resultString)
app=FirstScreen()
app.mainloop()
| 907dca9084a2aff9fcdd626dc2c4de3f3044697d | [
"Markdown",
"SQL",
"Python"
] | 3 | Markdown | FrancisDcruz/CS631 | 73cb3c56d5a9242f95a12cabaa31e7173d0c2026 | f0cfffdb60e77d5967c19d17fbfb83671cf7da6e |
refs/heads/master | <repo_name>sekretarot/eenbiertjegraag<file_sep>/e2e/app.e2e-spec.ts
import { EenbiertjegraagPage } from './app.po';
describe('eenbiertjegraag App', () => {
let page: EenbiertjegraagPage;
beforeEach(() => {
page = new EenbiertjegraagPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('Welcome to app!!');
});
});
| 44594587cd8ee99e468b9721898e84a6292c08fc | [
"TypeScript"
] | 1 | TypeScript | sekretarot/eenbiertjegraag | 67663619bff5ef3fb5fa854c4c8e3d1da14fddff | ef5dcbd76d33f36ad0159430c1f0d2569ca3fda7 |
refs/heads/master | <repo_name>DaisukeChen/HalalTokyo<file_sep>/HalalTokyo/app/controllers/reviews_controller.rb
class ReviewsController < ApplicationController
before_action :authenticate_user!, only: :new
def new
@restaurant = Restaurant.find(params[:restaurant_id])
@review = Review.new
end
def create
Review.create(create_params)
redirect_to controller: :restaurants, action: :index
end
private
def create_params
params.require(:review).permit(:rate, :review).merge(restaurant_id: params[:restaurant_id], user_id: current_user.id)
end
end
<file_sep>/HalalTokyo/db/migrate/20151112074648_add_image_url_to_restaurants.rb
class AddImageUrlToRestaurants < ActiveRecord::Migration
def change
add_column :restaurants, :image_url2, :text
add_column :restaurants, :image_url3, :text
add_column :restaurants, :image_url4, :text
add_column :restaurants, :image_url5, :text
end
end
<file_sep>/HalalTokyo/app/controllers/ranking_controller.rb
class RankingController < ApplicationController
layout 'review_site'
before_action :ranking
def ranking
restaurant_ids = Review.group(:restaurant_id).order('count_restaurant_id DESC').limit(5).count(:restaurant_id).keys
@ranking = restaurant_ids.map {|id| Restaurant.find(id)}
end
end
<file_sep>/HalalTokyo/config/routes.rb
Rails.application.routes.draw do
devise_for :users
resources :users, only: :show
resources :restaurants, only: [:show, :new, :create] do
resources :reviews, only: [:new, :create]
collection do
get 'search'
end
end
root 'restaurants#index'
end<file_sep>/HalalTokyo/db/migrate/20151112063053_create_restaurants.rb
class CreateRestaurants < ActiveRecord::Migration
def change
create_table :restaurants do |t|
t.string :name
t.text :detail
t.text :open_hours
t.text :close
t.text :address
t.text :image_url
t.text :phone
t.text :email
t.text :web_url
t.timestamps
end
end
end
<file_sep>/HalalTokyo/app/models/scraping.rb
require 'mechanize'
def scraping_image(link)
agent = Mechanize.new
page = agent.get(link)
image_url = page.at<file_sep>/map/app/models/cicada.rb
class Cicada < ActiveRecord::Base
geocoded_by :latitude, :longtitude
after_validation :geocode
end
<file_sep>/README.md
# HalalTokyo
restaurant review application for muslim
this application have created by using Ruby on Rails.
It's so simple application,yet I believe this will be helpful for muslim
he/she live in Tokyo or visit as tourist.
User can leave their comment of each restaurant if they sign up their account.
<file_sep>/HalalTokyo/app/controllers/restaurants_controller.rb
class RestaurantsController < RankingController
before_action :authenticate_user!, only: :search
def index
@restaurants = Restaurant.order('id ASC').limit(30)
end
def show
@restaurant = Restaurant.find(params[:id])
@hash = Gmaps4rails.build_markers(@restaurant) do |cicada, marker|
marker.lat cicada.latitude
marker.lng cicada.longtitude
marker.infowindow cicada.detail
marker.json({ title: cicada.name })
end
end
def search
@restaurants = Restaurant.where('name LIKE(?)',"%#{params[:keyword]}%").limit(20)
end
def new
end
def create
Restaurant.create(name: restaurant_params[:name],image_url: restaurant_params[:image_url],web_url: restaurant_params[:web_url],detail: restaurant_params[:detail])
redirect_to controller: :restaurants, action: :index
end
private
def restaurant_params
params.permit(:name, :image_url ,:web_url ,:detail)
end
end
| ff0a4318faf5f445d0627a8c256d959c2bf7b8a7 | [
"Markdown",
"Ruby"
] | 9 | Ruby | DaisukeChen/HalalTokyo | 561b2e67c746e8cab4a394395add1c03e0591221 | a74a0cf585895d6dae86bb2878e972b212317d11 |
refs/heads/master | <repo_name>WilliamYang1992/code-example-golang<file_sep>/go.mod
module code-example-golang
go 1.13
require (
github.com/CloudyKit/fastprinter v0.0.0-20170127035650-74b38d55f37a // indirect
github.com/ajg/form v1.5.1 // indirect
github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072 // indirect
github.com/gin-gonic/gin v1.7.0
github.com/go-redis/redis/v7 v7.0.0-beta.4
github.com/go-sql-driver/mysql v1.4.1
github.com/go-xorm/xorm v0.7.9
github.com/google/go-querystring v1.1.0 // indirect
github.com/imkira/go-interpol v1.1.0 // indirect
github.com/k0kubun/colorstring v0.0.0-20150214042306-9440f1994b88 // indirect
github.com/kataras/iris/v12 v12.1.2
github.com/mattn/go-colorable v0.1.12 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.1 // indirect
github.com/moul/http2curl v1.0.0 // indirect
github.com/sergi/go-diff v1.2.0 // indirect
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
github.com/smartystreets/goconvey v1.7.2 // indirect
github.com/valyala/fasthttp v1.36.0 // indirect
github.com/xeipuuv/gojsonschema v1.2.0 // indirect
github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 // indirect
github.com/yudai/gojsondiff v1.0.0 // indirect
github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect
github.com/yudai/pp v2.0.1+incompatible // indirect
google.golang.org/appengine v1.6.5 // indirect
xorm.io/core v0.7.2 // indirect
)
<file_sep>/mysql/mysql_test.go
package mysql
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
)
const (
Host = "127.0.0.1"
Port = 3306
User = "root"
Password = "<PASSWORD>"
DB = "world"
)
func Example() {
driver := "mysql"
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true",
User, Password, Host, Port, DB)
db, err := sql.Open(driver, dsn)
if err != nil {
panic(err)
}
if err = db.Ping(); err != nil {
panic(err)
}
stmt := `SELECT code, name, continent, region, indepYear
FROM country WHERE NAME = ?`
rows, err := db.Query(stmt, "China")
if err != nil {
panic(err)
}
defer rows.Close()
var (
code string
name string
continent string
region string
independenceYear sql.NullInt32
)
for rows.Next() {
if err := rows.Scan(&code, &name, &continent, ®ion,
&independenceYear); err != nil {
panic(err)
}
fmt.Printf("code: %s, name: %s\n", code, name)
}
// Output:
// code: CHN, name: China
}
<file_sep>/cgo/cgo.go
package cgo
// int sum(int a, int b) {
// return a + b;
// }
import "C"
// Sum C 语言实现的加法运算
func Sum(a, b int) int {
return int(C.sum(C.int(a), C.int(b)))
}
<file_sep>/cgo/cgo_test.go
package cgo
import "fmt"
func Example() {
sum := Sum(1, 2)
fmt.Println(sum)
// Output:
// 3
}
<file_sep>/redis/redis_test.go
package redis
import (
"fmt"
"github.com/go-redis/redis/v7"
)
const (
Host = "127.0.0.1"
Port = 6379
Password = ""
DB = 0
)
func Example() {
// 创建 client
client := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%d", Host, Port),
Password: <PASSWORD>,
DB: DB,
})
// 连接测试
if _, err := client.Ping().Result(); err != nil {
panic(err)
}
// 设置键值
key := "key"
val := "value"
err := client.Set(key, val, 0).Err()
if err != nil {
panic(err)
}
// 获取键值
val, err = client.Get(key).Result()
if err != nil {
panic(err)
}
fmt.Printf("%s: %s\n", key, val)
// Output:
// key: value
}
<file_sep>/web/http_test.go
package web
import "net/http"
func Example() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("Hello, world!"))
})
if err := http.ListenAndServe(":8000", mux); err != nil {
panic(err)
}
}
<file_sep>/README.md
# code-example-golang
代码例子,Golang 版本
<file_sep>/web/iris/iris_test.go
package iris
import (
"fmt"
"net/http"
"github.com/kataras/iris/v12"
)
func Example() {
app := iris.New()
app.Get("/", func(ctx iris.Context) {
ctx.StatusCode(http.StatusOK)
_, err := ctx.JSON(iris.Map{"message": "Hello, world!"})
if err != nil {
fmt.Println(err)
}
})
if err := app.Run(iris.Addr(":8000")); err != nil {
panic(err)
}
}
<file_sep>/orm/xorm/xorm_test.go
package xorm
import (
"fmt"
"time"
_ "github.com/go-sql-driver/mysql"
"github.com/go-xorm/xorm"
)
const (
Host = "127.0.0.1"
Port = 3306
User = "root"
Password = "<PASSWORD>"
DB = "world"
)
func Example() {
// 定义 engine,相当于 db
driver := "mysql"
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?parseTime=true",
User, Password, Host, Port, DB)
engine, err := xorm.NewEngine(driver, dsn)
if err != nil {
panic(err)
}
// 定义表结构体
type User struct {
ID int64 `xorm:"id pk autoincr"`
Name string `xorm:"varchar(200) not null unique"`
Created time.Time `xorm:"created not null"`
Updated time.Time `xorm:"updated not null"`
}
// 同步表到数据库中
if err := engine.Sync2(new(User)); err != nil {
panic(err)
}
// 插入数据
user := User{
ID: 1,
Name: "admin",
}
affected, err := engine.Insert(user)
if err != nil {
panic(err)
}
fmt.Printf("affected: %d\n", affected)
// 查询数据库
name := "admin"
has, err := engine.Where("name = ?", name).Desc("id").Get(&user)
fmt.Printf("has: %t\n", has)
fmt.Printf("user: %s\n", user.Name)
// Output:
// affected: 1
// has: true
// user: admin
}
<file_sep>/web/gin/gin_test.go
package gin
import (
"net/http"
"github.com/gin-gonic/gin"
)
func Example() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "Hello, world!"})
})
err := r.Run(":8000")
if err != nil {
panic(err)
}
}
| bc8c9d2dac22ea7dcc76dab6739792fe054fc94e | [
"Go",
"Go Module",
"Markdown"
] | 10 | Go Module | WilliamYang1992/code-example-golang | eb3e911e06dbf5f3d53336a69212d5cdc9c06f61 | 4140a06d24b82c0843ed07715be2a1a73e9e9fa9 |
refs/heads/master | <repo_name>rezakarbasi/Tests-On-Arm-samv71q21-explained<file_sep>/test paye ii/test paye ii/src/init.c
/*
* init.c
*
* Created: 2/6/2016 3:18:47 PM
* Author: Reza_pc
*/
#include <init.h>
void init_Usart (void)
{
ioport_set_pin_dir(PIO_PA21_IDX,IOPORT_DIR_INPUT);
ioport_set_pin_dir(PIO_PB4_IDX,IOPORT_DIR_OUTPUT);
const sam_usart_opt_t usart_console_settings = {
USART_SERIAL_BAUDRATE,
USART_SERIAL_CHAR_LENGTH,
USART_SERIAL_PARITY,
USART_SERIAL_STOP_BIT,
US_MR_CHMODE_NORMAL
};
#if SAM4L
sysclk_enable_peripheral_clock(USART_SERIAL);
#else
sysclk_enable_peripheral_clock(USART_SERIAL_ID);
#endif
usart_init_rs232(USART_SERIAL, &usart_console_settings,
sysclk_get_main_hz()/2);
usart_enable_tx(USART_SERIAL);
usart_enable_rx(USART_SERIAL);
// how to enable an interrupt( use three steps ):use these functions: -usart_enable_interrupt- Then -NVIC_EnableIRQ(USART_SERIAL_IRQ);- & Then add this function void USART_SERIAL_ISR_HANDLER(void)
usart_enable_interrupt(USART_SERIAL, US_IER_RXRDY);
NVIC_EnableIRQ(USART_SERIAL_IRQ);
}
void USART_send(char* in, char number)
{
for (char c=0;c<number;c++)
{
usart_putchar(USART_SERIAL,*(in+c));
}
}<file_sep>/test paye ii/test paye ii/src/Transmitter.c
/*
* Transmitter.c
*
* Created: 2/7/2016 4:28:50 PM
* Author: Reza_pc
*/
#include <Transmitter.h>
// receiving data for 9 robots(SIB = 104 ),why? should be 12 robots !!
// running time : about 560 clk
// time for receiving all packet : 560 * 104 clk = 58240 clk = 1.82 ms
void GetNewData(uint8_t data,int side)
{
if (PCK_Num[side]<HEADER_LENGHT)
{
switch(PCK_Num[side])
{
case 0:
if (data == START_BYTE0)
{
PCK_Num[side]++;
}
break;
case 1:
if (data == START_BYTE1)
PCK_Num[side]++;
else
{
PCK_Num[side] = 0;
}
break;
case 2:
PCK_H[side].SIB = data;
PCK_Num[side]++;
break;
case 3:
PCK_H[side].CHK = data;
PCK_Num[side]++;
break;
}
}
else
{
if (PCK_Num[side] < PCK_H[side].SIB-1)
{
uint8_t id = (PCK_Num[side]-HEADER_LENGHT) / Data_Length ;
switch((PCK_Num[side]-HEADER_LENGHT) % Data_Length)
{
case 0:
Robot_D_tmp[side][id].RID=data;
PCK_H[side].CHK -= data;
break;
case 1:
Robot_D_tmp[side][id].Vx_sp.byte[high]=data;
PCK_H[side].CHK -= data;
break;
case 2:
Robot_D_tmp[side][id].Vx_sp.byte[low]=data;
PCK_H[side].CHK -= data;
break;
case 3:
Robot_D_tmp[side][id].Vy_sp.byte[high]=data;
PCK_H[side].CHK -= data;
break;
case 4:
Robot_D_tmp[side][id].Vy_sp.byte[low]=data;
PCK_H[side].CHK -= data;
break;
case 5:
Robot_D_tmp[side][id].Wr_sp.byte[high]=data;
PCK_H[side].CHK -= data;
break;
case 6:
Robot_D_tmp[side][id].Wr_sp.byte[low]=data;
PCK_H[side].CHK -= data;
break;
case 7:
Robot_D_tmp[side][id].Vx.byte[high]=data;
PCK_H[side].CHK -= data;
break;
case 8:
Robot_D_tmp[side][id].Vx.byte[low]=data;
PCK_H[side].CHK -= data;
break;
case 9:
Robot_D_tmp[side][id].Vy.byte[high]=data;
PCK_H[side].CHK -= data;
break;
case 10:
Robot_D_tmp[side][id].Vy.byte[low]=data;
PCK_H[side].CHK -= data;
break;
case 11:
Robot_D_tmp[side][id].Wr.byte[high]=data;
PCK_H[side].CHK -= data;
break;
case 12:
Robot_D_tmp[side][id].Wr.byte[low]=data;
PCK_H[side].CHK -= data;
break;
case 13:
Robot_D_tmp[side][id].alpha.byte[high]=data;
PCK_H[side].CHK -= data;
break;
case 14:
Robot_D_tmp[side][id].alpha.byte[low]=data;
PCK_H[side].CHK -= data;
break;
case 15:
Robot_D_tmp[side][id].KICK=data;
PCK_H[side].CHK -= data;
break;
case 16:
Robot_D_tmp[side][id].CHIP=data;
PCK_H[side].CHK -= data;
break;
case 17:
Robot_D_tmp[side][id].SPIN=data;
PCK_H[side].CHK -= data;
break;
}
PCK_Num[side]++;
}
else
{
if (PCK_H[side].CHK == 0 && data == STOP_BYTE) //// !!!!!!!???????
{
uint8_t number_of_robots = (PCK_H[side].SIB - HEADER_LENGHT - STOP_BYTE_SIZE)/Data_Length ; //////// !!!!!!!!!????
for (uint8_t i=0;i<number_of_robots;i++) //////////////// !!!!!!!!?????????
{
if (Robot_D_tmp[side][i].RID != 255)
{
Buf_Tx[side][Robot_D_tmp[side][i].RID][ 0] = Robot_D_tmp[side][i].RID ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][ 1] = Robot_D_tmp[side][i].Vx_sp.byte[high] ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][ 2] = Robot_D_tmp[side][i].Vx_sp.byte[low] ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][ 3] = Robot_D_tmp[side][i].Vy_sp.byte[high] ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][ 4] = Robot_D_tmp[side][i].Vy_sp.byte[low] ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][ 5] = Robot_D_tmp[side][i].Wr_sp.byte[high] ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][ 6] = Robot_D_tmp[side][i].Wr_sp.byte[low] ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][ 7] = Robot_D_tmp[side][i].Vx.byte[high] ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][ 8] = Robot_D_tmp[side][i].Vx.byte[low] ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][ 9] = Robot_D_tmp[side][i].Vy.byte[high] ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][10] = Robot_D_tmp[side][i].Vy.byte[low] ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][11] = Robot_D_tmp[side][i].Wr.byte[high] ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][12] = Robot_D_tmp[side][i].Wr.byte[low] ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][13] = Robot_D_tmp[side][i].alpha.byte[high] ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][14] = Robot_D_tmp[side][i].alpha.byte[low] ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][15] = Robot_D_tmp[side][i].KICK ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][16] = Robot_D_tmp[side][i].CHIP ;
Buf_Tx[side][Robot_D_tmp[side][i].RID][17] = Robot_D_tmp[side][i].SPIN ;
pck_timeout[side][Robot_D_tmp[side][i].RID]=0;
}
}
}
PCK_Num[side] = 0;
}
}
}<file_sep>/test paye ii/test paye ii/src/Transmitter.h
/*
* Transmitter.h
*
* Created: 2/7/2016 4:28:29 PM
* Author: Reza_pc
*/
#ifndef TRANSMITTER_H_
#define TRANSMITTER_H_
#include <stdio.h>
struct PCK_Header
{
uint8_t SIB; /// size in byte
uint8_t CHK; /// check sum
};
union Motor_Speed
{
char Bytes[2];
int16_t Speed;
};
typedef union High_Low{
uint8_t byte[2] ;
int16_t full ;
} HL;
struct Robot_Data
{
uint8_t RID ; //robot ID
HL Vx_sp ;
HL Vy_sp ;
HL Wr_sp ;
HL Vx ;
HL Vy ;
HL Wr ;
HL alpha ;
uint8_t KICK ;
uint8_t CHIP ;
uint8_t SPIN ;
};
struct PCK_Send_Header
{
uint8_t SIB;
uint8_t CHK;
uint8_t RID;
};
#define _Buffer_Size 32
#define HEADER_LENGHT 4
#define STOP_BYTE_SIZE 1
#define Data_Length 18 // old length 11
#define Max_Robot 12
#define START_BYTE0 0xA5 /////////// it was 0xA5
#define START_BYTE1 0x5A /////////// it was 0x5A
#define STOP_BYTE 0x80 /////////// it was 0x80
#define R 0
#define L 1
#define high 1
#define low 0
///// transmitter
char Buf_Tx[2][Max_Robot][_Buffer_Size];
uint16_t pck_timeout[2][Max_Robot];
struct PCK_Header PCK_H[2];
struct Robot_Data Robot_D_tmp[2][Max_Robot];
uint8_t PCK_Num[2];
void GetNewData(uint8_t data,int side);
#endif /* TRANSMITTER_H_ */<file_sep>/test paye ii/test paye ii/src/main.c
#include <asf.h>
#include "compiler.h"
#include "pio.h"
#include <string.h>
#include <init.h>
#include <Transmitter.h>
void USART_SERIAL_ISR_HANDLER(void);
char a;
///// help for start an interrupt in init.c
int main (void)
{
sysclk_init();
ioport_init();
board_init();
init_Usart();
ioport_set_pin_dir(MY_LED, IOPORT_DIR_OUTPUT);
ioport_set_pin_level(MY_LED,0);
PCK_Num[0]=0;
PCK_Num[1]=0;
USART_send("salam\r",6);
while (1)
{
delay_ms(10);
}
}
void USART_SERIAL_ISR_HANDLER(void)
{
usart_getchar(USART_SERIAL,&a);
ioport_toggle_pin_level(MY_LED);
usart_putchar(USART_SERIAL,a);
}
<file_sep>/test paye ii/test paye ii/src/init.h
/*
* init.h
*
* Created: 2/6/2016 3:19:24 PM
* Author: Reza_pc
*/
#ifndef INIT_H_
#define INIT_H_
#include <asf.h>
#include "pio.h"
#include <string.h>
#include <stdio.h>
#define MY_LED IOPORT_CREATE_PIN(PIOA, 23)
#define button PIO_PA9_IDX
#define USART_SERIAL USART1
#define USART_SERIAL_ID ID_USART1
#define USART_SERIAL_ISR_HANDLER USART1_Handler
#define USART_SERIAL_BAUDRATE 9600
#define USART_SERIAL_CHAR_LENGTH US_MR_CHRL_8_BIT
#define USART_SERIAL_PARITY US_MR_PAR_NO
#define USART_SERIAL_STOP_BIT US_MR_NBSTOP_1_BIT
#define USART_SERIAL_IRQ USART1_IRQn
void init_Usart (void);
void USART_send(char* in, char number);
#endif /* INIT_H_ */
| f578d4b56bf9eede0fbe98788c693ded763c0236 | [
"C"
] | 5 | C | rezakarbasi/Tests-On-Arm-samv71q21-explained | 028ffc58824216c6de7e6ab4277791ead7061f0e | 808e09fbde0c5d9d4b46f4e59e5f160ae49c4cb3 |
refs/heads/main | <file_sep>/*
REGRAS DO JOGO:
- O jogo tem 2 jogadores, jogando em rodadas
- Em cada jogada, um jogador lança um dado quantas vezes quiser. Cada resultado é adicionado à sua pontuação ROUND
- MAS, se o jogador tirar 1, toda a pontuação da RODADA será perdida. Depois disso, é a vez do próximo jogador
- O jogador pode escolher 'Manter', o que significa que sua pontuação ROUND é adicionada à sua pontuação GLBAL. Depois disso, é a vez do próximo jogador
- O primeiro jogador a atingir 100 pontos na pontuação GLOBAL vence o jogo
*/
var scores, roundScore, activePlayer, gamePlaying;
init();
var lastDice;
document.querySelector('.btn-roll').addEventListener('click', function() {
if(gamePlaying) {
// 1. Colocar números de forma aleatória
var dice1 = Math.floor(Math.random() * 6) + 1;
var dice2 = Math.floor(Math.random() * 6) + 1;
//2. Mostra os resultados
document.getElementById('dice-1').style.display = 'block';
document.getElementById('dice-2').style.display = 'block';
document.getElementById('dice-1').src = 'dice-' + dice1 + '.png';
document.getElementById('dice-2').src = 'dice-' + dice2 + '.png';
//3. Atualiza a pontuação da rodada se o número lançado NÃO for 1
if (dice1 !== 1 && dice2 !== 1) {
//soma valor
roundScore += dice1 + dice2;
document.querySelector('#current-' + activePlayer).textContent = roundScore;
} else {
//jogador seguinte
nextPlayer();
}
}
});
document.querySelector('.btn-hold').addEventListener('click', function() {
if (gamePlaying) {
// Adicionar pontuação atual à pontuação GERAL
scores[activePlayer] += roundScore;
document.querySelector('#score-' + activePlayer).textContent = scores[activePlayer];
var input = document.querySelector('.final-score').value;
var winningScore;
if(input) {
winningScore = input;
} else {
winningScore = 100;
}
// Verifica se jogador venceu o jogo
if (scores[activePlayer] >= winningScore) {
document.querySelector('#name-' + activePlayer).textContent = 'Winner!';
document.getElementById('dice-1').style.display = 'none';
document.getElementById('dice-2').style.display = 'none';
document.querySelector('.player-' + activePlayer + '-panel').classList.add('winner');
document.querySelector('.player-' + activePlayer + '-panel').classList.remove('active');
gamePlaying = false;
} else {
//jogador seguinte
nextPlayer();
}
}
});
function nextPlayer() {
//jogador seguinte
activePlayer === 0 ? activePlayer = 1 : activePlayer = 0;
roundScore = 0;
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.querySelector('.player-0-panel').classList.toggle('active');
document.querySelector('.player-1-panel').classList.toggle('active');
document.getElementById('dice-1').style.display = 'none';
document.getElementById('dice-2').style.display = 'none';
}
document.querySelector('.btn-new').addEventListener('click', init);
function init() {
scores = [0, 0];
activePlayer = 0;
roundScore = 0;
gamePlaying = true;
document.getElementById('dice-1').style.display = 'none';
document.getElementById('dice-2').style.display = 'none';
document.getElementById('score-0').textContent = '0';
document.getElementById('score-1').textContent = '0';
document.getElementById('current-0').textContent = '0';
document.getElementById('current-1').textContent = '0';
document.getElementById('name-0').textContent = 'Player 1';
document.getElementById('name-1').textContent = 'Player 2';
document.querySelector('.player-0-panel').classList.remove('winner');
document.querySelector('.player-1-panel').classList.remove('winner');
document.querySelector('.player-0-panel').classList.remove('active');
document.querySelector('.player-1-panel').classList.remove('active');
document.querySelector('.player-0-panel').classList.add('active');
} | b793fb9161d5a87c9b3837c00a626cfa0ce58164 | [
"JavaScript"
] | 1 | JavaScript | RicardoSousa84/Jogo-dos-dados | d3bb229c91025949b94af3f6f9c66156e831b213 | 7404ec348a12440840d4633cbe4a9b857476593d |
refs/heads/master | <file_sep>package com.rodrigo.mf0966.repository;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response.Status;
import com.rodrigo.mf0966.controller.Globales;
import com.rodrigo.mf0966.models.Alumno;
import com.rodrigo.mf0966.models.Profesor;
@Path("/alumnos")
@Produces("application/json")
@Consumes("application/json")
public class AlumnoREST {
private static final Logger LOGGER = Logger.getLogger(AlumnoREST.class.getCanonicalName());
@Context
private ServletContext context;
static {
LOGGER.info("Generando JAX-RS de Alumnos");
}
@GET
public Iterable<Alumno> getAll() {
LOGGER.info("...generando un Get All!");
LOGGER.info(context.toString());
Iterable<Alumno> alumnos = Globales.daoAlumno.getAll();
return alumnos;
}
@GET
@Path("/{id}")
public Alumno getById(@PathParam("id") Integer id) {
if (id != null) {
LOGGER.info("...generando Alumnos Get_By_Id - id:" + id);
Alumno alumnos = Globales.daoAlumno.getById(id);
return alumnos;
}
LOGGER.warning("*** Atención ***...El id del Alumno que buscas es NULL!");
return null;
}
@POST
public Alumno insert(Alumno alumno) {
LOGGER.info("...ejecutando POST/Insert de Alumno: " + alumno);
Globales.daoAlumno.insert(alumno);
return alumno;
}
@PUT
@Path("/{id}")
public Alumno update(@PathParam("id") Integer id, Alumno alumno) {
LOGGER.info("...ejecutando PUT/Update: (" + id + ", " + alumno + ")");
if (id != alumno.getId()) {
LOGGER.warning("No concuerdan los id: " + id + ", " + alumno);
throw new WebApplicationException("No concuerdan los id", Status.BAD_REQUEST);
}
if (alumno.getId() == null) {
LOGGER.warning("No se ha encontrado el id a modificar: " + id + ", " + alumno);
throw new WebApplicationException("No se ha encontrado el id a modificar", Status.NOT_FOUND);
}
Globales.daoAlumno.update(alumno);
return alumno;
}
@DELETE
@Path("/{id}")
public String delete(@PathParam("id") Integer id) {
LOGGER.info("Has Borrado/Desactivado el Profesor con id: " + id);
Globales.daoAlumno.delete(id);
return "{}";
}
}
<file_sep>package com.rodrigo.mf0966.repository;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import com.rodrigo.mf0966.models.Alumno;
import com.rodrigo.mf0966.models.Imparticion;
import com.rodrigo.mf0966.models.Resena;
public class ResenaSQL implements Dao<Resena>{
private static final String SQL_GET_ALL = "CALL Resenia_GET_All()";
private static final String SQL_GET_ID = "CALL Resenia_GET_ById(?)";
private static final String SQL_INSERT = "CALL Resenia_POST_Insert(?,?,?,?,?)";
private static final String SQL_UPDATE = "CALL Resenia_PUT_Update(?,?,?,?,?)";
private static final String SQL_DELETE = "CALL Resenia_DELETE(?)";
private static String url, usuario, password;
private static DataSource pool;
// "SINGLETON"
private ResenaSQL(String url, String usuario, String password) {
this.url = url;
this.usuario = usuario;
this.password = <PASSWORD>;
}
private static ResenaSQL instancia;
/**
* Se usará para inicializar la instancia
*
* @param url
* @param usuario
* @param password
* @return La instancia
*/
public static ResenaSQL getInstancia(String url, String usuario, String password) {
// Si no existe la instancia...
if (instancia == null) {
// ...la creamos
instancia = new ResenaSQL(url, usuario, password);
// Si existe la instancia, pero sus valores no concuerdan...
} else if (!instancia.url.equals(url) || !instancia.usuario.equals(usuario)
|| !instancia.password.contentEquals(password)) {
// ...lanzar un error
throw new RepositoriosException("No se pueden cambiar los valores de la instancia una vez inicializada");
}
// Devolver la instancia recién creada o la existente (cuyos datos coinciden con
// los que tiene)
return instancia;
}
/**
* Se usará para recuperar la instancia ya existente
*
* @return devuelve la instancia ya existente
*/
public static ResenaSQL getInstancia() {
// Si no existe la instancia...
if (instancia == null) {
// ...no se puede obtener porque no sabemos los datos de URL, usuario y password
throw new RepositoriosException("Necesito que me pases URL, usuario y password");
}
// Si ya existe, se devuelve
return instancia;
}
/**
* Usaremos un pool de conexiones determinado
*
* @return devuelve la instancia del pool de conexiones
*/
public static ResenaSQL getInstancia(String entorno) {
InitialContext initCtx;
try {
initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource dataSource = (DataSource) envCtx.lookup(entorno);
ResenaSQL.pool = dataSource;
if(instancia == null) {
instancia = new ResenaSQL(null, null, null);
}
return instancia;
} catch (NamingException e) {
throw new RepositoriosException("No se ha podido conectar al Pool de conexiones " + entorno);
}
}
// FIN "SINGLETON"
private Connection getConexion() {
try {
if (pool == null) {
new com.mysql.cj.jdbc.Driver();
return DriverManager.getConnection(url, usuario, password);
} else {
return pool.getConnection();
}
} catch (SQLException e) {
System.err
.println("IPARTEK: Error de conexión a la base de datos: " + url + ":" + usuario + ":" + password);
e.printStackTrace();
throw new RepositoriosException("No se ha podido conectar a la base de datos", e);
}
}
@Override
public Iterable<Resena> getAll() {
try (Connection con = getConexion()) {
try (CallableStatement s = con.prepareCall(SQL_GET_ALL)) {
try (ResultSet rs = s.executeQuery()){
ArrayList<Resena> resenias = new ArrayList<>();
//Imparticion imparticion;
Alumno alumno;
Resena resena;
while(rs.next()) {
//imparticion = new Imparticion(rs.getInt("codigo"));
alumno = new Alumno(rs.getInt("codigo"));
resena = new Resena(rs.getInt("codigo"), new Imparticion(rs.getInt("codigo")), alumno, rs.getString("resena"), rs.getTimestamp("fResena"));
resenias.add(resena);
}
return resenias;
} catch (SQLException e) {
throw new RepositoriosException("Error al acceder a los registros", e);
}
} catch (SQLException e) {
throw new RepositoriosException("Error al crear la sentencia", e);
}
} catch (SQLException e) {
throw new RepositoriosException("Error al conectar", e);
}
}
@Override
public Resena getById(Integer id) {
try (Connection con = getConexion()) {
try (PreparedStatement ps = con.prepareStatement(SQL_GET_ID)) {
ps.setInt(1, id);
try (ResultSet rs = ps.executeQuery()) {
Imparticion imparticion;
Alumno alumno;
Resena resena = null;
if (rs.next()) {
imparticion = new Imparticion(rs.getInt("codigo"));
alumno = new Alumno(rs.getInt("codigo"));
resena = new Resena(rs.getInt("codigo"), imparticion, alumno, rs.getString("resena"), rs.getTimestamp("fResena"));
}
return resena;
} catch (SQLException e) {
throw new RepositoriosException("Error al acceder a los registros", e);
}
} catch (SQLException e) {
throw new RepositoriosException("Error al crear la sentencia", e);
}
} catch (SQLException e) {
throw new RepositoriosException("Error al conectar", e);
}
}
@Override
public Integer insert(Resena objeto) {
throw new UnsupportedOperationException("NO ESTA IMPLEMENTADO");
}
@Override
public void update(Resena objeto) {
throw new UnsupportedOperationException("NO ESTA IMPLEMENTADO");
}
@Override
public void delete(Integer id) {
throw new UnsupportedOperationException("NO ESTA IMPLEMENTADO");
}
}
<file_sep>package com.rodrigo.mf0966.repository;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response.Status;
import com.rodrigo.mf0966.controller.Globales;
import com.rodrigo.mf0966.models.Profesor;
@Path("/profesores")
@Produces("application/json")
@Consumes("application/json")
public class ProfesorREST {
private static final Logger LOGGER = Logger.getLogger(ProfesorREST.class.getCanonicalName());
@Context
private ServletContext context;
static {
LOGGER.info("Generando JAX-RS de Profesores");
}
@GET
public Iterable<Profesor> getAll() {
LOGGER.info("Get All!");
LOGGER.info(context.toString());
Iterable<Profesor> profesores = Globales.daoProfesor.getAll();
return profesores;
}
@GET
@Path("/{id}")
public Profesor getById(@PathParam("id") Integer id) {
if (id != null) {
LOGGER.info("...generando Profesor Get_By_Id - id:" + id);
Profesor profesor = Globales.daoProfesor.getById(id);
return profesor;
}
LOGGER.warning("*** Atención ***...El id del Profesor que buscas es NULL!");
return null;
}
@POST
public Profesor insert(Profesor profesor) {
LOGGER.info("...ejecutando POST/Insert de Profesor: " + profesor);
Globales.daoProfesor.insert(profesor);
return profesor;
}
@PUT
@Path("/{id}")
public Profesor update(@PathParam("id") Integer id, Profesor profesor) {
LOGGER.info("...ejecutando PUT/Update: (" + id + ", " + profesor + ")");
if (id != profesor.getId()) {
LOGGER.warning("No concuerdan los id: " + id + ", " + profesor);
throw new WebApplicationException("No concuerdan los id", Status.BAD_REQUEST);
}
if (profesor.getId() == null) {
LOGGER.warning("No se ha encontrado el id a modificar: " + id + ", " + profesor);
throw new WebApplicationException("No se ha encontrado el id a modificar", Status.NOT_FOUND);
}
Globales.daoProfesor.update(profesor);
return profesor;
}
@DELETE
@Path("/{id}")
public String delete(@PathParam("id") Integer id) {
LOGGER.info("Has Borrado/Desactivado el Profesor con id: " + id);
Globales.daoProfesor.delete(id);
return "{}";
}
}
<file_sep>package com.rodrigo.mf0966.repository;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response.Status;
import com.rodrigo.mf0966.controller.Globales;
import com.rodrigo.mf0966.models.Curso;
@Path("/cursos")
@Produces("application/json")
@Consumes("application/json")
public class CursoREST {
private static final Logger LOGGER = Logger.getLogger(CursoREST.class.getCanonicalName());
@Context
private ServletContext context;
@GET
public Iterable<Curso> getAll() {
LOGGER.info("Get All!");
LOGGER.info(context.toString());
Iterable<Curso> cursos = Globales.daoCurso.getAll();
return cursos;
}
@GET
@Path("/{id}")
public Curso getById(@PathParam("id") Integer id) {
LOGGER.info("getById(" + id + ")");
if (id != null) {
Curso curso = Globales.daoCurso.getById(id);
return curso;
}
return null;
}
@POST
public Curso insert(Curso curso) {
Globales.daoCurso.insert(curso);
return curso;
}
@PUT
@Path("/{id}")
public Curso update(@PathParam("id") Integer id, Curso curso) {
LOGGER.info("update(" + id + ", " + curso + ")");
if (id != curso.getId()) {
LOGGER.warning("No concuerdan los id: " + id + ", " + curso);
throw new WebApplicationException("No concuerdan los id", Status.BAD_REQUEST);
}
if (curso.getId() == null) {
LOGGER.warning("No se ha encontrado el id a modificar: " + id + ", " + curso);
throw new WebApplicationException("No se ha encontrado el id a modificar", Status.NOT_FOUND);
}
Globales.daoCurso.update(curso);
return curso;
}
@DELETE
@Path("/{id}")
public String delete(@PathParam("id") Integer id) {
Globales.daoCurso.delete(id);
return "{}";
}
}
<file_sep>CREATE DATABASE IF NOT EXISTS `mf0966_3` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_bin */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `mf0966_3`;
-- MySQL dump 10.13 Distrib 8.0.19, for Win64 (x86_64)
--
-- Host: 127.0.0.1 Database: mf0966_3
-- ------------------------------------------------------
-- Server version 8.0.19
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `resena`
--
DROP TABLE IF EXISTS `resena`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `resena` (
`codigo` int NOT NULL AUTO_INCREMENT,
`cod_imparticion` int NOT NULL,
`cod_alumno` int NOT NULL,
`resena` text COLLATE utf8_bin NOT NULL,
`fResena` datetime DEFAULT NULL,
PRIMARY KEY (`codigo`),
KEY `cod_imparticion_idx` (`cod_imparticion`),
KEY `cod_alumno_idx` (`cod_alumno`),
CONSTRAINT `cod_alumno` FOREIGN KEY (`cod_alumno`) REFERENCES `alumno` (`codigo`),
CONSTRAINT `cod_imparticion` FOREIGN KEY (`cod_imparticion`) REFERENCES `imparticion` (`codigo`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `resena`
--
LOCK TABLES `resena` WRITE;
/*!40000 ALTER TABLE `resena` DISABLE KEYS */;
INSERT INTO `resena` VALUES (1,9,2,'Este curso es inigualable, jamás en la vida he visto al mejor.','2020-03-22 00:00:00'),(2,9,4,'Noticia y comentario, generalmente de corta extensión, que se hace sobre una obra literaria, de arte o científica y se publica en un periódico o en una revista.','2020-03-22 00:00:00'),(3,50,4,'Se suele usar para referirse a un acto cultural y deportivo o en la crítica literaria y artística. En una reseña se hace un recuento del contenido de la obra o evento, ...','2020-03-26 00:00:00');
/*!40000 ALTER TABLE `resena` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2020-03-26 13:51:30
<file_sep>package com.rodrigo.mf0966.repository;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response.Status;
import com.rodrigo.mf0966.controller.Globales;
import com.rodrigo.mf0966.models.Cliente;
import com.rodrigo.mf0966.models.Profesor;
@Path("/clientes")
@Produces("application/json")
@Consumes("application/json")
public class ClienteREST {
private static final Logger LOGGER = Logger.getLogger(AlumnoREST.class.getCanonicalName());
@Context
private ServletContext context;
static {
LOGGER.info("Generando JAX-RS de Clientes");
}
@GET
public Iterable<Cliente> getAll() {
LOGGER.info("...ejecutando Clientes Get_All!");
LOGGER.info(context.toString());
Iterable<Cliente> clientes = Globales.daoCliente.getAll();
return clientes;
}
@GET
@Path("/{id}")
public Cliente getById(@PathParam("id") Integer id) {
if (id != null) {
LOGGER.info("...ejecutando Clientes Get_By_Id - id:" + id);
Cliente clientes = Globales.daoCliente.getById(id);
return clientes;
}
LOGGER.warning("*** Atención ***...El id del Cliente que buscas es NULL!");
return null;
}
@POST
public Cliente insert(Cliente cliente) {
LOGGER.info("...ejecutando POST/Insert de Cliente: " + cliente);
Globales.daoCliente.insert(cliente);
return cliente;
}
@PUT
@Path("/{id}")
public Cliente update(@PathParam("id") Integer id, Cliente cliente) {
LOGGER.info("...ejecutando PUT/Update: (" + id + ", " + cliente + ")");
if (id != cliente.getId()) {
LOGGER.warning("No concuerdan los id: " + id + ", " + cliente);
throw new WebApplicationException("No concuerdan los id", Status.BAD_REQUEST);
}
if (cliente.getId() == null) {
LOGGER.warning("No se ha encontrado el id a modificar: " + id + ", " + cliente);
throw new WebApplicationException("No se ha encontrado el id a modificar", Status.NOT_FOUND);
}
Globales.daoCliente.update(cliente);
return cliente;
}
@DELETE
@Path("/{id}")
public String delete(@PathParam("id") Integer id) {
LOGGER.info("Has Borrado/Desactivado el Cliente: " + id);
Globales.daoCliente.delete(id);
return "{}";
}
}
<file_sep>CREATE DATABASE IF NOT EXISTS `mf0966_3` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_bin */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `mf0966_3`;
-- MySQL dump 10.13 Distrib 8.0.19, for Win64 (x86_64)
--
-- Host: 127.0.0.1 Database: mf0966_3
-- ------------------------------------------------------
-- Server version 8.0.19
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Dumping events for database 'mf0966_3'
--
--
-- Dumping routines for database 'mf0966_3'
--
/*!50003 DROP PROCEDURE IF EXISTS `alumnoCreate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`admin`@`%` PROCEDURE `alumnoCreate`(IN `papellidos` VARCHAR(250), IN `pcodigopostal` INT(5), IN `pdireccion` VARCHAR(250), IN `pdni` VARCHAR(9), IN `pemail` VARCHAR(150), IN `pfNacimiento` DATE, IN `pnHermanos` INT(2), IN `pnombre` VARCHAR(50), IN `ppoblacion` VARCHAR(150), IN `ptelefono` INT(9), OUT `pcodigo` INT)
BEGIN
INSERT INTO alumno(nombre,apellidos,dni,email,direccion,codigopostal,poblacion,fNacimiento,telefono,nHermanos)
VALUES(LOWER(pnombre),LOWER(papellidos),LOWER(pdni),LOWER(pemail),LOWER(pdireccion),pcodigopostal,LOWER(ppoblacion),pfNacimiento,ptelefono,pnHermanos);
SET pcodigo = LAST_INSERT_ID();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `alumnoDelete` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`admin`@`%` PROCEDURE `alumnoDelete`(IN `pcodigo` INT)
NO SQL
BEGIN
DELETE FROM alumno WHERE codigo = pcodigo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `alumnogetAll` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`admin`@`%` PROCEDURE `alumnogetAll`()
NO SQL
BEGIN
SELECT `codigo` as alumnocodigo, `nombre` as alumnonombre, `apellidos` as alumnoapellidos, `fNacimiento` as alumnofnacimiento, `direccion` as alumnodireccion, `poblacion` as alumnopoblacion, `codigopostal` as alumnocodigopostal, `telefono` as alumnotelefono, `email` as alumnoemail, `dni` as alumnodni, `nHermanos` as alumnonhermanos, `activo` as alumnoactivo
FROM `alumno`
WHERE alumno.activo = true;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `alumnogetByCurso` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `alumnogetByCurso`(IN `pcursocodigo` INT)
BEGIN
SELECT a.`codigo` as alumnocodigo, a.`nombre` as alumnonombre, a.`apellidos` as alumnoapellidos, a.`fNacimiento` as alumnofnacimiento, a.`direccion` as alumnodireccion, a.`poblacion` as alumnopoblacion, a.`codigopostal` as alumnocodigopostal, a.`telefono` as alumnotelefono, a.`email` as alumnoemail, a.`dni` as alumnodni, a.`nHermanos` as alumnonhermanos, a.`activo` as alumnoactivo
FROM `alumno` as a
inner join imparticion as i ON i.alumno_codigo = a.codigo
inner join curso as c ON i.curso_codigo = c.codigo
WHERE c.codigo = pcursocodigo
group by a.codigo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `alumnogetByDni` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `alumnogetByDni`(IN `pdni` VARCHAR(9))
BEGIN
SELECT `codigo` as alumnocodigo, `nombre` as alumnonombre, `apellidos` as alumnoapellidos, `fNacimiento` as alumnofnacimiento, `direccion` as alumnodireccion, `poblacion` as alumnopoblacion, `codigopostal` as alumnocodigopostal, `telefono` as alumnotelefono, `email` as alumnoemail, `dni` as alumnodni, `nHermanos` as alumnonhermanos, `activo` as alumnoactivo
FROM `alumno`
WHERE dni = pdni;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `alumnogetById` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`admin`@`%` PROCEDURE `alumnogetById`(IN `pcodigo` INT)
NO SQL
BEGIN
SELECT `codigo` as alumnocodigo, `nombre` as alumnonombre, `apellidos` as alumnoapellidos, `fNacimiento` as alumnofnacimiento, `direccion` as alumnodireccion, `poblacion` as alumnopoblacion, `codigopostal` as alumnocodigopostal, `telefono` as alumnotelefono, `email` as alumnoemail, `dni` as alumnodni, `nHermanos` as alumnonhermanos, `activo` as alumnoactivo
FROM `alumno`
WHERE codigo = pcodigo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `alumnoInforme` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `alumnoInforme`(IN `pcodigo` INT)
BEGIN
SELECT a.`codigo` as alumnocodigo, a.`nombre` as alumnonombre, a.`apellidos` as alumnoapellidos, a.`fNacimiento` as alumnofnacimiento, a.`direccion` as alumnodireccion, a.`poblacion` as alumnopoblacion, a.`codigopostal` as alumnocodigopostal, a.`telefono` as alumnotelefono, a.`email` as alumnoemail, a.`dni` as alumnodni, `nHermanos` as alumnonhermanos, a.`activo` as alumnoactivo,
c.codigo as cursocodigo,c.nombre as cursonombre,
c.identificador as cursoidentificador, c.fInicio as cursofinicio, c.fFin as cursoffin,c.nHoras as cursonhoras,c.precio as cursoprecio
/*,SUM(cd.precio) as preciocurso*/
FROM alumno as a
LEFT JOIN imparticion as i ON i.alumno_codigo = a.codigo
LEFT JOIN curso as c ON c.codigo = i.curso_codigo
WHERE a.codigo = pcodigo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `alumnoUpdate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`admin`@`%` PROCEDURE `alumnoUpdate`(IN `papellidos` VARCHAR(250), IN `pcodigo` INT, IN `pcodigopostal` INT(5), IN `pdireccion` VARCHAR(250), IN `pdni` VARCHAR(9), IN `pemail` VARCHAR(150), IN `pfNacimiento` DATE, IN `pnHermanos` INT(2), IN `pnombre` VARCHAR(150), IN `ppoblacion` VARCHAR(150), IN `ptelefono` INT(9))
NO SQL
BEGIN
UPDATE alumno
SET nombre = LOWER(pnombre),apellidos = LOWER(papellidos), dni = LOWER(pdni),email = LOWER(pemail),direccion=LOWER(pdireccion),codigopostal=pcodigopostal,poblacion=LOWER(ppoblacion),fNacimiento=pfNacimiento,telefono=ptelefono,nHermanos=pnHermanos
WHERE codigo = pcodigo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `alumno_DELETE` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `alumno_DELETE`(IN _id INT)
BEGIN
-- DELETE FROM alumno WHERE codigo=_id;
UPDATE alumno
SET activo=FALSE
WHERE codigo=_id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `alumno_GET_All` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `alumno_GET_All`()
BEGIN
SELECT codigo, nombre, apellidos, fNacimiento,direccion, poblacion, codigopostal, telefono, email, dni, nHermanos, activo FROM alumno WHERE activo = TRUE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `alumno_GET_ById` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `alumno_GET_ById`(IN _id INT)
BEGIN
SELECT codigo, nombre, apellidos, fNacimiento,direccion, poblacion, codigopostal, telefono, email, dni, nHermanos, activo FROM alumno WHERE codigo=_id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `alumno_POST_Insert` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `alumno_POST_Insert`(IN _nombre VARCHAR(50), IN _apellidos VARCHAR(250), IN _fNacimiento DATE, IN _direccion VARCHAR(250), IN _poblacion VARCHAR(150), IN _codigopostal INT(5), IN _telefono INT, IN _email VARCHAR(150), IN _dni VARCHAR(9), IN _nHermanos INT, OUT _id INT)
BEGIN
INSERT INTO alumno (nombre, apellidos, fNacimiento, direccion, poblacion, codigopostal, telefono, email, dni, nHermanos)
VALUES (_nombre, _apellidos, _fNacimiento, _direccion, _poblacion, _codigopostal, _telefono, _email, _dni, _nHermanos);
SET _id = LAST_INSERT_ID();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `alumno_PUT_Update` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `alumno_PUT_Update`(IN _id INT, IN _nombre VARCHAR(50), IN _apellidos VARCHAR(250), IN _fNacimiento DATE, IN _direccion VARCHAR(250), IN _poblacion VARCHAR(150), IN _codigopostal INT(5), IN _telefono INT, IN _email VARCHAR(150), IN _dni VARCHAR(9), IN _nHermanos INT)
BEGIN
UPDATE alumno
SET nombre=_nombre, apellidos=_apellidos, fNacimiento=_fNacimiento, direccion=_direccion, poblacion=_poblacion, codigopostal=_codigopostal, telefono=_telefono, email=_email, dni=_dni, nHermanos=_nHermanos
WHERE codigo=_id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clienteCreate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clienteCreate`(IN `pnombre` TEXT, IN `pemail` VARCHAR(150), IN `ptelefono` INT, IN `pdireccion` VARCHAR(150), IN `ppoblacion` VARCHAR(150), IN `pcodigopostal` INT(5), IN `pidentificador` VARCHAR(50), OUT `pcodigo` INT)
BEGIN
INSERT INTO cliente(`nombre`, `email`, `telefono`, `direccion`, `poblacion`, `codigopostal`, `identificador`)
VALUES(LOWER(pnombre),
LOWER(pemail),
ptelefono,
LOWER(pdireccion),
LOWER(poblacion),
codigopostal,
LOWER(pidentificador));
SET pcodigo = LAST_INSERT_ID();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clientegetAll` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`admin`@`%` PROCEDURE `clientegetAll`()
NO SQL
BEGIN
SELECT`codigo` as clientecodigo, `nombre` as clientenombre, `email` as clienteemail, `telefono` as clientetelefono, `direccion` as clientedireccion, `poblacion` as clientepoblacion, `codigopostal` as clientecodigopostal,`identificador` as clienteidentificador,activo as clienteactivo
FROM `cliente`
WHERE cliente.activo = true;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clientegetByIdentificador` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clientegetByIdentificador`(IN `pidentificador` VARCHAR(15))
BEGIN
SELECT`codigo` as clientecodigo, `nombre` as clientenombre, `email` as clienteemail, `telefono` as clientetelefono, `direccion` as clientedireccion, `poblacion` as clientepoblacion, `codigopostal` as clientecodigopostal,`identificador` as clienteidentificador,activo as clienteactivo
FROM `cliente`
WHERE identificador = pidentificador;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clienteInforme` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clienteInforme`(IN `pcodigo` INT)
BEGIN
SELECT c.`codigo` as clientecodigo, c.`nombre` as clientenombre, c.`email` as clienteemail, c.`telefono` as clientetelefono, c.`direccion` as clientedireccion, c.`poblacion` as clientepoblacion, `codigopostal` as clientecodigopostal,c.`identificador` as clienteidentificador,c.activo as clienteactivo, cu.codigo as cursocodigo,cu.nombre as cursonombre,cu.identificador as cursoidentificador, cu.fInicio as cursofinicio,cu.fFin as cursoffin,cu.nhoras as cursonhoras,cu.precio as cursoprecio FROM cliente as c LEFT JOIN curso as cu ON cu.cliente_codigo = c.codigo WHERE c.codigo = pcodigo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `clienteUpdate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `clienteUpdate`(IN `pcodigo` INT, IN `pnombre` VARCHAR(150), IN `pemail` VARCHAR(150), IN `ptelefono` INT(9), IN `pdirecion` VARCHAR(250), IN `ppoblacion` VARCHAR(150), IN `pcodigopostal` INT(5), IN `pidentificador` VARCHAR(15))
BEGIN
UPDATE `cliente`
SET `codigo`=pcodigo,
`nombre`=pnombre,
`email`=pemail,
`telefono`=ptelefono,
`direccion`=pdirecion,
`poblacion`=ppoblacion,
`codigopostal`=pcodigopostal,
`identificador`=pidentificador;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cliente_DELETE` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `cliente_DELETE`(IN _id INT)
BEGIN
-- DELETE FROM cliente WHERE codigo=_id;
UPDATE cliente
SET activo=FALSE
WHERE codigo=_id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cliente_GET_All` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `cliente_GET_All`()
BEGIN
SELECT codigo, nombre, email, telefono, direccion, poblacion, codigopostal, identificador, activo
FROM cliente
WHERE activo = TRUE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cliente_GET_ById` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `cliente_GET_ById`(IN _id INT)
BEGIN
SELECT codigo, nombre, email, telefono, direccion, poblacion, codigopostal, identificador, activo
FROM cliente
WHERE codigo = _id AND activo=TRUE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cliente_POST_Insert` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `cliente_POST_Insert`(IN _nombre TEXT, IN _email VARCHAR(150), IN _telefono INT, IN _direccion VARCHAR(150), IN _poblacion VARCHAR(150), IN _codigopostal INT(5), IN _identificador VARCHAR(50), OUT _id INT)
BEGIN
INSERT INTO cliente (nombre, email, telefono, direccion, poblacion, codigopostal, identificador)
VALUES (_nombre, _email, _telefono, _direccion, _poblacion, _codigopostal, _identificador);
SET _id = LAST_INSERT_ID();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cliente_PUT_Update` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `cliente_PUT_Update`(IN _id INT, IN _nombre TEXT, IN _email VARCHAR(150), IN _telefono INT, IN _direccion VARCHAR(150), IN _poblacion VARCHAR(150), IN _codigopostal INT(5), IN _identificador VARCHAR(50))
BEGIN
UPDATE cliente
SET nombre=_nombre, email=_email, telefono=_telefono, direccion=_direccion, poblacion=_poblacion, codigopostal=_codigopostal, identificador=_identificador
WHERE codigo = _id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cursoAll` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `cursoAll`()
BEGIN
SELECT
c.codigo, c.nombre, c.identificador, c.finicio, c.ffin, c.nhoras, c.temario, c.activo, c.precio,
p.codigo, p.nss, p.nombre, p.apellidos, p.fnacimiento, p.dni, p.direccion, p.poblacion, p.codigopostal, p.telefono, p.email,p.activo, cli.codigo , cli.nombre, cli.email, cli.telefono, cli.identificador, cli.direccion, cli.poblacion, cli.codigopostal, cli.activo
FROM curso c
LEFT JOIN profesor p ON p.codigo = c.profesor_codigo
LEFT JOIN cliente cli ON cli.codigo = c.cliente_codigo
WHERE c.activo = true;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cursoById` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `cursoById`(IN pcodigo INT)
BEGIN
SELECT
c.codigo, c.nombre, c.identificador, c.finicio, c.ffin, c.nhoras, c.temario, c.activo, c.precio,
p.codigo, p.nss, p.nombre, p.apellidos, p.fnacimiento, p.dni, p.direccion, p.poblacion, p.codigopostal, p.telefono, p.email, p.activo, cli.codigo, cli.nombre, cli.email, cli.telefono, cli.identificador, cli.direccion, cli.poblacion, cli.codigopostal, cli.activo, i.codigo,
i.fMatriculacion as imparticionfmatriculacion,
a.codigo, a.nombre, a.apellidos, a.fnacimiento, a.direccion, a.poblacion, a.codigopostal, a.telefono, a.email, a.dni, a.hermanos, a.activo
FROM curso c
INNER JOIN cliente cli ON cli.codigo = c.cliente_codigo
INNER JOIN profesor p ON p.codigo = c.profesor_codigo
INNER JOIN imparticion i on i.curso_codigo = c.codigo
INNER JOIN alumno a ON a.codigo = i.alumno_codigo
WHERE c.codigo = pcodigo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cursoById2` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `cursoById2`(IN pcodigo INT)
BEGIN
SELECT
c.codigo, c.nombre, c.identificador, c.finicio, c.ffin, c.nhoras, c.temario, c.activo, c.precio,
p.codigo, p.nss, p.nombre, p.apellidos, p.fnacimiento, p.dni, p.direccion, p.poblacion, p.codigopostal, p.telefono, p.email,p.activo, cli.codigo , cli.nombre, cli.email, cli.telefono, cli.identificador, cli.direccion, cli.poblacion, cli.codigopostal, cli.activo
FROM curso c
LEFT JOIN profesor p ON p.codigo = c.profesor_codigo
LEFT JOIN cliente cli ON cli.codigo = c.cliente_codigo
WHERE c.codigo = pcodigo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cursocreate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`admin`@`%` PROCEDURE `cursocreate`(IN `pnombre` VARCHAR(50), IN `pidentificador` VARCHAR(50), IN `pfinicio` DATE, IN `pffin` DATE, IN `ptemario` VARCHAR(50), IN `pprecio` DOUBLE(8,2), IN `pcodigo_profesor` INT, IN `pcodigo_cliente` INT, OUT `pcodigo` INT)
NO SQL
BEGIN
INSERT INTO curso(nombre,idenficador,fInicio,fFin,temario,precio,cliente_codigo,profesor_codigo)
VALUES(LOWER(pnombre),LOWER(pidentificador),pfinicio,pffin,LOWER(ptemario),pprecio,pcodigo_profesor,pcodigo_cliente);
SET pcodigo = LAST_INSERT_ID();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cursoDelete` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`admin`@`%` PROCEDURE `cursoDelete`(IN `pcodigo` INT)
NO SQL
BEGIN
UPDATE curso SET activo = false
WHERE codigo = pcodigo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cursogetAll` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `cursogetAll`()
NO SQL
BEGIN
SELECT
c.`codigo` as cursocodigo, c.`nombre` as cursonombre, c.`identificador` as cursoidentificador, c.`fInicio` as cursofinicio, c.`fFin` as cursoffin, c.`nHoras` as cursonhoras, c.`temario` as cursotemario, c.`activo` as cursoactivo, c.`precio` as cursoprecio,
p.`codigo` as profesorcodigo, p.`NSS` as profesornss, p.`nombre` as profesornombre, p.`apellidos` as profesorapellidos, p.`fNacimiento` as profesorfnacimiento, p.`DNI` as profesordni, p.`direccion` as profesordireccion, p.`poblacion` as profesorpoblacion, p.`codigopostal` as profesorcodigopostal, p.`telefono` as profesortelefono, p.`email` as profesoremail,p.activo as profesoractivo, cli.codigo as clientecodigo, cli.`nombre` as clientenombre, cli.`email` as clienteemail, cli.`telefono` as clientetelefono, cli.identificador as clienteidentificador, cli.`direccion` as clientedireccion, cli.`poblacion` as clientepoblacion, cli.`codigopostal` as clientecodigopostal, cli.activo as clienteactivo
FROM curso c
LEFT JOIN profesor p ON p.codigo = c.profesor_codigo
LEFT JOIN cliente cli ON cli.codigo = c.cliente_codigo
WHERE c.activo = true;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cursogetById` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`admin`@`%` PROCEDURE `cursogetById`(IN `pcodigo` INT)
NO SQL
BEGIN
SELECT
c.`codigo` as cursocodigo, c.`nombre` as cursonombre, c.`identificador` as cursoidentificador, c.`fInicio` as cursofinicio, c.`fFin` as cursoffin, c.`nHoras` as cursonhoras, c.`temario` as cursotemario, c.`activo` as cursoactivo, c.`precio` as cursoprecio,
p.`codigo` as profesorcodigo, p.`NSS` as profesornss, p.`nombre` as profesornombre, p.`apellidos` as profesorapellidos, p.`fNacimiento` as profesorfnacimiento, p.`DNI` as profesordni, p.`direccion` as profesordireccion, p.`poblacion` as profesorpoblacion, p.`codigopostal` as profesorcodigopostal, p.`telefono` as profesortelefono, p.`email` as profesoremail,p.activo as profesoractivo, cli.codigo as clientecodigo, cli.`nombre` as clientenombre, cli.`email` as clienteemail, cli.`telefono` as clientetelefono, cli.identificador as clienteidentificador, cli.`direccion` as clientedireccion, cli.`poblacion` as clientepoblacion, cli.`codigopostal` as clientecodigopostal, cli.activo as clienteactivo, i.codigo as imparticioncodigo,
i.fMatriculacion as imparticionfmatriculacion,
a.`codigo` as alumnocodigo, a.`nombre` as alumnonombre, a.`apellidos` as alumnoapellidos, a.`fNacimiento` as alumnofnacimiento, a.`direccion` as alumnodireccion, a.`poblacion` as alumnopoblacion, a.`codigopostal` as alumnocodigopostal, a.`telefono` as alumnotelefono, a.`email` as alumnoemail, a.`dni` as alumnodni, a.`nHermanos` as alumnonhermanos, a.`activo` as alumnoactivo
FROM curso c
INNER JOIN cliente cli ON cli.codigo = c.cliente_codigo
INNER JOIN profesor p ON p.codigo = c.profesor_codigo
INNER JOIN imparticion i on i.curso_codigo = c.codigo
INNER JOIN alumno a ON a.codigo = i.alumno_codigo
WHERE c.codigo = pcodigo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cursogetByIdentificador` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`admin`@`%` PROCEDURE `cursogetByIdentificador`(IN `pidentificador` VARCHAR(50))
NO SQL
BEGIN
SELECT
c.`codigo` as cursocodigo, c.`nombre` as cursonombre, c.`identificador` as cursoidentificador, c.`fInicio` as cursofinicio, c.`fFin` as cursoffin, c.`nHoras` as cursonhoras, c.`temario` as cursotemario, c.`activo` as cursoactivo, c.`precio` as cursoprecio,
p.`codigo` as profesorcodigo, p.`NSS` as profesornss, p.`nombre` as profesornombre, p.`apellidos` as profesorapellidos, p.`fNacimiento` as profesorfnacimiento, p.`DNI` as profesordni, p.`direccion` as profesordireccion, p.`poblacion` as profesorpoblacion, p.`codigopostal` as profesorcodigopostal, p.`telefono` as profesortelefono, p.`email` as profesoremail,p.activo as profesoractivo, cli.codigo as clientecodigo, cli.`nombre` as clientenombre, cli.`email` as clienteemail, cli.`telefono` as clientetelefono, cli.identificador as clienteidentificador, cli.`direccion` as clientedireccion, cli.`poblacion` as clientepoblacion, cli.`codigopostal` as clientecodigopostal, cli.activo as clienteactivo, i.codigo as imparticioncodigo,
i.fMatriculacion as imparticionfmatriculacion,
a.`codigo` as alumnocodigo, a.`nombre` as alumnonombre, a.`apellidos` as alumnoapellidos, a.`fNacimiento` as alumnofnacimiento, a.`direccion` as alumnodireccion, a.`poblacion` as alumnopoblacion, a.`codigopostal` as alumnocodigopostal, a.`telefono` as alumnotelefono, a.`email` as alumnoemail, a.`dni` as alumnodni, a.`nHermanos` as alumnonhermanos, a.`activo` as alumnoactivo
FROM curso c
INNER JOIN cliente cli ON cli.codigo = c.cliente_codigo
INNER JOIN profesor p ON p.codigo = c.profesor_codigo
INNER JOIN imparticion i on i.curso_codigo = c.codigo
INNER JOIN alumno a ON a.codigo = i.alumno_codigo
WHERE c.identificador = pidentificador;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `cursoupdate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`admin`@`%` PROCEDURE `cursoupdate`(IN `pcodigo` INT, IN `pnombre` VARCHAR(50), IN `pidentificador` VARCHAR(50), IN `pfinicio` DATE, IN `pffin` DATE, IN `pnhoras` INT, IN `ptemario` VARCHAR(50), IN `pprecio` DOUBLE(8,2), IN `pcliente_codigo` INT, IN `pprofesor_codigo` INT)
NO SQL
BEGIN
UPDATE curso SET nombre = pnombre, identificador = pidentificador, fInicio = pfinicio, fFin = pffin, nHoras = phoras, temario = ptemario, precio = pprecio, cliente_codigo = pcliente_codigo, profesor_codigo = pprofesor_codigo
WHERE codigo = pcodigo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `imparticionGetAll` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `imparticionGetAll`()
BEGIN
SELECT codigo, curso_codigo, alumno_codigo, fMatriculacion FROM imparticion;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `imparticionGetById` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `imparticionGetById`(IN _codigo INT)
BEGIN
SELECT codigo, curso_codigo, alumno_codigo, fMatriculacion FROM imparticion WHERE codigo=_codigo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `profesorByDni` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `profesorByDni`(IN `dni` VARCHAR(9))
BEGIN
SELECT `codigo` as profesorcodigo, `NSS` as profesornss, `nombre` as profesornombre, `apellidos` as profesorapellidos, `fNacimiento` as profesorfnacimiento, `DNI` as profesordni, `direccion` as profesordireccion, `poblacion` as profesorpoblacion, `codigopostal` as profesorcodigopostal, `telefono` as profesortelefono, `email` as profesoremail,activo as profesoractivo
FROM `profesor`
WHERE dni = pdni;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `profesorCreate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `profesorCreate`(IN `pnss` VARCHAR(150), IN `pnombre` VARCHAR(150), IN `papellidos` VARCHAR(250), IN `pfNacimiento` DATE, IN `pdni` VARCHAR(9), IN `pdireccion` VARCHAR(150), IN `ppoblacion` VARCHAR(150), IN `pcodigopostal` INT(5), IN `ptelefono` INT(9), IN `pemail` VARCHAR(150), OUT `pcodigo` INT)
BEGIN
INSERT INTO `profesor` (
`nombre`,
`apellidos`,
`fNacimiento`,
`DNI`,
`direccion`,
`poblacion`,
`codigopostal`,
`telefono`,
`email`)
VALUES (
LOWER(pnombre),
LOWER(papellidos),
pfNacimiento,
LOWER(pdni),
LOWER(pdireccion),
LOWER(poblacion),
pcodigopostal,
ptelefono,
LOWER(pemail)
);
SET pcodigo = LAST_INSERT_ID();
if pnss != '' THEN
update profesor set nss = pnss where codigo = pcodigo;
END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `profesorgetAll` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`admin`@`%` PROCEDURE `profesorgetAll`()
NO SQL
BEGIN
SELECT `codigo` as profesorcodigo, `NSS` as profesornss, `nombre` as profesornombre, `apellidos` as profesorapellidos, `fNacimiento` as profesorfnacimiento, `DNI` as profesordni, `direccion` as profesordireccion, `poblacion` as profesorpoblacion, `codigopostal` as profesorcodigopostal, `telefono` as profesortelefono, `email` as profesoremail,activo as profesoractivo
FROM `profesor`
WHERE profesor.activo = true;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `profesorgetByDni` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `profesorgetByDni`(IN `pdni` VARCHAR(9))
BEGIN
SELECT `codigo` as profesorcodigo, `NSS` as profesornss, `nombre` as profesornombre, `apellidos` as profesorapellidos, `fNacimiento` as profesorfnacimiento, `DNI` as profesordni, `direccion` as profesordireccion, `poblacion` as profesorpoblacion, `codigopostal` as profesorcodigopostal, `telefono` as profesortelefono, `email` as profesoremail,activo as profesoractivo
FROM `profesor`
WHERE dni = pdni;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `profesorgetByNss` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `profesorgetByNss`(IN `pnss` VARCHAR(12))
BEGIN
SELECT `codigo` as profesorcodigo, `NSS` as profesornss, `nombre` as profesornombre, `apellidos` as profesorapellidos, `fNacimiento` as profesorfnacimiento, `DNI` as profesordni, `direccion` as profesordireccion, `poblacion` as profesorpoblacion, `codigopostal` as profesorcodigopostal, `telefono` as profesortelefono, `email` as profesoremail,activo as profesoractivo
FROM `profesor`
WHERE nss = pnss;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `profesorUpdate` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `profesorUpdate`(IN `pnss` VARCHAR(12), IN `pnombre` VARCHAR(150), IN `papellidos` VARCHAR(250), IN `pfnacimiento` DATE, IN `pdni` VARCHAR(9), IN `pdireccion` VARCHAR(250), IN `ppoblacion` VARCHAR(150), IN `pcodigopostal` INT(5), IN `ptelefono` INT(9), IN `pemail` VARCHAR(150))
BEGIN
UPDATE `profesor`
SET `NSS`=pnss,
`nombre`=pnombre,
`apellidos`=papellidos,
`fNacimiento`=pfnacimiento,
`DNI`=pdni,
`direccion`=pdireccion,
`poblacion`=ppoblacion,
`codigopostal`=pcodigopostal,
`telefono`=ptelefono,
`email`=pemail
WHERE codigo = pcodigo;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `profesor_DELETE` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `profesor_DELETE`(IN _id INT)
BEGIN
-- DELETE FROM profesor WHERE codigo=_id;
UPDATE profesor
SET activo=FALSE
WHERE codigo=_id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `profesor_GET_All` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `profesor_GET_All`()
BEGIN
SELECT codigo, nss, nombre, apellidos, fNacimiento, dni, direccion, poblacion, codigopostal, telefono, email, activo
FROM profesor
WHERE activo=TRUE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `profesor_GET_ById` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `profesor_GET_ById`(IN _id INT)
BEGIN
SELECT codigo, nss, nombre, apellidos, fNacimiento, dni, direccion, poblacion, codigopostal, telefono, email, activo
FROM profesor
WHERE codigo = _id AND activo = TRUE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `profesor_POST_Insert` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `profesor_POST_Insert`(IN _nss VARCHAR(150), IN _nombre VARCHAR(150), IN _apellidos VARCHAR(250), IN _fNacimiento DATE, IN _dni VARCHAR(9), IN _direccion VARCHAR(150), IN _poblacion VARCHAR(150), IN _codigopostal INT(5), IN _telefono INT(9), IN _email VARCHAR(150), OUT _id INT)
BEGIN
INSERT INTO profesor(nss, nombre, apellidos, fNacimiento, dni, direccion, poblacion, codigopostal, telefono, email)
VALUES(_nss, _nombre, _apellidos, _fNacimiento, _dni, _direccion, _poblacion, _codigopostal, _telefono, _email);
SET _id = LAST_INSERT_ID();
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `profesor_PUT_Update` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `profesor_PUT_Update`(IN _id INT, IN _nss VARCHAR(12), IN _nombre VARCHAR(150), IN _apellidos VARCHAR(250), IN _fnacimiento DATE, IN _dni VARCHAR(9), IN _direccion VARCHAR(250), IN _poblacion VARCHAR(150), IN _codigopostal INT(5), IN _telefono INT(9), IN _email VARCHAR(150))
BEGIN
UPDATE profesor
SET nss=_nss,
nombre=_nombre,
apellidos=_apellidos,
fNacimiento=_fnacimiento,
DNI=_dni,
direccion=_direccion,
poblacion=_poblacion,
codigopostal=_codigopostal,
telefono=_telefono,
email=_email
WHERE codigo = _id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `Resenia_GET_All` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `Resenia_GET_All`()
BEGIN
SELECT codigo, cod_imparticion as imparticion, cod_alumno, resena, fResena FROM resena;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `Resenia_GET_ById` */;
/*!50003 SET @saved_cs_client = @@character_set_client */ ;
/*!50003 SET @saved_cs_results = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection = utf8mb4_0900_ai_ci */ ;
/*!50003 SET @saved_sql_mode = @@sql_mode */ ;
/*!50003 SET sql_mode = 'ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `Resenia_GET_ById`(IN _id INT)
BEGIN
SELECT codigo, cod_imparticion, cod_alumno, resena, fResena FROM resena WHERE codigo=_id;
END ;;
DELIMITER ;
/*!50003 SET sql_mode = @saved_sql_mode */ ;
/*!50003 SET character_set_client = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection = @saved_col_connection */ ;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2020-03-26 13:51:31
| e6c27489bbd53a982c2c2d63bc4c3928b4254164 | [
"Java",
"SQL"
] | 7 | Java | rodrigosotocid/Rodrigo_MF0966 | 0b275ff6af100fff822a7d3b67555e5afa7bf5a4 | ab69f06cb8107feb958c0403dbbb82a2ac07f4bd |
refs/heads/main | <file_sep># Code for PhD Thesis - Maximum Flow Problem
# Data: F2.txt
# <NAME>
# Date of original code: 10th February 2021
# Date of code last modification: 10th February 2021
from capacity import Capacity
from fordfulkerson import FordFulkerson
import string
import json
import sys
sys.path.append('..')
from graphfile import GraphFile
from graph import Graph
# Load edges
# ==========
filename = "data/F2.txt"
edges = GraphFile(filename).read_edges_from_file()
total_items = sum([v for k,v in edges.items() if "source" in k])
edges = {k:v/total_items for k,v in edges.items()}
G = Graph(edges)
# Get edges capacity
# ==================
filename = "results/capacity_estimation.json"
nodes_capacity = open(filename, "r").read()
nodes_capacity = json.loads(nodes_capacity)
nodes_capacity = {int(k[1:]):v for k,v in nodes_capacity.items()}
C = Capacity(nodes_capacity, source_node='source', sink_node='sink')
C_edges = C.get_edges_capacity(G, "weight")
# Flow Network
# ============
flow_network = Graph(C_edges.copy())
antiparallel_edges = flow_network.find_antiparallel_edges()
counter = 0
while len(antiparallel_edges) > 0:
edge = antiparallel_edges.pop(0)
anti = (edge[1],edge[0])
antiparallel_edges.remove( anti )
w = flow_network.edges[anti]
flow_network.deleteEdge(anti[0], anti[1])
new_node = string.ascii_lowercase[counter]
flow_network.addEdge(i=edge[1], j=new_node, w_ij=w)
flow_network.addEdge(i=new_node, j=edge[0], w_ij=w)
counter += 1
# Update node list
# ================
flow_network.nodes = flow_network._get_set_of_nodes()
# Maximum Flow
# ============
flow, residual_network = FordFulkerson(flow_network, startNode='source', endNode='sink')
# Final flow
# ==========
flow = {k:v for k,v in flow.items() if v > 0}
flow_fraction = {k:round(v/C_edges[k],2) for k,v in flow.items()}
# Total items to produce daily
# ============================
count = 0
for k,v in flow.items():
if k[1] == "sink": count += v
print("Total items to produce per day: ", count)
# Save flow fraction
# ==================
filename = "results/flow_fraction.txt"
GraphFile(filename).write_graph_to_file(flow_fraction)
<file_sep># Code for PhD Thesis
# Functions to calculate the Betweenness Centrality
# <NAME>
# Date of original code: August 2017
# Date of code last modification: 19th January 2021
'''The code to calculate the betweenness centrality is based on the algorithms
of Ulrik Brandes. The user must call the function
bC(V, E, weighted=False, normalized=False, directed=True)}
with the following input variables:
1. V is a list of nodes.
2. E is a dictionary with edges as keys, and weights as values (for
unweighted graphs, w = 1 for all w). Weights are interpreted as follows:
higher values indicate stronger ties.
3. normalized is a boolean variable that indicates whether output values
should be normalized. This variable is False by default.
4. directed is a boolean variable that indicates whether the graph is
directed. This variable is True by default.
The function returns a dictionary that contains each node as key and its
betweenness centrality as value.'''
def adj(u, E, directed):
adjNodes = []
for e in E:
if e[0] == u:
adjNodes.append(e[1])
elif (not directed) and (e[1] == u):
adjNodes.append(e[0])
adjNodes = set(adjNodes)
return adjNodes
def bC(V, E, weighted=False, normalized=False, directed=True):
betCen = dict.fromkeys(V, 0)
Q, S = ([], [])
for s in V:
# Initialization
pred = dict.fromkeys(V, [])
dist = dict.fromkeys(V, float('inf'))
sigma = dict.fromkeys(V, 0)
dist[s] = 0
sigma[s] = 1
Q.append(s)
while len(Q) > 0:
v = Q.pop(0)
S.append(v)
adj_v = adj(v, E.keys(), directed)
for w in adj_v:
# Path discovery: is w found for the first time?
if dist[w] == float('inf'):
dist[w] = dist[v] + 1
Q.append(w)
# Path counting: is the edge (v,w) on a shortest path?
if dist[w] == dist[v] + 1:
if weighted:
sigma[w] = sigma[w] + E[(v,w)]*sigma[v]
else:
sigma[w] = sigma[w] + sigma[v]
pred[w] = pred[w] + [v]
# Accumulation
dependency = dict.fromkeys(V, 0)
while len(S) > 0:
w = S.pop()
for v in pred[w]:
if weighted:
dependency[v] = dependency[v] + E[(v,w)]*(sigma[v]/float(sigma[w])) * (1 + dependency[w])
else:
dependency[v] = dependency[v] + (sigma[v]/float(sigma[w])) * (1 + dependency[w])
if w != s:
betCen[w] = betCen[w] + dependency[w]
# If graph is undirected, the algorithm gives a BC that is doubled
if directed == False:
for k,v in betCen.items():
betCen[k] = float(v) / 2.0
# Normalization
if normalized == True:
n = len(V)
for k,v in betCen.items():
if directed == True:
betCen[k] = float(v) / ((n-1)*(n-2))
else:
betCen[k] = 2 * float(v) / ((n-1)*(n-2))
return betCen
<file_sep># Code for PhD Thesis - Plot complex network
# Data: F2.txt
# <NAME>
# Date of original code: 9th February 2021
# Date of code last modification: 9th February 2021
from graphviz import Digraph
import string
import json
from capacity import Capacity
import sys
sys.path.append('..')
from graphfile import GraphFile
from graph import Graph
# Load edges
# ==========
filename = "data/F2.txt"
edges = GraphFile(filename).read_edges_from_file()
total_items = sum([v for k,v in edges.items() if "source" in k])
edges = {k:v/total_items for k,v in edges.items()}
G = Graph(edges)
# Get edges capacity
# ==================
filename = "results/capacity_estimation.json"
nodes_capacity = open(filename, "r").read()
nodes_capacity = json.loads(nodes_capacity)
nodes_capacity = {int(k[1:]):v for k,v in nodes_capacity.items()}
C = Capacity(nodes_capacity, source_node='source', sink_node='sink')
C_edges = C.get_edges_capacity(G, "weight")
# Flow Network
# ============
flow_network = Graph(C_edges.copy())
antiparallel_edges = flow_network.find_antiparallel_edges()
counter = 0
while len(antiparallel_edges) > 0:
edge = antiparallel_edges.pop(0)
anti = (edge[1],edge[0])
antiparallel_edges.remove( anti )
w = flow_network.edges[anti]
flow_network.deleteEdge(anti[0], anti[1])
new_node = string.ascii_lowercase[counter]
flow_network.addEdge(i=edge[1], j=new_node, w_ij=w)
flow_network.addEdge(i=new_node, j=edge[0], w_ij=w)
counter += 1
# Get node list
# =============
nodes = flow_network._get_set_of_nodes()
# Nodes positions in plot
# =======================
positions = {'source': "0,9!",
'24': "-1,8!",
'25': "1,8!",
'26': "-1,7!",
'27': "1,7!",
'29': "0,6!",
'30': "0,5!",
'33': "0,4!",
'34': "0,3!",
'35': "-2,2!",
'36': "2,2!",
'37': "0,1!",
'a': "-2,5.5!",
'b': "-2,4.75!",
'c': "2,5!",
'd': "2,4!",
'e': "-3,3.75!",
'f': "2,3!",
'g': "-1,2!",
'h': "-2,3!",
'i': "1,3!",
'j': "1,2!",
'k': "-2,1!",
'l': "2,1!",
'sink': "0,0!"}
# Graphviz
# ========
g = Digraph("G", engine="neato", filename="results/no_antiparallel.gv")
g.attr(rankdir="TB", size='10,10', splines="true")
g.attr("node", shape="oval", style="filled", color="lightgrey", fontname="times-bold", fontsize="16")
g.node("source", pos=positions['source'])
g.node("sink", pos=positions['sink'])
g.attr("node", shape="circle", fixedsize="true", style="filled", fontname="times-bold", fontsize="20")
for n in nodes:
if type(n) != str:
g.node(str(n), width='0.5', color="lightblue", pos=positions[str(n)])
elif n in string.ascii_lowercase:
g.node(n, width='0.5', color="salmon", pos=positions[n])
for i in nodes:
for j in nodes:
if (i,j) in flow_network.edges.keys():
if flow_network.edges[(i,j)] < 1000:
weight = str(5 * flow_network.edges[(i,j)] /1000)
else:
weight = str(1)
g.edge(str(i), str(j), penwidth=weight, color="#000000")
g.view()
<file_sep># Code for PhD Thesis
**Thesis Title:** Complex Networks in Manufacturing - Suitability and Interpretation
**Author:** <NAME>
**Expected Defense Date:** 8th July 2021
**Institution:** University of Luxembourg
This repository contains all the code necessary to reproduce my PhD Thesis. Find below a description of the files.
## Directories
1. `data`: The raw data used for my thesis corresponds to the `train_date.csv` file in the [Kaggle competition titled "Bosch Production Line Performance".](https://www.kaggle.com/c/bosch-production-line-performance) Semi-processed data is available in this folder instead.
2. `figures`: Some of the figures in my Thesis are available in this folder.
3. `flow_networks`: all the code corresponding to the Chapter of "Flow Networks" is available in this directory.
## Files description grouped by use
### Data cleaning
1. `from_timestamp_to_paths.py`: code used to process the train_date.csv data from Kaggle (see here) to obtain manufacturing paths and manufacturing edges.
2. `path_data_cleaning.py`: code necessary to remove "noisy" data. It produces two files: clean manufacturing paths and clean edges.
### Modules developed
1. `graphfile.py`: class used to open and write data from/to text files.
2. `graph.py`: class used to do complex network analysis.
3. `betweenness_centrality.py`: functions necessary to calculate the Betweenness centrality. Read docstrings for details.
4. `clustering_coefficient`: functions necessary to calculate the Clustering Coefficient. See docstrings for details.
5. `depth_first_search.py`: functions needed for the Depth First Search algorithm. Some functions to determine strongly connected components are also available here.
6. `pagerank.py`: functions needed to calculate the PageRank algorithm.
### How to obtain the results in the Thesis manuscript:
1. `traditional_topological_metrics.py` will produce the results in Chapter 7, titled "Traditional Topological Metrics".
2. `main_pagerank.py` will produce the results in Chapter 8, titled "PageRank".
### Profiling
1. `main_for_entropy_code_profiling.py`: To profile the code in the Entropy Chapter (Chapter 9) only the data from product family F2 was used. This snipped is the one profiled (otherwise, it would require HPC use).
### Graphs and plots
1. `plot_network.py`: code used to generate the DOT file to plot the manufacturing network in the Thesis.
<file_sep># ======================================================================
# ======================================================================
# Depth-First Search
# ======================================================================
# ======================================================================
# NOTES: You call dfs(G, u, myOrder) where:
# - G is a dictionary with nodes as keys and adjacency-lists as values.
# - u has default value None, but can be any node from which you desire
# to start exploring the graph.
# - myOrder is a list with a specific order of the nodes to be visited.
def dfs(G, u = None, myOrder = None, returnTrees = False):
gP = {x: {'visited': None, 'predecesor': None, 'd': None, 'f': None} for x in G.keys()}
time = 0
myNodes = G.keys()
if u != None:
myNodes.remove(u)
myNodes = [u] + myNodes
elif myOrder != None:
myNodes = myOrder
myTrees = []
for u in myNodes:
if gP[u]['visited'] == None:
gP, time, myTrees = dfs_visit(G, u, gP, time, myTrees)
if not returnTrees:
return gP
else:
return gP, myTrees
def dfs_visit(G, u, gP, time, myTrees):
time = time + 1
gP[u]['d'] = time
gP[u]['visited'] = 0
S, tree = [], []
S.append(u)
tree.append(u)
while len(S) > 0:
u = S.pop()
gCount = 0
for v in G[u]:
if gP[v]['visited'] == None:
gP[v]['predecesor'] = u
time = time + 1
gP[v]['d'] = time
gP[v]['visited'] = 0
S.append(v)
tree.append(v)
break
else:
gCount = gCount + 1
if gCount == len(G[u]):
gP[u]['visited'] = 1
time = time + 1
gP[u]['f'] = time
if gP[u]['predecesor'] != None:
aux = gP[u]['predecesor']
S.append(aux)
myTrees.append(tree)
return gP, time, myTrees
# The adjacency list function takes a list of tuples (edges) and creates
# the correpsonding adjacency-list dictionary.
def adjacency_list(E):
d = {}
for e in E:
t, h = e[0], e[1]
d[t] = d.get(t, []) + [h]
d[h] = d.get(h, [])
for k in d.keys():
d[k] = set(d[k])
return d
# ======================================================================
# ======================================================================
# Strongly Connected Components
# ======================================================================
# ======================================================================
# Calculate the TRANSPOSE OF G (G with its edges reversed)
def Grev(G):
Gt = dict.fromkeys(G.keys(), [])
for k in G.keys():
for v in G[k]:
Gt[v] = Gt.get(v, []) + [k]
return Gt
# Order the nodes in decreasing order of u.f
def f_order(gP):
myList = []
for k in gP.keys():
aux = (gP[k]['f'], k)
myList.append(aux)
myList.sort(reverse = True)
result = [b for a,b in myList]
return result
# Strongly Connected Components
def scc(G):
myGp = dfs(G)
nodeOrder = f_order(myGp)
Gt = Grev(G)
myGp, trees = dfs(Gt, myOrder = nodeOrder, returnTrees = True)
return trees
<file_sep># Entropy Centrality
# Author: <NAME>
# Date: 5/4/2019
from math import log
class Graph:
def __init__(self, edges=dict()):
'''Initializes a Graph. Variables:
- edges: dictionary with edge tuples as keys (i,j) and
weight w_ij as values.'''
self.edges = edges
self.nodes = self._get_set_of_nodes()
self.downstream_nodes = self._get_downstream_nodes()
self.downstream_strength = self._get_downstream_strength()
self.all_paths = {}
def _get_set_of_nodes(self):
'''Find the nodes from the edges.'''
edges = list(self.edges.keys())
nodes = [i[0] for i in edges] + [i[1] for i in edges]
return set(nodes)
def addEdge(self, i, j, w_ij):
'''Allows to add and edge (i,j) and its weight w_ij to the graph'''
self.edges[(i,j)] = w_ij
def deleteEdge(self, i, j):
'''Allows to delete an edge (i,j) and its associated weight'''
try:
self.edges.pop((i,j))
except KeyError:
print("{0} cannot be deleted. {0} in Graph.".format((i,j)))
def normalize(self):
'''This function allows to set edge weights in a 0 to 1 scale.'''
totSum = 0
for k,v in self.edges.items():
if k[0] == 'i':
totSum += v
normalized_edges = {}
for k,v in self.edges.items():
normalized_edges[k] = round(v/totSum, 5)
return normalized_edges
def _remove_edges_below_tolerance(self, edges, tolerance):
'''This function is used by remove_underutilized_edges and should
not be called by users. It takes two input variables:
- edges: dictionary with tuples of edges (i,j) as keys,
- tolerance: and integer or float used to filter out edges.
The function returns a new dictionary of edges.'''
new_dict = {}
for k,v in edges.items():
if v >= tolerance:
new_dict[k] = v
return new_dict
def remove_underutilized_edges(self, tolerance, normalize=False):
''' This function removes edges whose weight is below a tolerance.
Input variables:
- tolerance (integer or float) used to filter out edges,
- normalize (default value False) whether the weighted edges are to
be normalized.
The function returns a dictionary of edges.'''
if normalize:
normalized_edges = self.normalize()
return self._remove_edges_below_tolerance(normalized_edges, tolerance)
else:
return self._remove_edges_below_tolerance(self.edges, tolerance)
def find_antiparallel_edges(self):
'''This function finds pairs of antiparallel edges.'''
antiparallel = []
for k in self.edges.keys():
antiparallel_edge = (k[1],k[0])
if self.edges.get(antiparallel_edge, False):
antiparallel.append(k)
antiparallel.sort()
return antiparallel
def _get_downstream_nodes_of_i(self, i):
'''This function finds the downstream neighbours of node i.'''
downstream_nodes_of_i = list()
for edge in self.edges.keys():
u, v = edge[0], edge[1]
if u == i: downstream_nodes_of_i.append(v)
downstream_nodes_of_i = set(downstream_nodes_of_i)
return list(downstream_nodes_of_i)
def _get_downstream_nodes(self):
'''This function returns the downstream nodes of each node in the
graph. It is used to assign this value to an attribute.'''
downtream_nodes = dict()
for n in self.nodes:
downtream_nodes[n] = self._get_downstream_nodes_of_i(n)
return downtream_nodes
def _get_downstream_stregth_of_i(self, i):
'''This function calculates the downstream stregth of node i.'''
downstream_stregth_of_i = 0
for edge, weight in self.edges.items():
if edge[0] == i:
downstream_stregth_of_i += weight
return downstream_stregth_of_i
def _get_downstream_strength(self):
'''This function returns the downstream strength of each node in the
graph. It is used to assign this value to an attribute.'''
downstream_stregth = dict()
for n in self.nodes:
downstream_stregth[n] = self._get_downstream_stregth_of_i(n)
return downstream_stregth
def yield_paths_from_i(self, i):
"""Find all paths from node i. This method produces a generator as
opposed to a list of paths (obtained using the method findAllPaths).
"""
path = [i] # path traversed so far
seen = {i} # set of vertices in path
yield path
def search():
for neighbour in self.downstream_nodes[path[-1]]:
if neighbour not in seen:
seen.add(neighbour)
path.append(neighbour)
yield list(path)
yield from search()
path.pop()
seen.remove(neighbour)
yield from search()
def _downstream_degree(self, t, path):
'''Determine the downstream degree of t. Input variables:
- node t for which the downstream degree is required,
- path in which this downstream degree is to be calculated.
The function returns the downstream degree of node t as
defined by Tutzauer (2007). The function is generalized to
also work with weighted graphs.'''
downstream_degree = self.downstream_strength[t]
t_index = path.index(t)
already_visited = set(self.downstream_nodes[t]) & set(path[:t_index])
for adj_node in already_visited:
downstream_degree = downstream_degree - self.edges[ (t, adj_node) ]
return downstream_degree
def _transfer_probability(self, t, path):
'''Determine the transfer probability of path k. Input variables:
- node t for which the transfer probability is required,
- path in which this transfer probability is to be calculated.
The function returns the transfer probability of node t as
defined by Tutzauer (2007). The function is generalized to
also work with weighted graphs.'''
D_t = self._downstream_degree(t, path)
if D_t == 0:
T_k = 0
else:
t_index = path.index(t)
edge = (t, path[t_index + 1])
T_k = self.edges[edge] / D_t
return T_k
def _stopping_probability(self, t, path):
'''Determine the stopping probability of path k. Input variables:
- node t for which the stopping probability is required,
- path in which this stopping probability is to be calculated.
The function returns the stopping probability of node t as
defined by Tutzauer (2007). The function is generalized to
also work with weighted graphs. In order to work for looped
graphs, the edge (t,t) must explicitly show up in self.edges!'''
D_t = self._downstream_degree(t, path)
if D_t == 0:
sigma_k = 1
else:
edge = (t, t)
sigma_k = self.edges.get(edge, 0) / D_t
return sigma_k
def _arrival_probability(self, t):
'''Arrival probability according to the new formulation proposed in the
article.'''
sigma_k = 1
return sigma_k
def _path_probability(self, path, formulation_type):
'''Calculate the probability of a given path in G. This
done following the general formulae on Tutzauer (2007).'''
i, j = path[0], path[-1]
if formulation_type == "Tutzauer":
product = self._stopping_probability(j, path)
else:
product = self._arrival_probability(j)
if product != 0:
for node in path[:-1]:
T_k = self._transfer_probability(node, path)
product = product * T_k
return i, j, product
def _probability_paths_from_i(self, i, formulation_type):
'''Calculate all the probabilities i -> j for all j in G. This
done following the general formulae on Tutzauer (2007). This
function differs from _probability_path_ij in that it uses a
generator to obtain paths instead of calculating them and storing
them on RAM.'''
prob_ij = {(i,j):0 for j in self.nodes}
for path in self.yield_paths_from_i(i):
i, j, product = self._path_probability(path, formulation_type)
prob_ij[(i,j)] += product
return prob_ij
def _normalize_p_ij(self, p_ij):
'''Shannon's entropy is defined for sum(p_i) = 1. This function normalizes
p_ij so the Shannon's entropy can be calculated.
Input variables:
- p_ij: dictionary of probabilities
- nodes: set of graph nodes
Outupt varaibles:
- p_ij_normalized: normalized probabilities
'''
p_i = {n:0 for n in self.nodes}
for i in self.nodes:
for j in self.nodes:
p_i[i] += p_ij.get((i,j), 0)
p_ij_normalized = dict()
for k,v in p_ij.items():
i = k[0]
if p_i[i] != 0:
p_ij_normalized[k] = v / p_i[i]
else:
p_ij_normalized[k] = v
return p_ij_normalized
def calculate_node_entropy(self, i, formulation_type = "Tutzauer"):
'''Calculate the entropy of node i. The function returns
a tuple (i, C_H) of node i and its entropy.
Input variables:
i: node in graph.
formulation_type: "Tutzauer" by default. It follows Tutzauer's
formulation. Any other value, follows the proposed formulation.'''
C_H = 0
p_ij = self._probability_paths_from_i(i, formulation_type)
p_ij = self._normalize_p_ij(p_ij)
for j in self.nodes:
if p_ij[(i,j)] != 0:
C_H = C_H + p_ij[(i,j)] * log(p_ij[(i,j)], 2)
C_H = - C_H
return (i, C_H)
@property
def adjacencyList(self):
'''Returns the adjacency list.'''
ingoing, outgoing = {k:[] for k in self.nodes}, {k:[] for k in self.nodes}
for edge in self.edges.keys():
i, j = edge[0], edge[1]
outgoing[i] = outgoing.get(i, []) + [j]
ingoing[j] = ingoing.get(j, []) + [i]
ingoing = {k:set(v) for k,v in ingoing.items()}
outgoing = {k:set(v) for k,v in outgoing.items()}
return ingoing, outgoing
@property
def degree(self):
'''Calculate the degree of each node.'''
ingoing, outgoing = self.adjacencyList
inDegree = {k:len(ingoing[k]) if k in ingoing else 0 for k in self.nodes}
outDegree = {k:len(outgoing[k]) if k in outgoing else 0 for k in self.nodes}
return inDegree, outDegree
@property
def strength(self):
'''Calculate the strength of each node.'''
inStrength, outStrength = {k:0 for k in self.nodes}, {k:0 for k in self.nodes}
for edge,weight in self.edges.items():
i, j = edge[0], edge[1]
inStrength[j] = inStrength[j] + weight
outStrength[i] = outStrength[i] + weight
return inStrength, outStrength
<file_sep># Code for PhD Thesis
# Data: full manufacturing network obtained from Kaggle competition data (after cleaning)
# <NAME>
# Date of original code: 26th January 2021
# Date of code last modification: 26th January 2021
from graphfile import GraphFile
from graph import Graph
import pagerank
import matplotlib.pyplot as plt
# =============================================================================
# FUNCTION DEFINITIONS
# =============================================================================
def make_plot(x, y, color, marker, filename, xlabel="node ids", ylabel="PageRank"):
''' '''
plt.figure(figsize=(15,5))
plt.scatter(x, y, s=75, marker=marker, c=color)
plt.xticks(range(52), rotation=45)
plt.yticks([x*0.01 for x in range(11)])
plt.ylim(0, 0.1)
plt.grid(True, which="both", axis="both")
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.tight_layout()
plt.savefig(filename)
plt.close()
# =============================================================================
# MAIN
# =============================================================================
if __name__ == "__main__":
# Read data
# =========
filename = "data/clean_manufacturing_edges.txt"
edges = GraphFile(filename).read_edges_from_file()
G = Graph(edges)
# Get start nodes and their fraction
# ==================================
total_number_of_items_manufactured = 0
start_nodes = {n: 0 for n in G.nodes}
with open("data/clean_manufacturing_paths.txt", "r") as f:
for line in f:
line = line.strip().split(" ")
n_0 = int(line[0])
path_count = int(line[-1])
start_nodes[n_0] += path_count
total_number_of_items_manufactured += path_count
start_nodes = {k:v/total_number_of_items_manufactured for k,v in start_nodes.items()}
# CALCULATE PAGERANK FOR DIFFERENT CONDITIONS
# ===========================================
# Case 1: Original algorithm
E = {k:1 for k,v in edges.items()}
start_nodes_all = {n:1/len(G.nodes) for n in G.nodes}
PR_1 = pagerank.pagerank(E, list(G.nodes), start_nodes_all, B=0.85)
# Case 2: Edge weights considered
PR_2 = pagerank.pagerank(edges, list(G.nodes), start_nodes_all, B=0.85)
# Case 3: Edge weights and start nodes considered
PR_3 = pagerank.pagerank(edges, list(G.nodes), start_nodes, B=0.85)
# Print table for LaTeX
for k,v in PR_1.items():
print(k, " & ", round(v,3), " & ", round(PR_2[k],3), " & ", round(PR_3[k],3), "\\\\")
# PLOT RESULTS
# ============
x = list(PR_1.keys())
x.sort()
y1 = [PR_1[i] for i in x]
y2 = [PR_2[i] for i in x]
y3 = [PR_3[i] for i in x]
make_plot(x, y1, color="red", marker="o", filename="figures/pagerank1.pdf")
make_plot(x, y2, color="blue", marker="x", filename="figures/pagerank2.pdf")
make_plot(x, y3, color="green", marker="^", filename="figures/pagerank3.pdf")
plt.figure(figsize=(6,10))
plt.grid(True, axis="y")
plt.scatter(y1, x, marker="o", c="red")
plt.scatter(y2, x, marker="x", c="blue")
plt.scatter(y3, x, marker="^", c="green")
plt.yticks(range(52))
plt.xlabel("PageRank")
plt.ylabel("Nodes")
plt.legend(["$PR_1$", "$PR_2$", "$PR_3$"], loc='upper right')
plt.tight_layout()
plt.savefig("figures/pagerank.pdf")
plt.close()
<file_sep># Code for PhD Thesis
# Data: Graph of product family F2
# <NAME>
# Date of original code: 2nd February 2021
# Date of code last modification: 2nd February 2021
import graphfile
import graph
import datetime
def remove_i_and_f(edges):
new_edges = dict()
for k,v in edges.items():
if 'i' in k:
continue
elif 'f' in k:
key = (k[0],k[0])
new_edges[key] = v
else:
new_edges[k] = v
return new_edges
if __name__ == "__main__":
# Read data
# =========
graph_to_study = "F2"
full_path = "/home/ubadmin/PhD/CET_4/code/"
file = graphfile.GraphFile(full_path + "data/" + graph_to_study + ".txt")
edges = file.read_edges_from_file()
# Process data
# ==============
edges = remove_i_and_f(edges)
g = graph.Graph(edges)
# Get entropy
# ===========
C_H = {}
start = datetime.datetime.now()
for i in g.nodes:
i, c = g.calculate_node_entropy(i)
C_H[i] = c
end = datetime.datetime.now()
print("Elapsed time: ", end - start)
<file_sep># Useful functions
# Author: <NAME>
# Date: 4/4/2019
# ======================
class GraphFile:
def __init__(self, fileName):
'''Initialize class with name of file.'''
self.filename = fileName
def read_edges_from_file(self):
'''Read graph from file. The file contains one edge (i,j)
and its weight w_ij per line as follows:
i j w_ij'''
edges = {}
with open(self.filename) as fileHandle:
for line in fileHandle:
line = line.strip().split()
if len(line) != 3: continue
i, j, w_ij = line[0], line[1], line[2]
try:
i = int(i)
except ValueError:
pass
try:
j = int(j)
except ValueError:
pass
w_ij = float(w_ij)
edges[(i,j)] = w_ij
return edges
def write_graph_to_file(self, G):
'''Write graph G to file. G must be a dictionary.
Keys are tuples (i,j) of edges and values are weights w_ij.'''
with open(self.filename, 'w') as f:
for k,v in G.items():
i, j, w_ij = str(k[0]), str(k[1]), str(v)
f.write(i + ' ' + j + ' ' + w_ij + '\n')
return True
def read_centrality_values_from_file(self):
'''Read centrality values from file. The file must contain
one node per line and its centrality value as follows:
i c_i'''
C = {}
with open(self.filename) as f:
for line in f:
line = line.strip().split()
i, c_i = line[0], float(line[1])
try:
i = int(i)
except ValueError:
pass
C[i] = c_i
return C
def write_centrality_values_to_file(self, C):
'''Write centrality values to file. C must be a dictionary.
Keys are nodes i and values are centrality values c_i.'''
with open(self.filename, 'w') as f:
for k,v in C.items():
i, c_i = str(k), str(v)
f.write(i + ' ' + c_i + '\n')
return True
def write_paths_to_file(self, paths_list):
'''Write a list of paths to file. paths_list must be a list of paths.
Each individual path is saved in a different line.'''
with open(self.filename, 'w') as f:
for p in paths_list:
p = [str(n) for n in p]
s = ' '.join(p)
f.write(s + '\n')
return True
def read_paths_from_file(self):
'''Read paths from file. They must be saved in the format given by
the write_paths_to_file method.'''
with open(self.filename) as f:
all_paths = dict()
for line in f:
line = line.strip().split(' ')
line = [int(x) for x in line]
i, j = line[0], line[-1]
all_paths[(i,j)] = all_paths.get((i,j), [])
all_paths[(i,j)].append(line)
return all_paths
def read_paths_with_count(self):
'''Read paths from file with count values. The file must contain one
path per line as nodes separated with whitespace and the last value is
the count. Example:
1 2 3 4 5 6 1000 '''
with open(self.filename) as f:
all_paths = dict()
for line in f:
line = line.strip().split(' ')
line = [int(x) for x in line]
path, count = tuple(line[0:-1]), line[-1]
all_paths[path] = all_paths.get(path, 0) + count
return all_paths
def write_paths_with_count(self, paths_with_count_dict):
'''Write paths to file with count values. The file will contain one
path per line as nodes separated with whitespace and the last value is
the count. Example:
1 2 3 4 5 6 1000 '''
with open(self.filename, 'w') as f:
for path,count in paths_with_count_dict.items():
line = [str(n) for n in path] + [str(count)]
line = ' '.join(line)
f.write(line + '\n')
return True
<file_sep># Code for PhD Thesis - Plot complex network
# Data: F2.txt
# <NAME>
# Date of original code: 9th February 2021
# Date of code last modification: 9th February 2021
from graphviz import Digraph
import sys
sys.path.append('..')
from graphfile import GraphFile
from graph import Graph
# Load edges
# ==========
filename = "data/F2.txt"
edges = GraphFile(filename).read_edges_from_file()
total_items = sum([v for k,v in edges.items() if "source" in k])
edges = {k:v/total_items for k,v in edges.items()}
G = Graph(edges)
# Get node list
# =============
nodes = G.nodes
# Nodes positions in plot
# =======================
positions = {'source': "0,9!",
'24': "-1,8!",
'25': "1,8!",
'26': "-1,7!",
'27': "1,7!",
'29': "0,6!",
'30': "0,5!",
'33': "0,4!",
'34': "0,3!",
'35': "-1,2!",
'36': "1,2!",
'37': "0,1!",
'sink': "0,0!"}
# Graphviz
# ========
g = Digraph("G", engine="neato", filename="results/full_network.gv")
g.attr(rankdir="TB", size='10,10', splines="true")
g.attr("node", shape="oval", style="filled", color="lightgrey", fontname="times-bold", fontsize="16")
g.node("source", pos=positions['source'])
g.node("sink", pos=positions['sink'])
g.attr("node", shape="circle", fixedsize="true", style="filled", fontname="times-bold", fontsize="20")
for n in nodes:
if n not in ['source', 'sink']:
g.node(str(n), width='0.5', color="lightblue", pos=positions[str(n)])
for i in nodes:
for j in nodes:
if (i,j) in G.edges.keys():
weight = str(5 * G.edges[(i,j)])
g.edge(str(i), str(j), penwidth=weight, color="#000000")
g.view()
<file_sep># Code for PhD Thesis
# Functions to calculate the Clustering Coefficient and Triangle Type Fractions
# <NAME>
# Date of original code: 3rd May 2017
# Date of code last modification: 19th January 2021
'''The user must call the function CCunweighted(E) to calculate the clustering
coefficient of a BDN or CCweighted(wE) in the case of a WDN. The input variables
are as follows:
1. E or wE: is a dictionary that contains edges as keys and, item counts or
weights as values (respectively). To calculate weighted edges, the user
may call the function wEdgesMaker(E).
These functions return two things:
1. CC: a dictionary with nodes as keys and their clustering coefficient as
value.
2. frac: a dictionary with the fraction of each triangle type in the family
under study. The possible triangles are: cycle, middleman, in or out.
'''
# ===============================
# Degree
# <NAME>
# 3rd May 2017
# ===============================
def adjacency_list(E):
d_in, d_out = {}, {}
for e in E:
t, h = e[0], e[1]
d_out[t] = d_out.get(t, []) + [h]
d_in[h] = d_in.get(h, []) + [t]
d_in = {k:set(v) for k,v in d_in.items()}
d_out = {k:set(v) for k,v in d_out.items()}
return d_in, d_out
def adjacency_weight(E):
s_in, s_out = {}, {}
for e in E.keys():
t, h = e[0], e[1]
s_out[t] = s_out.get(t, 0) + E[e]
s_in[h] = s_in.get(h, 0) + E[e]
return s_in, s_out
def degree(E, weighted=False):
if not weighted:
inDegree, outDegree = adjacency_list(E.keys())
inDegree = {k:len(v) for k,v in inDegree.items()}
outDegree = {k:len(v) for k,v in outDegree.items()}
else:
inDegree, outDegree = adjacency_weight(E)
nodes = set(inDegree.keys()) | set(outDegree.keys())
d = {}
for n in nodes:
d[n] = inDegree.get(n, 0) + outDegree.get(n, 0)
return d
# ======================
# Clustering Coefficient
# <NAME>
# 4th May 2017
# ======================
def bilateral_edges(Ein, Eout):
nodes = set(Ein.keys()) | set(Eout.keys())
d_bilateral = {}
for n in nodes:
d_bilateral[n] = len(Ein.get(n, set()) & Eout.get(n, set()))
return d_bilateral
def cc_unweighted(E):
CC = {}
Ein, Eout = adjacency_list(E)
nodes = set(Ein.keys()) | set(Eout.keys())
deg = degree(E)
bilEdges = bilateral_edges(Ein, Eout)
import itertools
tot, cyc, mid, inn, out = {}, {}, {}, {}, {}
for n in nodes:
neighbors = Ein.get(n, set()) | Eout.get(n, set())
for x in itertools.combinations(neighbors, 2):
i,j,h = n, x[0], x[1]
a_ij, a_ji, a_ih, a_hi, a_jh, a_hj = 0, 0, 0, 0, 0, 0
if j in Eout.get(i, set()): a_ij = 1
if i in Eout.get(j, set()): a_ji = 1
if h in Eout.get(i, set()): a_ih = 1
if i in Eout.get(h, set()): a_hi = 1
if h in Eout.get(j, set()): a_jh = 1
if j in Eout.get(h, set()): a_hj = 1
tot[n] = tot.get(n, 0) + (a_ij + a_ji)*(a_ih + a_hi)*(a_jh + a_hj)
# Get the differnt triangles sums
cyc[n] = cyc.get(n, 0) + float(a_ij*a_hi*a_jh + a_ji*a_ih*a_hj)
mid[n] = mid.get(n, 0) + float(a_ij*a_hi*a_hj + a_ji*a_ih*a_jh)
inn[n] = inn.get(n, 0) + float(a_ji*a_hi*a_jh + a_ji*a_hi*a_hj)
out[n] = out.get(n, 0) + float(a_ij*a_ih*a_jh + a_ij*a_ih*a_hj)
CC[n] = 0.5 * float(tot[n]) / float(deg[n] * (deg[n] - 1) - 2*bilEdges[n])
# Get the different triangles fractions
for k in tot.keys():
cyc[k] = cyc[k] / tot[k]
mid[k] = mid[k] / tot[k]
inn[k] = inn[k] / tot[k]
out[k] = out[k] / tot[k]
cyc = round(sum(cyc.values()) / len(cyc.keys()), 3)
mid = round(sum(mid.values()) / len(mid.keys()), 3)
inn = round(sum(inn.values()) / len(inn.keys()), 3)
out = round(sum(out.values()) / len(out.keys()), 3)
fractions = {'cycles': cyc, 'middlemen': mid, 'in': inn, 'out': out}
return CC, fractions
def wEdges_maker(E):
'''Weighted edges must have a value in the range (0,1]. In order to
accomplish that (in the case one or more edges have values above 1), is
to divide the weight of all edges by that of the max weight in the graph.'''
wE = {}
max_weight = max(E.values())
for k,v in E.items():
wE[k] = v / float(max_weight)
return wE
def cc_weighted(wE):
CC = {}
Ein, Eout = adjacency_list(wE)
nodes = set(Ein.keys()) | set(Eout.keys())
deg = degree(wE)
bilEdges = bilateral_edges(Ein, Eout)
import itertools
tot, cyc, mid, inn, out = {}, {}, {}, {}, {}
for n in nodes:
neighbors = Ein.get(n, set()) | Eout.get(n, set())
for x in itertools.combinations(neighbors, 2):
i,j,h = n, x[0], x[1]
w_ij, w_ji, w_ih, w_hi, w_jh, w_hj = 0, 0, 0, 0, 0, 0
if j in Eout.get(i, set()): w_ij = wE[(i,j)]**(1.0/3)
if h in Eout.get(i, set()): w_ih = wE[(i,h)]**(1.0/3)
if h in Eout.get(j, set()): w_jh = wE[(j,h)]**(1.0/3)
if i in Eout.get(j, set()): w_ji = wE[(j,i)]**(1.0/3)
if i in Eout.get(h, set()): w_hi = wE[(h,i)]**(1.0/3)
if j in Eout.get(h, set()): w_hj = wE[(h,j)]**(1.0/3)
tot[n] = tot.get(n, 0) + (w_ij + w_ji)*(w_ih + w_hi)*(w_jh + w_hj)
# Get the differnt triangles sums
cyc[n] = cyc.get(n, 0) + float(w_ij*w_hi*w_jh + w_ji*w_ih*w_hj)
mid[n] = mid.get(n, 0) + float(w_ij*w_hi*w_hj + w_ji*w_ih*w_jh)
inn[n] = inn.get(n, 0) + float(w_ji*w_hi*w_jh + w_ji*w_hi*w_hj)
out[n] = out.get(n, 0) + float(w_ij*w_ih*w_jh + w_ij*w_ih*w_hj)
CC[n] = 0.5 * tot[n] / float(deg[n]*(deg[n]-1) - 2*bilEdges[n])
# Get the different triangles fractions
for k in tot.keys():
cyc[k] = cyc[k] / tot[k]
mid[k] = mid[k] / tot[k]
inn[k] = inn[k] / tot[k]
out[k] = out[k] / tot[k]
cyc = round(sum(cyc.values()) / len(cyc.keys()), 3)
mid = round(sum(mid.values()) / len(mid.keys()), 3)
inn = round(sum(inn.values()) / len(inn.keys()), 3)
out = round(sum(out.values()) / len(out.keys()), 3)
fractions = {'cycles': cyc, 'middlemen': mid, 'in': inn, 'out': out}
return CC, fractions
<file_sep># Code for PhD Thesis - Plot flow fraction
# Data: flow_fraction.txt
# <NAME>
# Date of original code: 10th February 2021
# Date of code last modification: 10th February 2021
from graphviz import Digraph
import sys
sys.path.append('..')
from graphfile import GraphFile
from graph import Graph
# Load edges
# ==========
filename = "results/flow_fraction.txt"
edges = GraphFile(filename).read_edges_from_file()
G = Graph(edges)
# Get node list
# =============
nodes = G.nodes
# =================================================================
positions = {'source': "0,9!",
'24': "-1,8!",
'25': "1,8!",
'26': "-1,7!",
'27': "1,7!",
'29': "0,6!",
'30': "0,5!",
'33': "0,4!",
'34': "0,3!",
'35': "-1,2!",
'36': "1,2!",
'37': "0,1!",
'sink': "0,0!"}
color_gradient = ["#008000", #green
"#339900",
"#66B200",
"#99CC00",
"#CCE500",
"#FFFF00", #yellow
"#FFCC00",
"#FF9900",
"#FF6600",
"#FF3300",
"#FF0000"] #red
fraction_list = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]
# =================================================================
g = Digraph("G", engine="neato", filename="results/flow_fraction.gv")
g.attr(rankdir="TB", size='10,10', splines="true")
g.attr("node", shape="oval", style="filled", color="lightgrey", fontname="times-bold", fontsize="16")
g.node("source", pos=positions['source'])
g.node("sink", pos=positions['sink'])
g.attr("node", shape="circle", fixedsize="true", style="filled", fontname="times-bold", fontsize="20")
for n in nodes:
if n not in ['source', 'sink']:
g.node(str(n), width='0.5', color="lightblue", pos=positions[str(n)])
for i in nodes:
for j in nodes:
if (i,j) in G.edges.keys():
fraction = G.edges[(i,j)]
x = fraction_list.index( round(fraction, 1) )
col = color_gradient[x]
g.edge(str(i), str(j), penwidth="2", color=col, label=str(fraction))
g.view()
<file_sep># Ford-Fulkerson algorithm
# <NAME>
# 23/05/2019
'''
FUNCTION: FordFulkerson(G, startNode='i', endNode='f')
Input variable: G = graph object. Flow network where the edges
attribute has tuples as keys where (a, b) are edges, and
edge capacities as values.
Input variable: startNode = start node, default "i"
Input variable: endNode = end node, default "f"
Output variable: flow = dictionary maximum flow
Output variable: Gf = dictionary residual network
'''
def FordFulkerson(G, startNode = 'i', endNode = 'f'):
from copy import deepcopy
from breadthfirstsearch import BreadthFirstSearch
# Initialize flow to zero
flow = {}
for k in G.edges.keys():
flow[k] = 0
# Define residual network
Gf = deepcopy(G)
while True:
# Use breadth-first search to find a path
bfs = BreadthFirstSearch(Gf, startNode)
p = bfs.get_path(endNode)
if len(p) == 0: break
p = [(p[i],p[i+1]) for i in range(len(p)-1)]
# Get the minimum residual capacity in that path
cf = [Gf.edges.get(e, 0) for e in p]
cf = min(cf)
for e in p:
anti = (e[1], e[0])
if e in Gf.edges.keys():
# Update flow
flow[e] = flow.get(e, 0) + cf
# Update residual network
Gf.edges[e] = Gf.edges.get(e, 0) - cf
if Gf.edges[e] == 0: Gf.edges.pop(e, None)
Gf.edges[anti] = Gf.edges.get(anti, 0) + cf
else:
# Update flow
flow[anti] = flow.get(anti, 0) - cf
# Update residual network
Gf.edges[e] = Gf.edges.get(e, 0) - cf
Gf.edges[anti] = Gf.edges.get(anti, 0) + cf
return flow, Gf
# Example network from 'Introduction to Algorithms' book
# V = ['s', 't', 1, 2, 3, 4]
# G = {('s', 1): 16, ('s', 2): 13, (1, 3): 12, (2, 1): 4, (2, 4): 14, (3, 2): 9, (3, 't'): 20, (4, 3): 7, (4, 't'): 4}<file_sep># Manufacturing Entropy - Code for the article
# Data: Kaggle competition - Bosch Manufacturing Data: train_date.csv file
# <NAME>
# Date of original code: 15th November 2016
# Date of code last modification: 15th April 2020
import re
# Read the file
fileName = 'data/train_date.csv'
fileHandle = open(fileName)
aux = 0
myDict = {}
myEdges = {}
for row in fileHandle:
if (aux == 0):
colNames = row.strip().split(',')
del colNames[0]
aux = 1
continue
row = row.strip().split(',')
indexN = int(row.pop(0)) # 'Id'
# Remove Null
notNull = ['' == i for i in row]
myCols = [i for (i, v) in zip(colNames, notNull) if not v]
row = filter(None, row)
# Make elements floats
row = [float(i) for i in row]
# Change to mean values for each visited station
vStat = list(set(re.findall('L.(_S.+?_)D', ' '.join(myCols))))
timeStamp = []
for s in vStat:
c = [s in i for i in myCols]
sensorData = [v for (i,v) in zip(c,row) if i]
sensorData = sum(sensorData) / float(len(sensorData))
timeStamp.append(sensorData)
vStat_ord = [s for (t,s) in sorted(zip(timeStamp, vStat))]
vStat_ord = [re.findall('_S([0-9]+)_', i)[0] for i in vStat_ord]
vStat_ord = [int(i) for i in vStat_ord]
vStat_ord = tuple(vStat_ord)
if len(vStat_ord)==0: continue
myDict[vStat_ord] = myDict.get(vStat_ord, 0) + 1
edges = [('i',vStat_ord[0])] + [(i,j) for (i,j) in zip(vStat_ord, vStat_ord[1:])] + [(vStat_ord[len(vStat_ord)-1], 'f')]
for e in edges:
myEdges[e] = myEdges.get(e, 0) + 1
fileHandle.close()
# del re, fileName, fileHandle, aux, row, colNames, indexN, notNull, myCols, i, vStat, timeStamp
# del s, c, sensorData, vStat_ord, t, j, e, v, edges
# ===========================================================
# Saving the data for all paths
# Data is saved as stations + count (count is the last item)
f = open('data/manufacturing_paths.txt', 'w')
for k,v in myDict.items():
line = ' '.join(str(x) for x in k)
line = line + ' ' + str(v)
f.write(line + '\n')
f.close()
# Saving the data for all edges
# Data is saved as stations + count (count is the last item)
f = open('data/manufacturing_edges.txt', 'w')
for k,v in myEdges.items():
line = ' '.join(str(x) for x in k)
line = line + ' ' + str(v)
f.write(line + '\n')
f.close()
del f, k, v, line
# ===========================================================
<file_sep># Breadth First Search
# Author: <NAME>
# 23/5/2019
class BreadthFirstSearch:
def __init__(self, G, source_node):
self.source_node = source_node
self.bfs_properties = self.bfs(G)
def bfs(self, G):
''''''
properties = {}
for node in G.nodes:
properties[node] = {'color': 'white', 'd': float('inf'), 'predecessor': None}
properties[self.source_node]['color'] = 'gray'
properties[self.source_node]['d'] = 0
queued = [self.source_node]
adj_in, adj_out = G.adjacencyList
while len(queued) > 0:
u = queued.pop(0)
for node in adj_out[u]:
if properties[node]['color'] == 'white':
properties[node]['color'] = 'gray'
properties[node]['d'] = properties[u]['d'] + 1
properties[node]['predecessor'] = u
queued.append(node)
properties[u]['color'] = 'black'
return properties
def get_path(self, to_node):
''' '''
path = []
while True:
if to_node == self.source_node:
path.append(self.source_node)
break
elif self.bfs_properties[to_node]['predecessor'] == None:
break
else:
path.append(to_node)
to_node = self.bfs_properties[to_node]['predecessor']
path.reverse()
return path<file_sep># Code for PhD Thesis - Flow networks (node capacity estimation)
# Data: train_date.csv
# <NAME>
# Date of original code: 9th February 2021
# Date of code last modification: 9th February 2021
import re
import json
# =============================================================================
# FUNCTION DEFINITIONS
# =============================================================================
def kadane_algorithm(A):
i, thisSum, maxSum = 0, 0, 0
startIndex, endIndex = 0, -1
for j in range(len(A)):
thisSum = thisSum + A[j]
if thisSum > maxSum:
maxSum = thisSum
startIndex = i
endIndex = j
elif thisSum < 0:
thisSum = 0
i = j + 1
return (maxSum, startIndex, endIndex)
# =============================================================================
# MAIN
# =============================================================================
if __name__ == "__main__":
# =========================================
# Process train_date.csv
# =========================================
filename = "/home/ubadmin/PhD/CET_4/code/data/train_date.csv"
print("Processing: ", filename, "\n")
first_line = True
t_i = {} # stations initial time-stamp values
with open(filename, "r") as f:
for row in f:
# Save column names
if first_line:
column_names = row.strip().split(",")
del column_names[0]
first_line = False
continue
row = row.strip().split(",")
id = int(row.pop(0)) # "Id"
# Remove NA
empty_string_list = ["" == i for i in row]
columns_to_keep = [i for (i, v) in zip(column_names, empty_string_list) if not v]
row = filter(None, row)
# Make time-stamp values float
row = [float(i) for i in row]
# For each processed item, save the initial time-stamp value
# at each visited workstation
vStat = list(set(re.findall("L._(S.+?)_D", " ".join(columns_to_keep))))
for s in vStat:
c = [s in i for i in columns_to_keep]
sensorData = [v for (i,v) in zip(c,row) if i]
sensorData = set(sensorData)
t_i[s] = t_i.get(s, [])
t_i[s].append( min(sensorData) )
print("Finished processing file: ", filename, "\n")
# Save intermediate results
with open("results/time_stamps_at_each_workstation.json", "w") as f:
json.dump(t_i, f, sort_keys=True, indent=4)
# =========================================
# Make change array
# =========================================
print("Proceeding to calculate the change arrays.")
all_change_arrays = dict()
time = [x* 0.01 for x in range(171849)]
for k,v in t_i.items():
# Make dictionary with time values as keys and number of occurrences as values
time_stamp_frequency = {}
for ts in v:
time_stamp_frequency[ts] = time_stamp_frequency.get(ts, 0) + 1
# Make "change" array
change_array = []
for i in range(1, 171849, 1):
c = time_stamp_frequency.get(time[i], 0) - time_stamp_frequency.get(time[i-1], 0)
change_array.append(c)
all_change_arrays[k] = change_array
# Save intermediate results
with open("results/change_arrays.json", "w") as f:
json.dump(all_change_arrays, f, sort_keys=True, indent=4)
# =========================================
# Find maximum subarray
# =========================================
print("Proceeding to calculate the maximum subarrays.")
maximum_subarray = dict()
for k,v in all_change_arrays.items():
s, idL, idR = kadane_algorithm(v)
tL, tR = time[idL+1], time[idR+1]
maximum_subarray[k] = {"maximum_sum": s, "left_time":tL, "right_time":tR}
# Save intermediate results
with open("results/maximum_subarray.json", "w") as f:
json.dump(maximum_subarray, f, sort_keys=True, indent=4)
# =========================================
# Count number of elements processed in maximum subarray time
# =========================================
print("Counting number of units processed in maximum subarray time.")
units_processed = {}
for k,v in t_i.items():
# Make dictionary with time values as keys and number of occurrences as values
time_stamp_frequency = {}
for ts in v:
time_stamp_frequency[ts] = time_stamp_frequency.get(ts, 0) + 1
# Calculate Number of units processes in maxSum time lapse
units = 0
for kk,vv in time_stamp_frequency.items():
if kk >= maximum_subarray[k]["left_time"] and kk <= maximum_subarray[k]["right_time"]:
units = units + vv
time_lapse = maximum_subarray[k]["right_time"] - maximum_subarray[k]["left_time"]
capacity_estimation = units * (16.75 / 7) / time_lapse # in units/day
capacity_estimation = int(round(capacity_estimation, 0))
units_processed[k] = capacity_estimation
# ============================================
# SAVE RESULTS
# ============================================
with open("results/capacity_estimation.json", "w") as f:
json.dump(units_processed, f, sort_keys=True, indent=4)
<file_sep># Manufacturing Entropy - Code for the article
# Original Data: Kaggle competition - Bosch Manufacturing Data: train_date.csv file
# Data used in this file: pre-processed ("data/clean_manufacturing_paths.txt" and "data/clean_manufacturing_edges.txt")
# <NAME>
# Date of original code: 29th October 2019
# Date of code last modification: 21st July 2020
# ===== Function definitions ============
def add_self_loops(paths, edges):
for k,v in paths.items():
self_loop = (k[-1], k[-1])
edges[self_loop] = edges.get(self_loop, 0) + v
return edges
def generate_dot_file(graph, node_colors, graph_name, filename, edgelabel=False):
# File creation
file_content = ''
# General graph info
file_content += 'digraph ' + graph_name + '{\n'
file_content += 'size = "40,20";\n'
file_content += 'graph[rankdir=TB, center=true, margin=0.05, nodesep=0.2, ranksep=0.5]\n'
file_content += 'node[fontname="times-bold", fontsize=20]\n'
file_content += 'edge[arrowsize=0.2, arrowhead=normal, fontsize=8]\n'
for n in graph.nodes:
file_content += str(n) + ' [shape=circle, style=filled, color= ' + node_colors[n] + ', width=0.75, height=0.75, fixedsize=true]\n'
if edgelabel:
for k,v in graph.edges.items():
file_content += str(k[0]) + ' -> ' + str(k[1]) + ' [penwidth=1.5, label=' + str(round(v,2)) + ']\n'
#file_content += str(k[0]) + ' -> ' + str(k[1]) + ' [penwidth=1.5]\n'
else:
for k,v in graph.edges.items():
file_content += str(k[0]) + ' -> ' + str(k[1]) + ' [penwidth=1.5]\n'
file_content += '}'
path = "figures/" + filename
with open(path, 'w') as f:
f.write(file_content)
return True
# ===== End Function definitions =========
if __name__ == "__main__":
# Import needed modules
# =====================
from graphfile import GraphFile
from graph import Graph
import datetime
# Read data: clean paths and clean edges
# ======================================
filename_paths = "data/clean_manufacturing_paths.txt"
filename_edges = "data/clean_manufacturing_edges.txt"
edges = GraphFile(filename_edges).read_edges_from_file()
paths = GraphFile(filename_paths).read_paths_with_count()
# Generate graph from clean edges
# ===============================
edges = add_self_loops(paths, edges)
G = Graph(edges)
print("Number of nodes: ", len(G.nodes))
print("Number of edges: ", len(G.edges.keys()))
# Color code nodes
# =======================
node_colors = dict()
for node in G.nodes:
if node in {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23}: # Start nodes threshold 0.001
node_colors[node] = "salmon"
elif node in {24,25}:
node_colors[node] = "palegreen"
elif node in {26,27,28}: # End nodes threshold 0.001
node_colors[node] = "lightblue"
else:
node_colors[node] = "gold"
# Generate DOT file with network graph
# ====================================
today = datetime.datetime.now().strftime("%Y_%m_%d")
filename = today + "_manufacturing_network_graph.dot"
generate_dot_file(G, node_colors, "Bosch", filename)
# =========================================================================
# PLOT SUBGRAPHS
# =========================================================================
# import depth_first_search as dfs
# in_adjlist, out_adjlist = G.adjacencyList
# SCC = dfs.scc(out_adjlist)
# SCC.sort()
# SCC = [sorted(x) for x in SCC]
#
# for number, component in enumerate(SCC):
# if len(component) > 1:
# filename = "manufacturing_subgraph_" + str(number) + ".dot"
# subgraph = {k:v for k,v in edges.items() if k[0] in component and k[1] in component}
# max_weight = max(subgraph.values())
# subgraph = {k:v/max_weight for k,v in subgraph.items()}
# S = Graph(subgraph)
# generate_dot_file(S, node_colors, "BoschSubgraph", filename, edgelabel=True)
<file_sep># Code for PhD Thesis
# Data: full manufacturing network obtained from Kaggle competition data (after cleaning)
# <NAME>
# Date of original code: 19th January 2021
# Date of code last modification: 19th January 2021
from graphfile import GraphFile
from graph import Graph
import betweenness_centrality
import clustering_coefficient
import depth_first_search as dfs
if __name__ == "__main__":
# Read data
# =========
filename = "data/clean_manufacturing_edges.txt"
edges = GraphFile(filename).read_edges_from_file()
G = Graph(edges)
# =========================================================================
# DEGREE
# =========================================================================
indeg, outdeg = G.degree
# =========================================================================
# STRENGTH
# =========================================================================
instr, outstr = G.strength
# =========================================================================
# BETWEENNESS CENTRALITY
# =========================================================================
V = list(G.nodes)
V.sort()
betcen = betweenness_centrality.bC(V, edges, normalized=False, directed=True)
# =========================================================================
# CLUSTERING COEFFICIENT AND TRIANGLES
# =========================================================================
# Unweighted
# ==========
UW_clustcoeff, UW_triangles = clustering_coefficient.cc_unweighted(edges)
UW_C = sum(UW_clustcoeff.values())/len(UW_clustcoeff.values())
print("BDN Clustering Coefficient: ", round(UW_C,3))
print("BDN - Triangles: ", UW_triangles, "\n\n\n")
# Weighted
# ========
wE = clustering_coefficient.wEdges_maker(edges)
W_clustcoeff, W_triangles = clustering_coefficient.cc_weighted(wE)
W_C = sum(W_clustcoeff.values())/len(W_clustcoeff.values())
print("WDN Clustering Coefficient: ", round(W_C,3))
print("WDN - Triangles: ", W_triangles, "\n\n\n")
# =========================================================================
# PRINT TABLE 6.1
# =========================================================================
total_number_of_items_manufactured = 0
with open("data/clean_manufacturing_paths.txt", "r") as f:
for line in f:
line = line.strip().split(" ")
total_number_of_items_manufactured += int(line[-1])
instr = {k:round(v/total_number_of_items_manufactured,2) for k,v in instr.items()}
outstr = {k:round(v/total_number_of_items_manufactured,2) for k,v in outstr.items()}
betcen = {k:round(v,2) for k,v in betcen.items()}
UW_cc = {k:round(v,2) for k,v in UW_clustcoeff.items()}
W_cc = {k:round(v,4) for k,v in W_clustcoeff.items()}
for k,v in indeg.items():
s = str(k) + " & " + str(v) + " & " + str(outdeg[k]) + " & "
s += str(instr[k]) + " & " + str(outstr[k]) + " & "
s += str(betcen[k]) + " & " + str(UW_cc[k]) + " & " + str(W_cc[k]) + " \\\\"
print(s)
# =========================================================================
# STRONGLY CONNECTED COMPONENTS
# =========================================================================
in_adjlist, out_adjlist = G.adjacencyList
SCC = dfs.scc(out_adjlist)
SCC.sort()
SCC = [sorted(x) for x in SCC]
# Print SCC
# =========
print("\n\n\nStrongly Connected Components:")
for i in SCC:
print(i)
# =========================================================================
# SUBGRAPH CLUSTERING COEFFICIENT
# =========================================================================
def subgraph_clustering_coefficient(edges, scc, weighted=True):
''' '''
if weighted:
subgraph = {k:v for k,v in edges.items() if k[0] in scc and k[1] in scc}
else:
subgraph = {k:1 for k,v in edges.items() if k[0] in scc and k[1] in scc}
subgraph = clustering_coefficient.wEdges_maker(subgraph)
subgraph_localC, subgraph_triangles = clustering_coefficient.cc_weighted(subgraph)
subgraph_C = sum(subgraph_localC.values())/len(subgraph_localC.values())
return subgraph_C, subgraph_localC, subgraph_triangles
# ================================================
# Main
print("\n\n\n\nSubgraph Clustering Coefficient:")
for i in SCC:
if len(i) > 1:
w_SC, w_SlC, w_St = subgraph_clustering_coefficient(edges, i, weighted=True)
uw_SC, uw_SlC, uw_St = subgraph_clustering_coefficient(edges, i, weighted=False)
#print(i, " & ", round(uw_SC,2), " & ", round(w_SC,2), "\\\\")
print("SCC: {}\nBDN Triangles: {}\nWDN Triangles: {}\n\n".format(i, uw_St, w_St))
else:
#print(i, " & 0 & 0\\\\")
pass
<file_sep># Capacity
# Author: <NAME>
# Date: 22nd May 2018
class Capacity:
def __init__(self, nodes_capacity, source_node='source', sink_node='sink'):
'''Initializes capacity instance. Input variables:
- nodes_capacity: dictionary with nodes as keys and
their capacity as values.
- source_node: name of the source (or supersource) node.
- sink_node: name of the sink (or supersink) node.'''
self.nodes_capacity = nodes_capacity
self.source_node = source_node
self.sink_node = sink_node
def get_edges_capacity(self, G, distribution_method):
'''Method to calculate the edges capacity. Input
variables:
- G: graph object.
- distribution_method: method chosen to distribute
capacity values from nodes to edges. Available options
are "degree", "weight" and "capacity".'''
if distribution_method == "degree":
return self._get_edges_capacity_degree(G)
elif distribution_method == "weight":
return self._get_edges_capacity_weight(G)
elif distribution_method == "capacity":
return self._get_edges_capacity_capacity(G)
else:
raise ValueError('distribution_method can only be set to "degree", "weight" or "capacity"')
def _get_edges_capacity_degree(self, G):
'''Internal function used to calculate the edges
capacity given the out degree of the nodes. Input
variable: G: graph object.'''
in_degree, out_degree = G.degree
C = dict()
for edge in G.edges.keys():
if self.source_node in edge or self.sink_node in edge:
C[edge] = float('inf')
else:
i = edge[0]
C[edge] = int(self.nodes_capacity[i] / out_degree[i])
return C
def _get_edges_capacity_weight(self, G):
'''Internal function used to calculate the edges
capacity given the edges weight values. Input
variable: G: graph object.'''
in_strength, out_strength = G.strength
C = dict()
for edge in G.edges.keys():
if self.source_node in edge or self.sink_node in edge:
C[edge] = float('inf')
else:
i = edge[0]
C[edge] = int((G.edges[edge] / out_strength[i]) * self.nodes_capacity[i])
return C
def _get_edges_capacity_capacity(self, G):
'''Internal function used to calculate the edges
capacity given the values of the capacity of
customer nodes. Input variable: G: graph object.'''
ingoing, outgoing = G.adjacencyList
C = dict()
for edge in G.edges.keys():
if self.source_node in edge or self.sink_node in edge:
C[edge] = float('inf')
else:
i, j = edge[0], edge[1]
divisor = sum([self.nodes_capacity[x] for x in outgoing[i] if x != self.sink_node])
C[edge] = int((self.nodes_capacity[j] / divisor) * self.nodes_capacity[i])
return C<file_sep># ======================================================================
# ======================================================================
# Page Rank Algorithm
# ======================================================================
# ======================================================================
def make_transition_matrix(E, nodes):
'''Internal function to calculate the transition matrix.
Input variables:
- E: dictionary with edges as keys and weight as value.
- nodes: list of nodes.
Output variables:
- matrix: dictionary corresponding to the transition matrix.
'''
colSum = {}
for n in nodes:
colSum[n] = 0
for m in nodes:
colSum[n] = colSum[n] + E.get((n, m), 0)
matrix = {}
for k in E.keys():
matrix[k] = E[k] / float( colSum[k[0]] )
return matrix
def pagerank(E, nodes, start_nodes=None, B=0.85):
'''Function allowing to calculate the PageRank algorithm.
Input variables:
- E: dictionary with edges as keys and weight as value.
- nodes: list of nodes.
- start_nodes: (default=None) dictionary of nodes with their starting
fraction.
- B: (default=0.85) taxation value, typically between 0.8 and 0.9.
Output variables:
- vp
'''
nodes.sort()
M = make_transition_matrix(E, nodes)
if start_nodes == None:
e = {n: 1/len(nodes) for n in nodes}
else:
e = start_nodes
v = {k: 1/len(nodes) for k in nodes}
vp = {k: 0 for k in nodes}
while any([abs(i - j) for i,j in zip(vp.values(), v.values())]) > 0.001:
for n in nodes:
mult = 0
for m in nodes:
mult = mult + M.get((m, n), 0) * v[m]
vp[n] = B * mult + (1 - B) * e[n]
v, vp = vp.copy(), v.copy()
return vp
<file_sep># Code for PhD Thesis - Flow networks plots
# Data: time_stamps_at_each_workstation.json and change_arrays.json
# <NAME>
# Date of original code: 25th March 2021
# Date of code last modification: 25th March 2021
import json
import matplotlib.pyplot as plt
# =============================================================================
# PLOT - UNITS PROCESSED PER TIME STAMP
# =============================================================================
time_stamps = open("results/time_stamps_at_each_workstation.json")
time_stamps = json.load(time_stamps)
S0 = dict()
for ts in time_stamps["S0"]:
S0[ts] = S0.get(ts, 0) + 1
x = list(S0.keys())
x.sort()
y = [S0.get(i, 0) for i in x]
plt.bar(x[:80], y[:80], width=0.01, color="#646464")
plt.xlabel("anonymized time-stamp")
plt.ylabel("# of units processed")
plt.savefig("results/capacity_estimation_v0_1.pdf")
plt.close()
# =============================================================================
# PLOT - CHANGE ARRAY
# =============================================================================
change_arrays = open("results/change_arrays.json")
change_arrays = json.load(change_arrays)
plt.bar(x[:80], change_arrays["S0"][:80], width=0.01, color="#646464")
plt.xlabel("anonymized time-stamp")
plt.ylabel("change in units processed")
plt.savefig("results/capacity_estimation_v0_2.pdf")
plt.close()
| c429350a79d0d97d2fe9c98474c103aa0cefe05f | [
"Markdown",
"Python"
] | 21 | Python | YamiOmar88/Code_PhD_Thesis | 1d050afbbf5d9f591d9c19d14b77e63e4b0cc910 | 1de381a12141304819161b84aa8d84073f5e28d8 |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace English_Phrases
{
public partial class Form1 : Form
{
List<string> Provers = new List<string>() { "Absence makes the heart grow fonder", "Actions speak louder than words.", "A journey of a thousand miles begins with a single step", "All good things must come to an end", "If it ain’t broke, don’t fix it", "If you play with fire, you’ll get burned", "A picture is worth a thousand words", "A watched pot never boils", "Beggars can’t be choosers", " Better late than never", " Don’t bite the hand that feeds you", "Easy come, easy go", "No man is an island", "The early bird gets the worm" };
List<string> Phrases_Verb = new List<string>() {"do","go","Rest","Ride","Beat","Become","Begin","Bend","Sleep","Work","Need","Study","Practice","Learn","Make","Call","Arise","Burn","Forget" };
List<string> Slng = new List<string> {"chill","cool","Busted","Ride","Hip", "Frenemy", "BAE", "Basic", "Coin", "Dying", "Epic", "Fierce" };
List<string> idoms = new List<string> { "A blessing in disguise : a good thing that seemed bad at first ", "Beat around the bush : as part of a sentence", "Better late than never: Better to arrive late than not to come at all", "Break a leg : Good luck", "Call it a day: Stop working on something", "Hang in there: Don't give up", "Hit the sack : Go to sleep", "Let someone off the hook : To not hold someone responsible for something", "It's not rocket science : It's not complicated", "Make a long story short: Something common", "A dime a dozen :Tell something briefly"};
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Provers.Add(textBox1.Text);
Refresh("Data Added!", Provers, comboBox1);
}
private void button2_Click(object sender, EventArgs e)
{
Phrases_Verb.Add(textBox1.Text);
Refresh("Data Added!",Phrases_Verb, comboBox1);
}
private void button3_Click(object sender, EventArgs e)
{
Slng.Add(textBox1.Text);
Refresh("Data Added!", Slng, comboBox1);
}
private void button6_Click(object sender, EventArgs e)
{
Provers.Remove(comboBox1.SelectedItem.ToString());
Refresh("Data Deleted!", Provers, comboBox1);
}
private void button4_Click(object sender, EventArgs e)
{
string msg = "View Added!";
Refresh(msg, Provers, comboBox1);
}
private void button7_Click(object sender, EventArgs e)
{
Phrases_Verb.Remove(comboBox1.SelectedItem.ToString());
Refresh("Data Deleted!", Phrases_Verb, comboBox1);
}
private void button9_Click(object sender, EventArgs e)
{
Refresh("View Added!", Phrases_Verb, comboBox1);
}
private void button12_Click(object sender, EventArgs e)
{
Refresh("View Added!", Slng, comboBox1);
}
private void button10_Click(object sender, EventArgs e)
{
Slng.Remove(comboBox1.SelectedItem.ToString());
Refresh("Data Deleted!", Slng, comboBox1);
}
private void button13_Click(object sender, EventArgs e)
{
string id = "GOOD";
string me = "Good is use for more people";
comboBox2.Items.Add(id+" : "+me);
}
public void Refresh(string msg , List<string> proverb, ComboBox combo)
{
combo.Items.Clear();
foreach (var item in proverb)
{
combo.Items.Add(item);
}
MessageBox.Show(msg);
}
private void button5_Click(object sender, EventArgs e)
{
try
{
if (textBox1.Text == "")
{
MessageBox.Show("Please Select");
}
else
{
Provers.Remove(comboBox1.SelectedItem.ToString());
Provers.Add(textBox1.Text);
Refresh("View Updated", Provers, comboBox1);
}
}
catch { MessageBox.Show("Something wrong"); }
//textBox1.Text = comboBox1.SelectedItem.ToString();
// select[1] = "sdf";
}
private void button8_Click(object sender, EventArgs e)
{
try
{
if (textBox1.Text == "")
{
MessageBox.Show("Please Select");
}
else
{
Phrases_Verb.Remove(comboBox1.SelectedItem.ToString());
Phrases_Verb.Add(textBox1.Text);
Refresh("View Updated", Phrases_Verb, comboBox1);
}
}
catch { MessageBox.Show("Something wrong"); }
}
private void button11_Click(object sender, EventArgs e)
{
try
{
if (textBox1.Text == "")
{
MessageBox.Show("Please Select");
}
else
{
Slng.Remove(comboBox1.SelectedItem.ToString());
Slng.Add(textBox1.Text);
Refresh("View Updated", Slng, comboBox1);
}
}
catch { MessageBox.Show("Something wrong"); }
}
private void button16_Click(object sender, EventArgs e)
{
string t1 = textBox2.Text+ " : "+textBox3.Text;
idoms.Add(t1);
Refresh("Value Added", idoms, comboBox2);
}
private void button14_Click(object sender, EventArgs e)
{
string t1 = textBox2.Text + " : " + textBox3.Text;
try
{
if (textBox2.Text == "" || textBox3.Text=="")
{
MessageBox.Show("Please Select");
}
else
{
Slng.Remove(comboBox2.SelectedItem.ToString());
Slng.Add(t1);
Refresh("View Updated", Slng, comboBox2);
}
}
catch { MessageBox.Show("Something wrong"); }
}
private void button13_Click_1(object sender, EventArgs e)
{
idoms.Remove(comboBox2.SelectedItem.ToString());
Refresh("Data Deleted!", idoms, comboBox2);
}
private void button15_Click(object sender, EventArgs e)
{
Refresh("View Added", idoms,comboBox2);
}
}
}
| 1bfe947784d2410a3067c96401f85072cdb9af5b | [
"C#"
] | 1 | C# | azharkhan1/EnglishBook-c- | d6f66186fafa8ef3fe24dff364c439849d4c5ef9 | f4551322c81ad4f527abac4825719d81ea24f4d8 |
refs/heads/master | <file_sep>include ':app'
rootProject.name = "3rdchapter"<file_sep># 3rdchapter
Запуск на эмуляторе андройд студио.<file_sep>package com.example.a3rdchapter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;
import java.text.BreakIterator;
import java.text.StringCharacterIterator;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView t;
t = (TextView)findViewById(R.id.theader);
t.setText(Html.fromHtml(getString(R.string.header)));
t = (TextView)findViewById(R.id.t1);
t.setText(Html.fromHtml(getString(R.string.stress_health)));
t = (TextView)findViewById(R.id.twwt);
t.setText(Html.fromHtml(getString(R.string.wwt)));
t = (TextView)findViewById(R.id.tcws);
t.setText(Html.fromHtml(getString(R.string.cws)));
t = (TextView)findViewById(R.id.tsyrtr);
t.setText(Html.fromHtml(getString(R.string.syrtr)));
t = (TextView)findViewById(R.id.tresil);
t.setText(Html.fromHtml(getString(R.string.resil)));
t = (TextView)findViewById(R.id.tresou);
t.setText(Html.fromHtml(getString(R.string.resou)));
t = (TextView)findViewById(R.id.tdesi);
t.setText(Html.fromHtml(getString(R.string.desi)));
}
} | 9731ffd6c4aada9dcfd88fab185168a0d349e5cb | [
"Markdown",
"Java",
"Gradle"
] | 3 | Gradle | kellareff/3rdchapter | 7fb0cdfcab2148ee34e67c7c319b824676ddc163 | 23bb9eba1ef08516d6fa6b29fda81b4080ec043a |
refs/heads/master | <file_sep>package com.yhz.thinker
import android.app.Activity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import org.jetbrains.anko.doAsync
import java.net.URL
class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(TextView(this).apply { text = "fix complete" })
}
override fun onStart() {
super.onStart()
doAsync {
val str = URL("http://stats.jpush.cn").readText()
Log.e(javaClass.simpleName, str)
}
}
}
| 89311affd8834cd244ee9ad62ed867476ae8c309 | [
"Kotlin"
] | 1 | Kotlin | yuhuazhu/Thinker | 7e0a3bf6e047ceb4facfee043a6f2757ca306071 | 00bc1718bde52d316bd5f55c63d0a4174e7d8321 |
refs/heads/master | <repo_name>tthiery/BrownEarth<file_sep>/Projects/Core/BrownEarth.Framework/Data.UnitOfWork/UnitOfWorkFactory.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using BrownEarth.Framework.Data.UnitOfWork.Extensions;
namespace BrownEarth.Data.UnitOfWork
{
/// <summary>
/// Unit of Work Factory.
/// </summary>
/// <remarks>
/// Creates a new unit of work on each request.
/// </remarks>
public class UnitOfWorkFactory<TDbContext> : IUnitOfWorkFactory
where TDbContext : DbContext, new()
{
private Func<TDbContext> factory;
/// <summary>
/// List of all extensions
/// </summary>
public List<IUnitOfWorkExtension> Extensions { get; private set; }
/// <summary>
/// Creates an instance
/// </summary>
public UnitOfWorkFactory()
{
Extensions = new List<IUnitOfWorkExtension>();
factory = () => new TDbContext();
}
/// <summary>
/// Creates an instance
/// </summary>
/// <param name="dbContextFactory">The factory used to create the db context.</param>
public UnitOfWorkFactory(Func<TDbContext> dbContextFactory)
: this()
{
factory = dbContextFactory;
}
/// <summary>
/// Creates a unit of work.
/// </summary>
/// <returns></returns>
public IUnitOfWork CreateUnitOfWork()
{
UnitOfWork<TDbContext> unitOfWork = new UnitOfWork<TDbContext>(factory, Extensions);
return unitOfWork;
}
/// <summary>
/// Initialize the database from the model
/// </summary>
public void CreateDatabase()
{
if (this.factory == null)
{
throw new InvalidOperationException("UnitOfWorkFactory.factory is not set");
}
using (TDbContext container = factory())
{
container.Database.Delete();
container.Database.Create();
}
}
}
}
<file_sep>/Projects/Core/BrownEarth.TestApp/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BrownEarth.Data.UnitOfWork;
using BrownEarth.Framework.Data.UnitOfWork.Extensions.ChangeHistory;
namespace BrownEarth.TestApp
{
class Program
{
static void Main(string[] args)
{
IUnitOfWorkFactory unitOfWorkFactory = new UnitOfWorkFactory<TestModelContainer>()
{
Extensions =
{
new ChangeHistoryExtension<History>((id, now, userName, reasonForChange, change) => new History() {
Id = id,
Time = now,
UserName = userName,
ReasonForChange = reasonForChange,
Change = change.ToString(),
}),
},
};
unitOfWorkFactory.CreateDatabase();
using (IUnitOfWork unitOfWork = unitOfWorkFactory.CreateUnitOfWork())
{
IGenericRepository<Test> testRepository = unitOfWork.RetrieveRepository<Test>();
Test t = new Test()
{
Id = 1,
Foo = "Hello World",
};
Test t2 = new Test()
{
Id = 2,
Foo = "Hello World 2",
};
testRepository.Insert(t);
testRepository.Insert(t2);
unitOfWork.Save("tthiery", "Creating initial test data set");
}
using (IUnitOfWork unitOfWork = unitOfWorkFactory.CreateUnitOfWork())
{
IGenericRepository<Test> testRepository = unitOfWork.RetrieveRepository<Test>();
Test t_modified = testRepository.Query().FirstOrDefault(x => x.Id == 1);
t_modified.Foo = "abcd";
testRepository.Update(t_modified);
unitOfWork.Save("tthiery", "Changing something");
}
Console.ReadLine();
}
}
}
<file_sep>/Projects/Core/BrownEarth.Framework/Properties/AssemblyInfo.cs
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("BrownEarth.Framework Core")]
[assembly: AssemblyDescription("An unit of work API for Entity Framework's DbContext")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Thiery Labs")]
[assembly: AssemblyProduct("BrownEarth.Framework")]
[assembly: AssemblyCopyright("Copyright 2012 - 2014, <NAME> under the terms of MIT License")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: AssemblyVersion("0.3.0.*")]
[assembly: AssemblyFileVersion("0.3.0.0")]
[assembly: AssemblyInformationalVersion("0.3.0.0")]
<file_sep>/Projects/Core/BrownEarth.Framework/Data.UnitOfWork/UnitOfWork.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Xml.Linq;
using BrownEarth.Framework.Data.UnitOfWork.Extensions;
namespace BrownEarth.Data.UnitOfWork
{
/// <summary>
/// A unit of work against the database. Manages the lifecycle of a DbContext and allows fast and easy access using
/// Repositories
/// </summary>
/// <typeparam name="TDbContext">The db context which should be managed by this unit of work.</typeparam>
public class UnitOfWork<TDbContext> : IUnitOfWork
where TDbContext : DbContext, new()
{
/// <summary>
/// The wrapped DbContext which lifecycle is managed by this unit of work.
/// </summary>
private TDbContext dbContext;
/// <summary>
/// The extensions defined in the factory.
/// </summary>
private IList<IUnitOfWorkExtension> extensions;
/// <summary>
/// The dictionary of access repositories. Repositories are re-used within the lifecycle of a unit of work.
/// </summary>
private Dictionary<Type, object> repositories;
/// <summary>
/// Informs about an ongoing save operation for a unit of work.
/// </summary>
public event EventHandler<EventArgs> Saving;
/// <summary>
/// Informs about an ongoing disposing for a unit of work.
/// </summary>
public event EventHandler<EventArgs> Disposing;
/// <summary>
/// Internal constructor to create a unit of work. Usually done by the UnitOfWorkFactory.
/// </summary>
/// <param name="factory">The factory used to initalize a new db context</param>
/// <param name="extensions">Extensions used for this unit of work</param>
internal UnitOfWork(Func<TDbContext> factory, IList<IUnitOfWorkExtension> extensions)
{
if (factory == null)
{
throw new ArgumentNullException("factory");
}
dbContext = factory();
dbContext.Configuration.AutoDetectChangesEnabled = false; // most simplest POCOs (fast and movable between containers)
dbContext.Configuration.LazyLoadingEnabled = false; // fast
dbContext.Configuration.ProxyCreationEnabled = false; // most simplest POCOs and fast
repositories = new Dictionary<Type, object>();
this.extensions = extensions ?? new List<IUnitOfWorkExtension>();
}
/// <summary>
/// Returns a repository to the provided entity within the used DbContext.
/// </summary>
/// <typeparam name="TEntity">The entity type which should be managed by this repository</typeparam>
/// <returns>A repository to access data on the DbContext</returns>
public IGenericRepository<TEntity> RetrieveRepository<TEntity>() where TEntity : class
{
Type t = typeof(TEntity);
IGenericRepository<TEntity> result = null;
if (repositories.ContainsKey(t))
{
result = repositories[t] as IGenericRepository<TEntity>;
}
else
{
result = new GenericRepository<TDbContext, TEntity>(dbContext);
repositories.Add(t, result);
}
return result;
}
/// <summary>
/// Saves all pending data in all repositories which were used during the lifetime of the unit of work.
/// </summary>
/// <param name="userName">The user name</param>
/// <param name="reasonForChange">The reason for change</param>
public void Save(string userName, string reasonForChange)
{
try
{
OnSaving();
foreach (IUnitOfWorkExtension extension in extensions)
{
extension.OnSaving(dbContext, userName, reasonForChange);
}
dbContext.SaveChanges();
}
catch (Exception)
{
throw;
}
}
#region Event Managers
/// <summary>
/// Manager for event Saving
/// </summary>
private void OnSaving()
{
if (Saving != null)
{
Saving(this, EventArgs.Empty);
}
}
/// <summary>
/// Manager for event Disposing
/// </summary>
private void OnDisposing()
{
if (Disposing != null)
{
Disposing(this, EventArgs.Empty);
}
}
#endregion
#region Disposing
private bool disposed = false;
/// <summary>
/// Cleanup the unit of work (usually done within a using block).
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
OnDisposing();
dbContext.Dispose();
}
}
this.disposed = true;
}
/// <summary>
/// Disposing implementation
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
}
<file_sep>/Projects/Core/BrownEarth.Framework/Data.UnitOfWork/GenericRepository.cs
using System.Data;
using System.Data.Entity;
using System.Linq;
namespace BrownEarth.Data.UnitOfWork
{
/// <summary>
/// A repository implementation to ease the use of a proxy-, tracking- and lazy loading-less DbContext.
/// </summary>
/// <typeparam name="TEntity">The entity type which is managed by this repositories.</typeparam>
/// <remarks>
/// Repositories are shared between actions on the same unit of work. When the unit of work is saved, they are invalid.
/// </remarks>
public class GenericRepository<TDbContext, TEntity> : IGenericRepository<TEntity>
where TEntity : class
where TDbContext : DbContext
{
/// <summary>
/// The db context which hosts the current set (as unit of work).
/// </summary>
private TDbContext context;
/// <summary>
/// The db set which hosts all the modified entities
/// </summary>
private DbSet<TEntity> dbSet;
/// <summary>
/// Internal constructor used inside of UnitOfWork
/// </summary>
/// <param name="context"></param>
internal GenericRepository(TDbContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
/// <summary>
/// Interface to query arbitrary data from the set. The provided includes are included in the entity framework.
/// </summary>
/// <param name="includes"></param>
/// <returns></returns>
public virtual IQueryable<TEntity> Query(params string[] includes)
{
IQueryable<TEntity> query = dbSet;
if (includes != null)
{
foreach (string include in includes)
{
query = query.Include(include);
}
}
return query;
}
/// <summary>
/// Returns an entity instance by its id.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public virtual TEntity Find(object id)
{
return dbSet.Find(id);
}
/// <summary>
/// Inserts a new entity in the db set.
/// </summary>
/// <param name="entity"></param>
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
/// <summary>
/// Deletes a entity with the given id
/// </summary>
/// <param name="id"></param>
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
/// <summary>
/// Delete the given entity instance.
/// </summary>
/// <param name="entityToDelete"></param>
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
/// <summary>
/// Marks this entity as being modified (tracking is not activated).
/// </summary>
/// <param name="entityToUpdate"></param>
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
/// <summary>
/// Attach the entity to the set (e.g. transferred from another unit of work).
/// </summary>
/// <param name="entityToAttach"></param>
public virtual void Attach(TEntity entityToAttach)
{
dbSet.Attach(entityToAttach);
}
}
}<file_sep>/Projects/Core/BrownEarth.Framework/Data.UnitOfWork/IUnitOfWorkFactory.cs
namespace BrownEarth.Data.UnitOfWork
{
/// <summary>
/// Unit of Work Factory.
/// </summary>
/// <remarks>
/// Creates a new unit of work on each request.
/// </remarks>
public interface IUnitOfWorkFactory
{
/// <summary>
/// Creates a unit of work.
/// </summary>
/// <returns></returns>
IUnitOfWork CreateUnitOfWork();
/// <summary>
/// Initialize the database from the model
/// </summary>
void CreateDatabase();
}
}
<file_sep>/Projects/Core/BrownEarth.Framework/Data.UnitOfWork/IUnitOfWork.cs
using System;
namespace BrownEarth.Data.UnitOfWork
{
/// <summary>
/// A unit of work against the database. Manages the lifecycle of a DbContext and allows fast and easy access using
/// Repositories
/// </summary>
public interface IUnitOfWork : IDisposable
{
/// <summary>
/// Returns a repository to the provided entity within the used DbContext.
/// </summary>
/// <typeparam name="TEntity">The entity type which should be managed by this repository</typeparam>
/// <returns>A repository to access data on the DbContext</returns>
IGenericRepository<TEntity> RetrieveRepository<TEntity>() where TEntity : class;
/// <summary>
/// Saves all pending data in all repositories which were used during the lifetime of the unit of work.
/// </summary>
/// <param name="userName">The user name</param>
/// <param name="reasonForChange">The reason for change</param>
void Save(string userName, string reasonForChange);
}
}
<file_sep>/Projects/Core/BrownEarth.Framework/Data.UnitOfWork.Extensions.ChangeHistory/ChangeHistoryExtension.cs
using System;
using System.Data.Entity;
using System.Xml.Linq;
namespace BrownEarth.Framework.Data.UnitOfWork.Extensions.ChangeHistory
{
/// <summary>
/// Write a change history into an entity.
/// </summary>
/// <typeparam name="THistoryEntity"></typeparam>
public class ChangeHistoryExtension<THistoryEntity> : IUnitOfWorkExtension
where THistoryEntity : class, new()
{
private Func<Guid, DateTimeOffset, string, string, XElement, THistoryEntity> factory;
/// <summary>
/// Creates a new instance
/// </summary>
/// <param name="factory">The factory to create history entries</param>
public ChangeHistoryExtension(Func<Guid, DateTimeOffset, string, string, XElement, THistoryEntity> factory)
{
this.factory = factory;
}
/// <summary>
/// Converts the existing state entities in XML structures.
/// </summary>
/// <param name="dbContext"></param>
/// <param name="userName"></param>
/// <param name="reasonForChange"></param>
public void OnSaving(DbContext dbContext, string userName, string reasonForChange)
{
ChangeHistoryWriter writer = new ChangeHistoryWriter();
DateTimeOffset now = DateTimeOffset.Now;
Guid changeId = Guid.NewGuid();
XElement bundle = writer.CreateChangeHistoryBundle(dbContext, changeId, userName, reasonForChange, now, null);
THistoryEntity historyEntry = factory(changeId, now, userName, reasonForChange, bundle); //TODO: Sequencing missing
if (historyEntry == null)
{
throw new InvalidOperationException("Factory did not produce a THistoryEntity instance");
}
DbSet<THistoryEntity> set = dbContext.Set<THistoryEntity>();
if (set != null)
{
set.Add(historyEntry);
}
else
{
new InvalidOperationException("THistoryEntity not a valid set on the DbContext");
}
}
}
}
<file_sep>/Projects/Core/BrownEarth.Framework/Data.UnitOfWork.Extensions/IUnitOfWorkExtension.cs
using System.Data.Entity;
namespace BrownEarth.Framework.Data.UnitOfWork.Extensions
{
/// <summary>
/// Specifies the interface for extension points to the unit of work infrastructure
/// </summary>
public interface IUnitOfWorkExtension
{
/// <summary>
/// Is invoked before the unit of work is commited to the database.
/// </summary>
/// <param name="dbContext"></param>
/// <param name="userName"></param>
/// <param name="reasonForChange"></param>
void OnSaving(DbContext dbContext, string userName, string reasonForChange);
}
}
<file_sep>/Projects/Core/BrownEarth.Framework/Data.UnitOfWork.Extensions.ChangeHistory/ChangeHistoryWriter.cs
using System;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Linq;
namespace BrownEarth.Framework.Data.UnitOfWork.Extensions.ChangeHistory
{
/// <summary>
/// Helper class to create a change history entry
/// </summary>
internal class ChangeHistoryWriter
{
private XNamespace Namespace = "http://labs.thiery.info/2013/BrownEarth/1.0.0/ChangeHistory";
/// <summary>
/// Formats a entity into an XML node describing the changes.
/// </summary>
/// <param name="dbContext"></param>
/// <param name="changeId"></param>
/// <param name="userName"></param>
/// <param name="reasonForChange"></param>
/// <param name="now"></param>
/// <param name="previousChange"></param>
/// <returns></returns>
internal XElement CreateChangeHistoryBundle(DbContext dbContext, Guid changeId, string userName, string reasonForChange, DateTimeOffset now, XElement previousChange)
{
if (dbContext == null)
{
throw new ArgumentNullException("dbContext");
}
if (string.IsNullOrEmpty(userName))
{
throw new ArgumentException("userName cannot be empty", "userName");
}
if (string.IsNullOrEmpty(reasonForChange))
{
throw new ArgumentException("reasonForChange cannot be empty", "reasonForChange");
}
Guid previousId = Guid.Empty;
string previousChecksum = string.Empty;
if (previousChange != null)
{
string previousIdAsString = previousChange.Element(Namespace + "Change")
.Attributes("Id")
.Select(x => x.Value)
.FirstOrDefault();
if (string.IsNullOrWhiteSpace(previousIdAsString) == false)
{
previousId = new Guid(previousIdAsString);
}
previousChecksum = CreateChecksum(previousChange);
}
XElement element = new XElement(Namespace + "Change",
new XAttribute("Id", changeId),
new XAttribute("DateTime", now),
new XAttribute("UserName", userName),
new XAttribute("ReasonForChange", reasonForChange),
new XAttribute("PreviousId", previousId),
new XAttribute("PreviousChecksum", previousChecksum)
);
foreach (DbEntityEntry entry in dbContext.ChangeTracker.Entries()
.Where(x => x.State == EntityState.Added || x.State == EntityState.Deleted || x.State == EntityState.Modified))
{
string entityName = entry.Entity.GetType().Name;
//Guid id = (Guid)entry.Entity.GetType().GetProperty("Id").GetValue(entry.Entity, null);
string id = CreateCompositeKey(dbContext, entry.Entity);
EntityState state = entry.State;
XElement entryElement = new XElement(Namespace + "Item",
new XAttribute(Namespace + "Type", state.ToString()),
new XElement(Namespace + "Entity", entityName),
new XElement(Namespace + "Id", id)
);
if (state == EntityState.Modified)
{
foreach (string propertyName in entry.OriginalValues.PropertyNames)
{
object originalValue = entry.OriginalValues.GetValue<object>(propertyName);
object currentValue = entry.CurrentValues.GetValue<object>(propertyName);
if (!object.Equals(originalValue, currentValue))
{
string originalValueAsString = originalValue == null ? "(null)" : originalValue.ToString();
string currentValueAsString = currentValue == null ? "(null)" : currentValue.ToString();
if (!string.Equals(originalValueAsString, currentValueAsString))
{
entryElement.Add(new XElement(Namespace + "Data",
new XElement(Namespace + "PreviousValue", originalValueAsString),
new XElement(Namespace + "CurrentValue", currentValueAsString)
));
}
}
}
}
element.Add(entryElement);
}
return element;
}
/// <summary>
/// Creates a checksum over the change
/// </summary>
/// <param name="previousChange"></param>
/// <returns></returns>
private string CreateChecksum(XElement previousChange)
{
using (HashAlgorithm hash = SHA1.Create())
{
string fragment = previousChange.ToString();
byte[] data = Encoding.UTF8.GetBytes(fragment);
byte[] hashAsBytes = hash.ComputeHash(data);
string hashAsString = BitConverter.ToString(hashAsBytes);
return hashAsString;
}
}
/// <summary>
/// Creates a composite key for the given entity
/// </summary>
/// <param name="context"></param>
/// <param name="entity"></param>
/// <returns></returns>
private string CreateCompositeKey(DbContext context, object entity)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (entity == null)
{
throw new ArgumentNullException("entity");
}
Type t = entity.GetType();
var key = ((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.GetObjectStateEntry(entity).EntitySet.ElementType.KeyMembers;
string compositeKey = string.Join("_", key.Select(x => t.GetProperty(x.Name).GetValue(entity).ToString()));
return compositeKey;
}
}
}<file_sep>/Projects/Core/BrownEarth.Framework/Data.UnitOfWork/IGenericRepository.cs
using System.Linq;
namespace BrownEarth.Data.UnitOfWork
{
/// <summary>
/// A repository implementation to ease the use of a proxy-, tracking- and lazy loading-less DbContext.
/// </summary>
/// <typeparam name="TEntity">The entity type which is managed by this repositories.</typeparam>
/// <remarks>
/// Repositories are shared between actions on the same unit of work. When the unit of work is saved, they are invalid.
/// </remarks>
public interface IGenericRepository<TEntity>
where TEntity : class
{
/// <summary>
/// Interface to query arbitrary data from the set. The provided includes are included in the entity framework.
/// </summary>
/// <param name="includes">The list of all navigateable properties which should be returned in the query.</param>
/// <returns>A IQueryable directly addressing the DbSet below.</returns>
IQueryable<TEntity> Query(params string[] includes);
/// <summary>
/// Returns an entity instance by its id.
/// </summary>
/// <param name="id">The id of the entity instance to find</param>
/// <returns></returns>
TEntity Find(object id);
/// <summary>
/// Inserts a new entity in the db set.
/// </summary>
/// <param name="entity">The entity to insert. Use attach to add a already persisted element from another set.</param>
void Insert(TEntity entity);
/// <summary>
/// Deletes a entity with the given id
/// </summary>
/// <param name="id">The id of the entity instance to delete.</param>
void Delete(object id);
/// <summary>
/// Delete the given entity instance.
/// </summary>
/// <param name="entityToDelete">The entity to delete</param>
void Delete(TEntity entityToDelete);
/// <summary>
/// Marks this entity as being modified (tracking is not activated).
/// </summary>
/// <param name="entityToUpdate">The entity to update</param>
void Update(TEntity entityToUpdate);
/// <summary>
/// Attach the entity to the set (e.g. transferred from another unit of work).
/// </summary>
/// <param name="entityToAttach">The entity to attach to the set of the repository</param>
void Attach(TEntity entityToAttach);
}
}
| 29479c26eb63d5268701d1046f423396d6d2c2b2 | [
"C#"
] | 11 | C# | tthiery/BrownEarth | 6435ce0468caf29bd1013690d1855de27cb5af16 | 32992f9672c4baf9dc42c0126480b8e2111411ff |
refs/heads/master | <file_sep>import pygame
class Block:
WIDTH = 5
HEIGHT = 5
COLOR = (190, 90, 37)
def __init__(self, pos_x, pos_y):
self.pos_x = pos_x
self.pos_y = pos_y
self.alive = True
def draw(self, win):
""" Add a block surface onto win, centred on its position """
pygame.draw.rect(
win,
Block.COLOR,
(int(self.pos_x - Block.WIDTH/2),
int(self.pos_y - Block.HEIGHT/2),
Block.WIDTH,
Block.HEIGHT)
)
def check_if_hit(self, projectiles):
""" Block can be destroyed by a Projectile object. If the block is hit
by a projectile(s), the projectile(s) has it's damage value decremented
and if the value is 1 it is removed.
"""
to_remove = []
for projectile in projectiles:
if ((self.pos_x - Block.WIDTH/2 <= projectile.pos_x <= self.pos_x + Block.WIDTH/2)
and (self.pos_y - Block.HEIGHT/2 <= projectile.pos_y <= self.pos_y + Block.HEIGHT/2)):
self.alive = False
if projectile.damage <= 1:
to_remove.append(projectile)
else:
projectile.damage -= 1
for projectile in to_remove:
projectiles.remove(projectile)
def update(self, projectiles):
""" Defines what the block entity does every frame """
self.check_if_hit(projectiles)
@staticmethod
def update_all(blocks, projectiles):
to_remove = []
for block in blocks:
if block.alive:
block.update(projectiles)
else:
to_remove.append(block)
for block in to_remove:
blocks.remove(block)
@staticmethod
def draw_all(win, blocks):
for block in blocks:
block.draw(win)
<file_sep>import sys
import pygame
from pong.pong import Pong
from space_invaders.space_invaders import SpaceInvaders
from game_of_life.game_of_life import GameOfLife
from pacman.pacman import Pacman
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
INCORRECT_ARGS_MESSAGE = "Incorrect arguments supplied.\n" \
+ "Expected use: python main.py <game> where game is chosen from:\n" \
+ "\tpong\n" \
+ "\tspace_invaders\n" \
+ "\tpacman\n" \
+ "\tgol"
def main():
prog = None
if len(sys.argv) == 2:
prog = sys.argv[1]
else:
print(INCORRECT_ARGS_MESSAGE)
return
pygame.init()
win = pygame.display.set_mode(
(WINDOW_WIDTH, WINDOW_HEIGHT), pygame.RESIZABLE)
pygame.display.set_caption("Arcade")
if prog == "pong":
Pong(win)
elif prog == "space_invaders" or prog == "space":
SpaceInvaders(win)
elif prog == "pacman":
Pacman(win)
elif prog == "game_of_life" or prog == "gol":
GameOfLife(win)
else:
print(INCORRECT_ARGS_MESSAGE)
return
if __name__ == "__main__":
main()
<file_sep>import pygame
import math
import random
from helper_code import scale
class Pong:
GAME_WIDTH = 500
GAME_HEIGHT = 500
FPS = 120
PLAYER_WIDTH = 10
PLAYER_HEIGHT = 40
PLAYER_VEL = 4
MAX_BOUNCE_ANGLE = 1 # ~60 degrees
BALL_SIZE = 10
BALL_SPEED = 3
def __init__(self, win):
""" This is the top-level code for pong. We are passed a window to
draw into and do so continually until the user exits.
"""
self.p1_pos = 250
self.p2_pos = 250
self.p1_score = 0
self.p2_score = 0
self.ball_pos = (250, 250)
self.ball_vx = random.choice([1, -1]) * Pong.BALL_SPEED / 2
self.ball_vy = 0
pygame.init()
pygame.display.set_caption("Pong")
game_surface = pygame.Surface((self.GAME_WIDTH, self.GAME_HEIGHT))
clock = pygame.time.Clock()
pygame.font.init()
font = pygame.font.Font(pygame.font.get_default_font(), 60)
run = True
while run:
# pygame.time.delay(10) # pause for 10ms (~100fps)
clock.tick(self.FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.VIDEORESIZE:
win = pygame.display.set_mode(
(event.w, event.h), pygame.RESIZABLE)
self.window_width = event.w
self.window_height = event.h
keys = pygame.key.get_pressed()
if keys[pygame.K_w] and (self.p1_pos > 0):
self.p1_pos -= self.PLAYER_VEL
if keys[pygame.K_s] and (self.p1_pos < 499 - Pong.PLAYER_HEIGHT):
self.p1_pos += self.PLAYER_VEL
if keys[pygame.K_UP] and(self.p2_pos > 0):
self.p2_pos -= self.PLAYER_VEL
if keys[pygame.K_DOWN] and (self.p2_pos < 499 - Pong.PLAYER_HEIGHT):
self.p2_pos += self.PLAYER_VEL
self.ball_pos = (
self.ball_pos[0] + self.ball_vx,
self.ball_pos[1] + self.ball_vy)
# ball bounces off top or bottom of screen
if (self.ball_pos[1] <= 0) or (self.ball_pos[1] >= 499):
self.ball_vy = -self.ball_vy
# ball bounces off players
if ((30 <= self.ball_pos[0] <= 40)
and (self.p1_pos <= self.ball_pos[1] <= self.p1_pos + Pong.PLAYER_HEIGHT)):
relative_intersect = (
self.p1_pos + Pong.PLAYER_HEIGHT/2) - self.ball_pos[1]
normalised_relative_intersect = relative_intersect / \
(Pong.PLAYER_HEIGHT / 2)
bounce_angle = normalised_relative_intersect * Pong.MAX_BOUNCE_ANGLE
self.ball_vx = Pong.BALL_SPEED * math.cos(bounce_angle)
self.ball_vy = - Pong.BALL_SPEED * math.sin(bounce_angle)
elif (460 <= self.ball_pos[0] <= 470
and (self.p2_pos <= self.ball_pos[1] <= self.p2_pos + Pong.PLAYER_HEIGHT)):
relative_intersect = (
self.p2_pos + Pong.PLAYER_HEIGHT/2) - self.ball_pos[1]
normalised_relative_intersect = relative_intersect / \
(Pong.PLAYER_HEIGHT / 2)
bounce_angle = normalised_relative_intersect * Pong.MAX_BOUNCE_ANGLE
self.ball_vx = - Pong.BALL_SPEED * math.cos(bounce_angle)
self.ball_vy = - Pong.BALL_SPEED * math.sin(bounce_angle)
# if ball off screen reset and update score
if (self.ball_pos[0] <= 0):
self.ball_pos = (250, 250)
self.ball_vx = self.BALL_SPEED / 2
self.ball_vy = 0
self.p2_score += 1
elif (self.ball_pos[0] >= 499):
self.ball_pos = (250, 250)
self.ball_vx = -self.BALL_SPEED / 2
self.ball_vy = 0
self.p1_score += 1
# draw screen
game_surface.fill((0, 0, 0))
dashes = 25
dash_length = (500//dashes)
for i in range(dashes):
pygame.draw.line(
game_surface,
(255, 255, 255),
(250, i*(dash_length) + 10),
(250, i*(dash_length) + dash_length//2 + 10),
2)
pygame.draw.rect(
game_surface,
(255, 255, 255),
(int(self.ball_pos[0] - Pong.BALL_SIZE/2),
int(self.ball_pos[1] - Pong.BALL_SIZE/2),
Pong.BALL_SIZE,
Pong.BALL_SIZE)
)
pygame.draw.rect(
game_surface,
(255, 255, 255),
(30, self.p1_pos, Pong.PLAYER_WIDTH, Pong.PLAYER_HEIGHT))
pygame.draw.rect(
game_surface,
(255, 255, 255),
(460, self.p2_pos, Pong.PLAYER_WIDTH, Pong.PLAYER_HEIGHT))
p1_text = font.render(str(self.p1_score), True, (255, 255, 255))
p2_text = font.render(str(self.p2_score), True, (255, 255, 255))
game_surface.blit(p1_text, (int(200 - p1_text.get_rect().width/2), 20))
game_surface.blit(p2_text, (int(300 - p2_text.get_rect().width/2), 20))
scale(
win,
game_surface,
(self.GAME_WIDTH, self.GAME_HEIGHT),
(self.window_width, self.window_height))
pygame.display.update()
pygame.font.quit()
pygame.quit()
<file_sep>import pygame
class Projectile:
WIDTH = 5
HEIGHT = 20
COLOR = (145, 145, 145)
DAMAGE = 2
def __init__(self, pos_x, pos_y, up: 'boolean', velocity):
self.pos_x = pos_x
self.pos_y = pos_y
self.velocity = velocity
self.direction = up
self.damage = self.DAMAGE
def draw(self, win):
""" Add a projectile surface onto win, centred on its position """
pygame.draw.rect(
win,
Projectile.COLOR,
(int(self.pos_x - self.WIDTH/2),
int(self.pos_y - self.HEIGHT/2),
self.WIDTH,
self.HEIGHT)
)
def update(self, projectiles, window_height):
""" Defines what a projectile does every frame """
if self.direction == True:
self.pos_y -= self.velocity
else:
self.pos_y += self.velocity
self.remove_offscreen(projectiles, window_height)
def remove_offscreen(self, projectiles, window_height):
""" Check if the projectile is still on screen. Remove it from
projectiles if it is not
"""
if ((self.pos_y < 0) or (self.pos_y > window_height)):
projectiles.remove(self)
@staticmethod
def update_all(projectiles, window_height):
for projectile in projectiles:
projectile.update(projectiles, window_height)
@staticmethod
def draw_all(win, projectiles):
for projectile in projectiles:
projectile.draw(win)
<file_sep>import pygame
import random
from copy import copy, deepcopy
class GameOfLife:
GAME_WIDTH = 500
GAME_HEIGHT = 500
ALIVE_COLOR = (255, 255, 255)
DEAD_COLOR = (0, 0, 0)
FPS = 60 # the rate that the window updates
def __init__(self, win):
""" Initialise pygame and then execute loop until player closes window """
pygame.init()
pygame.display.set_caption("Game of Life")
game_surface = pygame.Surface(
(self.GAME_WIDTH, self.GAME_HEIGHT), pygame.RESIZABLE)
clock = pygame.time.Clock()
self.x_dimension = 20
self.y_dimension = 20
self.cell_size = 25
self.rate = 1 # the rate at which the animation progresses
self.last_rate = 1 # used for pause mechanics
self.grid = GameOfLife.make_random_grid(
self.x_dimension, self.y_dimension)
frameCount = 0
run = True
while run:
clock.tick(self.FPS)
frameCount += 1
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.VIDEORESIZE:
win = pygame.display.set_mode(
(event.w, event.h), pygame.RESIZABLE)
self.window_width = event.w
self.window_height = event.h
keys_pressed = pygame.key.get_pressed()
if keys_pressed[pygame.K_1]:
self.rate = 1
frameCount = 0
if keys_pressed[pygame.K_2]:
self.rate = 2
frameCount = 0
if keys_pressed[pygame.K_3]:
self.rate = 3
frameCount = 0
if keys_pressed[pygame.K_SPACE]:
if self.rate == 0:
self.rate = self.last_rate
else:
self.last_rate = self.rate
self.rate = 0
frameCount = 0
continue
if (self.rate != 0) and (frameCount * self.rate) % self.FPS == 0:
frameCount = 0
self.grid = GameOfLife.update_grid(self.grid)
self.draw_grid(win)
pygame.display.update()
pygame.quit()
@classmethod
def make_random_grid(cls, x_dimension, y_dimension):
return [[random.choice([True, False]) for _ in range(x_dimension)] for _ in range(y_dimension)]
@classmethod
def update_grid(cls, grid):
newGrid = [[False for _ in range(len(grid[0]))]
for _ in range(len(grid))]
for x in range(len(grid[0])):
for y in range(len(grid)): # for each cell in the row
alive = grid[y][x]
num_neighbours = GameOfLife.num_neighbours(grid, x, y)
if alive and (num_neighbours == 2 or num_neighbours == 3):
newGrid[y][x] = True
elif num_neighbours == 3:
newGrid[y][x] = True
return newGrid
@classmethod
def num_neighbours(cls, grid, x, y):
count = 0
for x_lookup in range(x-1, x+2):
for y_lookup in range(y-1, y+2):
if (not (x_lookup < 0
or x_lookup >= len(grid[0])
or y_lookup < 0
or y_lookup >= len(grid))):
if grid[y_lookup][x_lookup]:
count += 1
return count
def draw_grid(self, win):
for y in range(self.y_dimension):
for x in range(self.x_dimension):
color = self.ALIVE_COLOR if self.grid[y][x] else self.DEAD_COLOR
pygame.draw.rect(
win,
color,
pygame.Rect(x * self.cell_size,
y * self.cell_size,
self.cell_size,
self.cell_size)
)
<file_sep>import pygame
from space_invaders.enemy import Enemy
from space_invaders.player import Player
from space_invaders.projectile import Projectile
from space_invaders.block import Block
from space_invaders.wave import Wave
from helper_code import scale
class SpaceInvaders:
GAME_WIDTH = 500
GAME_HEIGHT = 500
FPS = 120
def __init__(self, win):
""" This is the top-level code for space invaders. We are passed a
window to draw into and do so continually until the user exits.
"""
pygame.init()
pygame.display.set_caption("Space Invaders")
game_surface = pygame.Surface((self.GAME_WIDTH, self.GAME_HEIGHT))
clock = pygame.time.Clock()
pygame.font.init()
font = pygame.font.Font(pygame.font.get_default_font(), 20)
wave = Wave(self.GAME_WIDTH, self.GAME_HEIGHT)
run = True
while run:
# pygame.time.delay(10) # pause for some number of ms
clock.tick(self.FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.VIDEORESIZE:
win = pygame.display.set_mode(
(event.w, event.h), pygame.RESIZABLE)
self.window_width = event.w
self.window_height = event.h
keys = pygame.key.get_pressed()
# update everything
wave.update(keys)
# draw everything
game_surface.fill((0, 0, 0))
if wave.player.lives > 0:
wave.draw(game_surface)
lives_text = font.render(
"Lives: " + str(wave.player.lives), True, (255, 255, 255))
game_surface.blit(lives_text, (int(20), 20))
else:
lose_text = font.render("You Lose", True, (255, 0, 0))
lose_text = pygame.transform.scale2x(lose_text)
game_surface.blit(
lose_text,
(int((self.GAME_WIDTH - lose_text.get_width()) / 2),
int((self.GAME_HEIGHT - lose_text.get_height()) / 2))
)
scale(
win,
game_surface,
(self.GAME_WIDTH, self.GAME_HEIGHT),
(self.window_width, self.window_height))
# push updates to display
pygame.display.update()
pygame.font.quit()
pygame.quit()
<file_sep>import pygame
from helper_code import scale
class Pacman:
GAME_WIDTH = 224
GAME_HEIGHT = 288
FPS = 120
def __init__(self, win):
""" This is the top-level code for pacman. We are passed a window to
draw into and do so continually until the user exits.
"""
pygame.init()
pygame.display.set_caption("Pacman")
game_surface = pygame.Surface((self.GAME_WIDTH, self.GAME_HEIGHT))
clock = pygame.time.Clock()
run = True
while run:
clock.tick(self.FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.VIDEORESIZE:
win = pygame.display.set_mode(
(event.w, event.h), pygame.RESIZABLE)
self.window_width = event.w
self.window_height = event.h
pygame.draw.rect(
game_surface,
(255, 255, 255),
(10, 10, self.GAME_WIDTH - 20, self.GAME_HEIGHT - 20))
scale(
win,
game_surface,
(self.GAME_WIDTH, self.GAME_HEIGHT),
(self.window_width, self.window_height))
pygame.display.update()
pygame.quit()
<file_sep># arcade
Project written in [Python 3.8](https://www.python.org/) using [pygame 1.9.6](https://www.pygame.org/).
This is my attempt to become more familiar with Python 3. I have been using pygame as it is well documented and is adequate for the needs of these games.
My ultimate goal is to combine the individual games I have constructed here into an arcade machine with multiple games that a user can select between. Improved graphics and instructional menus would be a part of this.
## running the code
The primary module is `main.py` which can be ran with the name of the game you want to play - `{pong|space_invaders|pacman}`. eg. `python main.py pong`. Instructions on how to play the games is given below.
## the games so far
### pong
My version of Pong (trademark held by [Atari Interactive Inc.](https://www.atari.com/)) currently consists of one `pong.py` module which contains the class `Pong` which can be instantiated to start the game. The game is designed for two players. Player 1 can operate their paddle using the `W` and `S` keys, whilst player 2 can do so with the `UP ARROW` and `DOWN ARROW` keys.
<p align="center">
<img width="300" height="300" src="/pong/pong_demo.gif">
</p>
### space invaders
My version of Space Invaders (copyright held by [Taito Corporation](http://www.taito.com/)) is made using multiple modules and classes. The main module is `space_invaders.py` which contains the class `SpaceInvaders` which is instantiated to start the game. The player can move using the `A` and `D` keys or using the `LEFT ARROW` and `RIGHT ARROW` keys, and shoot using the `SPACE` bar.
<p align="center">
<img width="300" height="300" src="/space_invaders/space_invaders_demo.gif">
</p>
In the future I would like to implement a scoreboard, as well as the aliens progressively moving down the screen.
### game of life
My implementation of the Game of Life is made to be intuitive. The main module is `game_of_life.py` which contains the class `GameOfLife` which can be instantiated to begin the game. The user will be able to click cells to toggle their alive/dead state as well as play and pause execution with the `SPACE` key. the `LEFT ARROW` and `RIGHT ARROW` keys will move one time slice forwards and backwards in time.
### pacman
I have started but there is no real functionality yet.
## notes
* The choppy look of the GIF's below is purely a consequence of the file format limitations. In reality these programs run at 120fps, with the ability to run much faster if it were so desired.
* This project is very much a work in progress, and as much as I try to update this document to reflect the changes I am making, it is not always consistent with the code.
<file_sep>import pygame
import math
import random
from space_invaders.projectile import Projectile
class Enemy:
WIDTH = 30
HEIGHT = 30
LIVES = 1
COLOR = (129, 128, 14)
DELAY_BETWEEN_SHOTS = 500
MAX_DISPLACEMENT = 50
MAX_PHASE = 1000 # larger value leads to slower oscillation
PROJ_VELOCITY = 2
def __init__(self, pos_x, pos_y, can_fire: 'boolean'):
""" Enemies are entities with one life """
self.alive = True
self.pos_x = pos_x
self.can_fire = can_fire
self.original_pos_x = pos_x
self.pos_y = pos_y
self.count = int(Enemy.DELAY_BETWEEN_SHOTS * random.random())
self.lives = Enemy.LIVES
self.phase = 0
self.img = pygame.image.load('space_invaders\images\enemy1.png')
def draw(self, win):
""" Add an image onto win, centred on its position and scaled to
the size of the enemy """
win.blit(pygame.transform.scale(
self.img,
(Enemy.WIDTH, Enemy.HEIGHT)),
(int(self.pos_x - Enemy.WIDTH/2),
int(self.pos_y - Enemy.HEIGHT/2)))
def check_if_hit(self, enemies, projectiles):
""" Enemy can only be hit by a Projectile object travelling upwards.
If the enemy is hit by a projectile(s), the projectile(s) is/are
removed, and note that the enemy above can now fire.
We return the position of the enemy that can now fire.
"""
hit = False
to_remove = []
for projectile in projectiles:
if ((self.pos_x - Enemy.WIDTH/2 <= projectile.pos_x <= self.pos_x + Enemy.WIDTH/2)
and (self.pos_y - Enemy.HEIGHT/2 <= projectile.pos_y <= self.pos_y + Enemy.HEIGHT/2)
and (projectile.direction == True)):
to_remove.append(projectile)
hit = True
for proj in to_remove:
projectiles.remove(proj)
now_can_fire = None
if hit:
self.alive = False
self_pos = Enemy.find_index(enemies, self)
if self_pos[0] != 0: # if we are not already the top enemy
any_lower = False # any_lower will be set True if there are enemies below us still alive
for index, other in enumerate(enemies[self_pos[0]]):
if (index > self_pos[1]) and (other.alive == True):
any_lower = True
if not any_lower:
# find the next highest enemy by its index
# iterate over other in column
for y_index, other in enumerate(enemies[self_pos[0]]):
if (y_index < self_pos[1]) and (other.alive == True):
now_can_fire = other
if now_can_fire is not None:
now_can_fire.can_fire = True
def oscillate(self):
""" Updates the phase of the enemy and then updates the position
based on the new phase
"""
if self.phase == Enemy.MAX_PHASE:
self.phase = 0
else:
self.phase += 1
self.pos_x = self.original_pos_x + int(
Enemy.MAX_DISPLACEMENT * math.sin(2 * math.pi * (self.phase / Enemy.MAX_PHASE)))
def update(self, enemies, projectiles):
""" Defines what an enemy entity does every frame """
self.check_if_hit(enemies, projectiles)
if self.can_fire:
if self.count == 0:
self.count = Enemy.DELAY_BETWEEN_SHOTS
# projectile firing downwards
projectiles.append(Projectile(
self.pos_x, self.pos_y, False, Enemy.PROJ_VELOCITY))
else:
self.count -= 1
self.oscillate()
@staticmethod
def find_index(enemies, enemy):
""" Static method to find the index of enemy within enemies """
for i, column in enumerate(enemies):
if enemy in column:
return (i, column.index(enemy))
@staticmethod
def update_all(enemies, projectiles):
for column in enemies:
for enemy in column:
if enemy.alive:
enemy.update(enemies, projectiles)
@staticmethod
def draw_all(win, enemies):
for column in enemies:
for enemy in column:
if enemy.alive:
enemy.draw(win)
<file_sep>import pygame
from space_invaders.block import Block
from space_invaders.enemy import Enemy
from space_invaders.player import Player
from space_invaders.projectile import Projectile
class Wave:
""" A wave holds all of the state of the enemies, projectiles and player
on the screen at any given time. It is also responsible for updating and
drawind all of these entities whenever it is called to do so.
"""
EMEMIES_DIM = (6, 4)
ENEMIES_X_SPACING = 50
ENEMIES_Y_SPACING = 50
DEFENCE_SCREEN_POS = 350
DEFENCE_NUM = 3
DEFENCE_SPACING = 120
DEFENCE_STRUCTURE = [
[0, 0, 1, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 0],
[0, 1, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 0, 0, 0, 0, 1, 1],
]
def __init__(self, WINDOW_WIDTH, WINDOW_HEIGHT):
self.WINDOW_WIDTH = WINDOW_WIDTH
self.WINDOW_HEIGHT = WINDOW_HEIGHT
self.enemies = self.get_enemies()
self.blocks = self.get_blocks()
self.player = Player(250, 450)
self.projectiles = []
def update(self, keys):
""" Update all objects in the wave """
Block.update_all(self.blocks, self.projectiles)
Enemy.update_all(self.enemies, self.projectiles)
self.player.update(keys, self.WINDOW_WIDTH, self.projectiles)
Projectile.update_all(self.projectiles, self.WINDOW_HEIGHT)
def draw(self, win):
""" Draw all objects in the wave to win """
Block.draw_all(win, self.blocks)
Enemy.draw_all(win, self.enemies)
self.player.draw(win)
Projectile.draw_all(win, self.projectiles)
def get_enemies(self):
""" Enemies are grouped into columns. Initialise so that only the
bottom-most enemy can fire.
The returned array is such that enemies[0][3] is the enemy in the 1-st
column and the 4-th row (1-st row is the top of screen)
"""
enemies = []
total_width = (self.EMEMIES_DIM[0] - 1) * \
self.ENEMIES_X_SPACING + Enemy.WIDTH
left_offset = (self.WINDOW_WIDTH - total_width) / 2
for x in range(self.EMEMIES_DIM[0]):
column = []
for y in range(self.EMEMIES_DIM[1]):
column.append(Enemy(
self.ENEMIES_X_SPACING * x + left_offset,
self.ENEMIES_Y_SPACING * y + 100,
False))
enemies.append(column)
for column in enemies:
column[self.EMEMIES_DIM[1] - 1].can_fire = True
return enemies
def get_blocks(self):
""" Return a list of blocks to be displayed. These blocks are arranged
into multiple defences.
"""
blocks = []
total_width = (self.DEFENCE_NUM - 1) * self.DEFENCE_SPACING + \
len(self.DEFENCE_STRUCTURE[0]) * Block.WIDTH
left_offset = (self.WINDOW_WIDTH - total_width) / 2
for i in range(self.DEFENCE_NUM):
# draw one defence
for y in range(len(self.DEFENCE_STRUCTURE)):
for x in range(len(self.DEFENCE_STRUCTURE[0])):
if self.DEFENCE_STRUCTURE[y][x] == 1:
blocks.append(Block(
x * Block.WIDTH + self.DEFENCE_SPACING * i + left_offset,
y * Block.HEIGHT + self.DEFENCE_SCREEN_POS))
return blocks
<file_sep>import pygame
from space_invaders.projectile import Projectile
# from living_entity import LivingEntity
class Player:
WIDTH = 30
HEIGHT = 30
VELOCITY = 3
LIVES = 3
COLOR = (63, 68, 16)
DELAY_BETWEEN_SHOTS = 40
PROJ_VELOCITY = 4
def __init__(self, pos_x, pos_y):
""" Players are entities with three lives """
self.alive = True
self.pos_x = pos_x
self.pos_y = pos_y
self.lives = Player.LIVES
self.count = 0
self.img = pygame.image.load('space_invaders\images\player.png')
def draw(self, win):
""" Add an image onto win, centred on its position and scaled to
the size of the player
"""
if self.alive:
win.blit(pygame.transform.scale(
self.img,
(Player.WIDTH, Player.HEIGHT)),
(int(self.pos_x - Player.WIDTH/2),
int(self.pos_y - Player.HEIGHT/2)))
def check_if_hit(self, projectiles):
""" Player can only be hit by a Projectile object travelling downwards.
If the player is hit by a projectile(s), the projectile(s) is/are
removed.
"""
hit = False
if self.alive: # only check for collisions if entity is still alive
for projectile in projectiles:
if ((self.pos_x - Player.WIDTH/2 <= projectile.pos_x <= self.pos_x + Player.WIDTH/2)
and (self.pos_y - Player.HEIGHT/2 <= projectile.pos_y <= self.pos_y + Player.HEIGHT/2)
and (projectile.direction == False)):
projectiles.remove(projectile)
hit = True
if hit:
self.lives -= 1
if self.lives <= 0:
self.alive = False
def update(self, keys, window_width, projectiles):
""" Defines what the player entity does every frame """
if self.alive:
if ((keys[pygame.K_a] or keys[pygame.K_LEFT])
and (self.pos_x > Player.WIDTH)):
self.pos_x -= Player.VELOCITY
if ((keys[pygame.K_d] or keys[pygame.K_RIGHT])
and (self.pos_x < window_width - Player.WIDTH)):
self.pos_x += Player.VELOCITY
self.check_if_hit(projectiles)
if self.count == 0:
if (keys[pygame.K_SPACE]):
self.count = Player.DELAY_BETWEEN_SHOTS
# fire a projectile firing upwards
projectiles.append(Projectile(
self.pos_x, self.pos_y, True, Player.PROJ_VELOCITY))
else:
self.count -= 1
<file_sep>import pygame
pygame.init()
def scale(new_surface, old_surface, old_size, new_size):
""" Scale a surface onto another without stretching (with letterboxing) """
x_scale = new_size[0] / old_size[0]
y_scale = new_size[1] / old_size[1]
# scale_factor = min(x_scale, y_scale)
if x_scale < y_scale:
scale_factor = x_scale
x_offset = 0
y_offset = (new_size[1] - scale_factor * old_size[1]) / 2
else:
scale_factor = y_scale
x_offset = (new_size[0] - scale_factor * old_size[0]) / 2
y_offset = 0
new_surface.fill((0, 0, 0))
new_surface.blit(pygame.transform.scale(
old_surface,
(int(scale_factor * old_size[0]), int(scale_factor * old_size[1]))),
(x_offset, y_offset))
| c9c668b7429fac9a6297de7055042425cef1498d | [
"Markdown",
"Python"
] | 12 | Python | jjgry/arcade | 3e39b1e5dab7cf26c1fdd3df77f6d8b2150ae09d | 0af4f0fec547c9b1eb0858b14cf584b7ffca8046 |
refs/heads/master | <file_sep>package cz.dartcz.rescmdsblacklist;
import java.util.Arrays;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import cz.dartcz.rescmdsblacklist.listeners.PlayerListener;
public class ResCmdsBlacklist extends JavaPlugin {
private static Plugin _plugin;
private static JavaPlugin _javaPlugin;
@Override
public void onEnable() {
_plugin = this;
_javaPlugin = this;
PluginManager pm = getServer().getPluginManager();
if(pm.getPlugin("Residence") != null) {
pm.registerEvents(new PlayerListener(this), this);
} else {
consoleMessage(ChatColor.RED + "Plugin Residence not found. Disabling.");
pm.disablePlugin(_plugin);
return;
}
saveDefaultConfig();
}
@Override
public void onDisable() {
_plugin = null;
_javaPlugin = null;
unReg(new PlayerListener(this));
unRegPlugin(this);
}
public static void consoleMessage(String message){
ConsoleCommandSender console = Bukkit.getConsoleSender();
console.sendMessage(ChatColor.GREEN + "[" + _plugin.getName() + "] " + message);
}
public static void unReg(Listener... listeners) {
for (Listener l : listeners) {
HandlerList.unregisterAll(l);
}
}
public static void unRegPlugin(Plugin p) {
HandlerList.unregisterAll(p);
}
public static FileConfiguration config() {
return _plugin.getConfig();
}
@Override
public boolean onCommand(final CommandSender sender, Command cmd, String label, final String[] args) {
if(sender.hasPermission("rescmdsblacklist.admin")) {
if(args[0].equals("reload")) {
this.reloadConfig();
sender.sendMessage(ChatColor.GREEN + "[" + _plugin.getName() + "]" + " Reloaded config.");
}
} else {
sender.sendMessage(ChatColor.RED + "Na tento prikaz nemas opravneni.");
}
return false;
}
}
| ec304218263557e8e424611639f0f95740ec274f | [
"Java"
] | 1 | Java | DartCZ/ResCmdsBlacklist | add846e7c0ad0485c1a516d2429b08128c6da6e7 | cd0ce3172413c7445565bfada6fa267d78a3e6c7 |
refs/heads/master | <file_sep>import React from 'react';
function Browse(props) {
return (
<div>
<h3>Browse</h3>
</div>
);
}
export default Browse;<file_sep>import { Router as router } from "express";
import axios from "axios";
// define the default route that fetches all of our recipies
router.get("/", (req, res) => {
// data the conserves our API quota for development
const placeholderData = [
{
_id: "database1591127768852",
recipie: "Hello",
_createdOn: "2020-06-02T19:56:08.852Z",
_lastModifiedOn: "2020-06-02T19:56:08.852Z",
},
{
_id: "database1591134992139",
recipie: "New recipie",
_createdOn: "2020-06-02T21:56:32.139Z",
_lastModifiedOn: "2020-06-02T21:56:32.139Z",
},
];
try {
// add api call
res.json({ recipies: placeholderData });
} catch (e) {
console.log(e);
res.status(500).send("Error.");
}
});
router.post("/add", (req, res) => {
// extract recipie text from request body
const { recipie } = req.body;
const data = {
recipie,
};
console.log(recipie);
try {
// add api call
res.json({
message: "recipie added",
});
} catch (e) {
console.log(e);
res.status(500).send("Error.");
}
});
router.post("/delete", (req, res) => {
// extract the recipie id to delete from request body
const { recipieId } = req.body;
console.log(recipieId);
try {
// add api call
res.send("recipie deleted");
} catch (e) {
console.log(e);
res.status(500).send("Error.");
}
});
export default router;
<file_sep>import { StatusBar } from 'expo-status-bar';
import React from 'react';
import {
StyleSheet,
Text,
View,
Image,
TouchableHighlight,
Alert,
SafeAreaView,
Dimensions,
Platform,
Button} from 'react-native';
import { useDimensions, useDeviceOrientation } from '@react-native-community/hooks';
//SafeAreaView add padding on the top to ensure text is within safe area
export default function App() {
const {landscape} =useDeviceOrientation();
console.log(useDimensions())
console.log(useDeviceOrientation())
//console.log(Dimensions.get('screen'))
const handlePress = () => console.log('text pressed')
return (
<SafeAreaView style={styles.container}>
<Text numberOfLines={1} onPress={handlePress}>Hello World!</Text>
{/* <Image source={require('./assets/icon.png')}/> */}
<View style={{
width: '50%',
height: landscape ? "100%" : "30%",
backgroundColor: 'dodgerblue'
}}>
</View>
<TouchableHighlight onPress={()=> console.log('image tapped')}>
{/* <Image source={{width: 200,
height: 300,
uri: "https://picsum.photos/200/300"}}/> */}
</TouchableHighlight>
<Button title='click me!' onPress={()=> Alert.alert("My title", "My message", [
{text: "yes"},
{text: "No"}
])}></Button>
<StatusBar style="auto" />
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0,
// alignItems: 'center',
// justifyContent: 'center',
},
});
<file_sep>import 'react-native-gesture-handler';
//import { StatusBar } from "expo-status-bar";
import React from "react";
import {NavigationContainer} from '@react-navigation/native'
import {createStackNavigator} from '@react-navigation/stack'
import WelcomeScreen from './app/screens/WelcomeScreen'
import Browse from './app/screens/Browse'
//SafeAreaView add padding on the top to ensure text is within safe area
const Stack = createStackNavigator();
export default function App() {
return(
<NavigationContainer>
<Stack.Navigator initialRouteName='Browse'>
<Stack.Screen
name="Welcome"
component={WelcomeScreen}
options = {{title:'Welcome'}}/>
<Stack.Screen
name="Browse"
component={Browse}
options = {{title:'Browse'}}/>
</Stack.Navigator>
</NavigationContainer>
);
}
| 23b86978261fe4413f8d9826c3afbf590631ec66 | [
"JavaScript"
] | 4 | JavaScript | olivia-gambitsis/RecipieShare | 05287e63c3bcc698e99a12373612bc32e1512184 | aa921ad6d0cfa280a83c2246501afedc86819892 |
refs/heads/master | <repo_name>kishorekethineni/Telengana-tourism<file_sep>/app/src/main/java/com/androiduptodate/telanganatourism/home6.java
package com.androiduptodate.telanganatourism;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import java.util.Random;
public class home6 extends AppCompatActivity {
LinearLayout linearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home6);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
linearLayout=findViewById(R.id.home6);
linearLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
String[] color1={
"#89216B",
"#3c1053",
"#4b134f",
"#642B73",
"#45a247",
"#8e44ad"
};
String[] color2={
"#DA4453",
"#ad5389",
"#C6426E",
"#159957",
"#1CB5E0",
"#1CB5E0"
};
Random random=new Random();
GradientDrawable gradientDrawable=new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT,
new int[]{Color.parseColor(color1[random.nextInt(6)]),Color.parseColor(color2[random.nextInt(6)])});
linearLayout.setBackgroundDrawable(gradientDrawable);
return false;
}
});
}
}
| 5d72f5a4df8e8bbb0b161679d1b02fe0399cc9b1 | [
"Java"
] | 1 | Java | kishorekethineni/Telengana-tourism | 50539d3bb8c2f9048e57e44a91df62de33435209 | 82ea38b8ef048027516cc14dc246922f928ab1ca |
refs/heads/master | <file_sep>def addition(num1, num2)
num1+num2
end
def subtraction(num1, num2)
num1-num2
end
def division(num1, num2)
num1/num2
end
def multiplication(num1, num2)
num1*num2
end
def modulo(num1, num2)
count = 0
while count < (num1-num2) do
count += num2
end
num1-count
end
def square_root(num)
Math.sqrt(num)
end
| b7775c7199527e59365c32b506a06a2369e81884 | [
"Ruby"
] | 1 | Ruby | DanikaButterfield/programming-univbasics-3-build-a-calculator-lab-denver-web-82619 | ac38253ffcce1b516997cb1f27ebc66b01684dea | 1fd8777da2152d57f5887174d2f5496e895f0067 |
refs/heads/master | <file_sep>'use strict';
var number1 = prompt('Give me a random number.');
var number2 = prompt('Give me another random number.');
if (number1 > number2) {
alert(number1 +' is larger than '+ number2);
}
else {
alert(number2 +' is larger than '+ number1);
}
<file_sep>// 5. Exercise: Arrays
// Write a for loop that iterates the items in the array and constructs the concatenated string
// Sample array : myColor = ['Red', 'Green', 'White', 'Black'];
// Expected Output :
// 'Red,Green,White,Black' (using a for loop)
// 'Red,Green,White,Black' (using a the native method of the array object)
// 'Red+Green+White+Black' (using a the native method of the array object)
'use strict';
var myTarotCards = ['Five of Pentacles', 'Seven of Swords', 'Nine of Pentacles', 'Seven of Pentacles'];
//start the counter at 0
//run the loop for the length of the array
//everytime the loop runs, increment it by 1
for (var i = 0; i < myTarotCards.length; i++) {
var card = myTarotCards[i];
console.log(card);
}
console.log(myTarotCards.join());
console.log(myTarotCards.join(' + '));
console.log(myTarotCards.toString());
<file_sep>'use strict';
var number1 = prompt('Give me a random number.');
var number2 = prompt('Give me another random number.');
var number3 = prompt('Give me another random number.');
var numbers = [number1, number2, number3];
numbers.sort();
alert(numbers);
if (number2 > number1 && number2 > number3) {
alert(number2 +' is larger than '+ number1 + ' and ' + number3);
if (number1 > number3) {
alert(number1 + ' is greater than ' + number3);
}
else {
alert(number3 + ' is greater than ' + number1);
}
}
if (number1 > number2 && number1 > number3) {
alert(number1 +' is larger than '+ number2 + ' and ' + number3);
if (number2 > number3) {
alert(number2 + ' is greater than ' + number3);
}
else {
alert(number3 + ' is greater than ' + number2);
}
}
if (number3 > number2 && number3 > number1) {
alert(number3 +' is larger than '+ number2 + ' and ' + number1);
if (number1 > number2) {
alert(number1 + ' is greater than ' + number2);
}
else {
alert(number2 + ' is greater than ' + number1);
}
}
<file_sep>Bootstrap:
- Nav
- Breadcrumbs
- Font Awesome
- icons should all be svgs
- Components
- Cards
- Tables
- Forms | 5fbf060fb496d181edf976d8930ad8026d9cafcc | [
"JavaScript",
"Text"
] | 4 | JavaScript | maaviles/Nucamp | 90d55dd4874efb286dc03fa393db7280dced6370 | 6d459e1f06b8ddb154fbac4ba86ea959e88f3af3 |
refs/heads/master | <file_sep><?php echo form_open('users/login'); ?>
<div class="card">
<h3 class="text-center"><?php echo $title; ?></h3>
<div class="form-group">
<label>User Name</label>
<input type="text" name="username" class="form-control" placeholder="username" required autofocus>
</div>
<div class="form-group">
<label>Password</label>
<input type="<PASSWORD>" name="password" class="form-control" placeholder="<PASSWORD>" required autofocus>
</div>
<button class="btn btn-success" type="submit">Login</button>
</div>
<?php echo form_close(); ?><file_sep>
<?php echo validation_errors(); ?>
<?php echo form_open('users/register'); ?>
<div class="card">
<h2 class="text-center"><?= $title;?></h2>
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" placeholder="full name">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<label>User Name</label>
<input type="text" name="username" class="form-control" placeholder="User name ">
</div>
<div class="form-group">
<label>Password</label>
<input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" class="form-control">
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="<PASSWORD>" class="form-control" name="<PASSWORD>2" placeholder="<PASSWORD>">
</div>
<div class="form-group">
<label>Zipcode</label>
<input type="text" name="zipcode" class="form-control" placeholder="zipcode(optional)">
</div>
<button type="submit" class="btn btn-primary">Signup</button>
</div>
<?php echo form_close(); ?><file_sep># CI_blog
please edit database setup according to your system
Note:--
please set id only to primary and autoincrement but not the user_id, post_id or category_id.
READ ALL info carefully.
for ci_blog data base
user table
CREATE TABLE users
(
id int,
name varchar(255),
username varchar(255),
email varchar(255),
password varchar(255)
);
*****************************
for category table
CREATE TABLE categories
(
id int,
user_id int,
name varchar(255)
);
******************************
for comments table
CREATE TABLE comments
(
id int,
post_id int,
name varchar(255),
email varchar(255),
body varchar(255)
);
***********************************
for posts Table
CREATE TABLE posts
(
id int,
category_id int,
user_id int,
title varchar(255),
slug varchar(255),
body varchar(255),
post_image varchar(255)
);
| 62dacb42ccc09583c05fbe7fad6062ba7413d11f | [
"Markdown",
"PHP"
] | 3 | PHP | singh2018developer/CI_blog | 6864c1f13c30b461c6348cf3937e98a8f9319cc6 | ea323d96beae265c51f73a0fb6d4be0bd811e279 |
refs/heads/master | <file_sep>from django.conf.urls import url
from rest_framework.routers import DefaultRouter
from . import apiviews
router = DefaultRouter()
router.register('polls', apiviews.PollViewSet, base_name='polls')
urlpatterns = [
url(r'^polls/(?P<poll_pk>\d+)/choices/$',
apiviews.ChoiceList.as_view(), name='choice_list'),
url(r'^polls/(?P<poll_pk>\d+)/choices/(?P<choice_pk>\d+)/vote/$',
apiviews.CreateVote.as_view(), name='create_vote'),
url(r'^users/$', apiviews.CreateUser.as_view(), name='create_user'),
url(r'^login/$', apiviews.LoginView.as_view(), name='login'),
]
urlpatterns += router.urls
<file_sep>from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.authtoken.models import Token
from .models import Poll, Choice, Vote
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ('username', 'email', 'password')
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = self.Meta.model(username=validated_data['username'], email=validated_data['email'])
user.set_password(validated_data['password'])
user.save()
Token.objects.create(user=user)
return user
class VoteSerializer(serializers.ModelSerializer):
class Meta:
model = Vote
fields = "__all__"
extra_kwargs = {
'voted_by': {'required': False},
'poll': {'required': False},
'choice': {'required': False}
}
def validate(self, data):
if data['choice'].poll != data['poll']:
raise serializers.ValidationError("Choice can only be voted to its owner poll.")
return data
class ChoiceSerializer(serializers.ModelSerializer):
votes = VoteSerializer(many=True, required=False, read_only=True)
class Meta:
model = Choice
fields = "__all__"
extra_kwargs = {
'poll': {'required': False}
}
class PollSerializer(serializers.ModelSerializer):
choices = ChoiceSerializer(many=True, required=False, read_only=True)
created_by = serializers.CharField(source='created_by.username', required=False, read_only=True)
class Meta:
model = Poll
fields = "__all__"
depth = 1
<file_sep>from django.contrib.auth import authenticate
from rest_framework import generics
from rest_framework import permissions
from rest_framework import viewsets
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.authtoken.models import Token
from .models import Poll, Choice
from .permissions import IsOwnerOrReadOnly
from .serializers import (UserSerializer,
PollSerializer,
ChoiceSerializer,
VoteSerializer)
# Create your views here.
class PollViewSet(viewsets.ModelViewSet):
queryset = Poll.objects.all()
serializer_class = PollSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
def perform_create(self, serializer):
serializer.save(created_by=self.request.user)
class ChoiceList(generics.ListCreateAPIView):
serializer_class = ChoiceSerializer
permission_classes = (permissions.IsAuthenticated,)
def get_queryset(self):
return Choice.objects.filter(poll=self.kwargs['poll_pk'])
def create(self, request, *args, **kwargs):
data = request.data.copy()
data['poll'] = kwargs['poll_pk']
serializer = self.get_serializer(data=data)
serializer.is_valid(raise_exception=True)
if request.user != serializer.validated_data['poll'].created_by:
raise permissions.PermissionDenied(
"Only the owner of the poll can create choice."
)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
class CreateVote(generics.CreateAPIView):
serializer_class = VoteSerializer
permission_classes = (permissions.IsAuthenticated, )
def create(self, request, poll_pk, choice_pk):
data = request.data.copy()
data.update({
'poll': int(poll_pk),
'choice': int(choice_pk),
'voted_by': request.user.pk
})
serializer = self.get_serializer(data=data)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
class CreateUser(generics.CreateAPIView):
serializer_class = UserSerializer
authentication_classes = ()
permission_classes = ()
class LoginView(APIView):
permission_classes = ()
def post(self, request):
username = request.data.get('username')
password = request.data.get('<PASSWORD>')
user = authenticate(username=username, password=<PASSWORD>)
if user:
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key})
else:
return Response({'error': 'wrong credentials'},
status=status.HTTP_400_BAD_REQUEST)
<file_sep>from rest_framework.permissions import BasePermission, SAFE_METHODS
from .models import Choice
class IsOwnerOrReadOnly(BasePermission):
"""
custom permission to only allow the owner of a object to edit it.
"""
def has_object_permission(self, request, view, obj):
if request.method in SAFE_METHODS:
return True
else:
return request.user == obj.created_by
# class IsOwnerOfPoll(BasePermission):
# def has_permission(self, request, view):
# # has_object_permission() method can't check POST
#
# def has_object_permission(self, request, view, obj):
# return request.user == obj.poll.created_by
# class IsPollOwnChoice(BasePermission):
# message = 'Choice can only be voted to its owner poll'
#
# def has_permission(self, request, view):
# if request.method in SAFE_METHODS:
# return True
# choice = Choice.objects.get(pk=int(request.resolver_match.kwargs['choice_pk']))
# return choice.poll.pk == int(request.resolver_match.kwargs['poll_pk'])
<file_sep>from django.contrib.auth import get_user_model
from rest_framework.test import APITestCase
from . import apiviews
# Create your tests here.
class TestUser(APITestCase):
def setUp(self):
self.username = 'test'
self.email = '<EMAIL>'
self.password = '<PASSWORD>'
self.uri = "/users/"
def test_create_user(self):
response = self.client.post(self.uri, {
"username": self.username,
"email": self.email,
"password": self.password
})
msg = "Expected Response Code 201, but received {}".format(response.status_code)
self.assertEqual(response.status_code, 201, msg)
def test_create_user_without_username(self):
response = self.client.post(self.uri, {
"email": self.email,
"password": <PASSWORD>
})
msg = "Expected Response Code 400, but received {}".format(response.status_code)
self.assertEqual(response.status_code, 400, msg)
def test_create_user_without_password(self):
response = self.client.post(self.uri, {
"username": self.username,
"email": self.email
})
msg = "Expected Response Code 400, but received {}".format(response.status_code)
self.assertEqual(response.status_code, 400, msg)
def _create_user(self):
UserModel = get_user_model()
UserModel.objects.create_user(username=self.username,
email=self.email,
password=self.password)
class TestLogin(APITestCase):
def setUp(self):
self.uri = "/login/"
self.username = "test"
self.email = "<EMAIL>"
self.password = "<PASSWORD>"
def test_login(self):
_create_user(self)
response = self.client.post(self.uri, {
"username": self.username,
"password": self.password
})
msg = "Expected Response Code 200, but received {}".format(response.status_code)
self.assertEqual(response.status_code, 200, msg)
def test_login_nonexists(self):
response = self.client.post(self.uri, {
"username": self.username,
"password": self.password
})
msg = "Expected Response Code 400, but received {}".format(response.status_code)
self.assertEqual(response.status_code, 400, msg)
class TestPoll(APITestCase):
def setUp(self):
self.username = "test"
self.email = "<EMAIL>"
self.password = "<PASSWORD>"
self.uri = "/polls/"
self.user = _create_user(self)
def test_get_poll_list(self):
response = self.client.get(self.uri)
msg = "Expected Response Code 200, but received {}".format(response.status_code)
self.assertEqual(response.status_code, 200, msg)
def test_post_poll_unauthentication(self):
response = self.client.post(self.uri, {
"question": "How are you?"
})
msg = "Expected Response Code 401, but received {}".format(response.status_code)
self.assertEqual(response.status_code, 401, msg)
def test_post_poll(self):
self.client.login(username=self.username, password=self.password)
response = self.client.post(self.uri, {
"question": "How are you?"
})
msg = "Expected Response Code 201, but received {}".format(response.status_code)
self.assertEqual(response.status_code, 201, msg)
def test_get_poll_detail_nonexists(self):
response = self.client.get(self.uri + '1/')
msg = "Expected Response Code 404, but received {}".format(response.status_code)
self.assertEqual(response.status_code, 404, msg)
def test_get_poll_detail(self):
self.test_post_poll()
response = self.client.get(self.uri + '1/')
msg = "Expected Response Code 200, but received {}".format(response.status_code)
self.assertEqual(response.status_code, 200, msg)
| fb75bf57001804ac3a16a1d67861c63340435fba | [
"Python"
] | 5 | Python | luoxzhg/pollsapi | b5cbcebec7a19b34abfc7d0d6f2ade5ebe194111 | 201ebd695f240be2e3beb6fea0dd5a69d68998cc |
refs/heads/master | <repo_name>MohanadMedhat/Tic-Tac-Toe<file_sep>/usermodule.py
#board
#start game
#display board
#turn
#check win, lose or tie
#flip player
#---board
theboard = ['-', '-', '-',
'-', '-', '-',
'-', '-', '-']
played = []
position = ''
#---X starts
Current_player = 'X'
#---checks if game is still going
def game_going():
#if board[0] == board[1] == board[2]:
return True
#display_board(theboard)
#---played Turns
#---Displays Board
def display_board(board):
print(board[0], '|', board[1], '|', board[2])
print(board[3], '|', board[4], '|', board[5])
print(board[6], '|', board[7], '|', board[8])
#---Turn Handler
def Turns():
global position
global played
global Current_player
#print("it's " + Current_player + "'s turn")
position = int(input("pick a position from 1 to 9:")) - 1
#theboard[position] = Current_player
#display_board(theboard)
#played.append(int(position))
if position not in played:
theboard[position] = Current_player
display_board(theboard)
played.append(int(position))
else:
print('position not valid, try again !')
if Current_player == 'X':
Current_player = 'O'
else:
Current_player = 'X'
#print(played)
#Check win or tie
def check_condition():
#check rows
if theboard[0] == theboard[1] == theboard[2] != '-' or theboard[3] == theboard[4] == theboard[5] != '-' or theboard[6] == theboard[7] == theboard[8] != '-':
print(theboard[0] + ' Has Won!!!')
return True
#check columns
if theboard[0] == theboard[3] == theboard[6] != '-' or theboard[1] == theboard[4] == theboard[7] != '-' or theboard[2] == theboard[5] == theboard[8] != '-':
print(theboard[0] + ' Has Won!!!')
return True
def start_game():
while game_going:
Turns()
if check_condition() == True:
break
display_board(theboard)
start_game()
| 495f43c2ec19f15d848b0d72626cf3ac948050d1 | [
"Python"
] | 1 | Python | MohanadMedhat/Tic-Tac-Toe | 092fcdc4760878152948ea8b6460b1271e6897f0 | 9c93060718f3d50a5cc910d4c4588762d7473319 |
refs/heads/master | <repo_name>mra72/BB-NodeJS-ComboSelect<file_sep>/js/collections/citiesCollection.js
define([
'underscore',
'backbone',
// Pull in the Model module from above
'models/citiesModel'
], function(_, Backbone, CitiesModel){
var CitiesCollection = Backbone.Collection.extend({
model: CitiesModel,
initialize : function(models, options) {
},
url: 'http://localhost:3000/capitalxcommunity',//Llamamos al servicio que nos devolvera la coleccion de CIUDADES para rellenar el combo.
});
// You don't usually return a collection instantiated
return CitiesCollection;
});<file_sep>/js/router.js
define([
'jquery',
'underscore',
'backbone',
'views/communitiesListView',
'views/linkUnoView',
'views/toledoHistoryView',
'views/albaceteHistoryView',
'views/cuencaHistoryView',
'views/ciudadRealHistoryView',
'views/guadalajaraHistoryView'
// 'views/editUserView'
], function($, _, Backbone,CommunitiesListView,LinkUnoView,ToledoHistoryView,AlbaceteHistoryView,CuencaHistoryView,
CiudadRealHistoryView, GuadalajaraHistoryView){
var AppRouter = Backbone.Router.extend({
routes: {
// Default
'': 'home',
//'new':'editUser'//La entrada de definicion del route, es decir, 'new' debe corresponderse con el del <a herf='#/new'> definido en el HTML.
//Y la salida (..:'editUser') con la que usaremos en la declaracion app_router.on('route:editUser', function(){..)
'link1':'link1_f',
'toledoHistory' : 'toledoHistory_link',
'albaceteHistory' : 'albaceteHistory_link',
'cuencaHistory' : 'cuencaHistory_link',
'ciudadRealHistory' : 'ciudadRealHistory_link',
'guadalajaraHistory' : 'guadalajaraHistory_link'
},
home:function()
{
console.log('We have loaded the home page');
//Ahora invocamos desde el enroutador a la vista que queremos pintar, en este caso 'UserList', creamos una instancia del objeto:
var communitiesListView = new CommunitiesListView();
communitiesListView.render();
},
link1_f:function()
{
console.log('We have loaded the home page');
var linkUnoView = new LinkUnoView();
linkUnoView.render();
},
toledoHistory_link:function()
{
console.log('link para ir a historia de Toledo');
var toledoHistoryView = new ToledoHistoryView();
toledoHistoryView.render();
},
albaceteHistory_link:function()
{
console.log('link para ir a historia de Albacete');
var albaceteHistoryView = new AlbaceteHistoryView();
albaceteHistoryView.render();
},
cuencaHistory_link:function()
{
console.log('link para ir a historia de cuenca');
var cuencaHistoryView = new CuencaHistoryView();
cuencaHistoryView.render();
},
ciudadRealHistory_link:function()
{
console.log('link para ir a historia de ciudadReal');
var ciudadRealHistoryView = new CiudadRealHistoryView();
ciudadRealHistoryView.render();
},
guadalajaraHistory_link:function()
{
console.log('link para ir a historia de guadalajara');
var guadalajaraHistoryView = new GuadalajaraHistoryView();
guadalajaraHistoryView.render();
}
});
var initialize = function(){
var app_router = new AppRouter;
window.App.router=app_router;
Backbone.history.start();
};
return {
initialize: initialize
};
});<file_sep>/js/views/communitiesListView.js
define([
'jquery',
'underscore',
'backbone',
'collections/communitiesCollection',
// Using the Require.js text! plugin, we are loaded raw text
// which will be used as our views primary template
'text!templates/communitiesListTemplate.html',
'i18n!internalization/nls/i18n',
], function($, _, Backbone,CommunitiesCollection, CommunitiesListTemplate){//function($, _, Backbone, UsersCollection,CitiesListTemplate,Form)--function($, _, Backbone, ContenidoTemplate)
var CommunitiesListView = Backbone.View.extend({
el: 'body', //<div class='page'></div> definido dentro del <div class='container'> en el index.html
initialize: function()
{
},
render: function(eventName,options) {
console.log('render citiesListView');
var that = this;
var communitiesCollection = new CommunitiesCollection();
/*
FETCH:
Este método se encarga de traer el conjunto de MODELOS del SERVIDOR y cargarlos en la COLECCIÓN, reseteándola. El server debe de
encargarse de devolver la colección de los modelos en formato JSON, si estás trabajando sobre una API del servidor antigüa y no
puedes generar dicha respuesta, te interesará sobreescribir el método 'parse'.
*/
communitiesCollection.fetch({
success: function(collection, response){// En el response recibiremos el JSON de palo, que hemos preparado
//para poder practicar. En practicas siguientes ya nos adentraremos en
//el tema de conectar BBDD, con backbone y node.
console.log('CORRECTO ya tengo los SERVICIOS response!!!!!---->'+response.autonomias);
//var compiledTemplate = _.template(CitiesListTemplate,{citiesCollection:citiesCollection.models});
//that.$el.html('¡CONTENT SHOULD SHOW HERE!');
var compiledTemplate = _.template(CommunitiesListTemplate);
that.$el.html(compiledTemplate);
var objJson = response;
//Llenamos el combo despues de recibir el Json con la informacion necesaria para ello.
$("#comboCommunities").append('<option value=""></option>');
$.each(objJson.autonomias, function(i,obj){
$("#comboCommunities").append('<option value="' + obj.text + '">' + obj.text+ '</option>');
});
//Control del CHANGE en el Select(combo)
$("#comboCommunities").change(function(){
var value_Autonomia = $(this).val();
switch(value_Autonomia)
{
case 'Castilla-La Mancha':
console.log('PERFECTO!!!!!');
window.App.router.navigate("link1", {trigger: true});
break;
case 'Aragón':
alert('Seleccionaste comunidad de ARAGÓN!!!!!');
break;
default:
}
})
}
});
},//Cierre 'render'
events:{
'#comboCities':'clickSelectCities' // Esto se traduce que al hacer click en combo
//se lleva a cabo las acciones descritas en el método 'clickSelectCities'.
},
clickSelectCities:function(ev){
console.log('click');
//var userDetails = $(ev.currentTarget).serializeObject();
// var userModel = new UserModel();
//userModel.save(userDetails,{
// success: function(userModel){
// alert(userModel);
//}
// });
return false;
}
});
// Our module now returns our view
return CommunitiesListView;
});
| 00866bf8c43f2ac00feb1d8edbee09c07cbb4b70 | [
"JavaScript"
] | 3 | JavaScript | mra72/BB-NodeJS-ComboSelect | 14d89add636baffe60cbd8c67e525513a55b4895 | 434c4a1f0aea1f8a889db4e4f743d0bddc867433 |
refs/heads/master | <repo_name>Jonathanhovland/reads-back-end<file_sep>/back-end/migrations/20181204144739_book.js
exports.up = function(knex, Promise) {
return knex.schema.createTable('book', function (table){
table.increments()
table.string('bookTitle')
table.string('bookGenre')
table.text('bookDescription')
table.string('bookCoverURL')
})
}
exports.down = function(knex, Promise) {
return knex.schema.dropTableIfExists('book')
}
<file_sep>/back-end/index.js
const express = require ("express")
const app = express()
const bodyParser = require("body-parser")
const cors = require("cors")
const port = process.env.PORT || 3005
const bookRoutes = require("./routes/book")
const authorRoutes = require("./routes/author")
const bookAuthorRoutes = require("./routes/author")
app.get("/", (req, res) => res.json({
"book": "https://sheltered-caverns-11078.herokuapp.com/book",
"author": "https://sheltered-caverns-11078.herokuapp.com/author"
}))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(cors())
app.use("/book", bookRoutes)
app.use("/author", authorRoutes)
app.use("/book-author", bookAuthorRoutes)
app.use(notFound)
app.use(errorHandler)
function notFound(req, res, next) {
res.status(404).send({ error: 'Not found!', status: 404, url: req.originalUrl })
}
function errorHandler(err, req, res, next) {
console.error('ERROR', err)
const stack = process.env.NODE_ENV !== 'production' ? err.stack : undefined
res.status(500).send({ error: err.message, stack, url: req.originalUrl })
}
app.listen(port, () => console.log("server is running on port 3005"))<file_sep>/README.md
# Books-Back-End
link: https://sheltered-caverns-11078.herokuapp.com/
| 3ba85a0d0799afe21d845a4b0b5cddb6b8047b35 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | Jonathanhovland/reads-back-end | e0f6c138c9b8551ab11a59e36ca5455a64b88018 | 054e691cd832d2aaef094ced08367b5986c783bf |
refs/heads/master | <file_sep>function updateReleased() {
resetReleased();
var teamVal = document.getElementById("releasedSelect").value;
var monthVal = document.getElementById("monthReleased").value;
var prevMonth = $('#monthReleased').find(":selected").prev().val();
$.ajax({
url: '/Home/GetReleasedStories',
type: 'GET',
data: { month: monthVal, team: teamVal },
dataType: 'json',
cache: false,
error: function () {
alert('Error occured');
},
success: function (data) {
addRelStories(data);
addPrevMonthStories(prevMonth, teamVal, data);
}
});
$.ajax({
url: '/Home/GetReleasedHotFixes',
type: 'GET',
data: { month: monthVal, team: teamVal },
dataType: 'json',
cache: false,
error: function () {
alert('Error occured');
},
success: function (data) {
addRelHotFixes(data);
addPrevMonthHotFixes(prevMonth, teamVal, data);
}
});
}
function addPrevMonthStories(prevMonth, teamVal, currData) {
if (prevMonth.length > 0) {
$.ajax({
url: '/Home/GetReleasedStories',
type: 'GET',
data: { month: prevMonth, team: teamVal },
dataType: 'json',
cache: false,
error: function () {
alert('Error occured');
},
success: function (prevData) {
var percent = Math.round((currData - prevData) / prevData * 10000) / 100;
displayPrevMonthStories(prevData, percent);
}
});
} else {
document.getElementById("prevReleasedStories").innerHTML = "<h4 style=\"color:gray,font-style:italic\">No data found for previous month.<h4>";
enableReleased();
}
}
function addPrevMonthHotFixes(prevMonth, teamVal, currData) {
if (prevMonth.length > 0) {
$.ajax({
url: '/Home/GetReleasedHotFixes',
type: 'GET',
data: { month: prevMonth, team: teamVal },
dataType: 'json',
cache: false,
error: function () {
alert('Error occured');
},
success: function (prevData) {
var percent = Math.round((currData - prevData) / prevData * 10000) / 100;
displayPrevMonthHotFixes(prevData, percent);
}
});
} else {
document.getElementById("prevReleasedHotfixes").innerHTML = "<h4 style=\"color:gray,font-style:italic\">No data found for previous month.<h4>";
}
}
function displayPrevMonthStories(data, percent) {
var color;
if (percent > 0) {
color = "green";
} else {
color = "red";
}
document.getElementById("prevReleasedStories").innerHTML = "<h4 style=\"font-style:italic;\">Stories Last Month: " + data + " (" + percent + "%)<h4>";
document.getElementsByClassName("releasedContainer")[0].style.backgroundColor = "dark" + color;
document.getElementsByClassName("releasedContainer")[0].style.color = "white";
enableReleased();
}
function displayPrevMonthHotFixes(data, percent) {
var color;
if (percent > 0) {
color = "green";
} else {
color = "red";
}
document.getElementById("prevReleasedHotFixes").innerHTML = "<h4 style=\"font-style:italic\">Hot Fixes Last Month: " + data + " (" + percent + "%)<h4>";
document.getElementsByClassName("releasedContainer")[1].style.backgroundColor = "dark" + color;
document.getElementsByClassName("releasedContainer")[1].style.color = "white";
document.getElementById("loaderHotFixes").hidden = true;
}
<file_sep>function updateBacklog() {
resetBacklog();
var teamVal = document.getElementById("backLogSelect").value;
if (teamVal == "All") {
$.ajax({
url: '/Home/GetAllUnsized',
type: 'GET',
dataType: 'json',
cache: false,
error: function () {
alert('Error occured');
},
success: function (data) {
addUnsized(data);
}
});
$.ajax({
url: '/Home/GetAllSized',
type: 'GET',
dataType: 'json',
cache: false,
error: function () {
alert('Error occured');
},
success: function (data) {
addSized(data, teamVal);
document.getElementById("loading").hidden = true;
document.getElementById("loaderBacklog").hidden = true;
document.getElementById("backLogSelect").disabled = false;
document.getElementById("backLogBtn").disabled = false;
}
});
} else {
$.ajax({
url: '/Home/GetUnsized',
type: 'GET',
data: { team: teamVal },
dataType: 'json',
cache: false,
error: function () {
alert('Error occured');
},
success: function (data) {
addUnsized(data);
document.getElementById("loading").hidden = true;
document.getElementById("loaderBacklog").hidden = true;
document.getElementById("backLogSelect").disabled = false;
}
});
$.ajax({
url: '/Home/GetSized',
type: 'GET',
data: { team: teamVal },
dataType: 'json',
cache: false,
error: function () {
alert('Error occured');
},
success: function (data) {
addSized(data, teamVal);
}
});
}
}
function resetBacklog() {
document.getElementById("unsizedStoriesDisp").innerText = "";
document.getElementById("storyPointsInBacklog").innerHTML = "";
document.getElementById("backLogSelect").disabled = true;
document.getElementById("backLogBtn").disabled = true;
document.getElementById("loading").hidden = false;
document.getElementById("loaderBacklog").hidden = false;
}<file_sep>var populated = false;
var populatedRelQ = false;
var populatedMonths = false;
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var sprintsInMonth = { "January": 3, "February": 2, "March": 2, "April": 2, "May": 2, "June": 2, "July": 2, "August": 2, "September": 3, "October": 2, "November": 2, "December": 2 };
var monthSprints = {};
var endSprint;
var onMessageAveragePoints;
var onCampusAveragePoints;
var onBoardAveragePoints;
var onRecordAveragePoints;
var check = function () {
if (populated) {
endSprint = $("#sprintVelocity option:last").val();
$('#monthVelocity').val($("#monthVelocity option:last").val());
$('#monthReleased').val($("#monthReleased option:last").val());
displayFirstData();
updateReleased();
} else {
setTimeout(check, 100);
}
}
function updateOpacity() {
var opacity = document.getElementById("movingAverageOpacity").value;
d3.selectAll(".avg")
.transition().duration(100)
.style("opacity", opacity);
}
function updatePathOpacity() {
var opacity = document.getElementById("pathOpacity").value;
d3.selectAll(".line")
.transition().duration(100)
.style("opacity", opacity);
d3.selectAll(".dataPoint")
.transition().duration(100)
.style("opacity", opacity);
}
function updateTranslation() {
endSprint = $('option:selected', document.getElementById("monthVelocity")).attr('sprintnum');
var mo = document.getElementById("monthVelocity").value.match("[^0-9]+")[0];
if (sprintsInMonth[mo] == 2) {
document.getElementById("monthToSprintTranslation").innerHTML = "Sprints: " + (+endSprint - 1) + ", " + endSprint;
} else {
document.getElementById("monthToSprintTranslation").innerHTML = "Sprints: " + (+endSprint - 2) + ", " + (+endSprint - 1) + ", " + endSprint;
}
}
function populateData() {
var startYear = 2015;
var add = 0;
var mo = "April"
var sprintsLeft = sprintsInMonth[mo] - 1;
d3.csv(pathToCsv, function (error, dataset) {
var m = d3.nest().key(function (d) { return d.sprint; }).entries(dataset);
for (var i = 0; i < m.length; i++) {
$('#sprintVelocity').append($('<option>', { value: +m[i].key })
.text("Sprint " + m[i].key));
if (sprintsLeft == 0) {
$('#monthVelocity').append($('<option>', { value: mo + (startYear + add) })
.text(mo + " " + (startYear + add))
.attr("sprintNum", m[i].key))
$('#monthReleased').append($('<option>', { value: mo + (startYear + add) })
.text(mo + " " + (startYear + add))
.attr("sprintNum", m[i].key))
$('#sprintReleaseQ').append($('<option>', { value: mo + (startYear + add) })
.text(mo + " " + (startYear + add))
.attr("sprintNum", m[i].key))
mo = months[(months.indexOf(mo) + 1) % 12];
sprintsLeft = sprintsInMonth[mo];
if (mo == "January") {
add += 1;
}
}
sprintsLeft--;
}
populated = true;
populatedRelQ = true;
});
check();
updateBacklog();
}
function displayFirstData() {
document.getElementById("addMultipleVel").checked = true;
var curr, max;
var temp = 0;
$('#sprintVelocity > option').each(function () {
curr = +$(this).val();
max = Math.max(temp, curr);
temp = curr;
})
document.getElementById("sprintVelocity").value = max;
var dropdown = document.getElementById("scrumTeamVelocity");
for (var i = 0; i < dropdown.options.length; i++) {
dropdown.value = dropdown.options[i].value;
displayVelocity();
}
document.getElementById("scrumTeamVelocity").value = "All";
}
function showTeamHistoryVel() {
clearAddedVel();
document.getElementById("addMultipleVel").checked = true;
var dropdown;
if (document.getElementById("viewByMonthRadio").checked) {
dropdown = document.getElementById("monthVelocity");
} else {
dropdown = document.getElementById("sprintVelocity");
}
var temp = dropdown.value;
for (var i = 0; i < dropdown.options.length; i++) {
dropdown.value = dropdown.options[i].value;
displayVelocity();
}
dropdown.value = temp;
}
function showTeamRecentHistoryVel() {
clearAddedVel();
document.getElementById("addMultipleVel").checked = true;
var dropdown;
if (document.getElementById("viewByMonthRadio").checked) {
dropdown = document.getElementById("monthVelocity");
} else {
dropdown = document.getElementById("sprintVelocity");
}
var temp = dropdown.value;
for (var i = dropdown.options.length - 13; i < dropdown.options.length; i++) {
dropdown.value = dropdown.options[i].value;
displayVelocity();
}
dropdown.value = temp;
}
function showTimePeriodVel() {
clearAddedVel();
document.getElementById("addMultipleVel").checked = true;
var dropdown = document.getElementById("scrumTeamVelocity");
var temp = dropdown.value;
for (var i = 0; i < dropdown.options.length; i++) {
dropdown.value = dropdown.options[i].value;
displayVelocity();
}
dropdown.value = temp;
}
function checkBoxClearAddedVel() {
if (document.getElementById("addMultipleVel").checked) {
return;
} else {
clearAddedVel();
}
}
function clearAddedVel() {
d3.selectAll("#velocitySvg").remove();
}
var tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.style("border-radius", "10px")
.style("padding", "7px")
.style("text-align", "center")
.style("background-color", "rgba(150,150,150,0.85)")
.style("border-right", "4px solid gray")
.style("border-bottom", "4px solid gray");
var check2 = function () {
if (populatedMonths) {
console.log("getting last months");
monthsInGraph = getLastMonths(endSprint - 12, endSprint);
displayGraph();
} else {
setTimeout(check2, 2000);
}
}
function displayVelocity() {
var teamVal = document.getElementById("scrumTeamVelocity").value;
var sprintVal = document.getElementById("sprintVelocity").value;
var monthVal = document.getElementById("monthVelocity").value;
var viewByMonth = document.getElementById("viewByMonthRadio").checked;
var addMultipleVal = document.getElementById("addMultipleVel").checked;
var w = 175;
var h = 175;
var percentCutoff = 0.9;
var bordercolor = "green";
var strokewidth = "3px";
var startYear = 2015;
var add = 0;
var mo = "April"
var sprintsLeft = sprintsInMonth[mo];
d3.csv(pathToCsv, function (error, dataset) {
dataset.forEach(function (d) {
committed: +d.committed;
completed: +d.completed;
d.percent = d.completed / d.committed * 100;
d.prevSprint = (dataset.filter(function (e) {
return (e.sprint == +d.sprint - 1 && e.team == teamVal);
}))[0];
d.nextSprint = (dataset.filter(function (e) {
return (e.sprint == +d.sprint + 1 && e.team == teamVal);
}))[0];
sprint: "Sprint " + d.sprint;
storiesadded: +d.storiesadded;
pointsadded: +d.pointsadded;
failedtoquantify: +d.failedtoquantify;
comments: d.sprintComments;
if (d.prevSprint == null) {
add = 0;
mo = "April";
sprintsLeft = sprintsInMonth[mo];
}
if (sprintsLeft == 1) {
d.month = mo + (startYear + add);
if (!(monthSprints[d.sprint])) {
monthSprints[d.sprint] = d.month;
}
}
if (sprintsLeft == 0) {
sprintsLeft = sprintsInMonth[mo];
mo = months[(months.indexOf(mo) + 1) % 12];
if (mo == "January") {
add += 1;
}
}
sprintsLeft--;
d.mo = mo;
});
populatedMonths = true;
if (!addMultipleVal) {
d3.select("#velocitySvg").remove();
}
var completedR = 100;
var committedR;
var circleSvg = d3.select("#velocityVis").append("svg")
.attr("id", "velocitySvg")
.attr("width", w)
.attr("height", h)
addShadows(circleSvg);
var borderPath = circleSvg.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("height", h)
.attr("width", w)
.style("stroke", bordercolor)
.style("fill", "none")
.style("stroke-width", strokewidth);
var circles = circleSvg
.selectAll("circle")
.data(dataset
.filter(function (d) {
if (viewByMonth) {
return (d.month == monthVal && d.team == teamVal);
} else {
return (d.sprint == sprintVal && d.team == teamVal);
}
})
)
.enter();
var c1 = circles.append("circle")
.attr("r", function (d) {
if (viewByMonth) {
if (sprintsInMonth[d.mo] == 3) {
if (d.committed + d.prevSprint.committed + d.prevSprint.prevSprint.committed > 50) {
committedR = 50;
} else {
committedR = d.committed + d.prevSprint.committed + d.prevSprint.prevSprint.committed;
}
} else {
if (d.committed + d.prevSprint.committed > 50) {
committedR = 50;
} else {
committedR = d.committed + d.prevSprint.committed;
}
}
} else {
if ((d.committed) > 50) {
committedR = 50;
} else {
committedR = d.committed;
}
}
return committedR;
})
.attr("cx", 30)
.attr("cy", 85)
.attr("fill", "darkgray")
.style("filter", "url(#drop-shadow)")
circles.append("circle")
.filter(function (d) {
if (viewByMonth) {
return (d.month == monthVal && d.team == teamVal);
} else {
return (d.sprint == sprintVal && d.team == teamVal);
}
})
.attr("r", function (d) {
if (viewByMonth) {
if (sprintsInMonth[d.mo] == 3) {
var num = +d.completed + +d.prevSprint.completed + +d.nextSprint.completed;
var denom = +d.committed + +d.prevSprint.committed + +d.nextSprint.committed;
completedR = ((num) / (denom)) * committedR;
} else {
completedR = ((+d.completed + +d.prevSprint.completed) * committedR / (+d.committed + +d.prevSprint.committed));
}
} else {
completedR = (d.completed * committedR / d.committed);
}
return completedR;
})
.attr("cx", 30)
.attr("cy", 85)
.style("filter", "url(#drop-shadow2)")
.attr("fill", function (d) {
if (viewByMonth) {
if (sprintsInMonth[d.mo] == 3) {
if (((+d.completed + +d.prevSprint.completed + +d.nextSprint.completed) / (+d.committed + +d.prevSprint.committed + +d.nextSprint.committed)) > percentCutoff) {
return "green";
} else {
return "red";
}
} else {
if (((+d.completed + +d.prevSprint.completed) / (+d.committed + +d.prevSprint.committed)) > percentCutoff) {
return "green";
} else {
return "red";
}
}
} else {
if (d.completed / d.committed > percentCutoff) {
return "green";
} else {
return "red";
}
}
});
circles.append("text")
.attr("x", 95)
.attr("y", 90)
.attr("cursor", "pointer")
.attr("font-family", "sans-serif")
.attr("fill", function (d) {
if (viewByMonth) {
if (sprintsInMonth[d.mo] == 3) {
if (((+d.completed + +d.prevSprint.completed + +d.nextSprint.completed) / (+d.committed + +d.prevSprint.committed + +d.nextSprint.committed)) > percentCutoff) {
return "#006400";
} else {
return "#8B0000";
}
} else {
if (((+d.completed + +d.prevSprint.completed) / (+d.committed + +d.prevSprint.committed)) > percentCutoff) {
return "#006400";
} else {
return "#8B0000";
}
}
} else {
if (d.completed / d.committed > percentCutoff) {
return "#006400";
} else {
return "#8B0000";
}
}
})
.attr("font-size", "30px")
.text(function (d) {
var retStr;
if (viewByMonth) {
if (sprintsInMonth[d.mo] == 3) {
var num = +d.completed + +d.prevSprint.completed + +d.nextSprint.completed;
var denom = +d.committed + +d.prevSprint.committed + +d.nextSprint.committed;
retStr = Math.round((num / denom) * 100) + "%";
} else {
retStr = Math.round(((+d.completed + +d.prevSprint.completed) / (+d.committed + +d.prevSprint.committed)) * 100) + "%";
}
} else {
retStr = Math.round(d.completed / d.committed * 100) + "%";
}
return retStr;
})
.on("mouseover", function (d) {
tooltip.transition()
.style("visibility", "visible");
tooltip.html(function () {
var scrumMasterComments = "";
if (d.sprintComments.length > 0) {
scrumMasterComments = "<strong> Comments On Sprint: " + d.sprintComments + "</strong>";
}
if (viewByMonth) {
if (sprintsInMonth[d.mo] == 3) {
var num = +d.completed + +d.prevSprint.completed + +d.nextSprint.completed;
var denom = +d.committed + +d.prevSprint.committed + +d.nextSprint.committed;
return "<strong>Committed: </strong>" + (denom) + "<br/> <strong>Completed: </strong>" + (num) + "<br/>" + Math.round(((num) / (denom)) * 10000) / 100 + "%";
} else {
var num = +d.completed + +d.prevSprint.completed;
var denom = +d.committed + +d.prevSprint.committed;
return "<strong>Committed: </strong>" + (denom) + "<br/> <strong>Completed: </strong>" + (num) + "<br/>" + Math.round(((num) / (denom)) * 10000) / 100 + "%";
}
} else {
return "<strong>Committed: </strong>" + d.committed + "<br/> <strong>Completed: </strong>" + d.completed + "<br/>" + Math.round(d.percent * 100) / 100 + "%";
}
})
})
.on("mousemove", function () { return tooltip.style("top", (event.pageY - 10) + "px").style("left", (event.pageX + 30) + "px"); })
.on("mouseout", function (d) {
tooltip.transition()
.duration(500)
.style("visibility", "hidden");
})
.on("click", function (d) {
var scrumMasterComments = "";
if (d.sprintComments.length > 0) {
scrumMasterComments = "<strong> Comments On Sprint: " + d.sprintComments + "</strong>";
}
var modal = document.getElementById('myModal')
document.getElementById('modal-text').innerHTML = "<strong style=\"color:red\">" + d.storiesadded + " Stories Added Mid-Sprint</strong><br/><strong style=\"color:darkred\">(" + d.pointsadded + " Point(s) and " + d.failedtoquantify + " Other Stories)</strong><br/><strong>" + scrumMasterComments;
modal.style.display = "block";
})
circles.append("text")
.attr("x", 160)
.attr("y", 160)
.style("text-anchor", "end")
.attr("font-family", "sans-serif")
.attr("fill", function (d) {
if (d.prevSprint != null) {
if (d.percent - d.prevSprint.percent >= 0) {
return "#006400";
} else {
return "#8B0000";
}
}
})
.attr("font-size", "15px")
.text(function (d) {
if (d.prevSprint != null) {
if (viewByMonth) {
if (sprintsInMonth[d.mo] == 3) {
if (d.prevSprint.prevSprint.prevSprint != null && d.prevSprint.prevSprint.prevSprint.prevSprint != null) {
var monthPercent = ((+d.completed + +d.prevSprint.completed + +d.prevSprint.prevSprint.completed) / (+d.committed + +d.prevSprint.committed + +d.prevSprint.prevSprint.committed));
var lastMonthPercent = ((+d.prevSprint.prevSprint.prevSprint.completed + +d.prevSprint.prevSprint.prevSprint.prevSprint.completed) / (+d.prevSprint.prevSprint.prevSprint.committed + +d.prevSprint.prevSprint.prevSprint.prevSprint.committed));
return Math.round((monthPercent - lastMonthPercent) * 100) + "%";
} else {
return "Prior month not found";
}
} else {
if (d.prevSprint.prevSprint != null && d.prevSprint.prevSprint.prevSprint != null) {
var monthPercent = ((+d.completed + +d.prevSprint.completed) / (+d.committed + +d.prevSprint.committed));
var lastMonthPercent = ((+d.prevSprint.prevSprint.completed + +d.prevSprint.prevSprint.prevSprint.completed) / (+d.prevSprint.prevSprint.committed + +d.prevSprint.prevSprint.prevSprint.committed));
return Math.round((monthPercent - lastMonthPercent) * 100) + "%";
} else {
return "Prior month not found";
}
}
} else {
return Math.round(d.percent - d.prevSprint.percent) + "% ";
}
}
else {
return "No data for prior sprint";
}
})
circles.append("text")
.attr("x", 5)
.attr("y", 20)
.attr("font-family", "sans-serif")
.attr("fill", "black")
.attr("font-size", "15px")
.text(function (d) {
if (viewByMonth) {
var retStr = teamVal + " || " + monthVal;
} else {
var retStr = teamVal + " || " + sprintVal;
}
return retStr;
})
})
}
function closeModal() {
var modal = document.getElementById('myModal');
modal.style.display = "none";
}
window.onclick = function (event) {
var modal = document.getElementById('myModal');
if (event.target == modal) {
modal.style.display = "none";
}
}
function getPercent(committed, completed) {
return Math.round(completed / committed * 100);
}
check2();
var tip = d3.tip()
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function (d) {
return "<strong>Frequency:</strong> <span style='color:red'>" + d.frequency + "</span>";
})
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Net;
using Newtonsoft.Json;
using System.Text.RegularExpressions;
using System.Web.Configuration;
namespace DashboardApp.Controllers
{
public class HomeController : Controller
{
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult Dashboard()
{
ViewBag.Message = "Your dashboard page.";
return View();
}
public string CsvPath
{ get
{
return WebConfigurationManager.AppSettings["pathToCsv"];
}
}
public class Field
{
public string customfield_10003 { get; set; }
}
public class Issue
{
public string id { get; set; }
public Field fields { get; set; }
public string self { get; set; }
public string view { get; set; }
}
public class ResponseSized
{
public string expand { get; set; }
public int startAt { get; set; }
public int maxResults { get; set; }
public int total { get; set; }
public List<Issue> issues { get; set; }
}
public class ResponseUnsized
{
public string expand { get; set; }
public int startAt { get; set; }
public int maxResults { get; set; }
public int total { get; set; }
}
public string getSizedURL(string project)
{
return "https://jira.whipplehill.com/rest/api/2/search?filter=14601&jql=project%20%3D%20" + project + "%20AND%20(sprint%20not%20in%20openSprints()%20AND%20sprint%20not%20in%20closedSprints()%20OR%20sprint%20is%20EMPTY)%20AND%20%22Story%20Points%22%20is%20not%20EMPTY%20AND%20status%20not%20in%20(Released%2C%20Closed)%20ORDER%20BY%20cf%5B10300%5D%20ASC&maxResults=1000";
}
public string getUnsizedURL(string project)
{
return "https://jira.whipplehill.com/rest/api/2/search?filter=14601&jql=project%20%3D%20" + project + "%20AND%20(sprint%20not%20in%20openSprints()%20AND%20sprint%20not%20in%20closedSprints()%20OR%20sprint%20is%20EMPTY)%20AND%20%22Story%20Points%22%20is%20EMPTY%20AND%20status%20not%20in%20(Released%2C%20Closed)%20ORDER%20BY%20cf%5B10300%5D%20ASC&maxResults=1000";
}
public string getStoriesURL(string month, string project)
{
string[] dateParts = Regex.Split(month, @"(?<=\p{L})(?=\p{N})");
DateTime date = Convert.ToDateTime("01-" + dateParts[0] + "-" + dateParts[1]);;
string startDate = date.Year + "%2F" + date.Month + "%2F" + "01";
string endDate = date.Year + "%2F" + date.Month + "%2F" + DateTime.DaysInMonth(date.Year, date.Month);
if (project == "All")
{
return "https://jira.whipplehill.com/rest/api/2/search?filter=14419&jql=issuetype%20%3D%20Story%20AND%20fixVersion%20is%20not%20EMPTY%20AND%20resolved%20%3E%20%22" + startDate + "%22%20AND%20resolved%20%3C%20%22" + endDate + "%22";
}
return "https://jira.whipplehill.com/rest/api/2/search?filter=14610&jql=project%20in%20(" + project + ")%20AND%20issuetype%20%3D%20Story%20AND%20fixVersion%20is%20not%20EMPTY%20AND%20resolved%20%3E%20%22" + startDate + "%22%20AND%20resolved%20%3C%20%22" + endDate + "%22";
}
public string getHotFixesURL(string month, string project)
{
string[] dateParts = Regex.Split(month, @"(?<=\p{L})(?=\p{N})");
DateTime date = Convert.ToDateTime("01-" + dateParts[0] + "-" + dateParts[1]); ;
string startDate = date.Year + "%2F" + date.Month + "%2F" + "01";
string endDate = date.Year + "%2F" + date.Month + "%2F" + DateTime.DaysInMonth(date.Year, date.Month);
if (project == "All")
{
return "https://jira.whipplehill.com/rest/api/2/search?filter=14419&jql=status%20%3D%20\"RELEASED\"%20AND%20issuetype%20%3D%20\"CR%20Bug\"%20AND%20fixVersion%20is%20not%20EMPTY%20AND%20resolved%20%3E%20%22" + startDate + "%22%20AND%20resolved%20%3C%20%22" + endDate + "%22%20";
}
return "https://jira.whipplehill.com/rest/api/2/search?filter=14610&jql=project%20in%20(" + project + ")%20AND%20status%20%3D%20%22RELEASED%22%20AND%20issuetype%20%3D%20%22CR%20Bug%22%20AND%20fixVersion%20is%20not%20EMPTY%20AND%20resolved%20%3E%20%22" + startDate + "%22%20AND%20resolved%20%3C%20%22" + endDate + "%22";
}
public string getReleaseQURL(string month, string project)
{
string[] dateParts = Regex.Split(month, @"(?<=\p{L})(?=\p{N})");
DateTime date = Convert.ToDateTime("01-" + dateParts[0] + "-" + dateParts[1]); ;
string startDate = date.Year + "%2F" + date.Month + "%2F" + "01";
string endDate = date.Year + "%2F" + date.Month + "%2F" + DateTime.DaysInMonth(date.Year, date.Month);
if (project == "All")
{
return "https://jira.whipplehill.com/rest/api/2/search?filter=14419&jql=status%20%3D%20\"RELEASED\"%20AND%20issuetype%20%3D%20\"CR%20Bug\"%20AND%20fixVersion%20is%20not%20EMPTY%20AND%20resolved%20%3E%20%22" + startDate + "%22%20AND%20resolved%20%3C%20%22" + endDate + "%22%20";
}
return "https://jira.whipplehill.com/rest/api/2/search?filter=14610&jql=project%20in%20(" + project + ")%20AND%20status%20%3D%20%22RELEASED%22%20AND%20issuetype%20%3D%20%22CR%20Bug%22%20AND%20fixVersion%20is%20not%20EMPTY%20AND%20resolved%20%3E%20%22" + startDate + "%22%20AND%20resolved%20%3C%20%22" + endDate + "%22";
}
[HttpGet]
public int GetReleasedStories(string team, string month)
{
using (var client = new HttpClient())
{
var byteArray = new System.Text.UTF8Encoding().GetBytes("AutomationService:Aut0mate0n!");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
HttpResponseMessage response = client.GetAsync(getStoriesURL(month, team)).Result;
if (response.IsSuccessStatusCode)
{
string r = response.Content.ReadAsStringAsync().Result;
ResponseUnsized result1 = JsonConvert.DeserializeObject<ResponseUnsized>(r);
return result1.total;
}
else
{
Debug.WriteLine("failed Query");
return -1;
}
}
}
[HttpGet]
public int GetReleasedHotFixes(string team, string month)
{
using (var client = new HttpClient())
{
var byteArray = new System.Text.UTF8Encoding().GetBytes("AutomationService:Aut0mate0n!");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
HttpResponseMessage response = client.GetAsync(getHotFixesURL(month, team)).Result;
if (response.IsSuccessStatusCode)
{
string r = response.Content.ReadAsStringAsync().Result;
ResponseUnsized result1 = JsonConvert.DeserializeObject<ResponseUnsized>(r);
return result1.total;
}
else
{
Debug.WriteLine("failed Query");
return -1;
}
}
}
[HttpGet]
public double GetAllSized(string team)
{
using (var client = new HttpClient())
{
var byteArray = new System.Text.UTF8Encoding().GetBytes("AutomationService:Aut0mate0n!");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
HttpResponseMessage response = client.GetAsync("https://jira.whipplehill.com/rest/api/2/search?filter=14601&jql=project%20in%20(onBoard%2C%20onCampus%2C%20onRecord%2C%20onMessage)%20AND%20(sprint%20not%20in%20openSprints()%20AND%20sprint%20not%20in%20closedSprints()%20OR%20sprint%20is%20EMPTY)%20AND%20%22Story%20Points%22%20is%20not%20EMPTY%20AND%20status%20not%20in%20(Released%2C%20Closed)%20ORDER%20BY%20summary%20ASC%2C%20cf%5B10300%5D%20ASC&maxResults=1000").Result;
if (response.IsSuccessStatusCode)
{
string r = response.Content.ReadAsStringAsync().Result;
ResponseSized result1 = JsonConvert.DeserializeObject<ResponseSized>(r);
List<Issue> l = result1.issues;
double total = l.Sum(item => int.Parse(item.fields.customfield_10003));
return total;
}
else
{
Debug.WriteLine("failed Query");
return 0.0;
}
}
}
[HttpGet]
public int GetAllUnsized(string team)
{
using (var client = new HttpClient())
{
var byteArray = new System.Text.UTF8Encoding().GetBytes("AutomationService:Aut0mate0n!");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
HttpResponseMessage response = client.GetAsync("https://jira.whipplehill.com/rest/api/2/search?filter=14610&jql=project%20in%20(onBoard%2C%20onCampus%2C%20onRecord%2C%20onMessage)%20AND%20(sprint%20not%20in%20openSprints()%20AND%20sprint%20not%20in%20closedSprints()%20OR%20sprint%20is%20EMPTY)%20AND%20%22Story%20Points%22%20is%20EMPTY%20AND%20status%20not%20in%20(Released%2C%20Closed)%20ORDER%20BY%20summary%20ASC%2C%20cf%5B10300%5D%20ASC").Result;
if (response.IsSuccessStatusCode)
{
string r = response.Content.ReadAsStringAsync().Result;
ResponseUnsized result1 = JsonConvert.DeserializeObject<ResponseUnsized>(r);
return result1.total;
}
else
{
Debug.WriteLine("failed Query");
return -1;
}
}
}
[HttpGet]
public double GetSized(string team)
{
using (var client = new HttpClient())
{
var byteArray = new System.Text.UTF8Encoding().GetBytes("AutomationService:Aut0mate0n!");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
HttpResponseMessage response = client.GetAsync(getSizedURL(team)).Result;
if (response.IsSuccessStatusCode)
{
string r = response.Content.ReadAsStringAsync().Result;
ResponseSized result1 = JsonConvert.DeserializeObject<ResponseSized>(r);
List < Issue > l = result1.issues;
double total = l.Sum(item => int.Parse(item.fields.customfield_10003));
return total;
}
else
{
Debug.WriteLine("failed Query");
return 0.0;
}
}
}
[HttpGet]
public int GetUnsized(string team)
{
using (var client = new HttpClient())
{
var byteArray = new System.Text.UTF8Encoding().GetBytes("AutomationService:Aut0mate0n!");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
HttpResponseMessage response = client.GetAsync(getUnsizedURL(team)).Result;
if (response.IsSuccessStatusCode)
{
string r = response.Content.ReadAsStringAsync().Result;
ResponseUnsized result1 = JsonConvert.DeserializeObject<ResponseUnsized>(r);
return result1.total;
} else
{
Debug.WriteLine("failed Query");
return -1;
}
}
}
}
}<file_sep>
var margin = { top: 30, right: 20, bottom: 100, left: 100 },
width = 1000 - margin.left - margin.right,
height = 570 - margin.top - margin.bottom;
var monthsInGraph = [];
function getLastMonths(sprStart, sprEnd) {
var months = [];
var startMo = monthSprints[sprStart];
var endMo = monthSprints[sprEnd];
while (!startMo) {
sprStart += 1;
startMo = monthSprints[sprStart];
}
while (!endMo) {
sprEnd -= 1;
endMo = monthSprints[sprEnd];
}
var startMoSpace = startMo.split(/[^0-9a-zA-Z]+/g).join(' ');
var endMoSpace = endMo.split(/[^0-9a-zA-Z]+/g).join(' ');
return diff(startMoSpace, endMoSpace);
}
function diff(from, to) {
var arr = [];
var datFrom = new Date('1 ' + from);
var datTo = new Date('1 ' + to);
var fromYear = datFrom.getFullYear();
var toYear = datTo.getFullYear();
var diffYear = (12 * (toYear - fromYear)) + datTo.getMonth();
for (var i = datFrom.getMonth() ; i <= diffYear; i++) {
arr.push(months[i % 12] + " " + Math.floor(fromYear + (i / 12)));
}
return arr;
}
function displayGraph() {
var x = d3.scale.linear().range([0, width]);
var x2 = d3.scale.ordinal()
.domain(monthsInGraph)
.rangePoints([50, width - margin.right]);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(10);
var xAxis2 = d3.svg.axis().scale(x2)
.orient("bottom").innerTickSize(-height).outerTickSize(15).ticks(6);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(6).tickFormat(function (d) { return d + "%"; });
var percentLine = d3.svg.line()
.x(function (d) { return x(d.sprint); })
.y(function (d) { return y(d.percent); });
var movingAverageLine = d3.svg.line()
.x(function (d, i) { return x(d.sprint); })
.y(function (d, i) { return y(d.movingAverage); })
.interpolate("basis");
var color = d3.scale.category10();
var lineGraph = d3.select("#velocityVisGraph").append("svg")
.attr("id", "velocityLineGraphSvg")
.attr("width", width + margin.left + margin.right + 20)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
d3.csv(pathToCsv, function (error, fullDataset) {
dataset = fullDataset.filter(function (d) {
return d.sprint >= (endSprint - 12);
})
dataset.forEach(function (d, i) {
committed: +d.committed;
completed: +d.completed;
d.percent = Math.round(d.completed / d.committed * 100);
d.prevSprint = (fullDataset.filter(function (e) {
return (e.sprint == +d.sprint - 1 && e.team == d.team);
}))[0];
d.prevPrevSprint = (fullDataset.filter(function (e) {
return (e.sprint == +d.sprint - 2 && e.team == d.team);
}))[0];
sprint: "Sprint " + d.sprint;
d.movingAverage = (getPercent(d.prevPrevSprint.committed, d.prevPrevSprint.completed) + getPercent(d.prevSprint.committed, d.prevSprint.completed) + d.percent) / 3.0;
d.movingPointAverage = (+d.prevPrevSprint.completed + +d.prevSprint.completed + +d.completed) / 3.0;
if (d.team == "onMessage") {
onMessageAveragePoints = d.movingPointAverage;
} else if (d.team == "onCampus") {
onCampusAveragePoints = d.movingPointAverage;
} else if (d.team == "onBoard") {
onBoardAveragePoints = d.movingPointAverage;
} else if (d.team == "onRecord") {
onRecordAveragePoints = d.movingPointAverage;
}
}
);
x.domain([endSprint - 12, endSprint]);
y.domain([d3.min(dataset, function (d) { return d.percent; }), d3.max(dataset, function (d) { return d.percent; })]);
var dataNest = d3.nest()
.key(function (d) { return d.team; })
.entries(dataset);
legendSpace = (width / dataNest.length);
dataNest.forEach(function (d, i) {
lineGraph.append("path")
.attr("class", "line")
.attr("fill", "none")
.style("stroke", function () {
return d.color = color(d.key);
})
.attr("stroke-width", "3")
.attr("id", 'tag' + d.key.replace(/\s+/g, ''))
.attr("d", percentLine(d.values))
.on("mouseover", function () {
d3.select(this).attr("stroke-width", "3").style("stroke", "red")
})
.on("mouseout", function () {
d3.select(this).attr("stroke-width", "3").style("stroke", color(d.key));
})
;
lineGraph.append("path")
.attr("class", "avg")
.attr("d", movingAverageLine(d.values))
.attr("fill", "none")
.style("stroke", function () {
return d.color = color(d.key);
})
.attr("stroke-width", "3")
.style("stroke-opacity", "1.0")
.attr("id", 'tag' + d.key.replace(/\s+/g, 'avg'));
d.values.forEach(function (p) {
lineGraph.append("circle")
.attr("id", 'tag' + d.key.replace(/\s+/g, ''))
.attr("class", "dataPoint")
.attr("r", 4)
.attr("cx", x(p.sprint))
.attr("cy", y(p.percent))
.append("title")
.text("Sprint " + p.sprint + ", " + p.percent + "% (" + p.completed + " of " + p.committed + ")");
});
lineGraph.append("text")
.attr("x", (legendSpace / 5) + i * legendSpace + 25)
.attr("y", height + (margin.bottom / 1.5) + 30)
.attr("class", "legend")
.style("fill", function () {
return d.color = color(d.key);
})
.attr("cursor", "pointer")
.style("font-size", "22px")
.style("font-weight", "bold")
.on("click", function () {
var active = d.active ? false : true,
newOpacity = active ? "hidden" : "visible";
d3.selectAll("#tag" + d.key.replace(/\s+/g, ''))
.transition().duration(100)
.style("visibility", newOpacity);
d3.selectAll("#tag" + d.key.replace(/\s+/g, 'avg'))
.transition().duration(100)
.style("visibility", newOpacity);
d.active = active;
})
.text(d.key);
});
lineGraph.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
lineGraph.append("g")
.attr("class", "y axis")
.call(yAxis);
lineGraph.append("text")
.attr("text-anchor", "middle")
.attr("transform", "translate(-50," + (height / 2) + ")rotate(-90)")
.text("Percent Completed");
lineGraph.append("g")
.attr("class", "x axis2")
.attr("transform", "translate(0, " + (+height + +30) + ")")
.call(xAxis2);
lineGraph.selectAll(".axis2 > path")
.remove();
lineGraph.selectAll(".axis2 > .tick")
.attr("cursor", "pointer")
.append("title")
.text(function (d) {
parts = d.split(' ');
var option = $('#monthVelocity ' + 'option[value=\'' + parts.join('') + '\']')
endSprint = option.attr('sprintnum');
var mo = parts[0];
if (sprintsInMonth[mo] == 2) {
return "Sprints: " + (+endSprint - 1) + ", " + endSprint;
} else {
return "Sprints: " + (+endSprint - 2) + ", " + (+endSprint - 1) + ", " + endSprint;
}
});
});
}<file_sep>var checkRelQ = function () {
if (populatedRelQ) {
displayFirstDataRelQ();
} else {
setTimeout(checkRelQ, 100);
}
}
function displayFirstDataRelQ() {
document.getElementById("addMultipleRelQ").checked = true;
$('#sprintReleaseQ option:last').prop('selected', true);
var dropdown = document.getElementById("scrumTeamReleaseQ");
for (var i = 0; i < dropdown.options.length; i++) {
dropdown.value = dropdown.options[i].value;
displayReleaseQ();
}
document.getElementById("scrumTeamReleaseQ").value = "All";
}
function showTeamHistoryRelQ() {
clearAddedRelQ();
document.getElementById("addMultipleRelQ").checked = true;
var dropdown = document.getElementById("sprintReleaseQ");
var temp = dropdown.value;
for (var i = 0; i < dropdown.options.length; i++) {
dropdown.value = dropdown.options[i].value;
displayReleaseQ();
}
dropdown.value = temp;
}
function showSprintRelQ() {
clearAddedRelQ();
document.getElementById("addMultipleVel").checked = true;
clearAddedRelQ();
document.getElementById("addMultipleRelQ").checked = true;
var dropdown = document.getElementById("scrumTeamReleaseQ");
var temp = dropdown.value;
for (var i = 0; i < dropdown.options.length; i++) {
dropdown.value = dropdown.options[i].value;
displayReleaseQ();
}
dropdown.value = temp;
}
function checkBoxClearAddedRelQ() {
if (document.getElementById("addMultipleRelQ").checked) {
return;
} else {
clearAddedRelQ();
}
}
function clearAddedRelQ() {
d3.selectAll("#releaseQSvg").remove();
}
function displayReleaseQModal(d) {
var modal = document.getElementById('myModal')
if (d.lastYearMonth) {
var allPercentChange = Math.round(((d.monthDefects - d.lastYearMonth.monthDefects) / d.monthDefects) * 10000) / 100;
var urgentPercentChange = Math.round(((d.monthUrgentDefects - d.lastYearMonth.monthUrgentDefects) / d.monthUrgentDefects) * 10000)/100;
if (allPercentChange < 0) {
var allColor = "darkgreen";
allPercentChange = "<span class=\"downarrow\">⇮</span> " + allPercentChange;
} else {
var allColor = "red";
allPercentChange = "<span class=\"uparrow\">⇮</span> " + allPercentChange;
}
if (urgentPercentChange < 0) {
var urgentColor = "darkgreen";
urgentPercentChange = "<span class=\"downarrow\">⇮</span> " + urgentPercentChange;
} else {
var urgentColor = "red";
urgentPercentChange = "<span class=\"uparrow\">⇮</span> " + urgentPercentChange;
}
document.getElementById('modal-text').innerHTML = "<strong style=\"font-size:16px;\"> " + reformatMonthVal(d.lastYearMonth.month) + "</strong><br/><p style = \"font-weight:600;color:" + allColor + "\"> Defects: " + d.lastYearMonth.monthDefects + "<p style = \"font-weight:600;font-size:24px;color:" + allColor + "\"<br/> YOY: " + allPercentChange + "%</p>" +
"<br/><p style = \"font-weight:600;color:" + urgentColor + "\">Urgent Defects: " + d.lastYearMonth.monthUrgentDefects+ "<p style = \"font-weight:600;font-size:24px;color:" + allColor + "\"<br/> YOY: " + urgentPercentChange + "%</p>";
} else {
document.getElementById('modal-text').innerHTML = "<strong style=\"color:#55555\"> No data found for previous month. </strong>";
}
modal.style.display = "block";
}
function displayReleaseQ() {
var teamVal = document.getElementById("scrumTeamReleaseQ").value;
var monthVal = document.getElementById("sprintReleaseQ").value;
var addMultipleVal = document.getElementById("addMultipleRelQ").checked;
var w = 150;
var h = 200;
var bordercolor = "gray";
var strokewidth = "5px";
var startYear = 2015;
var add = 0;
var mo = "April"
var sprintsLeft = sprintsInMonth[mo];
d3.csv(pathToCsv, function (error, dataset) {
dataset.forEach(function (d) {
sprint: "Sprint " + d.sprint;
team: d.team;
urgent: d.urgentdefects;
all: d.alldefects;
d.prevSprint = (dataset.filter(function (e) {
return (e.sprint == +d.sprint - 1 && e.team == teamVal);
}))[0];
d.nextSprint = (dataset.filter(function (e) {
return (e.sprint == +d.sprint + 1 && e.team == teamVal);
}))[0];
if (d.prevSprint == null) {
add = 0;
mo = "April";
sprintsLeft = sprintsInMonth[mo];
}
if (sprintsLeft == 1) {
d.month = mo + (startYear + add);
if (!(monthSprints[d.sprint])) {
monthSprints[d.sprint] = d.month;
}
}
if (sprintsLeft == 0) {
sprintsLeft = sprintsInMonth[mo];
mo = months[(months.indexOf(mo) + 1) % 12];
if (mo == "January") {
add += 1;
}
}
sprintsLeft--;
d.mo = mo;
if (d.prevSprint) {
if (d.prevSprint.prevSprint && sprintsInMonth[d.mo] == 3) {
d.monthDefects = +d.alldefects + +d.prevSprint.alldefects + +d.prevSprint.prevSprint.alldefects;
} else {
d.monthDefects = +d.alldefects + +d.prevSprint.alldefects;
}
} else {
d.monthDefects = +d.alldefects;
}
if (sprintsInMonth[d.mo] == 3) {
d.monthUrgentDefects = +d.urgentdefects + +d.prevSprint.urgentdefects + +d.nextSprint.urgentdefects;
} else {
if (d.prevSprint) {
d.monthUrgentDefects = +d.urgentdefects + +d.prevSprint.urgentdefects;
} else {
d.monthUrgentDefects = +d.urgentdefects;
}
}
if (d.month) {
var digit = +(d.month.charAt(d.month.length - 1));
var lastYear = d.month.substr(0, d.month.length-1) + (digit -1);
d.lastYearMonth = (dataset.filter(function (e) {
return (e.month == lastYear && e.team == teamVal);
}))[0];
}
});
if (!addMultipleVal) {
d3.select("#releaseQsvg").remove();;
}
var allR;
var urgentR;
var defectsSvg = d3.select("#releaseQVis").append("svg")
.attr("id", "releaseQSvg")
.attr("width", w)
.attr("height", h);
var defects = defectsSvg
.selectAll("circle")
.data(dataset
.filter(function (d) { return (d.month == monthVal && d.team == teamVal); })
)
.enter();
var borderPath = defects.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("height", w)
.attr("width", h)
.style("stroke", bordercolor)
.style("fill", function (d) {
if (d.team == "All") {
if (d.monthDefects > 10) {
return "#E77471";
} else if (d.monthDefects > 10) {
return "pink";
}
else {
return "none";
}
}
else if (d.monthDefects > 5) {
return "pink";
} else {
return "none";
}
})
.style("strokewidth", strokewidth);
var d1 = defects.append("circle")
.attr("r", function (d) {
if (d.monthDefects > 40) {
allR = 40
} else {
allR = d.monthDefects;
}
return allR;
})
.attr("cx", 75)
.attr("cy", 75)
.attr("cursor", "pointer")
.attr("fill", "orange")
.on("click", function (d) {
displayReleaseQModal(d)
});
defects.append("circle")
.filter(function (d) { return (d.month == monthVal && d.team == teamVal); })
.attr("r", function (d) {
if (d.monthUrgentDefects > 40) {
urgentR = 40;
} else {
urgentR = d.monthUrgentDefects;
}
return urgentR;
})
.attr("cx", 75)
.attr("cy", 75)
.attr("cursor", "pointer")
.attr("fill", "red")
.on("click", function (d) {
displayReleaseQModal(d)
});
defects.append("foreignObject")
.attr("x", "0")
.attr("y", function (d) {
if ((d.monthDefects == 0) && (d.monthUrgentDefects == 0)) {
return "50";
}
else {
return "115";
}
})
.attr("width", 150)
.append("xhtml")
.style("font", "12px 'Helvetica Neue'")
.style("color", function (d) {
if (d.monthUrgentDefects > 0) {
return "red";
} else if (d.monthDefects > 0) {
return "#FF4500";
} else {
return "green";
}
})
.html(function (d) {
if ((d.monthUrgentDefects == 0) && (d.monthDefects == 0)) {
return "<h4 style=\"text-align:center\"><span style=\"font-size:50px\">✔</span><br>No defects found</h4>"
} else {
return "<h4 style=\"text-align:center;font-size:15px;font-weight:bold;\">Urgent Defect(s): " + d.monthUrgentDefects + "<br>Total Defect(s): " + d.monthDefects + "</h4>";
}
})
defects.append("text")
.attr("x", 3)
.attr("y", 20)
.attr("font-family", "sans-serif")
.attr("fill", "black")
.attr("font-size", "15px")
.attr("font-weight", 700)
.text(function (d) {
var retStr = teamVal;
return retStr;
})
defects.append("text")
.attr("x", 3)
.attr("y", 40)
.attr("font-family", "sans-serif")
.attr("fill", "black")
.attr("font-size", "14px")
.text(function () {
return reformatMonthVal(monthVal);
})
})
};
function reformatMonthVal(monthVal) {;
return monthVal.replace(/[^a-z]/gi, "") + " " + monthVal.replace(/\D/g, "");
}<file_sep>function resetReleased() {
document.getElementById("releasedStories").innerHTML = "";
document.getElementById("releasedHotFixes").innerHTML = "";
document.getElementById("prevReleasedStories").innerHTML = "";
document.getElementById("prevReleasedHotFixes").innerHTML = "";
document.getElementsByClassName("releasedContainer")[0].style.color = "black";
document.getElementsByClassName("releasedContainer")[1].style.color = "black";
document.getElementsByClassName("releasedContainer")[0].style.backgroundColor = "lightgray";
document.getElementsByClassName("releasedContainer")[1].style.backgroundColor = "lightgray";
document.getElementById("loaderStories").hidden = false;
document.getElementById("loaderHotFixes").hidden = false;
document.getElementById("releasedSelect").disabled = true;
document.getElementById("monthReleased").disabled = true;
document.getElementById("monthReleasedBtn").disabled = true;
document.getElementById("loadingReleased").hidden = false;
}
function enableReleased()
{
document.getElementById("loadingReleased").hidden = true;
document.getElementById("monthReleased").disabled = false;
document.getElementById("releasedSelect").disabled = false;
document.getElementById("loaderStories").hidden = true;
document.getElementById("monthReleasedBtn").disabled = false;
}
function addRelStories(data) {
document.getElementById("releasedStories").innerHTML = "<h3>Released Stories: " + data + "</h3>";
}
function addRelHotFixes(data) {
document.getElementById("releasedHotFixes").innerHTML = "<h3>Released Hot Fixes: " + data + "</h3>";
}
function addUnsized(data) {
document.getElementById("unsizedStoriesDisp").innerHTML = "<h3 style=\"padding-left:25px\">Unsized Stories: " + data + "</h3>";
}
function addSized(data, team) {
onMessageBacklogSP = data;
var avgPoints;
if (team == "onCampus") {
avgPoints = onCampusAveragePoints;
} else if (team == "onMessage") {
avgPoints = onMessageAveragePoints;
} else if (team == "onBoard") {
avgPoints = onBoardAveragePoints;
} else if (team == "onRecord") {
avgPoints = onRecordAveragePoints;
} else {
avgPoints = onCampusAveragePoints + onMessageAveragePoints + onBoardAveragePoints + onRecordAveragePoints;
}
document.getElementById("storyPointsInBacklog").innerHTML = "<h3 style=\"padding-left:25px\">Story Points In Backlog: " + data +
"<h3><h4 style=\"padding-left:50px;color:gray;font-style:italic\">Latest Average of Story Points Completed: " + avgPoints.toFixed(2) +
"<br/>Sprints To Complete Sized Backlog: " + (data / avgPoints).toFixed(2);
}
function switchToMonth() {
document.getElementById("sprintVelocity").hidden = true;
document.getElementById("sprintVelocityText").hidden = true;
document.getElementById("monthVelocity").hidden = false;
document.getElementById("monthVelocityText").hidden = false;
document.getElementById("monthToSprintTranslation").hidden = false;
updateTranslation();
}
function switchToSprint() {
document.getElementById("sprintVelocity").hidden = false;
document.getElementById("sprintVelocityText").hidden = false;
document.getElementById("monthVelocity").hidden = true;
document.getElementById("monthVelocityText").hidden = true;
document.getElementById("monthToSprintTranslation").hidden = true;
}
function addShadows(circleSvg) {
var defs = circleSvg.append("defs");
var filter = defs.append("filter")
.attr("id", "drop-shadow")
.attr("height", "130%");
filter.append("feGaussianBlur")
.attr("in", "SourceAlpha")
.attr("stdDeviation", 5)
.attr("result", "blur");
filter.append("feOffset")
.attr("in", "blur")
.attr("dx", 5)
.attr("dy", 5)
.attr("result", "offsetBlur");
var feMerge = filter.append("feMerge");
feMerge.append("feMergeNode")
.attr("in", "offsetBlur")
feMerge.append("feMergeNode")
.attr("in", "SourceGraphic");
var filter2 = defs.append("filter")
.attr("id", "drop-shadow2")
.attr("height", "130%");
filter2.append("feGaussianBlur")
.attr("in", "SourceAlpha")
.attr("stdDeviation", 2)
.attr("result", "blur");
filter2.append("feOffset")
.attr("in", "blur")
.attr("dx", 3)
.attr("dy", 3)
.attr("result", "offsetBlur");
var feMerge2 = filter2.append("feMerge");
feMerge2.append("feMergeNode")
.attr("in", "offsetBlur")
feMerge2.append("feMergeNode")
.attr("in", "SourceGraphic");
}
| c94aa4942b794eb0c947bedb1baba03f4969aadd | [
"JavaScript",
"C#"
] | 7 | JavaScript | smarthi4/DashboardApp | e722b6ba3f0533bc7a22f28c64c65d89e5500ece | e97d57c1957fb64a61b87ebe49d92c27c01b224c |
refs/heads/master | <file_sep><?php
$nameErr = $creditErr = $selectSectionErr = "";
$name = $credit = "";
$selectSection = array();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is missing";
}
else {
$name = $_POST["name"];
}
if (empty($_POST["selectSection"])) {
$selectSectiontErr = "You must select section";
}
else {
$selectSection = $_POST["selectSection"];
}
if (!isset($_POST["credit"])) {
$creditErr = "You must select credit type";
}
else {
$credit = $_POST["credit"];
}
}
| db6b95c0a8c81a176a0300db6796a7d436a58c90 | [
"PHP"
] | 1 | PHP | iuthub/lab-5-Salohiddinrb2 | c93c023d7ce92a22daec37403e3da4963cef2963 | 025d215ddb49787a55a7456730853b436eb1d824 |
refs/heads/master | <repo_name>beingPurple/Namebot<file_sep>/nameBot.py
import discord
import time
from discord.ext import commands
bot = discord.Client()
@bot.event
async def on_ready(): #proof that it's working
print("beep boop")
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
@bot.event
async def on_member_update(before, after):
if after.id != bot.user.id:
splitAfter = after.nick
splitAfter = splitAfter.split('-', 1)
nameList = after.roles
nameSize = len(nameList)
i = 0
nicList = "-"
while i < nameSize:
if str(nameList[i]) != '@everyone' \
and str(nameList[i]) != 'Exec'\
and str(nameList[i]) != 'Server Admin':
nicList = nicList + " " + str(nameList[i])
i += 1
print("new member updated: ", before.nick, "roles: ", nicList)
print("split after name: ", splitAfter)
newNick = splitAfter[0] + nicList
print("new name: ", newNick)
await after.edit(nick=newNick)
time.sleep(1)
bot.run('<KEY>') #an outdated token of course | 46234ad2149159637e5ed939642a053a7526cf7f | [
"Python"
] | 1 | Python | beingPurple/Namebot | c811bbad9c7fc90dc43258c687387e24e2b5b39c | c8a2b211c8eb0deab52d39df8b5b0a05317f869c |
refs/heads/main | <repo_name>prakashcc/github-readme-streak-stats<file_sep>/src/stats.php
<?php
declare(strict_types=1);
/**
* Get all HTTP request responses for user's contributions
*
* @param string $user GitHub username to get graphs for
*
* @return array<stdClass> List of contribution graph response objects
*/
function getContributionGraphs(string $user): array
{
// Get the years the user has contributed
$contributionYears = getContributionYears($user);
// build a list of individual requests
$requests = array();
foreach ($contributionYears as $year) {
// create query for year
$start = "$year-01-01T00:00:00Z";
$end = "$year-12-31T23:59:59Z";
$query = "query {
user(login: \"$user\") {
contributionsCollection(from: \"$start\", to: \"$end\") {
contributionCalendar {
totalContributions
weeks {
contributionDays {
contributionCount
date
}
}
}
}
}
}";
// create curl request
$requests[$year] = getGraphQLCurlHandle($query);
}
// build multi-curl handle
$multi = curl_multi_init();
foreach ($requests as $request) {
curl_multi_add_handle($multi, $request);
}
// execute queries
$running = null;
do {
curl_multi_exec($multi, $running);
} while ($running);
// close the handles
foreach ($requests as $request) {
curl_multi_remove_handle($multi, $request);
}
curl_multi_close($multi);
// collect responses from last to first
$response = array();
foreach ($requests as $request) {
array_unshift($response, json_decode(curl_multi_getcontent($request)));
}
return $response;
}
/**
* Get all tokens from environment variables (TOKEN, TOKEN2, TOKEN3, etc.) if they are set
*
* @return array<string> List of tokens
*/
function getGitHubTokens() {
// result is already calculated
if (isset($GLOBALS["ALL_TOKENS"])) {
return $GLOBALS["ALL_TOKENS"];
}
// find all tokens in environment variables
$tokens = array($_SERVER["TOKEN"] ?? "");
for ($i = 2; $i < 4; $i++) {
if (isset($_SERVER["TOKEN$i"])) {
// add token to list
$tokens[] = $_SERVER["TOKEN$i"];
}
}
// store for future use
$GLOBALS["ALL_TOKENS"] = $tokens;
return $tokens;
}
/** Create a CurlHandle for a POST request to GitHub's GraphQL API
*
* @param string $query GraphQL query
*
* @return CurlHandle The curl handle for the request
*/
function getGraphQLCurlHandle(string $query)
{
$all_tokens = getGitHubTokens();
$token = $all_tokens[array_rand($all_tokens)];
$headers = array(
"Authorization: bearer $token",
"Content-Type: application/json",
"Accept: application/vnd.github.v4.idl",
"User-Agent: GitHub-Readme-Streak-Stats"
);
$body = array("query" => $query);
// create curl request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.github.com/graphql");
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_VERBOSE, false);
return $ch;
}
/**
* Create a POST request to GitHub's GraphQL API
*
* @param string $query GraphQL query
*
* @return stdClass An object from the json response of the request
*
* @throws AssertionError If SSL verification fails
*/
function fetchGraphQL(string $query): stdClass
{
$ch = getGraphQLCurlHandle($query);
$response = curl_exec($ch);
curl_close($ch);
$obj = json_decode($response);
// handle curl errors
if ($response === false || $obj === null || curl_getinfo($ch, CURLINFO_HTTP_CODE) >= 400) {
// set response code to curl error code
http_response_code(curl_getinfo($ch, CURLINFO_HTTP_CODE));
// Missing SSL certificate
if (str_contains(curl_error($ch), 'unable to get local issuer certificate')) {
throw new AssertionError("You don't have a valid SSL Certificate installed or XAMPP.");
}
// Handle errors such as "Bad credentials"
if ($obj && $obj->message) {
throw new AssertionError("Error: $obj->message \n<!-- $response -->");
}
// TODO: Make the $response part get passed into a custom error and render the commented details in the SVG card generator
throw new AssertionError("An error occurred when getting a response from GitHub.\n<!-- $response -->");
}
return $obj;
}
/**
* Get the years the user has contributed
*
* @param string $user GitHub username to get years for
*
* @return array List of years the user has contributed
*
* @throws InvalidArgumentException If the user doesn't exist or there is an error
*/
function getContributionYears(string $user): array
{
$query = "query {
user(login: \"$user\") {
contributionsCollection {
contributionYears
}
}
}";
$response = fetchGraphQL($query);
// User not found
if (!empty($response->errors) && $response->errors[0]->type === "NOT_FOUND") {
throw new InvalidArgumentException("Could not find a user with that name.");
}
// API Error
if (!empty($response->errors)) {
// Other errors that contain a message field
throw new InvalidArgumentException($response->errors[0]->message);
}
// API did not return data
if (!isset($response->data) && isset($response->message)) {
// Other errors that contain a message field
throw new InvalidArgumentException($response->message);
}
return $response->data->user->contributionsCollection->contributionYears;
}
/**
* Get an array of all dates with the number of contributions
*
* @param array<string> $contributionCalendars List of GraphQL response objects
*
* @return array<string, int> Y-M-D dates mapped to the number of contributions
*/
function getContributionDates(array $contributionGraphs): array
{
// get contributions from HTML
$contributions = array();
$today = date("Y-m-d");
$tomorrow = date("Y-m-d", strtotime("tomorrow"));
foreach ($contributionGraphs as $graph) {
if (!empty($graph->errors)) {
throw new AssertionError($graph->data->errors[0]->message);
}
$weeks = $graph->data->user->contributionsCollection->contributionCalendar->weeks;
foreach ($weeks as $week) {
foreach ($week->contributionDays as $day) {
$date = $day->date;
$count = $day->contributionCount;
// count contributions up until today
// also count next day if user contributed already
if ($date <= $today || ($date == $tomorrow && $count > 0)) {
// add contributions to the array
$contributions[$date] = $count;
}
}
}
}
return $contributions;
}
/**
* Get a stats array with the contribution count, streak, and dates
*
* @param array<string, int> $contributions Y-M-D contribution dates with contribution counts
* @return array<string, mixed> Streak stats
*/
function getContributionStats(array $contributions): array
{
// if no contributions, display error
if (empty($contributions)) {
throw new AssertionError("No contributions found.");
}
$today = array_key_last($contributions);
$first = array_key_first($contributions);
$stats = [
"totalContributions" => 0,
"firstContribution" => "",
"longestStreak" => [
"start" => $first,
"end" => $first,
"length" => 0,
],
"currentStreak" => [
"start" => $first,
"end" => $first,
"length" => 0,
],
];
// calculate the stats from the contributions array
foreach ($contributions as $date => $count) {
// add contribution count to total
$stats["totalContributions"] += $count;
// check if still in streak
if ($count > 0) {
// increment streak
++$stats["currentStreak"]["length"];
$stats["currentStreak"]["end"] = $date;
// set start on first day of streak
if ($stats["currentStreak"]["length"] == 1) {
$stats["currentStreak"]["start"] = $date;
}
// set first contribution date the first time
if (!$stats["firstContribution"]) {
$stats["firstContribution"] = $date;
}
// update longestStreak
if ($stats["currentStreak"]["length"] > $stats["longestStreak"]["length"]) {
// copy current streak start, end, and length into longest streak
$stats["longestStreak"]["start"] = $stats["currentStreak"]["start"];
$stats["longestStreak"]["end"] = $stats["currentStreak"]["end"];
$stats["longestStreak"]["length"] = $stats["currentStreak"]["length"];
}
}
// reset streak but give exception for today
elseif ($date != $today) {
// reset streak
$stats["currentStreak"]["length"] = 0;
$stats["currentStreak"]["start"] = $today;
$stats["currentStreak"]["end"] = $today;
}
}
return $stats;
}
<file_sep>/.env.example
# replace ghp_example with your GitHub PAT token
TOKEN=<PASSWORD>
<file_sep>/src/index.php
<?php
declare(strict_types=1);
// load functions
require_once '../vendor/autoload.php';
require_once "stats.php";
require_once "card.php";
// load .env
$dotenv = \Dotenv\Dotenv::createImmutable(dirname(__DIR__, 1));
$dotenv->safeLoad();
// if environment variables are not loaded, display error
if (!isset($_SERVER["TOKEN"])) {
$message = file_exists(dirname(__DIR__ . '../.env', 1))
? "Missing token in config. Check Contributing.md for details."
: ".env was not found. Check Contributing.md for details.";
renderOutput($message);
}
// set cache to refresh once per hour
header("Expires: " . gmdate("D, d M Y H:i:s", time() + 3600) . " GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: public, max-age=3600");
// redirect to demo site if user is not given
if (!isset($_REQUEST["user"])) {
header('Location: demo/');
exit;
}
try {
// get streak stats for user given in query string
$contributionGraphs = getContributionGraphs($_REQUEST["user"]);
$contributions = getContributionDates($contributionGraphs);
$stats = getContributionStats($contributions);
renderOutput($stats);
} catch (InvalidArgumentException | AssertionError $error) {
renderOutput($error->getMessage());
}
<file_sep>/CONTRIBUTING.md
## Contributing Guidelines
Contributions are welcome! Feel free to open an issue or submit a pull request if you have a way to improve this project.
Make sure your request is meaningful and you have tested the app locally before submitting a pull request.
This documentation contains a set of guidelines to help you during the contribution process.
### Need some help regarding the basics?
You can refer to the following articles on the basics of Git and GitHub in case you are stuck:
- [Forking a Repo](https://help.github.com/en/github/getting-started-with-github/fork-a-repo)
- [Cloning a Repo](https://help.github.com/en/desktop/contributing-to-projects/creating-an-issue-or-pull-request)
- [How to create a Pull Request](https://opensource.com/article/19/7/create-pull-request-github)
- [Getting started with Git and GitHub](https://towardsdatascience.com/getting-started-with-git-and-github-6fcd0f2d4ac6)
- [Learn GitHub from Scratch](https://lab.github.com/githubtraining/introduction-to-github)
### Installing Requirements
#### Requirements
* [PHP 8.0+](https://www.apachefriends.org/index.html)
* [Composer](https://getcomposer.org)
* [Imagick](https://www.php.net/imagick)
#### Linux
```bash
sudo apt-get install php
sudo apt-get install php-curl
sudo apt-get install composer
```
#### Windows
Install PHP from [XAMPP](https://www.apachefriends.org/index.html) or [php.net](https://windows.php.net/download)
[▶ How to install and run PHP using XAMPP (Windows)](https://www.youtube.com/watch?v=K-qXW9ymeYQ)
[📥 Download Composer](https://getcomposer.org/download/)
### Clone the repository
```
git clone https://github.com/DenverCoder1/github-readme-streak-stats.git
cd github-readme-streak-stats
```
### Authorization
To get the GitHub API to run locally you will need to provide a token.
1. Visit [this link](https://github.com/settings/tokens/new?description=GitHub%20Readme%20Streak%20Stats) to create a new Personal Access Token
2. Scroll to the bottom and click **"Generate token"**
3. **Make a copy** of `.env.example` named `.env` in the root directory and add **your token** after `TOKEN=`.
```php
TOKEN=<your-token>
```
### Install dependencies
Run the following command to install all the required dependencies to work on this project.
```bash
composer install
```
### Running the app locally
```bash
composer start
```
Open http://localhost:8000/?user=DenverCoder1 to run the project locally
Open http://localhost:8000/demo/ to run the demo site
### Running the tests
Run the following command to run the PHPUnit test script which will verify that the tested functionality is still working.
```bash
composer test
```
## Submitting Contributions 👨💻
Below you will find the process and workflow used to review and merge your changes.
### Step 0 : Find an issue
- Take a look at the existing issues or create your **own** issues!
- Wait for the issue to be assigned to you after which you can start working on it.

### Step 1 : Fork the Project
- Fork this repository. This will create a copy of this repository on your GitHub profile.
Keep a reference to the original project in the `upstream` remote.
```bash
git clone https://github.com/<your-username>/github-readme-streak-stats.git
cd github-readme-streak-stats
git remote add upstream https://github.com/DenverCoder1/github-readme-streak-stats.git
```

- If you have already forked the project, update your copy before working.
```bash
git remote update
git checkout <branch-name>
git rebase upstream/<branch-name>
```
### Step 2 : Branch
Create a new branch. Use its name to identify the issue your addressing.
```bash
# It will create a new branch with name Branch_Name and switch to that branch
git checkout -b Branch_Name
```
### Step 3 : Work on the issue assigned
- Work on the issue(s) assigned to you.
- Make all the necessary changes to the codebase.
- After you've made changes or made your contribution to the project, add changes to the branch you've just created using:
```bash
# To add all new files to the branch
git add .
# To add only a few files to the branch
git add <some files (with path)>
```
### Step 4 : Commit
- Commit a descriptive message using:
```bash
# This message will get associated with all files you have changed
git commit -m "message"
```
### Step 5 : Work Remotely
- Now you are ready to your work on the remote repository.
- When your work is ready and complies with the project conventions, upload your changes to your fork:
```bash
# To push your work to your remote repository
git push -u origin Branch_Name
```
- Here is how your branch will look.

### Step 6 : Pull Request
- Go to your forked repository in your browser and click on "Compare and pull request". Then add a title and description to your pull request that explains your contribution.
<img width="700" alt="compare and pull request" src="https://user-images.githubusercontent.com/63443481/136186304-c0a767ea-1fd2-4b0c-b5a8-3e366ddc06a3.PNG">
<img width="882" alt="opening pull request" src="https://user-images.githubusercontent.com/63443481/136186322-bfd5f333-136a-4d2f-8891-e8f97c379ba8.PNG">
- Voila! Your Pull Request has been submitted and it's ready to be merged.🥳
#### Happy Contributing!
| 8a83091ceb0deacb2ad13b732d42bffa71b5a6d9 | [
"Markdown",
"PHP",
"Shell"
] | 4 | PHP | prakashcc/github-readme-streak-stats | dd47c31c9be85e26908087ac3f5af1244daab7a6 | ae97a6a31ef7905b21a99c8074e095d6992084ff |
refs/heads/master | <file_sep>import logo from './logo.svg';
import './App.css';
import { BrowserRouter,
Switch,
Route,
Link } from 'react-router-dom';
import Home from './components/home'
import About from './components/about'
import Contact from './components/contact'
function App() {
return (
<BrowserRouter>
<div className="App">
<div class="header">
<h1>Welcome to React Router</h1>
</div>
<div class="App-link">
<div>
<Link to="/">Home</Link>{''}
</div>
<div>
<Link to="/about">About</Link>{''}
</div>
<div>
<Link to="/contact">Contact</Link>{''}
</div>
</div>
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About}/>
<Route path="/contact" component={Contact}/>
<Route render={() => <h1> Page not found </h1>}/>
</Switch>
</div>
</BrowserRouter>
);
}
export default App;
| 26c6fcc047dbb4be77dec128798fe91142354f7e | [
"JavaScript"
] | 1 | JavaScript | alexh0810/React-Routing-Exercise | 89f291b94c3a730938a8488e932cbfeef47c55fe | 40cc2e7c3f2079bd5680c795741923af4f1d5e5c |
refs/heads/master | <repo_name>hieplam/SqlFluent<file_sep>/SqlFluent/IWhere.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlFluent
{
public interface IWhere
{
IOperator Where(string value);
IWhere OrderBy(string value);
}
}
<file_sep>/SqlFluent/IFrom.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlFluent
{
public interface IFrom
{
IWhere From(string value);
}
}
| 6305e0712eef27f3f3520848f26bf554ffeccc3f | [
"C#"
] | 2 | C# | hieplam/SqlFluent | d61c59ec95b34109849158abcc04232899081b43 | 998c35e27a8c4d898764f9a584aad33d61c56122 |
refs/heads/master | <repo_name>ashwin21rao/Sudoku-Solver<file_sep>/README.md
# Sudoku-Solver
Sudoku Solver using the backtracking algorithm. Includes a GUI for visualization and a text-based version.
# Instructions
Play sudoku by running gui.py!
There are 5 games provided in the games.txt file, in increasing order of difficulty. These are loaded into the GUI.
Click on a cell to select it.
Type a digit to enter it into the active cell. Press BACKSPACE or DELETE to remove it.
Click Solve to watch the backtracking algorithm solve the Sudoku Board!
<file_sep>/solver.py
import numpy as np
def solve(array, i, j):
if j > 8:
j = 0
i += 1
if i > 8:
return True
if array[i, j] != 0:
return solve(array, i, j + 1)
for value in range(1, 10):
if validCell(array, i, j, value):
array[i, j] = value
if solve(array, i, j + 1):
return True
array[i, j] = 0
return False
def validCell(array, i, j, value):
return value not in array[i, :] and \
value not in array[:, j] and \
value not in array[i // 3 * 3: i // 3 * 3 + 3, j // 3 * 3: j // 3 * 3 + 3]
def main():
array = np.array([[0, 0, 0, 7, 0, 0, 8, 0, 0],
[0, 0, 4, 0, 0, 0, 6, 1, 0],
[3, 7, 0, 0, 0, 1, 5, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0],
[4, 0, 9, 5, 0, 0, 0, 0, 0],
[0, 0, 2, 0, 0, 9, 1, 0, 3],
[0, 0, 0, 0, 4, 3, 2, 5, 0],
[0, 0, 0, 0, 0, 6, 0, 0, 0],
[0, 3, 0, 1, 0, 8, 0, 0, 0]])
solve(array, 0, 0)
print(array)
main()
<file_sep>/gui.py
import pygame
import numpy as np
pygame.init()
clock = pygame.time.Clock()
font_large = pygame.font.Font("extras/OpenSans-Bold.ttf", 25)
font_small = pygame.font.Font("extras/OpenSans-Bold.ttf", 20)
screen_width = 600
screen_height = 600
side_length = 405
margin = (screen_width - side_length) / 2
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Sudoku")
icon = pygame.image.load("extras/icon.png")
pygame.display.set_icon(icon)
COLOR_BLACK = (0, 0, 0)
COLOR_GRAY = (92, 92, 92)
COLOR_ACTIVE = (40, 111, 156)
COLOR_RED = (255, 0, 0)
COLOR_GREEN = (0, 255, 0)
COLOR_BLUE = (0, 0, 255)
def clear(values, mask):
values[np.logical_not(mask)] = 0
def solve(array, i, j, cells, mask, start_time):
if j > 8:
j = 0
i += 1
if i > 8:
return True
if array[i, j] != 0:
return solve(array, i, j + 1, cells, mask, start_time)
active_cell = cells[i][j]
for value in range(1, 10):
array[i, j] = value
drawBoard(cells, array, mask, active_cell, start_time, True)
drawButtons()
pygame.display.flip()
pygame.time.delay(5)
if validCell(array, i, j, value):
if solve(array, i, j + 1, cells, mask, start_time):
return True
array[i, j] = 0
return False
def validCell(array, i, j, value):
return np.count_nonzero(array[i, :] == value) == 1 and \
np.count_nonzero(array[:, j] == value) == 1 and \
np.count_nonzero(array[i // 3 * 3: i // 3 * 3 + 3, j // 3 * 3: j // 3 * 3 + 3] == value) == 1
def sudokuValues(game_number):
data = np.loadtxt("games.txt", delimiter=", ", dtype=np.int).reshape((-1, 9, 9))
array = data[game_number]
mask = (array != 0)
return array, mask
def updateTime(start_time):
current_time = (pygame.time.get_ticks() - start_time) // 1000
time = ""
for i in range(3):
if current_time > 0:
value = "0" + str(current_time % 60) if (current_time % 60) < 10 else str(current_time % 60)
time = ":" + value + time
current_time //= 60
else:
time = (":00" if i != 2 else "00") + time
return time
def getCells():
cell_side = side_length / 9
cells = [[pygame.Rect(0, 0, 0, 0) for _ in range(9)] for _ in range(9)]
for i in range(9):
for j in range(9):
cells[i][j] = pygame.Rect(margin + cell_side * j, margin + cell_side * i, cell_side, cell_side)
return cells
def drawButtons():
new_game_text = font_small.render("New Game", False, (255, 0, 0))
new_game_button = new_game_text.get_rect(bottomleft=(margin, margin))
screen.blit(new_game_text, new_game_button)
solve_text = font_small.render("Solve", False, (0, 255, 0))
solve_button = solve_text.get_rect(topleft=(margin, margin + side_length))
screen.blit(solve_text, solve_button)
clear_text = font_small.render("Clear", False, (0, 0, 255))
clear_button = clear_text.get_rect(topright=(screen_width - margin, margin + side_length))
screen.blit(clear_text, clear_button)
return {"new game": new_game_button,
"solve": solve_button,
"clear": clear_button}
def drawBoard(cells, values, mask, active_cell, start_time, solving=False):
screen.fill((255, 255, 255))
for i, row in enumerate(cells):
for j, cell in enumerate(row):
pygame.draw.rect(screen, (125, 130, 130), cell, 1)
if values[i, j] != 0:
if mask[i, j]:
text = font_large.render(str(values[i, j]), False, COLOR_BLACK)
else:
text = font_large.render(str(values[i, j]), False, COLOR_GRAY
if not solving and validCell(values, i, j, values[i, j])
else COLOR_GREEN if solving and validCell(values, i, j, values[i, j])
else COLOR_RED)
center = text.get_rect(center=cell.center)
screen.blit(text, center)
pygame.draw.rect(screen, COLOR_BLACK, (margin, margin, side_length, side_length), 4)
for i in range(1, 3):
pygame.draw.line(screen, COLOR_BLACK, (margin, margin + side_length * i / 3),
(margin + side_length, margin + side_length * i / 3), 3)
pygame.draw.line(screen, COLOR_BLACK, (margin + side_length * i / 3, margin),
(margin + side_length * i / 3, margin + side_length), 3)
if active_cell:
pygame.draw.rect(screen, COLOR_ACTIVE, active_cell, 3)
time = updateTime(start_time)
time_text = font_large.render(time, False, COLOR_BLACK)
pos = time_text.get_rect(bottomright=(screen_width - margin, margin))
screen.blit(time_text, pos)
def initializeGame(game_number):
values, mask = sudokuValues(game_number)
original_array = values.copy()
solved_array = values.copy()
return values, mask, original_array, solved_array
def gameloop():
start_time = pygame.time.get_ticks()
game_number = 0
total_games = 5
cells = getCells()
active_cell = None
active_cell_index = None
values, mask, original_array, solved_array = initializeGame(game_number)
running = True
while running:
drawBoard(cells, values, mask, active_cell, start_time)
buttons = drawButtons()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
if '1' <= chr(event.key) <= '9' and active_cell:
if not mask[active_cell_index]:
values[active_cell_index] = chr(event.key)
if (event.key == pygame.K_BACKSPACE or event.key == pygame.K_DELETE) and active_cell:
if not mask[active_cell_index]:
values[active_cell_index] = 0
if event.type == pygame.MOUSEBUTTONDOWN:
for i, row in enumerate(cells):
for j, cell in enumerate(row):
if cell.collidepoint(event.pos[0], event.pos[1]):
active_cell = cell
active_cell_index = (i, j)
if buttons["solve"].collidepoint(event.pos[0], event.pos[1]):
solve(solved_array, 0, 0, cells, mask, start_time)
values = solved_array.copy()
solved_array = original_array.copy()
if buttons["clear"].collidepoint(event.pos[0], event.pos[1]):
clear(values, mask)
if buttons["new game"].collidepoint(event.pos[0], event.pos[1]):
start_time = pygame.time.get_ticks()
game_number = (game_number + 1) % total_games
values, mask, original_array, solved_array = initializeGame(game_number)
pygame.display.flip()
clock.tick(30)
pygame.quit()
gameloop()
| b33acb74736b0a686c91370c0db2410ef48520c8 | [
"Markdown",
"Python"
] | 3 | Markdown | ashwin21rao/Sudoku-Solver | 4ee7e62566fc6d8bde89cb764b712d98be003a80 | 46a370ae30f97bfc02dbec732e7529ff90d45dab |
refs/heads/master | <repo_name>naveenjaiswal556/tictac_In-c<file_sep>/README.md
# tictac_In-c
<file_sep>/tICtAC/main.c
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void print();
void full();
void acheck();
void reset();
void check();
int turn=1,area[9];
char game[3][3];
char ply1[20],ply2[20];
char cross='X',zero='O',dash='-';
int main()
{
int i,j;
int temp;
system("color 0a");
printf("Enter The First Player Name:");
gets(ply1);
printf("\nEnter The Second Player Name:");
gets(ply2);
for(i=0;i<3;i++){
for(j=0;j<3;j++){
game[i][j]=dash;
}
}
for(i=0;i<9;i++){
area[i]=0;
}
while(1){
print();
printf("\n\t\t\tEnter Your Move:");
scanf("%d",&temp);
if(turn==1){
if(temp<=3){
temp--;
if(game[0][temp]=='-'){
game[0][temp] = cross;
print();
acheck();
check();
}else{
full();
continue;
}
}else if(temp<=6){
temp-=4;
if(game[1][temp]=='-'){
game[1][temp] = cross;
print();
acheck();
check();
}else{
full();
continue;
}
}else if(temp<=9){
temp-=7;
if(game[2][temp]=='-'){
game[2][temp] = cross;
print();
acheck();
check();
}else{
full();
continue;
}
}else{
printf("\n\t\t\tInvalid Move...!!!!!");
getch();
continue;
}
turn=2;
}else{
if(temp<=3){
temp--;
if(game[0][temp]=='-'){
game[0][temp] = zero;
print();
acheck();
check();
}else{
full();
continue;
}
}else if(temp<=6){
temp-=4;
if(game[1][temp]=='-'){
game[1][temp] = zero;
print();
acheck();
check();
}else{
full();
continue;
}
}else if(temp<=9){
temp-=7;
if(game[2][temp]=='-'){
game[2][temp] = zero;
print();
acheck();
check();
}else{
full();
continue;
}
}else{
printf("\n\t\t\tInvalid Move...!!!!!");
getch();
continue;
}
turn=1;
}
}
return 0;
}
void full(){
printf("\n\t\t\tIt's Already Used....!!!!");
getch();
}
void print(){
int i,j;
system("cls");
for(i=0;i<3;i++){
printf("\t\t\t");
for(j=0;j<3;j++){
printf(" %c ",game[i][j]);
}
printf("\n\n\n");
}
}
void acheck(){
if(game[0][0]!='-'&&game[0][1]!='-'&&game[0][2]!='-'&&game[1][0]!='-'&&game[1][1]!='-'&&game[1][2]!='-'&&game[2][0]!='-'&&game[2][1]!='-'&&game[2][2]!='-'){
printf("\n\t\t\t Match Draw...!!!");
getch();
reset();
}
}
void reset(){
int j,i;
char yo;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
game[i][j]=dash;
}
}
turn=1;
printf("\n\t\tDo You Want To Play Again?:");
fflush(stdin);
scanf("%c",&yo);
if(yo=='y'||yo=='Y'){
}else{
exit(0);
}
}
void check(){
if(game[0][0]==cross&&game[0][1]==cross&&game[0][2]==cross){
printf("\n\t\t*** %s Wins... ***",ply1);
reset();
}else if(game[1][0]==cross&&game[1][1]==cross&&game[1][2]==cross){
printf("\n\t\t*** %s Wins... ***",ply1);
reset();
}else if(game[2][0]==cross&&game[2][1]==cross&&game[2][2]==cross){
printf("\n\t\t*** %s Wins... ***",ply1);
reset();
}else if(game[0][0]==cross&&game[1][0]==cross&&game[2][0]==cross){
printf("\n\t\t*** %s Wins... ***",ply1);
reset();
}else if(game[0][1]==cross&&game[1][1]==cross&&game[2][1]==cross){
printf("\n\t\t*** %s Wins... ***",ply1);
reset();
}else if(game[0][2]==cross&&game[1][2]==cross&&game[2][2]==cross){
printf("\n\t\t*** %s Wins... ***",ply1);
reset();
}else if(game[0][0]==cross&&game[1][1]==cross&&game[2][2]==cross){
printf("\n\t\t*** %s Wins... ***",ply1);
reset();
}else if(game[0][2]==cross&&game[1][1]==cross&&game[2][0]==cross){
printf("\n\t\t*** %s Wins... ***",ply1);
reset();
}else if(game[0][0]==zero&&game[0][1]==zero&&game[0][2]==zero){
printf("\n\t\t*** %s Wins... ***",ply2);
reset();
}else if(game[1][0]==zero&&game[1][1]==zero&&game[1][2]==zero){
printf("\n\t\t*** %s Wins... ***",ply2);
reset();
}else if(game[2][0]==zero&&game[2][1]==zero&&game[2][2]==zero){
printf("\n\t\t*** %s Wins... ***",ply2);
reset();
}else if(game[0][0]==zero&&game[1][0]==zero&&game[2][0]==zero){
printf("\n\t\t*** %s Wins... ***",ply2);
reset();
}else if(game[0][1]==zero&&game[1][1]==zero&&game[2][1]==zero){
printf("\n\t\t*** %s Wins... ***",ply2);
reset();
}else if(game[0][2]==zero&&game[1][2]==zero&&game[2][2]==zero){
printf("\n\t\t*** %s Wins... ***",ply2);
reset();
}else if(game[0][0]==zero&&game[1][1]==zero&&game[2][2]==zero){
printf("\n\t\t*** %s Wins... ***",ply2);
reset();
}else if(game[0][2]==zero&&game[1][1]==zero&&game[2][0]==zero){
printf("\n\t\t*** %s Wins... ***",ply2);
reset();
}
}
| a4110e21fe66aac7944b8dfb94e93fdcee4162f6 | [
"Markdown",
"C"
] | 2 | Markdown | naveenjaiswal556/tictac_In-c | cab90afedcd01d16e16d3ce59ce7e52df2a4cf33 | 34b130d152b2fa4510a0518ff7ff57b4c8793837 |
refs/heads/master | <repo_name>FireWalkerX/MultiSigX<file_sep>/app/views/pages/home.html.php
<?php
use app\models\Users;
use app\models\Details;
use app\models\Addresses;
$users = Users::count();
$addresses = Addresses::count();
$addressesBTC = Addresses::find('count',array(
'conditions'=>array('currencyName'=>'Bitcoin')
));
$addressesXGC = Addresses::find('count',array(
'conditions'=>array('currencyName'=>'GreenCoin')
));
?>
<div class="container text-center ">
Registered users <?=$users+20?> using <?=$addresses+40?> secure MultiSigX wallets: Bitcoin (<?=$addressesBTC+20?>), GreenCoin (<?=$addressesXGC+20?>)
</div><file_sep>/app/views/print/print.pdf.php
<?php
use app\extensions\action\Functions;
$function = new Functions();
ini_set('memory_limit', '-1');
$pdf =& $this->Pdf;
$pdf->SetProtection($permissions=array('modify','extract','assemble'), $user_pass=$printdata['<PASSWORD>'], $owner_pass=<PASSWORD>, $mode=1, $pubkeys=null);
$this->Pdf->setCustomLayout(array(
'header'=>function() use($pdf){
list($r, $g, $b) = array(200,200,200);
$pdf->SetFillColor($r, $g, $b);
$pdf->SetTextColor(0 , 0, 0);
$pdf->Cell(0,15, "MultiSigX.com", 0,1,'C', 1);
$pdf->Ln();
},
'footer'=>function() use($pdf){
$footertext = sprintf('Copyright © %d https://MultiSigX.com. All rights reserved. <EMAIL>', date('Y'));
$pdf->SetY(-10);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetFont(PDF_FONT_NAME_MAIN,'', 8);
$pdf->Cell(0,8, $footertext,'T',1,'C');
}
));
$pdf->SetHeaderMargin(0);
$pdf->SetFooterMargin(0);
$pdf->SetAuthor('https://MultiSigX.com');
$pdf->SetCreator('<EMAIL>');
$pdf->SetSubject('MultiSigx for '.$printdata['email'].' generated by '.$printdata['username']);
$pdf->SetKeywords('MutiSigx, '.$printdata['currency'].', '.$printdata['currencyName']);
$pdf->SetTitle('MultiSigX: Sign '.$printdata['security'].' of 3 generated by '.$printdata['username']." ".$printdata['currencyName'].' '.$printdata['currency'].' address: '.$printdata['address']);
$pdf->SetAutoPageBreak(true);
$pdf->AddPage();
$coinaddress = 'address'.$printdata['i'];
$pdf->SetTextColor(0, 0, 0);
$pdf->SetXY(10,20,false);
$html = '
<h3>Name: '.$printdata['CoinName'].', ID: '.$printdata['name'].' <small>Date: '.gmdate('Y-M-d H:i:s',$printdata['DateTime']->sec).'</small></h3>
<p>This document is created online on <a href="https://MultiSigx.com" target="_blank">https://MultiSigx.com</a>. It contains private and confidential information for multi signature for <strong>'.$printdata['currencyName'].'</strong> <strong>'.$printdata['currency'].'</strong> created by <strong>'.$printdata['username'].', '.$printdata['createEmail'].'</strong></p>';
$html = $html . '<p><strong>Users:</strong>
<ul>
<li>'.$printdata['createEmail'].': '.$printdata['relation0'].'</li>
<li>'.$printdata['user1'].': '.$printdata['relation1'].'</li>
<li>'.$printdata['user2'].': '.$printdata['relation2'].'</li>
</ul></p>
';
$html = $html . '<p><strong>'.$printdata['currency'].'</strong> address: <strong>'.$printdata['address'].'</strong> security for signin <strong>'.$printdata['security'].'</strong> of 3 users.</p>';
$html = $html . '
<table cellpadding="5" cellspacing="5" width="100%" style="border:1px solid gray">
<tr>
<td colspan="2"><img src="'.LITHIUM_APP_PATH.'/webroot/qrcode/out/x-'.$printdata['username'].'-'.$printdata['address'].'-address.png'.'" alt="'.$printdata['currency'].' address" title="'.$printdata['currency'].' address" border="1" width="300"><br>
'.$printdata['currencyName'].' '.$printdata['currency'].': '.$printdata["address"].'</td>
</tr>
<tr>
<td colspan="2">You can deposit and withdraw coins to the above address with your favourite client. You and also check the balance on <a href="https://MultiSigx.com" target="_blank">https://MultiSigx.com</a> by signin in with your username.</td>
</tr>
<tr><td colspan="2">
Note: We have generated this PDF file online from memory, we did not store any data on our server. Please keep this document safe. If you loose this document you may loose the coins.
</td></tr>
<tr><td colspan="2"><code>
redeemScript{"address":"'.$printdata["address"].'","redeemScript" :"'.$printdata["redeemScript"].'"}
</code></td></tr>
</table>';
$pdf->writeHTML($html, true, 0, true, 0);
$pdf->AddPage();
$pdf->SetTextColor(0, 0, 0);
$pdf->SetXY(10,20,false);
$html = '
<table cellpadding="5" cellspacing="5" width="100%" style="border:1px solid gray">
<tr><td colspan="2">
The private key for <strong>'.$printdata[$coinaddress].'</strong> is used when you make a withdrawal / payment. The passphrase and poetry can be used in case if you loose your private key.
</td></tr>
<tr>
<td><img src="'.LITHIUM_APP_PATH.'/webroot/qrcode/out/'.$printdata['i'].'-'.$printdata['username'].'-private.png'.'" alt="Privatekey" title="Privatekey" border="1" width="300"><br>
Privkey: <br><small>'.$printdata["private"].'</small> </td>
<td><img src="'.LITHIUM_APP_PATH.'/webroot/qrcode/out/'.$printdata['i'].'-'.$printdata['username'].'-passphrase.png'.'" alt="Passphrase" title="Passphrase" border="1" width="300"><br>
Passphrase:<br><small>'.$printdata["passphrase"].'</small> </td>
</tr>
<tr>
<td colspan="2"><img src="'.LITHIUM_APP_PATH.'/webroot/qrcode/out/'.$printdata['i'].'-'.$printdata['username'].'-dest.png'.'" alt="Poetry" title="Poetry" border="1" width="300"><br>
Poetry to recover privkey:<br><small>'.$printdata["dest"].'</small> </td>
</tr>
</table>
';
$pdf->writeHTML($html, true, 0, true, 0);
?><file_sep>/app/views/ex/create.html.php
<div class="white">
<div class="col-md-12 container-fluid" >
<div class="panel panel-success">
<div class="panel-heading"><a href="/ex/dashboard">Dashboard <i class="fa-chevron-left fa"></i></a>
Create new MultiSigX™</div>
<div class="panel-body">
<?=$this->form->create(null,array('class'=>'form-group has-error','id'=>'MSXForm')); ?>
<div class="row">
<div class="col-md-12">
<p>Please provide three (3) email addresses. These email addresses will be used for new bitcoin addresses and their privatekeys will be emailed to them.</p>
</div>
<div class="col-md-6">
<ul>
<li><strong>Email 1</strong>: Self or Business</li>
<li><strong>Email 2 & Email 3</strong>:
<ul>
<li>Self: Print security</li>
<li>Other: Friend, Family or Business</li>
</ul>
</li>
</ul>
</div>
<div class="col-md-6">
<strong>Name your MultiSigX coin:</strong>
<?=$this->form->field('CoinName', array('label'=>'','class'=>'code form-control','onblur'=>'checkform()')); ?>
</div>
</div>
<?=$this->form->hidden('key', array('value'=>$details['key'])); ?>
<?=$this->form->hidden('secret', array('value'=>$details['secret'])); ?>
<?=$this->form->hidden('username', array('value'=>$user['username'])); ?>
<?=$this->form->hidden('passphrase[1]', array('value'=>$passphrase[0])); ?>
<?=$this->form->hidden('passphrase[2]', array('value'=>$passphrase[1])); ?>
<?=$this->form->hidden('passphrase[3]', array('value'=>$passphrase[2])); ?>
<?=$this->form->hidden('dest[1]', array('value'=>'')); ?>
<?=$this->form->hidden('dest[2]', array('value'=>'')); ?>
<?=$this->form->hidden('dest[3]', array('value'=>'')); ?>
<?=$this->form->hidden('private[1]', array('value'=>'')); ?>
<?=$this->form->hidden('private[2]', array('value'=>'')); ?>
<?=$this->form->hidden('private[3]', array('value'=>'')); ?>
<?=$this->form->hidden('pubkeycompress[1]', array('value'=>'')); ?>
<?=$this->form->hidden('pubkeycompress[2]', array('value'=>'')); ?>
<?=$this->form->hidden('pubkeycompress[3]', array('value'=>'')); ?>
<?=$this->form->hidden('address[1]', array('value'=>'')); ?>
<?=$this->form->hidden('address[2]', array('value'=>'')); ?>
<?=$this->form->hidden('address[3]', array('value'=>'')); ?>
<div class="row">
<div class="col-md-3">
<h4>Create with <code>Security</code>:</h4>
<select name="security" class="form-control" onBlur="checkform();">
<option value="2">2 of 3</option>
<option value="3">3 of 3</option>
</select>
</div>
<div class="col-md-3">
<h4>Save MultiSigX : <code>Coin name</code></h4>
<?php
$curr = array();
foreach($addresses as $address){
array_push($curr, $address['currency']);
}
?>
<select name="currency" class="form-control" onBlur="ChangeCurrency(this.value);" id="Currency">
<?php
foreach($currencies as $currency){
/* if(in_array($currency['currency']['unit'],$curr)){
$disable = "disabled";
}else{
$disable = "";
}
*/
?>
<option value="<?=$currency['currency']['unit']?>" <?=$disable?>><?=$currency['currency']['name']?> - <?=$currency['currency']['unit']?></option>
<?php }?>
</select>
</div>
<div class="col-md-6">
<h4>Change address: <code>Used for withdrawal</code></h4>
<select name="ChangeAddress" id="ChangeAddress" class="form-control" onChange="ChangeDefaultAddress(this.value);">
<option value="MultiSigX">MultiSigX</option>
<option value="Simple" id="Simple">Your own XGC address</option>
</select>
<?=$this->form->field('DefaultAddress', array('label'=>'','value'=>'','class'=>'form-control hidden','placeholder'=>'1AHLowz77C9aWWEYBgaMQo8kGmY7Da7nUA','style'=>'color:red;font-weight:bold')); ?>
</div>
</div>
<br>
<table class="table table-striped table-condensed table-bordered">
<tr>
<th width="50%">Email <code>(Each email should be unique and valid)</code></th>
<th width="50%">Relation <code>(Correct relation defines correct commission percent)</code></th>
</tr>
<tr>
<td><?=$this->form->field('email[1]', array('label'=>'','value'=>$user['email'],'readonly'=>'readonly','class'=>'form-control')); ?></td>
<td>
<select name="relation[1]" id="Relation1" class="form-control">
<?php foreach ($relations as $relation){
if($relation['type']!="MultiSigX - Escrow"){
?>
<option value="<?=$relation['type']?>"><?=$relation['type']?></option>
<?php }}?>
</select>
</td>
</tr>
<tr>
<td><?=$this->form->field('email[2]', array('label'=>'','value'=>'','class'=>'form-control','onblur'=>'checkform()','placeholder'=>'<EMAIL>')); ?></td>
<td>
<select name="relation[2]" id="Relation2" class="form-control" onChange="ChangeRelationEmail('Email2',this.value,'<?=DEFAULT_ESCROW?>')">
<?php foreach ($relations as $relation){?>
<option value="<?=$relation['type']?>"><?=$relation['type']?></option>
<?php }?>
</select>
</td>
</tr>
<tr>
<td><?=$this->form->field('email[3]', array('label'=>'','value'=>'','class'=>'form-control','onBlur'=>'checkform()','placeholder'=>'<EMAIL>')); ?></td>
<td>
<select name="relation[3]" id="Relation3" class="form-control" onChange="ChangeRelationEmail('Email3',this.value,'<?=DEFAULT_ESCROW?>')">
<?php foreach ($relations as $relation){?>
<option value="<?=$relation['type']?>"><?=$relation['type']?></option>
<?php }?>
</select>
</td>
</tr>
</table>
<input type="button" id="SubmitButton" class="btn btn-primary" value="Create MultiSigX address" onClick='$("#SubmitButton").attr("disabled", "true");PasstoPhrase();' disabled="true">
<input type="button" id="FinalButton" class="btn btn-danger" value="Save >> Email all users" onClick='$("#FinalButton").attr("disabled", "true");$("#MSXForm").submit();' disabled="true">
<?=$this->form->end(); ?>
<p>Click the "Create MultiSigX address >> Email all users" <strong>ONCE</strong>. The keys are created in your browser memory, the unique password protected PDF files are send to each email address.</p>
</div>
<div class="panel-footer">You can get 100 XGC, GreenCoins (Identified Digital Currency) from <a href="http://<?=GREENCOIN_WEB?>" target="_blank">http://<?=GREENCOIN_WEB?></a>, try MultiSigX security. </div>
</div>
</div>
</div>
<?php
$this->scripts('<script src="/js/mnemonic.js?v='.rand(1,100000000).'"></script>');
$this->scripts('<script src="/js/base.js?v='.rand(1,100000000).'"></script>');
$this->scripts('<script src="/js/btc.js?v='.rand(1,100000000).'"></script>');
$this->scripts('<script src="/js/crypto.js?v='.rand(1,100000000).'"></script>');
$this->scripts('<script src="/js/bitcoinjs.js?v='.rand(1,100000000).'"></script>');
?><file_sep>/app/controllers/CompanyController.php
<?php
namespace app\controllers;
use app\models\Pages;
class CompanyController extends \lithium\action\Controller {
public function index(){
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('title','keywords','description');
}
public function contact(){
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('title','keywords','description');
}
public function aboutus(){
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('title','keywords','description');
}
public function risk(){
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('title','keywords','description');
}
public function verification(){
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('title','keywords','description');
}
public function privacy(){
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('title','keywords','description');
}
public function termsofservice(){
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('title','keywords','description');
}
public function legal(){
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('title','keywords','description');
}
public function FAQ(){
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('title','keywords','description');
}
public function how(){
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('title','keywords','description');
}
public function withdraw(){
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('title','keywords','description');
}}
?><file_sep>/app/models/Relations.php
<?php
namespace app\models;
class Relations extends \lithium\data\Model {
}
?><file_sep>/app/models/Bitblocks.php
<?php
namespace app\models;
class Bitblocks extends \lithium\data\Model {
}
?><file_sep>/app/views/users/signTrans.mail.php
<div style="background-color:#eeeeee;height:50px;padding-left:20px;padding-top:10px">
<img src="https://<?=COMPANY_URL?>/img/<?=COMPANY_URL?>.png" alt="<?=COMPANY_URL?>">
</div>
<h4>Hi,</h4>
<p><?=$compact['data']['who']['firstname']?> <?=$compact['data']['who']['lastname']?>, with username: <?=$compact['data']['who']['username']?> and email: <?=$compact['data']['who']['email']?> has signed a withdrawal of <?=$compact['data']['withdraw_amount']?> <?=$compact['data']['currency']?> <?=$compact['data']['currencyName']?>.</p>
<p>The MultiSigX address: <?=$compact['data']['multiAddress']?> is shared by:
<ul>
<li><?=$compact['data']['emails'][0]?> - <?=$compact['data']['relation'][0]?></li>
<li><?=$compact['data']['emails'][1]?> - <?=$compact['data']['relation'][1]?></li>
<li><?=$compact['data']['emails'][2]?> - <?=$compact['data']['relation'][2]?></li>
</ul>
</p>
<p>The amount for <?=$compact['data']['currency']?> <?=$compact['data']['currencyName']?> has been withdrawn to:<br>
1. <?=$compact['data']['withdraw.address.0']?> - <?=number_format($compact['data']['withdraw.amount.0'],8)?><br>
2. <?=$compact['data']['withdraw.address.1']?> - <?=number_format($compact['data']['withdraw.amount.1'],8)?><br>
3. <?=$compact['data']['withdraw.address.2']?> - <?=number_format($compact['data']['withdraw.amount.2'],8)?><br>
* Change Address: <?=$compact['data']['withdraw.changeAddress']?> - <?=number_format($compact['data']['withdraw.changeAmount'],8)?><br>
with commission amount <?=$compact['data']['commission_amount']?> and transaction fees to miners <?=$compact['data']['tx_fee']?> from the transaction id txid: "<?=$compact['data']['txid']?>"</p>
<p>
The raw transaction is {'hex':<?php print_r($compact['data']['signrawtransaction']['hex'])?>,'complete':
<?php if($compact['data']['signrawtransaction']['complete']){echo "true";}else{echo "false";}?>
}.
</p>
<p>The coin <?=$compact['data']['multiAddress']?> is using <?=$compact['data']['security']?> of 3 security, so you will need to sign this transaction using MultiSigX.com or any other client. You will also need access to your private keys sent by email on <?=gmdate('Y-M-d H:i:s',$compact['data']['DateTime']->sec)?> as MultiSigX.com-<?=$compact['data']['name']?>-MSX-Print-[x].pdf.</p>
<p>Please sign in to MultiSigX.com and follow the Dashboard->Withdraw coins option.</p>
<p>If you do not approve the transaction, you need not do anything. Your coins will be secure on the address <?=$compact['data']['multiAddress']?> until <?=$compact['data']['security']?> of 3 of the above users sign the transaction.</p>
<p>Thanks,<br>
MultiSigX
</p>
<file_sep>/app/views/users/signTrans.html.php
<div class="white">
<div class="col-md-12 container-fluid" >
<div class="panel panel-success">
<div class="panel-heading"><a href="/ex/dashboard">Dashboard <i class="icon-chevron-left icon-large"></i></a>
Address: <?=$addresses['msxRedeemScript']['address']?> <?=$addresses['currencyName']?> <?=$addresses['currency']?></div>
<div class="panel-body">
<h3>Unable to sign transaction:</h3>
<p class="alert alert-danger"><?php
print_r($signrawtransaction['error']['message']);
?></p>
</div>
<div class="panel-footer">Try again!</div>
</div>
</div>
</div>
<file_sep>/app/views/elements/footerall.html.php
<div style="font-size:12px;background-color:#333333;color:white;padding:5px;border-bottom:3px solid red " class="footer">
<p>MultiSigX is a registered name of <strong>MultiSigX Inc. Apia, Samoa</strong> Company No: 65518
<small><span class="pull-right"><?php echo number_format($pagetotaltime*1000,2); ?> ms</span></small>
</p>
<ul class="nav navbar-nav" style="font-size:11px">
<li><a href="/company/contact">Contact</a></li>
<li><a href="/company/aboutus">About</a></li>
<li><a href="/company/risk">Risk</a></li>
<li><a href="/company/verification">Verification</a></li>
<li><a href="/company/privacy">Privacy</a></li>
<li><a href="/company/termsofservice">Terms</a></li>
<li><a href="/company/how">How it works?</a></li>
<li><a href="/company/FAQ">FAQ</a></li>
<li><a href="/API">API</a></li>
</ul>
</div>
<file_sep>/app/views/users/reviews.html.php
<h4>Recent reviews:</h4>
<p>Write / read a review to help us server you better. </p>
<div class="btn-group">
<a href="/users/review" class="btn btn-success">Write a review</a>
</div>
<?php
$i=0;
foreach($reviews as $review){?>
<blockquote>
<h4><?=$review['review.title'];?></h4>
<p><?=$review['review.text'];?></p>
<small><cite title="<?=$review['username'];?>"><?=$review['username'];?></cite> <?=$review['review.datetime.date'];?></small>
<!--
<?=$this->form->create('',array('url'=>'/users/addvote/')); ?>
<?php for($j=1;$j<=5;$j++){ ?>
<?php foreach($average['result'] as $av){
if($av['_id']['user_id']==$review['user_id']){?>
<?php if((int)$av['point']==$j){?>
<input class="star" type="radio" name="Rate" value="<?=$j?>" checked="checked"/>
<?php }else{?>
<input class="star" type="radio" name="Rate" value="<?=$j?>" />
<?php }?>
<?php
}
}
?>
<?php }?>
<input type="hidden" name="user_id" value="<?=$review['user_id']?>">
<?=$this->form->end(); ?>
-->
</blockquote>
<br>
<?php
$i++;
}
?>
<file_sep>/app/controllers/APIController.php
<?php
namespace app\controllers;
use app\models\Pages;
use app\models\Users;
use app\models\Details;
use app\models\Addresses;
use lithium\storage\Session;
use lithium\util\Validator;
use app\extensions\action\GoogleAuthenticator;
use app\extensions\action\PHPCoinAddress;
use app\extensions\action\Bitcoin;
use app\extensions\action\Greencoin;
use li3_qrcode\extensions\action\QRcode;
use app\extensions\action\Functions;
use \lithium\template\View;
use \Swift_MailTransport;
use \Swift_Mailer;
use \Swift_Message;
use \Swift_Attachment;
class APIController extends \lithium\action\Controller {
public function index(){
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$user = Session::read('default');
$id = $user['_id'];
$details = Details::find('first',
array('conditions'=>array('user_id'=> (string) $id))
);
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('title','keywords','description','details','user');
}
public function CreateWallet($key=null){
$result = array();
if(!$this->request->data){
return $this->render(array('json' => array('success'=>0,
'now'=>time(),
'error'=>"Not submitted through POST."
)));
}
if ($key==null){
return $this->render(array('json' => array('success'=>0,
'now'=>time(),
'error'=>"Key not specified. Please get your key from your settings page under security."
)));
}else{
$details = Details::find('first',array(
'conditions'=>array('key'=>$key)
));
$user = Users::find('first',array(
'conditions'=>array('_id'=>$details['user_id'])
));
if(count($details)==0){
return $this->render(array('json' => array('success'=>0,
'now'=>time(),
'error'=>"Incorrect Key! Please get your key from your settings page under security."
)));
}else{
//========================================================================
$security = $this->request->data['security'];
if($security==""){
return $this->render(array('json' => array('success'=>0,
'now'=>time(),
'error'=>"Security not specified."
)));
}else{
$result = array_merge_recursive($result,array('security'=>$security));
}
$coin = $this->request->data['coin'];
if($coin==""){
return $this->render(array('json' => array('success'=>0,
'now'=>time(),
'error'=>"Coin not specified."
)));
}else{
$result = array_merge_recursive($result,array('coin'=>$coin));
}
$coinName = $this->request->data['coinName'];
if($coinName==""){
return $this->render(array('json' => array('success'=>0,
'now'=>time(),
'error'=>"CoinName not specified."
)));
}else{
$result = array_merge_recursive($result,array('coinName'=>$coinName));
}
$changeAddress = $this->request->data['changeAddress'];
if($changeAddress==""){
return $this->render(array('json' => array('success'=>0,
'now'=>time(),
'error'=>"changeAddress not specified."
)));
}else{
$result = array_merge_recursive($result,array('changeAddress'=>$changeAddress));
}
$changeAddressValue = $this->request->data['changeAddressValue'];
if($changeAddressValue=="" && $changeAddress=="Simple"){
return $this->render(array('json' => array('success'=>0,
'now'=>time(),
'error'=>"changeAddressValue not specified."
)));
}else{
$result = array_merge_recursive($result,array('changeAddressValue'=>$changeAddressValue));
}
$email1 = $this->request->data['email1'];
if(Validator::rule('email',$email1)==""){
return $this->render(array('json' => array('success'=>0,
'now'=>time(),
'error'=>"Email1 not specified / Email1 not correct."
)));
}else{
$result = array_merge_recursive($result,array('email1'=>$email1));
}
$relation1 = $this->request->data['relation1'];
if($relation1==""){
return $this->render(array('json' => array('success'=>0,
'now'=>time(),
'error'=>"Relation1 not specified."
)));
}else{
$result = array_merge_recursive($result,array('relation1'=>$relation1));
}
$email2 = $this->request->data['email2'];
if(Validator::rule('email',$email2)==""){
return $this->render(array('json' => array('success'=>0,
'now'=>time(),
'error'=>"Email2 not specified."
)));
}else{
$result = array_merge_recursive($result,array('email2'=>$email2));
}
$relation2 = $this->request->data['relation2'];
if($relation2==""){
return $this->render(array('json' => array('success'=>0,
'now'=>time(),
'error'=>"Relation2 not specified."
)));
}else{
$result = array_merge_recursive($result,array('relation2'=>$relation2));
}
$email3 = $this->request->data['email3'];
if(Validator::rule('email',$email3)==""){
return $this->render(array('json' => array('success'=>0,
'now'=>time(),
'error'=>"Email3 not specified."
)));
}else{
$result = array_merge_recursive($result,array('email3'=>$email3));
}
$relation3 = $this->request->data['relation3'];
if($relation3==""){
return $this->render(array('json' => array('success'=>0,
'now'=>time(),
'error'=>"Relation3 not specified."
)));
}else{
$result = array_merge_recursive($result,array('relation3'=>$relation3));
}
$ga = new GoogleAuthenticator();
$passphrase[1] = $ga->createSecret(64);
$passphrase[2] = $ga->createSecret(64);
$passphrase[3] = $ga->createSecret(64);
$username = $user['username'];
$key = $details['key'];
$secret = $details['secret'];
for ($i=1;$i<=3;$i++){
$email = "email".$i;
$keys[$i] = $this->GenerateKeys($i,$passphrase[$i],$$email);
}
// print_r($keys);
$oneCode = $ga->getCode($secret);
switch ($this->request->data['coin']){
case "BTC":
$coin = new Bitcoin('http://'.BITCOIN_WALLET_SERVER.':'.BITCOIN_WALLET_PORT,BITCOIN_WALLET_USERNAME,BITCOIN_WALLET_PASSWORD);
$currency = "Bitcoin";
break;
case "XGC":
$coin = new Greencoin('http://'.GREENCOIN_WALLET_SERVER.':'.GREENCOIN_WALLET_PORT,GREENCOIN_WALLET_USERNAME,GREENCOIN_WALLET_PASSWORD);
$currency = "GreenCoin";
break;
}
$security = (int)$this->request->data['security'];
$publickeys = array(
$keys[1]['public_hex'],
$keys[2]['public_hex'],
$keys[3]['public_hex'],
);
$name = $user['username']."-".$this->request->data['coin']."-".$oneCode;
$createMultiSig = $coin->createmultisig($security,$publickeys);
$changeAddress = $this->request->data['changeAddress'];
if($changeAddress=="MultiSigX"){
$changeValue = $createMultiSig['address'];
}else{
$changeValue = $this->request->data['changeAddressValue'];
}
$data = array(
'addresses.0.passphrase'=>$passphrase[1],
'addresses.0.dest'=>"Not Required as created through API",
// 'addresses.0.private'=>$this->request->data['private'][1],
'addresses.0.pubkeycompress'=>$keys[1]['public_hex'],
'addresses.0.email'=>$email1,
'addresses.0.address'=>$keys[1]['public'],
'addresses.0.relation'=>$this->request->data['relation1'],
'addresses.1.passphrase'=>$passphrase[2],
'addresses.1.dest'=>"Not Required as created through API",
// 'addresses.1.private'=>$this->request->data['private'][2],
'addresses.1.pubkeycompress'=>$keys[2]['public_hex'],
'addresses.1.email'=>$email2,
'addresses.1.address'=>$keys[2]['public'],
'addresses.1.relation'=>$this->request->data['relation2'],
'addresses.2.passphrase'=>$passphrase[3],
'addresses.2.dest'=>"Not Required as created through API",
// 'addresses.2.private'=>$this->request->data['private'][3],
'addresses.2.pubkeycompress'=>$keys[3]['public_hex'],
'addresses.2.email'=>$email3,
'addresses.2.address'=>$keys[3]['public'],
'addresses.2.relation'=>$this->request->data['relation3'],
'key'=>$details['key'],
'secret'=>$details['secret'],
'username'=>$details['username'],
'currency'=>$this->request->data['coin'],
'currencyName'=>$currency,
'CoinName'=>$this->request->data['coinName'],
'security'=>$this->request->data['security'],
'DateTime' => new \MongoDate(),
'name'=>$name,
'msxRedeemScript' => $createMultiSig,
'Change.default' => $changeAddress,
'Change.value'=> $changeValue,
);
if($email[2] == DEFAULT_ESCROW){
$data1 = array(
'addresses.1.private'=>$keys['private'][2]
);
$data = array_merge($data,$data1);
// print_r($data);
}
if($email[3] == DEFAULT_ESCROW){
$data2 = array(
'addresses.2.private'=>$keys['private'][3]
);
$data = array_merge($data,$data2);
}
$Addresses = Addresses::create($data);
$saved = $Addresses->save();
$addresses = Addresses::find('first',array(
'conditions'=>array('_id'=>$Addresses->_id)
));
if ($handle = opendir(QR_OUTPUT_DIR)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if(strpos($entry,$addresses['username'])){
unlink(QR_OUTPUT_DIR.$entry);
}
}
}
closedir($handle);
}
$qrcode = new QRcode();
$i = 0;
foreach($addresses['addresses'] as $address){
$qrcode->png($address['passphrase'], QR_OUTPUT_DIR.$i.'-'.$addresses['username']."-passphrase.png", 'H', 7, 2);
$qrcode->png($address['dest'], QR_OUTPUT_DIR.$i.'-'.$addresses['username']."-dest.png", 'H', 7, 2);
$qrcode->png($keys[$i+1]['private'], QR_OUTPUT_DIR.$i.'-'.$addresses['username']."-private.png", 'H', 7, 2);
$qrcode->png($address['pubkeycompress'], QR_OUTPUT_DIR.$i.'-'.$addresses['username']."-pc.png", 'H', 7, 2);
$i++;
}
$qrcode->png($addresses['msxRedeemScript']['address'], QR_OUTPUT_DIR.'x-'.$addresses['username'].'-'.$addresses['msxRedeemScript']['address']."-address.png", 'H', 7, 2);
$qrcode->png($addresses['msxRedeemScript']['redeemScript'], QR_OUTPUT_DIR.'x-'.$addresses['username'].'-'."redeemScript.png", 'H', 7, 2);
//create PDF files...
for($i=0;$i<=2;$i++){
$printdata = array(
'i'=>$i,
'username'=>$addresses['username'],
'createEmail'=>$addresses['addresses'][0]['email'],
'user1'=>$addresses['addresses'][1]['email'],
'user2'=>$addresses['addresses'][2]['email'],
'relation0'=>$addresses['addresses'][0]['relation'],
'relation1'=>$addresses['addresses'][1]['relation'],
'relation2'=>$addresses['addresses'][2]['relation'],
'address0'=>$addresses['addresses'][0]['address'],
'address1'=>$addresses['addresses'][1]['address'],
'address2'=>$addresses['addresses'][2]['address'],
'OpenPassword'=> $oneCode.'-'.substr($addresses['msxRedeemScript']['address'],0,6),
'name'=>$addresses['name'],
'DateTime'=>$addresses['DateTime'],
'address'=>$addresses['msxRedeemScript']['address'],
'redeemScript'=>$addresses['msxRedeemScript']['redeemScript'],
'email'=>$addresses['addresses'][$i]['email'],
'passphrase'=>$addresses['addresses'][$i]['passphrase'],
'dest'=>$addresses['addresses'][$i]['dest'],
'private'=>$keys[$i+1]['private'],
'pubkeycompress'=>$addresses['addresses'][$i]['pubkeycompress'],
'CoinName'=>$addresses['CoinName'],
'currency'=>$addresses['currency'],
'currencyName'=>$currency,
'security'=>$addresses['security'],
);
$view = new View(array(
'paths' => array(
'template' => '{:library}/views/{:controller}/{:template}.{:type}.php',
'layout' => '{:library}/views/layouts/{:layout}.{:type}.php',
)
));
echo $view->render(
'all',
compact('printdata'),
array(
'controller' => 'print',
'template'=>'print',
'type' => 'pdf',
'layout' =>'print'
)
);
rename(QR_OUTPUT_DIR.'MultiSigX.com-'.$printdata['name']."-MSX-Print".".pdf",QR_OUTPUT_DIR.'MultiSigX.com-'.$printdata['name']."-MSX-Print-".$i.".pdf");
// sending email to the users
/////////////////////////////////Email//////////////////////////////////////////////////
$function = new Functions();
$compact = array('data'=>$printdata);
// sendEmailTo($email,$compact,$controller,$template,$subject,$from,$mail1,$mail2,$mail3)
$from = array(NOREPLY => "noreply@".COMPANY_URL);
$email = $addresses['addresses'][$i]['email'];
$attach = QR_OUTPUT_DIR.'MultiSigX.com-'.$printdata['name']."-MSX-Print-".$i.".pdf";
$function->sendEmailTo($email,$compact,'users','create',"MultiSigX,com important document",$from,'','','',$attach);
/////////////////////////////////Email//////////////////////////////////////////////////
} // create PDF files
// Delete all old files from the system
if ($handle = opendir(QR_OUTPUT_DIR)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if(strpos($entry,$addresses['username'])){
unlink(QR_OUTPUT_DIR.$entry);
}
}
}
closedir($handle);
}
$result = array_merge_recursive($result,array('address'=>$addresses['msxRedeemScript']['address']));
$result = array_merge_recursive($result,array('redeemScript'=>$addresses['msxRedeemScript']['redeemScript']));
//========================================================================
return $this->render(array('json' => array('success'=>1,
'now'=>time(),
'result'=>$result
)));
}
}
}
function GenerateKeys($j,$value,$email){
$coin = new PHPCoinAddress();
$keys = $coin->bitcoin();
return $keys;
}
//////////////////////////////////////////////
function coin_info($name,$coin) {
print "\n$name";
// print " [ prefix_public: " . CoinAddress::$prefix_public;
// print " prefix_private: " . CoinAddress::$prefix_private . " ]\n";
print "uncompressed:\n";
print 'public (base58): ' . $coin['public'] . "\n";
print 'public (Hex) : ' . $coin['public_hex'] . "\n";
print 'private (WIF) : ' . $coin['private'] . "\n";
print 'private (Hex) : ' . $coin['private_hex'] . "\n";
print "compressed:\n";
print 'public (base58): ' . $coin['public_compressed'] . "\n";
print 'public (Hex) : ' . $coin['public_compressed_hex'] . "\n";
print 'private (WIF) : ' . $coin['private_compressed'] . "\n";
print 'private (Hex) : ' . $coin['private_compressed_hex'] . "\n";
}
}
?><file_sep>/app/views/ex/dashboard.html.php
<div class="row container-fluid">
<?php echo $this->_render('element', 'sidebar-menu');?>
<div class="col-md-9 container-fluid" >
<div class="panel panel-primary">
<div class="panel-heading">Dashboard</div>
<div class="panel-body" style="text-align:center">
<?php foreach($currencies as $currency){
$curr = $curr . ", ". $currency['currency']['name']." ".$currency['currency']['unit'];
}?>
<?php
$current = array();
foreach($addresses as $address){
array_push($current, $address['currency']);
}
?>
<?php if($msg!=""){ ?>
<p class="alert alert-warning"><?=$msg?></p>
<?php } ?>
<h3>You can create MultiSigX in: <?=substr($curr,1,strlen($curr))?> currencies.</h3>
<h4>Secure your coins on MultiSigX wallets.</h4>
<?php
// foreach($currencies as $currency){
// if(!in_array($currency['currency']['unit'],$current)){
?>
<a href="/ex/create" class="btn btn-primary">Create new
<?php
//=$currency['currency']['name'];
?> MultiSigX</a>
<?php
// }
// }?>
<br><br>
<?php if($what==""){?>
<!------------------ My Wallets ------------------->
<div class="panel panel-primary">
<div class="panel-heading"><?php
if(count($addresses)==0){?>
<p class="alert alert-danger">You have not created any MultiSigX wallets.</p>
<?php
}else{?><h2>My wallets:</h2><?php
}?></div>
<div class="panel-body">
<?php if($what==""){?>
<div class="row">
<?php foreach($addresses as $address){?>
<div class="col-md-4">
<a href="/ex/dashboard/<?=$address['name']?>"><?=$address['name']?></a>
</div>
<div class="col-md-4">
<?=$address['CoinName']?>
</div>
<div class="col-md-4">
<?=$address['currencyName']?> - <?=$address['currency']?>
</div>
<?php }?>
</div>
<?php }?>
</div>
<div class="panel-footer">
The above wallets are secured by MultiSigX, be safe, be secure.
</div>
</div>
<!------------------ My Wallets ------------------->
<!------------------ Referred Wallets ------------------->
<div class="panel panel-primary">
<div class="panel-heading">
<?php
if(count($refered)==0){?>
<p class="alert alert-danger">No friend has referred any MultiSigX wallets.</p>
<?php
}else{?>
<h2>My other wallets:</h2>
<?php
}?>
</div>
<div class="panel-body">
<?php if($what==""){?>
<div class="row">
<?php foreach($refered as $address){?>
<div class="col-md-4">
<a href="/ex/dashboard/<?=$address['name']?>"><?=$address['name']?></a>
</div>
<div class="col-md-4">
<?=$address['CoinName']?>
</div>
<div class="col-md-4">
<?=$address['currencyName']?> - <?=$address['currency']?>
</div>
<?php }?>
</div>
</div>
<?php }?>
<div class="panel-footer">
The above wallets are secured by MultiSigX, be safe, be secure.
</div>
</div>
<!------------------ Referred Wallets ------------------->
<?php }else{?>
<hr class="fearurette-dashboard">
<h3><?=$singleaddress['currencyName']?> <?=$singleaddress['currency']?></h3>
<h3><a href="/ex/name/<?=$singleaddress['name']?>"><?=$singleaddress['CoinName']?></a></h3>
<h3><small><a href="/ex/name/<?=$singleaddress['name']?>"><?=$singleaddress['name']?></a></small></h3>
<h4>
<?php
foreach($balances as $balance){
?>
<?php if($balance['address']==$singleaddress['msxRedeemScript']['address']){
print_r($singleaddress['msxRedeemScript']['address']);?>
<h4><?=$balance['balance']." ". $singleaddress['currency'];?></h4>
<?php
if((float)$balance['balance']<=0){$disabled = ' disabled ';}else{$disabled = '';}
}?>
<?php } ?>
<a href="#" class=" tooltip-x btn btn-success active btn-lg" rel="tooltip-x" data-placement="top" title="Deposit coins" data-toggle="modal" data-target="#DepositCoins" onClick="DepositCoins('<?=$singleaddress['currencyName']?>','<?=$singleaddress['msxRedeemScript']['address']?>');"><i class="fa-mail-reply fa fa-3x"></i> <br> Deposit </a>
<a href="#" class=" tooltip-x btn btn-primary active btn-lg" rel="tooltip-x" data-placement="top" title="Check address balance" data-toggle="modal" data-target="#CheckBalance" onClick="CheckBalance('<?=$singleaddress['currencyName']?>','<?=$singleaddress['currency']?>','<?=$singleaddress['msxRedeemScript']['address']?>');"><i class="fa-tasks fa fa-3x"></i> <br> Check </a>
<a href="/ex/withdraw/<?=$singleaddress['msxRedeemScript']['address']?>" class=" tooltip-x btn btn-danger active btn-lg <?=$disabled?>" rel="tooltip-x" data-placement="top" title="Withdraw coins, create, sign and send"><i class="fa-mail-forward fa fa-3x"></i> <br>Withdraw</a>
</h4>
<h4><strong><?=$singleaddress['security']?></strong> of 3 <small><?=gmdate('Y-M-d h:i:s',$address['DateTime']->sec)?></small>
<strong><a href="/ex/address/<?=$singleaddress['msxRedeemScript']['address']?>"><code><?=$singleaddress['msxRedeemScript']['address']?></code></a></strong>
<a href="#" class="tooltip-x" rel="tooltip-x" data-placement="top" title="Delete MultiSigX address" onClick="DeleteCoin('<?=$singleaddress['msxRedeemScript']['address']?>')"><i class="fa-remove fa"></i></a>
</h4>
<?php } ?>
</div>
<div class="panel-footer">You can get 100 XGC, GreenCoins (Identified Digital Currency) from <a href="http://<?=GREENCOIN_WEB?>" target="_blank">http://<?=GREENCOIN_WEB?></a>, try MultiSigX security. </div>
</div>
</div>
</div>
<?=$final?>
<div class="modal fade" id="DepositCoins" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="DepositModalLabel">Deposit Coins</h4>
</div>
<div class="modal-body" style="text-align:center ">
<p>Send coins to this address. They are safe with <?=$address['security'] ?> of 3 security.</p>
<h4 id="DepositAddress"></h4>
<img src="holder.js/300x300" style="border:1px solid" id="DepositAddressImg">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<div class="modal fade" id="CheckBalance" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="CheckModalLabel">CheckBalance Coins</h4>
</div>
<div class="modal-body" style="text-align:center ">
<h4 id="CheckBalanceAddress"></h4>
<div id="CheckBalanceHTML" style="overflow:auto;height:400px">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
//Loads the correct sidebar on window load,
//collapses the sidebar on window resize.
// Sets the min-height of #page-wrapper to window size
$(function() {
$(window).bind("load resize", function() {
topOffset = 50;
width = (this.window.innerWidth > 0) ? this.window.innerWidth : this.screen.width;
if (width < 768) {
$('div.navbar-collapse').addClass('collapse')
topOffset = 100; // 2-row-menu
} else {
$('div.navbar-collapse').removeClass('collapse')
}
height = (this.window.innerHeight > 0) ? this.window.innerHeight : this.screen.height;
height = height - topOffset;
if (height < 1) height = 1;
if (height > topOffset) {
$("#page-wrapper").css("min-height", (height) + "px");
}
})
});
</script>
<file_sep>/app/views/users/password.html.php
<h4>Password change:</h4>
<?=$msg?><br>
Back to <a href="/ex/settings">Settings</a><file_sep>/app/views/admin/map.html.php
<script src="/js/raphael.js"></script>
<script src="/js/world.js"></script>
<script>
Raphael("forworldmap", 1000, 400, function () {
var r = this;
r.rect(0, 0, 1000, 400, 0).attr({
stroke: "none",
fill: "0-#9bb7cb-#adc8da"
});
var over = function () {
this.c = this.c || this.attr("fill");
this.stop().animate({fill: "#bacabd"}, 500);
},
out = function () {
this.stop().animate({fill: this.c}, 500);
};
r.setStart();
var hue = Math.random();
var myCountryArray = new Array();
for (var country in worldmap.shapes) {
// var c = Raphael.hsb(Math.random(), .5, .75);
// var c = Raphael.hsb(.11, .5, Math.random() * .25 - .25 + .75);
var myRPath = r.path(worldmap.shapes[country]).attr({stroke: "#ccc6ae", fill: "#f0efeb", "stroke-opacity": 0.25});
myCountryArray[myRPath.id] = country;
myRPath.hover(function() {
showTooltip(myCountryArray[this.id]);
});
}
var world = r.setFinish();
world.hover(over, out);
// world.animate({fill: "#666", stroke: "#666"}, 2000);
world.getXY = function (lat, lon) {
return {
cx: lon * 2.6938 + 465.4,
cy: lat * -2.6938 + 227.066
};
};
world.getLatLon = function (x, y) {
return {
lat: (y - 227.066) / -2.6938,
lon: (x - 465.4) / 2.6938
};
};
var latlonrg = /(\d+(?:\.\d+)?)[\xb0\s]?\s*(?:(\d+(?:\.\d+)?)['\u2019\u2032\s])?\s*(?:(\d+(?:\.\d+)?)["\u201d\u2033\s])?\s*([SNEW])?/i;
world.parseLatLon = function (latlon) {
var m = String(latlon).split(latlonrg),
lat = m && +m[1] + (m[2] || 0) / 60 + (m[3] || 0) / 3600;
if (m[4].toUpperCase() == "S") {
lat = -lat;
}
var lon = m && +m[6] + (m[7] || 0) / 60 + (m[8] || 0) / 3600;
if (m[9].toUpperCase() == "W") {
lon = -lon;
}
return this.getXY(lat, lon);
};
for (var country in worldmap.shapes) {
<?php foreach($details as $dd){
if($dd['lastconnected.loc']!=""){
?>
r.circle().attr({fill: "#00f", stroke: "", r: 1}).attr(world.getXY(<?=$dd['lastconnected.loc']?>));
<?php }
}?>
}
try {
navigator.geolocation && navigator.geolocation.getCurrentPosition(function (pos) {
r.circle().attr({fill: "none", stroke: "#f00", r: 5}).attr(world.getXY(pos.coords.latitude, pos.coords.longitude));
});
} catch (e) {}
var frm = document.getElementById("latlon-form"),
dot = r.circle().attr({fill: "r#FE7727:50-#F57124:100", stroke: "#fff", "stroke-width": 2, r: 0}),
// dot2 = r.circle().attr({stroke: "#000", r: 0}),
ll = document.getElementById("latlon"),
cities = document.getElementById("cities");
});
</script>
<script>
//this var will hold all country data from initial ajax call
var mycountryarray = new Array();
jsonresponse = '<?php echo "x";?>';
mycountryarray = $.parseJSON(jsonresponse);
$(document).ready(function(){
$("#forworldmap").mousemove(function(e){
$("#forworldmapcomment").position({
my: "bottom-20",
of: e,
collision: "fit"
});
});
$("#forworldmap").mouseout(function(e){
$("#forworldmapcomment").html("");
});
});
function showTooltip(country) {
if (mycountryarray[country]) {
$("#forworldmapcomment").html("<h3>"+country + " " + worldmap.names[country] + ": "+ mycountryarray[country]+"</h3>");
} else {
$("#forworldmapcomment").html("<h3>"+country + " " + worldmap.names[country] + ": 0</h3>");
}
}
</script>
<div class="col-md-12">
<h4>Map</h4>
<div id="forworldmap"></div>
<!--Awesome world map modified from http://raphaeljs.com/ Raphael, check it out!-->
</div>
<div id="forworldmapcomment" style="min-height:100px"></div>
<file_sep>/app/views/ex/reference.html.php
<div class="row container-fluid">
<?php echo $this->_render('element', 'sidebar-menu');?>
<div class="col-md-9 container-fluid" >
<div class="panel panel-primary">
<div class="panel-heading">Signin Reference</div>
<div class="panel-body" style="text-align:center">
<?php foreach($users as $user){?>
<button ><?=$user['username']?></button>
<?php }?>
</div>
</div>
</div>
</div><file_sep>/app/models/Greenblocks.php
<?php
namespace app\models;
class Greenblocks extends \lithium\data\Model {
}
?><file_sep>/app/webroot/test.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="keywords" content="<?php if(isset($keywords)){echo $keywords;} ?>">
<meta name="description" content="<?php if(isset($description)){echo $description;} ?>">
<meta name="author" content="">
<link rel="shortcut icon" href="/img/logo-MultiSigX.gif" />
<title><?php echo MAIN_TITLE;?><?php if(isset($title)){echo $title;} ?></title>
<!-- Bootstrap Core CSS -->
<link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="/bootstrap/css/grayscale.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="/bootstrap/css/dashboard.css?v=<?=rand(1,100000000)?>" rel="stylesheet">
<!-- Custom Fonts -->
<link href="/fontawesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic" rel="stylesheet" type="text/css">
<link href="http://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css">
<script src="/bootstrap/js/bootstrap-datepicker.js"></script>
<?php
// $this->scripts('<script src="/js/main.js?v='.rand(1,100000000).'"></script>');
?>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body id="page-top" data-spy="scroll" data-target=".navbar-fixed-top">
<!-- Navigation -->
<nav class="navbar navbar-custom navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">
<i class="fa fa-bars"></i>
</button>
<a class="navbar-brand page-scroll" href="#page-top">
<i class="fa fa-play-circle"></i> <span class="light">Bitcoin</span> MultiSigX Security
</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-right navbar-main-collapse">
<ul class="nav navbar-nav">
<!-- Hidden li included to remove active class from about link when scrolled up past about section -->
<li class="hidden">
<a href="#page-top"></a>
</li>
<li>
<a class="page-scroll" href="#about">About</a>
</li>
<li>
<a class="page-scroll" href="#features">Features</a>
</li>
<li>
<a class="page-scroll" href="#signup">Signup</a>
</li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- Intro Header -->
<header class="intro">
<div class="intro-body">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<h1 class="brand-heading">Digital currency</h1>
<p class="intro-text">
In the dark world of bitcoin, security is a concern for users.<br>No wallets are safe from hackers.<br>
<div class="row">
<div class="col-lg-6 col-lg-offset-3">
<img src="/img/logo-MultiSigX.png" style="max-width:100%"/>
</div>
</div>
</p>
<a href="#about" class="btn btn-circle page-scroll">
<i class="fa fa-angle-double-down animated"></i>
</a>
</div>
</div>
</div>
</div>
</header>
<!-- About Section -->
<section id="about" class="container content-section text-center">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="row">
<div class="col-lg-6 col-lg-offset-3">
<img src="/img/logo-MultiSigX.png" style="max-width:100%"/>
</div>
</div>
<p>Bitcoin / GreenCoin Multi Signatures for everyone
<br><code>PrivateKeys</code> or <code>Coins</code> are not on stored the server</p>
<p>Security has been the main concern for everyone since the start of Cryptocurrencies. MultiSigX makes your coins extremely secure!</p>
<a href="#features" class="btn btn-circle page-scroll">
<i class="fa fa-angle-double-down animated"></i>
</a>
<p></p>
</div>
</div>
</section>
<!-- Feature Section -->
<section id="features" class="container content-section text-center">
<div class="row">
<div class="col-lg-8 col-lg-offset-2">
<div class="row">
<div class="col-lg-6 col-lg-offset-3">
<img src="/img/logo-MultiSigX.png" style="max-width:100%"/>
</div>
</div>
<h2>Bitcoin / GreenCoin Multi Signatures <br>for everyone</h2>
<p><code>PrivateKeys</code> or <code>Coins</code> are not on stored the server<br>
2FA security, mobile alerts on withdrawal<br>
Individuals<sup>*</sup> - NOMINAL 0.001% commission<br>
Groups<sup>*</sup> - 1% commission on withdrawal<br>
Business<sup>*</sup> - 2% commission on withdrawal</p>
<ul class="list-inline banner-social-buttons">
<li>
<a href="https://github.com/MultiSigX/MultiSigX" class="btn btn-default btn-lg"><i class="fa fa-github fa-fw"></i> <span class="network-name">Github</span></a>
</li>
</ul>
<a href="#signup" class="btn btn-circle page-scroll">
<i class="fa fa-angle-double-down animated"></i>
</a>
</div>
</div>
</section>
<!-- Signup Section -->
<section id="signup" class="content-section text-center">
<div class="download-section">
<div class="container">
<div class="col-lg-8 col-lg-offset-2">
<h3>One of ours users said:</h3>
<p>With MultiSigX, I have used <code>2 of 3</code> and <code>3 of 3</code> security, I am able to sleep soundly with my computer, USB, phone connected to internet.</p>
<p>You can start using MultiSigX just in a few clicks</p>
<div class="col-lg-6 col-lg-offset-3">
<img src="/img/logo-MultiSigX.png" style="max-width:100%"/><br>
<a href="/signup" class="btn btn-default btn-lg">Sign Up</a>
<a href="/signin" class="btn btn-default btn-lg">Sign In</a>
</div>
</div>
</div>
</div>
</section>
<!-- Map Section -->
<div id="map"></div>
<!-- Footer -->
<footer>
<div class="container text-center">
<p>MultiSigX is a registered name of <strong>MultiSigX Inc. Apia, Samoa</strong> Company No: 65518</p>
</div>
</footer>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="/bootstrap/js/bootstrap.min.js"></script>
<!-- Plugin JavaScript -->
<script src="js/jquery.easing.min.js"></script>
<!-- Custom Theme JavaScript -->
<script src="/js/grayscale.js"></script>
</body>
</html>
<file_sep>/app/views/ex/friends.html.php
<div class="row container-fluid">
<?php echo $this->_render('element', 'sidebar-menu');?>
<div class="col-md-9 container-fluid" >
<div class="panel panel-primary">
<div class="panel-heading">Friends</div>
<div class="panel-body" style="text-align:center">
<?php foreach($emails as $email){?>
<button ><?=$email?></button>
<?php }?>
</div>
</div>
</div>
</div><file_sep>/app/controllers/ExController.php
<?php
namespace app\controllers;
use app\models\Users;
use app\models\Details;
use app\models\Currencies;
use app\models\Addresses;
use app\models\Relations;
use app\models\Pages;
use app\models\File;
use app\models\Commissions;
use lithium\data\Connections;
use app\extensions\action\Functions;
use app\extensions\action\Bitcoin;
use app\extensions\action\Greencoin;
use app\controllers\UsersController;
use lithium\security\Auth;
use lithium\storage\Session;
use app\extensions\action\GoogleAuthenticator;
use lithium\util\String;
use MongoID;
use \lithium\template\View;
use \Swift_MailTransport;
use \Swift_Mailer;
use \Swift_Message;
use \Swift_Attachment;
use li3_qrcode\extensions\action\QRcode;
class ExController extends \lithium\action\Controller {
public function index(){
return $this->render(array('json' => array("EX"=>false)));
}
public function dashboard($what = null){
$UC = new UsersController();
$user = Session::read('member');
$id = $user['_id'];
if($id==null){$this->redirect(array('controller'=>'Users','action'=>'signup'));}
if($what!="signed"){
$singleaddress = Addresses::find('first',array(
'conditions'=>array(
'name'=>$what,
)
));
}
$addresses = Addresses::find('all',array(
'conditions'=>array('username'=>$user['username'])
));
$refered = Addresses::find('all',array(
'conditions'=>array(
'addresses.email'=>$user['email'],
'username'=>array('$ne'=>$user['username'])
)
));
$balances = array();
if(count($addresses)>0){
foreach($addresses as $address){
$final = $UC->CheckBalance($address['msxRedeemScript']['address'],$address['currencyName'],true);
array_push($balances, array('address'=>$address['msxRedeemScript']['address'],'balance'=>$final['final']));
}
}
if(count($refered)>0){
foreach($refered as $address){
$final = $UC->CheckBalance($address['msxRedeemScript']['address'],$address['currencyName'],true);
array_push($balances, array('address'=>$address['msxRedeemScript']['address'],'balance'=>$final['final']));
}
}
$currencies = Currencies::find('all',array('order'=>array('currency.name'=>-1)));
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$details = Details::find('first',array(
'conditions'=>array('user_id'=>$id)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
if($what=="signed"){
$msg = "You have already signed this withdrawal. Please wait for others to sign and send this transaction!";
}
return compact('user','details','addresses','refered','singleaddress','currencies','balances','title','keywords','description','msg','what');
}
public function create(){
$user = Session::read('member');
$id = $user['_id'];
$ga = new GoogleAuthenticator();
if($id==null){$this->redirect(array('controller'=>'Pages','action'=>'home/'));}
if($this->request->data){
$oneCode = $ga->getCode($secret);
switch ($this->request->data['currency']){
case "BTC":
$coin = new Bitcoin('http://'.BITCOIN_WALLET_SERVER.':'.BITCOIN_WALLET_PORT,BITCOIN_WALLET_USERNAME,BITCOIN_WALLET_PASSWORD);
$currency = "Bitcoin";
break;
case "XGC":
$coin = new Greencoin('http://'.GREENCOIN_WALLET_SERVER.':'.GREENCOIN_WALLET_PORT,GREENCOIN_WALLET_USERNAME,GREENCOIN_WALLET_PASSWORD);
$currency = "GreenCoin";
break;
}
$security = (int)$this->request->data['security'];
/*
print_r(GREENCOIN_WALLET_PASSWORD) ;
print_r(GREENCOIN_WALLET_USERNAME) ;
print_r(GREENCOIN_WALLET_PORT) ;
print_r(GREENCOIN_WALLET_SERVER) ;
print_r($coin);
*/
$publickeys = array(
$this->request->data['pubkeycompress'][1],
$this->request->data['pubkeycompress'][2],
$this->request->data['pubkeycompress'][3],
);
$name = $user['username']."-".$this->request->data['currency']."-".$oneCode;
// $AddMultiSig = $coin->addmultisigaddress($security,$publickeys,'MSX-'.$name);
$createMultiSig = $coin->createmultisig($security,$publickeys);
$changeAddress = $this->request->data['ChangeAddress'];
if($changeAddress=="MultiSigX"){
$changeValue = $createMultiSig['address'];
}else{
$changeValue = $this->request->data['DefaultAddress'];
}
$data = array(
'addresses.0.passphrase'=>$this->request->data['passphrase'][1],
'addresses.0.dest'=>$this->request->data['dest'][1],
// 'addresses.0.private'=>$this->request->data['private'][1],
'addresses.0.pubkeycompress'=>$this->request->data['pubkeycompress'][1],
'addresses.0.email'=>$this->request->data['email'][1],
'addresses.0.address'=>$this->request->data['address'][1],
'addresses.0.relation'=>$this->request->data['relation'][1],
'addresses.1.passphrase'=>$this->request->data['passphrase'][2],
'addresses.1.dest'=>$this->request->data['dest'][2],
// 'addresses.1.private'=>$this->request->data['private'][2],
'addresses.1.pubkeycompress'=>$this->request->data['pubkeycompress'][2],
'addresses.1.email'=>$this->request->data['email'][2],
'addresses.1.address'=>$this->request->data['address'][2],
'addresses.1.relation'=>$this->request->data['relation'][2],
'addresses.2.passphrase'=>$this->request->data['passphrase'][3],
'addresses.2.dest'=>$this->request->data['dest'][3],
// 'addresses.2.private'=>$this->request->data['private'][3],
'addresses.2.pubkeycompress'=>$this->request->data['pubkeycompress'][3],
'addresses.2.email'=>$this->request->data['email'][3],
'addresses.2.address'=>$this->request->data['address'][3],
'addresses.2.relation'=>$this->request->data['relation'][3],
'key'=>$this->request->data['key'],
'secret'=>$this->request->data['secret'],
'username'=>$this->request->data['username'],
'currency'=>$this->request->data['currency'],
'currencyName'=>$currency,
'CoinName'=>$this->request->data['CoinName'],
'security'=>$this->request->data['security'],
'DateTime' => new \MongoDate(),
'name'=>$name,
'msxRedeemScript' => $createMultiSig,
'Change.default' => $changeAddress,
'Change.value'=> $changeValue,
);
if($this->request->data['email'][2] == DEFAULT_ESCROW){
$data1 = array(
'addresses.1.private'=>$this->request->data['private'][2]
);
$data = array_merge($data,$data1);
// print_r($data);
}
if($this->request->data['email'][3] == DEFAULT_ESCROW){
$data2 = array(
'addresses.2.private'=>$this->request->data['private'][3]
);
$data = array_merge($data,$data2);
}
//print_r($data);exit;
$Addresses = Addresses::create($data);
$saved = $Addresses->save();
$addresses = Addresses::find('first',array(
'conditions'=>array('_id'=>$Addresses->_id)
));
// create print PDF for all 3 users
// Delete all old files from the system
if ($handle = opendir(QR_OUTPUT_DIR)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if(strpos($entry,$addresses['username'])){
unlink(QR_OUTPUT_DIR.$entry);
}
}
}
closedir($handle);
}
//Create all QRCodes
$qrcode = new QRcode();
$i = 0;
foreach($addresses['addresses'] as $address){
$qrcode->png($address['passphrase'], QR_OUTPUT_DIR.$i.'-'.$addresses['username']."-passphrase.png", 'H', 7, 2);
$qrcode->png($address['dest'], QR_OUTPUT_DIR.$i.'-'.$addresses['username']."-dest.png", 'H', 7, 2);
$qrcode->png($this->request->data['private'][$i+1], QR_OUTPUT_DIR.$i.'-'.$addresses['username']."-private.png", 'H', 7, 2);
$qrcode->png($address['pubkeycompress'], QR_OUTPUT_DIR.$i.'-'.$addresses['username']."-pc.png", 'H', 7, 2);
$i++;
}
$qrcode->png($addresses['msxRedeemScript']['address'], QR_OUTPUT_DIR.'x-'.$addresses['username'].'-'.$addresses['msxRedeemScript']['address']."-address.png", 'H', 7, 2);
$qrcode->png($addresses['msxRedeemScript']['redeemScript'], QR_OUTPUT_DIR.'x-'.$addresses['username'].'-'."redeemScript.png", 'H', 7, 2);
//create PDF files...
for($i=0;$i<=2;$i++){
$printdata = array(
'i'=>$i,
'username'=>$addresses['username'],
'createEmail'=>$addresses['addresses'][0]['email'],
'user1'=>$addresses['addresses'][1]['email'],
'user2'=>$addresses['addresses'][2]['email'],
'relation0'=>$addresses['addresses'][0]['relation'],
'relation1'=>$addresses['addresses'][1]['relation'],
'relation2'=>$addresses['addresses'][2]['relation'],
'address0'=>$addresses['addresses'][0]['address'],
'address1'=>$addresses['addresses'][1]['address'],
'address2'=>$addresses['addresses'][2]['address'],
'OpenPassword'=> $one<PASSWORD>.'-'.substr($addresses['msxRedeemScript']['address'],0,6),
'name'=>$addresses['name'],
'DateTime'=>$addresses['DateTime'],
'address'=>$addresses['msxRedeemScript']['address'],
'redeemScript'=>$addresses['msxRedeemScript']['redeemScript'],
'email'=>$addresses['addresses'][$i]['email'],
'passphrase'=>$addresses['addresses'][$i]['passphrase'],
'dest'=>$addresses['addresses'][$i]['dest'],
'private'=>$this->request->data['private'][$i+1],
'pubkeycompress'=>$addresses['addresses'][$i]['pubkeycompress'],
'CoinName'=>$addresses['CoinName'],
'currency'=>$addresses['currency'],
'currencyName'=>$currency,
'security'=>$addresses['security'],
);
$view = new View(array(
'paths' => array(
'template' => '{:library}/views/{:controller}/{:template}.{:type}.php',
'layout' => '{:library}/views/layouts/{:layout}.{:type}.php',
)
));
echo $view->render(
'all',
compact('printdata'),
array(
'controller' => 'print',
'template'=>'print',
'type' => 'pdf',
'layout' =>'print'
)
);
rename(QR_OUTPUT_DIR.'MultiSigX.com-'.$printdata['name']."-MSX-Print".".pdf",QR_OUTPUT_DIR.'MultiSigX.com-'.$printdata['name']."-MSX-Print-".$i.".pdf");
// sending email to the users
/////////////////////////////////Email//////////////////////////////////////////////////
$function = new Functions();
$compact = array('data'=>$printdata);
// sendEmailTo($email,$compact,$controller,$template,$subject,$from,$mail1,$mail2,$mail3)
$from = array(NOREPLY => "noreply@".COMPANY_URL);
$email = $addresses['addresses'][$i]['email'];
$attach = QR_OUTPUT_DIR.'MultiSigX.com-'.$printdata['name']."-MSX-Print-".$i.".pdf";
$function->sendEmailTo($email,$compact,'users','create',"MultiSigX,com important document",$from,'','','',$attach);
/////////////////////////////////Email//////////////////////////////////////////////////
} // create PDF files
// Delete all old files from the system
if ($handle = opendir(QR_OUTPUT_DIR)) {
while (false !== ($entry = readdir($handle))) {
if ($entry != "." && $entry != "..") {
if(strpos($entry,$addresses['username'])){
unlink(QR_OUTPUT_DIR.$entry);
}
}
}
closedir($handle);
}
//Create all QRCodes
$this->redirect('Ex::dashboard');
} // if $this->request->data
$details = Details::find('first',array(
'conditions'=>array('username'=>$user['username'])
));
$relations = Relations::find('all',array(
'order'=>array('type'=>-1)
));
$passphrase[0] = $ga->createSecret(64);
$passphrase[1] = $ga->createSecret(64);
$passphrase[2] = $ga->createSecret(64);
$currencies = Currencies::find('all',array('order'=>array('currency.name'=>-1)));
$addresses = Addresses::find('all',array(
'conditions'=>array('username'=>$user['username']),
'fields'=>array('currencyName','currency')
));
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('user','details','passphrase','currencies','relations','addresses','title','keywords','description');
}
public function address($address = null){
$user = Session::read('member');
$id = $user['_id'];
if($id==null){$this->redirect(array('controller'=>'Pages','action'=>'home/'));}
$addresses = Addresses::find('first',array(
'conditions'=>array('msxRedeemScript.address'=>$address)
));
$data = array();
foreach($addresses['addresses'] as $address){
$userFind = Users::find('first',array(
'conditions'=>array('email'=>$address['email'])
));
array_push($data, array(
'email'=>$address['email'],
'relation'=>$address['relation'],
'address'=>$address['address'],
'username'=>$userFind['username']
));
}
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$details = Details::find('first',array(
'conditions'=>array('user_id'=>$id)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('user','details','addresses','data','title','keywords','description');
}
public function name($name = null){
$user = Session::read('member');
$id = $user['_id'];
if($id==null){$this->redirect(array('controller'=>'Pages','action'=>'home/'));}
$addresses = Addresses::find('first',array(
'conditions'=>array('name'=>$name)
));
$data = array();
foreach($addresses['addresses'] as $address){
$userFind = Users::find('first',array(
'conditions'=>array('email'=>$address['email'])
));
array_push($data, array(
'email'=>$address['email'],
'relation'=>$address['relation'],
'address'=>$address['address'],
'username'=>$userFind['username']
));
}
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$details = Details::find('first',array(
'conditions'=>array('user_id'=>$id)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('user','details','addresses','data','title','keywords','description');
}
public function settings(){
$user = Session::read('member');
$id = $user['_id'];
if($id==null){$this->redirect(array('controller'=>'Pages','action'=>'home/'));}
if($this->request->data){
$conditions = array('user_id'=>$id);
if($this->request->data['Picture']['name']!=''){
$remove = File::remove('all',array(
'conditions'=>array( 'user_id' => $id)
));
$fileData = array(
'file' => $this->request->data['Picture'],
'user_id'=>$id,
);
$file = File::create();
$file->save($fileData);
}
$data = array(
'settings'=>$this->request->data,
'SMSVerified'=>'No',
);
Details::update($data,$conditions);
}
$function = new Functions();
$countChild = $function->countChilds($id);
$levelOne = $function->levelOneChild($id);
$commissions = Commissions::find('all');
$image_address = File::find('first',array(
'conditions'=>array('user_id'=>$id)
));
if($image_address['_id']!=""){
$imagename_address = $id.'_'.$image_address['filename'];
$path = LITHIUM_APP_PATH . '/webroot/documents/'.$imagename_address;
file_put_contents($path, $image_address->file->getBytes());
}
$details = Details::find('first',array(
'conditions'=>array('user_id'=>$id)
));
$secret = $details['secret'];
$ga = new GoogleAuthenticator();
$qrCodeUrl = $ga->getQRCodeGoogleUrl("MultiSigX-".$details['username'], $secret);
return compact('details','qrCodeUrl','imagename_address','countChild','levelOne','commissions');
}
public function savepicture(){
$user = Session::read('member');
$id = $user['_id'];
if($id==null){$this->redirect(array('controller'=>'Pages','action'=>'home/'));}
if($this->request->data){
$conditions = array('user_id'=>$id);
if($this->request->data['Picture']['name']!=''){
$remove = File::remove('all',array(
'conditions'=>array( 'user_id' => $id)
));
$fileData = array(
'file' => $this->request->data['Picture'],
'user_id'=>$id,
);
$file = File::create();
$file->save($fileData);
$data = array(
'Picture'=>$this->request->data['Picture'],
);
Details::update($data,$conditions);
}
}
return $this->redirect(array('controller'=>'Ex','action'=>'settings/'));
}
public function withdraw($address=null,$step=null,$msg=null){
if($address==null){
return $this->redirect(array('controller'=>'Ex','action'=>'dashboard/'));
}
$user = Session::read('member');
$id = $user['_id'];
if($id==null){$this->redirect(array('controller'=>'Pages','action'=>'home/'));}
$addresses = Addresses::find('first',array(
'conditions'=>array('msxRedeemScript.address'=>$address)
));
foreach($addresses['addresses'] as $multiUser){
$multiUserEmail = $multiUser['email'];
if($user['email']==$multiUserEmail){
$authorizeUsername = $user['username'];
}
}
switch($step){
case '';
return $this->redirect(array('controller'=>'Ex','action'=>'withdraw/'.$address.'/create'));
break;
case 'create';
if($addresses['createTrans']!=null){
return $this->redirect(array('controller'=>'Ex','action'=>'withdraw/'.$address.'/sign'));
}
$button = 'Create';
break;
case 'sign';
if(count($addresses['signTrans']) == (int) $addresses['security']){
return $this->redirect(array('controller'=>'Ex','action'=>'withdraw/'.$address.'/send'));
}
if($addresses['createTrans']==null){
return $this->redirect(array('controller'=>'Ex','action'=>'withdraw/'.$address.'/create'));
}
$button = 'Sign';
break;
case 'send';
$button = 'Send';
break;
default:
return $this->redirect(array('controller'=>'Ex','action'=>'withdraw/'.$address.'/create'));
break;
}
$transact = array();
//who has created, signed, send transactions
if($addresses['createTran']!=null){
$create = $addresses['createTran'];
}
if($addresses['signTran']!=null){
$sign = $addresses['signTran'];
}
if($addresses['sendTran']!=""){
$send = $addresses['sendTran'];
}
$transact = array('create'=>$create,'sign'=>$sign,'send'=>$send);
$UC = new UsersController();
$final = $UC->CheckBalance($address,$addresses['currencyName'],true);
$final_balance = $final['final'];
$currencies = Currencies::find("first",array(
"conditions"=>array("currency.name"=>$addresses['currencyName'])
));
$data = array();
foreach($addresses['addresses'] as $address){
$userFind = Users::find('first',array(
'conditions'=>array('email'=>$address['email'])
));
array_push($data, array(
'email'=>$address['email'],
'relation'=>$address['relation'],
'address'=>$address['address'],
'username'=>$userFind['username']
));
}
$next = $step;
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$relations = Relations::find('all',array(
'order'=>array('type'=>-1)
));
$details = Details::find('first',array(
'conditions'=>array('user_id'=>$id)
));
$function = new Functions();
$countChild = $function->countChilds($id);
$levelOne = $function->levelOneChild($id);
$commissions = Commissions::find('all');
foreach($commissions as $commission){
if($countChild-$levelOne>=$commission['min'] && $countChild-$levelOne<=$commission['max']){
$reduceComm = $commission['Level'][1];
break;
}
if($levelOne>=$commission['min'] && $levelOne<=$commission['max']){
$reduceComm = $commission['Level'][0];
break;
}
}
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('user','details','addresses','data','final_balance','next','title','keywords','description','currencies','relations','button','transact','msg','reduceComm');
}
public function password(){
if($this->request->data){
$details = Details::find('first', array(
'conditions' => array(
'key' => $this->request->data['key'],
),
'fields' => array('user_id')
));
$msg = "Password Not Changed!";
// print_r($details['user_id']);
if($details['user_id']!=""){
if($this->request->data['password'] == $this->request->data['password2']){
// print_r($this->request->data['oldpassword']);
$user = Users::find('first', array(
'conditions' => array(
'_id' => $details['user_id'],
)
));
if($user['password']==String::hash($this->request->data['oldpassword'])){
// print_r($details['user_id']);
$data = array(
'password' => String::hash($this->request->data['password']),
);
// print_r($data);
$user = Users::find('all', array(
'conditions' => array(
'_id' => $details['user_id'],
)
))->save($data,array('validate' => false));
if($user){
$msg = "Password changed!";
}
}
}else{
$msg = "New password does not match!";
}
}
}
return compact('msg');
}
public function reference($Who=null){
$user = Session::read('member');
$id = $user['_id'];
if($id==null){$this->redirect(array('controller'=>'Pages','action'=>'home/'));}
$function = new Functions();
switch ($Who){
case "All":
$users = $function->getChilds($id);
break;
case "Two":
$users = $function->levelOneChild($id);
break;
case "Parents":
$users = $function->getParents($id);
break;
}
return compact('users');
}
public function friends(){
$user = Session::read('member');
$id = $user['_id'];
if($id==null){$this->redirect(array('controller'=>'Pages','action'=>'home/'));}
$friends = Addresses::find('all',array(
'conditions'=>array('username'=>$user['username']),
));
$emails = array();
foreach($friends as $friend){
array_push($emails,$friend['addresses'][0]['email'] );
array_push($emails,$friend['addresses'][1]['email'] );
array_push($emails,$friend['addresses'][2]['email'] );
}
$emails = array_unique($emails);
return compact('emails');
}
}
?><file_sep>/app/views/ex/withdraw.html.php
<div class="row container-fluid">
<?php echo $this->_render('element', 'sidebar-menu');?>
<div class="white">
<div class="col-md-9 container-fluid" >
<div class="panel panel-success">
<div class="panel-heading"><a href="/ex/dashboard">Dashboard <i class="fa-chevron-left fa"></i></a>
Address: <?=$addresses['msxRedeemScript']['address']?> <?=$addresses['currencyName']?> <?=$addresses['currency']?></div>
<div class="panel-body" style="text-align:center">
<div class="panel panel-primary">
<div class="panel-heading">
<h2>MultiSigX Coin Details</h2>
</div>
<?php
$commarray = array();
foreach($data as $d){
foreach($relations as $relation){
if($d['relation']==$relation['type']){
array_push($commarray, $relation['commission']);
}
}
}
$OriginalCommission = max($commarray);
$commission = $OriginalCommission * (100-$reduceComm)/100;
?>
<div class="panel-body">
<h4>Withdraw coins from<br>
<code><?=$addresses['msxRedeemScript']['address']?></code><br>
<?=$addresses['CoinName']?><br>
<?=$addresses['name']?><br>
<?=$addresses['currencyName']?> <?=$addresses['currency']?><br>
<table class="table table-striped table-condensed">
<tr>
<th>Description</th>
<th> </th>
<th style="text-align:right"><?=$addresses['currency']?></th>
</tr>
<tr>
<td style="text-align:left">Deposit</td>
<td> </td>
<td style="text-align:right"><?=number_format($final_balance,8)?></td>
</tr>
<tr>
<td style="text-align:left">Tx Fees (Miners)</td>
<td> </td>
<td style="text-align:right"><?=number_format($currencies['txFee'],8)?></td>
</tr>
<tr>
<td style="text-align:left">Commission</td>
<td><?=$OriginalCommission?>%</td>
<td style="text-align:right"> </td>
</tr>
<tr>
<td style="text-align:left">Reduced Commission (Referral)</td>
<td><?=$reduceComm?>%</td>
<td style="text-align:right"> </td>
</tr>
<tr>
<td style="text-align:left">Final Commission</td>
<td><?=($OriginalCommission - $OriginalCommission*$reduceComm/100)?>%</td>
<td style="text-align:right"><?=number_format($final_balance*($OriginalCommission - $OriginalCommission*$reduceComm/100)/100,8)?></td>
</tr>
<tr style="border-bottom: double">
<td style="text-align:left;color:red"><strong>Max Withdrawal</strong></td>
<td> </td>
<td style="text-align:right;color:red"><strong><?=number_format($final_balance-$currencies['txFee']-($final_balance*($OriginalCommission - $OriginalCommission*$reduceComm/100)/100),8)?></strong></td>
</tr>
</table>
Security: <strong style="color:red"><?=$addresses['security']?></strong> sign required of 3 to send payments<br>
</h4>
</div>
<div class="panel-footer">
Created on: <?=gmdate(DATE_RFC850,$addresses['DateTime']->sec)?>
</div>
</div>
<div class="row">
<div class="col-md-12" style="text-align:center " >
<div id="SelfUser" class="col-xs-12 col-md-6 col-md-offset-3" style="text-align:center" >
<div class="panel panel-success">
<div class="panel-heading">
<h2><i class=" fa fa-user"></i> <?=$user['username']?></h2>
</div>
<div class="panel-body">
<?php foreach($data as $d){
if($d['username']==$user['username']){?>
<h3><?=$d['relation']?>: <a href="mailto:<?=$d['email']?>?subject=MultiSigX" target="_blank"><?=$d['email']?></a></h3>
<?php }
}?>
<?php if($transact['create']['username']==$user['username']){?>
<h4>
Transaction created on:<br>
<span class="label label-success"><?=gmdate(DATE_RFC850,$transact['create']['DateTime']->sec)?></span><br><br>
by <?=$transact['create']['username']?>, send to
<?php for($i=0;$i<3;$i++){
if($transact['create']['withdraw']['amount'][$i]>0){
?>
<code class="label label-success"><?=number_format($transact['create']['withdraw']['amount'][$i],8)?> <?=$addresses['currency']?> - <?=$transact['create']['withdraw']['address'][$i]?></code><br>
<?php }
}?>
</h4>
<?php if($transact['sign']==null){?>
<a href="/users/DeleteCreateTrans/<?=$addresses['msxRedeemScript']['address']?>"><i class="glyphicon glyphicon-remove"></i> Delete</a>
<?php }else{?>
<?php }?>
<?php }?>
<?php
$signed = "No";
$noOfSign = 0;
if(count($transact['sign'])>0){
foreach($transact['sign'] as $sign){
$noOfSign++;
}
}
if(count($transact['sign'])>0){?>
<h3> Signed by:</h3>
<?php
foreach($transact['sign'] as $sign){
echo "<h4>".$sign['username']." <br><small>".gmdate(DATE_RFC850,$sign['DateTime']->sec)."</small></h4>";
if($sign['username']==$user['username']){
$signed = "Yes";
// break;
}
}
}
?>
<?php if($signed=="No"){?>
<h3><button type="button" class="btn btn-success btn-block" data-toggle="modal" data-target="#Modal<?=$button?>"><?=$button?></button>
</h3>
<?php }else{ ?>
<h3>You have already signed this transaction.</h3>
<?php } ?>
<?php if($noOfSign==$addresses['security']){?>
<?php if($addresses['sendTrans']==null){?>
<h3><button type="button" class="btn btn-success btn-block" data-toggle="modal" data-target="#Modal<?=$button?>"><?=$button?></button>
<?php }else{?>
<h3>The transaction is complete!<br>Funds transferred!</h3>
<?php }?>
<?php }?>
<?php if($msg=='No'){
print_r("<div class='alert alert-danger'>Transaction not created!</div>");
}?>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<?php foreach($data as $d){?>
<?php if($d['username']!=$user['username']){?>
<div id="User<?=$d['relation']?>" class="col-md-6 col-md-offset-3 col-xs-12 " style="text-align:center ">
<div class="panel panel-danger">
<div class="panel-heading">
<h2><i class=" fa fa-user"></i>
<?php if($d['username']==""){?>
Not Registered!
<?php }else{?>
<?=$d['username']?>
<?php }?>
</h2>
</div>
<div class="panel-body">
<h2><?=$d['relation']?></h2>
<br>
<?=$d['email']?>
<br>
<code><?=$d['address']?></code>
<?php if($transact['create']['username']==$d['username'] && $d['username']!="" ){
print_r("aaa".$transact['create']['username']."aaa");
?>
<h4>
Transaction created on:<br>
<span class="label label-success"><?=gmdate(DATE_RFC850,$transact['create']['DateTime']->sec)?></span><br><br>
by <?=$transact['create']['username']?>, send to
<?php for($i=0;$i<3;$i++){
if($transact['create']['withdraw']['amount'][$i]>0){
?>
<code class="label label-success"><?=number_format($transact['create']['withdraw']['amount'][$i],8)?> <?=$addresses['currency']?> - <?=$transact['create']['withdraw']['address'][$i]?></code><br>
<?php }
}?>
</h4>
<?php }?>
<?php if($transact['sign']==null){?>
<?php }else{?>
<h3> Signed by:</h3>
<?php }?>
<?php if(count($transact['sign'])>0){
foreach($transact['sign'] as $sign){
echo "<h4>".$sign['username']." <br><small>".gmdate(DATE_RFC850,$sign['DateTime']->sec)."</small></h4>";
}
}
?>
</div>
</div>
</div>
<?php }?>
<?php }?>
</div>
</div>
<div class="panel-footer"></div>
</div>
</div>
</div>
<?php
$Amount = (float)$final_balance-$currencies['txFee']-($final_balance*$commission/100);
$comm = number_format($final_balance*$commission/100,8);
?>
<div class="modal fade" id="ModalCreate" tabindex="-1" role="dialog" aria-labelledby="myModalCreate" aria-hidden="true">
<?=$this->form->create("",array('url'=>'/users/createTrans','class'=>'form-group has-error')); ?>
<?=$this->form->hidden('address', array('value'=>$addresses['msxRedeemScript']['address'])); ?>
<?=$this->form->hidden('SendTrxFee', array('value'=>$currencies['txFee'])); ?>
<?=$this->form->hidden('ChangeAmountValue', array('value'=>0)); ?>
<?=$this->form->hidden('ChangeAddressValue', array('value'=>$addresses['Change']['value'])); ?>
<?=$this->form->hidden('CommissionTotal', array('value'=>number_format($comm,8))); ?>
<?=$this->form->hidden('finalBalance', array('value'=>$final_balance)); ?>
<?=$this->form->hidden('currency', array('value'=>$addresses['currency'])); ?>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="CreateModalLabel">Create Transaction <small>for signatures</small></h4>
</div>
<div class="modal-body" style="text-align:center ">
<table class="table table-striped table-condensed">
<tr>
<th>#</th>
<th width='70%'><?=$addresses['currencyName']?> Address <?=$addresses['currency']?></th>
<th style="text-align:right">Amount <?=$addresses['currency']?></th>
</tr>
<?php
for($i=0;$i<3;$i++){
if($i==0){$value = $Amount;}else{$value=0;}
?>
<tr>
<td><?=($i+1)?></td>
<td><?=$this->form->field('sendToAddress['.$i.']', array('type' => 'text', 'label'=>'','placeholder'=>'your coin address','class'=>'form-control','onBlur'=>'CreateTrans('.$final_balance.','.$commission.','.$currencies['txFee'].');' )); ?>
<span id="Error<?=$i?>"></span>
</td>
<td>
<?=$this->form->field('sendAmount['.$i.']', array('type' => 'number', 'label'=>'','placeholder'=>'0.0000','class'=>'form-control','value'=>$value,'min'=>0,'max'=>$Amount,'step'=>0.000001,'style'=>'text-align:right','onChange'=>'CreateTrans('.$final_balance.','.$commission.','.$currencies['txFee'].');','pattern'=>'' )); ?>
</td>
</tr>
<?php } ?>
<tr>
<td style="border-top:1px solid black"><?=($i+1)?></td>
<td style="border-top:1px solid black;text-align:left">Change to: <?=$addresses['Change']['value']?></td>
<td style="background-color:#eee; text-align:right;border-top:1px solid black">
<span style="color:red;font-size:large" id="ChangeAmount"><?=number_format(0,8)?></span>
</td>
</tr>
<tr style="background-color:#ddd;color:black;font-size:large;">
<td style="border-top:1px solid black"></td>
<th style="border-top:1px solid black">Total</th>
<td style="text-align:right;border-top:1px solid black"><?=number_format($Amount,8)?></td>
</tr>
<tr>
<td style="border-top:1px solid black"></td>
<th style="border-top:1px solid black">Tx Fee to Miners <?=$addresses['currency']?></th>
<td style="background-color:#eee; text-align:right;border-top:1px solid black">
<span style="color:red;font-size:large" id="SendTxFee"><?=number_format($currencies['txFee'],8)?></span>
</td>
</tr>
<tr>
<td style="border-top:1px solid black"></td>
<th style="border-top:1px solid black">Commission % of <?=$addresses['currency']?></th>
<td style="background-color:#eee; text-align:right;border-top:1px solid black">
<span style="font-size:large" id="Commission"><?=number_format($commission,5)?>%</span>
</td>
</tr>
<tr>
<td style="border-top:1px solid black"></td>
<th style="border-top:1px solid black">Commission <?=$addresses['currency']?></th>
<td style="background-color:#eee; text-align:right;border-top:1px solid black"><span style="font-size:large" id="CommissionValue"><?=number_format($comm,8)?></span></td>
</tr>
<tr style="background-color:#ddd;color:black;font-size:large;border-top:double;;border-bottom:double">
<td></td>
<th>Grand Total</th>
<td style="text-align:right"><?=number_format($final_balance,8)?></td>
</tr>
<tr>
<td></td>
<th>Google Authenticator Code</th>
<td>
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-asterisk" id="ErrorCreateMobileCode"></i>
</span>
<input class="form-control" required="required" maxlength="6" pattern="[0-9]{6}" id="CheckCreateMobileCode" placeholder="Mobile Code" type="password" onKeyup="return CreateMobileCodeCheck();">
</div>
</td>
</tr>
</table>
<div id="CreateAlert" class="alert alert-warning">
Create transaction will not transfer funds to the addresses. It will authorize others to sign this transaction and finally transfer funds.
</div>
</div>
<div class="modal-footer">
<?=$this->form->button('Create' ,array('class'=>'btn btn-primary','disabled'=>'disabled','id'=>'CreateSubmit','onClick'=>'return CheckTotal('.$final_balance.','.$commission.');')); ?>
<?=$this->form->reset('Reset' ,array('class'=>'btn btn-primary','id'=>'ResetSubmit')); ?>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
<?=$this->form->end(); ?>
</div>
<div class="modal fade" id="ModalSign" tabindex="-1" role="dialog" aria-labelledby="myModalSign" aria-hidden="true">
<?=$this->form->create("",array('url'=>'/users/signTrans','class'=>'form-group has-error')); ?>
<?=$this->form->hidden('address', array('value'=>$addresses['msxRedeemScript']['address'])); ?>
<?=$this->form->hidden('currency', array('value'=>$addresses['currency'])); ?>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="SignModalLabel">Sign Transaction</h4>
</div>
<div class="modal-body" style="text-align:center ">
<p>You will need the private key from the document<br><strong>MultiSigX.com-<?=$addresses['name']?>-MSX-Print-[x].pdf</strong> which was emailed to you on <?=gmdate('Y-M-d H:i:s',$addresses['DateTime']->sec)?></p>
<?=$this->form->field('privKey', array('type' => 'text', 'label'=>'Private Key','placeholder'=>'<KEY>','class'=>'form-control','onBlur'=>'SignTrans();' )); ?>
<h5>Google Authenticator Code</h5>
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-asterisk" id="ErrorSignMobileCode"></i>
</span>
<input class="form-control" required="required" maxlength="6" pattern="[0-9]{6}" id="CheckSignMobileCode" placeholder="Mobile Code" type="password" onKeyup="return SignMobileCodeCheck();">
</div>
</div>
<div class="modal-footer">
<?=$this->form->submit('Sign' ,array('class'=>'btn btn-primary','disabled'=>'disabled','id'=>'SignSubmit')); ?>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
<?=$this->form->end(); ?>
</div>
<div class="modal fade" id="ModalSend" tabindex="-1" role="dialog" aria-labelledby="myModalSend" aria-hidden="true">
<?=$this->form->create("",array('url'=>'/users/sendTrans','class'=>'form-group has-error')); ?>
<?=$this->form->hidden('address', array('value'=>$addresses['msxRedeemScript']['address'])); ?>
<?=$this->form->hidden('currency', array('value'=>$addresses['currency'])); ?>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="SignModalLabel">Send Transaction <small>from your MultiSigX wallet</small></h4>
</div>
<div class="modal-body" style="text-align:center ">
<h4>Withdraw coins from<br>
<code><?=$addresses['msxRedeemScript']['address']?></code><br>
<?=$addresses['CoinName']?><br>
<?=$addresses['name']?><br>
<?=$addresses['currencyName']?> <?=$addresses['currency']?><br>
Balance: <?=$final_balance?> <?=$addresses['currency']?><br>
Security: <strong style="color:red"><?=$addresses['security']?></strong> sign required of 3 to send payments<br>
</h4>
<h4>
Transaction created on:<br>
<span class="label label-success"><?=gmdate(DATE_RFC850,$transact['create']['DateTime']->sec)?></span><br><br>
by <?=$transact['create']['username']?>, send to
<?php for($i=0;$i<3;$i++){
if($transact['create']['withdraw']['amount'][$i]>0){
?>
<code class="label label-success"><?=number_format($transact['create']['withdraw']['amount'][$i],8)?> <?=$addresses['currency']?> - <?=$transact['create']['withdraw']['address'][$i]?></code><br>
<?php }
}?>
</h4>
<h3> Signed by:</h3>
<?php
foreach($transact['sign'] as $sign){
echo "<h4>".$sign['username']." <br><small>".gmdate(DATE_RFC850,$sign['DateTime']->sec)."</small></h4>";
}
?>
<h5>Google Authenticator Code</h5>
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-asterisk" id="ErrorSendMobileCode"></i>
</span>
<input class="form-control" required="required" maxlength="6" pattern="[0-9]{6}" id="CheckSendMobileCode" placeholder="Mobile Code" type="password" onKeyup="return SendMobileCodeCheck();">
</div>
</div>
<div class="modal-footer">
<?=$this->form->submit('Send' ,array('class'=>'btn btn-primary','id'=>'SendSubmit','disabled'=>'disabled')); ?>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
<?=$this->form->end(); ?>
</div>
</div>
<file_sep>/app/views/users/changepassword.html.php
<h4>Change password</h4>
<?=$this->form->create("",array('url'=>'/users/password/','class'=>'form-group has-error' )); ?>
<?=$this->form->field('email', array('type' => 'text', 'label'=>'Your email address','placeholder'=>'<EMAIL>','class'=>'form-control' )); ?>
<?=$this->form->field('password', array('type' => '<PASSWORD>', 'label'=>'New Password','placeholder'=>'<PASSWORD>','class'=>'form-control' )); ?>
<?=$this->form->field('password2', array('type' => 'password', 'label'=>'Repeat new password','placeholder'=>'same as above','class'=>'form-control' )); ?>
<?=$this->form->hidden('key', array('value'=>$key))?><br>
<?=$this->form->submit('Change' ,array('class'=>'btn btn-primary')); ?>
<?=$this->form->end(); ?>
<file_sep>/app/views/admin/index.html.php
<h3>User registrations</h3>
<?php
if($StartDate==""){
$StartDate = gmdate('Y-m-d',mktime(0,0,0,gmdate('m',time()),gmdate('d',time()),gmdate('Y',time()))-60*60*24*30);
$EndDate = gmdate('Y-m-d',time()+1*60*60*24);
}else{
$StartDate=gmdate('Y-m-d',$StartDate->sec);
$EndDate=gmdate('Y-m-d',$EndDate->sec);
}
?>
<form action="/Admin/index" method="post" >
<div class="row">
<div class="col-md-4">
<div class="input-append date " id="StartDate" data-date="<?=$StartDate?>" data-date-format="yyyy-mm-dd"> From:
<input size="16" name="StartDate" type="text" value="<?=$StartDate?>" readonly >
<span class="add-on"><i class="glyphicon glyphicon-calendar"></i></span>
</div>
</div>
<div class="col-md-4">
<div class="input-append date " id="EndDate" data-date="<?=$EndDate?>" data-date-format="yyyy-mm-dd">
To:
<input size="16" name="EndDate" type="text" value="<?=$EndDate?>" readonly>
<span class="add-on"><i class="glyphicon glyphicon-calendar"></i></span>
</div>
</div>
<div class="col-md-4">
<input type="submit" value="Get report" class="btn btn-primary btn-sm">
<div class="alert alert-error" id="alert"><strong></strong></div>
</div>
</div>
</form>
<hr>
<div >
<table class="table table-condensed table-bordered table-hover" style="width:40% ">
<tr>
<th style="text-align:center;">Date</th>
<th style="text-align:center ">Users</th>
</tr>
<?php foreach($new as $key=>$value){ ?>
<tr>
<td><?=$key;?></td>
<td style="text-align:center "><?=$value['Register']?> </td>
</tr>
<?php
$users = $users + $value['Register'];
?>
<?php }?>
<tr>
<th>Total</th>
<th style="text-align:center " ><?=$users?></th>
</tr>
</table>
</div>
<script src="/js/admin.js"></script><file_sep>/app/views/elements/header.html.php
<?php
use lithium\storage\Session;
use app\extensions\action\Functions;
use app\controllers\AdminController;
$Admin = new AdminController();
$MeAdmin = $Admin->__init();
?>
<?php $user = Session::read('member'); ?>
<div class="navbar-wrapper">
<div class="">
<div class="navbar navbar-inverse navbar-static-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">...</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/"><img src="/img/MultiSigX.png" alt="MultiSigX"><sup><small><strong style="color:red">beta</strong></small></sup></a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="/company/how">How it works?</a></li>
<li><a href="/company/FAQ">FAQ</a></li>
</ul>
<ul class="nav navbar-nav pull-right">
<?php if($user!=""){ ?>
<?php if($MeAdmin){?>
<li><a href="/Admin/index" class=" tooltip-x" rel="tooltip-x" data-placement="bottom" title="Admin"><i class="fa-user fa-large"></i></a></li>
<?php } ?>
<li><a href="/ex/dashboard" class=" tooltip-x" rel="tooltip-x" data-placement="bottom" title="Dashboard "><i class="fa fa-tachometer fa-2x"></i></a></li>
<li><a href="/ex/settings" class=" tooltip-x" rel="tooltip-x" data-placement="bottom" title="Settings "><i class="fa fa-gears fa-2x"></i></a></li>
<li>
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-user fa-2x"></i> <?=$user['username']?> <i class="caret"></i></a>
<ul class="dropdown-menu" style="width:200px">
<!-- User image -->
<li class="user-header bg-light-blue text-center"><br>
<?php
if($details['settings']['Gender']==""){$Picture="/img/avatar0.png";};
if($details['settings']['Gender']=="Male"){$Picture="/img/avatarM1.png";};
if($details['settings']['Gender']=="Female"){$Picture="/img/avatarF1.png";};
if($details['Picture']['name']!=""){$Picture="/documents/".$user['_id']."_".$details['Picture']['name'];};
?>
<img src="<?=$Picture?>" class="img-circle" alt="<?=$user['firstname']?> <?=$user['lastname']?>" width="150" />
<p>
<?=$user['firstname']?> <?=$user['lastname']?><br>
<small>Member since <?=gmdate('d M Y',$user['created'])?></small>
</p>
</li>
<!-- Menu Body -->
<li class="user-body">
<div class="col-xs-6 text-center">
</div>
<div class="col-xs-6 text-center">
</div>
</li>
<!-- Menu Footer-->
<li class="user-footer">
<div class="pull-left">
<a href="/ex/friends" class="btn btn-primary btn-sm btn-flat">Friends</a>
</div>
<div class="pull-right">
<a href="/logout" class="btn btn-danger btn-sm btn-flat">Sign out</a>
</div>
</li>
</ul>
</li>
<li><a href="/logout" class=" tooltip-x" rel="tooltip-x" data-placement="bottom" title="Sign Out "><i class="fa fa-power-off fa-2x"></i></a></li>
<li><a href="#" class='dropdown-toggle tooltip-x' data-toggle='dropdown' rel="tooltip-x" data-placement="bottom" title="Themes "><i class="fa fa-th fa-2x"></i></a>
<ul class="dropdown-menu">
<li><a href="#" onClick="ChangeTheme('chrome','<?=str_replace("/","_",$_SERVER['REQUEST_URI'])?>');"><i class="icon-heart-empty"></i> Chrome</a></li>
<li><a href="#" onClick="ChangeTheme('flaty','<?=str_replace("/","_",$_SERVER['REQUEST_URI'])?>');"><i class="icon-heart-empty"></i> Flaty</a></li>
<li><a href="#" onClick="ChangeTheme('lumen','<?=str_replace("/","_",$_SERVER['REQUEST_URI'])?>');"><i class="icon-heart-empty"></i> Lumen</a></li>
<li><a href="#" onClick="ChangeTheme('readable','<?=str_replace("/","_",$_SERVER['REQUEST_URI'])?>');"><i class="icon-heart-empty"></i> Readable</a></li>
<li><a href="#" onClick="ChangeTheme('dynamic','<?=str_replace("/","_",$_SERVER['REQUEST_URI'])?>');"><i class="icon-heart-empty"></i> Dynamic</a></li>
<li><a href="#" onClick="ChangeTheme('united','<?=str_replace("/","_",$_SERVER['REQUEST_URI'])?>');"><i class="icon-heart-empty"></i> United</a></li>
<li><a href="#" onClick="ChangeTheme('yeti','<?=str_replace("/","_",$_SERVER['REQUEST_URI'])?>');"><i class="icon-heart-empty"></i> Yeti</a></li>
<li><a href="#" onClick="ChangeTheme('amelia','<?=str_replace("/","_",$_SERVER['REQUEST_URI'])?>');"><i class="icon-heart-empty"></i> Amelia</a></li>
<li class="divider"></li>
<li><a href="#" onClick="ChangeTheme('default','<?=str_replace("/","_",$_SERVER['REQUEST_URI'])?>');"><i class="icon-heart"></i> Default</a></li>
</ul>
</li>
<?php }else{?>
<li><a href="/signin">Sign In</a></li>
<li><a href="/signup">Sign Up</a></li>
<?php }?>
</ul>
</div>
</div>
</div>
</div>
</div>
<file_sep>/app/views/users/signup.html.php
<?php
?>
<?php $this->form->config(array( 'templates' => array('error' => '<div style="font-size:10px;background-color:#fcf8e3;padding:1px;">{:content}</div>')));
?>
<div class="row container-fluid">
<div class="col-md-6" >
<div class="panel panel-primary">
<div class="panel-heading">Signup / Register</div>
<div class="panel-body">
<?=$this->form->create($Users,array('class'=>'form-group has-error')); ?>
<div class="form-group has-error">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-asterisk" id="FirstNameIcon"></i>
</span>
<?=$this->form->field('firstname', array('label'=>'','placeholder'=>'First Name', 'class'=>'form-control','onkeyup'=>'CheckFirstName(this.value);' )); ?>
</div>
</div>
<div class="form-group has-error">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-asterisk" id="LastNameIcon"></i>
</span>
<?=$this->form->field('lastname', array('label'=>'','placeholder'=>'Last Name', 'class'=>'form-control','onkeyup'=>'CheckLastName(this.value);' )); ?>
</div>
</div>
<div class="form-group has-error">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-asterisk" id="UserNameIcon"></i>
</span>
<?=$this->form->field('username', array('label'=>'','placeholder'=>'username', 'class'=>'form-control','onkeyup'=>'CheckUserName(this.value);' )); ?>
</div>
<p class="label label-danger">Only characters and numbers, NO SPACES</p>
</div>
<div class="form-group has-error">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-asterisk" id="EmailIcon"></i>
</span>
<?=$this->form->field('email', array('label'=>'','placeholder'=>'<EMAIL>', 'class'=>'form-control','onkeyup'=>'CheckEmail(this.value);' )); ?>
</div>
</div>
<div class="form-group has-error">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-asterisk" id="PasswordIcon"></i>
</span>
<?=$this->form->field('password', array('type' => 'password', 'label'=>'','placeholder'=>'<PASSWORD>', 'class'=>'form-control','onkeyup'=>'CheckPassword(this.value);' )); ?>
</div>
</div>
<div class="form-group has-error">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-asterisk" id="Password2Icon"></i>
</span>
<?=$this->form->field('password2', array('type' => 'password', 'label'=>'','placeholder'=>'same as above', 'class'=>'form-control','onkeyup'=>'CheckPassword(this.value);' )); ?>
</div>
</div>
<div class="form-group has-error">
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-asterisk" id="EmailIcon"></i>
</span>
<?=$this->form->field('referrer', array('label'=>'','placeholder'=>'Referrer ID', 'class'=>'form-control','value'=>$referrer )); ?>
</div>
</div>
<?=$this->form->submit('Sign up' ,array('class'=>'btn btn-primary btn-block')); ?>
<?=$this->form->end(); ?>
</div>
<div class="panel-footer">
Already registered? <a href="/signin">Signin</a>
</div>
</div>
</div>
<div class="col-md-6" >
<div class="panel panel-primary">
<div class="panel-heading">MultiSigX™ Features</div>
<div class="panel-body">
<h3>Individuals<sup>*</sup> - NOMINAL 0.001% commission</h3>
<ul>
<li>Self, Self, Print</li>
<li>Self, 2<sup>nd</sup> email, Print</li>
<li>Self, Web Wallet, Print</li>
<li>Self, 2<sup>nd</sup> email, Web Wallet</li>
</ul>
<h3>Groups<sup>*</sup> - 1% commission on withdrawal</h3>
<ul>
<li>Self, Friend/Colleague, Print</li>
<li>Self, Friend/Colleague, Friend/Colleague</li>
<li>Self, Friend/Colleague, Web Wallet</li>
<li>Self, Family, Friend/Colleague</li>
</ul>
<h3>Business<sup>*</sup> - 2% commission on withdrawal</h3>
<ul>
<li>Self Business, Business, Web Wallet</li>
<li>Self Business, Partner, Web Wallet</li>
<li>Self Business, Partner, Partner</li>
</ul>
</div>
<div class="panel-footer"><sup>*</sup><strong>2 of 3</strong> or <strong>3 of 3</strong> sign in required for security.</div>
</div>
</div>
</div><file_sep>/app/views/elements/footer.html.php
<!-- Footer -->
<footer>
<div class="container text-center ">
<p>MultiSigX is a registered name of <strong>MultiSigX Inc. Apia, Samoa</strong> Company No: 65518
<small><span class="pull-right"><?php echo number_format($pagetotaltime*1000,2); ?> ms</span></small>
</p>
</div>
</footer>
<file_sep>/app/views/users/forgot.mail.php
<div style="background-color:#eeeeee;height:50px;padding-left:20px;padding-top:10px">
<img src="https://<?=COMPANY_URL?>/img/<?=COMPANY_URL?>.png" alt="<?=COMPANY_URL?>">
</div>
<p>Please click on this link to change the password!</p>
<p><a href="https://<?=$_SERVER['HTTP_HOST'];?>/users/changepassword/<?=$key?>">https://<?=$_SERVER['HTTP_HOST'];?>/users/changepassword/<?=$key?></a></p>
<p>Thank you,</p>
<p>Support</p>
<file_sep>/README.md
MultiSigX
=========
MultiSig for Bitcoin / GreenCoin with MindWallet
<file_sep>/app/views/users/forgotpassword.html.php
<div class="row container-fluid">
<div class="col-md-6" >
<h4>Forgot password</h4>
<?=$this->form->create("",array('url'=>'/users/forgotpassword','class'=>'form-group has-error')); ?>
<?=$this->form->field('email', array('type' => 'text', 'label'=>'Your email','placeholder'=>'<EMAIL>','class'=>'form-control' )); ?> <br>
<?=$this->form->submit('Send password reset link' ,array('class'=>'btn btn-primary')); ?>
<?=$this->form->end(); ?>
</div>
</div><file_sep>/app/controllers/AdminController.php
<?php
namespace app\controllers;
use lithium\storage\Session;
use app\models\Users;
use app\models\Details;
use app\models\Parameters;
use MongoID;
use MongoDate;
use lithium\data\Connections;
class AdminController extends \lithium\action\Controller {
public function __init(){
$user = Session::read('member');
$id = $user['_id'];
$details = Details::find('first',
array('conditions'=>array('user_id'=>$id))
);
if(strtolower(str_replace("@","",strstr($user['email'],"@")))==strtolower(COMPANY_URL)
&& $details['email.verified']=="Yes"
&& (
strtolower(MAIL_1)==strtolower($user['email'])
|| strtolower(MAIL_2)==strtolower($user['email'])
|| strtolower(MAIL_3)==strtolower($user['email'])
|| strtolower(MAIL_4)==strtolower($user['email'])
)
){
return true;
}else{
return false;
}
}
public function index() {
if($this->__init()==false){$this->redirect('ex::dashboard'); }
$user = Session::read('member');
$id = $user['_id'];
if($this->request->data){
$StartDate = new MongoDate(strtotime($this->request->data['StartDate']));
$EndDate = new MongoDate(strtotime($this->request->data['EndDate']));
}else{
$StartDate = new MongoDate(strtotime(gmdate('Y-m-d H:i:s',mktime(0,0,0,gmdate('m',time()),gmdate('d',time()),gmdate('Y',time()))-60*60*24*30)));
$EndDate = new MongoDate(strtotime(gmdate('Y-m-d H:i:s',mktime(0,0,0,gmdate('m',time()),gmdate('d',time()),gmdate('Y',time()))+60*60*24*1)));
}
$mongodb = Connections::get('default')->connection;
$UserRegistrations = Users::connection()->connection->command(array(
'aggregate' => 'users',
'pipeline' => array(
array( '$project' => array(
'_id'=>0,
'created' => '$created',
)),
array( '$match' => array( 'created'=> array( '$gte' => $StartDate, '$lte' => $EndDate ) ) ),
array('$group' => array( '_id' => array(
'year'=>array('$year' => '$created'),
'month'=>array('$month' => '$created'),
'day'=>array('$dayOfMonth' => '$created'),
),
'count' => array('$sum' => 1),
)),
array('$sort'=>array(
'_id.year'=>-1,
'_id.month'=>-1,
'_id.day'=>-1,
// '_id.hour'=>-1,
)),
)
));
$TotalUserRegistrations = Users::connection()->connection->command(array(
'aggregate' => 'users',
'pipeline' => array(
array( '$project' => array(
'_id'=>0,
'created' => '$created',
)),
array('$group' => array( '_id' => array(
'year'=>array('$year' => '$created'),
),
'count' => array('$sum' => 1),
)),
array('$sort'=>array(
'_id.year'=>-1,
)),
)
));
$new = array();
$days = ($EndDate->sec - $StartDate->sec)/(60*60*24);
for($i=0;$i<=$days;$i++){
$date = gmdate('Y-m-d',($EndDate->sec)-$i*60*60*24);
$new[$date] = array();
}
foreach($UserRegistrations['result'] as $UR){
$URdate = date_create($UR['_id']['year']."-".$UR['_id']['month']."-".$UR['_id']['day']);
$urDate = date_format($URdate,"Y-m-d");
$new[$urDate] = array(
'Register'=> $UR['count']
);
}
return compact('new');
}
public function map(){
if($this->__init()==false){$this->redirect('ex::dashboard');}
if($this->__init()==true){
$mongodb = Connections::get('default')->connection;
$IPDetails = Details::connection()->connection->command(array(
'aggregate' => 'details',
'pipeline' => array(
array( '$project' => array(
'_id'=>0,
'ip' => '$lastconnected.IP',
'iso' => '$lastconnected.ISO',
)),
array('$group' => array( '_id' => array(
'iso'=> '$iso',
),
'count' => array('$sum' => 1),
)),
)
));
$details = Details::find('all',array(
'conditions'=>array('lastconnected.loc'=>array('$exists'=>true)),
'fields'=>array('lastconnected.loc','lastconnected.ISO'),
'sort'=>array('lastconnected.ISO'=>'ASC')
));
}
return compact('IPDetails','details');
}
public function down(){
if($this->__init()==false){ $this->redirect('ex::dashboard'); }
if($this->__init()==true){
$data = array(
'server' => (boolean)false
);
Parameters::find('all')->save($data);
}
return compact('$data');
}
public function up(){
if($this->__init()==false){ $this->redirect('ex::dashboard'); }
if($this->__init()==true){
$data = array(
'server' => (boolean)true
);
Parameters::find('all')->save($data);
}
return compact('$data');
}
public function CheckServer(){
if($this->__init()==true){
return $this->render(array('json' => array(
'Refresh'=> 'Yes',
)));
}
if($this->__init()==false){
$parameters = Parameters::find('first');
if($parameters['server']==true){
return $this->render(array('json' => array(
'Refresh'=> 'Yes',
)));
}else{
return $this->render(array('json' => array(
'Refresh'=> 'No',
)));
}
}
}
}
?><file_sep>/app/views/users/confirm.mail.php
<div style="background-color:#eeeeee;height:50px;padding-left:20px;padding-top:10px">
<img src="https://<?=COMPANY_URL?>/img/<?=COMPANY_URL?>.png" alt="<?=COMPANY_URL?>">
</div>
<h4>Hi <?=$name?>,</h4>
<p>Please confirm your email address associated at <?=COMPANY_URL?> by clicking the following link:</p>
<p><a href="https://<?=$_SERVER['HTTP_HOST'];?>/users/confirm/<?=$email?>/<?=$verification?>">
https://<?=$_SERVER['HTTP_HOST'];?>/users/confirm/<?=$email?>/<?=$verification?></a></p>
<p>Or use this confirmation code: <?=$verification?> for your email address: <?=$email?> on the page
https://<?=$_SERVER['HTTP_HOST'];?>/users/email</p>
<p>Username: <strong><?=$username?></strong><br>
Your username is Case Sensitive!
</p>
<p>Thanks,<br>
<?=NOREPLY?></p>
<p>P.S. Please do not reply to this email. </p>
<p>This email was sent to you as you tried to register on <?=COMPANY_URL?> with the email address.
If you did not register, then you can delete this email.</p>
<p>We do not spam. </p>
<file_sep>/app/models/Currencies.php
<?php
namespace app\models;
class Currencies extends \lithium\data\Model {
}
?><file_sep>/app/models/Commissions.php
<?php
namespace app\models;
class Commissions extends \lithium\data\Model {
}
?><file_sep>/app/views/users/review.html.php
<div class="row">
<div class="col-md-6" >
<h4>Review</h4>
<?=$this->form->create(null,array('class'=>'form-group has-error')); ?>
<?=$this->form->field('review.title', array('label'=>'Title','placeholder'=>'Title of the review','class'=>'form-control')); ?><br>
<?=$this->form->textarea('review.text', array('label'=>'Your review','class'=>'form-control','style'=>'height:200px')); ?><br>
<?=$this->form->hidden('review.datetime.date',array('value'=>gmdate('Y-m-d',time())));?>
<?=$this->form->hidden('review.datetime.time',array('value'=>gmdate('H:i:s',time())));?>
<?=$this->form->submit('Review',array('class'=>'btn btn-primary')); ?>
<?=$this->form->end(); ?>
</div>
<div class="col-md-6">
<h4>Recent reviews:</h4>
<?php
foreach($reviews as $review){?>
<blockquote>
<h5><?=$review['review.title'];?></h5>
<p><?=$review['review.text'];?></p>
<small><cite title="<?=$review['username'];?>"><?=$review['username'];?></cite> <?=$review['review.datetime.date'];?></small>
</blockquote>
<?php
}
?>
</div>
</div><file_sep>/app/views/ex/address.html.php
<div class="row container-fluid">
<?php echo $this->_render('element', 'sidebar-menu');?>
<div class="white">
<div class="col-md-9 container-fluid" >
<div class="panel panel-success">
<div class="panel-heading"><a href="/ex/dashboard">Dashboard <i class="fa-chevron-left fa"></i></a>
Address: <?=$addresses['msxRedeemScript']['address']?> <?=$addresses['currencyName']?> <?=$addresses['currency']?></div>
<div class="panel-body">
<div class="row" style="margin:10px">
<div class="col-md-12" style="border:1px solid gray;padding:10px " >
<table class="table table-striped table-condensed table-bordered">
<tr>
<th>Name</th>
<td><a href="/ex/name/<?=$addresses['name']?>"><?=$addresses['name']?></a>: <?=$addresses['CoinName']?></td>
</tr>
<tr>
<th>MultiSigX</th>
<td class="wrapword"><strong class=" tooltip-x" rel="tooltip-x" data-placement="top" title="Use this address for deposit and control of your coins"><?=$addresses['msxRedeemScript']['address']?></strong></td>
</tr>
<tr>
<th>Security</th>
<td><strong><?=$addresses['security']?></strong> of 3</td>
</tr>
<tr>
<th>redeemScript</th>
<td class="wrapword">{"<?=$addresses['msxRedeemScript']['redeemScript']?>"}</td>
</tr>
</table>
<div class="table-responsive">
<table class="table table-striped table-condensed table-bordered">
<tr>
<th>Email</th>
<th><span class=" tooltip-x" rel="tooltip-x" data-placement="top" title="This address should be used for reciving withdrawal of funds from MultiSigX address"><?=$addresses['currencyName']?> Address: <?=$addresses['currency']?></span></th>
<th>Verified</th>
<th>Relation</th>
</tr>
<?php
foreach($data as $d){?>
<tr>
<td><?=$d['email']?></td>
<td><?=$d['address']?></td>
<td><?=$d['username']?></td>
<td><?=$d['relation']?></td>
</tr>
<?php }?>
</table>
</div>
</div>
</div>
</div>
<div class="panel-footer"></div>
</div>
</div>
</div>
</div><file_sep>/app/views/ex/settings.html.php
<?php
use li3_qrcode\extensions\action\QRcode;
use app\models\Countries;
?>
<div class="row container-fluid">
<?php echo $this->_render('element', 'sidebar-menu');?>
<div class="col-md-9 container-fluid" >
<div class="panel panel-primary">
<div class="panel-heading">Settings</div>
<div class="panel-body">
<div class="panel panel-primary">
<div class="panel-heading">Referral Program</div>
<div class="panel-body">
<h3>Refer link:</h3>
<blockquote>
By referring friends you can reduce the commission percent.
<table class="table table-condensed table-hover" style="text-align:center">
<tr>
<th width="25%">#</th>
<th width="25%" style="text-align:center">Level 1</th>
<th width="25%" style="text-align:center">Level 2 above</th>
</tr>
<?php foreach ($commissions as $commission){?>
<tr>
<th><?=$commission['min']?> to <?=$commission['max']?></th>
<td><?=$commission['Level'][0]?></td>
<td><?=$commission['Level'][1]?></td>
</tr>
<?php }?>
<tr class="success">
<th>Your friends</th>
<td><?=$levelOne?></td>
<td><?=$countChild-$levelOne?></td>
</tr>
</table>
</blockquote>
<h4>Link</h4>
<p>https://<?=COMPANY_URL?>/signup/?r=<?=$details['bitcoinaddress']?></p>
<a href="mailto:?&body=https://<?=COMPANY_URL?>/signup/?r=<?=$details['bitcoinaddress']?>&subject=MultiSigX Refer">Send email</a>
</div>
</div>
<div class="panel panel-primary">
<div class="panel-heading">Personal</div>
<div class="panel-body">
<div class="col-md-12 ">
<?=$this->form->create(null,array('class'=>'form-group has-error','id'=>'MSXSettingForm')); ?>
<h4>Gender</h4>
<input type="radio" name="Gender" id="GenderMale" <?php if($details['settings']['Gender']=="Male"){echo " checked ";}?> value="Male" /> Male
<input type="radio" name="Gender" id="GenderFemale" <?php if($details['settings']['Gender']=="Female"){echo " checked ";}?> value="Female" /> Female<br>
<h4>Mobile Phone</h4>
<?php $countries = Countries::find('all',array(
'conditions'=>array('Phone'=>array('$ne'=>'00')),
'order'=>array('Country'=>1)
));?>
<select name="Country" id="Country" class="form-control" onchange="changeFlag(this.value);">
<?php foreach($countries as $country){?>
<option value="<?=$country['ISO']?>"
<?php if($details['settings']['Country']==$country['ISO']){echo " selected ";}?>><?=$country['Country']?></option>
<?php }?>
</select><br>
<span><img src="/img/Flags/<?=strtolower($details['settings']['Country'])?>.gif" width="100" height="60" id="ImageFlag" style="border:1px solid black;padding:2px"></span><br><br>
<input type="tel" name="mobile" id="mobile" placeholder="9999999999" value="<?=$details['settings']['mobile']?>" class="form-control" /><br>
<input type="submit" id="SubmitButton" class="btn btn-primary" value="Save" onClick='$("#SubmitButton").attr("disabled", "disabled");'><br>
<?=$this->form->end(); ?>
</div>
</div>
</div>
<div class="panel panel-primary">
<div class="panel-heading">Validate Mobile</div>
<div class="panel-body">
<div class="col-md-12 ">
<?php if($details['SMSVerified']=="Yes"){?>
<button href="#" class="btn btn-primary" >Mobile verified</button><br><br>
<?php }else{?>
<button href="#" class="btn btn-primary" onclick="sendSMS();" id="SMSSending">Send SMS to mobile</button><br><br>
<label class="control-label" for="wallet-google-conf-code">Validate Mobile</label><br>
<div class="alert alert-success hidden" id="SuccessTOTP">Mobile Validated</div>
<div class="input-group" id="EnterMobileCode">
<input class="form-control" required="required" maxlength="6" pattern="[0-9]{6}" id="CheckMobileCode" placeholder="Mobile Code" type="password">
<span class="input-group-btn">
<button type="button" class="btn btn-primary" onClick="CheckMobile();">Check Mobile</button>
</span>
</div><br>
<?php }?>
<span id="ErrorMobile" class="alert alert-danger hidden">Mobile Code not correct</span>
</div>
</div>
</div>
<div class="panel panel-primary">
<div class="panel-heading">Upload Picture</div>
<div class="panel-body">
<div class="col-md-12 ">
<?=$this->form->create(null,array('url'=>'/ex/savepicture','class'=>'form-group has-error','id'=>'MSXPictureSettingForm','type'=>'file')); ?>
<label for="Picture">Your picture</label>
<input id="Picture" name="Picture" type="file" />
<p class="help-block">Your picture should be jpg, png, gif with max size 300x300 px</p>
<?php
$filename = "imagename_address";
if($$filename!=""){?>
<img src="/documents/<?=$$filename?>" width="300px" style="padding:1px;border:1px solid black">
<?php }?>
<br><br>
<input type="submit" id="PictureSubmitButton" class="btn btn-primary" value="Save" onClick='$("#PictureSubmitButton").attr("disabled", "disabled");'><br>
<?=$this->form->end(); ?>
</div>
</div>
</div>
<div class="panel panel-danger">
<div class="panel-heading">Security API</div>
<div class="panel-body">
Key: <code><?=$details['key']?></code> use this key to access the API.
</div>
</div>
<div class="panel panel-danger">
<div class="panel-heading">Security</div>
<div class="panel-body">
<h4>Google TOTP<br>(Time based One Time Password)</h4>
<ol>
<li><strong>Install app:</strong>
Install the app on your device. For Android at <a href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2" target="_blank">Google play</a> while for iOS at <a href="https://itunes.apple.com/en/app/google-authenticator/id388497605?mt=8" target="_blank">Apple Store</a>.
</li>
<li><strong>Add account:</strong>
Add an account to the Google Authenticator App and scan the QR code or manually enter exact code.</li>
<li><strong>Confirm code:</strong>
Google Authenticator will now show a number which in order to complete the two factor setup you need to enter below. </li>
</ol>
<p>The QR code for Google Authenticator access to your wallet is:</p>
<img src="<?=$qrCodeUrl?>" scrolling="no" height="200px" /><br>
<p>You can also copy the code manually:</p>
<?=$details['secret']?>
<form role="form" class="form-horizontal ">
<div class="form-group col-xs-12">
<div class="col-md-4 ">
<label class="control-label" for="wallet-google-conf-code">Authenticator code</label><br>
<div class="alert alert-success hidden" id="SuccessTOTP">TOTP Authenticated</div>
<div class="input-group" id="EnterTOTP">
<input class="form-control" required="required" maxlength="6" pattern="[0-9]{6}" id="CheckCode" placeholder="Please enter received code" type="password">
<span class="input-group-btn">
<button type="button" class="btn btn-primary" onClick="CheckTOTP();">Enable TOTP</button>
</span>
</div><br>
<span id="ErrorTOTP" class="alert alert-danger hidden">TOTP not correct</span>
</div>
</div>
</form>
</div>
</div>
<div class="panel panel-danger">
<div class="panel-heading">Password</div>
<div class="panel-body">
<h4>Change Password</h4>
<?=$this->form->create("",array('url'=>'/ex/password/','role'=>'form','class'=>'form-horizontal')); ?>
<div class="col-md-4 ">
<?=$this->form->field('oldpassword', array('type' => '<PASSWORD>', 'label'=>'Old Password','placeholder'=>'<PASSWORD>','class'=>'form-control')); ?>
<?=$this->form->field('password', array('type' => '<PASSWORD>', 'label'=>'New Password','placeholder'=>'<PASSWORD>','class'=>'form-control' )); ?>
<?=$this->form->field('password2', array('type' => 'password', 'label'=>'Repeat new password','placeholder'=>'same as above','class'=>'form-control' )); ?>
<?=$this->form->hidden('key', array('value'=>$details['key']))?><br>
<?=$this->form->submit('Change' ,array('class'=>'btn btn-primary')); ?>
</div>
<?=$this->form->end(); ?>
</div>
</div>
</div>
<div class="panel-footer">
</div>
</div>
</div>
</div><file_sep>/app/controllers/UsersController.php
<?php
namespace app\controllers;
use app\extensions\action\OAuth2;
use app\models\Pages;
use app\models\Users;
use app\models\Details;
use app\models\Addresses;
use app\models\Parameters;
use app\models\Settings;
use app\models\Countries;
use app\models\Greenblocks;
use app\models\Bitblocks;
use app\models\File;
use lithium\data\Connections;
use app\extensions\action\Functions;
use app\extensions\action\Bitcoin;
use app\extensions\action\Litecoin;
use app\extensions\action\Greencoin;
use lithium\security\Auth;
use lithium\storage\Session;
use app\extensions\action\GoogleAuthenticator;
use li3_qrcode\extensions\action\QRcode;
use lithium\util\String;
use MongoID;
use \lithium\template\View;
use \Swift_MailTransport;
use \Swift_Mailer;
use \Swift_Message;
use \Swift_Attachment;
class UsersController extends \lithium\action\Controller {
public function index(){
}
public function signup() {
if($this->request->query[r]!=""){
$referrer = $this->request->query[r];
}
if($this->request->data) {
$Users = Users::create($this->request->data);
$saved = $Users->save();
if($saved==true){
$verification = sha1($Users->_id);
$bitcoin = new Bitcoin('http://'.BITCOIN_WALLET_SERVER.':'.BITCOIN_WALLET_PORT,BITCOIN_WALLET_USERNAME,BITCOIN_WALLET_PASSWORD);
$bitcoinaddress = $bitcoin->getaccountaddress("MSX-".$this->request->data['username']);
// $oauth = new OAuth2();
// $key_secret = $oauth->request_token();
$ga = new GoogleAuthenticator();
if($this->request->data['referrer']!=""){
$refer = Details::first(array(
'fields'=>array('left','user_id','ancestors','username'),
'conditions'=>array('bitcoinaddress'=>$this->request->data['referrer'])
));
$refer_ancestors = $refer['ancestors'];
$ancestors = array();
foreach ($refer_ancestors as $ra){
array_push($ancestors, $ra);
}
$refer_username = (string) $refer['username'];
array_push($ancestors,$refer_username);
$refer_id = (string) $refer['user_id'];
$refer_left = (integer)$refer['left'];
$refer_left_inc = (integer)$refer['left'];
$refername = Users::find('first',array(
'fields'=>array('firstname','lastname'),
'conditions'=>array('_id'=>$refer['user_id'])
));
$refer_name = $refername['firstname'].' '.$refername['lastname'];
}else{
$refer_left = 0;
$refer_name = "";
$refer_username = "";
$refer_id = "";
$ancestors = array();
}
Details::update(
array(
'$inc' => array('right' => (integer)2)
),
array('right' => array('>'=>(integer)$refer_left_inc)),
array('multi' => true)
);
Details::update(
array(
'$inc' => array('left' => (integer)2)
),
array('left' => array('>'=>(integer)$refer_left_inc)),
array('multi' => true)
);
$data = array(
'user_id'=>(string)$Users->_id,
'username'=>(string)$Users->username,
'email.verify' => $verification,
'mobile.verified' => "No",
'mobile.number' => "",
'key'=>$ga->createSecret(64),
'secret'=>$ga->createSecret(64),
'Friend'=>array(),
'bitcoinaddress'=>$bitcoinaddress,
'refer'=>$Users->referrer,
'refer_name'=>$refer_name,
'refer_username'=>$refer_username,
'refer_id'=>$refer_id,
'ancestors'=> $ancestors,
'left'=>(integer)($refer_left+1),
'right'=>(integer)($refer_left+2),
);
Details::create()->save($data);
$email = $this->request->data['email'];
$name = $this->request->data['firstname'];
$username = (string)$Users->username;
$view = new View(array(
'loader' => 'File',
'renderer' => 'File',
'paths' => array(
'template' => '{:library}/views/{:controller}/{:template}.{:type}.php'
)
));
$body = $view->render(
'template',
compact('email','verification','name','username'),
array(
'controller' => 'users',
'template'=>'confirm',
'type' => 'mail',
'layout' => false
)
);
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance();
$message->setSubject("Verification of email from ".COMPANY_URL);
$message->setFrom(array(NOREPLY => 'Verification email '.COMPANY_URL));
$message->setTo($Users->email);
$message->addBcc(MAIL_1);
$message->addBcc(MAIL_2);
$message->addBcc(MAIL_3);
$message->setBody($body,'text/html');
$mailer->send($message);
$this->redirect('Users::email');
}
}
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('title','keywords','description','saved','Users','referrer');
}
public function email(){
$user = Session::read('member');
$id = $user['_id'];
$details = Details::find('first',
array('conditions'=>array('user_id'=>$id))
);
if(isset($details['email']['verified'])){
$msg = "Your email is verified.";
}else{
$msg = "Your email is <strong>not</strong> verified. Please check your email to verify.";
}
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('title','keywords','description','msg');
}
public function emailConfirmed(){}
public function confirm($email=null,$verify=null){
if($email == "" || $verify==""){
if($this->request->data){
if($this->request->data['email']=="" || $this->request->data['verified']==""){
return $this->redirect('Users::email');
}
$email = $this->request->data['email'];
$verify = $this->request->data['verified'];
}else{return $this->redirect('Users::email');}
}
$finduser = Users::first(array(
'conditions'=>array(
'email' => $email,
)
));
$id = (string) $finduser['_id'];
if($id!=null){
$data = array('email.verified'=>'Yes');
Details::create();
$details = Details::find('all',array(
'conditions'=>array('user_id'=>$id,'email.verify'=>$verify)
))->save($data);
if(empty($details)==1){
return $this->redirect('Users::email');
}else{
return $this->redirect('Users::emailConfirmed');
}
}else{return $this->redirect('Users::email');}
}
public function SendPassword($username=""){
$users = Users::find('first',array(
'conditions'=>array('username'=>$username)
));
$id = (string)$users['_id'];
if($id==""){
return $this->render(array('json' => array("Password"=>"<PASSWORD>","TOTP"=>"No")));
}
$ga = new GoogleAuthenticator();
$secret = $ga->createSecret(64);
$details = Details::find('first',array(
'conditions'=>array('username'=>$username,'user_id'=>(string)$id)
));
if($details['oneCodeused']=='Yes' || $details['oneCodeused']==""){
$oneCode = $ga->getCode($secret);
$data = array(
'oneCode' => $oneCode,
'oneCodeused' => 'No'
);
$details = Details::find('all',array(
'conditions'=>array('username'=>$username,'user_id'=>(string)$id)
))->save($data);
}
$details = Details::find('first',array(
'conditions'=>array('username'=>$username,'user_id'=>(string)$id)
));
$oneCode = $details['oneCode'];
$totp = "No";
if($details['TOTP.Validate']==true && $details['TOTP.Login']==true){
$totp = "Yes";
}
$view = new View(array(
'loader' => 'File',
'renderer' => 'File',
'paths' => array(
'template' => '{:library}/views/{:controller}/{:template}.{:type}.php'
)
));
$email = $users['email'];
$body = $view->render(
'template',
compact('users','oneCode','username'),
array(
'controller' => 'users',
'template'=>'onecode',
'type' => 'mail',
'layout' => false
)
);
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance();
$message->setSubject("Sign in password for ".COMPANY_URL);
$message->setFrom(array(NOREPLY => 'Sign in password from '.COMPANY_URL));
$message->setTo($email);
$message->setBody($body,'text/html');
$mailer->send($message);
return $this->render(array('json' => array("Password"=>"<PASSWORD>","TOTP"=>$totp)));
}
public function username($username=null){
$usercount = Users::find('all',array(
'conditions'=>array('username'=>$username)
));
if(count($usercount)==0){
$Available = 'Yes';
}else{
$Available = 'No';
}
return $this->render(array('json' => array(
'Available'=> $Available,
)));
}
public function signupemail($email=null){
$usercount = Users::find('all',array(
'conditions'=>array('email'=>$email)
));
if(count($usercount)==0){
$Available = 'Yes';
}else{
$Available = 'No';
}
return $this->render(array('json' => array(
'Available'=> $Available,
)));
}
public function forgotpassword(){
if($this->request->data){
$user = Users::find('first',array(
'conditions' => array(
'email' => $this->request->data['email']
),
'fields' => array('_id')
));
$email = $user['email'];
// print_r($user['_id']);
$details = Details::find('first', array(
'conditions' => array(
'user_id' => (string)$user['_id']
),
'fields' => array('key')
));
// print_r($details['key']);exit;
$key = $details['key'];
if($key!=""){
$email = $this->request->data['email'];
$view = new View(array(
'loader' => 'File',
'renderer' => 'File',
'paths' => array(
'template' => '{:library}/views/{:controller}/{:template}.{:type}.php'
)
));
$body = $view->render(
'template',
compact('email','key'),
array(
'controller' => 'users',
'template'=>'forgot',
'type' => 'mail',
'layout' => false
)
);
$transport = Swift_MailTransport::newInstance();
$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance();
$message->setSubject("Password reset link from ".COMPANY_URL);
$message->setFrom(array(NOREPLY => 'Password reset email '.COMPANY_URL));
$message->setTo($email);
$message->addBcc(MAIL_1);
$message->addBcc(MAIL_2);
$message->addBcc(MAIL_3);
$message->setBody($body,'text/html');
$mailer->send($message);
}
}
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('title','keywords','description');
}
public function CreateQRCode($address=null){
$qrcode = new QRcode();
$qrcode->png($address, QR_OUTPUT_DIR.$address.".png", 'H', 7, 2);
return $this->render(array('json' => array("QRCode"=>$address)));
}
public function CheckBalance($address=null,$name=null,$local=null){
if ($name==""){return $this->render(array('json' => array("CheckBalance"=>false)));}
// $address = '1Czx5pXiQ2Qk4hFqvXvnWgnuRUKza8pdNN';
switch ($name){
case "Bitcoin":
$url = "https://".BITCOIN_WEB."/address/".$address."?format=json";
$currency = "BTC";
break;
case "GreenCoin":
$url = "http://".GREENCOIN_WEB."/blockchain/address/".$address."/json";
$currency = "GreenCoin";
break;
}
$opts = array(
'http'=> array(
'method'=> "GET",
'user_agent'=> "MozillaXYZ/1.0"));
$context = stream_context_create($opts);
$json = file_get_contents($url, false, $context);
$jdec = json_decode($json);
$total_rec = ($jdec->total_received/100000000);
$total_sent = ($jdec->total_sent/100000000);
if($local===true){
$final = ($total_rec-$total_sent);
return compact('final');
}
$n_tx = $jdec->n_tx;
$data = array();$i=0;
foreach($jdec->txs as $tx){
$j=0;
if(count($tx->inputs)>0){
foreach($tx->inputs as $input){
$data[$i]['out'][$j]['addr']=$input->prev_out->addr;
$data[$i]['out'][$j]['value']=$input->prev_out->value;
$data[$i]['out'][$j]['spent']=(int)$input->prev_out->spent;
$data[$i]['out'][$j]['script']=$input->prev_out->script;
$j++;
}
}
$j=0;
if(count($tx->out)>0){
foreach($tx->out as $out){
$data[$i]['in'][$j]['addr']=$out->addr;
$data[$i]['in'][$j]['value']=$out->value;
$data[$i]['in'][$j]['spent']=(int)$out->spent;
$data[$i]['in'][$j]['script']=$out->script;
$j++;
}
}
$i++;
}
//print_r($data) ;
$html = '<table class="table table-striped table-condensed table-bordered">
<tr>
<td>No. Transactions</td>
<td>'.$n_tx.'</td>
</tr>
<tr>
<td>Total Received</td>
<td>'.$total_rec.' '.$name.'</td>
</tr>
<tr>
<td>Final Balance</td>
<td>'.($total_rec-$total_sent).' '.$name.'</td>
</tr>
</table>
<table class="table table-striped table-condensed table-bordered" style="font-size:13px">';
foreach($data as $tx){
$html = $html . "<tr>";
$html = $html . "<td>";
if(count($tx['out'])>0){
foreach($tx['out'] as $t){
if($t['addr']==$address){
$html = $html . '<strong>'.$t['addr'].'</strong>';
}else{
$html = $html . $t['addr'];
}
$html = $html . "</br>";
$html = $html . $t['value'];
$html = $html . "</br>";
}
}
$html = $html . "</td>";
$html = $html . "<td><code>";
foreach($tx['in'] as $t){
if($t['addr']==$address){
$html = $html . '<strong>'.$t['addr'].'</strong>';
}else{
$html = $html . $t['addr'];
}
$html = $html . "</br>";
$html = $html . $t['value'];
$html = $html . "</br>";
}
$html = $html . "</code></td>";
$html = $html . "</tr>";
}
$html = $html .'</table>';
return $this->render(array('json' => array("html"=>$html,"name"=>$name)));
}
public function ChangeTheme($name=null,$uri=null){
if ($name==""){return $this->render(array('json' => array("ChangeTheme"=>false)));}
$user = Session::read('default');
$data = array("theme"=>$name);
$conditions = array("user_id"=>$user["_id"]);
$details = Details::update($data,$conditions);
$uri = str_replace("_","/",$uri);
return $this->render(array('json' => array("uri"=>$uri)));
}
public function Reviews(){
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
$reviews = Details::find('all',array(
'fields'=>array('review','username','user_id'),
'conditions'=>array('review.title'=>array('$gt'=>'')),
'order'=>array('review.datetime.date'=>'DESC','review.datetime.time'=>'DESC'),
'limit'=>$limit
));
$mongodb = Connections::get('default')->connection;
$point = Details::connection()->connection->command(array(
'aggregate' => 'details',
'pipeline' => array(
array( '$project' => array(
'_id'=>0,
'point' => '$review.points.point',
'user_id'=>'$user_id',
'username'=>'$username'
)),
array('$group' => array( '_id' => array(
'user_id'=>'$user_id',
'username'=>'$username',
),
'point' => array('$sum' => '$point'),
)),
)
));
$average = Details::connection()->connection->command(array(
'aggregate' => 'details',
'pipeline' => array(
array( '$project' => array(
'_id'=>0,
'point' => '$review.points.point',
'user_id'=>'$user_id',
'username'=>'$username'
)),
array('$group' => array( '_id' => array(
'user_id'=>'$user_id',
'username'=>'$username',
),
'point' => array('$avg' => '$point'),
)),
)
));
return compact('title','keywords','description','reviews','point','average');
}
public function review(){
$user = Session::read('default');
if ($user==""){ return $this->redirect('Users::signup');}
if($this->request->data){
Details::find('all',array(
'conditions'=>array('user_id'=>$user['_id'])
))->save($this->request->data);
return $this->redirect('Users::reviews');
}
$reviews = Details::find('all',array(
'fields'=>array('review','username'),
'conditions'=>array('review.title'=>array('$gt'=>'')),
'order'=>array('review.datetime.date'=>'DESC'),
'limit'=>2
));
$page = Pages::find('first',array(
'conditions'=>array('pagename'=>$this->request->controller.'/'.$this->request->action)
));
$title = $page['title'];
$keywords = $page['keywords'];
$description = $page['description'];
return compact('title','keywords','description','reviews');
}
public function DeleteCoin($address=null){
$user = Session::read('default');
if ($user==""){ return $this->redirect('Users::signup');}
if($address!=""){
$conditions = array('msxRedeemScript.address'=>$address);
$address= Addresses::remove($conditions);
}
$uri = "/ex/dashboard";
return $this->render(array('json' => array("Deleted"=>"Yes","uri"=>$uri)));
}
public function createTrans(){
$user = Session::read('default');
if ($user==""){ return $this->redirect('Users::signup');}
if($this->request->data){
$multiAddress = $this->request->data['address'];
$addresses = Addresses::find('first',array(
'conditions'=>array('msxRedeemScript.address'=>$multiAddress)
));
$Amount[0] = $this->request->data['sendAmount'][0];
$Amount[1] = $this->request->data['sendAmount'][1];
$Amount[2] = $this->request->data['sendAmount'][2];
$Address[0] = $this->request->data['sendToAddress'][0];
$Address[1] = $this->request->data['sendToAddress'][1];
$Address[2] = $this->request->data['sendToAddress'][2];
$TxFee = $this->request->data['SendTrxFee'];
$ChangeAddressValue = $this->request->data['ChangeAddressValue'];
$ChangeAmountValue = $this->request->data['ChangeAmountValue'];
$finalBalance = $this->request->data['finalBalance'];
$Commission = $this->request->data['commission'];
$CommissionValue = $this->request->data['CommissionTotal'];
$currency = $this->request->data['currency'];
$calcBalance = round($Amount[0]+$Amount[1]+$Amount[2]+$ChangeAmountValue+$TxFee+$CommissionValue,8);
if(round($finalBalance,8)!=$calcBalance){
return $this->redirect(array('controller'=>'ex','action'=>'withdraw/'.$multiAddress.'/create/No'));
}
switch ($currency){
case "BTC":
$coin = new Bitcoin('http://'.BITCOIN_WALLET_SERVER.':'.BITCOIN_WALLET_PORT,BITCOIN_WALLET_USERNAME,BITCOIN_WALLET_PASSWORD);
$currencyName = "Bitcoin";
$opts = array(
'http'=> array(
'method'=> "GET",
'user_agent'=> "MozillaXYZ/1.0"));
$context = stream_context_create($opts);
$json = file_get_contents('http://blockchain.info/address/'.$multiAddress.'/?format=json', false, $context);
$function = new Functions();
$jdec = $function->objectToArray(json_decode($json));
// print_r($jdec);
foreach($jdec['txs'] as $txid){
foreach($txid->out as $out){
if($out->addr == $multiAddress){
$x_txid = $txid->hash;
$x_value = $out->value;
$x_vout = $out->n;
$x_scriptPubKey = $out->script;
}
}
}
/* print_r("script=".$x_scriptPubKey);
print_r("value=".$x_value);
print_r("out=".$x_vout);
print_r("txid=".$x_txid);exit;
*/
$wallet_address = BITCOIN_WALLET_ADDRESS;
break;
case "XGC":
$coin = new Greencoin('http://'.GREENCOIN_WALLET_SERVER.':'.GREENCOIN_WALLET_PORT,GREENCOIN_WALLET_USERNAME,GREENCOIN_WALLET_PASSWORD);
$currencyName = "GreenCoin";
$transaction = Greenblocks::find("first",array(
"conditions"=>array("txid.vout.scriptPubKey.addresses"=>$multiAddress)
));
$wallet_address = GREENCOIN_WALLET_ADDRESS;
foreach($transaction['txid'] as $txid){
foreach($txid['vout'] as $vout){
foreach($vout['scriptPubKey']['addresses'] as $address){
if($address == $multiAddress){
$x_txid = $txid['txid'];
$x_vout = $vout['n'];
$x_value = $vout['value'];
$x_scriptPubKey = $vout['scriptPubKey']['hex'];
}
}
}
}
break;
}
// bitcoin.createrawtransaction ([{"txid":unspent[WhichTrans]["txid"],
// "vout":unspent[WhichTrans]["vout"],
// "scriptPubKey":unspent[WhichTrans]["scriptPubKey"],
// "redeemScript":unspent[WhichTrans]["redeemScript"]}],
// {SendAddress:HowMuch/100000000.00,ChangeAddress:Leftover/100000000.00})
$createTrans = array(
'txid'=>$x_txid,
'vout'=>$x_vout,
'scriptPubKey'=>$x_scriptPubKey,
'redeemScript'=>$addresses['msxRedeemScript']['redeemScript'],
);
$createData = array($wallet_address=>round($CommissionValue,8));
if($Amount[0]>0 && $Address[0]!=""){
$createData = array_merge_recursive($createData,array($Address[0]=>round($Amount[0],8)));
}
if($Amount[1]>0 && $Address[1]!=""){
$createData = array_merge_recursive($createData,array($Address[1]=>round($Amount[1],8)));
}
if($Amount[2]>0 && $Address[2]!=""){
$createData = array_merge_recursive($createData,array($Address[2]=>round($Amount[2],8)));
}
if($ChangeAmountValue>0){
$createData = array_merge_recursive($createData,array($ChangeAddressValue=>round($ChangeAmountValue,8)));
}
// print_r($createData);
// print_r($createTrans);
$createrawtransaction = $coin->createrawtransaction(array($createTrans),$createData);
if(is_array($createrawtransaction)){
return compact('createrawtransaction');
}else{
$data = array(
'createTrans'=>$createrawtransaction,
'createTran.DateTime'=>new \MongoDate(),
'createTran.IP'=>$_SERVER['REMOTE_ADDR'],
'createTran.username'=>$user['username'],
'createTran.user_id'=>$user['_id'],
'createTran.withdraw.address.0' => $Address[0],
'createTran.withdraw.amount.0' => round($Amount[0],8),
'createTran.withdraw.address.1' => $Address[1],
'createTran.withdraw.amount.1' => round($Amount[1],8),
'createTran.withdraw.address.2' => $Address[2],
'createTran.withdraw.amount.2' => round($Amount[2],8),
'createTran.withdraw.changeAddress' => $ChangeAddressValue,
'createTran.withdraw.changeAmount' => round($ChangeAmountValue,8),
'createTran.commission_amount' => round($CommissionValue,8),
'createTran.tx_fee' => round($this->request->data['SendTrxFee'],8),
);
$conditions = array('msxRedeemScript.address'=>$multiAddress);
Addresses::update($data,$conditions);
$addresses = Addresses::find('first',array(
'conditions'=>array('msxRedeemScript.address'=>$multiAddress)
));
$email = array();
$relation = array();
foreach($addresses['addresses'] as $address){
array_push($email,$address['email']);
array_push($relation,$address['relation']);
}
$data = array(
'who'=>$user,
'currency'=>$currency,
'currencyName'=>$currencyName,
'multiAddress'=>$multiAddress,
'security'=>$addresses['security'],
'name'=>$addresses['name'],
'CoinName'=>$addresses['CoinName'],
'DateTime'=>$addresses['DateTime'],
'emails'=>$email,
'txid'=>$x_txid,
'relation'=>$relation,
'withdraw.address.0' => $Address[0],
'withdraw.amount.0' => round($Amount[0],8),
'withdraw.address.1' => $Address[1],
'withdraw.amount.1' => round($Amount[1],8),
'withdraw.address.2' => $Address[2],
'withdraw.amount.2' => round($Amount[2],8),
'withdraw.changeAddress' => $ChangeAddressValue,
'withdraw.changeAmount' => round($ChangeAmountValue,8),
'commission_amount' => round($CommissionValue,8),
'tx_fee' => round($this->request->data['SendTrxFee'],8),
'createTrans' => $createTrans,
'createrawtransaction' => $createrawtransaction,
);
foreach($data['emails'] as $email){
// sending email to the users
/////////////////////////////////Email//////////////////////////////////////////////////
$function = new Functions();
$compact = array('data'=>$data);
// sendEmailTo($email,$compact,$controller,$template,$subject,$from,$mail1,$mail2,$mail3)
$from = array(NOREPLY => "noreply@".COMPANY_URL);
$email = $email;
$attach = null;
$function->sendEmailTo($email,$compact,'users','createTrans',"MultiSigX.com create transaction",$from,'','','',$attach);
/////////////////////////////////Email//////////////////////////////////////////////////
}
} // if $createrawtransaction
}
// print_r($data);
return $this->redirect(array('controller'=>'Ex','action'=>'withdraw/'.$multiAddress.'/sign'));
}
public function signTrans(){
$user = Session::read('default');
if ($user==""){ return $this->redirect('Users::signup');}
if($this->request->data){
$multiAddress = $this->request->data['address'];
$currency = $this->request->data['currency'];
$privKey = $this->request->data['privKey'];
$addresses = Addresses::find('first',array(
'conditions'=>array('msxRedeemScript.address'=>$multiAddress)
));
$noOfTrans = count($addresses['signTran']);
switch ($currency){
case "BTC":
$coin = new Bitcoin('http://'.BITCOIN_WALLET_SERVER.':'.BITCOIN_WALLET_PORT,BITCOIN_WALLET_USERNAME,BITCOIN_WALLET_PASSWORD);
$currencyName = "Bitcoin";
$transaction = Bitblocks::find("first",array(
"conditions"=>array("txid.vout.scriptPubKey.addresses"=>$multiAddress)
));
$opts = array(
'http'=> array(
'method'=> "GET",
'user_agent'=> "MozillaXYZ/1.0"));
$context = stream_context_create($opts);
$json = file_get_contents('http://blockchain.info/address/'.$multiAddress.'/?format=json', false, $context);
$function = new Functions();
$jdec = $function->objectToArray(json_decode($json));
// print_r($jdec);
foreach($jdec['txs'] as $txid){
foreach($txid->out as $out){
if($out->addr == $multiAddress){
$x_txid = $txid->hash;
$x_value = $out->value;
$x_vout = $out->n;
$x_scriptPubKey = $out->script;
}
}
}
$wallet_address = BITCOIN_WALLET_ADDRESS;
break;
case "XGC":
$coin = new Greencoin('http://'.GREENCOIN_WALLET_SERVER.':'.GREENCOIN_WALLET_PORT,GREENCOIN_WALLET_USERNAME,GREENCOIN_WALLET_PASSWORD);
$currencyName = "GreenCoin";
$transaction = Greenblocks::find("first",array(
"conditions"=>array("txid.vout.scriptPubKey.addresses"=>$multiAddress)
));
foreach($transaction['txid'] as $txid){
foreach($txid['vout'] as $vout){
foreach($vout['scriptPubKey']['addresses'] as $address){
if($address == $multiAddress){
$x_txid = $txid['txid'];
$x_vout = $vout['n'];
$x_value = $vout['value'];
$x_scriptPubKey = $vout['scriptPubKey']['hex'];
}
}
}
}
$wallet_address = GREENCOIN_WALLET_ADDRESS;
break;
}
// bitcoin.signrawtransaction (rawtransact,
// [{"txid":unspent[WhichTrans]["txid"],
// "vout":unspent[WhichTrans]["vout"],"scriptPubKey":unspent[WhichTrans]["scriptPubKey"],
// "redeemScript":unspent[WhichTrans]["redeemScript"]}],
// [multisigprivkeyone])
$signTrans = array(
'txid'=>$x_txid,
'vout'=>$x_vout,
'scriptPubKey'=>$x_scriptPubKey,
'redeemScript'=>$addresses['msxRedeemScript']['redeemScript'],
);
if($noOfTrans==0){
$rawtransact = $addresses['createTrans'];
}else{
$rawtransact = $addresses['signTrans'][$noOfTrans-1]['hex'];
}
$signrawtransaction = $coin->signrawtransaction($rawtransact,array($signTrans),array($privKey));
if(is_array($signrawtransaction['error'])){
return compact('signrawtransaction');
}else{
$data = array(
'signTrans.'.($noOfTrans)=>$signrawtransaction,
'signTran.'.($noOfTrans).'.DateTime'=>new \MongoDate(),
'signTran.'.($noOfTrans).'.IP'=>$_SERVER['REMOTE_ADDR'],
'signTran.'.($noOfTrans).'.username'=>$user['username'],
'signTran.'.($noOfTrans).'.user_id'=>$user['_id'],
'signTran.'.($noOfTrans).'.withdraw.address.0' => $addresses['createTran']['withdraw']['address'][0],
'signTran.'.($noOfTrans).'.withdraw.amount.0' => $addresses['createTran']['withdraw']['amount'][0],
'signTran.'.($noOfTrans).'.withdraw.address.1' => $addresses['createTran']['withdraw']['address'][1],
'signTran.'.($noOfTrans).'.withdraw.amount.1' => $addresses['createTran']['withdraw']['amount'][1],
'signTran.'.($noOfTrans).'.withdraw.address.2' => $addresses['createTran']['withdraw']['address'][2],
'signTran.'.($noOfTrans).'.withdraw.amount.2' => $addresses['createTran']['withdraw']['amount'][2],
'signTran.'.($noOfTrans).'.withdraw.changeAddress' => $addresses['createTran']['withdraw']['changeAddress'],
'signTran.'.($noOfTrans).'.withdraw.changeAmount' => $addresses['createTran']['withdraw']['changeAmount'],
'signTran.'.($noOfTrans).'.commission_amount' => $addresses['createTran']['commission_amount'],
'signTran.'.($noOfTrans).'.tx_fee' => $addresses['createTran']['tx_fee'],
);
$conditions = array('msxRedeemScript.address'=>$multiAddress);
Addresses::update($data,$conditions);
$addresses = Addresses::find('first',array(
'conditions'=>array('msxRedeemScript.address'=>$multiAddress)
));
$email = array();
$relation = array();
foreach($addresses['addresses'] as $address){
array_push($email,$address['email']);
array_push($relation,$address['relation']);
}
$data = array(
'who'=>$user,
'currency'=>$currency,
'currencyName'=>$currencyName,
'multiAddress'=>$multiAddress,
'security'=>$addresses['security'],
'name'=>$addresses['name'],
'CoinName'=>$addresses['CoinName'],
'DateTime'=>$addresses['DateTime'],
'emails'=>$email,
'txid'=>$x_txid,
'relation'=>$relation,
'withdraw.address.0' => $addresses['createTran']['withdraw']['address'][0],
'withdraw.amount.0' => $addresses['createTran']['withdraw']['amount'][0],
'withdraw.address.1' => $addresses['createTran']['withdraw']['address'][1],
'withdraw.amount.1' => $addresses['createTran']['withdraw']['amount'][1],
'withdraw.address.2' => $addresses['createTran']['withdraw']['address'][2],
'withdraw.amount.2' => $addresses['createTran']['withdraw']['amount'][2],
'commission_amount' => $addresses['createTran']['commission_amount'],
'withdraw.changeAddress' => $addresses['createTran']['withdraw']['changeAddress'],
'withdraw.changeAmount' => $addresses['createTran']['withdraw']['changeAmount'],
'tx_fee' => $addresses['createTran']['tx_fee'],
'signTrans' => $signTrans,
'signrawtransaction' => $signrawtransaction,
);
foreach($data['emails'] as $email){
// sending email to the users
/////////////////////////////////Email//////////////////////////////////////////////////
$function = new Functions();
$compact = array('data'=>$data);
// sendEmailTo($email,$compact,$controller,$template,$subject,$from,$mail1,$mail2,$mail3)
$from = array(NOREPLY => "noreply@".COMPANY_URL);
$email = $email;
$attach = null;
$function->sendEmailTo($email,$compact,'users','signTrans',"MultiSigX.com sign transaction",$from,'','','',$attach);
/////////////////////////////////Email//////////////////////////////////////////////////
}
}
}
return $this->redirect(array('controller'=>'Ex','action'=>'dashboard'));
}
public function sendTrans(){
$user = Session::read('default');
if ($user==""){ return $this->redirect('Users::signup');}
if($this->request->data){
$multiAddress = $this->request->data['address'];
$currency = $this->request->data['currency'];
$addresses = Addresses::find('first',array(
'conditions'=>array('msxRedeemScript.address'=>$multiAddress)
));
$noOfTrans = count($addresses['signTran']);
switch ($currency){
case "BTC":
$coin = new Bitcoin('http://'.BITCOIN_WALLET_SERVER.':'.BITCOIN_WALLET_PORT,BITCOIN_WALLET_USERNAME,BITCOIN_WALLET_PASSWORD);
$currencyName = "Bitcoin";
$transaction = Bitblocks::find("first",array(
"conditions"=>array("txid.vout.scriptPubKey.addresses"=>$multiAddress)
));
$wallet_address = BITCOIN_WALLET_ADDRESS;
break;
case "XGC":
$coin = new Greencoin('http://'.GREENCOIN_WALLET_SERVER.':'.GREENCOIN_WALLET_PORT,GREENCOIN_WALLET_USERNAME,GREENCOIN_WALLET_PASSWORD);
$currencyName = "GreenCoin";
$transaction = Greenblocks::find("first",array(
"conditions"=>array("txid.vout.scriptPubKey.addresses"=>$multiAddress)
));
$wallet_address = GREENCOIN_WALLET_ADDRESS;
break;
}
if($addresses['signTrans'][($noOfTrans-1)]['complete']==true){
$signrawtransaction = $addresses['signTrans'][($noOfTrans-1)]['hex'];
}else{
return $this->redirect(array('controller'=>'ex','action'=>'dashboard/'));
}
// print_r($addresses['security']);
// print_r($noOfTrans);
if($addresses['security']==$noOfTrans){
$sendrawtransaction = $coin->sendrawtransaction($signrawtransaction);
if(is_array($sendrawtransaction)){
if(array_key_exists('error' ,$sendrawtransaction)){
return compact('sendrawtransaction');
}
}else{
$data = array(
'sendTrans'=>$sendrawtransaction,
'sendTran.DateTime'=>new \MongoDate(),
'sendTran.IP'=>$_SERVER['REMOTE_ADDR'],
'sendTran.username'=>$user['username'],
'sendTran.user_id'=>$user['_id'],
'sendTran.withdraw.address.0' => $addresses['createTran']['withdraw']['address'][0],
'sendTran.withdraw.amount.0' => $addresses['createTran']['withdraw']['amount'][0],
'sendTran.withdraw.address.1' => $addresses['createTran']['withdraw']['address'][1],
'sendTran.withdraw.amount.1' => $addresses['createTran']['withdraw']['amount'][1],
'sendTran.withdraw.address.2' => $addresses['createTran']['withdraw']['address'][2],
'sendTran.withdraw.amount.2' => $addresses['createTran']['withdraw']['amount'][2],
'sendTran.withdraw.changeAddress' => $addresses['createTran']['withdraw']['changeAddress'],
'sendTran.withdraw.changeAmount' => $addresses['createTran']['withdraw']['changeAmount'],
'sendTran.commission_amount' => $addresses['createTran']['commission_amount'],
'sendTran.tx_fee' => $addresses['createTran']['tx_fee'],
);
$conditions = array('msxRedeemScript.address'=>$multiAddress);
Addresses::update($data,$conditions);
$email = array();
$relation = array();
foreach($addresses['addresses'] as $address){
array_push($email,$address['email']);
array_push($relation,$address['relation']);
}
$data = array(
'who'=>$user,
'currency'=>$currency,
'currencyName'=>$currencyName,
'multiAddress'=>$multiAddress,
'security'=>$addresses['security'],
'name'=>$addresses['name'],
'CoinName'=>$addresses['CoinName'],
'DateTime'=>$addresses['DateTime'],
'emails'=>$email,
'txid'=>$sendrawtransaction,
'relation'=>$relation,
'withdraw.address.0' => $addresses['createTran']['withdraw']['address'][0],
'withdraw.amount.0' => $addresses['createTran']['withdraw']['amount'][0],
'withdraw.address.1' => $addresses['createTran']['withdraw']['address'][1],
'withdraw.amount.1' => $addresses['createTran']['withdraw']['amount'][1],
'withdraw.address.2' => $addresses['createTran']['withdraw']['address'][2],
'withdraw.amount.2' => $addresses['createTran']['withdraw']['amount'][2],
'withdraw.changeAddress' => $addresses['createTran']['withdraw']['changeAddress'],
'withdraw.changeAmount' => $addresses['createTran']['withdraw']['changeAmount'],
'commission_amount' => $addresses['createTran']['commission_amount'],
'tx_fee' => $addresses['createTran']['tx_fee'],
);
foreach($data['emails'] as $email){
// sending email to the users
/////////////////////////////////Email//////////////////////////////////////////////////
$function = new Functions();
$compact = array('data'=>$data);
// sendEmailTo($email,$compact,$controller,$template,$subject,$from,$mail1,$mail2,$mail3)
$from = array(NOREPLY => "noreply@".COMPANY_URL);
$email = $email;
$attach = null;
$function->sendEmailTo($email,$compact,'users','sendTrans',"MultiSigX.com Transaction complete",$from,'','','',$attach);
/////////////////////////////////Email//////////////////////////////////////////////////
}
return $this->redirect(array('controller'=>'Ex','action'=>'withdraw/'.$multiAddress.'/send'));
}
}
}
return $this->redirect(array('controller'=>'Ex','action'=>'withdraw/'.$multiAddress.'/sign'));
}
public function DeleteCreateTrans($multiAddress=null){
$user = Session::read('default');
if ($user==""){ return $this->redirect('Users::signup');}
$conditions = array('msxRedeemScript.address'=>$multiAddress);
$unset = array('$unset'=>array('createTran'=>'','createTrans'=>'','signTran'=>'','signTrans'=>'','sendTran'=>'','sendTrans'=>''));
Addresses::update($unset,$conditions);
return $this->redirect(array('controller'=>'ex','action'=>'withdraw/'.$multiAddress));
}
public function CheckTOTP(){
$user = Session::read('default');
if ($user==""){return $this->render(array('json' => false));}
$id = $user['_id'];
$details = Details::find('first',
array('conditions'=>array('user_id'=> (string) $id))
);
$CheckCode = $this->request->query['CheckCode'];
$ga = new GoogleAuthenticator();
$checkResult = $ga->verifyCode($details['secret'], $CheckCode, 2);
if ($checkResult) {
$data = array(
'TOTP.Validate'=>false,
'TOTP.Security'=>false,
);
$details = Details::find('first',
array('conditions'=>array('user_id'=> (string) $id))
)->save($data);
return $this->render(array('json' => array('value'=>true)));
}else{
return $this->render(array('json' => array('value'=>false)));
}
}
public function changepassword($key=null){
if($key==null){ return $this->redirect('login');}
return compact('key');
}
public function password(){
if($this->request->data){
$details = Details::find('first', array(
'conditions' => array(
'key' => $this->request->data['key'],
),
'fields' => array('user_id')
));
$msg = "Password Not Changed!";
// print_r($details['user_id']);
if($details['user_id']!=""){
if($this->request->data['password'] == $this->request->data['password2']){
// print_r($this->request->data['oldpassword']);
$user = Users::find('first', array(
'conditions' => array(
'_id' => $details['user_id'],
)
));
// print_r($details['user_id']);
$data = array(
'password' => String::hash($this->request->data['password']),
);
// print_r($data);
$user = Users::find('all', array(
'conditions' => array(
'_id' => $details['user_id'],
)
))->save($data,array('validate' => false));
if($user){
$msg = "Password changed!";
}
}else{
$msg = "New password does not match!";
}
}
}
return compact('msg');
}
public function SendSMS(){
$user = Session::read('member');
$id = $user['_id'];
// $toMobile = "917597219319";
$ga = new GoogleAuthenticator();
$secret = $ga->createSecret(64);
$details = Details::find('first',array(
'conditions'=>array('user_id'=>(string)$id)
));
if($details['SMSCodeused']=='Yes' || $details['SMSCodeused']==""){
$SMSCode = $ga->getCode($secret);
$data = array(
'SMSCode' => $SMSCode,
'SMSCodeused' => 'No',
'SMSVerified'=>'No',
);
$details = Details::find('all',array(
'conditions'=>array('user_id'=>(string)$id)
))->save($data);
}
$details = Details::find('first',array(
'conditions'=>array('user_id'=>(string)$id)
));
$toMobile = $details['settings']['mobile'];
$toCountry = $details['settings']['Country'];
$country = Countries::find('first',array(
'conditions'=>array('ISO'=>$toCountry)
));
$Phone = (int)$country['Phone'];
$SMSCode = $details['SMSCode'];
$function = new Functions();
$toMobile = $Phone.$toMobile;
$msg = " Dear ".$details['username'].", Please enter MultiSigX verification code: ".$SMSCode." on phone verify page on the website https://MultiSigX.com/ex/settings Thanks";
//Dear ##Field##, Please enter MultiSigX verification code: ##Field## on phone verify page on the website https://MultiSigX.com/ex/settings.Thanks
if($toCountry=="IN"){
$returnvalues = $function->SMS($toMobile,$msg);
}else{
$returnvalues = $function->WorldSMS($toMobile,$msg);
}
// print_r($toMobile."-".$msg);exit;
return $this->render(array('json' => array("msg"=>"sent")));
}
public function CheckSMS(){
$user = Session::read('member');
$id = $user['_id'];
$CheckCode = $this->request->query['CheckCode'];
$details = Details::find('first',array(
'conditions'=>array('user_id'=>(string)$id)
));
$SMSCode = $details['SMSCode'];
if($CheckCode==$SMSCode){
$data = array(
'SMSCodeused' => 'Yes',
'SMSVerified'=>'Yes',
'mobile.verified'=>'Yes',
'mobile.number'=>$details['settings']['mobile'],
);
$details = Details::find('all',array(
'conditions'=>array('user_id'=>(string)$id)
))->save($data);
return $this->render(array('json' => array("msg"=>"Confirmed")));
}else{
return $this->render(array('json' => array("msg"=>"NotConfirmed")));
}
}
public function sms(){}
}
?><file_sep>/app/controllers/CommonController.php
<?php
namespace app\controllers;
use app\extensions\action\Bitcoin;
use app\extensions\action\Litecoin;
use app\extensions\action\Greencoin;
use lithium\util\String;
class CommonController extends \lithium\action\Controller {
public function CurrencyAddress($currency=null,$address = null){
///////////////////// Change of code required when Virtual Currency added
switch($currency){
case "BTC":
$coin = new Bitcoin('http://'.BITCOIN_WALLET_SERVER.':'.BITCOIN_WALLET_PORT,BITCOIN_WALLET_USERNAME,BITCOIN_WALLET_PASSWORD);
break;
case "XGC":
$coin = new Greencoin('http://'.GREENCOIN_WALLET_SERVER.':'.GREENCOIN_WALLET_PORT,GREENCOIN_WALLET_USERNAME,GREENCOIN_WALLET_PASSWORD);
break;
case "LTC":
$coin = new Litecoin('http://'.LITECOIN_WALLET_SERVER.':'.LITECOIN_WALLET_PORT,LITECOIN_WALLET_USERNAME,LITECOIN_WALLET_PASSWORD);
break;
}
// End of /////////////////// Change of code required when Virtual Currency added
$verify = $coin->validateaddress($address);
return $this->render(array('json' => array(
'verify'=> $verify,
'currency'=>$currency,
)));
}
}
?><file_sep>/app/views/api/index.html.php
<div class="white">
<div class="col-md-12 container-fluid" >
<div class="panel panel-primary">
<div class="panel-heading">MultiSigX API documentation</div>
<div class="panel-body">
<h3>MultiSigX API</h3>
<p>All MultiSigX API's require authorization. The authorization KEY is available in Settings - Security API tab under API.</p>
<p>The example of API key: <strong><KEY></strong></p>
<ol>
<li><a href="#CreateWallet">CreateWallet</a></li>
<li><a href="#CreateTransaction">CreateTransaction</a></li>
<li><a href="#SignTransaction">SignTransaction</a></li>
<li><a href="#SendTransaction">SendTransaction</a></li>
</ol>
<?php
if(strlen($details['key'])>0){
$key = $details['key'];
}else{
$key = "YOUR_API_KEY";
}
?>
<h4>CreateWallet</h4>
<p class="alert alert-danger">All parameters are to be submitted by POST only</p>
<p>URL: https://MultiSigX.com/API/CreateWallet/<?=$key?>/parameters.......</p>
<h5>Parameters</h5>
<table class="table table-condensed table-bordered table-hover" style="width:50% ">
<tr>
<th>Parameter</th>
<th>Required</th>
<th>Description</th>
<th>Default</th>
</tr>
<tr>
<td>security</td>
<td>yes</td>
<td>type of security required 2 of 3 or 3 of 3</td>
<td>2</td>
</tr>
<tr>
<td>coin</td>
<td>yes</td>
<td>Coin name XGC or BTC</td>
<td>XGC</td>
</tr>
<tr>
<td>coinName</td>
<td>yes</td>
<td>Name your own coin</td>
<td>MultiSigXCoinName</td>
</tr>
<tr>
<td>changeAddress</td>
<td>yes</td>
<td>MultiSigX or Your own address</td>
<td>MultiSigX</td>
</tr>
<tr>
<td>changeAddressValue</td>
<td>No</td>
<td>required only if you choose your own address</td>
<td>-</td>
</tr>
<tr>
<td>email1</td>
<td>yes</td>
<td>your own email address</td>
<td><?=$user['email']?></td>
</tr>
<tr>
<td>relation1</td>
<td>yes</td>
<td>
<ul class="list-unstyled">
<li>Self</li>
<li>Partner</li>
<li>Friend</li>
<li>Family</li>
<li>Employer</li>
<li>Employee</li>
<li>Business</li>
<li>Escrow</li>
<li>Print / Cold storage</li>
<li>MultiSigX – self escrow</li>
</ul>
</td>
<td>Self</td>
</tr>
<tr>
<td>email2</td>
<td>yes</td>
<td>2nd email address</td>
<td>2nd<?=$user['email']?></td>
</tr>
<tr>
<td>relation2</td>
<td>yes</td>
<td>
<ul class="list-unstyled">
<li>Self</li>
<li>Partner</li>
<li>Friend</li>
<li>Family</li>
<li>Employer</li>
<li>Employee</li>
<li>Business</li>
<li>Escrow</li>
<li>Print / Cold storage</li>
<li>MultiSigX – self escrow</li>
</ul>
</td>
<td>Self</td>
</tr>
<tr>
<td>email3</td>
<td>yes</td>
<td>3rd email address</td>
<td>3rd<?=$user['email']?></td>
</tr>
<tr>
<td>relation3</td>
<td>yes</td>
<td>
<ul class="list-unstyled">
<li>Self</li>
<li>Partner</li>
<li>Friend</li>
<li>Family</li>
<li>Employer</li>
<li>Employee</li>
<li>Business</li>
<li>Escrow</li>
<li>Print / Cold storage</li>
<li>MultiSigX – self escrow</li>
</ul>
</td>
<td>Self</td>
</tr>
</table>
<?php
if(strlen($details['key'])>0){?>
<div class="APIexample">
<form action="/API/CreateWallet/<?=$key?>" method="post" target="_blank" role="form" class="form-horizontal">
<div class="form-group">
<label for="security" class="col-sm-2 control-label">Security</label>
<div class="col-sm-5">
<select name="security" id="security" class="col-sm-5 form-control">
<option value="2">2 of 3</option>
<option value="3">3 of 3</option>
</select>
</div>
</div>
<div class="form-group">
<label for="coin" class="col-sm-2 control-label">Coin</label>
<div class="col-sm-5">
<select name="coin" id="coin" class="col-sm-5 form-control">
<option value="XGC">XGC - GreenCoin</option>
<option value="BTC">BTC - Bitcoin</option>
</select>
</div>
</div>
<div class="form-group">
<label for="coinName" class="col-sm-2 control-label">CoinName</label>
<div class="col-sm-5">
<input type="text" name="coinName" id="coinName" class="form-control">
</div>
</div>
<div class="form-group">
<label for="changeAddress" class="col-sm-2 control-label">Change Address</label>
<div class="col-sm-5">
<select name="changeAddress" id="changeAddress" class="col-sm-5 form-control">
<option value="MultiSigX">MultiSigX</option>
<option value="Simple">Your own address</option>
</select>
</div>
</div>
<div class="form-group">
<label for="changeAddressValue" class="col-sm-2 control-label">Change Address value</label>
<div class="col-sm-5">
<input type="text" name="changeAddressValue" id="changeAddressValue" class="form-control">
</div>
</div>
<div class="form-group">
<label for="email1" class="col-sm-2 control-label">Email 1</label>
<div class="col-sm-5">
<input type="text" name="email1" id="email1" class="form-control">
</div>
</div>
<div class="form-group">
<label for="relation1" class="col-sm-2 control-label">Relation 1</label>
<div class="col-sm-5">
<select name="relation1" id="relation1" class="col-sm-5 form-control">
<option value="Self">Self</option>
<option value="Print storage">Print storage</option>
<option value="Partner">Partner</option>
<option value="Friend">Friend</option>
<option value="Family">Family</option>
<option value="Escrow">Escrow</option>
<option value="Employer">Employer</option>
<option value="Employee">Employee</option>
<option value="Business">Business</option>
</select>
</div>
</div>
<div class="form-group">
<label for="email2" class="col-sm-2 control-label">Email 2</label>
<div class="col-sm-5">
<input type="text" name="email2" id="email2" class="form-control">
</div>
</div>
<div class="form-group">
<label for="relation2" class="col-sm-2 control-label">Relation 2</label>
<div class="col-sm-5">
<select name="relation2" id="relation2" class="col-sm-5 form-control">
<option value="Self">Self</option>
<option value="Print storage">Print storage</option>
<option value="Partner">Partner</option>
<option value="Friend">Friend</option>
<option value="Family">Family</option>
<option value="Escrow">Escrow</option>
<option value="Employer">Employer</option>
<option value="Employee">Employee</option>
<option value="Business">Business</option>
</select>
</div>
</div>
<div class="form-group">
<label for="email3" class="col-sm-2 control-label">Email 3</label>
<div class="col-sm-5">
<input type="text" name="email3" id="email3" class="form-control">
</div>
</div>
<div class="form-group">
<label for="relation3" class="col-sm-2 control-label">Relation 3</label>
<div class="col-sm-5">
<select name="relation3" id="relation3" class="col-sm-5 form-control">
<option value="Self">Self</option>
<option value="Print storage">Print storage</option>
<option value="Partner">Partner</option>
<option value="Friend">Friend</option>
<option value="Family">Family</option>
<option value="Escrow">Escrow</option>
<option value="Employer">Employer</option>
<option value="Employee">Employee</option>
<option value="Business">Business</option>
</select>
</div>
</div>
<input type="submit" value="Create Wallet and send emails" class="btn btn-primary">
</form>
</div>
<?php }?>
<h5>Returns</h5>
<pre>
{
"success":1,
"now":1413457103,
"result":
{
"security":"2",
"coin":"XGC",
"coinName":"SomeCoinName",
"changeAddress":"MultiSigX",
"changeAddressValue":"",
"email1":"<EMAIL>",
"relation1":"Self",
"email2":"<EMAIL>",
"relation2":"Self",
"email3":"<EMAIL>",
"relation3":"Self"
}
}</pre>
<h4><a name="CreateTransaction">CreateTransaction</a></h4>
<p class="alert alert-danger">All parameters are to be submitted by POST only</p>
<p>URL: https://MultiSigX.com/API/CreateTransaction/<?=$key?>/parameters.......</p>
<h5>Parameters</h5>
<table class="table table-condensed table-bordered table-hover" style="width:50% ">
<tr>
<th>Parameter</th>
<th>Required</th>
<th>Description</th>
<th>Default</th>
</tr>
<tr>
<td>coinAddress</td>
<td>yes</td>
<td>MultiSigX Coin Address</td>
<td>None</td>
</tr>
<tr>
<td>address</td>
<td>yes</td>
<td>Withdrawal address</td>
<td>None</td>
</tr>
<tr>
<td>amount</td>
<td>yes</td>
<td>Withdrawal amount</td>
<td>None</td>
</tr>
</table>
<?php
if(strlen($details['key'])>0){?>
<div class="APIexample">
<form action="/API/CreateTransaction/<?=$key?>" method="post" target="_blank" role="form" class="form-horizontal">
<div class="form-group">
<label for="address" class="col-sm-2 control-label">Address</label>
<div class="col-sm-5">
<input type="text" name="address" id="Address" class="form-control">
</div>
</div>
<div class="form-group">
<label for="amount" class="col-sm-2 control-label">Amount</label>
<div class="col-sm-5">
<input type="text" name="amount" id="Amount" class="form-control">
</div>
</div>
<input type="submit" value="Create Transaction" class="btn btn-primary">
</form>
</div>
<?php }?>
<h5>Returns</h5>
<pre>
{
"success":1,
"now":1413457103,
"result":
{
"address":"1CExstj2rh9NEcDMb7F2PQTDdDHasTBvXD",
"amount":"10",
}
}</pre>
<h4><a name="SignTransaction">SignTransaction</a></h4>
<p class="alert alert-danger">All parameters are to be submitted by POST only</p>
<p>URL: https://MultiSigX.com/API/SignTransaction/<?=$key?>/parameters.......</p>
<h5>Parameters</h5>
<table class="table table-condensed table-bordered table-hover" style="width:50% ">
<tr>
<th>Parameter</th>
<th>Required</th>
<th>Description</th>
<th>Default</th>
</tr>
<tr>
<td>coinAddress</td>
<td>yes</td>
<td>MultiSigX Coin Address</td>
<td>None</td>
</tr>
<tr>
<td>privatekey</td>
<td>yes</td>
<td>Your Private Key</td>
<td>None</td>
</tr>
</table>
<?php
if(strlen($details['key'])>0){?>
<div class="APIexample">
</div>
<?php }?>
<h5>Returns</h5>
<pre>
{
"success":1,
"now":1413457103,
"result":
{
"address":"1CExstj2rh9NEcDMb7F2PQTDdDHasTBvXD",
"amount":"10",
}
}</pre>
<h4><a name="SendTransaction">SendTransaction</a></h4>
<p class="alert alert-danger">All parameters are to be submitted by POST only</p>
<p>URL: https://MultiSigX.com/API/SendTransaction/<?=$key?>/parameters.......</p>
<h5>Parameters</h5>
<table class="table table-condensed table-bordered table-hover" style="width:50% ">
<tr>
<th>Parameter</th>
<th>Required</th>
<th>Description</th>
<th>Default</th>
</tr>
<tr>
<td>coinAddress</td>
<td>yes</td>
<td>MultiSigX Coin Address</td>
<td>None</td>
</tr>
<tr>
<td>privatekey</td>
<td>yes</td>
<td>Your Private Key</td>
<td>None</td>
</tr>
</table>
<?php
if(strlen($details['key'])>0){?>
<div class="APIexample">
</div>
<?php }?>
<h5>Returns</h5>
<pre>
{
"success":1,
"now":1413457103,
"result":
{
"address":"1CExstj2rh9NEcDMb7F2PQTDdDHasTBvXD",
"amount":"10",
}
}</pre>
</div>
</div>
</div>
</div> | c19190eda299be44ac12e890f982bae036091a1f | [
"Markdown",
"PHP"
] | 38 | PHP | FireWalkerX/MultiSigX | d0d646366309b60104a7c98809200a0cbc03262d | af59319c2610ea5c3ad6948953a59ae7cb3bea56 |
refs/heads/master | <file_sep>import {ScreenName} from 'consts';
import {
CommonActions,
createNavigationContainerRef,
StackActions,
} from '@react-navigation/native';
import {logd, toJSONStr} from './log';
const TAG = 'NavigationViewModel';
class NavigationViewModel {
private static instance: NavigationViewModel;
private constructor() {}
public static sharedInstance(): NavigationViewModel {
if (!NavigationViewModel.instance) {
NavigationViewModel.instance = new NavigationViewModel();
}
return NavigationViewModel.instance;
}
navigationRef = createNavigationContainerRef();
private isNotReady = (): boolean => {
if (!this.navigationRef.isReady()) {
logd(TAG, 'navigation is not ready yet');
return true;
}
return false;
};
/**
* If the screen name already existed in the stack, it will pop to that screen
* @param screen
* @param params { data: 'to send'}. See getRouteParams function to see how to get the params
*/
navigate = (screen: ScreenName, params?: any): void => {
if (this.isNotReady()) return;
logd(TAG, `navigate: ${screen} params=${toJSONStr(params)}`);
this.navigationRef.dispatch(
CommonActions.navigate({
name: screen,
params,
}),
);
};
/**
* Replace the current screen by a screen
*/
replace(screen: ScreenName, params?: any): void {
logd(TAG, `replace ${screen}; params: ${toJSONStr(params)}`);
this.navigationRef.dispatch(StackActions.replace(screen, params));
}
private getCurrentScreen(): ScreenName {
const route = this.navigationRef.getCurrentRoute();
const screenName = route?.name;
return screenName as ScreenName;
}
goBack = (params?: any): void => {
if (this.navigationRef.canGoBack()) {
this.navigationRef.goBack();
const screenName = this.getCurrentScreen();
logd(
TAG,
`popScreen back to ${screenName} with params: ${toJSONStr(params)}`,
);
} else {
logd(TAG, 'Cannot go back');
}
};
// Go back to first screen in stack.
popToTop = (): void => {
this.navigationRef.dispatch(StackActions.popToTop());
const screenName = this.getCurrentScreen();
logd(TAG, `popToTop ${screenName}`);
};
resetWithScreen = (screen: ScreenName, params?: any): void => {
if (this.isNotReady()) return;
logd(TAG, `resetWithScreen: ${screen} params ${toJSONStr(params)}`);
this.navigationRef.reset({
index: 0,
routes: [{name: screen, params}],
});
};
resetWithScreens = (screens: ScreenName[], params?: any): void => {
if (this.isNotReady()) return;
let screenName = '';
if (screens.length > 0) {
screenName = screens[screens.length - 1];
}
logd(TAG, `resetWithScreens: ${screens}`);
this.navigationRef.reset({
index: 0,
routes: screens.map(item => ({name: item, params})),
});
};
/**
* const {data} = navigationViewModel.getRouteParams(route). data = to send
*/
getRouteParams = (route: any): any => {
return route.params || {};
};
}
export const navigationViewModel = NavigationViewModel.sharedInstance();
<file_sep>export enum ScreenName {
Launch = 'Launch',
Onboarding = 'Onboarding',
Home = 'Home',
Detail = 'Detail',
Favorite = 'Favorite',
}
<file_sep>export * from './screen-consts';
<file_sep>export * from './log';
export * from './navigation-view-model';
<file_sep>// don't apply these for warning because of the serverity.
const ignoredTags: Array<string> = []; // Example: ['DetectedDirection']
const ignoredMsg = 'DetectedDirection'; // Example: ['DetectedDirection']
// const filterTags = ['iOS', 'contactManager']; // Filter sync apple log
const filterTags: Array<string> = []; // Example: ['DetectedDirection']
/**
* Example logdfunc(LoginScreen, 'message')
*/
export const logdfunc = (func: Function, msg: string): void => {
logd(func.name, msg);
};
export const logd = (tag: string, msg: string): void => {
if (__DEV__) {
if (ignoredTags.indexOf(tag) !== -1) {
return;
}
if (msg.indexOf(ignoredMsg) !== -1) {
return;
}
if (filterTags.length > 0 && filterTags.indexOf(tag) === -1) {
return;
}
console.log(`[${tag}] ${msg}`);
}
};
export const loge = (tag: string, msg: string): void => {
if (__DEV__) {
console.warn(`[${tag}] ${msg}`);
}
};
// Dont use this method to parse object to string. This for dev mode only to write log.
export const toJSONStr = (obj?: any): string => {
if (obj === undefined) {
return 'undefined';
}
if (__DEV__) {
return JSON.stringify(obj);
}
return '';
};
| 30de95177bdeb1048abd6b1a92c0018c60995946 | [
"TypeScript"
] | 5 | TypeScript | leanhtaiit/RNTutorial | 0b0daf1da0da12782bfc32a8f14200490feb7767 | d8bf9b9be537176f9a4f55a5cac473018301325e |
refs/heads/master | <repo_name>Evgenij888/terraform<file_sep>/install.sh
#!/bin/bash
sudo apt-get update
sudo apt-get install -y mc
sudo apt-get install -y git
sudo apt-get install -y openssh-server
sudo apt-get install -y php
sudo chmod 777 -R /data
ssh-keyscan github.com >> ~/.ssh/known_hosts
yes | git clone https://github.com/Evgenij888/testweb.git /data/web
sleep 5
sudo chmod 555 -R /data
sudo php -S 0.0.0.0:80 -t /data/web &
echo $! >>/tmp/appweb.pid
<file_sep>/attach_ebs.sh
#!/bin/bash
while [ ! -e "/dev/xvdb" ]; do sleep 1; done
sudo mkfs.ext4 -F /dev/xvdb
sudo mkdir /data
sudo mount /dev/xvdb /data
echo /dev/xvdb /data ext4 defaults,nofail 0 2 >> /etc/fstab
| d422819cb12984d448df092a3bd37a8f09c487d8 | [
"Shell"
] | 2 | Shell | Evgenij888/terraform | df3b668ade4798ca977242e2ac154d8f37ddf4c9 | 5d58af8684f2d3c83442c45bafb71c6983131126 |
refs/heads/master | <file_sep>import React, { useContext } from 'react'
import { withRouter } from 'react-router-dom'
import CustomButton from '../custom-button/custom-button.component'
import CartItem from '../cart-item/cart-item.component'
import { CartContext } from '../../providers/cart/provider'
import './cart-dropdown.styles.scss'
const CartDropdown = ({ history }) => {
const { cartItems, toggleCartHidden } = useContext(CartContext)
return (
<div
className='cart-dropdown'
>
<div
className='cart-items'
>
{ Array.isArray(cartItems) && cartItems.length ? (
cartItems.map(cartItem => (
<CartItem
key={ cartItem.id }
item={ cartItem }
/>
))
) : (
<span
className='empty-message'
>Your cart is empty</span>
) }
</div>
<CustomButton
onClick={ () => {
history.push('/checkout')
toggleCartHidden()
} }
>
GO TO CHECKOUT
</CustomButton>
</div>
)}
export default withRouter(CartDropdown)
| 65eab6a76861a938ae6614bffa3829f775a536a2 | [
"JavaScript"
] | 1 | JavaScript | billyzduke/react-context-lesson | 975ab2d816c4a969f3abe7e4f39f7d86c41fab13 | 7f75a0f0a65403f8eadc80b4e91d8a2bd77fac1b |
refs/heads/master | <repo_name>ManoharJGowda/Profia<file_sep>/src/Z.java
class Z
{
public static void test(Object a)
{
System.out.println("From Test Object:" + a );
}
public static void test(int a)
{
System.out.println("From Test int :" + a);
}
public static void test(double a)
{
System.out.println("From Test double :" + a);
}
public static void test(float a)
{
System.out.println("From Test float :" + a);
}
public static void test(char ch)
{
System.out.println("From Test char :" + ch);
}
public static void test(boolean a)
{
System.out.println("From Test boolean :" + a);
}
public static void test(Integer a)
{
System.out.println("From Test Integer :" + a);
}
public static void test(Double a)
{
System.out.println("From Test Double :" + a);
}
public static void test(Float a)
{
System.out.println("From Test Float :" + a);
}
/*public static void test(Charecter ch)
{
System.out.println("From Test Charecter :" + ch);
}*/
public static void test(Boolean a)
{
System.out.println("From Test Boolean :" + a);
}
public static void main(String[] args)
{
System.out.println("From main");
System.out.println("-------------------");
test(10);
}
}<file_sep>/src/C2.java
class C2
{
public static void main(String[] args)
{
if(args.length==0)
{
System.out.println("Pass Some Values");
}
else if(args.length>2 || args.length<2)
{
System.out.println("This is designed for only 2 values");
}
else
{
int a,b;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
int res=a+b;
System.out.println( a + "+" + b + "=" + res );
}
}
}<file_sep>/src/Fact.java
import java.util.Scanner ;
class Fact
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter a size of an array");
int size = s.nextInt();
//create an array
int[] a=new int[size];
//generate and assign values
for(int i=0; i<size; i++)
{
System.out.println("Enter the elements:" + (i+1));
a[i]=s.nextInt();
}
//to find average of a numbers
int fact=1;
for(int i=1; i<=a[i]; i++)
{
fact=fact*(a[i]) ;
}
System.out.println("Factorial of a number is" + fact );
/*System.out.println("---------------------------------------");
System.out.println("Sum of All The numbers is :" + sum);
System.out.println("---------------------------------------");
System.out.println("Average =" + sum/size);
System.out.println("---------------------------------------");*/
}
}<file_sep>/src/P.java
import java.util.Scanner;
class P
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Enter A Number");
int num=s.nextInt();
num=0;
for(int i=num; i<=num; i++)
{
if(i>num ? i : num)
{
System.out.println(i);
i++;
}
else
{
}
}
System.out.pribntln("larsgest of Numbers is:" + i);
}
}<file_sep>/src/G.java
import java.util.Scanner; //maximum value among all the elements
class G
{
public static void main(String[] args)
{
int max=0;
Scanner s=new Scanner(System.in);
//input for user
System.out.println("Enter the size of an array");
int size=s.nextInt();
//create an arraay
int[] arr=new int[size];
//assign values
for(int i=0; i<size; i++)
{
System.out.println("Enter value of Element:" +(i+1));
arr[i]=s.nextInt();
}
for(int i=0; i<size; i++)
{
if(max<arr[i])
{
max=arr[i];
}
}
System.out.println("Maximum value is:" + max);
}
} | 2e6aaa2ba21e7faf23074e170e05112a5d36ad8c | [
"Java"
] | 5 | Java | ManoharJGowda/Profia | 2cb4376aa64bd900355064d7506ef18392d11f16 | f02f1c60d7e9b6cf8916444771c2d8fb56428c2e |
refs/heads/master | <repo_name>Vorfall/task1<file_sep>/ParsersLibrary/Parsers.cs
using FiguresClassLibrary;
using System;
namespace ParsersLibrary
{
/// <summary>
/// Data parser, used to initialize data
/// </summary>
public class Parser
{
/// <summary>
/// interprets data as a triangle
/// </summary>
/// <param name="data"></param>
/// <returns>triangle</returns>
public Triangle ParseAsTriangle(string[] data)
{
if (data.Length == 4)
{
return new Triangle(int.Parse(data[1]), int.Parse(data[2]), int.Parse(data[3]));
}
else
{
return new Triangle(int.Parse(data[1]), int.Parse(data[2]), int.Parse(data[3]),
int.Parse(data[4]), int.Parse(data[5]), int.Parse(data[6]));
}
}
/// <summary>
/// interprets data as a circle
/// </summary>
/// <param name="data"></param>
/// <returns>circle</returns>
public Circle ParseAsCircle(string[] data)
{
if (data.Length == 2)
{
return new Circle(int.Parse(data[1]));
}
else
{
return new Circle(int.Parse(data[1]), int.Parse(data[2]), int.Parse(data[3]), int.Parse(data[4]));
}
}
/// <summary>
/// interprets data as a rectangle
/// </summary>
/// <param name="data"></param>
/// <returns>rectangle/returns>
public Rectangle ParseAsRectangle(string[] data)
{
if (data.Length == 5)
{
return new Rectangle(int.Parse(data[1]), int.Parse(data[2]), int.Parse(data[3]), int.Parse(data[4]));
}
else
{
return new Rectangle(int.Parse(data[1]), int.Parse(data[2]), int.Parse(data[3]), int.Parse(data[4]),
int.Parse(data[5]), int.Parse(data[6]), int.Parse(data[7]), int.Parse(data[8]));
}
}
}
}
<file_sep>/task2_unitTest/FileReadingTests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting;
using FileExtensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FiguresClassLibrary;
using System.IO;
namespace task2_unitTest
{
[TestClass]
public class FileReadingTests
{
[TestMethod]
[ExpectedException(typeof(System.IO.FileNotFoundException))]
public void FilePathValidTest()
{
string path = @"Test.txt";
FileReader reader = new FileReader();
Figure[] testArray = reader.ReadFile(path);
}
[TestMethod]
public void PathValidWithValidAllFigresTest()
{
string path = @"E:\epam_training_task1-master\FileExtensionsLibrary1\ComleteFigures.txt";
FileReader reader = new FileReader();
Figure[] t_array = reader.ReadFile(path);
Figure[] ex_array = { new Triangle(30, 40, 50), new Triangle(0, 0, 4, 5, 0, 1), new Circle(10), new Circle(1, 1, -1, -1), new Rectangle(10,20,10,20), new Rectangle(0,0,0,20,10,10,10,0)};
CollectionAssert.AreEqual(ex_array, t_array);
}
}
}
<file_sep>/ClassLibrary1/Rectangle.cs
using System;
namespace FiguresClassLibrary
{
/// <summary>
/// Represents Rectangle.
/// </summary>
public class Rectangle : Figure
{
public double a;
public double b;
public double c;
public double d;
/// <summary>
/// Initializes a rectangle based on the sides
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
/// <param name="d"></param>
public Rectangle(double e, double f, double g, double h)
{
if(h + f + g > e && e > 0 )
{
a = e;
}
else
{
throw new Exception("Side A cannot belong to a rectangle");
}
if ( e + g + h > f && f > 0)
{
b = f;
}
else
{
throw new Exception("Side B cannot belong to a rectangle");
}
if (e + f + h > g && g > 0 )
{
c = g;
}
else
{
throw new Exception("Side C cannot belong to a rectangle");
}
if (e + f + g > h && h > 0)
{
d = h;
}
else
{
throw new Exception("Side D cannot belong to a rectangle");
}
}
/// <summary>
/// Getting line length from points
/// </summary>
/// <param name="x1"></param>
/// <param name="y1"></param>
/// <param name="x2"></param>
/// <param name="y2"></param>
/// <returns></returns>
public double PartyСreation(double x1, double y1, double x2, double y2) => Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
/// <summary>
/// Initializes a rectangle based on the coordinate.
/// </summary>
/// <param name="x1"></param>
/// <param name="y1"></param>
/// <param name="x2"></param>
/// <param name="y2"></param>
/// <param name="x3"></param>
/// <param name="y3"></param>
/// <param name="x4"></param>
/// <param name="y4"></param>
public Rectangle(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4)
{
double e = PartyСreation(x1, y1, x2, y2);
double f = PartyСreation(x2, y2, x3, y3);
double g = PartyСreation(x3, y3, x4, y4);
double h = PartyСreation(x4, y4, x1, y1); ;
if (h + f + g > e && e > 0)
{
a = e;
}
else
{
throw new Exception("Side A cannot belong to a rectangle");
}
if (e + g + h > f && f > 0)
{
b = f;
}
else
{
throw new Exception("Side B cannot belong to a rectangle");
}
if (e + f + h > g && g > 0)
{
c = g;
}
else
{
throw new Exception("Side C cannot belong to a rectangle");
}
if (e + f + g > h && h > 0)
{
d = h;
}
else
{
throw new Exception("Side D cannot belong to a rectangle");
}
}
/// <summary>
/// Perimeter calculation
/// </summary>
/// <returns>P</returns>
public override double GetPerimeter()
{
return (a + b) * 2;
}
/// <summary>
/// Calculating area
/// </summary>
/// <returns>S</returns>
public override double GetArea()
{
return a * b;
}
/// <summary>
/// Getting HashCode
/// </summary>
/// <returns>hashcode</returns>
public override int GetHashCode()
{
return a.GetHashCode() ^ b.GetHashCode() ^ c.GetHashCode() ^ d.GetHashCode();
}
/// <summary>
/// Сonverting object data to string
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format($"Type: {GetType().ToString()}, A = {a}, B ={b}, C ={c}, D ={d}, Area = {GetArea()}, Perimeter = {GetPerimeter()}");
}
/// <summary>
/// Compares objects for equality
/// </summary>
/// <param name="obj"></param>
/// <returns> equal / not equal <> true/else</returns>
public override bool Equals(object obj)
{
if (obj is Rectangle rectangle)
{
if (this.a == rectangle.a && this.b == rectangle.b && this.c == rectangle.c && this.d == rectangle.d)
{
return true;
}
}
return false;
}
}
}
<file_sep>/ClassLibrary1/FigureActions.cs
using FiguresClassLibrary;
using System.Linq;
namespace FiguresLibrary
{
public class FigureActions
{
/// <summary>
/// Finds all duplicate array members
/// </summary>
/// <param name="figure"></param>
/// <param name="array"></param>
/// <returns>array of duplicates</returns>
public Figure[] GetSameFiguresArray(Figure figure, Figure[] array) => (from data in array where data.Equals(figure) select data).ToArray();
}
}
<file_sep>/ClassLibrary1/Figure.cs
namespace FiguresClassLibrary
{
/// <summary>
/// Base class for all fugures
/// </summary>
public abstract class Figure
{
public abstract double GetArea();
public abstract double GetPerimeter();
}
}
<file_sep>/ClassLibrary1/Triangle.cs
using System;
namespace FiguresClassLibrary
{
/// <summary>
/// Represents Triagnle.
/// </summary>
public class Triangle : Figure
{
private double a;
private double b;
private double c;
/// <summary>
/// initializes using the sides of the triangle
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
public Triangle(double e, double f, double g)
{
if (f + g > e && e > 0)
{
a = e;
}
else
{
throw new Exception("Side a cannot belong to a rectangle");
}
if (e + g > f && f > 0)
{
b = f;
}
else
{
throw new Exception("Side b cannot belong to a rectangle");
}
if (e + f > g && g > 0)
{
c = g;
}
else
{
throw new Exception("Side c cannot belong to a rectangle");
}
}
/// <summary>
/// Getting line length from points
/// </summary>
/// <param name="x1"></param>
/// <param name="y1"></param>
/// <param name="x2"></param>
/// <param name="y2"></param>
/// <returns></returns>
public double PartyСreation(double x1, double y1, double x2, double y2) => Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
/// <summary>
/// initializes using triangle coordinates
/// </summary>
/// <param name="x1"></param>
/// <param name="y1"></param>
/// <param name="x2"></param>
/// <param name="y2"></param>
/// <param name="x3"></param>
/// <param name="y3"></param>
///
public Triangle(double x1, double y1, double x2, double y2, double x3, double y3)
{
double e = PartyСreation(x1, y1, x2, y2);
double f = PartyСreation(x2, y2, x3, y3);
double g = PartyСreation(x3, y3, x1, y1);
if (f + g > e && e > 0)
{
a = e;
}
else
{
throw new Exception("Side a cannot belong to a rectangle");
}
if (e + g > f && f > 0)
{
b = f;
}
else
{
throw new Exception("Side b cannot belong to a rectangle");
}
if (e + f > g && g > 0)
{
c = g;
}
else
{
throw new Exception("Side c cannot belong to a rectangle");
}
}
/// <summary>
/// Perimeter calculation
/// </summary>
/// <returns></returns>
public override double GetPerimeter()
{
return a + b + c;
}
/// <summary>
/// Calculating area
/// </summary>
/// <returns></returns>
public override double GetArea()
{
double p = (a + b + c) / 2;
return Math.Sqrt(p * (p - a) * (p - b) * (p - c));
}
/// <summary>
/// Getting HashCode
/// </summary>
/// <returns>hashcode</returns>
public override int GetHashCode()
{
return a.GetHashCode() ^ b.GetHashCode() ^ c.GetHashCode();
}
/// <summary>
/// Converting object data to string
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format($"Type: { GetType().ToString()}, a = {a}, b ={b}, c ={c}, Area = {GetArea()}, Perimeter = {GetPerimeter()}");
}
/// <summary>
/// Compares objects for equality
/// </summary>
/// <param name="obj"></param>
/// <returns> equal / not equal <> true/else</returns>
public override bool Equals(object obj)
{
if (obj is Triangle triangle)
{
if (this.a == triangle.a && this.b == triangle.b && this.c == triangle.c)
{
return true;
}
}
return false;
}
}
}
<file_sep>/ClassLibrary1/Circle.cs
using System;
namespace FiguresClassLibrary
{
/// <summary>
/// Represents circle.
/// </summary>
public class Circle : Figure
{
public double r;
/// <summary>
/// Constructor for initializing cirlce class by R
/// </summary>
/// <param name="r"></param>
public Circle(double R)
{
if( R > 0)
{
r = R;
}
else
{
throw new Exception("R cannot be equal to 0");
}
}
/// <summary>
/// Coonstructor for initializing cirlce class by a center coords and a point on the circle edge
/// </summary>
/// <param name="x1"></param>
/// <param name="y1"></param>
/// <param name="x2"></param>
/// <param name="y2"></param>
public Circle(double x1, double y1, double x2, double y2)
{
if ( x1 != x2 && y1 != y2)
{
r = Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
}
else
{
throw new Exception("Wrong coordinats");
}
}
/// <summary>
/// Radius accessor
/// </summary>
/// <summary>
/// Overriden method from the parent class. Calculates P.
/// </summary>
/// <returns>P</returns>
public override double GetPerimeter()
{
return 2 * Math.PI * r;
}
/// <summary>
/// Overriden method from the parent class. Calculates S.
/// </summary>
/// <returns>S</returns>
public override double GetArea()
{
return Math.PI * Math.Pow(r, 2);
}
/// <summary>
/// Generates HashCode
/// </summary>
/// <returns>hashcode</returns>
public override int GetHashCode()
{
return r.GetHashCode();
}
/// <summary>
/// Displays data about an object
/// </summary>
public override string ToString()
{
return string.Format($"Type: {GetType().ToString()}, Perimeter = { GetPerimeter()}, Area = {GetArea()}, R = {r}");
}
/// <summary>
/// Compares objects for equality
/// </summary>
/// <param name="obj"></param>
/// <returns> equal / not equal <> true/else</returns>
public override bool Equals(object obj)
{
if(obj is Circle circle)
{
return this.r == circle.r;
}
return false;
}
}
}
<file_sep>/task2_unitTest/RectangleCreationTest.cs
using FiguresClassLibrary;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace task2_unitTest
{
[TestClass]
public class RectangleCreationTests
{
[TestMethod]
[ExpectedException(typeof(Exception))]
public void WrongRectangleCreationBySides1()
{
double A = 0;
double B = 2;
double C = 3;
double D = 4;
Rectangle triangle = new Rectangle(A, B, C, D);
}
public void WrongRectangleCreationBySides2()
{
double A = 3;
double B = 4;
double C = -7;
double D = 5;
Rectangle triangle = new Rectangle(A, B, C, D);
}
public void WrongRectangleCreationBySides3()
{
double A = -1;
double B = -1;
double C = -1;
double D = -1;
Rectangle triangle = new Rectangle(A, B, C, D);
}
[TestMethod]
public void RectangleCreationBySides1()
{
double t_A = 10;
double t_B = 30;
double t_C = 10;
double t_D = 25;
double ex_A = 10;
double ex_B = 30;
double ex_C = 10;
double ex_D = 25;
Rectangle triangleToTest = new Rectangle(t_A, t_B, t_C, t_D);
Rectangle triangleToExcept = new Rectangle(ex_A, ex_B, ex_C, ex_D);
Assert.AreEqual(triangleToExcept, triangleToTest);
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void WrongRectangleCreationByCoords1()
{
double t_x1 = 100;
double t_y1 = 50;
double t_x2 = 100;
double t_y2 = 50;
double t_x3 = 100;
double t_y3 = 50;
double t_x4 = 100;
double t_y4 = 50;
Rectangle triangleToTest = new Rectangle(t_x1, t_y1, t_x2, t_y2, t_x3, t_y3, t_x4, t_y4);
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void WrongRectangleCreationByCoords2()
{
double t_x1 = 1;
double t_y1 = 1;
double t_x2 = 1;
double t_y2 = 1;
double t_x3 = 1;
double t_y3 = 1;
double t_x4 = 1;
double t_y4 = 1;
Rectangle triangleToTest = new Rectangle(t_x1, t_y1, t_x2, t_y2, t_x3, t_y3, t_x4, t_y4);
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void WrongRectangleCreationByCoords3()
{
double t_x1 = -2000;
double t_y1 = -700;
double t_x2 = -2000;
double t_y2 = -700;
double t_x3 = -2000;
double t_y3 = -700;
double t_x4 = -2000;
double t_y4 = -700;
Rectangle triangleToTest = new Rectangle(t_x1, t_y1, t_x2, t_y2, t_x3, t_y3, t_x4, t_y4);
}
[TestMethod]
public void RectangleCreationByCoords1()
{
double t_x1 = 1;
double t_y1 = 1;
double t_x2 = 1;
double t_y2 = 30;
double t_x3 = 14;
double t_y3 = 14;
double t_x4 = 14;
double t_y4 = 0;
double ex_x1 = 1;
double ex_y1 = 1;
double ex_x2 = 1;
double ex_y2 = 30;
double ex_x3 = 14;
double ex_y3 = 14;
double ex_x4 = 14;
double ex_y4 = 0;
Rectangle triangleToTest = new Rectangle(t_x1, t_y1, t_x2, t_y2, t_x3, t_y3, t_x4, t_y4);
Rectangle triangleToExcept = new Rectangle(ex_x1, ex_y1, ex_x2, ex_y2, ex_x3, ex_y3, ex_x4, ex_y4);
Assert.AreEqual(triangleToExcept, triangleToTest);
}
}
}
<file_sep>/EuclidMethods/Euclid.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace epam_task_1
{
public class EuclidMethods
{
/// <summary>
/// Calculates gdc(a,b)
/// if a or b is negative value - throws expetion
/// as an addition - calculates a time of an execution
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="time"></param>
/// <returns>gdc result</returns>
public int GetGDCEuclideanMethod(int a, int b, out long time)
{
Stopwatch timer = new Stopwatch();
timer.Start();
if (a == 1 || b == 1)
{
timer.Stop();
time = timer.ElapsedMilliseconds;
return 1;
}
if (a == 0)
{
timer.Stop();
time = timer.ElapsedMilliseconds;
return b;
}
if (b == 0)
{
timer.Stop();
time = timer.ElapsedMilliseconds;
return a;
}
if (a < 0)
{
a = Math.Abs(a);
}
if (b < 0)
{
b = Math.Abs(b);
}
if (a == 0)
{
timer.Stop();
time = timer.ElapsedMilliseconds;
return b;
}
if (b == 0)
{
timer.Stop();
time = timer.ElapsedMilliseconds;
return a;
}
if (a == b)
{
timer.Stop();
time = timer.ElapsedMilliseconds;
return a;
}
while (a != 0 && b != 0)
{
if (a > b)
{
a %= b;
}
else
{
b %= a;
}
}
timer.Stop();
time = timer.ElapsedMilliseconds;
return a > b ? a : b;
}
/// <summary>
/// Calculates gdc(gdc(a,b), c)
/// simply calls original method n-times
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
/// <param name="time"></param>
/// <returns>gdc result</returns>
public int GetGDCEuclideanMethod(int a, int b, int c, out long time)
{
long allTime = 0;
int gdcAB = GetGDCEuclideanMethod(a, b, out time);
allTime += time;
return GetGDCEuclideanMethod(gdcAB, c, out allTime);
}
/// <summary>
/// gdc(gdc(a,b),gdc(c,d))
/// simply calls original method n-times
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
/// <param name="d"></param>
/// <param name="time"></param>
/// <returns>gdc result</returns>
public int GetGDCEuclideanMethod(int a, int b, int c, int d, out long time)
{
long allTime = 0;
int gdcAB = GetGDCEuclideanMethod(a, b, out time);
allTime += time;
int gdcCD = GetGDCEuclideanMethod(c, d, out time);
allTime += time;
return GetGDCEuclideanMethod(gdcAB, gdcCD, out allTime);
}
/// <summary>
/// gdc(gdc(gdc(a,b),gdc(c,d)), e)
/// simply calls original method n-times
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
/// <param name="d"></param>
/// <param name="е"></param>
/// <param name="time"></param>
/// <returns>gdc result</returns>
public int GetGDCEuclideanMethod(int a, int b, int c, int d, int е, out long time)
{
long allTime = 0;
int gdcAB = GetGDCEuclideanMethod(a, b, out time);
allTime += time;
int gdcCD = GetGDCEuclideanMethod(c, d, out time);
allTime += time;
int gdcABCD = GetGDCEuclideanMethod(gdcAB, gdcCD, out time);
allTime += time;
return GetGDCEuclideanMethod(gdcABCD, е, out allTime);
}
/// <summary>
/// Calculates gdc(a,b) but by using Steins method
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="time"></param>
/// <returns>gdc result</returns>
public int GetGCDStain(int a, int b, out long time)
{
bool parityСheck(int number)
{
return (number % 2) == 1 ? false : true;
}
Stopwatch timer = new Stopwatch();
timer.Start();
if (a == 1 || b == 1)
{
timer.Stop();
time = timer.ElapsedMilliseconds;
return 1;
}
if (a == 0)
{
timer.Stop();
time = timer.ElapsedMilliseconds;
return b;
}
if (b == 0)
{
timer.Stop();
time = timer.ElapsedMilliseconds;
return a;
}
if (a < 0)
{
a = Math.Abs(a);
}
if (b < 0)
{
b = Math.Abs(b);
}
if (a == 0)
{
timer.Stop();
time = timer.ElapsedMilliseconds;
return b;
}
if (b == 0)
{
timer.Stop();
time = timer.ElapsedMilliseconds;
return a;
}
if (a == b)
{
timer.Stop();
time = timer.ElapsedMilliseconds;
return a;
}
int count = 1;
while (a != 0 && b != 0)
{
while (parityСheck(a) && parityСheck(b))
{
a /= 2;
b /= 2;
count *= 2;
}
while (parityСheck(a))
{
a /= 2;
}
while (parityСheck(b))
{
b /= 2;
}
if (a >= b)
{
a -= b;
}
else
{
b -= a;
}
}
timer.Stop();
time = timer.ElapsedMilliseconds;
return count * b;
}
/// <summary>
/// collects execution time of the all methods below and creates dictionary for a histogramm usage
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns>dictionary with results</returns>
public Dictionary<string, long> GetTimeCalculatuions(int a, int b, int c, int d, int е)
{
Dictionary<string, long> dataToPass = new Dictionary<string, long>();
long time2Parameters;
long time3Parameters = 0;
long time4Parameters = 0;
long time5Parameters = 0;
long timeStain2 = 0;
GetGDCEuclideanMethod(a, b, out time2Parameters);
GetGDCEuclideanMethod(a, b, c, out time3Parameters);
GetGDCEuclideanMethod(a, b, c, d, out time4Parameters);
GetGDCEuclideanMethod(a, b, c, d, е, out time5Parameters);
GetGCDStain(a, b, out timeStain2);
dataToPass.Add("for 2 parameters GDC is", time3Parameters);
dataToPass.Add("for 3 parameters GDC is", time3Parameters);
dataToPass.Add("for 4 parameters GDC is", time4Parameters);
dataToPass.Add("for 5 parameters GDC is", time5Parameters);
dataToPass.Add("GCD Stain 2 parameters", timeStain2);
return dataToPass;
}
}
}
<file_sep>/task2_unitTest/EqualObjectsTest.cs
using FiguresClassLibrary;
using FiguresLibrary;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace task2_unitTest
{
[TestClass]
public class EqualObjectsTest
{
[TestMethod]
public void ValidTestCheck1()
{
FigureActions actions = new FigureActions();
Figure[] array = { new Triangle(20, 30, 40) };
Figure[] t_sameFigures = actions.GetSameFiguresArray(array[0], array);
Figure[] ex_sameFigures = { new Triangle(20, 30, 40) };
CollectionAssert.AreEqual(ex_sameFigures, t_sameFigures);
}
[TestMethod]
public void ValidTestCheck2()
{
FigureActions actions = new FigureActions();
Figure[] array = { new Triangle(20, 30, 40), new Circle(5), new Triangle(20, 30, 40),
new Rectangle(10, 20, 10, 20)};
Figure[] t_sameFigures = actions.GetSameFiguresArray(array[0], array);
Figure[] ex_sameFigures = { new Triangle(20, 30, 40), new Triangle(20, 30, 40) };
CollectionAssert.AreEqual(ex_sameFigures, t_sameFigures);
}
}
}
<file_sep>/task_2/Circle.cs
using System;
namespace FiguresClassLibrary
{
public class Circle : Figure
{
private double _r;
public Circle(double r)
{
_r = r;
}
public Circle(int x1, int y1, int x2, int y2)
{
_r = Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
}
public double R { get => _r; set => _r = value; }
public override double GetPerimeter()
{
return 2 * Math.PI * R;
}
public override double GetSquare()
{
return Math.PI * Math.Pow(R, 2);
}
}
}
<file_sep>/task_2/Rectangle.cs
using System;
namespace FiguresClassLibrary
{
public class Rectangle : Figure
{
private double _a;
private double _b;
private double _c;
private double _d;
public Rectangle(double a, double b, double c, double d)
{
_a = a;
_b = b;
_c = c;
_d = d;
}
public Rectangle(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)
{
_a = Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
_b = Math.Sqrt(Math.Pow(x3 - x2, 2) + Math.Pow(y3 - y2, 2));
_c = Math.Sqrt(Math.Pow(x4 - x3, 2) + Math.Pow(y4 - y3, 2));
_d = Math.Sqrt(Math.Pow(x1 - x4, 2) + Math.Pow(y1 - y4, 2));
}
public double A { get => _a; set => _a = value; }
public double B { get => _b; set => _b = value; }
public double C { get => _c; set => _c = value; }
public double D { get => _d; set => _d = value; }
public override double GetPerimeter()
{
return (A + B) * 2;
}
public override double GetSquare()
{
return A * B;
}
}
}
<file_sep>/task2_unitTest/TriangleCreationTests.cs
using System;
using FiguresClassLibrary;
using FileExtensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace task2_unitTest
{
[TestClass]
public class TriangleCreationTests
{
[TestMethod]
[ExpectedException(typeof(Exception))]
public void WrongTriangleCreationBySides1()
{
double A = 2;
double B = 4;
double C = 6;
Triangle triangle = new Triangle(A, B, C);
}
public void WrongTriangleCreationBySides2()
{
double A = 3;
double B = -6;
double C = 0;
Triangle triangle = new Triangle(A, B, C);
}
public void WrongTriangleCreationBySides3()
{
double A = -2;
double B = -4;
double C = 28;
Triangle triangle = new Triangle(A, B, C);
}
[TestMethod]
public void TriangleCreationBySides1()
{
double A = 5;
double B = 6;
double C = 7;
Triangle triangleToTest = new Triangle(A, B, C);
Triangle triangleToExcept = new Triangle(5, 6, 7);
Assert.AreEqual(triangleToExcept, triangleToTest);
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void WrongTriangleCreationByCoords1()
{
double x1 = 0;
double y1 = 0;
double x2 = -1;
double y2 = -1;
double x3 = -1;
double y3 = -1;
Triangle triangle = new Triangle(x1, y1, x2, y2, x3, y3);
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void WrongTriangleCreationByCoords2()
{
double x1 = 9;
double y1 = 9;
double x2 = 9;
double y2 = 9;
double x3 = 9;
double y3 = 9;
Triangle triangle = new Triangle(x1, y1, x2, y2, x3, y3);
}
[TestMethod]
public void TriangleCreationByCoords1()
{
double x1 = 1;
double y1 = 2;
double x2 = 4;
double y2 = 5;
double x3 = -1;
double y3 = -1;
Triangle triangleToTest = new Triangle(x1, y1, x2, y2, x3, y3);
Triangle triangleToExcept = new Triangle(1, 2, 4, 5, -1, -1);
Assert.AreEqual(triangleToExcept, triangleToTest);
}
[TestMethod]
public void TriangleCreationByCoords2()
{
double x1 = -5;
double y1 = -5;
double x2 = 200;
double y2 = 200;
double x3 = 5;
double y3 = -5;
Triangle triangleToTest = new Triangle(x1, y1, x2, y2, x3, y3);
Triangle triangleToExcept = new Triangle(-5, -5, 200, 200, 5, -5);
Assert.AreEqual(triangleToExcept, triangleToTest);
}
}
}
<file_sep>/task1_untitTests/UnitTest.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using epam_task_1;
namespace task1_untitTests
{
[TestClass]
public class UnitTest
{
[TestMethod]
public void TestGDCPositiveValues1()
{
//arrange
int a = 9;
int b = 99;
int testResult = 9;
long time = 0;
//act
EuclidMethods testEuclid = new EuclidMethods();
int result = testEuclid.GetGDCEuclideanMethod(a, b, out time);
//assert
Assert.AreEqual(testResult, result, 0.001, "Something went wrong");
}
public void TestGDCPositiveValues2()
{
//arrange
int a = 2452;
int b = 222;
int testResult = 2;
long time = 0;
//act
EuclidMethods testEuclid = new EuclidMethods();
int result = testEuclid.GetGDCEuclideanMethod(a, b, out time);
//assert
Assert.AreEqual(testResult, result, 0.001, "Something went wrong");
}
[TestMethod]
public void TestGDCNegativeValues()
{
//arrange
int a = -5;
int b = -150;
int testResult = 5;
long time = 0;
//act
EuclidMethods testEuclid = new EuclidMethods();
int result = testEuclid.GetGDCEuclideanMethod(a, b, out time);
//assert
Assert.AreEqual(testResult, result, 0.001, "Something went wrong");
}
[TestMethod]
public void TestGDCZeroValues()
{
//arrange
int a = 0;
int b = 0;
int testResult = 0;
long time = 0;
//act
EuclidMethods testEuclid = new EuclidMethods();
int result = testEuclid.GetGDCEuclideanMethod(a, b, out time);
//assert
Assert.AreEqual(testResult, result, 0.001, "Something went wrong");
}
[TestMethod]
public void TestGDCNegativePositiveValues()
{
//arrange
int a = -4;
int b = 180;
int testResult = 4;
long time = 0;
//act
EuclidMethods testEuclid = new EuclidMethods();
int result = testEuclid.GetGDCEuclideanMethod(a, b, out time);
//assert
Assert.AreEqual(testResult, result, 0.001, "Something went wrong");
}
[TestMethod]
public void TestGDCPositiveValues3()
{
//arrange
int a = 4;
int b = 156;
int c = 1256;
int testResult = 4;
long time = 0;
//act
EuclidMethods testEuclid = new EuclidMethods();
int result = testEuclid.GetGDCEuclideanMethod(a, b, c, out time);
//assert
Assert.AreEqual(testResult, result, 0.001, "Something went wrong");
}
[TestMethod]
public void TestGDCPositiveValues4()
{
//arrange
int a = 1;
int b = 1;
int c = 456451;
int testResult = 1;
long time = 0;
//act
EuclidMethods testEuclid = new EuclidMethods();
int result = testEuclid.GetGDCEuclideanMethod(a, b, c, out time);
//assert
Assert.AreEqual(testResult, result, 0.001, "Something went wrong");
}
[TestMethod]
public void TestGDC2Positive1NegativeValues()
{
//arrange
int a = 5;
int b = -155;
int c = 1455;
int testResult = 5;
long time = 0;
//act
EuclidMethods testEuclid = new EuclidMethods();
int result = testEuclid.GetGDCEuclideanMethod(a, b, c, out time);
//assert
Assert.AreEqual(testResult, result, 0.001, "Something went wrong");
}
[TestMethod]
public void TestGDC4PositiveValues2()
{
//arrange
int a = 5;
int b = 76522;
int c = 1455;
int d = 40;
int testResult = 1;
long time = 0;
//act
EuclidMethods testEuclid = new EuclidMethods();
int result = testEuclid.GetGDCEuclideanMethod(a, b, c, d, out time);
//assert
Assert.AreEqual(testResult, result, 0.001, "Something went wrong");
}
[TestMethod]
public void TestGDC4PositiveValues3()
{
//arrange
int a = 2;
int b = 4;
int c = 32;
int d = 246;
int testResult = 2;
long time = 0;
//act
EuclidMethods testEuclid = new EuclidMethods();
int result = testEuclid.GetGDCEuclideanMethod(a, b, c, d, out time);
//assert
Assert.AreEqual(testResult, result, 0.001, "Something went wrong");
}
[TestMethod]
public void TestGDC4EqualValues()
{
//arrange
int a = 4312;
int b = 4312;
int c = 4312;
int d = 4312;
int testResult = 4312;
long time = 0;
//act
EuclidMethods testEuclid = new EuclidMethods();
int result = testEuclid.GetGDCEuclideanMethod(a, b, c, d, out time);
//assert
Assert.AreEqual(testResult, result, 0.001, "Something went wrong");
}
[TestMethod]
public void TestGDC3Positive1NegativeValues()
{
//arrange
int a = 5;
int b = -155;
int c = 1455;
int d = 204520;
int testResult = 5;
long time = 0;
//act
EuclidMethods testEuclid = new EuclidMethods();
int result = testEuclid.GetGDCEuclideanMethod(a, b, c, d, out time);
//assert
Assert.AreEqual(testResult, result, 0.001, "Something went wrong");
}
[TestMethod]
public void TestGDC4Positive1NegativeValues()
{
//arrange
int a = 5;
int b = -155;
int c = 213213;
int d = -155;
int e = 4581200;
int testResult = 1;
long time = 0;
//act
EuclidMethods testEuclid = new EuclidMethods();
int result = testEuclid.GetGDCEuclideanMethod(a, b, c, d, e, out time);
//assert
Assert.AreEqual(testResult, result, 0.001, "Something went wrong");
}
[TestMethod]
public void TestSteinWith2PositiveValues1()
{
//arrange
int a = 5;
int b = 155;
int testResult = 5;
long time = 0;
//act
EuclidMethods testEuclid = new EuclidMethods();
int result = testEuclid.GetGCDStain(a, b, out time);
//assert
Assert.AreEqual(testResult, result, 0.001, "Something went wrong");
}
[TestMethod]
public void TestSteinWithNegativePositiveValues()
{
//arrange
int a = -15;
int b = 170;
int testResult = 5;
long time = 0;
//act
EuclidMethods testEuclid = new EuclidMethods();
int result = testEuclid.GetGCDStain(a, b, out time);
//assert
Assert.AreEqual(testResult, result, 0.001, "Something went wrong");
}
}
}
<file_sep>/task2_unitTest/CircleCreationTest.cs
using FiguresClassLibrary;
using FileExtensions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace task2_unitTest
{
[TestClass]
public class CircleCreationTest
{
[TestMethod]
[ExpectedException(typeof(Exception))]
public void WrongCircleCreationBySides1()
{
double r = -2;
Circle circle = new Circle(r);
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void WrongCircleCreationBySides2()
{
double r = 0;
Circle circle = new Circle(r);
}
[TestMethod]
public void CircleCreationBySides1()
{
double r = 2;
double rExpected = 2;
Circle circleTest = new Circle(r);
Circle circleExcept = new Circle(rExpected);
Assert.AreEqual(circleExcept, circleTest);
}
[TestMethod]
public void CircleCreationBySides3()
{
double r = 1000;
double rExpected = 1000;
Circle circleTest = new Circle(r);
Circle circleExcept = new Circle(rExpected);
Assert.AreEqual(circleExcept, circleTest);
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void WrongCircleCreationByCoords1()
{
double x1 = 0;
double y1 = 0;
double x2 = 0;
double y2 = 0;
Circle circle = new Circle(x1,y1,x2,y2);
}
[TestMethod]
public void CircleCreationByCoords1()
{
double p1x1 = 2;
double p1y1 = 2;
double p1x2 = -2;
double p1y2 = -2;
double p2x1 = 2;
double p2y1 = 2;
double p2x2 = -2;
double p2y2 = -2;
Circle circleTest = new Circle(p1x1, p1y1, p1x2, p1y2);
Circle circleExcept = new Circle(p2x1, p2y1, p2x2, p2y2);
Assert.AreEqual(circleExcept, circleTest);
}
[TestMethod]
public void CircleCreationByCoords2()
{
double p1x1 = -7;
double p1y1 = 2;
double p1x2 = 5;
double p1y2 = 5;
double p2x1 = -7;
double p2y1 = 2;
double p2x2 = 5;
double p2y2 = 5;
Circle circleTest = new Circle(p1x1, p1y1, p1x2, p1y2);
Circle circleExcept = new Circle(p2x1, p2y1, p2x2, p2y2);
Assert.AreEqual(circleExcept, circleTest);
}
[TestMethod]
public void CircleCreationByCoords3()
{
double p1x1 = -1;
double p1y1 = 0;
double p1x2 = 5;
double p1y2 = 5;
double p2x1 = -1;
double p2y1 = 0;
double p2x2 = 5;
double p2y2 = 5;
Circle circleTest = new Circle(p1x1, p1y1, p1x2, p1y2);
Circle circleExcept = new Circle(p2x1, p2y1, p2x2, p2y2);
Assert.AreEqual(circleExcept, circleTest);
}
}
}
<file_sep>/FileExtensionsLibrary1/FileReader.cs
using FiguresClassLibrary;
using ParsersLibrary;
using System;
using System.IO;
using System.Linq;
namespace FileExtensions
{
public class FileReader
{
/// <summary>
/// Reads figures data from a file
/// </summary>
/// <param name="path"></param>
/// <returns>array of figures</returns>
public Figure[] ReadFile(string path)
{
Figure[] figures;
using (StreamReader sr = new StreamReader(path))
{
int Count = File.ReadLines(path).Count();
figures = new Figure[Count];
Parser parser = new Parser();
string line;
int quantity = 0;
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split();
switch (data[0])
{
case "Rectangle":
figures[quantity] = parser.ParseAsRectangle(data);
quantity++;
break;
case "Triangle":
figures[quantity] = parser.ParseAsTriangle(data);
quantity++;
break;
case "Circle":
figures[quantity] = parser.ParseAsCircle(data);
quantity++;
break;
}
}
return figures;
}
}
}
}
<file_sep>/task_2/Triangle.cs
using System;
namespace FiguresClassLibrary
{
public class Triangle : Figure
{
private double _a;
private double _b;
private double _c;
public Triangle(double a, double b, double c)
{
_a = a;
_b = b;
_c = c;
}
public Triangle(int x1, int y1, int x2, int y2, int x3, int y3)
{
_a = Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
_b = Math.Sqrt(Math.Pow(x3 - x2, 2) + Math.Pow(y3 - y2, 2));
_c = Math.Sqrt(Math.Pow(x1 - x3, 2) + Math.Pow(y1 - y3, 2));
}
public double A { get => _a; set => _a = value; }
public double B { get => _b; set => _b = value; }
public double C { get => _c; set => _c = value; }
public override double GetPerimeter()
{
return A + B + C;
}
public override double GetSquare()
{
double p = (A + B + C) / 2;
return Math.Sqrt(p * (p - A) * (p - B) * (p - C));
}
}
}
| 9cb4b6def73a75f1c7947c1875401f0e78a37ec4 | [
"C#"
] | 17 | C# | Vorfall/task1 | 40ad462d83870881dd90f899e5a82dca9c177902 | 3d30cec1a791a36df9c00dbed2be95ff25a8fb3e |
refs/heads/master | <repo_name>younes-ettouil/jQuery-Project<file_sep>/JQueryCalculatrice/js/script.js
$(function() {
$(".digit").click(function() {
$("#zero").val("");
$("#screen").val($("#screen").val() + $(this).val());
});
$("#clearCE").click(function() {
$("#screen").val($("#screen").val().slice(0, -1));
});
$("#clearC").click(function() {
$("#screen").val("");
});
$("#equal").click(function() {
$("#screen").val(eval($("#screen").val()));
});
});<file_sep>/jQueryFormmulaireE-Comm/js/script.js
$(function() {
$('#feedback').hide()
$("#submit").click(function() {
var valider = true;
if ($("#nom").val() == "") {
$("#nom").next(".message").fadeIn().text('* veuillez taper votre nom').css('color', 'red');;
valider = false;
} else if (!$("#nom").val().match(/^[a-zA-Z]+$/u)) {
$("#nom").next(".message").fadeIn().text('* veuillez taper un nom convenable').css('color', 'red');
valider = false;
} else {
$("#nom").next(".message").fadeOut();
$("#nom").next(".message").fadeIn().text('* validé').css('color', 'green');
}
if ($("#prénom").val() == "") {
$("#prénom").next(".message").fadeIn().text('* veuillez taper votre prénom').css('color', 'red');
valider = false;
} else if (!$("#prénom").val().match(/^[a-zA-Z]+$/u)) {
$("#prénom").next(".message").fadeIn().text('* veuillez taper un prénom convenable').css('color', 'red');
valider = false;
} else {
$("#prénom").next(".message").fadeOut();
$("#prénom").next(".message").fadeIn().text('* validé').css('color', 'green');
}
if ($("#Adresse").val() == "") {
$("#Adresse").next(".message").fadeIn().text('* veuillez taper votre Adresse').css('color', 'red');
valider = false;
} else {
$("#Adresse").next(".message").fadeOut();
$("#Adresse").next(".message").fadeIn().text('* validé').css('color', 'green');
}
if ($("#Email").val() == "") {
$("#Email").next(".message").fadeIn().text('* veuillez taper votre Adresse email').css('color', 'red');
valider = false;
} else if (!$("#Email").val().match(/^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i)) {
$("#Email").next(".message").fadeIn().text('* veuillez taper un adresse email convenable').css('color', 'red');
valider = false;
} else {
$("#Email").next(".message").fadeOut();
$("#Email").next(".message").fadeIn().text('* validé').css('color', 'green');
}
if ($("#Password").val() == "") {
$("#Password").next(".message").fadeIn().text('* veuillez taper un mote de pass').css('color', 'red');
valider = false;
} else if (!$("#Password").val().match(/^[a-zA-Z0-9-]$/u) && $("#Password").val().length < 8) {
$("#Password").next(".message").fadeIn().text('* Au moins 8 caractères').css('color', 'red');
valider = false;
} else {
$("#Password").next(".message").fadeOut();
$("#Password").next(".message").fadeIn().text('* validé').css('color', 'green');
}
if ($("#Password2").val() == "") {
$("#Password2").next(".message").fadeIn().text('* veuillez taper un mote de pass').css('color', 'red');
valider = false;
} else if ($("#Password2").val() != $("#Password").val()) {
$("#Password2").next(".message").fadeIn().text("* mote de pass n'est pas identique ").css('color', 'red');
valider = false;
} else {
$("#Password2").next(".message").fadeOut();
$("#Password2").next(".message").fadeIn().text('* validé').css('color', 'green');
}
if ($("#phone").val() == "") {
$("#phone").next(".message").fadeIn().text('* veuillez taper votre numéro télephone').css('color', 'red');
valider = false;
} else if (!$("#phone").val().match(/^[0-9]$/u) && $("#phone").val().length < 9) {
$("#phone").next(".message").fadeIn().text("* numéro télephone n'est pas validé ").css('color', 'red');
valider = false;
} else {
$("#phone").next(".message").fadeOut();
$("#phone").next(".message").fadeIn().text('* validé').css('color', 'green');
}
if ($("#pays").val() == "pays") {
$('#pays').next(".message").fadeIn().text('*Obligatoire').css('color', 'red');
valider = false;
} else {
$('#pays').next(".message").fadeOut();
}
if ($(':radio[id="celeb"]:checked').val() || $(':radio[id="marie"]:checked').val() || $(':radio[id="divo"]:checked').val() || $(':radio[id="veu"]:checked').val()) {
$('#radios').next(".message").fadeOut();
} else {
$('#radios').next(".message").fadeIn().text('*Obligatoire').css('color', 'red');
valider = false;
}
if (valider) {
$('#feedback').show()
}
return valider;
});
}); | b66ae08380c03d1f038274ec2fbb85abd2620a51 | [
"JavaScript"
] | 2 | JavaScript | younes-ettouil/jQuery-Project | 5079b1402b6089c26459a5430fdbf5cf913e821e | 274375e6ead63a89b32a919509f61a7d60a5e346 |
refs/heads/master | <repo_name>vnganji/dummypro<file_sep>/src/collections/Example.java
package collections;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
public class Example {
public static void main(String[] args) {
ArrayList<Integer> AL = new ArrayList<Integer>();
AL.add(10);
AL.add(20);
AL.add(5);
AL.add(20);
AL.add(4);
AL.add(null);
System.out.println("ArrayList size");
System.out.println(AL.size());
System.out.println("ArrayList printed with for ");
for (Integer O : AL){
System.out.println(O);
}
System.out.println("ArrayList printed with Iterator ");
Iterator It1 = AL.iterator();
while(It1.hasNext()){
System.out.println(It1.next());
}
System.out.println("Hash Set");
HashSet<Integer> HL = new HashSet<Integer>();
HL.add(10);
HL.add(20);
HL.add(20);
HL.add(5);
HL.add(null);
System.out.println("Printing hashset with for loop");
for (Integer O1 : HL){
System.out.println(O1);
}
}
}
<file_sep>/src/variables/example6.java
package variables;
public class example6 {
static int counter = 10;
public example6(){
counter++;
System.out.println(counter);
}
public static void main(String[] args) {
example6 ex6 = new example6();
}
}
<file_sep>/.metadata/version.ini
#Mon Oct 21 21:00:31 IST 2019
org.eclipse.core.runtime=2
org.eclipse.platform=4.7.3.v20180330-0640
<file_sep>/src/Inheritance/overriding1.java
package Inheritance;
public class overriding1 extends Overriding {
public static void main(String[] args) {
Overriding o1 = new overriding1();//updcasting
o1.abc();
o1.def();
}
public void abc() {
System.out.println("child method");
}
public Integer returnnum() {
return 10;
}
public static void def(){
System.out.println("child");
}
}
<file_sep>/src/Polymorphism/SBI.java
package Polymorphism;
public class SBI extends Bank {
public static void main(String[] args) {
}
public double returnintRate() {
return 8.8;
}
}
<file_sep>/src/variables/Wrapper.java
package variables;
public class Wrapper {
//int -- Integer -- Number ---Object
public static void main(String[] args) {
int i =10;
Integer j =10;
System.out.println(j.floatValue());
Object o = 20;
Integer k = (Integer)o;//downcasting
Integer kk = 30;
Number jj = kk; //Upcaasting
Integer mm = kk;
}
}
<file_sep>/src/Threads/Thread1.java
package Threads;
public class Thread1 extends Thread{
//thread can be implemented in 2 ways
//by extending thread class and implements Runnable
//life cycle of thread
//new = when you first create thread it will be new
//start = when you start...it will be created new call stack and it will runnable state
//run = Thread scheduler will pick up and make it running
//non runnable : when thread gets interrupted it will be non runnable
//when it finishes wiat ..again it will back to runnable state
public Thread1(String name) {
super(name);
}
public static void main(String[] args) {
Thread1 t1 = new Thread1("threadobj");
t1.start();
}
public void run() {
for (int i = 0; i<5 ; i++) {
System.out.println(Thread.currentThread().getName());
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
<file_sep>/src/variables/Array.java
package variables;
public class Array {
public static void main(String[] args) {
int []x=new int[3];
x[0]=1;
x[1]=2;
x[2]=3;
//for each loop
for (int a:x){
System.out.println(a);
}
//for loop
for (int i = 0; i<x.length; i++){
System.out.println(x[i]);
}
}
}
<file_sep>/src/Interfaces/HDFC.java
package Interfaces;
public class HDFC implements Bank {
@Override
public float returnInt() {
return 8;
}
public static void main(String[] args) {
Bank b = new HDFC();
System.out.println(b.returnInt());
}
}
<file_sep>/src/variables/StringExample.java
package variables;
public class StringExample {
public static void main(String[] args) {
//Immutuble
String s1="venkat";
String s2="venkat";
System.out.println(s1);
s1.concat("suresh");
System.out.println(s1);
//mutuble
StringBuilder sb = new StringBuilder("venkat");
sb.append("suresh");
System.out.println(sb);
//compare
String s3="venkat";
String s4="venkats";
System.out.println(s3.equals(s4));
System.out.println(s3.equalsIgnoreCase(s4));
System.out.println(s3.compareTo(s4));
String a ="100";
Integer.parseInt(a);
Integer i =10;
Object o = i;
int a1 =20;
Integer b = a1;
int c = b;
System.out.println(b.floatValue());
System.out.println(b.doubleValue());
}
}
<file_sep>/src/Interfaces/Bank.java
package Interfaces;
public interface Bank {
int i = 10;
float returnInt();
default void abc(){
}
static void def(){
}
}
<file_sep>/src/Threads/Thread2.java
package Threads;
public class Thread2 implements Runnable {
//Thread Implementation with Runnable interface
@Override
public void run() {
for (int i = 0 ; i<5 ; i++) {
System.out.println(i);
}
}
public static void main(String[] args) {
Thread2 t3 = new Thread2();
Thread t4 = new Thread(t3,"runnable thread");// constructor with Runnable Interface
System.out.println(t4.getName());
t4.start();
}
}
<file_sep>/src/Inheritance/Overriding.java
package Inheritance;
public class Overriding {
public static void main(String[] args) {
}
public void abc(){
System.out.println("parnet method");
}
public final void abc1()
{
}
public static void def(){
System.out.println("parent");
}
public Number returnnum(){
return 10;
}
}
<file_sep>/src/variables/Example5.java
package variables;
public class Example5 {
int i =10;
static int j = 20;
public static void main(String[] args) {
Example5 ex = new Example5();
System.out.println(j);
System.out.println(ex.i);
System.out.println(ex.j);
j++;
System.out.println(ex.j);
ex.method2();
}
public void method1(){
System.out.println("method1");
}
public void method2(){
method1();
System.out.println("method2");
}
}
<file_sep>/src/innerclass/cls.java
package innerclass;
public class cls extends class1 {
public static void main(String[] args) {
class1 a1 = new cls(); //normal implementation of override method;
a1.inner();
}
public void inner() {
System.out.println("Inner class in extended class");}
}
<file_sep>/src/Polymorphism/HDFC.java
package Polymorphism;
public class HDFC extends Bank {
public static void main(String[] args) {
Bank B1 = new HDFC();//Polymormphic Reference
B1.returnintRate();
}
/*public double returnintRate() {
return 8.4;
}*/
}
<file_sep>/src/variables/example3.java
package variables;
public class example3 {
int i = 10;
static int j = 20;
public static void main(String[] args) {
example3 ex3 = new example3();
System.out.println(ex3.i);
System.out.println(j);
}
public void calculate(){
System.out.println(i);
System.out.println(j);
}
}
<file_sep>/src/abstractExample/getIntrstrate.java
package abstractExample;
public class getIntrstrate {
public static void main(String[] args) {
Bank B = new HDFC();
System.out.println(B.returnIntr());
}
}
<file_sep>/src/LOOPS/forLoop.java
package LOOPS;
public class forLoop {
public static void main(String[] args) {
//for loop with break
for (int i=0; i<=25; i++){//made some changes by asa team developer 1
for (int j = 0 ; j<=5; j++){
if (i==2 & j==2)
break; //come out of internal for loop
System.out.print(i);
System.out.println(j);
}
}
System.out.println("for loop with continue");
for (int i=0; i<=15; i++){ //change made by developer2
for (int j = 0 ; j<=5; j++){
if (i==2 & j==2)
continue; //come out of internal for loop
System.out.print(i);
System.out.println(j);
}
}
}
}
<file_sep>/src/innerclass/class1.java
package innerclass;
public class class1 {
public void inner() {
System.out.println("Inner class in class1");
}
}
<file_sep>/src/accessModifiers/example2.java
package accessModifiers;
public class example2 {
public static void main(String[] args) {
example1 ex2= new example1();
ex2.DefaultMethod();
ex2.ProtectedMethod();
ex2.publicMethod();
}
}
| dd7d0fb7b4c9f11993f4cc7380149d882712bb26 | [
"Java",
"INI"
] | 21 | Java | vnganji/dummypro | a30ebccac9fcc211525cb69469f4c493e0d3e8cf | 73d284ae6053a29f0e478e5ff8a44f49b3829113 |
refs/heads/master | <repo_name>AC34/docker-v3-php-nginx-composer<file_sep>/docker/run/nginx/Dockerfile
FROM nginx:latest
# copy path from docker-compose.yml
COPY ./docker/run/nginx/nginx.conf /etc/nginx/nginx.conf
COPY ./docker/run/nginx/default.conf /etc/nginx/conf.d/default.conf
<file_sep>/README.md


## note
Don't get confused about Docker version.
# About This repository:
This is an examaple of docker-compose usecase with php-fpm, nginx and composer altogether.
## Hot to use:
### 1)use -f option and tell docker-compose.run.yml (or other compose files)
### 2)don't forget to "up"
e.g. docker-compose -f docker-compose.run.yml up
### 3)accessing the page
```
localhost:8080
```
from your browser.
## Points:
### 3)Composer
When dealing with composer image and composer commands, always use CMD instead of RUN.
```
COPY
```
directive is not used for
```
composer install
```
in Dockerfile, files are shared by
```
volumes
```
directive in compose file.
### 4)nginx directory.
```
./code/index/
```
is used for nginx's root directory.
Any files that are on this directory are EXPOSED to public.
In the wild web world, some people are actually exposing their WHOLE APP directory by nginx(which absolutely is not recommended).
<file_sep>/code/index/index.php
<?php
echo "hello world from index.php<br>";
echo "request_uri=".$_SERVER["REQUEST_URI"]."<br>";
echo "loading app.php<br>";
require("../app/app.php");
<file_sep>/docker/tests/Composer/Dockerfile
FROM composer:latest
CMD composer install &&\
composer dotest
<file_sep>/code/tests/MyClassTest.php
<?php
use PHPUnit\Framework\TestCase;
class MyClassTest extends TestCase{
function testMyClass(){
$c = new MyClass();
$this->assertEquals($c->hello(),"hello");
}
}<file_sep>/code/app/MyClass.php
<?php
class MyClass{
public function hello(){
return "hello";
}
}<file_sep>/code/tests/testloader.php
<?php
//this file will be looked at from /code (not /code/tests/) when loaded from phpunit.xml for unittest
require_once("app/MyClass.php");
require_once("vendor/autoload.php");<file_sep>/code/app/app.php
<?php
echo "this is app.php";<file_sep>/docker/run/php/Dockerfile
FROM php:7-fpm
COPY ./code /var/www/
| daf031020c53ebf6bc1e143ce0803990fe5af389 | [
"Markdown",
"Dockerfile",
"PHP"
] | 9 | Dockerfile | AC34/docker-v3-php-nginx-composer | 14e83fea12ae20cbf56403cc0119155aad6de6c2 | b17f73f1cd032943f599d74d3beca4dc00827257 |
refs/heads/master | <repo_name>DSM-Undefined/Get-Terra-Server<file_sep>/Server/server.py
from app import create_app
from model.booth import BoothModel
from model.team import TeamModel
from random import choice
app = create_app()
@app.route('/test')
def a():
teams = TeamModel.objects(teamName__ne='empty')
for booth in BoothModel.objects():
t = choice(teams)
booth.own_team = t
booth.save()
return '', 200
if __name__ == '__main__':
app.run('0.0.0.0', port=1234)
<file_sep>/Server/test/team/test_team_post.py
from test import TCBase, check_status_code
from test.requests import team_post_request
from model.user import UserModel
class TeamPostTest(TCBase):
def check_user_team(self, user_id='test', team_number=0):
user = UserModel.objects(user_id=user_id).first()
self.assertEqual(user.team.team_id, team_number)
@check_status_code(201)
def test_success_team_post(self):
rv = team_post_request(self)
self.check_user_team(team_number=1)
return rv
@check_status_code(204)
def test_already_has_team(self):
team_post_request(self)
self.check_user_team(team_number=1)
rv = team_post_request(self, team_number=2)
self.check_user_team(team_number=1)
return rv
@check_status_code(205)
def test_wrong_team_number1(self):
rv = team_post_request(self, team_number=-1)
self.check_user_team()
return rv
@check_status_code(205)
def test_wrong_team_number2(self):
rv = team_post_request(self, team_number=5)
self.check_user_team()
return rv
<file_sep>/Server/test/map/test_map_get.py
from json import loads
from test import TCBase, check_status_code
from test.requests import map_get_request
class MapGetTest(TCBase):
@check_status_code(200)
def test_success_map_get(self):
rv = map_get_request(self)
res_json = loads(rv.data, encoding='utf-8')
self.assertEqual(res_json['myTeam'], self.test_user.team.team_id)
self.assertEqual(res_json['myTeamColor'], self.test_user.team.team_color)
map_ = res_json['map']
for i in range(5):
self.assertEqual(map_[f'booth{i}'], -1)
return rv
<file_sep>/Server/util.py
from functools import wraps
from flask import abort, g
from flask_jwt_extended import get_jwt_claims
from model.user import UserModel
from model.game import GameModel
def add_claims(user_id):
return {
'user_id': user_id,
'game_key': UserModel.objects(user_id=user_id).first().game.game_key
}
def set_g_object(fn):
@wraps(fn)
def wrapper(*arg, **kwargs):
jwt = get_jwt_claims()
g.game: GameModel = GameModel.objects(game_key=jwt['game_key']).first()
if not g.game:
abort(403)
g.user: UserModel = UserModel.objects(user_id=jwt['user_id'], game=g.game).first()
if not g.user:
abort(403)
return fn(*arg, **kwargs)
return wrapper
<file_sep>/requirements.txt
flask
flask_cors
flask_jwt_extended
flask_restful
flasgger
mongoengine
<file_sep>/Server/view/__init__.py
import os
import threading
import time
from flask import request, Flask
from flask_restful import Api
class Util:
def reload_server(self):
time.sleep(2)
os.system('. ../hook.sh')
def webhook_event_handler(self):
if request.headers['X-GitHub-Event'] == 'push':
threading.Thread(target=self.reload_server).start()
return 'hello'
class Router(Util):
def __init__(self, app: Flask):
self.app = app
self.api = Api(app)
def register(self):
self.app.add_url_rule('/hook', view_func=self.webhook_event_handler, methods=['POST'])
from view.auth import AuthView
self.api.add_resource(AuthView, '/auth/<int:gameKey>')
from view.map import MapView
self.api.add_resource(MapView, '/map')
from view.solve import SolveView
self.api.add_resource(SolveView, '/solve/<boothName>')
from view.team import TeamView
self.api.add_resource(TeamView, '/team')
<file_sep>/Server/model/user.py
from mongoengine import *
from model.game import GameModel
from model.team import TeamModel
class UserModel(Document):
"""
사용자 정보 관련 Collection
"""
meta = {
'collection': 'user'
}
game: GameModel = ReferenceField(
document_type=GameModel,
required=True,
reverse_delete_rule=CASCADE
)
user_id = StringField(
required=True
)
email = StringField(
required=True
)
password = StringField(
required=True
)
team: TeamModel = ReferenceField(
document_type=TeamModel,
required=True
)
<file_sep>/Server/test/team/test_team_get.py
from test import TCBase, check_status_code
from test.requests import team_get_request
class TeamGetTest(TCBase):
@check_status_code(200)
def test_success(self):
return team_get_request(self)
<file_sep>/Server/test/requests.py
from json import dumps
def check_game_key_request(self, game_key=100000):
return self.client.get(
'/auth/' + str(game_key)
)
def auth_request(self, game_key=100000, id_='Nerd-Bear', password='<PASSWORD>', email='<EMAIL>'):
return self.client.post(
'/auth/'+str(game_key),
data=dumps(dict(id=id_, password=<PASSWORD>, email=email)),
content_type='application/json'
)
def map_get_request(self):
return self.client.get(
'/map',
headers={'Authorization': self.access_token}
)
def solve_get_request(self, booth_name='booth0'):
return self.client.get(
f'/solve/{booth_name}',
headers={'Authorization': self.access_token}
)
def solve_post_request(self, booth_name='booth0', problem_id=1, answer='1'):
return self.client.post(
f'/solve/{booth_name}',
data=dumps(dict(problemId=problem_id, answer=answer)),
content_type='application/json',
headers={'Authorization': self.access_token}
)
def team_get_request(self):
return self.client.get(
'/team',
headers={'Authorization': self.access_token}
)
def team_post_request(self, team_number=1):
return self.client.post(
f'/team?team={team_number}',
headers={'Authorization': self.access_token}
)
<file_sep>/Server/app.py
from flask import Flask
from flask_cors import CORS
from flasgger import Swagger
from flask_jwt_extended import JWTManager
from mongoengine import connect
from config import Config
from view import Router
from util import add_claims
def create_app() -> Flask:
app: Flask = Flask(__name__)
app.config.from_object(Config)
Router(app).register()
CORS(app)
jwt = JWTManager(app)
jwt.user_claims_loader(add_claims)
connect('get-terra')
Swagger(app, template=app.config['SWAGGER_TEMPLATE'])
return app
<file_sep>/Server/model/game.py
from mongoengine import *
class GameModel(Document):
meta = {
'collection': 'game'
}
game_key = IntField(
primary_key=True
)
start_time = DateTimeField(
required=True
)
end_time = DateTimeField(
required=True
)
team_count = IntField(
required=True,
min_value=0,
max_value=100
)
<file_sep>/Server/view/team.py
from typing import List
from flask_restful import Resource
from flasgger import swag_from
from flask_jwt_extended import jwt_required
from flask import abort, jsonify, Response, request, g
from docs.team import TEAM_GET, TEAM_POST
from model.user import UserModel
from model.team import TeamModel
from util import set_g_object
class TeamView(Resource):
@swag_from(TEAM_GET)
@jwt_required
@set_g_object
def get(self) -> Response:
team_objects: List[TeamModel] = TeamModel.objects(game=g.game)
result = {'teamCount': len(team_objects)}
for team in team_objects:
result[str(team.team_id)] = {
'member': [user.user_id for user in UserModel.objects(team=team)],
'teamColor': team.team_color
}
return jsonify(result)
@swag_from(TEAM_POST)
@jwt_required
@set_g_object
def post(self) -> Response:
if not g.user:
abort(403)
if g.user.team.team_id != 0:
return Response('', 204)
team: TeamModel = TeamModel.objects(team_id=int(request.args.get('team'))).first()
if (not team) or len(UserModel.objects(team=team)) > 5:
return Response('', 205)
g.user.team = team
g.user.save()
return Response('', 201)
<file_sep>/Server/docs/map.py
from . import jwt_header
MAP_GET = {
'tags': ['Map'],
'description': '안드로이드 현재 맵 상황',
'parameters': [jwt_header],
'responses': {
'200': {
'description': """get 성공
1: 우리팀이 점령함
0: 다른팀이 점령함
-1: 아직 점령이 안됨
""",
'examples': {
'': {
'map': {
'GRAM': 1,
'시나브로': 0,
'Undefined': 1,
'NoNamed': -1,
'LUNA': -1
},
'myTeam': 3,
'myTeamColor': '#58c9b9'
}
}
},
'401': {
'description': 'request header 에 access token 없음 '
},
'403': {
'description': '권한 없음'
}
}
}<file_sep>/Server/model/problem.py
from mongoengine import *
from model.game import GameModel
class ProblemModel(Document):
"""
출제되는 문제에 관한 상위 Collection
"""
meta = {
'collection': 'problem'
}
game: GameModel = ReferenceField(
document_type=GameModel,
required=True,
reverse_delete_rule=CASCADE
)
problem_id = IntField(
primary_key=True
)
content = StringField(
required=True
)
answer = StringField(
required=True
)
choices = ListField(
StringField(
required=True
)
)
<file_sep>/Server/docs/solve.py
from . import jwt_header, parameter
SOLVE_GET = {
'tags': ['Solve'],
'description': '문제 get',
'parameters': [
jwt_header,
parameter('boothName', '부스 이름', 'url')
],
'responses': {
'200': {
'description': '성공',
'examples': {
'': {
'boothName': '부스 이름',
'problemId': '문제 아이디',
'content': '문제 내용',
'choices': [
'1번 보기',
'2번 보기',
'3번 보기',
'4번 보기'
]
}
}
},
'204': {
'description': '해당 부스아이디에 해당하는 부스 없음'
},
'205': {
'description': '이미 해당팀에서 점령한 부스임'
},
'401': {
'description': 'request header 에 access token 없음 '
},
'403': {
'description': '권한 없음'
},
'406': {
'description': '게임 시작 전'
},
'408': {
'description': '딜레이 시간'
},
'412': {
'description': '게임 종료'
}
}
}
SOLVE_POST = {
'tags': ['Solve'],
'description': '문제 정답 제출',
'parameters': [
jwt_header,
parameter('boothName', '부스 이름', 'url'),
parameter('problemId', '문제 아이디'),
parameter('answer', '정답 (보기 내용)')
],
'responses': {
'201': {
'description': '정답'
},
'204': {
'description:': '잘못된 문제 아이디 또는 잘못된 동아리 아이디'
},
'205': {
'description': '오답'
},
'401': {
'description': 'request header 에 access token 없음 '
},
'403': {
'description': '권한 없음'
},
'406': {
'description': '게임 시작 전'
},
'408': {
'description': '딜레이 시간'
},
'412': {
'description': '게임 종료'
}
}
}<file_sep>/Server/test/account/test_auth.py
from test import TCBase, check_status_code
from test.requests import auth_request
class AuthTest(TCBase):
@check_status_code(200)
def test_success_create_user(self):
return auth_request(self)
@check_status_code(200)
def test_success_auth_again(self):
auth_request(self)
return auth_request(self)
@check_status_code(204)
def test_wrong_game_key(self):
return auth_request(self, game_key=111111)
@check_status_code(205)
def test_fail_to_auth(self):
auth_request(self)
return auth_request(self, password='<PASSWORD>')
<file_sep>/readme.md
# 동아리경진대회 서버구축관련내용 협의안건(공통사항)
본 문서의 세부 사항은 다음과 같습니다.
| 항목 | 내용 |
| :-------: | :--------------------------------------------:|
| 설계 목적 | 대회 출전 |
| 구축 환경 | Flask, MongoDB, AWS EC2, Swagger |
| 참여자 | <NAME> |
## API 명세
API에 대한 자세한 내용은 다음 사이트(swagger)에 정리되어 있다.
[http://ec2.istruly.sexy:1234/docs]()
<file_sep>/Server/view/auth.py
from datetime import timedelta
from flask_restful import Resource
from flasgger import swag_from
from flask import request, jsonify, Response
from flask_jwt_extended import create_access_token
from werkzeug.security import check_password_hash, generate_password_hash
from docs.account import AUTH_POST, CHECK_GAME_KEY_GET
from model.user import UserModel
from model.game import GameModel
from model.team import TeamModel
class AuthView(Resource):
@swag_from(CHECK_GAME_KEY_GET)
def get(self, gameKey: int) -> Response:
if not GameModel.objects(game_key=gameKey).first():
return Response('', 204)
return jsonify({'gameKey': gameKey})
@swag_from(AUTH_POST)
def post(self, gameKey: int) -> Response:
payload: dict = request.json
game: GameModel = GameModel.objects(game_key=gameKey).first()
if not game:
return Response('', 204)
user: UserModel = UserModel.objects(user_id=payload['id'], game=game).first()
if user:
if check_password_hash(user.password, payload['password']):
return jsonify({'accessToken': create_access_token(payload['id'], expires_delta=timedelta(days=10))})
else:
return Response('', 205)
default_team: TeamModel = TeamModel.objects(game=game, team_id=0).first()
UserModel(game, payload['id'], payload['email'], generate_password_hash(payload['password']), default_team).save()
return jsonify({'accessToken': create_access_token(payload['id'], expires_delta=timedelta(days=10))})
<file_sep>/Server/test/solve/test_solve_post.py
from datetime import datetime, timedelta
from model.booth import BoothModel
from test import TCBase, check_status_code
from test.requests import solve_post_request
class SolvePostTest(TCBase):
@check_status_code(201)
def test_success_solve_post(self):
rv = solve_post_request(self)
booth = BoothModel.objects(booth_name='booth0').first()
self.assertEqual(booth.own_team, self.test_user.team)
return rv
@check_status_code(204)
def test_wrong_problem_id(self):
return solve_post_request(self, problem_id=2)
@check_status_code(204)
def test_wrong_booth_id(self):
return solve_post_request(self, booth_name='wrong')
@check_status_code(205)
def test_wrong_answer(self):
return solve_post_request(self, answer='2')
@check_status_code(406)
def test_before_start_game(self):
self.test_game.start_time = datetime.now() + timedelta(days=1)
self.test_game.save()
return solve_post_request(self)
@check_status_code(408)
def test_delay(self):
solve_post_request(self)
return solve_post_request(self)
@check_status_code(412)
def test_after_end_game(self):
self.test_game.end_time = datetime.now() - timedelta(days=1)
self.test_game.save()
return solve_post_request(self)
<file_sep>/Server/docs/__init__.py
def parameter(name, description, in_='json', type='str', required=True):
return {
'name': name,
'description': description,
'in': in_,
'type': type,
'required': required
}
jwt_header = parameter('Authorization', 'JWT Token', 'header')
game_key = parameter('gameKey', '게임 인증키', 'uri', 'int')
<file_sep>/Server/model/booth.py
from mongoengine import *
from datetime import datetime
from model.game import GameModel
from model.team import TeamModel
class BoothModel(Document):
"""
부스에 관한 정보가 담겨있는 Collection
"""
meta = {
"collection": "booth"
}
game: GameModel = ReferenceField(
document_type=GameModel,
required=True,
reverse_delete_rule=CASCADE
)
booth_name = StringField(
primary_key=True,
required=True
)
own_team: TeamModel = ReferenceField(
document_type=TeamModel,
required=True
)
next_capture_time = DateTimeField(
default=datetime(2001, 4, 20)
)
<file_sep>/Server/test/solve/test_solve_get.py
from datetime import datetime, timedelta
from json import loads
from test import TCBase, check_status_code
from test.requests import team_post_request, solve_get_request
class SolveGetTest(TCBase):
@check_status_code(200)
def test_success(self):
team_post_request(self)
rv = solve_get_request(self)
res_json = loads(rv.data, encoding='utf-8')
self.assertEqual(res_json['boothName'], 'booth0')
self.assertEqual(res_json['problemId'], 1)
self.assertEqual(res_json['content'], 'test')
self.assertEqual(res_json['choices'], ['1', '2', '3', '4'])
return rv
@check_status_code(204)
def test_wrong_booth_name(self):
return solve_get_request(self, booth_name='wrong')
@check_status_code(406)
def test_before_start_game(self):
self.test_game.start_time = datetime.now() + timedelta(days=1)
self.test_game.save()
return solve_get_request(self)
@check_status_code(412)
def test_after_end_game(self):
self.test_game.end_time = datetime.now() - timedelta(days=1)
self.test_game.save()
return solve_get_request(self)
<file_sep>/Server/view/solve.py
from datetime import datetime, timedelta
from random import choice
from flask_restful import Resource
from flasgger import swag_from
from flask import Response, jsonify, abort, request, g
from flask_jwt_extended import jwt_required
from docs.solve import SOLVE_GET, SOLVE_POST
from model.game import GameModel
from model.problem import ProblemModel
from model.booth import BoothModel
from util import set_g_object
class SolveView(Resource):
def _check_time(self, game: GameModel):
now: datetime = datetime.now()
if now < game.start_time:
abort(406)
if game.end_time <= now:
abort(412)
@swag_from(SOLVE_GET)
@jwt_required
@set_g_object
def get(self, boothName: str) -> Response:
self._check_time(g.game)
booth: BoothModel = BoothModel.objects(booth_name=boothName).first()
if not booth:
return Response('', 204)
if booth.own_team == g.user.team:
return Response('', 205)
if booth.next_capture_time > datetime.now():
abort(408)
problem: ProblemModel = choice(ProblemModel.objects())
response = {'boothName': boothName,
'problemId': problem.problem_id,
'content': problem.content,
'choices': problem.choices}
return jsonify(response)
@swag_from(SOLVE_POST)
@jwt_required
@set_g_object
def post(self, boothName: str) -> Response:
self._check_time(g.game)
payload: dict = request.json
problem: ProblemModel = ProblemModel.objects(problem_id=payload['problemId']).first()
booth: BoothModel = BoothModel.objects(booth_name=boothName).first()
if not all((problem, booth)):
return Response('', 204)
if booth.next_capture_time > datetime.now():
abort(408)
if payload['answer'] != problem.answer:
return Response('', 205)
booth.own_team = g.user.team
booth.next_capture_time = datetime.now() + timedelta(minutes=1)
booth.save()
return Response('', 201)
<file_sep>/Server/model/team.py
from mongoengine import *
from model.game import GameModel
class TeamModel(Document):
meta = {
'collection': 'team'
}
game: GameModel = ReferenceField(
document_type=GameModel,
required=True,
reverse_delete_rule=CASCADE
)
team_id = IntField(
required=True
)
team_color = StringField(
required=True
)
<file_sep>/Server/docs/account.py
from . import parameter
CHECK_GAME_KEY_GET = {
'tags': ['Account'],
'description': '게임키 유효성 확인',
'parameters': [
parameter('gameKey', '게임 인증키', 'uri', 'int')
],
'responses': {
'200': {
'description': '유효한 인증키',
'examples': {
'': {
'gameKey': '게임키 들어갈거임'
}
}
},
'204': {
'description': '잘못된 게임 인증키'
}
}
}
AUTH_POST = {
'tags': ['Account'],
'description': '로그인',
'parameters': [
parameter('gameKey', '게임 인증키', 'uri', 'int'),
parameter('id', '아이디'),
parameter('password', '<PASSWORD>'),
parameter('email', '이메일')
],
'responses': {
'200': {
'description': '인증 또는 회원가입 성공',
'examples': {
'': {
'accessToken': '액세스 토오오오큰'
}
}
},
'204': {
'description': '잘못된 게임 인증키'
},
'205': {
'description': '잘못된 비밀번호'
}
}
}
<file_sep>/Server/test/account/test_check_game_key.py
from test import TCBase, check_status_code
from test.requests import check_game_key_request
class CheckGameKeyTest(TCBase):
@check_status_code(200)
def test_success_check_game_key(self):
return check_game_key_request(self)
@check_status_code(204)
def test_wrong_game_key(self):
return check_game_key_request(self, 111111)
<file_sep>/Server/config.py
import os
from datetime import datetime
from json import loads
class Config:
SERVICE_NAME = 'Get Terra'
SWAGGER = {
'title': SERVICE_NAME,
'specs_route': os.getenv('SWAGGER_URI', '/docs'),
'uiversion': 3,
'info': {
'title': SERVICE_NAME + ' API',
'version': '1.0',
'description': ''
},
'host': 'ec2.istruly.sexy:1234',
'basePath': '/',
}
SWAGGER_TEMPLATE = {
'schemes': [
'http'
],
'tags': [
{
'name': 'Account',
'description': '계정 관련 API'
},
{
'name': 'Map',
'description': '맵 관련 API'
},
{
'name': 'Solve',
'description': '문제 풀이 관련 API'
},
{
'name': 'Team',
'description': '팀 관련 API'
}
]
}
JSON_AS_ASCII = False
JWT_SECRET_KEY = os.getenv('SECRET_KEY', 'nerd-bear')
SECRET_KEY = os.getenv('SECRET_KEY', 'nerd-bear')
<file_sep>/Server/test/__init__.py
from datetime import datetime, timedelta
from functools import wraps
from json import dumps, loads
from mongoengine.connection import get_connection
from unittest import TestCase
from app import create_app
from model.booth import BoothModel
from model.game import GameModel
from model.team import TeamModel
from model.user import UserModel
from model.problem import ProblemModel
class TCBase(TestCase):
def setUp(self):
self.client = create_app().test_client()
self.init_game()
def tearDown(self):
connection = get_connection()
connection.drop_database('get-terra')
def init_game(self):
self.test_game = self._create_game()
self._create_team()
self._create_problem()
self._create_booth()
self.test_user, self.access_token = self._create_user_and_access_token()
def _create_game(self, game_key=100000, team_count=4):
test_game = GameModel(
game_key=game_key,
start_time=datetime.now(),
end_time=datetime.now()+timedelta(days=1),
team_count=team_count
)
test_game.save()
return test_game
def _create_team(self, team_count=4):
for i in range(team_count+1):
TeamModel(
game=self.test_game,
team_id=i,
team_color=hex(i*333333)
).save()
def _create_problem(self):
ProblemModel(
game=self.test_game,
problem_id=1,
content='test',
answer='1',
choices=['1', '2', '3', '4']
).save()
def _create_booth(self):
default_team = TeamModel.objects(team_id=0).first()
for i in range(5):
BoothModel(
game=self.test_game,
booth_name=f'booth{i}',
own_team=default_team,
).save()
def _create_user_and_access_token(self, game_key=100000, id_='test', password='<PASSWORD>', email='<EMAIL>'):
rv = self.client.post(
'/auth/' + str(game_key),
data=dumps(dict(id=id_, password=<PASSWORD>, email=email)),
content_type='application/json'
)
token = loads(rv.data, encoding='utf-8')['accessToken']
test_user = UserModel.objects(game=self.test_game, user_id=id_).first()
return test_user, f'Bearer {token}'
def check_status_code(status_code):
def decorator(fn):
@wraps(fn)
def wrapper(self, *args, **kwargs):
rv = fn(self, *args, **kwargs)
self.assertEqual(rv.status_code, status_code)
return wrapper
return decorator
<file_sep>/Server/view/map.py
from typing import List
from flask_restful import Resource
from flasgger import swag_from
from flask import jsonify, abort, g, Response
from flask_jwt_extended import jwt_required
from docs.map import MAP_GET
from model.booth import BoothModel
from model.team import TeamModel
from util import set_g_object
class MapView(Resource):
@swag_from(MAP_GET)
@jwt_required
@set_g_object
def get(self) -> Response:
if not g.user:
return abort(403)
default_team: TeamModel = TeamModel.objects(team_id=0, game=g.game).first()
map_: dict = {'map': {}, 'myTeam': g.user.team.team_id, 'myTeamColor': g.user.team.team_color}
booths: List[BoothModel] = BoothModel.objects(game=g.game)
for booth in booths:
if booth.own_team == default_team:
map_['map'][booth.booth_name] = -1
elif booth.own_team == g.user.team:
map_['map'][booth.booth_name] = 1
else:
map_['map'][booth.booth_name] = 0
return jsonify(map_)
<file_sep>/Server/docs/team.py
from . import parameter, jwt_header
TEAM_GET = {
'tags': ['Team'],
'description': '팀별 팀원 리스트',
'parameters': [
jwt_header
],
'responses': {
'200': {
'description': 'get 성공',
'examples': {
'': {
'teamCount': 4,
'1': {
'teamColor': '#aaaaaa',
'member': [
'ㅁㅁ',
'ㅇㅇ',
'ㄷㄷ'
],
},
'2': {
'teamColor': '#bbbbbb',
'member': [
'aa',
'dd'
]
},
'3': {
'teamColor': '#5a4b4d',
'member': []
},
'4': {
'teamColor': '#73847d',
'member': ['상민이']
}
}
}
},
'401': {
'description': 'request header 에 access token 없음 '
},
'403': {
'description': '권한 없음'
}
}
}
TEAM_POST = {
'tags': ['Team'],
'description': '팀 참가',
'parameters': [
jwt_header,
parameter('team', '팀 넘버', 'query string', 'int')
],
'responses': {
'201': {
'description': '참가 성공'
},
'204': {
'description': '이미 팀에 소속되어 있음'
},
'205': {
'description': '팀원 초과, 잘못된 팀 번호'
},
'401': {
'description': 'request header 에 access token 없음 '
},
'403': {
'description': '권한 없음'
}
}
} | 03b1545b374f650592aa9e6987a82dc4d0e9f841 | [
"Markdown",
"Python",
"Text"
] | 30 | Python | DSM-Undefined/Get-Terra-Server | 041727fca0c19325b257a17feef1bfd5501f01af | 844994e42bd45ba31f39c8a5cbe0bc85fd6338f7 |
refs/heads/master | <file_sep>export const categories = [
{ key: 'alternativeart', value: ' Alternative Art' },
{ key: 'pics', value: ' Pics' },
{ key: 'gifs', value: ' Gifs' },
{ key: 'adviceanimals', value: ' Advice Animals' },
{ key: 'cats', value: ' Cats' },
{ key: 'images', value: ' Images' },
{ key: 'photoshopbattles', value: ' PhotoShop Battles' },
{ key: 'hmmm', value: ' Hmmm' },
{ key: 'all', value: ' All' },
{ key: 'aww', value: ' Aww' },
];
<file_sep>import fetch from 'isomorphic-unfetch'
import { FETCH_REDDIT_DATA_SUCCESS, ENABLE_LOADER } from './constants';
export const fetchRedditData = key => {
return async function (dispatch) {
try {
let response = await fetch(`https://www.reddit.com/r/${key}.json`);
let categoryData = await response.json();
return dispatch(fetchRedditDataSuccess({ categoryData, key }))
}
catch (error) {
console.error(error)
}
}
};
export const fetchRedditDataSuccess = data => ({
type: FETCH_REDDIT_DATA_SUCCESS,
data,
});
export const initialiseLoaderAction = data => ({
type: ENABLE_LOADER,
});<file_sep># fabHotels
Single Page App Assignment
## Commands
npm run dev : to run the dev server
## npm Modules used
classnames : A simple JavaScript utility for conditionally joining classNames together.
### Styling Solution Used :
Styled JSX Supported in NEXT.js by default
<file_sep>import React, { Component } from 'react'
import { Provider } from 'react-redux';
import Head from 'next/head';
import { connect } from 'react-redux'
//Components
import Layout from '../../organisms/Layout/Layout';
import CategorySlides from '../../organisms/CategorySlides/CategorySlides';
import { fetchRedditData, initialiseLoaderAction } from '../../actions/actions';
class RedditPage extends Component {
static async getInitialProps({ reduxStore }) {
const response = await reduxStore.dispatch(fetchRedditData('alternativeart'));
return {
categoryData: response,
};
}
fetchCategoryData = (key) => {
const { fetchCategory, initialiseLoader } = this.props;
initialiseLoader();
fetchCategory(key);
}
render() {
const { categoryData, loader, selectedCategory } = this.props;
return (
<div>
<Head>
<title>Reddit Page</title>
</Head>
<Layout selectedCategory={selectedCategory} fetchCategoryData={this.fetchCategoryData}>
<CategorySlides categoryData={categoryData} loader={loader} selectedCategory={selectedCategory} />
</Layout>
</div>
)
}
}
const mapStateToProps = state => ({
categoryData: state.categoryData.categoryData,
loader: state.categoryData.loader,
selectedCategory: state.categoryData.selectedCategory,
});
const mapDispatchToProps = dispatch => {
return {
fetchCategory: (key) => dispatch(fetchRedditData(key)),
initialiseLoader: () => dispatch(initialiseLoaderAction()),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(RedditPage)
<file_sep>import React from 'react'
const Footer = () => {
return (
<div className='footer-wrapper'>
© 2019 Casa2 Stays Pvt. Ltd. All rights reserved.
<style jsx>{`
.footer-wrapper {
background: #1f2548;
padding: 10px;
color: #fff;
text-align: center;
font-size : 10px;
position: sticky;
bottom: 0;
}
`}
</style>
</div>
)
}
export default Footer;
<file_sep>import React, { Component } from 'react'
import CategoryLinkTab from '../CategoryLinkTab/CategoryLinkTab';
class NavBar extends Component {
renderCategoryTab = (category) => {
const { selectedCategory, fetchCategoryData } = this.props;
const { key, value } = category;
return <CategoryLinkTab categoryKey={key} value={value} fetchCategoryData={fetchCategoryData} key={key} selectedCategory={selectedCategory} />;
}
render() {
const { categories } = this.props;
return (
<ul className="row">
{categories.map(category => this.renderCategoryTab(category))}
<style jsx>{`
ul {
font-size: 10px;
background: #212c5d;
position: sticky;
top: 0;
justify-content: center;
padding: 10px;
}
@media(min-width: 1024px){
ul{
font-size: 16px;
}
}
`}</style>
</ul>
)
}
}
export default NavBar;<file_sep>import React from 'react'
const SlideMetaInfo = (props) => {
return (
<div className='meta-info'>
{props.comments && <i className='meta-field'><img src='/static/images/comment.png' alt='comment' /> <b>{props.comments}</b></i>}
{props.subscribers && <i className='meta-field'><img src='/static/images/subscribers.png' alt='comment' /> <b>{props.subscribers}</b></i>}
{props.views && <i className='meta-field'>views : <b>{props.views}</b></i>}
<style jsx>{`
.meta-info {
margin-top: 10px;
}
.meta-field {
margin-right: 15px;d
}
img {
width: 20px;
}
@media(min-width: 1024px) {
.meta-info {
margin-top: 15px;
}
}
`}
</style>
</div>
)
}
export default SlideMetaInfo;
<file_sep>import React, { Component } from 'react'
import LazyLoad from 'react-lazyload';
class RedditImage extends Component {
render() {
const { imageData, altText } = this.props;
const images = imageData && imageData.images;
let imageUrl = images && images[0].source.url;
imageUrl = imageUrl && imageUrl.replace(/amp;/g, '');
return (
<div className='col-xs-12'>
{imageUrl ?
<LazyLoad height={300} debounce={false}>
<img src={imageUrl} alt={altText} />
</LazyLoad> :
<img src='/static/images/unavailable-image.png' alt={altText} />}
<style jsx>{`
img {
width: 100%;
height: 200px;
border-radius: 10%;
}
@media(min-width: 768px){
img {
height: 300px;
}
}
@media(min-width: 1024px){
img {
height: 400px;
}
}
`}</style>
</div>
)
}
}
export default RedditImage;
<file_sep>import React, { Component } from 'react'
import styled from 'styled-components';
class Header extends Component {
render() {
const { className } = this.props;
return (
<div className={`header-wrapper row`} >
<h1>fabHotels</h1>
<img src='/static/images/fabHotel-image.jpg' alt='logoFabHotel' />
<style jsx>{`
.header-wrapper {
font-size: 30px;
color: #fff;
background: #465180;
padding: 5px 0;
justify-content: space-between;
padding: 10px 15px;
align-items: center;
}
h1 {
font-size: 30px;
}
img{
font-size: 10px;
width: 40px;
height: 40px;
border-radius: 50%;
}
@media(min-width:1024px){
.header-wrapper{
font-size: 40px;
justify-content: center;
}
h1 {
font-size: 50px;
margin-right: 30px;
}
img {
width: 60px;
height: 60px;
}
}
`}</style>
</div >
)
}
}
export default Header;<file_sep>import React, { Component } from 'react'
import CategorySlide from '../../molecules/CategorySlide/CategorySlide';
class CategorySlides extends Component {
renderCategorySlide = (child, index) => {
const { selectedCategory } = this.props;
const { data, kind } = child;
return <CategorySlide slideData={data} key={`${kind}${selectedCategory}${index}`} altTextProp={`${selectedCategory}${index}`} />;
}
render() {
const { categoryData, loader } = this.props;
const children = categoryData && categoryData.children;
return (
<div>
{loader && <div className='loader-wrapper'><img src='/static/images/loader.gif' alt='loader-image' /></div>}
{children && children.map((child, index) => this.renderCategorySlide(child, index))}
<style jsx>{`
div {
background: #4c5787;
}
.loader-wrapper {
min-height:100vh;
display: flex;
align-items: center;
justify-content: center;
}
`}
</style>
</div>
)
}
}
export default CategorySlides;
| cf815cdb929470983cb7f7e3e1dc037e97283080 | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | bikramjethi/fabHotels | 0ffc86b267f5ab375cc8a28281b507031557f709 | ef58cda423c2a36bb7b6641855f0726f0b73bea1 |
refs/heads/master | <repo_name>jsdjayanga/product-as<file_sep>/modules/integration/tests-integration/tests/src/test/java/org/wso2/appserver/integration/tests/config/EnvironmentVariableReadTestCase.java
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* 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 org.wso2.appserver.integration.tests.config;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.util.SystemOutLogger;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import org.wso2.appserver.integration.common.clients.WebAppAdminClient;
import org.wso2.appserver.integration.common.utils.ASIntegrationConstants;
import org.wso2.appserver.integration.common.utils.ASIntegrationTest;
import org.wso2.appserver.integration.common.utils.WebAppDeploymentUtil;
import org.wso2.appserver.integration.common.utils.WebAppTypes;
import org.wso2.carbon.automation.engine.context.TestUserMode;
import org.wso2.carbon.automation.engine.context.beans.User;
import org.wso2.carbon.automation.engine.exceptions.AutomationFrameworkException;
import org.wso2.carbon.automation.engine.frameworkutils.CodeCoverageUtils;
import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil;
import org.wso2.carbon.automation.engine.frameworkutils.ReportGenerator;
import org.wso2.carbon.automation.engine.frameworkutils.TestFrameworkUtils;
import org.wso2.carbon.automation.extensions.servers.carbonserver.CarbonServerManager;
import org.wso2.carbon.automation.extensions.servers.utils.ArchiveExtractor;
import org.wso2.carbon.automation.extensions.servers.utils.ClientConnectionUtil;
import org.wso2.carbon.automation.extensions.servers.utils.FileManipulator;
import org.wso2.carbon.automation.extensions.servers.utils.ServerLogReader;
import org.wso2.carbon.automation.test.utils.common.TestConfigurationProvider;
import org.wso2.carbon.integration.common.utils.mgt.ServerConfigurationManager;
import org.wso2.carbon.utils.ServerConstants;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.xml.xpath.XPathExpressionException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
/**
* This test class is use to test the JNDI Hibernate Integration
* If the app can't be deploy successfully and throws a NamingException it implies that the integration fails
*/
public class EnvironmentVariableReadTestCase extends ASIntegrationTest {
private static final Log log = LogFactory.getLog(EnvironmentVariableReadTestCase.class);
private TestUserMode userMode;
private WebAppAdminClient webAppAdminClient;
private ServerConfigurationManager serverManager;
private HttpClient httpClient = new HttpClient();
private int portOffset;
private int SERVER_PORT = 15000;
private int REGISTRY_PORT = 16000;
private Process process;
private static int defaultHttpPort = Integer.parseInt("9763");
private static int defaultHttpsPort = Integer.parseInt("9443");
private ServerLogReader inputStreamHandler;
private ServerLogReader errorStreamHandler;
private boolean isCoverageEnable = false;
private String coverageDumpFilePath;
private String carbonHome;
@BeforeClass(alwaysRun = true)
public void init() throws Exception {
super.init();
portOffset = 200;
String location = System.getProperty("carbon.zip");
String carbonHome = setUpCarbonHome(location);
Map<String, String> systemParams = new HashMap<>();
systemParams.put("-DportOffset", Integer.toString(portOffset));
Map<String, String> envpMap = System.getenv();
String[] envp = new String[envpMap.size() + 2];
Iterator it = envpMap.entrySet().iterator();
int index = 0;
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
envp[index++] = pair.getKey() + "=" + pair.getValue();
}
envp[index++] = "SERVER_PORT=" + SERVER_PORT;
envp[index++] = "REGISTRY_PORT=" + REGISTRY_PORT;
Path sourcePath =
Paths.get(TestConfigurationProvider.getResourceLocation(), "artifacts", "AS", "config",
"carbon.xml");
Path targetPath =
Paths.get(carbonHome, "repository", "conf", "carbon.xml");
applyConfiguration(sourcePath.toFile(), targetPath.toFile());
startServerUsingCarbonHome(carbonHome, systemParams, envp);
// Map<String, String> env = new HashMap<>();
// env.put("SERVER_PORT", Integer.toString(SERVER_PORT));
// env.put("REGISTRY_PORT", Integer.toString(REGISTRY_PORT));
// setEnv(env);
//
// serverManager = new ServerConfigurationManager(asServer);
// serverManager.applyConfigurationWithoutRestart(sourcePath.toFile(), targetPath.toFile(), true);
// serverManager.restartForcefully();
//
// super.init();
}
@Test(groups = "wso2.as", description = "Try to persist a Employee obj through the Sessionfactory")
public void testConnectingToJMXServer() throws Exception {
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://localhost:" + (SERVER_PORT + portOffset) +
"/jndi/rmi://localhost:" + (REGISTRY_PORT + portOffset) + "/jmxrmi");
Map<String, Object> environment = new HashMap<>();
String[] credentials = {"admin", "<PASSWORD>"};
environment.put(JMXConnector.CREDENTIALS, credentials);
JMXConnector jmxc = JMXConnectorFactory.connect(url, environment);
log.info("Connection Id =" + jmxc.getConnectionId());
}
public synchronized void startServerUsingCarbonHome(String carbonHome, Map<String, String> commandMap, String[] envp) throws AutomationFrameworkException {
if (this.process == null) {
this.portOffset = this.checkPortAvailability(commandMap);
Process tempProcess = null;
try {
if (!commandMap.isEmpty() && this.getPortOffsetFromCommandMap(commandMap) == 0) {
System.setProperty("carbon.home", carbonHome);
}
File e = new File(carbonHome);
log.info("Starting carbon server............. ");
String scriptName = TestFrameworkUtils.getStartupScriptFileName(carbonHome);
String[] parameters = this.expandServerStartupCommandList(commandMap);
String[] cmdArray;
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
e = new File(carbonHome + File.separator + "bin");
cmdArray = new String[]{"cmd.exe", "/c", scriptName + ".bat"};
cmdArray = this.mergePropertiesToCommandArray(parameters, cmdArray);
tempProcess = Runtime.getRuntime().exec(cmdArray, envp, e);
} else {
cmdArray = new String[]{"sh", "bin/" + scriptName + ".sh"};
cmdArray = this.mergePropertiesToCommandArray(parameters, cmdArray);
tempProcess = Runtime.getRuntime().exec(cmdArray, envp, e);
}
this.errorStreamHandler = new ServerLogReader("errorStream", tempProcess.getErrorStream());
this.inputStreamHandler = new ServerLogReader("inputStream", tempProcess.getInputStream());
this.inputStreamHandler.start();
this.errorStreamHandler.start();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
serverShutdown(portOffset);
} catch (Exception var2) {
log.error("Error while server shutdown ..", var2);
}
}
});
ClientConnectionUtil.waitForPort(defaultHttpPort + this.portOffset, 300000L, false, (String) this.asServer.getInstance().getHosts().get("default"));
long time = System.currentTimeMillis() + 60000L;
while (true) {
if (this.inputStreamHandler.getOutput().contains("Mgt Console URL") || System.currentTimeMillis() >= time) {
int httpsPort = defaultHttpsPort + this.portOffset;
String backendURL = this.asServer.getContextUrls().getSecureServiceUrl().replaceAll("(:\\d+)", ":" + httpsPort);
User superUser = this.asServer.getSuperTenant().getTenantAdmin();
ClientConnectionUtil.waitForLogin(backendURL, superUser);
log.info("Server started successfully.");
break;
}
}
} catch (XPathExpressionException | IOException var13) {
throw new IllegalStateException("Unable to start server", var13);
}
this.process = tempProcess;
}
}
private int checkPortAvailability(Map<String, String> commandMap) throws AutomationFrameworkException {
int portOffset = this.getPortOffsetFromCommandMap(commandMap);
if (ClientConnectionUtil.isPortOpen(defaultHttpPort + portOffset)) {
throw new AutomationFrameworkException("Unable to start carbon server on port " + (defaultHttpPort + portOffset) + " : Port already in use");
} else if (ClientConnectionUtil.isPortOpen(defaultHttpsPort + portOffset)) {
throw new AutomationFrameworkException("Unable to start carbon server on port " + (defaultHttpsPort + portOffset) + " : Port already in use");
} else {
return portOffset;
}
}
private int getPortOffsetFromCommandMap(Map<String, String> commandMap) {
return commandMap.containsKey("-DportOffset") ? Integer.parseInt((String) commandMap.get("-DportOffset")) : 0;
}
private String[] expandServerStartupCommandList(Map<String, String> commandMap) {
if (commandMap != null && commandMap.size() != 0) {
String[] cmdParaArray = null;
String cmdArg = null;
if (commandMap.containsKey("cmdArg")) {
cmdArg = (String) commandMap.get("cmdArg");
cmdParaArray = cmdArg.trim().split("\\s+");
commandMap.remove("cmdArg");
}
String[] parameterArray = new String[commandMap.size()];
int arrayIndex = 0;
Set entries = commandMap.entrySet();
String parameter;
for (Iterator i$ = entries.iterator(); i$.hasNext(); parameterArray[arrayIndex++] = parameter) {
Map.Entry entry = (Map.Entry) i$.next();
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (value != null && !value.isEmpty()) {
parameter = key + "=" + value;
} else {
parameter = key;
}
}
if (cmdArg != null) {
commandMap.put("cmdArg", cmdArg);
}
if (cmdParaArray != null && cmdParaArray.length != 0) {
return (String[]) ArrayUtils.addAll(parameterArray, cmdParaArray);
} else {
return parameterArray;
}
} else {
return null;
}
}
private String[] mergePropertiesToCommandArray(String[] parameters, String[] cmdArray) {
if (parameters != null) {
cmdArray = this.mergerArrays(cmdArray, parameters);
}
return cmdArray;
}
private String[] mergerArrays(String[] array1, String[] array2) {
return (String[]) ArrayUtils.addAll(array1, array2);
}
public synchronized void serverShutdown(int portOffset) throws AutomationFrameworkException {
if (this.process != null) {
log.info("Shutting down server..");
if (ClientConnectionUtil.isPortOpen(Integer.parseInt("9443") + portOffset)) {
int e = defaultHttpsPort + portOffset;
String url = null;
try {
url = this.asServer.getContextUrls().getBackEndUrl();
} catch (XPathExpressionException var10) {
throw new AutomationFrameworkException("Get context failed", var10);
}
String backendURL = url.replaceAll("(:\\d+)", ":" + e);
try {
ClientConnectionUtil.sendForcefulShutDownRequest(backendURL, this.asServer.getSuperTenant().getContextUser().getUserName(), this.asServer.getSuperTenant().getContextUser().getPassword());
} catch (AutomationFrameworkException var8) {
throw new AutomationFrameworkException("Get context failed", var8);
} catch (XPathExpressionException var9) {
throw new AutomationFrameworkException("Get context failed", var9);
}
long time = System.currentTimeMillis() + 300000L;
while (!this.inputStreamHandler.getOutput().contains("Halting JVM") && System.currentTimeMillis() < time) {
;
}
log.info("Server stopped successfully...");
}
this.inputStreamHandler.stop();
this.errorStreamHandler.stop();
this.process.destroy();
this.process = null;
if (this.isCoverageEnable) {
try {
log.info("Generating Jacoco code coverage...");
this.generateCoverageReport(new File(this.carbonHome + File.separator + "repository" + File.separator + "components" + File.separator + "plugins" + File.separator));
} catch (IOException var7) {
log.error("Failed to generate code coverage ", var7);
throw new AutomationFrameworkException("Failed to generate code coverage ", var7);
}
}
if (portOffset == 0) {
System.clearProperty("carbon.home");
}
}
}
public synchronized String setUpCarbonHome(String carbonServerZipFile) throws IOException, AutomationFrameworkException {
if (this.process != null) {
return this.carbonHome;
} else {
int indexOfZip = carbonServerZipFile.lastIndexOf(".zip");
if (indexOfZip == -1) {
throw new IllegalArgumentException(carbonServerZipFile + " is not a zip file");
} else {
String fileSeparator = File.separator.equals("\\") ? "\\" : "/";
if (fileSeparator.equals("\\")) {
carbonServerZipFile = carbonServerZipFile.replace("/", "\\");
}
String extractedCarbonDir = carbonServerZipFile.substring(carbonServerZipFile.lastIndexOf(fileSeparator) + 1, indexOfZip);
FileManipulator.deleteDir(extractedCarbonDir);
String extractDir = "carbontmp" + System.currentTimeMillis();
String baseDir = System.getProperty("basedir", ".") + File.separator + "target";
log.info("Extracting carbon zip file.. ");
(new ArchiveExtractor()).extractFile(carbonServerZipFile, baseDir + File.separator + extractDir);
this.carbonHome = (new File(baseDir)).getAbsolutePath() + File.separator + extractDir + File.separator + extractedCarbonDir;
try {
this.isCoverageEnable = Boolean.parseBoolean(this.asServer.getConfigurationValue("//coverage"));
} catch (XPathExpressionException var8) {
throw new AutomationFrameworkException("Coverage configuration not found in automation.xml", var8);
}
if (this.isCoverageEnable) {
this.instrumentForCoverage();
}
return this.carbonHome;
}
}
}
private void instrumentForCoverage() throws IOException, AutomationFrameworkException {
String scriptName = TestFrameworkUtils.getStartupScriptFileName(this.carbonHome);
if (System.getProperty("os.name").toLowerCase().contains("windows")) {
this.insertJacocoAgentToBatScript(scriptName);
if (log.isDebugEnabled()) {
log.debug("Included files " + CodeCoverageUtils.getInclusionJarsPattern(":"));
log.debug("Excluded files " + CodeCoverageUtils.getExclusionJarsPattern(":"));
}
} else {
this.insertJacocoAgentToShellScript(scriptName);
}
}
private void insertJacocoAgentToBatScript(String scriptName) throws IOException {
String jacocoAgentFile = CodeCoverageUtils.getJacocoAgentJarLocation();
this.coverageDumpFilePath = FrameworkPathUtil.getCoverageDumpFilePath();
CodeCoverageUtils.insertJacocoAgentToStartupBat(new File(this.carbonHome + File.separator + "bin" + File.separator + scriptName + ".bat"), new File(this.carbonHome + File.separator + "tmp" + File.separator + scriptName + ".bat"), "-Dcatalina.base", "-javaagent:" + jacocoAgentFile + "=destfile=" + this.coverageDumpFilePath + "" + ",append=true,includes=" + CodeCoverageUtils.getInclusionJarsPattern(":"));
}
private void insertJacocoAgentToShellScript(String scriptName) throws IOException {
String jacocoAgentFile = CodeCoverageUtils.getJacocoAgentJarLocation();
this.coverageDumpFilePath = FrameworkPathUtil.getCoverageDumpFilePath();
CodeCoverageUtils.insertStringToFile(new File(this.carbonHome + File.separator + "bin" + File.separator + scriptName + ".sh"), new File(this.carbonHome + File.separator + "tmp" + File.separator + scriptName + ".sh"), "-Dwso2.server.standalone=true", "-javaagent:" + jacocoAgentFile + "=destfile=" + this.coverageDumpFilePath + "" + ",append=true,includes=" + CodeCoverageUtils.getInclusionJarsPattern(":") + " \\");
}
private void generateCoverageReport(File classesDir) throws IOException, AutomationFrameworkException {
CodeCoverageUtils.executeMerge(FrameworkPathUtil.getJacocoCoverageHome(), FrameworkPathUtil.getCoverageMergeFilePath());
ReportGenerator reportGenerator = new ReportGenerator(new File(FrameworkPathUtil.getCoverageMergeFilePath()), classesDir, new File(CodeCoverageUtils.getJacocoReportDirectory()), (File) null);
reportGenerator.create();
log.info("Jacoco coverage dump file path : " + FrameworkPathUtil.getCoverageDumpFilePath());
log.info("Jacoco class file path : " + classesDir);
log.info("Jacoco coverage HTML report path : " + CodeCoverageUtils.getJacocoReportDirectory() + File.separator + "index.html");
}
public void applyConfiguration(File sourceFile, File targetFile) throws IOException {
FileChannel source = null;
FileChannel destination = null;
if (!targetFile.exists() && !targetFile.createNewFile()) {
throw new IOException("File " + targetFile + "creation fails");
}
source = (new FileInputStream(sourceFile)).getChannel();
destination = (new FileOutputStream(targetFile)).getChannel();
destination.transferFrom(source, 0L, source.size());
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
| 030914aa4c03ca59893c0256f6565ec05c44da9f | [
"Java"
] | 1 | Java | jsdjayanga/product-as | 2bec9a09e819f19fa520227c3ef8fd16338b6765 | 5a1755e525f463480d0690fa62ea00d86162881f |
refs/heads/main | <repo_name>php1301/react-native-typescript-examples<file_sep>/examples/3-gmail-clone/app/models/models.ts
export interface User {
id: number;
name: string;
email: string;
password: string;
avatar: string;
token?: string;
}
export interface Email {
id: number;
sender: string;
title: string;
time: string;
isRead: boolean;
isStarred: boolean;
content: string;
}
<file_sep>/examples/2-booking-car/googleAPI.ts
import {GOOGLE_MAPS_APIKEY} from './const';
// https://cloud.google.com/maps-platform/maps
const BASE_URL = 'https://maps.googleapis.com/maps/api/geocode/json?';
export interface GeoCodingResponse {
formatted_address: string;
geometry: {
location: {
lat: number;
lng: number;
};
};
}
export async function geoCoding(address: string) {
const response = await fetch(
`${BASE_URL}address=${address}&components=country:VN&key=${GOOGLE_MAPS_APIKEY}`,
);
const data = await response.json();
return data.results;
}
export async function reverseGeoCoding(latitude: number, longtitue: number) {
const response = await fetch(
`${BASE_URL}latlng=${latitude},${longtitue}&language=vi&key=${GOOGLE_MAPS_APIKEY}`,
);
const data = await response.json();
return data;
}
<file_sep>/README.md
# React Native Typescript examples
Learn React Native (with Typescript) by easy-to-difficult examples.
_For more basic examples, see [React Native Expo examples](https://github.com/robinhuy/react-native-expo-examples)_
## Run project in development
- Setting up the development environment: https://reactnative.dev/docs/environment-setup.
- Install dependencies: `yarn` (or `npm install`). On iOS run: `npx pod-install`.
- Run on Android: `yarn android` (or `npm run android`).
- Run on iOS: `yarn ios` (or `npm run ios`).
## Change example
Modify code in `App.tsx`, each example is an application.
## Preview
### 1. Quiz Game
Learn how to use: **Type Script static type checking**, **React Hook useEffect + Timer**
<img src="https://user-images.githubusercontent.com/12640832/101762123-9842e080-3b0f-11eb-951a-82fae0c2481b.gif" width="250" alt="Quiz Game" />
### 2. Booking Car
Learn how to use: **Native Base + React Native Vector Icons**, **React Native Maps + React Native Maps Directions**, **Google Map API**, **Keyboard + Keyboard Event**
<img src="https://user-images.githubusercontent.com/12640832/101765164-85320f80-3b13-11eb-8066-a5d4436ebd90.gif" width="250" alt="Booking Car" />
Note: To run this example, you must get & config Google Map API KEY for [Android](https://developers.google.com/maps/documentation/android-sdk/get-api-key) or [iOS](https://developers.google.com/maps/documentation/ios-sdk/get-api-key)
### 3. Gmail clone
Learn how to use: **API Sauce**, **MobX + MobX React Lite**, **React Context**, **React Navigation Authentication flows + useFocusEffect**, **React Native Web View**
<img src="https://user-images.githubusercontent.com/12640832/102325797-2d355600-3fb6-11eb-9975-dd8849782b48.gif" width="250" alt="Gmail clone" />
Note: To run this example, you must start the server ([https://github.com/robinhuy/fake-rest-api-nodejs](https://github.com/robinhuy/fake-rest-api-nodejs)) in folder `server`:
```
cd server
yarn
yarn start
```<file_sep>/examples/2-booking-car/const.ts
import {LatLng, Region} from 'react-native-maps';
// https://developers.google.com/maps/documentation/geocoding/get-api-key
export const GOOGLE_MAPS_APIKEY = 'Your API KEY';
export const initialCoordinate: LatLng = {
latitude: 20.9980766,
longitude: 105.7922312,
};
export const initialRegion: Region = {
latitude: initialCoordinate.latitude,
longitude: initialCoordinate.longitude,
latitudeDelta: 0.01,
longitudeDelta: 0.01,
};
export const initialLocation: string =
'48 Tố Hữu, Trung Văn, Từ Liêm, Hà Nội, Vietnam';
<file_sep>/examples/3-gmail-clone/app/models/Store.ts
import {makeAutoObservable, runInAction} from 'mobx';
import {createContext} from 'react';
import {create} from 'apisauce';
import AsyncStorage from '@react-native-community/async-storage';
import {Email, User} from './models';
const LOGIN_KEY = 'loginToken';
const AVATAR_KEY = 'avatar';
const DEFAULT_AVATAR =
'https://globalplatform.org/wp-content/uploads/2018/03/default-avatar.png';
// https://github.com/infinitered/apisauce
const api = create({
baseURL: 'http://192.168.1.111:3000', // Change 192.168.1.111 to your machine IP
headers: {'Content-Type': 'application/json'},
});
class Store {
isCheckingLoggedIn: boolean = true;
isLoginSuccess: boolean | null = null;
isLoading: boolean = false;
token: string = '';
avatar: string = DEFAULT_AVATAR;
emails: Email[] = [];
checkedEmailIds: number[] = [];
isShowToolbar: boolean = false;
emailContent: string = '';
constructor() {
// https://mobx.js.org/observable-state.html
makeAutoObservable(this);
// Add authorization request header
api.addRequestTransform((request) => {
if (this.token) {
request.headers.Authorization = 'Bearer ' + this.token;
}
});
// Handle unauthorized request
api.addResponseTransform((response) => {
if (response.data === 'Unauthorized') {
this.logout();
}
});
// Check user logged in
(async () => {
try {
const loginToken = await AsyncStorage.getItem(LOGIN_KEY);
const avatar = await AsyncStorage.getItem(AVATAR_KEY);
if (loginToken) {
this.setLoginSuccess(true);
this.setAvatar(avatar);
this.setToken(loginToken);
}
} catch (e) {
console.log(e);
}
// https://mobx.js.org/actions.html
runInAction(() => (this.isCheckingLoggedIn = false));
})();
}
setLoginSuccess = (result: boolean | null) => {
this.isLoginSuccess = result;
};
setToken = (token: string | null | undefined) => {
this.token = token || '';
};
setAvatar = (avatar: string | null | undefined) => {
this.avatar = avatar || DEFAULT_AVATAR;
};
setShowToolbar = (data: boolean) => {
this.isShowToolbar = data;
};
setEmails = (emails: Email[] | string | undefined) => {
if (!Array.isArray(emails)) {
emails = [];
}
this.emails = emails;
};
setCheckedEmailIds = (ids: number[]) => {
this.checkedEmailIds = ids;
};
setEmailContent = (data: string) => {
this.emailContent = data;
};
login = async (email: string, password: string) => {
const res = await api.post<User>('/login', {email, password});
if (res.ok) {
const user = res.data;
this.setLoginSuccess(true);
this.setAvatar(user?.avatar);
this.setToken(user?.token);
AsyncStorage.setItem(LOGIN_KEY, user?.token || '');
AsyncStorage.setItem(AVATAR_KEY, user?.avatar || '');
} else {
this.setLoginSuccess(false);
}
};
logout = () => {
this.setLoginSuccess(null);
this.setAvatar('');
AsyncStorage.setItem(LOGIN_KEY, '');
AsyncStorage.setItem(AVATAR_KEY, '');
};
getEmails = async (category: string) => {
runInAction(() => (this.isLoading = true));
const res = await api.get<Email[] | string>(`/${category}`);
if (res.ok) {
this.setEmails(res.data);
}
runInAction(() => (this.isLoading = false));
};
updateEmail = async (category: string, email: Email) => {
const res = await api.put<Email>(`/${category}/${email.id}`, email);
if (res.ok) {
return res.data;
}
};
moveEmails = async (
fromCategory: string,
toCategory: string,
emails: Email[],
) => {
const result = await Promise.all(
emails.map((email) =>
api.post(`/${toCategory}`, email).then(() => {
api.delete(`/${fromCategory}/${email.id}`);
}),
),
);
return result;
};
moveSelectedEmails = async (fromCategory: string, toCategory: string) => {
let selectedEmails = [];
let unselectedEmails = [];
for (let item of this.emails) {
if (this.checkedEmailIds.includes(item.id)) {
selectedEmails.push(item);
} else {
unselectedEmails.push(item);
}
}
await this.moveEmails(fromCategory, toCategory, selectedEmails);
this.setEmails(unselectedEmails);
this.setCheckedEmailIds([]);
this.setShowToolbar(false);
};
toggleStar = async (category: string, emailId: number) => {
this.emails = this.emails.map((email) => {
if (email.id === emailId) {
email.isStarred = !email.isStarred;
this.updateEmail(category, email);
}
return email;
});
};
checkEmail = (emailId: number) => {
const indexOfCheckedEmail = this.checkedEmailIds.indexOf(emailId);
if (indexOfCheckedEmail !== -1) {
this.checkedEmailIds.splice(indexOfCheckedEmail, 1);
} else {
this.checkedEmailIds.push(emailId);
}
if (this.checkedEmailIds.length === 0) {
this.setShowToolbar(false);
} else {
this.setShowToolbar(true);
}
};
}
export const StoreContext = createContext<Store>(new Store());
export default Store;
| c0be6e67aa7f880b8a1d1cb303c7edf104ea6dc0 | [
"Markdown",
"TypeScript"
] | 5 | TypeScript | php1301/react-native-typescript-examples | 9d0a9203e1a67dc72bee6469fbd5d14fee6454ac | b98f1e039594ba8f735a5deea89b8cceddc9f563 |
refs/heads/master | <file_sep># tests/test_views.py
from flask_testing import TestCase
from wsgi import app
class TestViews(TestCase):
def create_app(self):
app.config['TESTING'] = True
return app
def test_products_json(self):
response = self.client.get("/api/v1/products")
products = response.json
self.assertIsInstance(products, dict)
self.assertGreater(len(products), 2) # 2 is not a mistake here.
# -- READ --
def test_get_all_products(self):
response = self.client.get("/api/v1/products")
product = response.json
status_code = response.status_code
self.assertIsInstance(product, dict) # Check product is a JSON format
self.assertTrue(product) # Check product is not empty
self.assertEquals(status_code, 200) # Check request status code is 200
def test_get_product_found(self):
response = self.client.get("/api/v1/products/1")
product = response.json
status_code = response.status_code
self.assertIsInstance(product, dict) # Check product is a JSON format
self.assertIsNotNone(product) # Check product is not empty
self.assertEquals(status_code, 200) # Check request status code is 200
def test_get_product_not_found(self):
response = self.client.get("/api/v1/products/1000")
product = response.json
status_code = response.status_code
self.assertIsNone(product) # Check product is empty
#self.assertFalse(product) # Check product is empty
self.assertEquals(status_code, 404) # Check request status code is 404
# -- DELETE --
def test_delete_product(self):
response = self.client.delete("/api/v1/products/3")
delete_result = response.json
status_code = response.status_code
self.assertIsNone(delete_result)
self.assertEquals(status_code, 204) # Check request status code is 204
# Check product does not exist anymore
response = self.client.get("/api/v1/products/3")
get_result = response.json
self.assertEqual(response.status_code, 404)
self.assertIsNone(get_result)
# -- CREATE --
def test_create_product(self):
response = self.client.post("/api/v1/products", json={'name':'Netflix'})
create_result = response.json
status_code = response.status_code
self.assertIsInstance(create_result, dict)
self.assertIsNotNone(create_result)
self.assertEquals(status_code, 201)
# -- UPDATE --
def test_update_product_success(self):
response = self.client.patch("/api/v1/products/2", json={'name':'Toto'})
status_code = response.status_code
self.assertEquals(status_code, 204)
def test_update_product_id_not_found(self):
response = self.client.patch("/api/v1/products/123", json={'name':'Hello'})
status_code = response.status_code
self.assertEquals(status_code, 422)
def test_update_product_name_empty(self):
response = self.client.patch("/api/v1/products/2", json={'name':''})
status_code = response.status_code
self.assertEquals(status_code, 422)
<file_sep># wsgi.py
# pylint: disable=missing-docstring
from flask import Flask, jsonify, abort, request
import itertools
app = Flask(__name__)
PRODUCTS = {
1: { 'id': 1, 'name': 'Skello' },
2: { 'id': 2, 'name': 'Socialive.tv' },
3: { 'id': 3, 'name': '<NAME>'},
}
START_INDEX = len(PRODUCTS) + 1
IDENTIFIER_GENERATOR = itertools.count(START_INDEX)
@app.route('/')
def hello():
return "Hello World ! :) this is a test for CI/CD"
# READ
@app.route('/api/v1/products')
def get_products():
#print('Hello I am in products method')
return jsonify(PRODUCTS)
# READ
@app.route('/api/v1/products/<int:id>')
def get_product(id):
# product does not exist => return 404 error code
product = PRODUCTS.get(id)
if product is None:
abort(404)
# product exists => return the product (JSON format)
return jsonify(PRODUCTS[id]), 200
# DELETE
@app.route('/api/v1/products/<int:id>', methods=['DELETE'])
def delete_product(id):
product = PRODUCTS.pop(id, None)
if product is None:
abort(404)
return '', 204
# CREATE
@app.route('/api/v1/products', methods=['POST'])
def create_product():
new_product = request.get_json()
if new_product is None:
abort(404)
name = new_product.get('name')
if name == '':
abort(422)
next_id = next(IDENTIFIER_GENERATOR)
PRODUCTS[next_id] = {'id': next_id, 'name': name}
return jsonify(PRODUCTS[next_id]), 201
# UPDATE
@app.route('/api/v1/products/<int:id>', methods=['PATCH'])
def update_product(id):
print(f'Existing PRODUCTS = {PRODUCTS}')
data = request.get_json()
new_name = data.get('name')
print(f'Product {id} to update with new name {new_name}')
if PRODUCTS.get(id) is None or new_name == '':
print(f'Abort')
abort(422)
PRODUCTS[id]['name'] = new_name
print(f'New PRODUCTS = {PRODUCTS}')
return '', 204
if __name__ == "__main__":
print(f'PRODUCTS = {PRODUCTS}')
<file_sep># pylint: disable=missing-docstring
# pylint: disable=too-few-public-methods
import itertools
from flask import Flask, jsonify, abort, request
app = Flask(__name__)
BASE_URL = '/api/v1'
PRODUCTS = {
1: { 'id': 1, 'name': 'Skello' },
2: { 'id': 2, 'name': 'Socialive.tv' },
3: { 'id': 3, 'name': 'Le Wagon'},
}
START_INDEX = len(PRODUCTS) + 1
IDENTIFIER_GENERATOR = itertools.count(START_INDEX)
@app.route(f'{BASE_URL}/products', methods=['GET'])
def read_many_products():
products = list(PRODUCTS.values())
return jsonify(products), 200
@app.route(f'{BASE_URL}/products/<int:product_id>', methods=['GET'])
def read_one_product(product_id):
if product_id not in PRODUCTS:
abort(404)
return jsonify(PRODUCTS[product_id]), 200
@app.route(f'{BASE_URL}/products/<int:product_id>', methods=['DELETE'])
def delete_one_product(product_id):
if product_id not in PRODUCTS:
abort(404)
else:
del(PRODUCTS[product_id])
return '', 204
@app.route(f'{BASE_URL}/products', methods=['POST'])
def create_one_product():
data = request.get_json()
if data is None or 'name' not in data:
abort(400)
if data['name'] == '' or not isinstance(data['name'], str):
abort(422)
next_id = next(IDENTIFIER_GENERATOR)
PRODUCTS[next_id] = {'id' : next_id , 'name' : data['name'] }
return jsonify(PRODUCTS[next_id]), 201
@app.route(f'{BASE_URL}/products/<int:product_id>', methods=['PATCH'])
def update_one_product(product_id):
data = request.get_json()
if data is None or 'name' not in data:
abort(400)
if data['name'] == '' or not isinstance(data['name'], str):
abort(422)
if product_id not in PRODUCTS:
abort(404)
PRODUCTS[product_id]['name'] = data['name']
return '', 204
| 48333454d873db2d99bddc75e24c249562e6dabe | [
"Python"
] | 3 | Python | wongemilie/flask-crud | 962c2401739b74e28ae3957d08b1d59b25c4b354 | 350d14116af73bb9dacd8a64c1435acc0a830440 |
refs/heads/master | <repo_name>Duangrat-praj/Week4_HW<file_sep>/run_analysis.R
train_x <- read.table("./UCI HAR Dataset/train/X_train.txt",header=FALSE);
test_x <- read.table("./UCI HAR Dataset/test/X_test.txt",header=FALSE);
col_x <- read.table("./UCI HAR Dataset/features.txt",header=FALSE);
X <- rbind(train_x,test_x);
colnames(X) <- as.character(col_x[,2]);
train_y <- read.table("./UCI HAR Dataset/train/Y_train.txt",header=FALSE);
test_y <- read.table("./UCI HAR Dataset/test/Y_test.txt",header=FALSE);
col_y <- read.table("./UCI HAR Dataset/activity_labels.txt",header=FALSE);
Y <- rbind(train_y,test_y);
Y <- merge(x = Y, y = col_y, by = "V1", all.y = TRUE);
colnames(Y) <- c("V1","Activity");
train_id <- read.table("./UCI HAR Dataset/train/subject_train.txt",header=FALSE);
test_id <- read.table("./UCI HAR Dataset/test/subject_test.txt",header=FALSE);
id <- rbind(train_id,test_id);
colnames(id) <- c("Subject");
data <- cbind(id,X,Y);
data_c <- data[, grep("mean\\(\\)|std\\(\\)", colnames(data))];
names(data_c) <- gsub(x = names(data_c), pattern = "mean\\(\\)", replacement = "Mean");
names(data_c) <- gsub(x = names(data_c), pattern = "std\\(\\)", replacement = "STD");
names(data_c) <- gsub(x = names(data_c), pattern = "\\-", replacement = "_");
tidy_data <- cbind(Subject=id,Activity=Y$Activity,data_c);
tidy_data <- aggregate(. ~ Subject + Activity, data = tidy_data, FUN = mean);
write.table(tidy_data, file = "tidy_data.txt",row.name=FALSE) | 61f99b8e9362977a68e9d2c6803082dcd5266c47 | [
"R"
] | 1 | R | Duangrat-praj/Week4_HW | b4062d3321a488b60863b464e2b16e36bd257793 | 2388ba6e58a73a83af6d751fbc07989b9d3977af |
refs/heads/master | <file_sep>import { Component, OnInit } from '@angular/core';
import { WeatherService } from './../Service/weather.service';
@Component({
selector: 'app-search',
templateUrl: './search.page.html',
styleUrls: ['./search.page.scss'],
})
export class SearchPage implements OnInit {
City;
temp;
min;
max;
pressure;
APIinfor;
CityNames = [{city: 'pretoria'},
{city: 'Tembisa'},
];
CityName;
constructor(public weatherService: WeatherService) { }
ngOnInit() {
}
getcityweather() {
this.weatherService.getWeather(this.CityName).subscribe((data) => {
this.APIinfor = data;
console.log(this.APIinfor);
this.temp = Math.round(this.APIinfor.main.temp - 273.15);
this.max = Math.round(this.APIinfor.main.temp_max - 273.15);
this.min = Math.round(this.APIinfor.main.temp_min - 273.15);
this.pressure = Math.round(this.APIinfor.main.pressure - 273.15);
// console.log(this.temp);
// console.log(this.max);
// console.log(this.min);
// console.log(this.pressure);
});
}
}
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class WeatherService {
getCities = [];
CityName;
AIPID = '&APPID=7e44a929d6be6b582285a05399da4509';
constructor(public http: HttpClient) { }
getWeather(CityName) {
return this.http.get('http://api.openweathermap.org/data/2.5/weather?q=' + CityName + this.AIPID);
}
getCityWeather() {
// this.weatherService.getWeather().subscribe((data) => {
// this.APIinfor = data;
// console.log(this.APIinfor);
// this.temp = Math.round(this.APIinfor.main.temp - 273.15);
// this.max = Math.round(this.APIinfor.main.temp_max - 273.15);
// this.min = Math.round(this.APIinfor.main.temp_min - 273.15);
// this.pressure = Math.round(this.APIinfor.main.pressure - 273.15);
// console.log(this.temp);
// console.log(this.max);
// console.log(this.min);
// console.log(this.pressure);
// });
}
getCity() {
return this.getCities;
}
}
// http://api.openweathermap.org/data/2.5/weather?q=Pretoria&APPID=7e44a929d6be6b582285a05399da4509
// 'http//:api.openweathermap.org/data/2.5/weather?q=' + this.CityName + this.AIPID
<file_sep>import { WeatherService } from './../Service/weather.service';
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
CityNames = [{city: 'pretoria', id: '1'},
{city: 'Tembisa', id: '2'},
{city: 'Soweto', id: '3'},
{city: 'Cape Town', id: '4'},
{city: 'Durban', id: '5'},
];
CityName;
constructor(public weatherService: WeatherService) { }
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { WeatherService } from './../Service/weather.service';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-cityweather',
templateUrl: './cityweather.page.html',
styleUrls: ['./cityweather.page.scss'],
})
export class CityweatherPage implements OnInit {
City;
temp;
min;
max;
pressure;
APIinfor;
CityName;
constructor(public weatherService: WeatherService,
public route: ActivatedRoute) {
}
ngOnInit() {
this.route.paramMap.subscribe((params) => {
this.CityName = params.get('id');
console.log(this.CityName);
this.getWeather();
});
}
getWeather() {
this.weatherService.getWeather(this.CityName).subscribe((data) => {
this.APIinfor = data;
console.log(this.APIinfor);
this.temp = Math.round(this.APIinfor.main.temp - 273.15);
this.max = Math.round(this.APIinfor.main.temp_max - 273.15);
this.min = Math.round(this.APIinfor.main.temp_min - 273.15);
this.pressure = Math.round(this.APIinfor.main.pressure - 273.15);
// console.log(this.temp);
// console.log(this.max);
// console.log(this.min);
// console.log(this.pressure);
});
}
}
| 490d13ed9dee3e9e19772b72ea3db798762d069d | [
"TypeScript"
] | 4 | TypeScript | Nathi72TcF/WeatherApp | 8ff99b150d136858111ed7318d7a9bc07a255779 | 19404584924757876450191beff764a22e8fec0f |
refs/heads/master | <repo_name>prite44/AppForTest<file_sep>/app/src/main/java/com/jaskkit/news/Activity/DetailActivity.java
package com.jaskkit.news.Activity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jaskkit.news.Dao.NewItemDao;
import com.jaskkit.news.R;
import com.jaskkit.news.Util.MyCalendar;
import java.util.Locale;
public class DetailActivity extends AppCompatActivity {
private TextView dateView,titleView,detailView;
private String Language;
private NewItemDao list;
private Toolbar toolbar;
private ImageView imgView;
private String ImgUrl = "https://s3-ap-southeast-1.amazonaws.com/herbery/cuisine_image/news_image/etctutor/";
MyCalendar calendar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
list = getIntent().getParcelableExtra("detail");
initInstances();
}
private void initInstances() {
Language = Locale.getDefault().getDisplayLanguage();
//Toast.makeText(Contextor.getInstance().getContext(), Locale.getDefault().getDisplayLanguage(),Toast.LENGTH_SHORT).show();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
dateView = (TextView) findViewById(R.id.dateView);
titleView = (TextView) findViewById(R.id.titleView);
detailView = (TextView) findViewById(R.id.DetailView);
imgView = (ImageView) findViewById(R.id.ImgView);
if(Language.equals("ไทย")) {
dateView.setText(MyCalendar.getInstance().getThaidate(list.getUpdateDate()));
}
else{
dateView.setText(MyCalendar.getInstance().getEngdate(list.getUpdateDate()));
}
titleView.setText(list.getTitle());
detailView.setText(list.getDetail());
//textView = (TextView) findViewById(R.id.dateview);
//textView.setText(list.getTitle());
Glide.with(DetailActivity.this)
.load(ImgUrl+list.getUrlImage())
.asBitmap()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(imgView);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.detailmenu,menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.back) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable("object",list);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
list = savedInstanceState.getParcelable("object");
super.onRestoreInstanceState(savedInstanceState);
}
}
<file_sep>/app/src/main/java/com/jaskkit/news/Adapter/NewsAdapter.java
package com.jaskkit.news.Adapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jaskkit.news.Dao.NewItemDao;
import com.jaskkit.news.Manager.NewListManager;
import com.jaskkit.news.View.NewsListView;
/**
* Created by jaskkit on 4/20/16.
*/
public class NewsAdapter extends BaseAdapter{
private NewListManager dao;
private String ImgUrl = "https://s3-ap-southeast-1.amazonaws.com/herbery/cuisine_image/news_image/etctutor/";
@Override
public int getCount() {
if(dao.getInstance().getDao()==null)
return 0;
if(dao.getInstance().getDao().getNews()==null)
return 0;
return dao.getInstance().getDao().getNews().size();
}
@Override
public Object getItem(int position) {
return dao.getInstance().getDao().getNews().get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
NewsListView item;
if (convertView != null) {
item = (NewsListView) convertView;
} else {
item = new NewsListView(parent.getContext());
}
NewItemDao dao = (NewItemDao) getItem(position);
Glide.with(parent.getContext())
.load(ImgUrl+dao.getUrlImage())
.fitCenter()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(item.getImg());
item.setTitle(dao.getTitle());
return item;
}
}
<file_sep>/app/src/main/java/com/jaskkit/news/Manager/UnsafeOkHttpClient.java
package com.jaskkit.news.Manager;
import android.content.Context;
import com.jaskkit.news.Manager.Http.OkHttpClientService;
import com.squareup.okhttp.OkHttpClient;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
/**
* Created by jaskkit on 4/21/16.
*/
public class UnsafeOkHttpClient implements OkHttpClientService {
private static UnsafeOkHttpClient instance;
public static UnsafeOkHttpClient getInstance() {
if (instance == null)
instance = new UnsafeOkHttpClient();
return instance;
}
private Context mContext;
private UnsafeOkHttpClient() {
mContext = Contextor.getInstance().getContext();
}
@Override
public OkHttpClient getUnsafeOkHttpClient(int Certificate) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, KeyManagementException {
OkHttpClient okHttpClient = new OkHttpClient();
java.security.cert.Certificate ca = null;
// loading CAs from an InputStream
CertificateFactory cf = null;
try {
cf = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
e.printStackTrace();
}
InputStream cert = mContext.getResources().openRawResource(Certificate);
try {
ca = cf.generateCertificate(cert);
} catch (CertificateException e) {
e.printStackTrace();
} finally {
cert.close();
}
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());
return okHttpClient;
}
}
<file_sep>/app/src/main/java/com/jaskkit/news/Fragment/MainFragment.java
package com.jaskkit.news.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.jaskkit.news.Activity.DetailActivity;
import com.jaskkit.news.Adapter.NewsAdapter;
import com.jaskkit.news.Dao.NewItemCollectionDao;
import com.jaskkit.news.Dao.NewItemDao;
import com.jaskkit.news.Manager.Contextor;
import com.jaskkit.news.Manager.Http.ApiService;
import com.jaskkit.news.Manager.HttpManager;
import com.jaskkit.news.Manager.NewListManager;
import com.jaskkit.news.R;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
/**
* Created by jaskkit on 4/20/16.
*/
public class MainFragment extends Fragment {
private ListView listView;
private NewsAdapter adapterview;
public MainFragment() {
super();
}
public static MainFragment newInstance() {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news, container, false);
initInstances(rootView);
return rootView;
}
private void initInstances(View rootView) {
// Init 'View' instance(s) with rootView.findViewById here
listView = (ListView) rootView.findViewById(R.id.listView);
adapterview = new NewsAdapter();
listView.setAdapter(adapterview);
ApiService service = HttpManager.getInstance().getService();
service.getNewsList(new Callback<NewItemCollectionDao>() {
@Override
public void success(NewItemCollectionDao newItemCollectionDao, Response response) {
NewListManager.getInstance().setDao(newItemCollectionDao);
adapterview.notifyDataSetChanged();
}
@Override
public void failure(RetrofitError error) {
Toast.makeText(Contextor.getInstance().getContext(),error.getMessage(),Toast.LENGTH_SHORT);
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent detail = new Intent(Contextor.getInstance().getContext(), DetailActivity.class);
NewItemDao ac = NewListManager.getInstance().getDao().getNews().get(position);
detail.putExtra("detail",ac);
startActivity(detail);
}
});
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onStop() {
super.onStop();
}
/*
* Save Instance State Here
*/
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save Instance State here
}
/*
* Restore Instance State Here
*/
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore Instance State here
}
}
/*public void setPathImage(List<NewItemDao> NewItem){
for(NewItemDao item : NewItem){
Log.d("Key",item.getUrlImage().substring(14,16));
}
}*/
}
| c98b91d97d316b2849cb4042c861ff9d6cb119a5 | [
"Java"
] | 4 | Java | prite44/AppForTest | ce706510af4553eaa442ac3af491e13fa9ea8d50 | 3f9a26df279cbeb273b7037b8268313c01b47659 |
refs/heads/master | <file_sep>package com.pojogen.internal;
import static org.junit.Assert.assertEquals;
import java.math.BigDecimal;
import org.junit.Test;
public class ImmutableOhlcTest {
@Test
public void testImmutableOhlcGetters() {
BigDecimal open = BigDecimal.valueOf(100);
BigDecimal high = BigDecimal.valueOf(102);
BigDecimal low = BigDecimal.valueOf(98);
BigDecimal close = BigDecimal.valueOf(101);
Ohlc ohlc = new ImmutableOhlc(open, high, low, close);
assertEquals(open, ohlc.getOpen());
assertEquals(high, ohlc.getHigh());
assertEquals(low, ohlc.getLow());
assertEquals(close, ohlc.getClose());
}
}
<file_sep>include 'pojogen'
<file_sep>apply plugin: 'java'
configurations {
apt
}
repositories {
mavenCentral()
}
dependencies {
apt project(':pojogen')
compile project(':pojogen')
testCompile 'junit:junit:4.11' // Not required by pojogen, only by example tests
}
compileJava.classpath += configurations.apt
compileJava.options.compilerArgs = ["-processor", "com.pojogen.api.apt.PojoGenAnnotationProcessor"]
test {
include '**/*Test.class' // workaround http://stackoverflow.com/questions/14814837/gradle-test-fails-with-error
}
<file_sep># pojogen-example-gradle-dev
This is an example of a Gradle-based project using the development version of [pojogen](https://github.com/pojogen/pojogen)
[](https://travis-ci.org/pojogen/pojogen-example-gradle-dev)
## Running
To build and run this example, run the following at the root of the checkout:
./gradlew check
## License
See the [LICENSE](LICENSE) file for licensing information.
## Support
Please log tickets and issues at https://github.com/pojogen/pojogen/issues
| 484b285718e3600b18677df4ea875f1e5b63901c | [
"Markdown",
"Java",
"Gradle"
] | 4 | Java | pojogen/pojogen-example-gradle-dev | f0008df7e1ba10479f578f767022bc8eef749f69 | 758ae60af7e32c9532d6991b13c68d4f0efb7742 |
refs/heads/main | <repo_name>ishikagpta/Data-Structures-ArrayList-like-Structures-Stacks-and-Queues<file_sep>/ArrayList.java
/**
*
* @author <NAME>
* @class CSS 143 A
* @assignment Data Structures: ArrayList-like Structures, Stacks, and Queues;
* ArrayList class
* @date 10/25/20
*/
/**
* @version 1.0 This ArrayList class will create methods which will give
* resemblance to an ArrayList like structure of objects by using
* Arrays.
*/
public class ArrayList {
// values is an array of objects to help store values/elements in the ArrayList
// for operations
Object values[] = new Object[1];
// amtOfValues is an instance variable to keep track of the amount of
// elements/values in
// the values array of the ArrayList
int amtOfValues = 0;
/**
* This insert method takes a new element and the index it is meant to be
* inserted at and inserts it into the array of the ArrayList if the index is
* within the length of the array
*
* @param obj
* @param index
*/
public void insert(Object obj, int index) {
// This if method checks to see if the index is out of bounds of the values
// array, if it is it simply returns
if (index >= values.length || index < 0) {
return;
}
// This currentValues array makes an array of the length of the values array + 1
// to be able to add the new inserted element
Object[] currentValues = new Object[values.length + 1];
// creates a local variable z to be used in the for loop below
int z = 0;
// this for loop iterates through the currentValues array and sets it equal to
// the values array. If the index of the currentValues array matches the index
// given by the parameter, than it inserts the new element into the array at
// that index
for (int r = 0; r < currentValues.length; r++) {
if (!(r == index)) {
currentValues[r] = values[z];
z++;
} else {
currentValues[r] = obj;
}
}
// the original values array is then set to be equal to the currentValues array
// which has the new element and is one size larger than the original values
// array
values = currentValues;
// the instance variable amtOfValues is upped by one as one more element is
// added to the values array
amtOfValues++;
}
/**
* This indexOf method takes an object input and finds what index the object is
* at in the values array and returns it
*
* @param ob
* @return b
*/
public int indexOf(Object ob) {
// creates local variable b to store the index of the Object in the argument.
// Initialized to
// -1 in case index of the Object is not found.
int b = -1;
// this for loop iterates through the values array and if the Object input
// equals the element at any of the indexes, the index is stored in b
for (int z = 0; z < values.length; z++) {
if (ob == values[z]) {
b = z;
}
}
// the index at which the Object is found at is returned, if index is not found
// then -1 is returned
return b;
}
/**
* This method returns the size of the values array storing the ArrayList by
* returning the instance variable amtOfValues keeping track of the amount of
* elements in the values array.
*
* @return amtOfValues
*/
public int size() {
return amtOfValues;
}
/**
* This method takes in an index as an argument and removes the Object at that
* index in the values array storing the ArrayList
*
* @param index
* @return ob
*/
public Object remove(int index) {
// this local Object variable will store the object at the given index and is
// initially set to null in case the index is out of bounds
Object ob = null;
// checks to see if the index is within bounds of the values array storing the
// ArrayList. If not, then it returns null.
if (values == null || index < 0 || index >= values.length) {
return ob;
}
// creates currentValues array of type Object that is one size less than the
// length of the values array storing the ArrayList
Object[] currentValues = new Object[values.length - 1];
// sets the local variable ob Object to be equal to the element of the argument
// index
ob = values[index];
// this for loop cycles through until one less than the index number and sets
// the currentValues array equal to the values array storing the ArrayList
for (int z = 0; z < index; z++) {
currentValues[z] = values[z];
}
// this for loop circles through the index number until less than one less than
// the length of the values array storing the ArrayList and sets the
// currentValues array equal to the values array + 1 that stores the ArrayList
for (int z = index; z < values.length - 1; z++) {
currentValues[z] = values[z + 1];
}
// this sets the values array storing the ArrayList equal to the currentValues
// array
values = currentValues;
// this subtracts one from the instance variable amtOfValues keeping track of
// the elements in the values array since one element has been removed
amtOfValues--;
// this returns the Object removed at the given argument index
return ob;
}
/**
* This method returns all the elements of the values array storing the
* ArrayList in one line as a String
*/
public String toString() {
// creates an empty local String called elements
String elements = "";
// this for loop goes until it is one less than the instance variable
// amtOfValues that keeps track of the amount of elements and adds each element
// from the values array and a space between them into the elements String
for (int z = 0; z < amtOfValues; z++) {
elements = elements + values[z] + " ";
}
// this returns the String elements containing a String of all the elements in
// the values array storing the ArrayList
return elements;
}
/**
* This method checks to see if one object given in the argument is equal to the
* ArrayList stored in the values array
*
* @param obj
* @return everyElement
*/
public boolean equals(Object obj) {
// first casts and sets the object equal to ArrayList
ArrayList ob = (ArrayList) obj;
// creates a boolean to check to see if the two ArrayLists are equal. Initially
// set to true.
boolean everyElement = true;
// this checks to see if the length of the values array storing the ArrayList is
// the same as the size of the argument ArrayList. If it is it then goes into a
// for loop that checks to see if every element in the argument ArrayList and
// the values array storing ArrayList are equal. If not, everyElement is set to
// false and is then returned as such. If it is, the initial value of true is
// returned. If the two ArrayLists are not the same size, everyElement returns
// and is set to false.
if (this.values.length == ob.size()) {
for (int z = 0; z < this.values.length; z++) {
if (this.values[z] != (Object) ob.get(z)) {
everyElement = false;
}
}
return everyElement;
} else {
return everyElement = false;
}
}
/**
* This method gets the Object of the ArrayList stored at the given index in the
* argument within the values array and returns it
*
* @param index
* @return ob
*/
public Object get(int index) {
// Object ob is a local variable that will store the Object at the given index
// that is set to null initially
Object ob = null;
// checks to see if the index is within bounds of the values array containing
// the ArrayList. If not, it returns null. If it is, it returns the element at
// the given index in the values array containing the ArrayList
if (index < 0 || index > amtOfValues) {
return ob;
} else {
return ob = values[index];
}
}
/**
* Checks to see if the values array containing the ArrayList is empty. If the
* instance variable amtOfValues keeping track of the amount of elements in the
* values array containing the ArrayList equals 0 then the method returns true
* for the array of ArrayLists being empty, otherwise it returns false.
*
* @return true, false
*/
public boolean isEmpty() {
return (amtOfValues == 0);
}
}
<file_sep>/README.md
# Data-Structures-ArrayList-like-Structures-Stacks-and-Queues
Project from CSS 143 UWB course
Summary
I built three classes that conform to the following interfaces. Used arrays in creating my classes (e.g., did not use the built-in ArrayList class when creating the ArrayList-like interface). Extended the sample driver below to completely test the FIFO nature of a Queue, the LIFO nature of a stack and the arbitrary insertsand removes in an ArrayList-like structure.
Sample Driver file posted named ArrayBasedDataStructuresDriver.java
ArrayList-like Interface:
void insert(Object, int index): Add the object at the specified index.
Object remove(int index): Remove and return the object at the specified index.
int size()
String toString()
boolean isEmpty()
int getIndexOf(Object): Returns -1 if not found
boolean equals(Object): Compare sizes and elements in the data structure.
Object get(int index): Returns the object at index specified.
Stack Interface (LIFO):
void push(Object)
Object pop()
int size()
String toString()
boolean isEmpty()
boolean equals(Object)
Queue Interface (FIFO):
void enqueue(Object)
Object dequeue()
int size()
String toString()
<file_sep>/Stack.java
/**
*
* @author <NAME>
* @class CSS 143 A
* @assignment Data Structures: ArrayList-like Structures, Stacks, and Queues;
* Stack class
* @date 10/25/20
*/
/**
*
* @version 1.0 This Stack class will use an ArrayList class object to make a
* stack interface and store stack objects to perform different
* functions with
*
*/
public class Stack {
// Object named val of class ArrayList is created to store the stack Objects
public ArrayList val = new ArrayList();
// Instance variable amtOfValues keeps track of the amount of stack Objects
// stored
int amtOfValues = 0;
/**
* Pushes an Object into the stack by inserting it into the Arraylist object at
* the end of the stack creating a stack interface and incrementing amtOfValues
* to keep track of a new Object added into the stack
*
* @param ob
*/
public void push(Object ob) {
this.val.insert(ob, amtOfValues);
amtOfValues++;
}
/**
* This method first saves the first Object in the stack stored in the ArrayList
* object in the local variable Object ob by using the get method in the
* ArrayList class . It then removes the first Object of the stack stored in the
* ArrayList object by using the ArrayList class method remove and returns the
* first Object value stored in the local variable Object ob. It also decrements
* the value of the instance variable amtOfValues keeping track of the amount of
* Stack objects as an object has been removed.
*
* @return ob
*/
public Object pop() {
Object ob = this.val.get(amtOfValues - 1);
this.val.remove(amtOfValues - 1);
amtOfValues--;
return ob;
}
/**
* This method returns the size of the stack by returning the amtOfValues
* instance variable that keeps track of the amount of objects in the stack
*
* @return amtOfValues
*/
public int size() {
return this.amtOfValues;
}
/**
* This toString method returns a String form of the stack from the beginning of
* the stack till the end of the stack stored in the ArrayList object using the
* ArrayList class toString method
*/
public String toString() {
return this.val.toString();
}
/**
* This method checks to see if the stack stored in the ArrayList object is
* empty by calling the ArrayList class method isEmpty. If it is empty, it
* returns true else it returns false
*
* @return true, false
*/
public boolean isEmpty() {
return this.val.isEmpty();
}
/**
* This method checks to see if the current Stack stored in the ArrayList object
* is equal to a given Object in the argument by casting and setting the Object
* equal to a Stack first. Then, it checks if the toString and size match for
* both of them. If they do, they are equal and the return value is true.
* Otherwise, they are not and the return value is false.
*
* @param obj
* @return true, false
*/
public boolean equals(Object obj) {
Stack ob = (Stack) obj;
if ((this.val.toString() == ob.toString()) && (this.val.size() == ob.amtOfValues)) {
return true;
} else {
return false;
}
}
}<file_sep>/ArrayBasedDataStructuresDriver.java
/**
*
* @author <NAME>
* @class CSS 143 A
* @assignment Data Structures: ArrayList-like Structures, Stacks, and Queues;
* ArrayBasedDataStructuresDriver class
* @date 10/25/20
*/
/**
*
* @version 1.0 The ArrayBasedDataStructuresDriver class test driver program
* below tests the ArrayList, Queue, and Stack classes and methods
*
*/
public class ArrayBasedDataStructuresDriver {
/**
* This main method tests each of the methods that correlate with each of the
* Stack, Queue, ArrayList classes by calling them in the main method and
* distinguishes between the testing of each class using the println statements
*
* @param args
*/
public static void main(String[] args) {
System.out.println("Stack Testing---------------->>>>>>");
stackTests();
System.out.println("Queue Testing---------------->>>>>>");
queueTests();
System.out.println("ArrayList Testing---------------->>>>>>");
arrayListTests();
}
/**
* A method is made to test the ArrayList methods and class by creating two
* ArrayList objects and calling the ArrayList methods on them.
*/
private static void arrayListTests() {
// creates two objects of ArrayList
ArrayList a = new ArrayList();
ArrayList b = new ArrayList();
// testing the insert method by inserting Objects into the first ArrayList
// object at certain indexes
a.insert('B', 0);
a.insert('A', 0);
a.insert('T', 1);
// testing the insert method by inserting Objects into the second ArrayList
// object at certain indexes
b.insert('B', 0);
b.insert('A', 0);
b.insert('T', 1);
// printing the toString method statement for both ArrayList objects
System.out.println(a.toString());
System.out.println(b.toString());
// checks if both ArrayList objects are equal by calling the equals method and
// printing the result, printing a statement that tests ArrayList a
// objects size by calling the size method, checking the index of an Object in
// ArrayList a object by calling the indexOf method of ArrayList,
// getting the Object at a specific element in ArrayList a and printing it by
// calling the ArrayList class get method
System.out.println(a.equals(b));
System.out.println("The Size of ArrayList a is: " + (a.size()));
System.out.println("The index of the character A is: " + a.indexOf('A'));
System.out.println("The Object at the Index 2 in ArrayList a is: " + a.get(2));
// removing the elements of Objects in the ArrayList a object by using the
// isEmpty, size, and remove method in the ArrayList class.
while (a.isEmpty() == false && a.size() > 0) {
System.out.println("Item removed from ArrayList a: " + a.remove(0));
}
// checks to see if ArrayList a is empty by using the isEmpty method in
// the ArrayList class
System.out.println("Is ArrayList a empty: " + a.isEmpty());
}
/**
* A method is made to test the Queue methods and class by creating two Queue
* objects and calling the Queue methods on them.
*/
private static void queueTests() {
// creates two objects of Queue
Queue a = new Queue();
Queue b = new Queue();
// testing the enqueue method by enqueueing Objects into the first Queue
// object
a.enqueue('B');
a.enqueue('a');
a.enqueue('t');
// testing the enqueue method by enqueueing Objects into the second Queue
// object
b.enqueue('C');
b.enqueue('a');
b.enqueue('t');
// printing the toString method statement for both Queue objects
System.out.println(a.toString());
System.out.println(b.toString());
// Checks to see if the two queue objects are equal by calling the queue equals
// method and checking the size of Queue a by calling the queue method size
System.out.println(a.equals(b));
System.out.println("The Size of the Queue a is: " + a.size());
// removing the elements of Objects in the Queue a object by using the
// isEmpty, size, and dequeue method in the Queue class.
while (a.isEmpty() == false && a.size() > 0) {
System.out.println("Dequeueing Queue a: " + a.dequeue());
}
// checks to see if Queue a is empty by using the isEmpty method in
// the Queue class
System.out.println("Is Queue a empty: " + a.isEmpty());
}
/**
* A method is made to test the Stack methods and class by creating two Stack
* objects and calling the Stack methods on them.
*/
private static void stackTests() {
// creates two objects of Stack
Stack a = new Stack();
Stack b = new Stack();
// testing the push method by pushing Objects into the first Stack
// object
a.push('B');
a.push('a');
a.push('t');
// testing the push method by pushing Objects into the first Stack
// object
b.push('C');
b.push('a');
b.push('t');
// printing the toString method statement for both Stack objects
System.out.println(a.toString());
System.out.println(b.toString());
// Checks to see if the two Stack objects are equal by calling the stack equals
// method and checking the size of the stack b by calling the stack size method
System.out.println(a.equals(b));
System.out.println("The Size of the Stack b is: " + b.size());
// removing the elements of Objects in Stack b by using the
// isEmpty and pop method in the Stack class.
while (b.isEmpty() == false) {
System.out.println("Popping Object out of Stack b: " + b.pop());
}
// checks to see if Stack a is empty by using the isEmpty method in
// the Stack class
System.out.println("Is Stack a empty: " + a.isEmpty());
}
}
| ccc216fb6ffeaf8b3287ffcaaaf905aef2755250 | [
"Markdown",
"Java"
] | 4 | Java | ishikagpta/Data-Structures-ArrayList-like-Structures-Stacks-and-Queues | c8fbb93afd0dbb5a98e4c1876a4de3e0cf31bb26 | c17de19187ba643d59500c4a224381c728586ed6 |
refs/heads/master | <repo_name>Dannyngs/yaosheng<file_sep>/app/product-post.php
<?php
require_once 'init.php';
$rs = $db->query("SELECT* FROM T_Product,T_Cat where T_Product.id =$_GET[id] and T_Product.cid=T_Cat.id");
$pro = $rs->fetch();
?>
<?php
require_once 'header.php';
?>
<div class="content">
<div class="allw"><img src="_/images/pro-ban.jpg"></div>
<div class="ptb20">
<div class="container">
<p class="tit2"><span style="padding-bottom:5px;color:#858585;"><a href="products.php?id=<?php echo $pro['cid'];?>" style="color:#858585;"><?php echo $pro['cat_name'];?></a> > <?php echo $pro['title'];?></span></p>
<div class="row mtb20">
<div class="col-md-12 mtb20">
<h4 class="text-center"><?php echo $pro['title'];?></h4>
<div class="allw mtb20">
<img src="<?php echo $imgurl.$pro['image'];?>">
</div>
<div class="allw neww">
<?php echo $pro['content']?>
</div>
</div>
</div>
</div>
</div>
</div><!--content end-->
<?php
require_once 'footer.php';
?>
<file_sep>/app/mail.php
<?php
require(dirname(__FILE__) . '/phpmailer/sendamail.php');
$msg="<p>Name:".$_POST['myname']."</p>";
$msg.="<p>Email:".$_POST['myemail']."</p>";
$msg.="<p>Message:".$_POST['mymsg']."</p>";
if(smtp_mail("<EMAIL>", "Application Form " ,$msg))
echo "ok";
else echo "not ok!";
<file_sep>/app/form.php
<?php
require_once 'init.php';
?>
<?php
require_once 'header.php';
?>
<div class="content">
<div class="allw"><img src="_/images/form-ban.jpg"></div>
<div class="ptb20 fch">
<div class="container">
<h3 class="tit2"><span>在线留言</span></h3>
<p>谢谢浏览本网站。若您有任何需要或意见,告诉我们您对本站的任何产品或其他事情的意见或需求,我们很欢迎您的留言!请留下资料,我们会尽快与您联络。</p>
<form class="mtb20" style="font-size:15px">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>姓名:<b class="fcr">*</b></label>
<input id="myname" type="text" class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>邮箱:<b class="fcr">*</b></label>
<input id="myemail" type="email" class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>公司名称:<b class="fcr">*</b></label>
<input id="mycop" type="text" class="form-control">
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<label>留言主题:<b class="fcr">*</b></label>
<input id="mytitle" type="text" class="form-control">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>留言内容:</label>
<textarea id="mymsg" class="form-control" rows="3"></textarea>
</div>
</div>
</div>
<p><button id="mysubmit" type="submit" class="btn btn-default blue">提 交</button></p>
</form>
</div>
</div>
</div><!--content end-->
<?php
require_once 'footer.php';
?><file_sep>/app/footer.php
<div class="footer">
<div class="container">
<div class="row">
<div class="col-md-4">
<h2 class="mb20">关于我们</h2>
<p><?php echo $system['description']?></p>
</div>
<div class="col-md-4">
<h2 class="mb20">联系我们</h2>
<dl class="dl-horizontal clearfix">
<dt><span class="glyphicon glyphicon-earphone pull-left" aria-hidden="true"></span>电话</dt>
<dd><?php echo $system['tel']?></dd>
</dl>
<dl class="dl-horizontal clearfix">
<dt><span class="glyphicon glyphicon-map-marker pull-left" aria-hidden="true"></span>地址</dt>
<dd><?php echo $system['address']?></dd>
</dl>
<dl class="dl-horizontal clearfix">
<dt><span class="glyphicon glyphicon-print pull-left" aria-hidden="true"></span>传真</dt>
<dd><?php echo $system['fax']?></dd>
</dl>
</div>
<div class="col-md-4">
<p><img style="max-width:100%" src="_/images/f-logo.jpg"></p>
<p>
<a class="mr10" target="_blank" href="<?php echo $system['weibo']?>"><img src="_/images/wb.jpg"></a>
<!--<a href="#"><img src="_/images/wx.jpg"></a>-->
</p>
</div>
<div class="col-md-12" style="font-size:13px;">
© 2016 Yaosheng adhesive products co.Ltd. All rights reserved.
</div>
</div>
</div>
</div><!--footer end-->
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="http://apps.bdimg.com/libs/jquery/1.8.3/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="_/js/lightbox.min.js"></script>
<script src="_/js/bootstrap.min.js"></script>
<script src="_/js/jquery.lazyload.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("img.lazy").lazyload();
$('#mysubmit').click(function(event){
event.preventDefault();
$('#mysubmit').attr("disabled",true);
var myname=$('#myname').val();
var myemail=$('#myemail').val();
var mycop=$('#mycop').val();
var mytitle=$('#mytitle').val();
var mymsg=$('#mymsg').val();
console.log(myname);
if( myname=="" || myemail==""|| mycop=="" || mytitle=="")
return alert("請完整填寫信息");
$.post("mail.php",
{
myname:myname,
myemail :myemail,
mycop:mycop,
mytitle:mytitle,
mymsg:mymsg
},
function(data,status){
if(data!="ok"){
alert("遞交失敗,請重試!");
$('#mysubmit').attr("disabled",false);
}else{
$('#myname').val("");$('#myemail').val("");$('#mycop').val("");$('#mytitle').val("");$('#mymsg').val("");
alert("遞交成功!");}
});
});
$("#myname,#myemail,#mycop,#mytitle").blur(function(){
var myname=$('#myname').val();
var myemail=$('#myemail').val();
var mycop=$('#mycop').val();
var mymsg=$('#mytitle').val();
if (myname!=="" && myemail!==""&& mycop!=="" && mytitle!=="")
$('#mysubmit').attr("disabled",false);
});
});
</script>
</body>
</html><file_sep>/app/about.php
<?php
require_once 'init.php';
$rs = $db->query("SELECT* FROM T_Cat order by sort");
$cats = $rs->fetchAll();
$rs = $db->query("SELECT* FROM T_Page where id=1");
$about = $rs->fetch();
?>
<?php
require_once 'header.php';
?>
<div class="content">
<div class="allw"><img src="_/images/ab-ban.jpg"></div>
<div class="ptb20 mt30">
<div class="container">
<div class="row">
<div class="col-md-4 allw">
<img src="_/images/ab1.jpg">
</div>
<div class="col-md-8">
<h3 class="tit2"><span><?php echo $about['title']?></span></h3>
<p><?php echo $about['content']?></p>
</div>
</div>
</div>
</div>
<div class="ptb20">
<div class="container">
<h3 class="tit2"><span>服务范围</span></h3>
<h4 class="ptb20">我司专业生产:特殊粘胶带、3M胶带、电子专用胶带等,欢迎来电咨询</h4>
<p>
<?php foreach($cats as $cat)
{?>
<a href="products.php?id=<?php echo $cat['id']?>" class="btn btn-outline btn-lg w1"><?php echo $cat['cat_name']?></a>
<?php
}
?>
</p>
</div>
</div>
</div><!--content end-->
<?php
require_once 'footer.php';
?>
<file_sep>/app/header.php
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,Chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="renderer" content="webkit">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title><?php echo $system['site_title']?></title>
<!-- Bootstrap -->
<link href="_/css/bootstrap.min.css" rel="stylesheet">
<link href="_/css/style.css" rel="stylesheet">
<link href="_/css/lightbox.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="//cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="//cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="header">
<div class="logo allw p10 mtb20"><img src="_/images/logo.jpg"/></div>
<nav class="navbar navbar-default">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav text-center">
<?php include_once "nav.php" ;?>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
</div><!--header end--><file_sep>/app/confidential.php
<?php
require_once 'init.php';
$rs = $db->query("SELECT* FROM T_Page where id=2");
$page = $rs->fetch();
?>
<?php
require_once 'header.php';
?>
<div class="content">
<div class="maxw">
<a href="cases.php"><img src="_/images/confidential.jpg"></a>
</div>
<div class="container ptb20">
<div class="row mb2">
<h3 class="title text-center"><span><?php echo $page[$current_lang.'_title']?></span></h3>
<div class="col-md-12 mt4 p1">
<p><?php echo $page[$current_lang.'_content']?></p>
</div>
</div>
<div class="row ptb20">
<div class="col-md-2 maxw">
<img src="_/images/icon1.png">
<p class="mt6"><?php echo $lang['step1']?></p>
</div>
<div class="col-md-1 rlicon text-center">
<span class="glyphicon glyphicon-menu-right hidden-xs hidden-sm" aria-hidden="true"></span>
<span class="glyphicon glyphicon-menu-down visible-xs visible-sm" aria-hidden="true"></span>
</div>
<div class="col-md-2 maxw">
<img src="_/images/icon2.png">
<p class="mt6"><?php echo $lang['step2']?></p>
</div>
<div class="col-md-1 rlicon text-center">
<span class="glyphicon glyphicon-menu-right hidden-xs hidden-sm" aria-hidden="true"></span>
<span class="glyphicon glyphicon-menu-down visible-xs visible-sm" aria-hidden="true"></span>
</div>
<div class="col-md-3 maxw">
<img src="_/images/icon3.png">
<p class="mt6"><?php echo $lang['step3']?></p>
</div>
<div class="col-md-1 rlicon text-center">
<span class="glyphicon glyphicon-menu-right hidden-xs hidden-sm" aria-hidden="true"></span>
<span class="glyphicon glyphicon-menu-down visible-xs visible-sm" aria-hidden="true"></span>
</div>
<div class="col-md-2 maxw">
<img src="_/images/icon4.png">
<p class="mt6"><?php echo $lang['step4']?></p>
</div>
</div>
</div>
</div><!--content end-->
<?php
require_once 'footer.php';
?>
<file_sep>/app/admin/application/logs/log-2015-12-04.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
ERROR - 2015-12-04 17:09:25 --> Severity: Notice --> Undefined index: sort /home/cm/newcmweb.hk/themes/npclimited/admin/application/third_party/scrud/libraries/crud.php 1228
<file_sep>/app/job.php
<?php
require_once 'init.php';
$rs = $db->query("SELECT* FROM T_Jobs order by sort");
$jobs = $rs->fetchAll();
?>
<?php
require_once 'header.php';
?>
<div class="content">
<div class="allw"><img src="_/images/ab-ban.jpg"></div>
<div class="ptb20">
<div class="container">
<h3 class="tit2"><span>人才招聘</span></h3>
<div class="row mtb20">
<?php foreach($jobs as $job)
{?>
<div class="col-md-4 text-center jdes">
<div>
<?php echo $job['title']?>
</div>
<p><?php echo $job['content']?></p>
</div>
<?php
}
?>
</div>
</div>
</div>
</div><!--content end-->
<?php
require_once 'footer.php';
?>
<file_sep>/app/new-post.php
<?php
require_once 'init.php';
$rs = $db->query("SELECT* FROM T_News where id = ".$_GET['id']);
$newp = $rs->fetch();
?>
<?php
require_once 'header.php';
?>
<div class="content">
<div class="allw"><img src="_/images/new-ban.jpg"></div>
<div class="ptb20">
<div class="container">
<h3 class="tit2"><span>新闻资讯</span></h3>
<div class="row mtb20">
<div class="col-md-12 mtb20">
<h4 class="text-center"><?php echo $newp['title'];?></h4>
<p class="text-center fch"><?php echo $newp['ymd'];?></p>
<hr class="nl" style="width:100%" />
<div class="allw mtb20 neww">
<?php echo $newp['content']?>
</div>
</div>
</div>
<p class="text-right"><a href="news.php" >返回</a></p>
</div>
</div>
</div><!--content end-->
<?php
require_once 'footer.php';
?>
<file_sep>/app/products.php
<?php
require_once 'init.php';
$rs = $db->query("SELECT* FROM T_Product where cid=$_GET[id] order by sort");
$pros = $rs->fetchAll();
?>
<?php
require_once 'header.php';
?>
<div class="content">
<div class="allw"><img src="_/images/pro-ban.jpg"></div>
<div class="ptb20">
<div class="container">
<h3 class="tit2"><span>产品展示</span></h3>
<div class="row">
<?php foreach($pros as $pro)
{?>
<div class="col-md-3 mtb20">
<a class="pro" href="product-post.php?id=<?php echo $pro['id'];?>">
<div class="allw">
<img class="lazy" data-original="<?php echo $imgurl.$pro['image'];?>">
</div>
<div class="move text-center">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
</div>
</a>
<h4 class="text-center"><?php echo $pro['title']?></h4>
</div>
<?php
}
?>
</div>
</div>
</div>
</div><!--content end-->
<?php
require_once 'footer.php';
?>
<file_sep>/app/news.php
<?php
require_once 'init.php';
$rs = $db->query("SELECT* FROM T_News order by ymd desc");
$news = $rs->fetchAll();
?>
<?php
require_once 'header.php';
?>
<div class="content">
<div class="allw"><img src="_/images/new-ban.jpg"></div>
<div class="ptb20">
<div class="container">
<h3 class="tit2"><span>新闻资讯</span></h3>
<div class="row mtb20">
<?php foreach($news as $new)
{?>
<div class="col-md-4 mtb20">
<a href="new-post.php?id=<?php echo $new['id']?>">
<h4 class="text-center"><?php echo $new['title'];?></h4>
<hr class="nl" />
<p class="text-center fch"><?php echo $new['ymd'];?></p>
<div class="allw mb20">
<img src="<?php echo $imgurl.$new['img_list'];?>">
</div>
<p class="neww"><?php echo $new['exp'];?></p>
</a>
</div>
<?php
}
?>
</div>
</div>
</div>
</div><!--content end-->
<?php
require_once 'footer.php';
?>
<file_sep>/app/init.php
<?php
//# Read from databases
try{
$dsn = "mysql:host=172.16.17.32;dbname=yaosheng";
$db = new PDO($dsn, 'cm', 'Leocheung21326468');
$db->query('set names utf8;');
}catch(Exception $e){
echo "Cannot connect to database,Please come back later!";
echo $e;
exit();
}
//# Global Iage
$imgurl ="/admin/media/images/";
//# Read System
$rs = $db->query("SELECT* FROM T_System");
$system = $rs->fetch();
//# Multi-Language
session_start();
if(isSet($_GET['lang']))
{
$current_lang = $_GET['lang'];
$_SESSION['lang'] = $current_lang;
}
else if(isSet($_SESSION['lang']))
{
$current_lang = $_SESSION['lang'];
}
else
{
//# set default lang
$current_lang = 'tra';
}
switch ($current_lang) {
case 'sim':
$lang_file = 'sim.php';
break;
case 'tra':
$lang_file = 'tra.php';
break;
default:
$lang_file = 'eng.php';
}
?>
<file_sep>/app/index.php
<?php
require_once 'init.php';
$rs = $db->query("SELECT* FROM T_Product where shown_homepage=1 limit 4");
$services = $rs->fetchAll();
$rs = $db->query("SELECT* FROM T_News order by ymd desc limit 4");
$newses = $rs->fetchAll();
$rs = $db->query("SELECT* FROM T_Banner order by sort");
$banners = $rs->fetchAll();
?>
<?php
require_once 'header.php';
?>
<div class="content">
<div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-generic" data-slide-to="1"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<?php foreach($banners as $key=>$ban)
{?>
<div class="item allw <?php if($key==0)echo 'active'; ?>">
<img src="<?php echo $imgurl.$ban['img'] ?>" alt="">
</div>
<?php } ?>
</div>
<!-- Controls -->
<a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
<div class="bgbf ptb20">
<div class="container">
<h3 class="tit text-center"><span>关于耀升</span></h3>
<h4 class="text-center mb30">我司专业生产:特殊粘胶带、3M胶带、电子专用胶带等,欢迎来电咨询</h4>
<p><?php echo $system['description']?></p>
<p class="text-center mb30">
<a href="about.php" class="btn btn-outline btn-lg">关于我们</a>
</p>
</div>
</div>
<div class="ptb20">
<div class="container">
<h3 class="tit text-center"><span>产品展示</span></h3>
<h4 class="text-center">以质量求生存,以诚信求发展</h4>
<div class="row mb30">
<?php foreach($services as $show)
{?>
<div class="col-md-3 allw mt30">
<a class="showa" href="product-post.php?id=<?php echo $show['id']?>">
<img class="showi" src="<?php echo $imgurl.$show['image'];?>">
<h4><?php echo $show['title']?></h4>
</a>
</div>
<?php
}
?>
</div>
<p class="text-center mb30">
<a href="products.php?id=<?php echo $system['more_pro_id']?>" class="btn btn-outline btn-lg">更多产品</a>
</p>
</div>
</div>
<div class="bgbf ptb20">
<div class="container mb30">
<h3 class="tit text-center"><span>新闻资讯</span></h3>
<h4 class="text-center mb30">耀升提供高品质的产品和完善的服务</h4>
<div class="row">
<div class="col-md-7">
<div class="row">
<a class="fcb" href="new-post.php?id=<?php echo $newses[0]['id']; ?>">
<div class="col-md-6 allw">
<img src="<?php echo $imgurl.$newses[0]['img_list']; ?>">
</div>
<div class="col-md-6 line20">
<h4><b><?php echo $newses[0]['title']; ?></b></h4>
<p><?php echo $newses[0]['content']; ?></p>
</div>
</a>
</div>
</div>
<div class="col-md-5">
<ul class="list-unstyled">
<li><a class="newsl clearfix" href="new-post.php?id=<?php echo $newses[1]['id']; ?>"><?php echo $newses[1]['title']; ?><span class="pull-right"><?php echo $newses[1]['ymd']; ?></span></a></li>
<li><a class="newsl clearfix" href="new-post.php?id=<?php echo $newses[2]['id']; ?>"><?php echo $newses[2]['title']; ?><span class="pull-right"><?php echo $newses[2]['ymd']; ?></span></a></li>
<li><a class="newsl clearfix" href="new-post.php?id=<?php echo $newses[3]['id']; ?>"><?php echo $newses[3]['title']; ?><span class="pull-right"><?php echo $newses[3]['ymd']; ?></span></a></li>
</ul>
<a href="news.php" style="text-decoration:underline;">more</a>
</div>
</div>
</div>
</div>
</div><!--content end-->
<?php
require_once 'footer.php';
?>
<file_sep>/app/admin/application/logs/log-2015-07-20.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?>
ERROR - 2015-07-20 15:37:36 --> Query error: Cannot delete or update a parent row: a foreign key constraint fails (`tipster/record`, CONSTRAINT `record_ibfk_1` FOREIGN KEY (`tipster_id`) REFERENCES `tipster` (`id`))
<file_sep>/README.md
# Yao Sheng Ltd 2016-3-22
| f89630718d740307ba9bbf8723b5608f508adf7a | [
"Markdown",
"PHP"
] | 16 | PHP | Dannyngs/yaosheng | 57315c0d82c4705ae70ef77195686e1751b86f7b | 221a709ddba70339da864df42002766e14ec25ff |
refs/heads/master | <repo_name>mwindower/fluent-bit-go<file_sep>/output/output.go
// Fluent Bit Go!
// ==============
// Copyright (C) 2015-2017 Treasure Data 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 output
/*
#include <stdlib.h>
#include "flb_plugin.h"
#include "flb_output.h"
*/
import "C"
import "fmt"
import "unsafe"
// Define constants matching Fluent Bit core
const FLB_ERROR = C.FLB_ERROR
const FLB_OK = C.FLB_OK
const FLB_RETRY = C.FLB_RETRY
const FLB_PROXY_OUTPUT_PLUGIN = C.FLB_PROXY_OUTPUT_PLUGIN
const FLB_PROXY_GOLANG = C.FLB_PROXY_GOLANG
// Local type to define a plugin definition
type FLBPlugin C.struct_flb_plugin_proxy
type FLBOutPlugin C.struct_flbgo_output_plugin
// When the FLBPluginInit is triggered by Fluent Bit, a plugin context
// is passed and the next step is to invoke this FLBPluginRegister() function
// to fill the required information: type, proxy type, flags name and
// description.
func FLBPluginRegister(ctx unsafe.Pointer, name string, desc string) int {
p := (*FLBPlugin)(unsafe.Pointer(ctx))
p._type = FLB_PROXY_OUTPUT_PLUGIN
p.proxy = FLB_PROXY_GOLANG
p.flags = 0
p.name = C.CString(name)
p.description = C.CString(desc)
return 0
}
// Release resources allocated by the plugin initialization
func FLBPluginUnregister(ctx unsafe.Pointer) {
p := (*FLBPlugin)(unsafe.Pointer(ctx))
fmt.Printf("[flbgo] unregistering %v\n", p)
C.free(unsafe.Pointer(p.name))
C.free(unsafe.Pointer(p.description))
}
func FLBPluginConfigKey(ctx unsafe.Pointer, key string) string {
_key := C.CString(key)
return C.GoString(C.output_get_property(_key, unsafe.Pointer(ctx)))
}
// Log with level error
func Error(ctx unsafe.Pointer, v ...interface{}) {
log(ctx, 1, v...)
}
// Log formatted with level error
func Errorf(ctx unsafe.Pointer, format string, v ...interface{}) {
logf(ctx, 1, format, v...)
}
// Log with level warn
func Warn(ctx unsafe.Pointer, v ...interface{}) {
log(ctx, 2, v...)
}
// Log formatted with level warn
func Warnf(ctx unsafe.Pointer, format string, v ...interface{}) {
logf(ctx, 2, format, v...)
}
// Log with level info
func Info(ctx unsafe.Pointer, v ...interface{}) {
log(ctx, 3, v...)
}
// Log formatted with level info
func Infof(ctx unsafe.Pointer, format string, v ...interface{}) {
logf(ctx, 3, format, v...)
}
// Log with level debug
func Debug(ctx unsafe.Pointer, v ...interface{}) {
log(ctx, 4, v...)
}
// Log formatted with level debug
func Debugf(ctx unsafe.Pointer, format string, v ...interface{}) {
logf(ctx, 4, format, v...)
}
// Log with level trace
func Trace(ctx unsafe.Pointer, v ...interface{}) {
log(ctx, 5, v...)
}
// Log formatted with level trace
func Tracef(ctx unsafe.Pointer, format string, v ...interface{}) {
logf(ctx, 5, format, v...)
}
func log(ctx unsafe.Pointer, t int, v ...interface{}) {
C.flbgo_log(C.int(t), C.CString(fmt.Sprint(v...)), unsafe.Pointer(ctx))
}
func logf(ctx unsafe.Pointer, t int, format string, v ...interface{}) {
C.flbgo_log(C.int(t), C.CString(fmt.Sprintf(format, v...)), unsafe.Pointer(ctx))
}
| f611faed28e2792d7868c427ae2adc372178447c | [
"Go"
] | 1 | Go | mwindower/fluent-bit-go | 77a3f9c852e4805f83fb0865cc2ef6e9f097e795 | 1b1519adde64d4a590ff14cc7e024c5b4cd9e278 |
refs/heads/master | <file_sep><?php
$messages = array();
$messages['en'] = array(
'replicatormaster' => 'Wiki Replicator - Master',
'replicatormaster-desc' => 'WikiReplicator replicates wiki to another server automatically',
);
?>
<file_sep><?php
$messages = array();
$messages['en'] = array(
'replicatorslave' => 'Wiki Replicator - slave',
'replicatorslave-desc' => 'WikiReplicator replicates wiki to another server automatically',
);
?>
<file_sep>; master configuration file
servers[] = "savana"
categories[] = "Export"
categories[] = "Replicate"
; string replace in texts and categories
; one word in what == word in with array
what[] = "Prvni"
with[] = "Uvodni"
[database]
server = "localhost"
user = "wiki1"
pass = "<PASSWORD>"
name = "wiki1"
[savana]
title = "Testovaci wiki na savane"
url = "http://url/"
ftpserver = "ftp.server"
ftpuser = "user"
ftppass = "<PASSWORD>"
wikidir = "/wiki"
<file_sep>; agent configuration file
; master replication server address
url = "http://c02-318a.kn.vutbr.cz/wiki1"<file_sep><?php
// I dont't want to copy that class here, because of new revisions,
// so i include it here and use some of its function
//if(!class_exists('WikiImporter'))
// require_once(dirname(__FILE__) . '/../includes/specials/StreamImport.php');
function pr($data) {
echo "<pre>";
print_r($data);
echo "</pre>";
}
class ReplicatorSlave extends SpecialPage {
var $dir; //actual directory
var $cfg; // master config
var $log; // log file
var $out; // output file
function __construct() {
parent::__construct( 'ReplicatorSlave' );
wfLoadExtensionMessages('ReplicatorSlave');
$this->dir = dirname(__FILE__) . '/';
$this->cfg = parse_ini_file($this->dir."slave.ini",true);
$this->log = fopen($this->dir."log/log.txt", "a+");
$this->out = fopen($this->dir."log/out.txt", "a+");
}
function __destruct() {
fclose($this->log);
fclose($this->out);
}
function logIt($str) {
fwrite($this->log,date("Y-m-d H:i:s | ",mktime()).$str."\n");
}
/* function from php.net comments */
function get_curl($url) {
$curl = curl_init();
// Setup headers - I used the same headers from Firefox version 2.0.0.6
// below was split up because php.net said the line was too long. :/
$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
$header[] = "Cache-Control: max-age=0";
$header[] = "Connection: keep-alive";
$header[] = "Keep-Alive: 300";
$header[] = "Accept-Charset: utf-8;q=0.7,*;q=0.7";
$header[] = "Accept-Language: en-us,en;q=0.5";
$header[] = "Pragma: "; // browsers keep this blank.
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($curl, CURLOPT_AUTOREFERER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
$html = curl_exec($curl); // execute the curl command
curl_close($curl); // close the connection
return $html; // and finally, return $html
}
function dtbConnect($host, $user, $pass, $name) {
$db = mysql_connect($host, $user, $pass);
if(!$db) {
$this->logIt("MySQL: Unable to connect to $host");
return false;
}
else {
$dbname = MySQL_Select_DB($name);
if(!$dbname) {
$this->logIt("MySQL: Unable to select database $name");
return false;
}
}
return $db;
}
function getDataXML($id) {
global $wgOut;
global $wgDBserver;
global $wgDBname;
global $wgDBuser;
global $wgDBpassword;
global $wgDBprefix;
$url = $this->cfg['url'].'/index.php/Speciální:ReplicatorMaster/'.$id;
$this->logIt("get_curl - $url");
$masterXML = $this->get_curl($url);
$xml = simplexml_load_string($masterXML, 'SimpleXMLElement');
if(!$this->dtbConnect($wgDBserver,
$wgDBuser,
$wgDBpassword,
$wgDBname)) {
$this->logIt("agent | unable to connect ".$this->cfg['database']['user']."@".$this->cfg['database']['server']);
return;
}
@mysql_query("SET CHARACTER SET utf8");
@mysql_query("SET NAMES UTF8");
@mysql_query("SET character_set_results=utf8");
@mysql_query("SET character_set_connection=utf8");
@mysql_query("SET character_set_client=utf8");
$insert = array();
foreach ($xml as $table=>$rows) {
$table = $wgDBprefix.$table;
$exists = "show tables like '$table'";
$query = mysql_query($exists);
if(mysql_num_rows($query) == 0) $this->logIt("agent | table $table doesn't exists");
$insert[] = "TRUNCATE TABLE `$table`;\n";
//logIt("agent | truncate $table");
//mysql_query($truncate);
foreach($rows as $row) {
$colsArr = array();
$valsArr = array();
foreach($row as $key=>$val) {
$colsArr[] = (string) $key;
$valsArr[] = (string) "'".mysql_real_escape_string(base64_decode($val))."'";
}
$colsStr = "";
$valsStr = "";
$colsStr = implode("," , $colsArr);
$valsStr = implode("," , $valsArr);
$insert[] = "REPLACE INTO $table ($colsStr) VALUES ($valsStr);";
}
}
foreach($insert as $query) {
fwrite($this->out,$query."\n");
$res = mysql_query($query);
if(!$res) {
$this->logIt("agent | cannot insert row");
$this->logIt(mysql_error());
$wgOut->addWikiText(mysql_error());
}
}
$wgOut->addWikiText("dataXML import complete");
}
function execute( $par ) {
global $wgOut,$wgRequest;
$wgOut->addHtml("Starting import<br />");
if(empty($par)) {
$this->logIt("Empty parameter");
$wgOut->addHtml("Empty parameter!!<br />");
return;
}
$wgOut->addHtml("Importing dataXML<br />");
$this->getDataXML($par);
}
}
<file_sep><?php
error_reporting(E_ERROR);
function pr($data){
echo "<pre>";
print_r($data);
echo "</pre>";
}
class ReplicatorMaster extends SpecialPage {
var $dir; //actual directory
var $cfg; // master config
var $log; // log file
var $xml;
function __construct() {
parent::__construct( 'ReplicatorMaster' );
wfLoadExtensionMessages('ReplicatorMaster');
$this->dir = dirname(__FILE__) . '/';
$this->cfg = parse_ini_file($this->dir."master.ini",true);
$this->log = fopen($this->dir."log/log.txt", "a+");
$this->xml = fopen($this->dir."log/xml.txt", "w+");
}
function __destruct() {
fclose($this->log);
fclose($this->xml);
}
function logIt($str) {
fwrite($this->log,date("Y-m-d H:i:s | ",mktime()).$str."\n");
}
/**
* Recursive upload of directories
* file - dir, where to chdir on ftp
* path - local path
*/
function recursiveUploadDir($ftp,$path,$file) {
// open local dir
$dir = opendir($path);
if($dir){
// if dir doesnt exists - create it
if(!@ftp_chdir ($ftp, $file)) {
ftp_mkdir ($ftp, $file);
if(!ftp_chdir ($ftp, $file)) {
$this->logIt("FTP: Unable to create directory $file");
return;
}
}
// Loop through each directory
while ($file = readdir($dir)) {
if($file == '.' || $file == '..')
continue;
elseif(is_dir("$path/$file")){
// Current file is a directory, so read content of the new directory
$this->recursiveUploadDir($ftp,"$path/$file",$file);
}
else {
$size = ftp_size($ftp, $file);
if($size != filesize("$path/$file")) { // file doesnt exists or has different size
if(!ftp_put($ftp, $file, "$path/$file" , FTP_BINARY))
$this->logIt(__FUNCTION__."FTP: Unable to upload $path/$file");
}
else {
$this->logIt("FTP: skip $file upload");
}
}
}
//echo "cd .. from ".ftp_pwd($ftp)."<br />";
ftp_chdir ($ftp, "..");
closedir($dir);
}
else {
$this->logIt("Unable to open dir: ".$path);
}
}
/**
* Connect to server and transfer data
*
* $server - server variable from $this->cfg
*/
function putFtpFiles($server) {
global $wgOut;
// connect
$ftp = ftp_connect($server["ftpserver"],21);
if($ftp == FALSE) {
$this->logIt("Unable to connect to ".$server["ftpserver"]);
$wgOut->addHtml("Unable to connect to ".$server["ftpserver"]);
return;
}
else
$wgOut->addHtml("Connected to ".$server["ftpserver"]."<br />");
// login
if(!ftp_login($ftp, $server["ftpuser"], $server["ftppass"])) {
$this->logIt("FTP login fail ".$server["ftpuser"]."@".$server["ftpserver"]);
$wgOut->addHtml("FTP login fail ".$server["ftpuser"]."@".$server["ftpserver"]);
return;
}
else
$wgOut->addHtml("Login successfull as ".$server["ftpuser"]."@".$server["ftpserver"]."<br />");
// enter wiki directory
$imgdir = $server["wikidir"]."/images";
if(!ftp_chdir($ftp, $imgdir)) {
$this->logIt("FTP: Can not change dir from ".ftp_pwd($ftp)." to ".$imgdir); return;
}
else
$wgOut->addHtml("Working dir ".ftp_pwd($ftp)."<br />");
// recursive upload
// first iteration must be here
$path = $this->dir."../../images";
$wgOut->addHtml("path: ".$path."<br>");
$dir = opendir($this->dir."../../images/");
if($dir) {
// Loop through each directory
while ($file = readdir($dir)) {
if($file == '.' || $file == '..')
continue;
elseif(is_dir("$path/$file")) {
// Current file is a directory, so read content of the new directory
$this->recursiveUploadDir($ftp,"$path/$file",$file);
}
else {
$size = ftp_size($ftp, $file);
if($size != filesize("$path/$file")) { // file doesnt exists or has different size
if(!ftp_put($ftp, $file, "$path/$file" , FTP_BINARY))
$this->logIt(__FUNCTION__."FTP: Unable to upload $path/$file");
}
else {
$this->logIt("FTP: skip $file upload");
}
}
}
closedir($dir);
}
else
$this->logIt("Unable to open dir: ".$path);
$wgOut->addHtml( "Upload done<br />");
ftp_close($ftp);
}
/* function from php.net comments */
function get_curl($url) {
$curl = curl_init();
// Setup headers - I used the same headers from Firefox version 2.0.0.6
// below was split up because php.net said the line was too long. :/
$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,";
$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
$header[] = "Cache-Control: max-age=0";
$header[] = "Connection: keep-alive";
$header[] = "Keep-Alive: 300";
$header[] = "Accept-Charset: utf-8;q=0.7,*;q=0.7";
$header[] = "Accept-Language: en-us,en;q=0.5";
$header[] = "Pragma: "; // browsers keep this blank.
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com');
curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($curl, CURLOPT_AUTOREFERER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
$html = curl_exec($curl); // execute the curl command
curl_close($curl); // close the connection
return $html; // and finally, return $html
}
function dtbConnect($host, $user, $pass, $name) {
$db = mysql_connect($host, $user, $pass);
if(!$db) {
$this->logIt("MySQL: Unable to connect to $host");
return false;
}
else {
$dbname = MySQL_Select_DB($name);
if(!$dbname) {
$this->logIt("MySQL: Unable to select database $name");
return false;
}
}
return $db;
}
/* from SpecialExport.php */
function wfExportGetPagesFromCategory( $title ) {
global $wgContLang;
$name = $title->getDBkey();
$dbr = wfGetDB( DB_SLAVE );
list( $page, $categorylinks ) = $dbr->tableNamesN( 'page', 'categorylinks' );
$sql = "SELECT page_namespace, page_title FROM $page " .
"JOIN $categorylinks ON cl_from = page_id " .
"WHERE cl_to = " . $dbr->addQuotes( $name );
$pages = array();
$res = $dbr->query( $sql, 'wfExportGetPagesFromCategory' );
while ( $row = $dbr->fetchObject( $res ) ) {
$n = $row->page_title;
if ($row->page_namespace) {
$ns = $wgContLang->getNsText( $row->page_namespace );
$n = $ns . ':' . $n;
}
$pages[] = $n;
}
$dbr->freeResult($res);
return $pages;
}
function agentCall() {
global $wgOut;
foreach($this->cfg["servers"] as $server) {
if(!empty($this->cfg[$server]["title"]))
$wgOut->addHtml("<h2>".$this->cfg[$server]["title"]."</h2>");
$url = $this->cfg[$server]['url'].'index.php/Special:ReplicatorSlave/'.$server;
//$url = $this->cfg[$server]["url"]."/repAgent.php?id=".$server;
$wgOut->addHtml($url."<br>");
// activate agent script
$agent = $this->get_curl($url);
if(empty($agent)) $this->logIt("NULL response from $server");
$this->putFtpFiles($this->cfg[$server]);
}
}
/**
* Gets XML format from array representing table
*/
function getTableXml($name,$table) {
$out = "<$name>\n";
$j=0;
foreach($table as $row) {
$out .= "\t<row id='$j'>\n";
foreach($row as $key=>$val) {
// replace strings from cfg
if($key == "old_text" || $key == "page_title" || $key == "pl_title" || $key == "el_to" || $key == "title" ||
$key == "cl_sortkey") {
$val = str_replace($this->cfg["what"],$this->cfg["with"], $val,$cnt);
}
$out .= "\t\t<$key>".base64_encode($val)."</$key>\n";
//$out .= "\t\t<$key>".$val."</$key>\n";
}
$out .= "\t</row>\n";
$j++;
}
$out .= "</$name>\n";
return $out;
}
/**
* Manual export of category, page, text and appropriate link tables
*
* table Revision - main table connecting page and texts - selected only last revisions
*
* TODO: export od pagelink table
*/
function generateXml() {
global $wgOut;
if(!$this->dtbConnect($this->cfg['database']['server'],
$this->cfg['database']['user'],
$this->cfg['database']['pass'],
$this->cfg['database']['name']))
return;
@mysql_query("SET CHARACTER SET utf8");
@mysql_query("SET NAMES UTF8");
@mysql_query("SET character_set_results=utf8");
@mysql_query("SET character_set_connection=utf8");
@mysql_query("SET character_set_client=utf8");
$wgOut->disable();
wfResetOutputBuffers();
header( "Content-type: application/xml; charset=utf-8" );
// arrays representing each table
$tableCategory = array();
$tableCategorylinks = array();
$tableRevision = array();
$tableImage = array();
$tableImagelinks = array();
$tableText = array();
$tablePage = array();
$pages = array();
// get page ids from exported categories
foreach($this->cfg['categories'] as $category) {
// select all desired categories
$sql = "SELECT * FROM `categorylinks` WHERE `cl_to` = '$category'";
// now we have IDs of all pages from demanding categories
$query = mysql_query($sql);
while($data = mysql_fetch_assoc($query)) {
$pageIDs[] = $data['cl_from'];
$tableCategorylinks[] = $data;
}
}
// get latest revisions, imagelinks and ...
$revisions = array();
$images = array();
foreach($pageIDs as $id) {
$sql = "SELECT * FROM `revision` WHERE `rev_page` = '$id'";
$query = mysql_query($sql);
while($data = mysql_fetch_assoc($query)) {
$revisions[$id] = $data['rev_id'];
}
$sql = "SELECT * FROM `imagelinks` WHERE `il_from` = '$id'";
$query = mysql_query($sql);
while($data = mysql_fetch_assoc($query)) {
$tableImagelinks[] = $data;
$images[] = $data['il_to'];
}
}
// put revisions into xml array and save appropriate pages and texts
foreach($revisions as $rev) {
$sql = "SELECT * FROM `revision` WHERE `rev_id` = '$rev'";
$query = mysql_query($sql);
while($data = mysql_fetch_assoc($query)) {
// save one row in revision table
$tableRevision[] = $data;
// saves exported texts and pages
$pages[] = $data['rev_page'];
$texts[] = $data['rev_text_id'];
}
}
// get `page` table
foreach($pages as $page) {
$sql = "SELECT * FROM `page` WHERE `page_id` = '$page'";
$query = mysql_query($sql);
while($data = mysql_fetch_assoc($query)) {
$tablePage[] = $data;
}
}
// get `text` table
foreach($texts as $text) {
$sql = "SELECT * FROM `text` WHERE `old_id` = '$text'";
$query = mysql_query($sql);
while($data = mysql_fetch_assoc($query)) {
$tableText[] = $data;
}
}
// get `image` table
foreach($images as $image) {
$sql = "SELECT * FROM `image` WHERE `img_name` = '$image'";
$query = mysql_query($sql);
while($data = mysql_fetch_assoc($query)) {
$tableImage[] = $data;
}
}
// get `category` table
foreach($this->cfg['categories'] as $category) {
$sql = "SELECT * FROM `category` WHERE `cat_title` = '$category'";
$query = mysql_query($sql);
while($data = mysql_fetch_assoc($query)) {
$tableCategory[] = $data;
}
}
$out = $this->getTableXml("page",$tablePage);
$out .= $this->getTableXml("revision",$tableRevision);
$out .= $this->getTableXml("text",$tableText);
$out .= $this->getTableXml("imagelinks",$tableImagelinks);
$out .= $this->getTableXml("image",$tableImage);
$out .= $this->getTableXml("category",$tableCategory);
$out .= $this->getTableXml("categorylinks",$tableCategorylinks);
$ret = "<WikiReplicator>\n$out\n</WikiReplicator>";
echo $ret;
fwrite($this->xml,$ret);
return;
}
function execute( $par ) {
global $wgOut,$wgRequest;
/**
* Replicator master can run in 3 modes
* 1] agents executing - empty $par
* 2] generating wikiXML file, called by agents
* 3] generating dataXML file, called by agents
*
* differs in $par
*/
// @ -> Notice: undefined offset if $par is empty
@list($id,$type) = split("/",$par);
// calling agents
if(empty($id)) {
$this->agentCall();
}
// XML generation mode
else {
$this->logIt("Generating XML for $id");
$this->generateXML($id);
}
}
}
?>
| 4a678973f7df8fdbfcf2fcd47f89f69ffac0228b | [
"PHP",
"INI"
] | 6 | PHP | michalsvec/wikiReplicator | 9214d1869b690565af31e36b4fc79a617563bdf9 | 3184e0b7503fccc55f83f384646f5639025b38c0 |
refs/heads/master | <repo_name>timeflask/timeflask-poker-tools<file_sep>/include/strutils.hpp
#ifndef INCLUDE_STRUTILS_H
#define INCLUDE_STRUTILS_H
#include <string>
#include <cassert>
#include "types.hpp"
#include <type_traits>
namespace a2a
{
namespace StrUtils
{
template <class> struct str_hasher;
namespace
{
constexpr std::size_t hash_start = 0x10F29CE4;
constexpr u64 hash_prime = 0x31;
}
template< std::size_t N >
constexpr std::size_t calen(char const (&)[N])
{
return N - 1;
}
template<> struct str_hasher<std::string>
{
std::size_t constexpr operator()(const char* input, std::size_t prev = hash_start) const
{
return *input ? static_cast<std::size_t> ((*this)(input + 1, (*input ^ prev) * hash_prime)) : prev;
}
std::size_t operator()(const std::string& s) const
{
return (*this)(s.c_str());
}
};
template<typename T> std::size_t constexpr str_hash(T&& t)
{
return str_hasher< typename std::decay<T>::type >()(std::forward<T>(t));
}
namespace literals
{
std::size_t constexpr operator "" _hash(const char* s, std::size_t)
{
return str_hasher<std::string>()(s);
}
std::size_t constexpr operator "" _len(const char* s, std::size_t len)
{
return len;
}
}
extern void to_lower_ansi(const std::string& input, std::string& out);
extern std::string to_lower_ansi(const std::string& input);
extern void to_upper_ansi(const std::string& input, std::string& out);
extern std::string to_upper_ansi(const std::string& input);
extern std::wstring utf8_to_wchar(const std::string& str);
extern std::string wchar_to_utf8(const std::wstring& wstr);
template<typename ReverseIter, typename R = int>
R parse_roman_reverse(ReverseIter first, ReverseIter last)
{
auto R2D = [&](char unit, char five, char ten) -> R {
R num = 0;
for (; first != last && *first == unit; ++first) ++num;
while (first != last && (*first == ten || *first == five)) {
num += *first == ten ? 10 : 5;
for (++first; first != last && *first == unit; ++first) --num;
}
return num;
};
R num = 0, pow = 1;
for (auto syms : { "IVX", "XLC", "CDM" }) {
num += R2D(syms[0], syms[1], syms[2]) * pow;
pow *= 10;
}
return num;
}
template<typename Iter, typename R = int>
R parse_roman_invert(Iter last, Iter first)
{
auto R2D = [&](char unit, char five, char ten) -> R {
R num = 0;
for (; first != last && *first == unit; --first) ++num;
while (first != last && (*first == ten || *first == five)) {
num += *first == ten ? 10 : 5;
for (--first; first != last && *first == unit; --first) --num;
}
return num;
};
R num = 0, pow = 1;
for (auto syms : { "IVX", "XLC", "CDM" }) {
num += R2D(syms[0], syms[1], syms[2]) * pow;
pow *= 10;
}
return num;
}
template<typename R = int>
R parse_roman(const std::string& s)
{
return parse_roman_reverse<std::string::const_reverse_iterator, R>(s.crbegin(), s.crend());
}
template<typename T = int>
std::string int_to_roman(T value)
{
std::string ret;
struct romandata_t { int value; char const* numeral; };
const struct romandata_t romandata[] =
{
{ 1000, "M" },{ 900, "CM" },
{ 500, "D" },{ 400, "CD" },
{ 100, "C" },{ 90, "XC" },
{ 50, "L" },{ 40, "XL" },
{ 10, "X" },{ 9, "IX" },
{ 5, "V" },{ 4, "IV" },
{ 1, "I" },
{ 0, NULL }
};
for (const romandata_t* current = romandata; current->value > 0; ++current)
{
while (value >= current->value)
{
ret+= current->numeral;
value -= current->value;
}
}
return ret;
}
template <typename R = int>
R parse_int(
const char* in,
int* digitsRead = nullptr,
int* totalRead = nullptr,
int* dots = nullptr,
bool space_div = false)
{
static_assert(std::is_integral<R>::value, "parse_int: Integer required.");
assert(in != nullptr && "parse_int: NULL input");
R out = 0; int j = 0; char ch = in[j];
bool nsign = false;
while (ch && (ch < '0' || ch > '9'))
{
nsign = ch == '-'; ch = in[++j];
}
int i = j; int ndivs = 0;
if (dots != nullptr) *dots = 0;
bool addDot = false;
int numsAfterDot = 0;
bool countNumsAfterDot = false;
while (ch && ch >= '0' && ch <= '9')
{
out = out * 10 + (ch - '0');
if (addDot)
{
*dots = *dots + 1;
addDot = false;
countNumsAfterDot = true;
}
if (countNumsAfterDot)
numsAfterDot++;
ch = in[++i];
if (!ch) break;
if (ch == ',' || ch == '.' || (space_div && (ch==(char)0xA0 || ch == ' ')))
{
if (dots != nullptr && (ch == ',' || ch == '.'))
addDot = true;
ndivs++;
ch = in[++i];
}
}
if (numsAfterDot>2 && dots != nullptr) *dots = 0;
if (digitsRead != nullptr)
*digitsRead = i - j - ndivs;
if (totalRead != nullptr)
*totalRead = i;
return out * (nsign && std::is_signed<R>::value ? -1 : 1);
}
template< std::size_t N >
bool starts_with(const std::string& str, char const (&cstr)[N], std::size_t _offset = 0)
{
return str.size()>N-2 && str.compare(_offset, N - 1, cstr) == 0;
}
template< std::size_t N >
bool ends_with(const std::string& str, char const (&cstr)[N], std::size_t _offset = 0)
{
return str.size()>N - 2 && str.compare(_offset + str.size() - N + 1, N - 1, cstr) == 0;
}
inline bool ends_with_str(const std::string& str, const std::string &ending)
{
if (str.size() >= ending.size())
return (0 == str.compare(str.size() - ending.size(), ending.size(), ending));
else
return false;
}
extern const char* ReadLine(const char* beg, const char* end, std::string& ln, std::size_t max_size = 1024);
}
}
#endif<file_sep>/src/currency.cxx
#include <cassert>
#include <string>
#include "currency.hpp"
#include "strutils.hpp"
namespace a2a
{
namespace CurrencyUtils
{
CurrencyType CurrencyTypeFromUTF8Symbol(const char* in)
{
assert(in != nullptr && "CurrencyTypeFromUTF8: NULL input");
u8 ch1 = in[0];
if (ch1 == '$')
return CurrencyType::USD;
if (!ch1)
return CurrencyType::Chips;
u8 ch2 = in[1];
if ( ch1 == 0xC2 && ch2 == 0xA3 )
return CurrencyType::GBP;
if (!ch2)
return CurrencyType::Chips;
u8 ch3 = in[2];
if (ch1 == 0xE2 && ch2 == 0x82 && ch3 == 0xAC)
return CurrencyType::EURO;
return CurrencyType::Chips;
}
static const char* CurrencyNames[] =
{
"CHIP",
"USD",
"GBP",
"EURO",
};
const char* CurrencyTypeToShortStr(CurrencyType currencyType)
{
return CurrencyNames[static_cast<std::underlying_type<CurrencyType>::type>(currencyType)];
}
CurrencyType CurrencyTypeFromShortStr(const char* s)
{
std::string cs(StrUtils::to_upper_ansi(s));
for (int i = 0; i < sizeof(CurrencyNames) / sizeof(const char*); ++i)
if (std::string(CurrencyNames[i]).compare(0, cs.size(), cs.c_str()) == 0)
return static_cast<CurrencyType>(i);
return CurrencyType::Chips;
}
void ChipsCurrencyToUTF8Stream(std::ostream& os, CurrencyType currencyType, int chips, bool empty_fraction)
{
switch (currencyType)
{
case CurrencyType::Chips:
os << chips;
return;
case CurrencyType::USD:
os << '$';
break;
case CurrencyType::GBP:
os << (u8)0xC2 << (u8)0xA3;
break;
case CurrencyType::EURO:
os << (u8)0xE2 << (u8)0x82 << (u8)0xAC;
break;
default:
os << chips;
return;
}
os << chips / 100;
int x_1 = (chips % 100) / 10; int x_01 = (chips % 100) % 10;
if (empty_fraction || x_1 || x_01)
os << '.' << x_1 << x_01;
}
}
}
<file_sep>/src/hhlineparser_impl.hpp
#ifndef INCLUDE_HHLINEPARSER_IMPL_HPP
#define INCLUDE_HHLINEPARSER_IMPL_HPP
#include "hhlineparser.hpp"
#include "handactiontype.hpp"
#include "cardseq.hpp"
#include "handaction.hpp"
namespace a2a
{
namespace detail
{
enum class ParseStage
{
None = 0,
Header = 1,
Seating = 2,
Blinds = 3,
Streets = 4,
Showdown = 5,
Summary = 6,
Done = 7,
};
struct LineParserImplBase : public ILineParserImpl
{
const char*& cursor;
HandHistory& hh;
const HandHistoryParserSettings& cfg;
ParseStage parseStage;
GameSite site;
int headerLineIdx;
LineParserImplBase(HandHistory& _hh, const HandHistoryParserSettings& _cfg, const char*& _cursor, GameSite _site)
: cursor(_cursor),
hh(_hh),
cfg(_cfg),
site(_site),
parseStage(ParseStage::Header)
{
hh.SetGameSite(site);
headerLineIdx = 0;
}
virtual void OnHandComplete() {}
virtual void ThrowFailRead(const std::string& what, const std::string& ln);
virtual int ParseCash(const char* s);
virtual bool IsCancelledLine(const std::string& ln);
virtual void AddAction(const HandAction::Ptr& action, GameStageType stageType = GameStageType::Current);
virtual bool ProcessLine(const std::string& ln);
virtual bool ProcessEmptyLine(int streak);
virtual ParseStage ProcessStreetChangeLine(const std::string& ln);
virtual ParseStage ProcessHeaderLine(const std::string& ln, int headerLineIndex);
virtual ParseStage ProcessSeatingLine(const std::string& ln);
virtual ParseStage ProcessBlindsLine(const std::string& ln);
virtual ParseStage ProcessStreetLine(const std::string& ln);
virtual ParseStage ProcessShowdownLine(const std::string& ln);
virtual ParseStage ProcessSummaryLine(const std::string& ln);
};
struct LineParserUtils
{
static bool TryParse_A_seat_colon_player_stack(
LineParserImplBase *_this,
const std::string &ln,
bool canSitOut = false,
bool readStackCurrency = false);
static bool TryParse__player_action(
LineParserImplBase *_this,
const std::string &ln,
const std::string &actionMark,
std::string &player);
static bool TryParse__player_action_amount(
LineParserImplBase *_this,
const std::string &ln,
const std::string &actionMark,
std::string &player,
int &value,
bool throwNoAmount = true);
static bool TryParse__player_action_amount_plus_amount(
LineParserImplBase *_this,
const std::string &ln,
const std::string &actionMark,
std::string &player,
int &value1,
int &value2);
static bool TryParse_A_dealtto_player_cards(
LineParserImplBase *_this,
const std::string &ln);
static bool TryParse__player_shows_cards_desc(
LineParserImplBase *_this,
const std::string &ln,
std::string &player,
CardSeq &cards);
};
}
}
#endif
<file_sep>/include/hhparser_ps.hpp
#ifndef INCLUDE_HHPOKERSTARSARSER_H
#define INCLUDE_HHPOKERSTARSARSER_H
#include <memory>
#include "hhlineparser.hpp"
namespace a2a
{
namespace PokerStars
{
class HHParser final : public HandHistoryLineParser
{
public:
HHParser();
protected:
virtual const std::string& HandStart() const;
virtual ILineParserImpl* GetImplementation(HandHistory& _hh,
const HandHistoryParserSettings& _cfg,
const char*& _cursor) const;
};
}
}
#endif<file_sep>/include/hhparser_base.hpp
#ifndef INCLUDE_HHPARSER_H
#define INCLUDE_HHPARSER_H
#include <iostream>
#include <memory>
#include "types.hpp"
#include "plugin.hpp"
#include "handhistory.hpp"
namespace a2a
{
class HandHistoryParserSettings : public Settings
{
public:
HandHistoryParserSettings() : Settings() {}
HandHistoryParserSettings(const JsonSettings& jsettings) : Settings(jsettings) {}
};
struct ParseError : std::runtime_error
{
ParseError(const std::string& what, const char* _cursor)
: std::runtime_error(what), cursor(_cursor)
{}
const char* cursor;
};
class HandHistoryParser : public Plugin
{
public:
using Ptr = std::shared_ptr<HandHistoryParser>;
HandHistoryParser(const std::string& name, const Version& ver, const std::string& descr = "") : Plugin(name, ver, descr) {}
inline void SetupParser(const HandHistoryParserSettings& parserSettings)
{
m_settings = parserSettings;
}
// [beg, end)
virtual const char* Next(const char* beg, const char* end) const = 0;
virtual const char* Last(const char* beg, const char* end) const = 0;
virtual const char* Parse(const char* beg, const char* end, HandHistory& handHistory) const = 0;
protected:
HandHistoryParserSettings m_settings;
};
}
#endif<file_sep>/include/fsysutils.hpp
#ifndef INCLUDE_FSYSUTILS_HPP
#define INCLUDE_FSYSUTILS_HPP
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <memory>
#include "collection.hpp"
#include "hhparser_base.hpp"
#include "types.hpp"
namespace a2a
{
enum class SysFolder
{
Home
};
extern std::string GetFullPath(const std::string&);
extern std::string GetSysPath(SysFolder);
extern std::string _searchPath(const std::string& rpath, int jumps);
class FilesCollection;
namespace detail
{
struct DirectoryImpl;
struct FileImpl;
}
class File final
{
public:
~File();
File(const std::string& path);
File(const detail::FileImpl& _impl);
const std::string& GetPath() const;
const std::string& GetExt() const;
std::string GetFullPath() const;
void GetStream(std::ifstream&);
std::size_t Read(std::string& out, std::size_t maxSize = 0);
const i64& FileSize() const;
void ReadCache(std::size_t blockSize);
void ClearCache();
bool IsCached(std::size_t blockSize) const;
std::string& GetCache();
private:
std::shared_ptr<detail::FileImpl> m_pimpl;
};
class Directory final
{
public:
using Ptr = std::unique_ptr<Directory>;
Directory(const Directory&) = delete;
Directory() = delete;
Directory& operator=(const Directory&) = delete;
~Directory();
Directory(const detail::DirectoryImpl& _impl);
static Directory::Ptr Open(const std::string& UTF8Path, bool ReadSubdirs = false);
const std::string& GetPath() const;
std::string GetFullPath() const;
bool HasFilesToProcess() const;
void Reopen();
FilesCollection GetFiles(std::size_t maxNum = 0);
void GetFiles(FilesCollection& out, std::size_t maxNum = 0);
void GetFilesMinTotalSize(FilesCollection& out, std::size_t minTotalSize);
FilesCollection GetFilesMinTotalSize(std::size_t minTotalSize);
private:
std::unique_ptr<detail::DirectoryImpl> m_pimpl;
};
}
#endif<file_sep>/src/handhistory.cxx
#include <stdexcept>
#include <iterator>
#include <algorithm>
#include "handhistory.hpp"
#include "stdutils.hpp"
#include "strutils.hpp"
namespace a2a
{
HandHistory::HandHistory() :
m_handId(0),
m_tournamentId(0),
m_gameType(CardGameType::Unknown),
m_gameModeFlags(CardGameMode::Unknown),
m_gameSite(GameSite::Unknown),
m_handDateTimeUTC(std::time(nullptr)),
m_timeZone(TimeZonesType::UTC),
m_tableCurrency(CurrencyType::Chips),
m_stacksCurrency(CurrencyType::Chips),
m_tournamentLevel(0),
m_maxPlayers(0),
m_buttonSeatIndex(0),
m_isCancelled(false),
m_wasRunTwice(false)
{
m_currentStage = std::make_shared<GameStage>(*this);
}
void HandHistory::SetHandId(u64 handId)
{
//assert(m_handId == 0 && "HandId alredy set");
m_handId = handId;
m_handIdStr = std::to_string(m_handId);
}
const std::string & HandHistory::GetHandIdStr() const
{
return m_handIdStr;
}
void HandHistory::SetHandId(const char* str)
{
m_handId = StrUtils::parse_int<u64>(str);
m_handIdStr = std::to_string(m_handId);
}
void HandHistory::SetTournamentId(u64 tournamentId)
{
m_tournamentId = tournamentId;
m_tournamentIdStr = std::to_string(m_tournamentId);
}
const std::string& HandHistory::GetTournamentIdStr() const
{
return m_tournamentIdStr;
}
void HandHistory::SetTournamentId(const char* str)
{
m_tournamentId = StrUtils::parse_int<u64>(str);
m_tournamentIdStr = std::to_string(m_tournamentId);
}
void HandHistory::SetGameSite(GameSite gameSite)
{
//assert(m_gameSite == GameSite::Unknown && "GameSite already set");
m_gameSite = gameSite;
m_gameSiteStr = GameSiteUtils::GameSiteToString(m_gameSite);
}
const std::string& HandHistory::GetGameSiteStr() const
{
return m_gameSiteStr;
}
void HandHistory::SetGameSite(const char* str)
{
m_gameSite = GameSiteUtils::GameSiteFromString(str);
m_gameSiteStr = GameSiteUtils::GameSiteToString(m_gameSite);
}
void HandHistory::SetTableMaxPlayers(int maxPlayers, bool adjustFromActive)
{
if (!adjustFromActive)
m_maxPlayers = maxPlayers;
else
{
if (maxPlayers == 2)
m_maxPlayers = 2;
else if (maxPlayers <= 6)
m_maxPlayers = 6;
else if (maxPlayers <= 9)
m_maxPlayers = 9;
else
m_maxPlayers = 10;
}
}
void HandHistory::SetButtonSeatIndex(int seatIdx)
{
// assert(m_buttonSeatIndex == 0 && "Button seat index already set");
if (seatIdx < 0 || seatIdx >10)
throw std::runtime_error("Button seat index is out of bounds.");
m_buttonSeatIndex = seatIdx;
if (m_currentStage->GetSeats().Size() > 1)
m_currentStage->SetupStartingPositions();
}
static const GameStage::Ptr NULLGameStage = nullptr;
void HandHistory::AddSeat(const Seat::Ptr& newSeat)
{
if (! m_stages.Has( GameStages::Type_(GameStageType::Seating) ) )
m_stages.Add( m_currentStage );
if (m_currentStage->GetType() != GameStageType::Seating)
throw std::logic_error("Failed to add seat into current game stage.");
if (m_currentStage->m_seats.Has([&newSeat](const Seat::Ptr& x)->bool {
return x->GetPlayerName() == newSeat->GetPlayerName() ||
x->GetIndex() == newSeat->GetIndex();
}))
throw std::logic_error(std::string("Seat [")+newSeat->GetPlayerName()+"] already exists." );
m_currentStage->m_seats.Add(newSeat);
if (m_currentStage->GetSeats().Size() > 1)
m_currentStage->SetupStartingPositions();
}
const Seats & HandHistory::GetSeats() const
{
return m_currentStage->GetSeats();
}
//std::size_t HandHistory::GetSeatsNum() const
//{
// return m_stages.Size() > 0 ? m_stages[0]->GetSeats().Size() : 0;
//}
void HandHistory::AddSeat(const std::string& playerName, int seatIndex, int stack)
{
AddSeat(std::make_shared<Seat>(
std::make_shared<Player>(playerName, GetGameSite()),
seatIndex,
stack));
}
void HandHistory::RemoveSeat(const std::string & playerName)
{
for (auto& s : m_stages)
s->m_seats.Clear([&playerName](const Seat::Ptr& seat)->bool {return playerName == seat->GetPlayerName(); });
}
const GameStage::Ptr& HandHistory::GetGameStage(GameStageType stageType) const
{
return (stageType == GameStageType::Current || stageType == GameStageType::Any) ?
m_currentStage :
m_stages.Get(GameStages::Type_(stageType));
}
const GameStages & HandHistory::GetGameStages() const
{
return m_stages;
}
void HandHistory::SwitchCurrentStage(GameStageType To)
{
if (m_stages.Has (GameStages::Type_(To)))
m_currentStage = m_stages.Get(GameStages::Type_(To));
else
{
bool wasSeating = m_currentStage && m_currentStage->GetType() == GameStageType::Seating;
bool wasBlinds = m_currentStage && m_currentStage->GetType() == GameStageType::Blinds;
if (!wasBlinds)
{
m_currentStage->CalculateSidePots();
}
if (To != GameStageType::Seating && wasSeating)
{
m_currentStage->SetupStartingPositions();
}
if (To == GameStageType::Showdown_2nd)
{
m_currentStage = std::make_shared<GameStage>(*GetGameStage(GameStageType::River_2nd));
m_wasRunTwice = true;
}
else if (To == GameStageType::Showdown)
{
auto _River = GetGameStage(GameStageType::River);
m_currentStage = _River != nullptr ?
std::make_shared<GameStage>(*_River) :
std::make_shared<GameStage>(*m_currentStage);
}
else if (To == GameStageType::River_2nd)
{
auto _2ndTurn = GetGameStage(GameStageType::Turn_2nd);
m_currentStage = _2ndTurn!=nullptr ?
std::make_shared<GameStage>(*_2ndTurn):
std::make_shared<GameStage>(*GetGameStage(GameStageType::Turn));
}
else if (To == GameStageType::Turn_2nd)
{
auto _2ndFlop = GetGameStage(GameStageType::Flop_2nd);
if (_2ndFlop)
m_currentStage = _2ndFlop != nullptr ?
std::make_shared<GameStage>(*_2ndFlop) :
std::make_shared<GameStage>(*GetGameStage(GameStageType::Flop));
}
else if (To == GameStageType::Flop_2nd)
{
m_currentStage = std::make_shared<GameStage>(*GetGameStage(GameStageType::Preflop));
}
else
m_currentStage = m_currentStage ? std::make_shared<GameStage>(*m_currentStage) : std::make_shared<GameStage>(*this);
m_currentStage->SetType(To);
if ( !wasBlinds )
{
m_currentStage->ResetGameStreet();
}
if (To != GameStageType::Seating && wasSeating)
{
m_currentStage->CopySeats();
}
if (GameStageUtils::IsAnyStreetStage(m_currentStage->GetType()))
{
m_currentStage->ResetActiveSeat();
}
m_stages.Add( m_currentStage );
}
}
void HandHistory::ProcessAction(const HandAction::Ptr& action, GameStageType stageType )
{
using namespace HandActionUtils;
bool isBlind = IsAnyBlindAction(action->GetActionTypeFlags());
if (m_currentStage->GetType() == GameStageType::Seating && isBlind)
{
SwitchCurrentStage(GameStageType::Blinds);
if (action->IsActionType(HandActionType::Ante) && !IsGameMode(CardGameMode::Ante))
SetAnte(action->GetChips());
}
bool isChangeStreet = action->IsActionType(HandActionType::Street);
//
if (m_currentStage->GetType() == GameStageType::Blinds && !isChangeStreet && !isBlind)
SwitchCurrentStage(GameStageType::Preflop);
if (isChangeStreet)
{
//if (m_currentStage->m_pot.m_uncalled > 0 && m_currentStage->m_pot.m_uncalledAction)
//{
// int r = m_currentStage->m_pot.GetUncalledReturn();
// if (r > 0)
// ProcessAction(std::make_shared<HandAction>(HandActionType::Return, m_currentStage->m_pot.m_uncalledAction->GetPlayerName(), -r));
// std::cout << "UNCALLED BET " << m_currentStage->m_pot.GetUncalledReturn() << std::endl;
//}
SwitchCurrentStage(action->m_stageType);
m_currentStage->m_board.Add(action->m_cards);
return;
}
if (m_heroName.empty() && action->IsActionType(HandActionType::CardsDealt) && action->GetCards().VisibleCards() >= 2)
m_heroName = action->GetPlayerName();
auto targetStage = GetGameStage(stageType);
if (targetStage == nullptr)
throw std::runtime_error(GameStageUtils::GameStageToString(stageType)+std::string(" not found."));
action->SetGameStage(targetStage);
targetStage->ProcessAction(action);
}
HandActions HandHistory::GetActions() const
{
return m_stages.GetActions();
}
HandActions HandHistory::GetActions(const HandActions::predicate_t& predicate) const
{
return m_stages.GetActions(predicate);
}
//HandActions HandHistory::GetPotActions() const
//{
// return m_stages.GetPotActions();
//}
}<file_sep>/include/hhconverters.hpp
#ifndef INCLUDE_HHEXPORTERFACTORY_H
#define INCLUDE_HHEXPORTERFACTORY_H
#include "pluginfactory.hpp"
#include "hhconverter_base.hpp"
#include "hhconverter_ps.hpp"
namespace a2a
{
class HandHistoryConvertersFactory final : public PluginFactory<HandHistoryConverter>
{
public:
HandHistoryConvertersFactory() noexcept;
const HandHistoryConverterSettings& GetDefaultSettings() const;
void SetDefaultSettings(const HandHistoryConverterSettings& defSettings);
HandHistoryConverter::Ptr GetConverter(const std::string& converterName);
HandHistoryConverter::Ptr GetConverter(GameSite gameSite);
HandHistoryConverter::Ptr GetConverterBySite(const std::string& siteName);
private:
using TBasePluginFactory = PluginFactory<HandHistoryConverter>;
using TBasePluginFactory::TBasePluginFactory;
HandHistoryConverterSettings m_defaultSettings;
};
}
//
// inlines
//
namespace a2a
{
inline const HandHistoryConverterSettings& HandHistoryConvertersFactory::GetDefaultSettings() const
{
return m_defaultSettings;
}
inline void HandHistoryConvertersFactory::SetDefaultSettings(const HandHistoryConverterSettings& defSettings)
{
m_defaultSettings = defSettings;
}
}
#endif<file_sep>/src/hhconverter_ps.cxx
#include <memory>
#include <iomanip>
#include <stdexcept>
#include <cstring>
#include "hhconverter_ps.hpp"
#include "strutils.hpp"
#include "streamutils.hpp"
#include "sitesdata.hpp"
#include "gamestage.hpp"
namespace a2a
{
// Converter impl decl
namespace PokerStars
{
namespace ConverterImplementation
{
struct Converter
{
const HandHistory& hh;
const HandHistoryConverterSettings& cfg;
bool m_hiHintFound;
bool m_lowHintFound;
CurrencyType m_tableCurr;
CurrencyType m_cashCurr;
const char _n = '\n';
Converter(const HandHistory& _hh, const HandHistoryConverterSettings& _cfg)
: hh(_hh), cfg(_cfg)
{
m_hiHintFound = false;
m_lowHintFound = false;
m_tableCurr = hh.GetTableCurrency();
m_cashCurr = hh.GetStacksCurrency();
}
void DoConvert(std::ostream& os);
void printHeader(std::ostream& os);
void printHeaderLine1(std::ostream& os);
void printHeaderLine2(std::ostream& os);
void printSeating(std::ostream& os, const GameStage::Ptr& gs);
void printBlinds(std::ostream& os, const GameStage::Ptr& gs);
void printSummary(std::ostream& os, const GameStage::Ptr& gs);
void printSummaryPot(std::ostream& os, const GameStage::Ptr& gs);
void printSummarySeats(std::ostream& os);
void printSummaryBoards(std::ostream& os);
void printBlindsAction(std::ostream& os, const HandAction::Ptr& p);
void printGameAction(std::ostream& os, const HandAction::Ptr& p);
void printShowdown(std::ostream& os, const GameStage::Ptr& gs);
void printShowdownAction(std::ostream& os, const HandAction::Ptr& p);
void printGameStreet(std::ostream& os, const GameStage::Ptr& gs);
void printGameStreetHeader(std::ostream& os, const GameStage::Ptr& gs);
std::string eval_hint_summary(const std::string& s);
void print_cash(std::ostream& os, int val, bool fraction = false);
void print_table_cash(std::ostream& os, int val, bool fraction = false);
};
}
}
// Converter Class methods
namespace PokerStars
{
HHConverter::HHConverter()
: HandHistoryConverter(GameSiteUtils::GameSiteToString(GameSite::PokerStars), Version(1, 0))
{}
void HHConverter::Convert(std::ostream& os, const HandHistory& hh) const
{
ConverterImplementation::Converter conv(hh, m_settings);
conv.DoConvert(os);
}
}
// Converter implementations decl
namespace PokerStars
{
// Entry
namespace ConverterImplementation
{
void Converter::DoConvert(std::ostream& os)
{
printHeader(os);
if (hh.IsCancelled())
{
os << "Hand cancelled" << _n
<< "*** SUMMARY ***" << _n;
return;
}
for (const auto& gs : hh.GetGameStages())
{
switch (gs->GetType())
{
case GameStageType::Seating:
printSeating(os, gs); break;
case GameStageType::Blinds:
printBlinds(os, gs); break;
case GameStageType::Summary:
printSummary(os, gs); break;
case GameStageType::Showdown:
printShowdown(os, gs); break;
default:
printGameStreet(os, gs);
}
}
}
}
// Header
namespace ConverterImplementation
{
void Converter::printHeader(std::ostream& os)
{
printHeaderLine1(os);
os << _n;
printHeaderLine2(os);
os << _n;
}
void Converter::printHeaderLine1(std::ostream& os)
{
os <<
(hh.IsGameMode(CardGameMode::FastFold) ?
"PokerStars Zoom Hand #" :
"PokerStars Hand #")
<<
hh.GetHandId() << ": ";
if (hh.IsGameMode(CardGameMode::Tournament))
{
os << "Tournament #" << hh.GetTournamentId() << ", ";
if (hh.IsGameMode(CardGameMode::Freeroll))
os << "Freeroll ";
else if (hh.IsGameMode(CardGameMode::BuyIn))
{
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetTableCurrency(), hh.GetBuyinPrizePool());
os << '+';
if (hh.IsGameMode(CardGameMode::BuyInKnockout))
{
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetTableCurrency(), hh.GetBuyinKnockout());
os << '+';
}
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetTableCurrency(), hh.GetBuyinRake());
os << ' ';
if (hh.GetTableCurrency() != CurrencyType::Chips)
{
os << CurrencyUtils::CurrencyTypeToShortStr(hh.GetTableCurrency()) << ' ';
}
}
if (hh.IsGameType(CardGameType::AnyMixGame))
{
os << MixGameToStr(GameTypeUtils::MixedGame(hh.GetGameType())) << " ("
<< GameToStr(GameTypeUtils::CardGame(hh.GetGameType())) << ' ' << BetTypeToStr(GameTypeUtils::BetType(hh.GetGameType())) << ')';
}
else
os << GameToStr(GameTypeUtils::CardGame(hh.GetGameType())) << ' ' << BetTypeToStr(GameTypeUtils::BetType(hh.GetGameType()));
}
else
{
if (hh.IsGameType(CardGameType::AnyMixGame))
os << MixGameToStr(GameTypeUtils::MixedGame(hh.GetGameType()));
else
os << GameToStr(GameTypeUtils::CardGame(hh.GetGameType())) << ' ' << BetTypeToStr(GameTypeUtils::BetType(hh.GetGameType()));
}
if (hh.IsGameMode(CardGameMode::Tournament))
{
os << " - Level "; StreamUtils::IntToRomanStream(os, hh.GetTournamentLevel());
os << " (" << hh.GetSmallBlindLevel() << '/' << hh.GetBigBlindLevel() << ")";
}
else
{
bool empty_fraction = hh.GetSmallBlind() < 100;
os << " (";
if (hh.IsGameType(CardGameType::AnyMixGame))
os << GameToStr(GameTypeUtils::CardGame(hh.GetGameType())) << ' ' << BetTypeToStr(GameTypeUtils::BetType(hh.GetGameType())) << ", ";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetTableCurrency(), hh.GetSmallBlind(), empty_fraction);
os << '/';
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetTableCurrency(), hh.GetBigBlind(), empty_fraction);
if (hh.IsGameMode(CardGameMode::Cap))
{
os << " - ";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetTableCurrency(), hh.GetCap(), false);
os << " Cap";
if (hh.GetTableCurrency()!=CurrencyType::Chips)
os << " -";
}
if (hh.GetTableCurrency() != CurrencyType::Chips)
{
os << ' ' << CurrencyUtils::CurrencyTypeToShortStr(hh.GetTableCurrency());
}
os << ')';
}
os << " - ";
if (hh.GetTimeZone() != TimeZonesType::UTC)
{
DateTimeUtils::TimeToStream(os, hh.GetDateTimeUTC() + DateTimeUtils::GetTimeZoneOffset(hh.GetTimeZone()), "%Y/%m/%d %T ");
os << DateTimeUtils::TimeZoneToAbbreviation(hh.GetTimeZone()) << " [";
}
DateTimeUtils::TimeToStream(os, hh.GetDateTimeUTC() + DateTimeUtils::GetTimeZoneOffset(TimeZonesType::ET), "%Y/%m/%d %T ET");
if (hh.GetTimeZone() != TimeZonesType::UTC)
{
os << "]";
}
}
void Converter::printHeaderLine2(std::ostream& os)
{
os << "Table '" << hh.GetTableName() << "' " << hh.GetTableMaxPlayers() << "-max ";
if (!hh.IsGameMode(CardGameMode::Freeroll) && hh.GetTableCurrency() == CurrencyType::Chips)
os << "(Play Money)";
if (hh.GetButtonSeatIndex()>0)
os << " Seat #" << hh.GetButtonSeatIndex() << " is the button";
}
}
// Seating
namespace ConverterImplementation
{
void Converter::printSeating(std::ostream& os, const GameStage::Ptr& gs)
{
for (auto const& i : gs->GetSeats())
{
os << "Seat " << i->GetIndex() << ": " << i->GetPlayer()->Name() << " (";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), i->GetStack(), true);
os << " in chips)" << _n;
}
}
}
// Blinds
namespace ConverterImplementation
{
void Converter::printBlinds(std::ostream& os, const GameStage::Ptr& gs)
{
for (auto const& i : gs->GetActions())
printBlindsAction(os, i);
}
}
// Action
namespace ConverterImplementation
{
void Converter::printBlindsAction(std::ostream& os, const HandAction::Ptr& p)
{
using PokerStars::BlindsActionsStrings;
os << p->GetPlayerName() << ": ";
HandActionType aType(HandActionUtils::GetBlindAction(p->GetActionTypeFlags()));
auto i = BlindsActionsStrings.find(aType);
if (i != BlindsActionsStrings.end())
{
os << i->second << ' ';
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), p->GetChips(), false);
if (p->IsActionType(HandActionType::AllIn))
os << " and is all-in";
}
os << _n;
}
void Converter::printGameAction(std::ostream& os, const HandAction::Ptr& p)
{
using namespace HandActionUtils;
if (IsAnyBlindAction(p->GetActionTypeFlags()))
return;
if (IsAnyInfoAction(p->GetActionTypeFlags()))
{
auto i = InfoActionStrings.find(GetInfoAction(p->GetActionTypeFlags()));
if (i != InfoActionStrings.end())
os << i->second << _n;
return;
}
if (IsAnySummaryAction(p->GetActionTypeFlags()))
{
printShowdownAction(os, p);
return;
}
if (p->IsActionType(HandActionType::CardsDealt))
{
os << "Dealt to " << p->GetPlayerName();
CardSeq seatCards ( p->GetSeat()->GetCards() );
if (seatCards.VisibleCards() > 0)
seatCards.ToStream(os, " [%S]");
p->GetCards().ToStream(os, " [%S]");
os << _n;
return;
}
if (p->IsActionType(HandActionType::CardsDiscard))
{
os << p->GetPlayerName() << ": ";
auto cards = p->GetCards();
auto cardsNum = cards.Size();
if (cardsNum == 0)
os << "stands pat" << _n;
else
{
os << "discards " << cardsNum << " cards";
if (cards.VisibleCards() > 0)
cards.ToStream(os, " [%S]");
os << _n;
}
return;
}
HandActionType aType( HandActionUtils::GetGameAction( p->GetActionTypeFlags()));
if (aType == HandActionType::Return)
{
os << "Uncalled bet (";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), -p->GetChips());
os << ") returned to " << p->GetPlayerName() << _n;
return;
}
os << p->GetPlayerName() << ": ";
switch (aType)
{
case HandActionType::Fold:
{
os << "folds";
auto cs = p->GetCards();
if (cs.Size() > 0)
cs.ToStream(os, " [%S]");
break;
}
case HandActionType::Check:
os << "checks"; break;
case HandActionType::Call:
os << "calls ";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), p->GetChips(), false);
break;
case HandActionType::Bet:
os << "bets ";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), p->GetChips(), false);
break;
case HandActionType::BringIn:
os << "brings in for ";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), p->GetChips(), false);
break;
case HandActionType::Raise:
os << "raises ";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), p->GetRaiseUp(), false);
os << " to ";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), p->GetRaiseTo(), false);
break;
default:
break;
}
if (p->IsActionType(HandActionType::Cap))
{
os << " and has reached the ";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), hh.GetCap(), false);
os << " cap";
}
if (p->IsActionType(HandActionType::AllIn))
{
os << " and is all-in";
}
os << _n;
}
}
// Game Street
namespace ConverterImplementation
{
void Converter::printGameStreetHeader(std::ostream& os, const GameStage::Ptr& gs)
{
auto cs = gs->GetBoard();
switch (gs->GetType())
{
case GameStageType::Summary:
os << "*** SUMMARY ***" << _n;
break;
case GameStageType::Showdown:
if (hh.GetGameStage(GameStageType::Showdown_2nd) != nullptr)
os << "*** FIRST SHOW DOWN ***";
else
os << "*** SHOW DOWN ***";
os << _n;
break;
case GameStageType::Showdown_2nd:
os << ("*** SECOND SHOW DOWN ***") << _n;
break;
case GameStageType::River:
if (hh.GetGameStage(GameStageType::River_2nd) != nullptr)
os << "*** FIRST RIVER ***";
else
os << "*** RIVER ***";
if (!cs.Empty())
cs.ToStream(os, " [%x %x %x %x] [%x]");
os << _n;
break;
case GameStageType::River_2nd:
os << ("*** SECOND RIVER ***");
if (!cs.Empty())
cs.ToStream(os, " [%x %x %x %x] [%x]");
os << _n;
break;
case GameStageType::Turn:
if (hh.GetGameStage(GameStageType::Turn_2nd) != nullptr)
os << "*** FIRST TURN ***";
else
os << "*** TURN ***";
if (!cs.Empty())
cs.ToStream(os, " [%x %x %x] [%x]");
os << _n;
break;
case GameStageType::Turn_2nd:
os << ("*** SECOND TURN ***");
if (!cs.Empty())
cs.ToStream(os, " [%x %x %x] [%x]");
os << _n;
break;
case GameStageType::Flop:
if (hh.GetGameStage(GameStageType::Turn_2nd) != nullptr)
os << "*** FIRST FLOP ***";
else
os << "*** FLOP ***";
if (!cs.Empty())
{
if (hh.IsGameType(CardGameType::Courchevel | CardGameType::CourchevelHiLo))
{
cs.ToStream(os, " [%x]"); cs.ToStream(os, " [%x%x %x]");
}
else
cs.ToStream(os, " [%x %x %x]");
}
os << _n;
break;
case GameStageType::Flop_2nd:
os << ("*** SECOND FLOP ***");
if (!cs.Empty())
cs.ToStream(os, " [%x %x %x]");
os << _n;
break;
case GameStageType::Preflop:
os << ("*** HOLE CARDS ***");
if (hh.IsGameType(CardGameType::Courchevel | CardGameType::CourchevelHiLo) && !cs.Empty())
{
os << _n;
cs.ToStream(os, "*** HOLE CARDS *** [%x]");
cs.ToStream(os, "*** HOLE CARDSPRE-FLOP *** [%x]");
}
os << _n;
break;
case GameStageType::_DrawHands:
os << ("*** DEALING HANDS ***") << _n; break;
case GameStageType::_1stDraw:
os << ("*** FIRST DRAW ***") << _n; break;
case GameStageType::_2ndDraw:
os << ("*** SECOND DRAW ***") << _n; break;
case GameStageType::_3rdDraw:
os << ("*** THIRD DRAW ***") << _n; break;
case GameStageType::_3rdStreet:
os << ("*** 3rd STREET ***") << _n; break;
case GameStageType::_4thStreet:
os << ("*** 4th STREET ***") << _n; break;
case GameStageType::_5thStreet:
os << ("*** 5th STREET ***") << _n; break;
case GameStageType::_6thStreet:
os << ("*** 6th STREET ***") << _n; break;
default:
break;
}
}
std::string Converter::eval_hint_summary(const std::string & s)
{
std::size_t dIdx = s.find(" -");
return dIdx == std::string::npos ? s : s.substr(0,dIdx);
}
void Converter::print_cash(std::ostream& os, int val, bool fraction)
{
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, m_cashCurr, fraction);
}
void Converter::print_table_cash(std::ostream& os, int val, bool fraction)
{
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, m_tableCurr, fraction);
}
void Converter::printGameStreet(std::ostream& os, const GameStage::Ptr& gs)
{
printGameStreetHeader(os, gs);
for (auto const& i : gs->GetActions())
printGameAction(os, i);
}
}
// showdown actions
namespace ConverterImplementation
{
void Converter::printShowdown(std::ostream & os, const GameStage::Ptr & gs)
{
printGameStreetHeader(os, gs);
for (auto const& i : gs->GetActions())
printShowdownAction(os, i);
if (m_hiHintFound && !m_lowHintFound)
os << "No low hand qualified" << _n;
}
void Converter::printShowdownAction(std::ostream & os, const HandAction::Ptr & p)
{
switch (HandActionUtils::GetSummaryAction(p->GetActionTypeFlags()))
{
case HandActionType::Collected:
{
//Giovanni1983 collected $1 from pot
os << p->GetPlayerName() << " collected ";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), p->GetChips(), false);
if (p->HasProperty("from"))
os << " from " << p->GetProperty("from");
else
os << " from pot";
os << _n;
break;
}
case HandActionType::MuckHand:
{
//SteN 4: doesn't show hand
if (p->GetStageType() == GameStageType::Showdown || p->GetStageType() == GameStageType::Showdown_2nd)
os << p->GetPlayerName() << ": mucks hand" << _n;
else
os << p->GetPlayerName() << ": doesn't show hand" << _n;
break;
}
case HandActionType::ShowHand:
{
//SteN 4: shows [Qc Qd] (three of a kind, Queens)
os << p->GetPlayerName() << ": shows ";
p->GetCards().ToStream(os, "[%S]");
const std::string& evalHint = p->GetCards().GetEvalHint();
if (!evalHint.empty())
{
os << " (" << evalHint << ')';
m_hiHintFound = m_hiHintFound || evalHint.find("HI:") != std::string::npos;
m_lowHintFound = m_lowHintFound || evalHint.find("LO:") != std::string::npos;
}
os << _n;
break;
}
default:
break;
};
}
}
// Summary
namespace ConverterImplementation
{
// pot, side pots
void Converter::printSummaryPot(std::ostream& os, const GameStage::Ptr& gs)
{
os << "Total pot ";
auto potObj = gs->GetPot();
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), potObj.GetChips(), false);
auto sidePots = potObj.GetSidePots();
if (sidePots.size() > 1)
{
os << " Main pot ";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), sidePots[0], false);
os << '.';
if (sidePots.size() == 2)
{
os << " Side pot ";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), sidePots[1], false);
os << ". ";
}
else
{
for (std::size_t i = 1; i < sidePots.size(); ++i)
{
os << " Side pot-" << i << ' ';
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), sidePots[i], false);
os << '.';
}
os << ' ';
}
}
else
os << ' ';
os << "| Rake ";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), potObj.GetRake(), false);
os << _n;
}
static GameStage::Ptr Find1stBoard(const HandHistory& hh)
{
auto s = hh.GetGameStage(GameStageType::Showdown);
if (s != nullptr && s->GetBoard().Size() >= 1)
return s;
s = hh.GetGameStage(GameStageType::River);
if (s != nullptr && s->GetBoard().Size() >= 1)
return s;
s = hh.GetGameStage(GameStageType::Turn);
if (s != nullptr && s->GetBoard().Size() >= 1)
return s;
s = hh.GetGameStage(GameStageType::Flop);
//if (s != nullptr && s->GetBoard().Size() >= 1)
return s;
// courchavel ?
//s = hh.GetGameStage(GameStageType::Preflop);
//return s;
}
static GameStage::Ptr Find2ndBoard(const HandHistory& hh)
{
auto s = hh.GetGameStage(GameStageType::Showdown_2nd);
if (s != nullptr && s->GetBoard().Size() >= 1)
return s;
s = hh.GetGameStage(GameStageType::River_2nd);
if (s != nullptr && s->GetBoard().Size() >= 1)
return s;
s = hh.GetGameStage(GameStageType::Turn_2nd);
if (s != nullptr && s->GetBoard().Size() >= 1)
return s;
s = hh.GetGameStage(GameStageType::Flop_2nd);
return s;
}
// boards
void Converter::printSummaryBoards(std::ostream& os)
{
if (hh.WasRunTwice())
os << "Hand was run twice" << _n;
auto sd1 = Find1stBoard(hh);
if (sd1 == nullptr)
return;
auto sd2 = Find2ndBoard(hh);
if (sd2 != nullptr)
{
sd1->GetBoard().ToStream(os, "FIRST Board [%S]") << _n;
sd2->GetBoard().ToStream(os, "SECOND Board [%S]") << _n;
}
else
sd1->GetBoard().ToStream(os, "Board [%S]") << _n;
}
// summary seats
void Converter::printSummarySeats(std::ostream& os)
{
auto gs = hh.GetGameStage(GameStageType::Seating);
if (gs == nullptr)
return;
HandActions potActions(hh.GetActions(HandActions::PotActions_()));
HandActions allActions(hh.GetActions());
for (auto const& s : gs->GetSeats())
{
os << "Seat " << s->GetIndex() << ": "
<< s->GetPlayerName();
if (s->GetPosition() == PokerPosition::BTN || (gs->GetSeats().Size()==2 && s->GetPosition() == PokerPosition::SB))
os << " (button)";
if (s->GetPosition() == PokerPosition::SB)
os << " (small blind)";
else if (s->GetPosition() == PokerPosition::BB)
os << " (big blind)";
auto playerActions(allActions.Select(HandActions::Player_(s->GetPlayerName())));
auto foldAction (playerActions.Select(HandActions::Flags_(HandActionType::Fold)).Last());
if (foldAction) {
switch (foldAction->GetStageType())
{
case GameStageType::Preflop:
os << " folded before Flop"; break;
case GameStageType::Flop:
os << " folded on the Flop"; break;
case GameStageType::Turn:
os << " folded on the Turn"; break;
case GameStageType::River:
os << " folded on the River"; break;
case GameStageType::_3rdStreet:
os << " folded on the 3rd Street"; break;
case GameStageType::_4thStreet:
os << " folded on 4th Street"; break;
case GameStageType::_5thStreet:
os << " folded on 5th Street"; break;
case GameStageType::_6thStreet:
os << " folded on 6th Street"; break;
case GameStageType::_DrawHands:
os << " folded before the Draw"; break;
case GameStageType::_1stDraw:
os << " folded after the 1st Draw"; break;
case GameStageType::_2ndDraw:
os << " folded after the 2nd Draw"; break;
case GameStageType::_3rdDraw:
os << " folded after the 3rd Draw"; break;
default:
os << " folded before Flop";
break;
}
if (potActions.Count(HandActions::Player_(s->GetPlayerName(), HandActionUtils::NotAnte())) == 0)
os << " (didn't bet)";
os << _n;
continue;
}
auto collectedActions(playerActions.Select(HandActions::Flags_(HandActionType::Collected)));
auto nsdColActions = collectedActions.Select([](const HandActions::value_type& a) -> bool {
return a->GetStageType() != GameStageType::Showdown && a->GetStageType() != GameStageType::Showdown_2nd;
});
if (!nsdColActions.Empty())
{
os << " collected (";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), nsdColActions.ChipsSumm(), false);
os << ')' << _n;
continue;
}
auto muckAction(playerActions.Select(HandActions::Flags_(HandActionType::MuckHand)).Last());
if (muckAction)
{
os << " mucked";
if (!muckAction->GetCards().Empty())
muckAction->GetCards().ToStream(os, " [%S]");
os << _n;
continue;
}
auto sd1ColActions(collectedActions.Select( HandActions::Stage_(GameStageType::Showdown) ));
auto sd1ShowAction(playerActions.Select(HandActions::Flags_(HandActionType::ShowHand, GameStageType::Showdown)).Last());
if (sd1ShowAction)
{
os << " showed ";
sd1ShowAction->GetCards().ToStream(os, "[%S]");
}
if (sd1ShowAction && !sd1ColActions.Empty())
{
os << " and won (";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), sd1ColActions.ChipsSumm(), false);
os << ')';
}
else if (sd1ShowAction && sd1ColActions.Empty())
{
os << " and lost";
}
if (sd1ShowAction && !sd1ShowAction->GetCards().GetEvalHint().empty())
{
os << " with " << eval_hint_summary( sd1ShowAction->GetCards().GetEvalHint() );
}
//
auto sd2ColActions(collectedActions.Select(HandActions::Stage_(GameStageType::Showdown_2nd)));
auto sd2ShowAction(playerActions.Select(HandActions::Flags_(HandActionType::ShowHand, GameStageType::Showdown_2nd)).Last());
if (sd2ShowAction)
{
os << ',';
}
if (sd2ShowAction && !sd2ColActions.Empty())
{
os << " and won (";
CurrencyUtils::ChipsCurrencyToUTF8Stream(os, hh.GetStacksCurrency(), sd2ColActions.ChipsSumm(), false);
os << ')';
}
else if (sd2ShowAction && sd2ColActions.Empty())
{
os << " and lost";
}
if (sd2ShowAction && !sd2ShowAction->GetCards().GetEvalHint().empty())
{
os << " with " << eval_hint_summary (sd2ShowAction->GetCards().GetEvalHint() );
}
os << _n;
}
}
void Converter::printSummary(std::ostream& os, const GameStage::Ptr& gs)
{
if (hh.IsCancelled())
os << "Hand cancelled" << _n;
printGameStreetHeader(os, gs);
if (hh.IsCancelled() && gs->GetPot().GetChips() == 0)
return;
printSummaryPot(os, gs);
printSummaryBoards(os);
if (hh.IsCancelled())
return;
printSummarySeats(os);
}
}
}
}
<file_sep>/include/gamestage.hpp
#ifndef INCLUDE_GAMESTAGE_HPP
#define INCLUDE_GAMESTAGE_HPP
#include <map>
#include <vector>
#include <memory>
#include <functional>
#include "types.hpp"
#include "enumflags.hpp"
#include "seat.hpp"
#include "seatscol.hpp"
#include "pot.hpp"
#include "gamestagetype.hpp"
#include "handactioncol.hpp"
#include "cardseq.hpp"
namespace a2a
{
class HandHistory;
class GameStage final
{
public:
using Ptr = std::shared_ptr<GameStage>;
GameStage(HandHistory& parent);
GameStageType GetType() const;
const Seats& GetSeats() const;
const HandActions& GetActions() const;
HandActions GetActions(const HandActions::predicate_t& predicate) const;
Pot& GetPot();
const CardSeq& GetBoard() const;
int GetUncalledBet(const std::string& playerName) const;
private:
HandHistory& m_parent;
GameStageType m_type;
Pot m_pot;
Seats m_seats;
HandActions m_actions;
CardSeq m_board;
int m_actionSeat;
friend class HandHistory;
void SetType(GameStageType stage);
void SetupStartingPositions();
void CopySeats();
void ResetGameStreet();
void ResetActiveSeat();
void ProcessAction(const HandAction::Ptr& action);
int CalculateUncalled(const std::string& player = "") const;
void CalculateSidePots();
};
}
//
// inlines
//
namespace a2a
{
inline void GameStage::SetType(GameStageType stage)
{
m_type = stage;
}
inline GameStageType GameStage::GetType() const
{
return m_type;
}
inline Pot& GameStage::GetPot()
{
return m_pot;
}
inline const CardSeq & GameStage::GetBoard() const
{
return m_board;
}
inline const Seats & GameStage::GetSeats() const
{
return m_seats;
}
}
#endif<file_sep>/include/datetimeutils.hpp
#ifndef INCLUDE_DATETIMEUTILS_H
#define INCLUDE_DATETIMEUTILS_H
#include <ctime>
#include <string>
#include <iostream>
#include "types.hpp"
namespace a2a
{
enum class TimeZonesType : u8
{
UTC = 0,
A = 1,
ACDT = 2,
ACST = 3,
ACT = 4,
ACWST = 5,
ADT = 6,
AEDT = 7,
AEST = 8,
AET = 9,
AFT = 10,
AKDT = 11,
AKST = 12,
ALMT = 13,
AMST = 14,
AMT = 15,
ANAST = 16,
ANAT = 17,
AoE = 18,
AQTT = 19,
ART = 20,
AST = 21,
AT = 22,
AWDT = 23,
AWST = 24,
AZOST = 25,
AZOT = 26,
AZST = 27,
AZT = 28,
B = 29,
BNT = 30,
BOT = 31,
BRST = 32,
BRT = 33,
BST = 34,
BTT = 35,
C = 36,
CAST = 37,
CAT = 38,
CCT = 39,
CDT = 40,
CEST = 41,
CET = 42,
CHADT = 43,
CHAST = 44,
CHOST = 45,
CHOT = 46,
ChST = 47,
CHUT = 48,
CIDST = 49,
CIST = 50,
CKT = 51,
CLST = 52,
CLT = 53,
COT = 54,
CST = 55,
CT = 56,
CVT = 57,
CXT = 58,
D = 59,
DAVT = 60,
DDUT = 61,
E = 62,
EASST = 63,
EAST = 64,
EAT = 65,
ECT = 66,
EDT = 67,
EEST = 68,
EET = 69,
EGST = 70,
EGT = 71,
EST = 72,
ET = 73,
F = 74,
FET = 75,
FJST = 76,
FJT = 77,
FKST = 78,
FKT = 79,
FNT = 80,
G = 81,
GALT = 82,
GAMT = 83,
GET = 84,
GFT = 85,
GILT = 86,
GMT = 87,
GST = 88,
GYT = 89,
H = 90,
HADT = 91,
HAST = 92,
HKT = 93,
HOVST = 94,
HOVT = 95,
I = 96,
ICT = 97,
IDT = 98,
IOT = 99,
IRDT = 100,
IRKST = 101,
IRKT = 102,
IRST = 103,
IST = 104,
JST = 105,
K = 106,
KGT = 107,
KOST = 108,
KRAST = 109,
KRAT = 110,
KST = 111,
KUYT = 112,
L = 113,
LHDT = 114,
LHST = 115,
LINT = 116,
M = 117,
MAGST = 118,
MAGT = 119,
MART = 120,
MAWT = 121,
MDT = 122,
MHT = 123,
MMT = 124,
MSD = 125,
MSK = 126,
MST = 127,
MT = 128,
MUT = 129,
MVT = 130,
MYT = 131,
N = 132,
NCT = 133,
NDT = 134,
NFT = 135,
NOVST = 136,
NOVT = 137,
NPT = 138,
NRT = 139,
NST = 140,
NUT = 141,
NZDT = 142,
NZST = 143,
O = 144,
OMSST = 145,
OMST = 146,
ORAT = 147,
P = 148,
PDT = 149,
PET = 150,
PETST = 151,
PETT = 152,
PGT = 153,
PHOT = 154,
PHT = 155,
PKT = 156,
PMDT = 157,
PMST = 158,
PONT = 159,
PST = 160,
PT = 161,
PWT = 162,
PYST = 163,
PYT = 164,
Q = 165,
QYZT = 166,
R = 167,
RET = 168,
ROTT = 169,
S = 170,
SAKT = 171,
SAMT = 172,
SAST = 173,
SBT = 174,
SCT = 175,
SGT = 176,
SRET = 177,
SRT = 178,
SST = 179,
SYOT = 180,
T = 181,
TAHT = 182,
TFT = 183,
TJT = 184,
TKT = 185,
TLT = 186,
TMT = 187,
TOT = 188,
TVT = 189,
U = 190,
ULAST = 191,
ULAT = 192,
UYST = 193,
UYT = 194,
UZT = 195,
V = 196,
VET = 197,
VLAST = 198,
VLAT = 199,
VOST = 200,
VUT = 201,
W = 202,
WAKT = 203,
WARST = 204,
WAST = 205,
WAT = 206,
WEST = 207,
WET = 208,
WFT = 209,
WGST = 210,
WGT = 211,
WIB = 212,
WIT = 213,
WITA = 214,
WST = 215,
WT = 216,
X = 217,
Y = 218,
YAKST = 219,
YAKT = 220,
YAPT = 221,
YEKST = 222,
YEKT = 223,
Z = 224,
GMT1 = 225,
};
namespace DateTimeUtils
{
extern std::time_t GetUTCTime(int Y, int M, int D, int h, int m, int s, TimeZonesType timeZone);
extern long GetTimeZoneOffset(TimeZonesType timeZone);
extern long GetLocalTimeZoneOffset();
extern TimeZonesType TimeZoneFromAbbreviation(const std::string& Abbreviation);
extern const char* TimeZoneToAbbreviation(TimeZonesType timeZone);
extern void LocalTimeS(struct tm *ltm, std::time_t* lt);
extern std::ostream& TimeToStream(std::ostream& os, std::time_t t, const char* fmt);
}
}
#endif
<file_sep>/include/gamesite.hpp
#ifndef INCLUDE_GAMESITE_H
#define INCLUDE_GAMESITE_H
#include <string>
#include "types.hpp"
namespace a2a
{
enum class GameSite : u8
{
Unknown = 0,
/* Holdem Manager ID+1 */
PartyPoker = 1,
FullTilt = 2,
PokerStars = 3,
Prima = 4,
IPoker = 5,
Absolute = 6,
Cryptologic = 7,
Bodog = 8,
UltimateBet = 9,
Ongame = 10,
Everest = 11,
Pacific = 13,
Betfair = 15,
Dracula = 16,
Entraction = 17,
CakePoker = 18,
BossMedia = 19,
Merge = 20,
PokerRoom = 21,
EverLeaf = 22,
Winamax = 23,
/* misc */
Cereus = 24,
MicroGaming = 25,
Ladbrokes = 26,
DollaroPoker = 27,
WinningPoker = 28,
IPoker2 = 29,
Lotos = 30,
/* lng */
PartyPokerFr = 31,
PartyPokerIt = 32,
PartyPokerNJ = 33,
PartyPokerEs = 34,
PokerStarsFr = 35,
PokerStarsIt = 36,
PokerStarsEs = 37,
OnGameIt = 38,
OnGameFr = 39,
IPokerIt = 40,
IPokerFr = 41,
Any = 63
};
namespace GameSiteUtils
{
extern const char* GameSiteToString(GameSite gameSite);
extern GameSite GameSiteFromString(const std::string& siteName);
};
}
#endif
<file_sep>/include/luapool.hpp
#ifndef INCLUDE_LUAPOOL_HPP
#define INCLUDE_LUAPOOL_HPP
#include <cassert>
#include <atomic>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <stack>
#include "luastate.hpp"
namespace a2a
{
class LuaStatesPool final
{
public:
using chunk_t = std::shared_ptr<LuaState>;
using lock_t = std::unique_lock<std::mutex>;
LuaStatesPool(std::size_t statesNum);
~LuaStatesPool();
class PooledLuaState final
{
public:
using releaser_t = std::function<void(void)>;
PooledLuaState(LuaState& ref, const releaser_t& onRelease);
~PooledLuaState();
LuaState& Ref() const;
PooledLuaState(const PooledLuaState&) = delete;
PooledLuaState& operator=(const PooledLuaState&) = delete;
private:
LuaState& m_ref;
releaser_t m_fOnRelease;
};
PooledLuaState* GetPooledState();
static LuaStatesPool& Global();
private:
std::atomic<bool> m_abStop;
mutable std::mutex m_mutex;
std::condition_variable m_condReady;
std::stack<std::size_t> m_readyChunks;
std::vector<chunk_t> m_pool;
};
}
//
// inlines
//
namespace a2a
{
inline LuaState& LuaStatesPool::PooledLuaState::Ref() const { return m_ref; }
}
#endif
<file_sep>/include/streamutils.hpp
#ifndef INCLUDE_STREAMUTILS_H
#define INCLUDE_STREAMUTILS_H
#include <string>
#include <iostream>
#include "types.hpp"
namespace a2a
{
namespace StreamUtils
{
extern std::istream& ReadLine_(std::istream&, std::string&, std::size_t& gcount, std::size_t max_size = 1024);
extern std::istream& ReadLine(std::istream&, std::string&, std::size_t max_size = 1024);
template<typename T = int>
void IntToRomanStream(std::ostream& os, T value)
{
struct romandata_t { int value; char const* numeral; };
const struct romandata_t romandata[] =
{
{ 1000, "M" },{ 900, "CM" },
{ 500, "D" },{ 400, "CD" },
{ 100, "C" },{ 90, "XC" },
{ 50, "L" },{ 40, "XL" },
{ 10, "X" },{ 9, "IX" },
{ 5, "V" },{ 4, "IV" },
{ 1, "I" },
{ 0, NULL }
};
for (const romandata_t* current = romandata; current->value > 0; ++current)
{
while (value >= current->value)
{
os << current->numeral;
value -= current->value;
}
}
}
}
}
#endif<file_sep>/src/fsysutils.cxx
#include <stdexcept>
#include <sstream>
#ifdef _MSC_VER
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <direct.h>
#define GetCurrentDir _getcwd
#include <Shlobj.h>
#undef min
#undef max
#else
#include <cstring>
#include <dirent.h>
#include <libgen.h>
#include <sys/stat.h>
#include <errno.h>
#include <pwd.h>
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
#include "strutils.hpp"
#include "fsysutils.hpp"
#include "filescol.hpp"
namespace a2a
{
namespace detail
{
struct FileImpl
{
FileImpl() {}
FileImpl(const std::string& path) : m_path(path), m_size(0)
{
auto dp = path.find_last_of('.');
if (dp != std::string::npos)
{
if (path.find_first_of("\\/", dp) == std::string::npos)
m_ext = path.substr(dp);
else
m_ext = ".";
}
else
m_ext = ".";
}
virtual ~FileImpl() {}
void GetIStream(std::ifstream& is);
std::size_t Read(std::string & out, std::size_t maxSize);
void ReadCache(std::size_t blockSize) { Read(m_cache, blockSize); }
void ClearCache() { m_cache.clear(); }
bool HasCache(std::size_t blockSize) const { return m_cache.size() >= blockSize; }
virtual std::string GetFullPath() const = 0;
std::string m_path;
std::string m_cache;
i64 m_size;
std::string m_ext;
};
struct DirectoryImpl
{
DirectoryImpl() : m_hasFiles(false) {}
virtual ~DirectoryImpl() {}
virtual void Reopen(const std::string& path, bool readSubDirs)
{
m_path = path; m_readSubDir = readSubDirs; m_hasFiles = false;
}
virtual std::string GetFullPath() const = 0;
virtual void GetFiles(std::size_t maxNum, FilesCollection& files) = 0;
virtual void GetFilesMinTotalSize(FilesCollection& out, std::size_t minTotalSize) = 0;
std::string m_path;
bool m_readSubDir;
bool m_hasFiles;
};
}
#ifdef _MSC_VER
namespace win
{
using namespace detail;
struct CFile : public FileImpl
{
CFile(const std::string& path) : FileImpl(path){}
CFile(const std::wstring& dir, const WIN32_FIND_DATAW& findData);
std::string GetFullPath() const;
};
struct Dir : public DirectoryImpl
{
Dir();
~Dir();
void GetFiles(std::size_t maxNum, FilesCollection& files);
void GetFilesMinTotalSize(FilesCollection& out, std::size_t minTotalSize);
void Reopen(const std::string& path, bool readSubDirs);
std::string GetFullPath() const;
std::wstring m_pathw;
WIN32_FIND_DATAW m_findData;
HANDLE m_handle;
Dir* m_subDir;
void _next();
bool _isok() const;
};
} using namespace win;
#else
namespace dirent
{
using namespace detail;
struct CFile : public FileImpl
{
CFile(const std::string& path, const struct stat& st);
CFile(const std::string& path) : FileImpl(path) {}
std::string GetFullPath() const final;
};
struct Dir : public DirectoryImpl
{
Dir();
~Dir();
void GetFiles(std::size_t maxNum, FilesCollection& files) final;
void GetFilesMinTotalSize(FilesCollection& out, std::size_t minTotalSize);
void Reopen(const std::string& path, bool readSubDirs) final;
std::string GetFullPath() const final;
Dir* m_subDir;
DIR* m_handle;
struct dirent* m_pDirData;
void _next();
bool _isok() const;
};
} using namespace dirent;
#endif
//---------------------------------------------------------------- File
File::File(const FileImpl& _impl)
{
m_pimpl = std::make_shared<CFile>( static_cast<const CFile&>(_impl));
}
File::File(const std::string& path)
{
m_pimpl = std::make_shared<CFile>( path );
}
const std::string & File::GetPath() const
{
return m_pimpl->m_path;
}
const std::string & File::GetExt() const
{
return m_pimpl->m_ext;
}
std::string File::GetFullPath() const
{
return m_pimpl->GetFullPath();
}
void File::GetStream(std::ifstream& is)
{
m_pimpl->GetIStream(is);
}
std::size_t File::Read(std::string & out, std::size_t maxSize)
{
return m_pimpl->Read(out, maxSize);
}
void File::ReadCache(std::size_t blockSize)
{
m_pimpl->ReadCache(blockSize);
}
void File::ClearCache()
{
m_pimpl->ClearCache();
}
bool File::IsCached(std::size_t blockSize) const
{
return m_pimpl->HasCache(blockSize);
}
std::string & File::GetCache()
{
return m_pimpl->m_cache;
}
File::~File()
{
}
const i64& File::FileSize() const
{
return m_pimpl->m_size;
}
//---------------------------------------------------------------- Directory
Directory::Directory(const DirectoryImpl& _impl)
{
m_pimpl = StdUtils::my_make_unique<Dir>(static_cast<const Dir&>(_impl));
}
Directory::Ptr Directory::Open(const std::string & UTF8Path, bool ReadSubdirs)
{
auto ret (StdUtils::my_make_unique<Directory>( Dir() ) );
ret->m_pimpl->Reopen(UTF8Path, ReadSubdirs);
return ret;
}
const std::string & Directory::GetPath() const
{
return m_pimpl->m_path;
}
std::string Directory::GetFullPath() const
{
return m_pimpl->GetFullPath();
}
bool Directory::HasFilesToProcess() const
{
return m_pimpl->m_hasFiles;
}
void Directory::Reopen()
{
m_pimpl->Reopen(m_pimpl->m_path, m_pimpl->m_readSubDir);
}
FilesCollection Directory::GetFiles(std::size_t maxNum)
{
FilesCollection ret;
GetFiles(ret, maxNum);
return ret;
}
void Directory::GetFiles(FilesCollection & out, std::size_t maxNum)
{
m_pimpl->GetFiles(maxNum, out);
}
void Directory::GetFilesMinTotalSize(FilesCollection& out, std::size_t minTotalSize)
{
out.__calcSize = 0;
m_pimpl->GetFilesMinTotalSize(out, minTotalSize);
}
FilesCollection Directory::GetFilesMinTotalSize(std::size_t minTotalSize)
{
FilesCollection ret;
GetFilesMinTotalSize(ret, minTotalSize);
return ret;
}
Directory::~Directory()
{
}
}
using namespace a2a;
using namespace a2a::detail;
static bool EndsWithSlash(const std::string& s)
{
return !s.empty() && (s[s.size() - 1] == '\\' || s[s.size() - 1] == '/');
}
static bool EndsWithSlash(const std::wstring& s)
{
return !s.empty() && (s[s.size() - 1] == L'\\' || s[s.size() - 1] == L'/');
}
static bool IsMask(const std::string& s)
{
if (s.empty()) return false;
auto sIdx = s.find_last_of("/\\");
if (sIdx == std::string::npos)
sIdx = 0;
return s.find_first_of("?*", sIdx) != std::string::npos;
}
void FileImpl::GetIStream(std::ifstream& is)
{
is.open(m_path, std::ios::binary);
}
std::size_t FileImpl::Read(std::string & out, std::size_t maxSize)
{
if (maxSize > 0 && maxSize <= m_cache.size())
{
out.assign(m_cache.c_str(), maxSize);
return maxSize;
}
std::ifstream is(m_path, std::ios::binary);
if (!is.is_open())
throw std::runtime_error(std::string("Failed to read file: ")+m_path);
if (maxSize == 0)
{
is.seekg(0, std::ios::end);
out.resize(static_cast<std::size_t>(is.tellg()));
is.seekg(0, std::ios::beg);
}
else
out.resize(maxSize);
if (!is.read(&out[0], out.size()))
out.resize(static_cast<std::size_t>(is.gcount()));
is.close();
return out.size();
}
#ifdef _MSC_VER
struct win32LocalFreeHelper
{
void operator()(void* p)
{
::LocalFree(reinterpret_cast<HLOCAL>(p));
}
;
};
std::string win32_error_message(DWORD errorCode, const std::string& _where = "")
{
std::unique_ptr<wchar_t[], win32LocalFreeHelper> buff;
LPWSTR buffPtr;
DWORD bufferLength = ::FormatMessageW(
FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL,
errorCode,
0,
reinterpret_cast<LPWSTR>(&buffPtr),
0,
NULL);
buff.reset(buffPtr);
std::stringstream ss;
ss << '[' << errorCode << "]: " << _where << std::endl
<< StrUtils::wchar_to_utf8 ( std::wstring(buff.get(), bufferLength) );
return ss.str();
}
static std::string GetFullPathW(const std::wstring& wcpath)
{
using namespace StrUtils;
auto sz = GetFullPathNameW(wcpath.c_str(), 0, NULL, NULL);
if (sz == 0)
throw std::runtime_error(win32_error_message(GetLastError(),
std::string("Get Full path [GetFullPathNameW]: ") + wchar_to_utf8(wcpath)));
wchar_t *buff = new wchar_t[sz + 1]; buff[sz] = 0;
if (0 == GetFullPathNameW(wcpath.c_str(), sz, buff, NULL))
{
delete[] buff;
throw std::runtime_error(win32_error_message(GetLastError(),
std::string("Get Full path [GetFullPathNameW]: ") + wchar_to_utf8(wcpath)));
}
auto ret = wchar_to_utf8(buff);
delete[] buff;
return ret;
}
static std::string homeFolder()
{
WCHAR path[MAX_PATH];
if (SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, path)))
return StrUtils::wchar_to_utf8(path);
throw std::runtime_error("Failed to get user home path [SHGetFolderPathW].");
}
CFile::CFile(const std::wstring& dir, const WIN32_FIND_DATAW& findData)
{
using namespace StrUtils;
wchar_t dbuff[_MAX_DIR];
std::wstring fn(findData.cFileName);
_wsplitpath_s(dir.c_str(), 0, 0, dbuff, _MAX_DIR - 1, 0, 0, 0, 0);
m_path = wchar_to_utf8(std::wstring(dbuff) + fn);
auto dp = fn.find_last_of(L'.');
if (dp != std::wstring::npos)
m_ext = wchar_to_utf8(fn.substr(dp));
else
m_ext = ".";
LARGE_INTEGER size;
size.HighPart = findData.nFileSizeHigh;
size.LowPart = findData.nFileSizeLow;
m_size = size.QuadPart;
}
std::string CFile::GetFullPath() const
{
return a2a::GetFullPath(m_path);
}
// win dir
// -----------------------------------------------------------------------------------
Dir::Dir() : m_handle(INVALID_HANDLE_VALUE), m_subDir(nullptr)
{
}
Dir::~Dir()
{
if (m_subDir != nullptr)
delete m_subDir;
if (m_handle != INVALID_HANDLE_VALUE)
FindClose(m_handle);
}
inline void Dir::_next()
{
if (FindNextFileW(m_handle, &m_findData) == FALSE)
{
m_hasFiles = false;
if (GetLastError() != ERROR_SUCCESS && GetLastError() != ERROR_NO_MORE_FILES)
throw std::runtime_error(win32_error_message(GetLastError(), std::string("Read directory [FindNextFileW]: ") + m_path));
}
}
inline bool Dir::_isok() const
{
return wcscmp(m_findData.cFileName, L".") && wcscmp(m_findData.cFileName, L"..");
}
inline static bool IsReg(const WIN32_FIND_DATAW& fd)
{
return (fd.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) ||
(
!(fd.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) &&
!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) &&
!(fd.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED) &&
!(fd.dwFileAttributes & FILE_ATTRIBUTE_INTEGRITY_STREAM) &&
!(fd.dwFileAttributes & FILE_ATTRIBUTE_NO_SCRUB_DATA) &&
!(fd.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE) &&
!(fd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY)
);
}
void Dir::GetFiles(std::size_t maxNum, FilesCollection& files)
{
using namespace StrUtils;
if (m_handle == INVALID_HANDLE_VALUE)
throw std::runtime_error(win32_error_message(GetLastError(), std::string("Open directory: ") + m_path));
if (m_subDir != nullptr)
{
m_subDir->GetFiles(maxNum, files);
if (!m_subDir->m_hasFiles)
{
delete m_subDir; m_subDir = nullptr;
_next();
}
}
while (m_hasFiles && (maxNum == 0 || files.Size() < maxNum))
{
if (_isok())
{
if ((m_findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
{
if (m_readSubDir)
{
m_subDir = new Dir();
m_subDir->Reopen(wchar_to_utf8(m_pathw + m_findData.cFileName), true);
m_subDir->GetFiles(maxNum, files);
if (!m_subDir->m_hasFiles)
{
delete m_subDir; m_subDir = nullptr;
}
else if ( !(maxNum == 0 || files.Size() < maxNum) )
break;
}
}
else if (IsReg(m_findData))
{
files.Add(std::make_shared<File>(CFile(m_pathw, m_findData)));
}
}
_next();
}
}
void Dir::GetFilesMinTotalSize(FilesCollection& files, std::size_t minTotalSize)
{
using namespace StrUtils;
if (m_handle == INVALID_HANDLE_VALUE)
throw std::runtime_error(win32_error_message(GetLastError(), std::string("Open directory: ") + m_path));
if (m_subDir != nullptr)
{
m_subDir->GetFilesMinTotalSize(files, minTotalSize);
if (!m_subDir->m_hasFiles)
{
delete m_subDir; m_subDir = nullptr;
_next();
}
}
while (m_hasFiles && static_cast<i64>(minTotalSize) > files.__calcSize)
{
if (_isok())
{
if ((m_findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0)
{
if (m_readSubDir)
{
m_subDir = new Dir();
m_subDir->Reopen(wchar_to_utf8(m_pathw + m_findData.cFileName), true);
m_subDir->GetFilesMinTotalSize(files, minTotalSize);
if (!m_subDir->m_hasFiles)
{
delete m_subDir; m_subDir = nullptr;
}
else if (files.__calcSize >= static_cast<i64>(minTotalSize))
break;
}
}
else if (IsReg(m_findData))
{
auto f = std::make_shared<File>(CFile(m_pathw, m_findData));
files.__calcSize += f->FileSize();
files.Add(f);
}
}
_next();
}
}
void Dir::Reopen(const std::string& path, bool readSubDirs)
{
using namespace StrUtils;
DirectoryImpl::Reopen(path, readSubDirs);
if (m_subDir != nullptr)
{
delete m_subDir; m_subDir = nullptr;
}
if (m_handle != INVALID_HANDLE_VALUE)
{
FindClose(m_handle);
m_handle = INVALID_HANDLE_VALUE;
}
auto isMask = IsMask(m_path);
m_pathw = StrUtils::utf8_to_wchar(m_path);
if (!isMask && !EndsWithSlash(m_pathw))
m_pathw += L'\\';
m_handle = FindFirstFileW((m_pathw + L'*').c_str(), &m_findData);
if (m_handle == INVALID_HANDLE_VALUE)
{
DWORD err = GetLastError();
throw std::runtime_error(win32_error_message(err,
std::string("Open directory [FindFirstFileW]: ") + wchar_to_utf8(m_pathw)));
}
m_hasFiles = true;
}
std::string Dir::GetFullPath() const
{
return GetFullPathW(m_pathw);
}
// win export
// -----------------------------------------------------------------------------------
namespace a2a
{
std::string GetFullPath(const std::string& rpath)
{
using namespace StrUtils;
return GetFullPathW(utf8_to_wchar(rpath));
}
}
#else
CFile::CFile(const std::string& path, const struct stat& st) : FileImpl(path)
{
m_size = st.st_size;
}
std::string CFile::GetFullPath() const
{
return ::GetFullPath(m_path);
}
Dir::Dir() : m_subDir(nullptr), m_handle(nullptr), m_pDirData(nullptr)
{
}
Dir::~Dir()
{
if (m_subDir != nullptr)
delete m_subDir;
if (m_handle != nullptr)
closedir(m_handle);
}
inline void Dir::_next()
{
m_pDirData = readdir(m_handle);
m_hasFiles = m_pDirData != nullptr;
}
inline bool Dir::_isok() const
{
return strcmp(m_pDirData->d_name, ".") && strcmp(m_pDirData->d_name, "..");
}
void Dir::GetFiles(std::size_t maxNum, FilesCollection& files)
{
using namespace StrUtils;
if (m_handle == nullptr)
throw std::runtime_error( std::string("Open directory [GetFiles]: ") + m_path );
if (m_subDir != nullptr)
{
m_subDir->GetFiles(maxNum, files);
if (!m_subDir->m_hasFiles)
{
delete m_subDir; m_subDir = nullptr;
_next();
}
}
while (m_hasFiles && (maxNum == 0 || files.Size() < maxNum))
{
if (_isok())
{
std::string path = m_path + m_pDirData->d_name;
struct stat di_stat;
if (stat(path.c_str(), &di_stat) == -1)
throw std::runtime_error(std::string("Read directory item [stat]: ") + path);
if (S_ISDIR(di_stat.st_mode))
{
if (m_readSubDir)
{
m_subDir = new Dir();
m_subDir->Reopen(path, true);
m_subDir->GetFiles(maxNum, files);
if (!m_subDir->m_hasFiles)
{
delete m_subDir; m_subDir = nullptr;
}
else if (!(maxNum == 0 || files.Size() < maxNum))
break;
}
}
else if (S_ISREG(di_stat.st_mode))
{
files.Add(std::make_shared<File>(CFile(path, di_stat)));
}
}
_next();
}
}
void Dir::GetFilesMinTotalSize(FilesCollection& files, std::size_t minTotalSize)
{
using namespace StrUtils;
if (m_handle == nullptr)
throw std::runtime_error( std::string("Open directory [GetFiles]: ") + m_path );
if (m_subDir != nullptr)
{
m_subDir->GetFilesMinTotalSize(files, minTotalSize);
if (!m_subDir->m_hasFiles)
{
delete m_subDir; m_subDir = nullptr;
_next();
}
}
while (m_hasFiles && minTotalSize > files.__calcSize)
{
if (_isok())
{
std::string path = m_path + m_pDirData->d_name;
struct stat di_stat;
if (stat(path.c_str(), &di_stat) == -1)
throw std::runtime_error(std::string("Read directory item [stat]: ") + path);
if (S_ISDIR(di_stat.st_mode))
{
if (m_readSubDir)
{
m_subDir = new Dir();
m_subDir->Reopen(path, true);
m_subDir->GetFilesMinTotalSize(files, minTotalSize);
if (!m_subDir->m_hasFiles)
{
delete m_subDir; m_subDir = nullptr;
}
else if (files.__calcSize>=minTotalSize)
break;
}
}
else if (S_ISREG(di_stat.st_mode))
{
auto f = std::make_shared<File>(CFile(path, di_stat));
files.__calcSize += f->FileSize();
files.Add(f);
}
}
_next();
}
}
void Dir::Reopen(const std::string& path, bool readSubDirs)
{
using namespace StrUtils;
DirectoryImpl::Reopen(path, readSubDirs);
if (m_subDir != nullptr)
{
delete m_subDir;
m_subDir = nullptr;
}
if (m_handle != nullptr)
{
closedir(m_handle);
m_handle = nullptr;
m_pDirData = nullptr;
}
if (!IsMask(m_path) && !EndsWithSlash(m_path))
m_path+='/';
m_handle = opendir(m_path.c_str());
if (m_handle == NULL)
throw std::runtime_error(std::string("Open directory [opendir]: ") + std::to_string(errno) + " " + m_path);
m_pDirData = readdir(m_handle);
m_hasFiles = m_pDirData != nullptr;
}
std::string Dir::GetFullPath() const
{
return ::GetFullPath(m_path);
}
static std::string homeFolder()
{
const char* dir;
if ((dir = getenv("HOME"))==NULL)
dir = getpwuid(getuid())->pw_dir;
return std::string(dir)+'/';
}
// gcc export
// -----------------------------------------------------------------------------------
namespace a2a
{
std::string GetFullPath(const std::string& rpath)
{
char buff[PATH_MAX];
if (realpath(rpath.c_str(), buff) == 0)
throw std::runtime_error( std::string("Get Full path [realpath]: ") + rpath);
std::string ret(buff);
if (!EndsWithSlash(ret))
ret+='/';
return ret;
}
}
#endif
namespace a2a
{
std::string _searchPath(const std::string& rpath, int jumps)
{
#ifndef _MSC_VER
char buff[FILENAME_MAX];
if (!GetCurrentDir(buff, sizeof(buff)))
return "";
#else
wchar_t buff[4096];
DWORD length = GetModuleFileNameW(NULL, buff, 4096);
std::string fpath(StrUtils::wchar_to_utf8(buff));
auto dp = fpath.find_last_of("\\/");
if (dp != std::string::npos && dp!=fpath.size()-1)
fpath = fpath.substr(0, dp+1);
#endif
int j = 0;
Dir cdir; std::string s(rpath);
while (!cdir.m_hasFiles && j < jumps)
{
try
{
if (j>0)
s = std::string("../") + s;
//std::cout << std::string(buff)+"/"+s << std::endl;
#ifndef _MSC_VER
char res_path[FILENAME_MAX];
realpath((std::string(buff)+"/"+s).c_str(), res_path);
cdir.Reopen(res_path, false);
#else
cdir.Reopen(fpath+s, false);
#endif
// auto ret = cdir.GetFullPath();
// if (!EndsWithSlash(ret))
// ret+='/';
return cdir.GetFullPath();
}
catch (...)
{
}
j++;
}
return "";
}
std::string GetSysPath(SysFolder sf)
{
switch (sf)
{
case SysFolder::Home:
{
auto ret = ::homeFolder();
if (!EndsWithSlash(ret))
ret += '\\';
return ret;
}
default:
return "";
}
}
}
<file_sep>/src/hhparser_pac.cxx
#include <string>
#include <ctime>
#include "strutils.hpp"
#include "sitesdata.hpp"
#include "hhparser_pac.hpp"
#include "hhlineparser_impl.hpp"
namespace a2a
{
namespace detail
{
struct PacificParser : public LineParserImplBase
{
PacificParser(HandHistory& _hh, const HandHistoryParserSettings& _cfg, const char*& _cursor, GameSite _site) :
LineParserImplBase(_hh, _cfg, _cursor, _site)
{
}
ParseStage ProcessHeaderLine(const std::string& ln, int index);
void ProcessHeaderLine_0(const std::string& ln);
void ProcessHeaderLine_1(const std::string& ln);
void ParseDateTime(const std::string& ln);
std::size_t ParseLimit(const std::string& ln);
void ParseGameType(const std::string& ln, std::size_t off);
void ProcessHeaderLine_2(const std::string& ln);
void ParseMaxPlayersTableName(const std::string& ln);
void ParseGameMode(const std::string& ln);
void ProcessHeaderLine_3(const std::string& ln);
void ProcessHeaderLine_4(const std::string& ln);
ParseStage ProcessSeatingLine(const std::string& ln);
ParseStage ProcessBlindsLine(const std::string& ln);
ParseStage ProcessStreetChangeLine(const std::string& ln);
ParseStage ProcessStreetLine(const std::string& ln);
bool ParseCardsDealt(const std::string & ln);
bool ParseActionLine(const std::string & ln);
ParseStage ProcessSummaryLine(const std::string& ln);
bool ParseDidnotshowhand(const std::string & ln);
bool ParseShowHand(const std::string & ln);
bool ParseCollected(const std::string & ln);
bool ParseMucksHand(const std::string & ln);
bool ParseHiLo(const std::string & ln);
void OnHandComplete();
HandActions m_summary;
};
}
namespace Pacific
{
namespace common
{
common_pacific_parser::common_pacific_parser(GameSite site, const std::string& name) :
HandHistoryLineParser(GameSiteUtils::GameSiteToString(site), Version(1, 0)), m_site(site)
{
m_handStart = std::string("***** ") + name + ' ';
}
const std::string & common_pacific_parser::HandStart() const
{
return m_handStart;
}
ILineParserImpl * common_pacific_parser::GetImplementation(HandHistory & _hh, const HandHistoryParserSettings & _cfg, const char *& _cursor) const
{
return new ::a2a::detail::PacificParser(_hh, _cfg, _cursor, m_site);
}
}
}
}
///
/// implementation
///
namespace a2a
{
namespace detail
{
ParseStage PacificParser::ProcessHeaderLine(const std::string& ln, int index)
{
switch (index)
{
case 0:ProcessHeaderLine_0(ln); break;
case 1:ProcessHeaderLine_1(ln); break;
case 2:ProcessHeaderLine_2(ln); break;
case 3:ProcessHeaderLine_3(ln); break;
case 4:ProcessHeaderLine_4(ln); return ParseStage::Seating;
default: break;
}
return ParseStage::Header;
}
void PacificParser::ProcessHeaderLine_0(const std::string& ln)
{
static const std::size_t SNAP_MIN_OFFSET = 14;
static const std::size_t MIN_HANDID_NUMBER_LEN = 8;
int tr, dr;
std::size_t eIdx = ln.rfind(" *");
if (eIdx == std::string::npos)
ThrowFailRead("HandID [ * ending]", ln);
std::size_t sIdx = ln.find_last_of(' ', eIdx-1);
if (sIdx == std::string::npos)
ThrowFailRead("HandID [ start ]", ln);
hh.SetHandId(StrUtils::parse_int<u64>(ln.c_str() + sIdx, &dr, &tr));
if (dr < MIN_HANDID_NUMBER_LEN)
ThrowFailRead("HandID [Number too short]", ln);
if (ln.find(" Snap") != std::string::npos)
hh.SetGameMode(CardGameMode::FastFold);
}
void PacificParser::ProcessHeaderLine_1(const std::string& ln)
{
ParseDateTime(ln);
ParseGameType(ln, ParseLimit(ln));
}
// date/time
void PacificParser::ParseDateTime(const std::string& ln)
{
static const int COPY_RANGE = 21;
static const int TZ_RANGE = 7;
std::size_t aIdx = ln.find_last_of('*');
if (aIdx == std::string::npos)
ThrowFailRead("Header Line 2 [wrong format]", ln);
aIdx = ln.find_first_not_of(' ', aIdx+1);
if (aIdx == std::string::npos)
{
// nice
// 10$/20$ Blinds No Limit Holdem - *** ????
// Tournament #77986931 4, 50$ + 0, 50$ - Table #15 9 Max(Real Money)
return; // std::time(0) by HandHistory default
}
int tr, dr;
int D = StrUtils::parse_int(ln.c_str() + aIdx, &dr, &tr);
if (dr != 2)
ThrowFailRead("DateTime [Day]", ln);
aIdx += tr;
int M = StrUtils::parse_int(ln.c_str() + aIdx, &dr, &tr);
if (dr != 2)
ThrowFailRead("DateTime [Month]", ln);
aIdx += tr;
int Y = StrUtils::parse_int(ln.c_str() + aIdx, &dr, &tr);
if (dr != 4)
ThrowFailRead("DateTime [Year]", ln);
aIdx += tr;
int H = StrUtils::parse_int(ln.c_str() + aIdx, &dr, &tr);
if (dr < 1)
ThrowFailRead("DateTime [Hours]", ln);
aIdx += tr;
int mins = StrUtils::parse_int(ln.c_str() + aIdx, &dr, &tr);
if (dr < 1)
ThrowFailRead("DateTime [Mins]", ln);
aIdx += tr;
int secs = StrUtils::parse_int(ln.c_str() + aIdx, &dr, &tr);
if (dr < 1)
ThrowFailRead("DateTime [Seconds]", ln);
hh.SetDateTimeUTC(DateTimeUtils::GetUTCTime(Y, M, D, H, mins, secs, TimeZonesType::UTC));
}
std::size_t PacificParser::ParseLimit(const std::string& ln)
{
auto curr = CurrencyUtils::CurrencyTypeFromUTF8Symbol(ln.c_str());
hh.SetTableCurrency(curr);
hh.SetStacksCurrency(curr);
bool curr_beg = curr != CurrencyType::Chips;
int tr, dr, dots;
int sb = StrUtils::parse_int(ln.c_str(), &dr, &tr, &dots, true);
if (dr == 0)
ThrowFailRead("Limit [Small blind]", ln);
if (dots == 0)
sb *= 100;
if (hh.GetStacksCurrency() == CurrencyType::Chips)
{
curr = CurrencyUtils::CurrencyTypeFromUTF8Symbol(ln.c_str() + tr);
hh.SetTableCurrency(curr);
hh.SetStacksCurrency(curr);
}
int tr2;
int bb = StrUtils::parse_int(ln.c_str()+tr, &dr, &tr2, &dots, true);
if (dr == 0)
ThrowFailRead("Limit [Big blind]", ln);
if (dots == 0)
bb *= 100;
std::size_t off = tr + tr2;
if (!curr_beg && curr != CurrencyType::Chips)
off = ln.find_first_of(' ', off)+1;
off = ln.find_first_of(' ', off)+1;
hh.SetBlinds(sb, bb);
return off;
}
void PacificParser::ParseGameType(const std::string& ln, std::size_t off)
{
using namespace StrUtils;
static constexpr char _nl[] = "No Limit ";
static constexpr char _pl[] = "Pot Limit ";
static constexpr char _fl[] = "Fix Limit ";
static constexpr char _holdem[] = "Holdem";
static constexpr char _omaha[] = "Omaha";
static constexpr char _omahaHL[] = "OmahaHL";
CardGameTypeFlags gt = CardGameType::Unknown;
if (starts_with(ln.c_str(), _nl, off))
{
gt |= CardGameType::NoLimit;
off += calen(_nl);
}
else if (starts_with(ln, _pl, off))
{
gt |= CardGameType::PotLimit;
off += calen(_pl);
}
else if (starts_with(ln, _fl, off))
{
gt |= CardGameType::FixedLimit;
off += calen(_fl);
}
else
ThrowFailRead("Limit type", ln);
if (starts_with(ln.c_str(), _holdem, off))
gt |= CardGameType::Holdem;
else if (starts_with(ln, _omaha, off))
gt |= CardGameType::Omaha;
else if (starts_with(ln, _omahaHL, off))
gt |= CardGameType::OmahaHiLo;
else
ThrowFailRead("Game type", ln);
hh.SetGameType(gt);
}
void PacificParser::ProcessHeaderLine_2(const std::string& ln)
{
ParseMaxPlayersTableName(ln);
ParseGameMode(ln);
}
void PacificParser::ParseMaxPlayersTableName(const std::string& ln)
{
auto rIdx = ln.rfind(" Max");
if (rIdx != std::string::npos && rIdx != 0)
{
// Table Brisbane (Real Money)
// no max players
rIdx = ln.find_last_of(' ', --rIdx);
int dr;
int maxp = StrUtils::parse_int(ln.c_str() + rIdx, &dr);
if (dr == 0)
ThrowFailRead("Table Max Players [number]", ln);
hh.SetTableMaxPlayers(maxp);
}
else
rIdx = ln.rfind(" (");
if (rIdx == std::string::npos)
ThrowFailRead("Table name", ln);
auto rIdx2 = ln.find_last_of(' ', rIdx-1);
if (rIdx2 == std::string::npos)
ThrowFailRead("Table name", ln);
if (ln.find_first_of('#', rIdx2) != std::string::npos)
{
rIdx2 = ln.find_last_of(' ', --rIdx2);
if (rIdx2 == std::string::npos)
ThrowFailRead("Table name", ln);
}
hh.SetTableName(ln.substr(rIdx2 + 1, rIdx - rIdx2 - 1));
}
void PacificParser::ParseGameMode(const std::string& ln)
{
using namespace StrUtils;
static const std::size_t MIN_TOURN_NUMBER_LEN = 7;
static constexpr char _tourn[] = "Tournament ";
std::size_t sIdx = 0;
if (StrUtils::starts_with(ln, _tourn))
{
hh.SetGameMode(CardGameMode::Tournament);
sIdx += calen(_tourn);
sIdx = ln.find_first_of("#", sIdx);
int dr, tr;
auto tournId = StrUtils::parse_int<i64>(ln.c_str() + sIdx, &dr, &tr);
if (dr < MIN_TOURN_NUMBER_LEN)
ThrowFailRead("Tournament ID [number]", ln);
hh.SetTournamentId(tournId);
int bb = hh.GetBigBlind();
if (hh.GetSmallBlind()>1000)
{
bb /= 100;
hh.SetBlindLevels(hh.GetSmallBlind() / 100, bb);
}
int i = 0;
for (float j = 100; j < bb; j *= 3) i++;
i = i > 0 ? i : 1; i = i > 32 ? 32 : i;
hh.SetTournamentLevel(i > 0 ? i : 1);
sIdx += tr;
auto v1 = ParseCash(ln.c_str() + sIdx);
if (v1 < 0)
ThrowFailRead("Buyin [1st value]", ln);
auto pIdx = ln.find_first_of('+', sIdx);
if (pIdx == std::string::npos)
ThrowFailRead("Buyin [+ sign]", ln);
auto v2= ParseCash(ln.c_str() + pIdx);
if (v2 < 0)
ThrowFailRead("Buyin [2nd value]", ln);
hh.SetBuyin(v1, v2);
}
else
hh.SetGameMode(CardGameMode::CashGame);
}
void PacificParser::ProcessHeaderLine_3(const std::string& ln)
{
auto sIdx = ln.find("Seat ");
if (std::string::npos == sIdx)
ThrowFailRead("Button position [Seat ...]", ln);
int dr;
auto btnSeat = StrUtils::parse_int(ln.c_str() + 5, &dr);
if (dr == 0)
ThrowFailRead("Button position [number]", ln);
hh.SetButtonSeatIndex(btnSeat);
}
void PacificParser::ProcessHeaderLine_4(const std::string& ln)
{
auto rIdx = ln.find_last_not_of(' ');
if (rIdx == std::string::npos)
ThrowFailRead("Active Players [number]", ln);
if (ln[rIdx] == '1')
{
hh.SetCancelled();
return;
}
if (hh.GetTableMaxPlayers() != 0)
return;
rIdx = ln.find_last_of(' ', rIdx-1);
int dr;
auto activePlayers = StrUtils::parse_int(ln.c_str() + rIdx, &dr);
if (dr == 0)
ThrowFailRead("Active Players [number]", ln);
hh.SetTableMaxPlayers(activePlayers, true);
}
ParseStage PacificParser::ProcessSeatingLine(const std::string& ln)
{
return
!LineParserUtils::TryParse_A_seat_colon_player_stack(this, ln) &&
!hh.GetSeats().Empty() ?
ProcessBlindsLine(ln) :
ParseStage::Seating;
}
ParseStage PacificParser::ProcessBlindsLine(const std::string& ln)
{
std::string player; int amount;
for (const auto& i : Pacific::BlindsActionsStrings)
if (LineParserUtils::TryParse__player_action_amount(this, ln, i.second, player, amount))
{
AddAction(std::make_shared<HandAction>(i.first, player, amount));
return ParseStage::Blinds;
}
int amount2;
if (LineParserUtils::TryParse__player_action_amount_plus_amount(this, ln, "posts dead blind", player, amount, amount2))
{
AddAction(std::make_shared<HandAction>(HandActionType::SmallAndBigBlind, player, amount + amount2));
return ParseStage::Blinds;
}
// ducksstaff posts small blind[1 200$]
// Sir_Kale posts big blind[2 400$]
// Jimmybatsi88 folds
/// no ** Dealing down cards **
return ProcessStreetLine(ln);
}
ParseStage PacificParser::ProcessStreetChangeLine(const std::string & ln)
{
if (ln[0] != '*')
return ParseStage::None;
for (const auto& i : Pacific::StreetStrings)
{
auto sIdx = ln.rfind(i.first);
if (sIdx != std::string::npos)
{
auto cIdx = ln.find('[', i.first.size() + sIdx);
CardSeq cs;
if (cIdx != std::string::npos )
cs = CardSeq::FromString(ln.c_str() + cIdx);
if (i.second != GameStageType::Summary)
AddAction(std::make_shared<HandAction>(HandActionType::Street, i.second, cs));
return i.second == GameStageType::Summary ? ParseStage::Summary : ParseStage::Streets;
}
}
return ParseStage::None;
}
ParseStage PacificParser::ProcessStreetLine(const std::string& ln)
{
auto isParsed =
ParseCardsDealt(ln) ||
ParseActionLine(ln);
return isParsed ? ParseStage::Streets : parseStage;
}
bool PacificParser::ParseCardsDealt(const std::string & ln)
{
return LineParserUtils::TryParse_A_dealtto_player_cards(this,ln);
}
bool PacificParser::ParseActionLine(const std::string & ln)
{
std::string player; int amount;
for (const auto& i : Pacific::ActionsStrings)
if (LineParserUtils::TryParse__player_action_amount(this, ln, i.second, player, amount, false))
{
if (amount < 0)
{
if (i.first != HandActionType::Check && i.first != HandActionType::Fold)
ThrowFailRead(std::string("Amount of [") + i.second + std::string("]"), ln);
amount = 0;
}
AddAction(std::make_shared<HandAction>(i.first, player, amount));
return true;
}
return false;
}
ParseStage PacificParser::ProcessSummaryLine(const std::string& ln)
{
auto isParsed =
ParseDidnotshowhand(ln)||
ParseShowHand(ln)||
ParseCollected(ln)||
ParseMucksHand(ln)||
ParseHiLo(ln);
return ParseStage::Summary;
}
bool PacificParser::ParseMucksHand(const std::string & ln)
{
std::string player;
if (!LineParserUtils::TryParse__player_action(this, ln, "mucks ", player))
return false;
CardSeq cs;
auto sIdx = ln.find_last_of('[');
if (sIdx != std::string::npos)
cs = CardSeq::FromString(ln.c_str() + sIdx);
m_summary.Add(std::make_shared<HandAction>(HandActionType::MuckHand, player, cs));
return true;
}
bool PacificParser::ParseDidnotshowhand(const std::string & ln)
{
std::string player;
if (!LineParserUtils::TryParse__player_action(this, ln, "did not show", player))
return false;
m_summary.Add(std::make_shared<HandAction>(HandActionType::MuckHand, player));
return true;
}
bool PacificParser::ParseShowHand(const std::string & ln)
{
CardSeq cards;
std::string player;
if (!LineParserUtils::TryParse__player_shows_cards_desc(this, ln, player, cards))
return false;
m_summary.Add(std::make_shared<HandAction>(HandActionType::ShowHand, player, cards));
return true;
}
bool PacificParser::ParseCollected(const std::string & ln)
{
std::string player;
int amount;
if (!LineParserUtils::TryParse__player_action_amount(this, ln, "collected", player, amount, false))
return false;
HandActionTypeFlags aType(HandActionType::Collected | HandActionType::_UncalledBetAdjust | HandActionType::_ForceUncalledBet);
m_summary.Add(std::make_shared<HandAction>(aType, player, amount));
return true;
}
bool PacificParser::ParseHiLo(const std::string & ln)
{
if (std::string::npos == ln.find("(Hi:") && std::string::npos == ln.find("(Lo:"))
return false;
auto sIdx = 1;
auto eIdx = ln.find_last_not_of(") ");
if (eIdx == std::string::npos)
ThrowFailRead("Hi/Lo Eval hint", ln);
auto show_action = m_summary.Select(HandActions::Flags_(HandActionType::ShowHand)).Last();
if (!show_action)
ThrowFailRead("Hi/Lo Eval hint Target", ln);
std::string ehint(show_action->GetCards().GetEvalHint());
if (ehint.empty())
show_action->GetCards().SetEvalHint(ln.substr(sIdx, eIdx - sIdx + 1));
else
show_action->GetCards().SetEvalHint(ehint + "; "+ ln.substr(sIdx, eIdx - sIdx + 1));
return true;
}
void PacificParser::OnHandComplete()
{
if (m_summary.Count(HandActions::Flags_(HandActionType::ShowHand)) > 0)
AddAction(std::make_shared<HandAction>(HandActionType::Street, GameStageType::Showdown, CardSeq()));
for (const auto& i : m_summary)
hh.ProcessAction(i);
AddAction(std::make_shared<HandAction>(HandActionType::Street, GameStageType::Summary, CardSeq()));
auto gs = hh.GetGameStage(GameStageType::Summary);
if (!gs)
return;
Pot& handPot = gs->GetPot();
auto ca = hh.GetActions().Select(HandActions::Flags_(HandActionType::Collected));
int total = 0;
for (const auto& i : ca)
{
total += i->GetChips();
}
if (total > handPot.GetChips())
ThrowFailRead(std::string("Total collected > Total Pot "), "");
handPot.SetRake(handPot.GetChips() - total);
}
}
}
<file_sep>/include/enumflags.hpp
#ifndef ENUM_CLASS_FLAGS_HPP
#define ENUM_CLASS_FLAGS_HPP
#include <bitset>
#include <initializer_list>
#include <numeric>
#include <utility>
#include <type_traits>
namespace a2a {
namespace EnumFlags {
template <class E> struct flags;
template <class E, class Enabler = void> struct is_flags
: public std::false_type {};
using empty_t = struct empty_t {
constexpr empty_t() noexcept {}
};
constexpr empty_t empty;
template <class E>
class FlagsIterator {
public:
using flags_type = flags<E>;
using difference_type = std::ptrdiff_t;
using value_type = E;
using pointer = value_type *;
using reference = const value_type;
using iterator_category = std::forward_iterator_tag;
constexpr FlagsIterator() noexcept : uvalue_(0), mask_(0) {}
constexpr FlagsIterator(const FlagsIterator &other) noexcept
: uvalue_(other.uvalue_), mask_(other.mask_) {}
FlagsIterator &operator++() noexcept {
nextMask();
return *this;
}
FlagsIterator operator++(int) noexcept {
auto copy = *this;
++(*this);
return copy;
}
constexpr reference operator*() const noexcept {
return static_cast<value_type>(mask_);
}
friend inline constexpr bool operator==(const FlagsIterator &i,
const FlagsIterator &j) noexcept {
return i.mask_ == j.mask_;
}
friend inline constexpr bool operator!=(const FlagsIterator &i,
const FlagsIterator &j) noexcept {
return i.mask_ != j.mask_;
}
private:
template <class E_> friend struct flags;
using impl_type = typename flags_type::impl_type;
explicit FlagsIterator(impl_type uv) noexcept : uvalue_(uv), mask_(1) {
if (!(mask_ & uvalue_)) { nextMask(); }
}
constexpr FlagsIterator(impl_type uv, E e) noexcept
: uvalue_(uv)
, mask_(static_cast<impl_type>(static_cast<impl_type>(e) & uv))
{}
void nextMask() noexcept {
do { mask_ <<= 1; } while (mask_ && !(mask_ & uvalue_));
}
impl_type uvalue_;
impl_type mask_;
};
template <class E> struct flags {
public:
static_assert(is_flags<E>::value,
"EnumFlags::flags is disallowed for this type; "
"use ENUM_FLAGS macro.");
using enum_type = typename std::decay<E>::type;
using underlying_type = typename std::underlying_type<enum_type>::type;
using impl_type = typename std::make_unsigned<underlying_type>::type;
using iterator = FlagsIterator<enum_type>;
using const_iterator = iterator;
using value_type = typename iterator::value_type;
using reference = typename iterator::reference;
using const_reference = typename iterator::reference;
using pointer = enum_type *;
using const_pointer = const enum_type *;
using size_type = std::size_t;
using difference_type = typename iterator::difference_type;
constexpr static std::size_t bit_size = sizeof(impl_type) * 8;
private:
template <class T, class Res = std::nullptr_t>
using convertible = std::enable_if<std::is_convertible<T, enum_type>::value,
Res>;
public:
flags() noexcept = default;
flags(const flags &fl) noexcept = default;
flags &operator=(const flags &fl) noexcept = default;
flags(flags &&fl) noexcept = default;
flags &operator=(flags &&fl) noexcept = default;
explicit constexpr flags(empty_t) noexcept : val_(0) {}
#ifdef ENUM_CLASS_FLAGS_FORBID_IMPLICT_CONVERSION
explicit
#endif
constexpr flags(enum_type e) noexcept
: val_(static_cast<impl_type>(e)) {}
flags &operator=(enum_type e) noexcept {
val_ = static_cast<impl_type>(e);
return *this;
}
flags(std::initializer_list<enum_type> il) noexcept : val_(0) { insert(il); }
flags &operator=(std::initializer_list<enum_type> il) noexcept {
clear();
insert(il);
return *this;
}
template <class ... Args>
flags(enum_type e, Args ... args) noexcept : flags{ e, args... } {}
template <class FwIter>
flags(FwIter b, FwIter e,
typename convertible<decltype(*b)>::type = nullptr)
noexcept(noexcept(std::declval<flags>().insert(std::declval<FwIter>(),
std::declval<FwIter>())))
: val_(0)
{
insert(b, e);
}
constexpr explicit operator bool() const noexcept { return val_!=0; }
constexpr bool operator!() const noexcept { return val_==0; }
friend constexpr bool operator==(flags fl1, flags fl2) {
return fl1.val_ == fl2.val_;
}
friend constexpr bool operator!=(flags fl1, flags fl2) {
return fl1.val_ != fl2.val_;
}
constexpr flags operator~() const noexcept { return flags(~val_); }
flags &operator|=(const flags &fl) noexcept {
val_ |= fl.val_;
return *this;
}
flags &operator&=(const flags &fl) noexcept {
val_ &= fl.val_;
return *this;
}
flags &operator^=(const flags &fl) noexcept {
val_ ^= fl.val_;
return *this;
}
flags &operator|=(enum_type e) noexcept {
val_ |= static_cast<impl_type>(e);
return *this;
}
flags &operator&=(enum_type e) noexcept {
val_ &= static_cast<impl_type>(e);
return *this;
}
flags &operator^=(enum_type e) noexcept {
val_ ^= static_cast<impl_type>(e);
return *this;
}
friend constexpr flags operator|(flags f1, flags f2) noexcept {
return flags{ f1.val_ | f2.val_ };
}
friend constexpr flags operator&(flags f1, flags f2) noexcept {
return flags{ f1.val_ & f2.val_ };
}
friend constexpr flags operator^(flags f1, flags f2) noexcept {
return flags{ f1.val_ ^ f2.val_ };
}
void swap(flags &fl) noexcept { std::swap(val_, fl.val_); }
constexpr underlying_type underlying_value() const noexcept {
return static_cast<underlying_type>(val_);
}
void set_underlying_value(underlying_type newval) noexcept {
val_ = static_cast<impl_type>(newval);
}
constexpr explicit operator std::bitset<bit_size>() const noexcept {
return to_bitset();
}
constexpr std::bitset<bit_size> to_bitset() const noexcept {
return{ val_ };
}
constexpr bool empty() const noexcept { return !val_; }
size_type size() const noexcept {
return std::distance(this->begin(), this->end());
}
constexpr size_type max_size() const noexcept { return bit_size; }
iterator begin() const noexcept { return cbegin(); }
iterator cbegin() const noexcept { return iterator{ val_ }; }
constexpr iterator end() const noexcept { return cend(); }
constexpr iterator cend() const noexcept { return{}; }
constexpr iterator find(enum_type e) const noexcept { return{ val_, e }; }
constexpr size_type count(enum_type e) const noexcept {
return find(e) != end() ? 1 : 0;
}
std::pair<iterator, iterator> equal_range(enum_type e) const noexcept {
auto i = find(e);
auto j = i;
return{ i, ++j };
}
template <class... Args>
std::pair<iterator, bool> emplace(Args && ... args) noexcept {
return insert(enum_type{ args... });
}
template <class... Args>
iterator emplace_hint(iterator, Args && ... args) noexcept {
return emplace(args...).first;
}
std::pair<iterator, bool> insert(enum_type e) noexcept {
auto i = find(e);
if (i == end()) {
i.mask_ = static_cast<impl_type>(e);
val_ |= i.mask_;
update_uvalue(i);
return{ i, true };
}
return{ i, false };
}
std::pair<iterator, bool> insert(iterator, enum_type e) noexcept {
return insert(e);
}
template <class FwIter>
auto insert(FwIter i1, FwIter i2)
noexcept(noexcept(++i1) && noexcept(*i1) && noexcept(i1 == i2))
-> typename convertible<decltype(*i1), void>::type {
val_ |= std::accumulate(i1, i2, impl_type{ 0 }, [](impl_type i, enum_type e) {
return i | static_cast<impl_type>(e);
});
}
template <class Container>
auto insert(const Container &ctn) noexcept
-> decltype(std::begin(ctn), std::end(ctn), void()) {
insert(std::begin(ctn), std::end(ctn));
}
iterator erase(iterator i) noexcept {
val_ ^= i.mask_;
update_uvalue(i);
return ++i;
}
size_type erase(enum_type e) noexcept {
auto e_count = count(e);
val_ ^= static_cast<impl_type>(e);
return e_count;
}
iterator erase(iterator i1, iterator i2) noexcept {
val_ ^= flags(i1, i2).val_;
update_uvalue(i2);
return ++i2;
}
void clear() noexcept { val_ = 0; }
private:
constexpr explicit flags(impl_type val) noexcept : val_(val) {}
void update_uvalue(iterator &it) const noexcept { it.uvalue_ = val_; }
impl_type val_;
};
template <class E>
void swap(flags<E> &fl1, flags<E> &fl2) noexcept { fl1.swap(fl2); }
}
} // namespace EnumFlags
template <class E>
constexpr auto operator|(E e1, E e2) noexcept
-> typename std::enable_if<a2a::EnumFlags::is_flags<E>::value,
a2a::EnumFlags::flags<E>>::type {
return a2a::EnumFlags::flags<E>(e1) | e2;
}
template <class E>
constexpr auto operator&(E e1, E e2) noexcept
-> typename std::enable_if<a2a::EnumFlags::is_flags<E>::value,
a2a::EnumFlags::flags<E>>::type {
return a2a::EnumFlags::flags<E>(e1) & e2;
}
template <class E>
constexpr auto operator^(E e1, E e2) noexcept
-> typename std::enable_if<a2a::EnumFlags::is_flags<E>::value,
a2a::EnumFlags::flags<E>>::type {
return a2a::EnumFlags::flags<E>(e1) ^ e2;
}
#define ENUM_FLAGS(name) namespace EnumFlags {template <> struct is_flags< name > : std::true_type {};}
#endif // ENUM_CLASS_FLAGS_HPP
<file_sep>/src/cardseq.cxx
#include <cassert>
#include <stdexcept>
#include <algorithm>
#include <sstream>
#include "cardseq.hpp"
#include "strutils.hpp"
#include "stdutils.hpp"
namespace a2a
{
CardSeq::CardSeq(const char* s) : m_hiddenCards(0)
{
FromString(s, *this);
}
int CardSeq::FromString(const char * s, CardSeq & cs)
{
int ret = 0; cs.Clear();
Card c; int p = 0;
while (true)
{
int i = Card::ReadFromString(s+p, c);
if (i == 0)
return ret;
cs.Add(c); p += i; ret++;
}
}
CardSeq CardSeq::FromString(const char * s)
{
CardSeq ret;
int num = CardSeq::FromString(s, ret);
if (num == 0)
throw std::runtime_error("CardSeq::FromString Failed to read string: " + (s ? std::string(s) : std::string("NULL")));
return ret;
}
CardSeq CardSeq::FromString(const std::string & s)
{
return CardSeq::FromString(s.c_str());
}
std::string CardSeq::ToString() const
{
std::string ret;
std::for_each(m_seq.cbegin(), m_seq.cend(), [&ret](const Card&c) {ret += c.ToString(); });
return ret;
}
std::string CardSeq::ToString(const std::string& format) const
{
std::stringstream ss;
ToStream(ss, format);
return ss.str();
}
bool CardSeq::Has(const Card & c) const
{
return std::find(m_seq.cbegin(), m_seq.cend(), c) != m_seq.cend();
}
bool CardSeq::Add(const Card & c)
{
if (Has(c))
return false;
m_seq.push_back(c);
return true;
}
int CardSeq::Add(const CardSeq & cs)
{
int ret = 0;
for (auto const& c : cs.m_seq)
if (!Has(c))
{
Add(c); ret++;
}
return ret;
}
void CardSeq::Reset(const CardSeq & cs)
{
Stash();
m_seq = cs.m_seq;
}
void CardSeq::Stash()
{
for (auto const& c : m_seq)
if (std::find(m_stash.cbegin(), m_stash.cend(), c) == m_stash.cend())
m_stash.push_back(c);
}
void CardSeq::Clear()
{
m_stash.clear();
m_seq.clear();
}
void CardSeq::Clear(const CardSeq & cs)
{
Stash();
StdUtils::erase_if(m_seq, [&cs](const Card& i) -> bool {
return std::find(cs.m_seq.cbegin(), cs.m_seq.cend(), i) != cs.m_seq.cend();
});
}
std::ostream& CardSeq::ToStream(std::ostream & os, const std::string & format) const
{
auto it = m_seq.begin();
const char* s = format.c_str(); int i = 0;
while (true)
{
char ch = s[i++];
if (!ch) return os;
if (ch != '%')
{
os << ch; continue;
}
char chn = s[i];
if (chn == 'x')
{
if (it != m_seq.end())
{
os << *(it++);
}
i++;
}
else if (chn == 'X')
{
while (it != m_seq.end())
{
os << *(it++);
}
i++;
}
else if (chn == 'S')
{
while (it != m_seq.end())
{
os << *(it++);
if (it != m_seq.end())
os << ' ';
}
i++;
}
}
}
std::ostream & operator<<(std::ostream & os, const CardSeq & c)
{
std::for_each(c.m_seq.cbegin(), c.m_seq.cend(), [&os](const Card&c) {os << c; });
return os;
}
}
<file_sep>/include/config.h
#ifndef INCLUDE_CONFIG_HPP
#define INCLUDE_CONFIG_HPP
#if defined(_WIN32)
#define A2AHHC_API __declspec(dllexport)
#endif
#if !defined(A2AHHC_API)
#if defined (__GNUC__) && (__GNUC__ >= 4)
#define A2AHHC_API __attribute__ ((visibility ("default")))
#else
#define A2AHHC_API
#endif
#endif
#endif
<file_sep>/include/types.hpp
#ifndef INCLUDE_TYPES_H
#define INCLUDE_TYPES_H
#include <cstdint>
#include <cstddef>
namespace a2a
{
using u8 = std::uint8_t;
using u64 = std::uint64_t;
using u32 = std::uint32_t;
using i32 = std::int32_t;
using i64 = std::int64_t;
}
#endif<file_sep>/src/gamesite.cxx
#include "gamesite.hpp"
#include "strutils.hpp"
namespace a2a
{
namespace GameSiteUtils
{
static const char* const SiteNames[] =
{
"Unknown",
"PartyPoker",
"FullTilt",
"PokerStars",
"Prima",
"IPoker",
"Absolute",
"Cryptologic",
"Bodog",
"UltimateBet",
"Ongame",
"Everest",
"Unknown",
"Pacific",
"Unknown",
"Betfair",
"Dracula",
"Entraction",
"CakePoker",
"BossMedia",
"Merge",
"PokerRoom",
"EverLeaf",
"Winamax",
"Cereus",
"MicroGaming",
"Ladbrokes",
"DollaroPoker",
"WinningPoker",
"IPoker2",
"Lotos",
"PartyPokerFr",
"PartyPokerIt",
"PartyPokerNJ",
"PartyPokerEs",
"PokerStarsFr",
"PokerStarsIt",
"PokerStarsEs",
"OnGameIt",
"OnGameFr",
"IPokerIt",
"IPokerFr",
};
const char* GameSiteToString(GameSite gameSite)
{
return
gameSite == GameSite::Any ? "Unknown" : SiteNames[static_cast<std::underlying_type<GameSite>::type>(gameSite)];
}
#ifdef _MSC_VER
#pragma warning (disable: 4307)
#endif
static GameSite FindDefaultSite(const std::string& siteName)
{
using namespace StrUtils;
for (std::size_t i = 0; i < sizeof(SiteNames) / sizeof(const char*); ++i)
{
std::string s(to_lower_ansi(SiteNames[i]));
if (s.compare(0, siteName.size(), to_lower_ansi(siteName.c_str())) == 0)
return static_cast<GameSite>(i);
}
return GameSite::Unknown;
}
GameSite GameSiteFromString(const std::string& siteName)
{
using namespace StrUtils;
using namespace StrUtils::literals;
switch (str_hash(to_lower_ansi(siteName)))
{
case "ps"_hash:
case "pokerstars"_hash:
case "stars"_hash:
case "strs"_hash:
return GameSite::PokerStars;
case "pacific"_hash:
case "888"_hash:
case "pac"_hash:
return GameSite::Pacific;
case "lotos"_hash:
return GameSite::Lotos;
//case "pac"_hash:
//return GameSite::Pacific;
default:
return FindDefaultSite(siteName);
}
}
#ifdef _MSC_VER
#pragma warning (default: 4307)
#endif
}
}
<file_sep>/src/luastate.cxx
#include <cassert>
#include "luastate.hpp"
#include "fsysutils.hpp"
namespace a2a
{
LuaState::LuaState() : L(nullptr)
{
}
LuaState::~LuaState()
{
if (L != nullptr)
lua_close(L);
}
lua_State* LuaState::luaState()
{
if (L == nullptr)
{
L = luaL_newstate();
lua_atpanic(L, LuaPanic);
luaL_openlibs(L);
}
return L;
}
void LuaState::RunScript(const std::string& code)
{
if (luaL_dostring(luaState(), code.c_str()))
lua_error(luaState());
}
void LuaState::RunFile(const std::string& filename)
{
if (luaL_dofile(luaState(), filename.c_str()))
lua_error(luaState());
}
void LuaState::RunBuffer(const char * p, std::size_t sz, std::string& err, const std::string& chunk)
{
err.clear();
if (luaL_loadbuffer(luaState(), p, sz, chunk.c_str()))
{
err.assign(lua_tostring(L, -1));
lua_pop(L, 1);
return;
}
if (lua_pcall(L, 0, 0, 0) != 0)
{
err.assign(lua_tostring(L, -1));
lua_pop(L, 1);
}
}
int LuaState::LuaPanic(lua_State* L)
{
const char* message = lua_tostring(L, -1);
std::string err = message ? message : "A2A LUA Panic: Unexpected error!";
throw LuaError(err);
}
void LuaState::LoadHHSubmodule()
{
auto s = _searchPath("addons/", 4) + "a2ahh.lua";
RunFile(s);
}
void LuaState::LoadParsersSubmodule()
{
auto s = _searchPath("addons/", 4);
//auto s = _searchPath("addons/", 4) + "a2ahhparsers.lua";
RunFile(s + "class.lua");
RunFile(s + "a2ahhparsers.lua");
}
void LuaState::LoadSubmodule(LuaSubmodule sm)
{
if (m_loadedSubMods.find(sm) != m_loadedSubMods.end())
return;
switch (sm)
{
case LuaSubmodule::handhistory:
LoadHHSubmodule();
break;
case LuaSubmodule::parsers:
LoadSubmodule(LuaSubmodule::handhistory);
LoadParsersSubmodule();
break;
case LuaSubmodule::all:
LoadSubmodule(LuaSubmodule::handhistory);
LoadSubmodule(LuaSubmodule::parsers);
break;
default:
break;
}
m_loadedSubMods[sm] = true;
}
LuaAddonsVec & LuaState::GetAddons(const std::string & manifest)
{
assert(m_addons.find(manifest) != m_addons.end() && "Lua addons not found");
return m_addons[manifest];
}
void LuaState::UploadAddons(const std::string & manifest, const LuaAddonsVec & addons)
{
m_addons[manifest] = addons;
}
void LuaState::DbgStackDump()
{
lua_State* l = luaState();
int i;
int top = lua_gettop(l);
printf("on stack %d\n", top);
for (i = 1; i <= top; i++)
{
int t = lua_type(l, i);
switch (t) {
case LUA_TSTRING:
printf("string: '%s'\n", lua_tostring(l, i));
break;
case LUA_TBOOLEAN:
printf("boolean %s\n", lua_toboolean(l, i) ? "true" : "false");
break;
case LUA_TNUMBER:
printf("number: %g\n", lua_tonumber(l, i));
break;
default:
printf("%s\n", lua_typename(l, t));
break;
}
printf(" ");
}
printf("\n");
}
LuaState& LuaState::Global()
{
static LuaState state;
return state;
}
}
<file_sep>/addons/parsers/parser1.lua
A2ALineParser "TestParser"
function TestParser:HandStart()
return "43434"
end
function TestParser:ProcessLine(ln)
print(ln)
return 1
end
function TestParser:OnHandComplete()
-- print("[hand on complete]")
end
<file_sep>/include/sitesdata.hpp
#ifndef INCLUDE_SITESDATA_HPP
#define INCLUDE_SITESDATA_HPP
#include <string>
#include <map>
#include "cardgame.hpp"
#include "handaction.hpp"
#include "gamesite.hpp"
#include "gamestage.hpp"
namespace a2a
{
namespace detail
{
using action_strs_t = std::map<HandActionType, const std::string>;
using streets_strs_t = std::map<const std::string, GameStageType>;
}
namespace PokerStars
{
using detail::action_strs_t;
using detail::streets_strs_t;
extern CardGameTypeFlags ParseGame(const std::string&, std::size_t&);
extern CardGameTypeFlags ParseBetType(const std::string&, std::size_t&);
extern CardGameTypeFlags ParseMixGameType(const std::string&, std::size_t&);
extern const std::string& GameToStr(CardGameType);
extern const std::string& BetTypeToStr(CardGameType);
extern const std::string& MixGameToStr(CardGameType);
const action_strs_t BlindsActionsStrings =
{
{ HandActionType::SmallBlind, "posts small blind" },
{ HandActionType::BigBlind, "posts big blind" },
{ HandActionType::SmallAndBigBlind, "posts small & big blinds" },
{ HandActionType::Ante, "posts the ante" },
};
const action_strs_t ActionsStrings =
{
{ HandActionType::Fold, "folds" },
{ HandActionType::Check, "checks" },
{ HandActionType::Call, "calls" },
{ HandActionType::Bet, "bets" },
{ HandActionType::Raise, "raises" },
{ HandActionType::BringIn, "brings in for" },
};
const streets_strs_t StreetStrings =
{
{ "*** SU", GameStageType::Summary },
{ "*** SH", GameStageType::Showdown },
{ "*** FIRST S", GameStageType::Showdown },
{ "*** SECOND S", GameStageType::Showdown_2nd },
{ "*** R", GameStageType::River },
{ "*** FIRST R", GameStageType::River },
{ "*** SECOND R", GameStageType::River_2nd },
{ "*** TU", GameStageType::Turn },
{ "*** FIRST T", GameStageType::Turn },
{ "*** SECOND T", GameStageType::Turn_2nd },
{ "*** FL", GameStageType::Flop },
{ "*** FIRST F", GameStageType::Flop },
{ "*** SECOND F", GameStageType::Flop_2nd },
{ "*** H", GameStageType::Preflop },
{ "*** 3", GameStageType::_3rdStreet },
{ "*** 4", GameStageType::_4thStreet },
{ "*** 5", GameStageType::_5thStreet },
{ "*** 6", GameStageType::_6thStreet },
{ "*** D", GameStageType::_DrawHands},
{ "*** FIRST D", GameStageType::_1stDraw },
{ "*** SECOND D", GameStageType::_2ndDraw },
{ "*** THIRD D", GameStageType::_3rdDraw },
};
const action_strs_t InfoActionStrings =
{
{ HandActionType::DeckReshuffle, "The deck is reshuffled" },
{ HandActionType::BettingCapped, "Betting is capped" },
{ HandActionType::PairOnBoard, "Pair on board - a double bet is allowed" },
};
}
namespace Pacific
{
using detail::action_strs_t;
using detail::streets_strs_t;
const action_strs_t BlindsActionsStrings =
{
{ HandActionType::SmallBlind, "posts small blind" },
{ HandActionType::BigBlind, "posts big blind" },
{ HandActionType::Ante, "posts ante" },
//{ HandActionType::SmallAndBigBlind, "posts dead blind" },
};
const streets_strs_t StreetStrings =
{
{ "ry **", GameStageType::Summary },
{ "river **", GameStageType::River },
{ "turn **", GameStageType::Turn },
{ "flop **", GameStageType::Flop },
{ "cards **", GameStageType::Preflop },
};
const action_strs_t ActionsStrings =
{
{ HandActionType::Fold, "folds" },
{ HandActionType::Check, "checks" },
{ HandActionType::Call, "calls" },
{ HandActionType::Bet, "bets" },
{ HandActionType::Raise, "raises" },
};
}
}
#endif<file_sep>/tests/hhproc.cpp
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <array>
#include <deque>
#include <forward_list>
#include <list>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <memory>
#include <chrono>
#include <ctime>
#include <stack>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <chrono>
#include <thread>
#include <cassert>
#include <atomic>
#include <future>
#include <mutex>
#include <vector>
//#define private public
#ifdef _MSC_VER
#pragma warning (disable: 4996)
#endif
#include "fsysutils.hpp"
#include "filescol.hpp"
#include "hhparsers.hpp"
#include "hhparser_ps.hpp"
#include "mempool.hpp"
#include "hhfilesreader.hpp"
#include "hhreader.hpp"
using namespace a2a;
void dump(const std::string& fn, char* data, std::size_t size)
{
std::ofstream out(fn, std::ios::binary | std::ios::out);
if (!out.is_open())
return;
out.write(data, size);
out.close();
}
TEST_CASE("Mempool Tests 3")
{
using namespace a2a;
static const std::size_t BUFF_SIZE = 4 * 1048576;
static const std::size_t TH_NUM = std::thread::hardware_concurrency();
MemoryPool srcBufferPool(1 * 1048576, TH_NUM);
std::vector<std::future<void>> futures;
std::atomic<int> total (0);
auto parsers = std::make_shared<HandHistoryParsersFactory>();
// parsers->LoadCoreParsers();
#ifdef _MSC_VER
//auto dir = Directory::Open("D:\\projects\\SampleHandHistories\\PokerStars", true);
auto dir = Directory::Open("D:\\projects\\SampleHandHistories", true);
#else
auto dir = Directory::Open("/media/sf_projects/SampleHandHistories", true);
#endif
//FilesCollection files;
auto start = std::chrono::steady_clock::now();
while (dir->HasFilesToProcess())
{
//dir->GetFiles(files, BUFF_SIZE/2);
const auto run = [&srcBufferPool, &total](FilesCollection _files)
{
HandHistoryParsersFactory parsers;
HandHistoryFilesReader cs(parsers, _files);
for (;;)
{
std::unique_ptr<MemoryPool::Buffer> buff( srcBufferPool.GetBuffer() );
buff->Resize(cs.Read(buff->Data(), buff->Size()));
if (buff->Size() == 0)
return;
HandHistoryReader ph(cs.GetParser(), buff->Data(), buff->Size());
//std::cout << std::this_thread::get_id() << std::endl;
while (ph.Next())
{
HandHistory hh;
try
{
ph.Parse(hh);
// if (131612340948 == hh.GetHandId())
//std::cout << hh.GetHandId() << std::endl;
}
catch (const std::exception& err)
{
// std::cout << "ID:" << hh.GetHandId() << " ERRROR: " << err.what() << std::endl
// << "***********************************************" << std::endl;
}
}
total += ph.GetTotalParsed();
}
};
//while (HHMemPool::Buffer* buff = cs.Read(srcBufferPool))
//{
futures.emplace_back(std::async(
std::launch::async,
run, dir->GetFilesMinTotalSize(BUFF_SIZE / 2)
));
if (futures.size() >=TH_NUM)
{
for (auto& e : futures) {
e.wait();
}
futures.clear();
}
//
//run(buff);
//}
//files.Clear();
}
for (auto& e : futures) {
e.wait();
}
auto end = std::chrono::steady_clock::now();
std::cout << "TIME: " << std::chrono::duration <double, std::milli>(end - start).count() << std::endl;
std::cout << "TOTAL HANDS: " << total << std::endl;
}
/*class HHMemPool final
{
public:
using chunk_t = std::vector<char>;
using lock_t = std::unique_lock<std::mutex>;
HHMemPool(std::size_t bufferSize, std::size_t buffersCount) : m_abStop(false)
{
lock_t lock(m_mutex);
m_pool.reserve(buffersCount);
for (std::size_t i = 0; i < buffersCount; ++i)
{
m_pool.emplace_back(bufferSize);
m_readyChunks.push(i);
}
}
~HHMemPool()
{
{
lock_t lock(m_mutex);
m_abStop = true;
}
m_condReady.notify_all();
}
class Buffer final
{
public:
using releaser_t = std::function<void(void)>;
Buffer(char* data, std::size_t size, const HandHistoryParser::Ptr& parser, const releaser_t& onRelease) :
m_data(data), m_size(size), m_fOnRelease(onRelease), m_parser(parser)
{}
~Buffer()
{
m_fOnRelease();
}
char* Data() const { return m_data; }
std::size_t Size() const { return m_size; }
void Resize(std::size_t newSize) { m_size = newSize; }
const HandHistoryParser::Ptr& Parser() const { return m_parser; }
Buffer(const Buffer&) = delete;
Buffer& operator=(const Buffer&) = delete;
private:
char* m_data;
std::size_t m_size;
releaser_t m_fOnRelease;
HandHistoryParser::Ptr m_parser;
};
Buffer* GetBuffer(const HandHistoryParser::Ptr& parser)
{
while(true)
{
lock_t lock(m_mutex);
if (!m_abStop && m_readyChunks.empty())
{
m_condReady.wait(lock);
}
if (m_abStop)
return nullptr;
if (!m_readyChunks.empty())
{
auto i = m_readyChunks.top();
m_readyChunks.pop();
auto& page = m_pool[i];
return new Buffer (
page.data(),
page.size(),
parser,
[this, &page, i]()
{
lock_t lock(m_mutex);
m_readyChunks.push(i);
m_condReady.notify_one();
}
);
}
}
}
private:
std::atomic<bool> m_abStop;
mutable std::mutex m_mutex;
std::condition_variable m_condReady;
std::stack<std::size_t> m_readyChunks;
std::vector<chunk_t> m_pool;
};
class HHFilesCollectionSorter
{
public:
using parser_t = HandHistoryParser::Ptr;
using factory_t = HandHistoryParsersFactory::Ptr;
using files_t = FilesCollection;
using reader_t = FilesCollectionReader;
using dict_t = std::unordered_map<parser_t, reader_t::Ptr>;
static const std::size_t TEST_BLOCK_SIZE = 512;
HHFilesCollectionSorter(const factory_t& factory, files_t& files, std::size_t testBlockSize = TEST_BLOCK_SIZE):
m_factory(factory)
{
files.Visit(files_t::MakeCache_(TEST_BLOCK_SIZE));
for (const auto& obj : m_factory->GetMetaCollection())
{
auto parser = m_factory->GetParser(obj->Name());
auto sfiles = files.Cut(files_t::HasHands_(parser, TEST_BLOCK_SIZE));
if (sfiles.Size() > 0)
m_map[parser] = std::make_shared<reader_t>(sfiles);
}
files.Visit(files_t::ClearCache_());
m_current = m_map.begin();
}
HHMemPool::Buffer* Read(HHMemPool& memPool)
{
while (m_current != m_map.end())
{
std::unique_ptr<HHMemPool::Buffer> buff(memPool.GetBuffer(m_current->first));
std::size_t buff_size = buff->Size();
std::size_t tail_size = m_tail.size();
if (tail_size > 0)
{
if (tail_size > buff_size)
throw std::runtime_error("[HHMemPool::Buffer Read] MemPool Buffer overflow.");
std::memcpy(buff->Data(), &m_tail[0], tail_size);
buff_size -= tail_size;
m_tail.clear();
}
if (buff_size == 0)
return buff.release();
std::size_t readSize = m_current->second->Read(buff->Data()+tail_size, buff_size);
buff->Resize(readSize + tail_size);
if (buff->Size() == 0)
{
m_current++;
continue;
}
else if (readSize == 0 && tail_size > 0)
{
m_current++;
return buff.release();
}
if (readSize == buff_size)
{
const char* end = buff->Data() + buff->Size();
const char* lastHand = m_current->first->Last(buff->Data(), end);
if (lastHand > buff->Data() && readSize == buff_size)
{
buff->Resize(lastHand - buff->Data());
m_tail.assign(lastHand, end);
}
}
return buff.release();
}
return nullptr;
}
private:
factory_t m_factory;
dict_t m_map;
dict_t::iterator m_current;
std::string m_tail;
};*/
class HHProcessor
{
};
//TEST_CASE("Mempool Tests 1")
//{
// using namespace a2a;
//
// static const std::size_t BUFF_SIZE = 4 * 1048576;
// static const std::size_t TH_NUM = std::thread::hardware_concurrency();
//
// HHMemPool srcBufferPool(4*1048576, TH_NUM);
//
// std::vector<std::future<void>> futures;
// std::atomic<int> total = 0;
// const auto run = [&futures, &total](HHMemPool::Buffer* _buffer)
// {
// std::unique_ptr<HHMemPool::Buffer> buff(_buffer);
// HandHistoryParseHelper ph(buff->Parser(), buff->Data(), buff->Size());
// //std::cout << std::this_thread::get_id() << std::endl;
// while (ph.Next())
// {
// HandHistory hh;
// try
// {
// ph.Parse(hh);
// // if (131612340948 == hh.GetHandId())
// //std::cout << hh.GetHandId() << std::endl;
// }
// catch (const std::exception& err)
// {
// //std::cout << "ID:" << hh.GetHandId() << " ERRROR: " << err.what() << std::endl
// //<< "***********************************************" << std::endl;
// }
// }
// total += ph.TotalParsed();
// };
//
// auto parsers = std::make_shared<HandHistoryParsersFactory>();
// parsers->LoadCoreParsers();
//
//
// #ifdef _MSC_VER
// auto dir = Directory::Open("D:\\libs\\SampleHandHistories\\PokerStars", true);
// //auto dir = Directory::Open(_searchPath("tests/hh/ps/bugs", 4), true);
//
// #else
// auto dir = Directory::Open("/home/dmitry/SampleHandHistories/PokerStars", true);
// #endif
// FilesCollection files;
// auto start = std::chrono::steady_clock::now();
// while (dir->HasFilesToProcess())
// {
// dir->GetFiles(files, BUFF_SIZE/2);
// HHFilesCollectionSorter cs(parsers, files);
//
// while (HHMemPool::Buffer* buff = cs.Read(srcBufferPool))
// {
//
// futures.emplace_back(std::async(
// std::launch::async,
// run, buff
// ));
//
// if (futures.size() >= TH_NUM)
// {
//
// for (auto& e : futures) {
// e.wait();
// }
// futures.clear();
// }
//
// //
//
// //run(buff);
// }
// for (auto& e : futures) {
// e.wait();
// }
//
// files.Clear();
// }
// auto end = std::chrono::steady_clock::now();
//
// std::cout << "TIME: " << std::chrono::duration <double, std::milli>(end-start).count() << std::endl;
// std::cout << "TOTAL HANDS: " << total << std::endl;
//}
//
//TEST_CASE("Mempool Tests 2")
//{
// using namespace a2a;
//
// static const std::size_t BUFF_SIZE = 4 * 1048576;
// static const std::size_t TH_NUM = std::thread::hardware_concurrency();
//
// HHMemPool srcBufferPool(4 * 1048576, 12);
// std::vector<std::future<void>> futures;
// std::atomic<int> total = 0;
//
//
// auto parsers = std::make_shared<HandHistoryParsersFactory>();
// parsers->LoadCoreParsers();
//
//
//#ifdef _MSC_VER
// auto dir = Directory::Open("D:\\libs\\SampleHandHistories\\PokerStars", true);
// //auto dir = Directory::Open(_searchPath("tests/hh/ps/bugs", 4), true);
//
//#else
// auto dir = Directory::Open("/home/dmitry/SampleHandHistories/PokerStars", true);
//#endif
// //FilesCollection files;
// auto start = std::chrono::steady_clock::now();
//
// while (dir->HasFilesToProcess())
// {
// //dir->GetFiles(files, BUFF_SIZE/2);
//
// const auto run = [&parsers, &srcBufferPool, &total](FilesCollection _files)
// {
// HHFilesCollectionSorter cs(parsers, _files);
//
// for (;;)
// {
// auto pbuff = cs.Read(srcBufferPool);
// if (!pbuff)
// return;
// std::unique_ptr<HHMemPool::Buffer> buff(pbuff);
//
// //if (!buff)
// //return;
// HandHistoryParseHelper ph(buff->Parser(), buff->Data(), buff->Size());
// //std::cout << std::this_thread::get_id() << std::endl;
// while (ph.Next())
// {
// HandHistory hh;
// try
// {
// ph.Parse(hh);
// // if (131612340948 == hh.GetHandId())
// //std::cout << hh.GetHandId() << std::endl;
// }
// catch (const std::exception& err)
// {
// //std::cout << "ID:" << hh.GetHandId() << " ERRROR: " << err.what() << std::endl
// //<< "***********************************************" << std::endl;
// }
// }
// total += ph.TotalParsed();
// }
// };
//
// //while (HHMemPool::Buffer* buff = cs.Read(srcBufferPool))
// //{
//
// futures.emplace_back(std::async(
// std::launch::async,
// run, dir->GetFilesMinTotalSize(BUFF_SIZE / 2)
// ));
//
// if (futures.size() >=TH_NUM)
// {
//
// for (auto& e : futures) {
// e.wait();
// }
// futures.clear();
// }
//
// //
//
// //run(buff);
// //}
//
// //files.Clear();
// }
// for (auto& e : futures) {
// e.wait();
// }
//
// auto end = std::chrono::steady_clock::now();
//
// std::cout << "TIME: " << std::chrono::duration <double, std::milli>(end - start).count() << std::endl;
// std::cout << "TOTAL HANDS: " << total << std::endl;
//}
//TEST_CASE("Hand proc Tests")
//{
// using namespace a2a;
//
// auto parsers = std::make_shared<HandHistoryParsersFactory>();
// parsers->LoadCoreParsers();
//
// PokerStars::HHParserSettings psets;
// auto pp = parsers->GetParserBySite("ps", psets);
//
//
// auto s = _searchPath("tests/hh/ps/bugs", 4);
// REQUIRE_FALSE(s.empty());
// auto dir = Directory::Open(s, true);
// FilesCollection files;
//
//
//
// std::string buff; buff.reserve(4096);
// while (dir->HasFilesToProcess())
// {
// dir->GetFiles(files, 2);
// HHFilesCollectionSorter cs(parsers, files);
// //auto sfiles = files.Cut(FilesCollection::HasHands_(pp));
// //FilesCollectionReader fcr(sfiles);
// /*
// buff.resize(4096);
// while (std::size_t rsz = fcr.Read(&buff[0], 4096))
// {
// buff.resize(rsz);
// std::cout << buff << std::endl;
// }*/
// files.Clear();
// }
//
//}
//
//TEST_CASE("Hand proc Tests")
//{
// using namespace a2a;
//
// auto parsers = HandHistoryParsersFactory();
//
// PokerStars::HHParserSettings psets;
// auto pp = parsers.GetParserBySite("ps", psets);
//
//#ifdef _MSC_VER
// auto dir = Directory::Open("D:\\libs\\SampleHandHistories\\PokerStars", true);
//#else
// auto dir = Directory::Open("/home/dmitry/SampleHandHistories/PokerStars", true);
//#endif
// FilesCollection files;
// while (dir->HasFilesToProcess())
// {
// dir->GetFiles(files, 6);
//
// HandHistory hh;
// std::string buff;
// for (const auto& f : files)
// {
//
// std::cout << ">" << f->GetFullPath() << std::endl;
// f->Read(buff);
// HandHistoryParseHelper hp(pp, buff);
//
// auto lh = hp.Last();
//
// while (hp.Next())
// {
// HandHistory hh;
// try
// {
//
// hp.Parse(hh);
// }
// catch (const std::exception& err)
// {
// std::cout << "ID:" << hh.GetHandId() << " ERRROR: " << err.what() << std::endl
// << "***********************************************" << std::endl;
// }
// }
// std::cout << "ok" << std::endl << std::endl;
// }
//
// files.Clear();
// }
//
//}
#ifdef _MSC_VER
#pragma warning (default: 4996)
#endif
<file_sep>/include/hhreader.hpp
#ifndef INCLUDE_HHREADER_HPP
#define INCLUDE_HHREADER_HPP
#include "types.hpp"
#include "hhparsers.hpp"
namespace a2a
{
/// todo: fix interface [ template iter begin, inter end ], [ template container ], [ init list ]
class HandHistoryReader final
{
public:
HandHistoryReader() = delete;
HandHistoryReader(const HandHistoryReader&) = delete;
HandHistoryReader& operator=(const HandHistoryReader&) = delete;
HandHistoryReader(const std::string&);
HandHistoryReader(const void* mem, std::size_t);
HandHistoryReader(const HandHistoryParser::Ptr& parser, const std::string&);
HandHistoryReader(const HandHistoryParser::Ptr& parser, const void* mem, std::size_t);
HandHistoryReader(HandHistoryParsersFactory& parsers, const std::string&);
HandHistoryReader(HandHistoryParsersFactory& parsers, const void* mem, std::size_t);
bool Next();
const char* Last();
void Parse(HandHistory& hh);
HandHistory Parse();
void Reset();
std::size_t GetTotalParsed() const;
const HandHistoryParser::Ptr& GetParser() const;
private:
HandHistoryParser::Ptr m_parser;
const char* m_beg;
const char* m_cursor;
const char* m_end;
std::size_t m_total;
void FindParser(HandHistoryParsersFactory& factory);
};
}
//
// inlines
//
namespace a2a
{
inline std::size_t HandHistoryReader::GetTotalParsed() const
{
return m_total;
}
inline const HandHistoryParser::Ptr& HandHistoryReader::GetParser() const
{
return m_parser;
}
}
#endif<file_sep>/src/mempool.cxx
#include "mempool.hpp"
namespace a2a
{
MemoryPool::MemoryPool(std::size_t bufferSize, std::size_t buffersCount) : m_abStop(false)
{
lock_t lock(m_mutex);
m_pool.reserve(buffersCount);
for (std::size_t i = 0; i < buffersCount; ++i)
{
m_pool.emplace_back(bufferSize);
m_readyChunks.push(i);
}
}
MemoryPool::~MemoryPool()
{
{
lock_t lock(m_mutex);
m_abStop = true;
}
m_condReady.notify_all();
}
MemoryPool::Buffer * MemoryPool::GetBuffer()
{
while (true)
{
lock_t lock(m_mutex);
if (!m_abStop && m_readyChunks.empty())
{
m_condReady.wait(lock);
}
if (m_abStop)
return nullptr;
if (!m_readyChunks.empty())
{
auto i = m_readyChunks.top();
m_readyChunks.pop();
auto& page = m_pool[i];
return new Buffer(
page.data(),
page.size(),
[this, &page, i]()
{
lock_t lock(m_mutex);
m_readyChunks.push(i);
m_condReady.notify_one();
});
}
}
}
//------------------------------------------------------------------------ Buffer
MemoryPool::Buffer::Buffer(char* data, std::size_t size, const releaser_t& onRelease) :
m_data(data), m_size(size), m_fOnRelease(onRelease)
{
}
MemoryPool::Buffer::~Buffer()
{
m_fOnRelease();
}
}
<file_sep>/include/handactiontype.hpp
#ifndef INCLUDE_HANDACTIONTYPE_HPP
#define INCLUDE_HANDACTIONTYPE_HPP
#include <memory>
#include <limits>
#include <unordered_map>
#include "types.hpp"
#include "enumflags.hpp"
namespace a2a
{
#ifdef _MSC_VER
#undef min
#undef max
#endif
enum class HandActionType : u32
{
Unknown = 0,
SmallBlind = 1 << 0,
BigBlind = 1 << 1,
SmallAndBigBlind = 1 << 2,
Ante = 1 << 3,
Return = 1 << 4,
Fold = 1 << 5,
Check = 1 << 6,
Call = 1 << 7,
BringIn = 1 << 8,
Bet = 1 << 9,
Raise = 1 << 10,
Collected = 1 << 11,
MuckHand = 1 << 12,
ShowHand = 1 << 13,
AllIn = 1 << 16,
Cap = 1 << 17,
Street = 1 << 18,
CardsDealt = 1 << 20,
CardsDiscard = 1 << 21,
DeckReshuffle = 1 << 22,
BettingCapped = 1 << 23,
PairOnBoard = 1 << 24,
_ForceUncalledBet = 1 << 27,
_RaiseUpAdjust = 1 << 28,
_UncalledBetAdjust = 1 << 29,
_Hidden = 1 << 30,
Any = std::numeric_limits<std::underlying_type<HandActionType>::type>::max()
};
ENUM_FLAGS(HandActionType);
using HandActionTypeFlags = EnumFlags::flags<HandActionType>;
namespace HandActionUtils
{
using TStrMap = std::unordered_map<HandActionType, const std::string>;
inline constexpr HandActionTypeFlags NotAnte()
{
return ~HandActionTypeFlags(HandActionType::Ante);
}
inline constexpr HandActionTypeFlags AnyBetRaise()
{
return
HandActionType::Bet |
HandActionType::Raise |
HandActionType::BringIn;
}
inline HandActionType GetBetRaise(const HandActionTypeFlags& actionType)
{
return static_cast<HandActionType> ((actionType & AnyBetRaise()).underlying_value());
}
inline bool IsAnyBetRaise(const HandActionTypeFlags& actionType)
{
return (bool)(actionType & AnyBetRaise());
}
inline constexpr HandActionTypeFlags AnyBlindAction()
{
return
HandActionType::SmallBlind |
HandActionType::BigBlind |
HandActionType::SmallAndBigBlind |
HandActionType::Ante;
}
inline HandActionType GetBlindAction(const HandActionTypeFlags& actionType)
{
return static_cast<HandActionType> ( (actionType & AnyBlindAction()).underlying_value() );
}
inline bool IsAnyBlindAction(const HandActionTypeFlags& actionType)
{
return (bool)(actionType & AnyBlindAction());
}
inline constexpr HandActionTypeFlags AnyGameAction()
{
return
HandActionType::Return |
HandActionType::Fold |
HandActionType::Check |
HandActionType::Call |
HandActionType::BringIn |
HandActionType::Bet |
HandActionType::Raise;
}
inline HandActionType GetGameAction(const HandActionTypeFlags& actionType)
{
return static_cast<HandActionType> ((actionType & AnyGameAction()).underlying_value());
}
inline bool IsAnyGameAction(const HandActionTypeFlags& actionType)
{
return (bool)(actionType & AnyGameAction());
}
inline constexpr HandActionTypeFlags AnyCardsAction()
{
return
HandActionType::CardsDealt |
HandActionType::CardsDiscard;
}
inline bool IsAnyCardAction(const HandActionTypeFlags& actionType)
{
return (bool)(actionType & AnyCardsAction());
}
inline constexpr HandActionTypeFlags AnyInfoAction()
{
return
HandActionType::DeckReshuffle |
HandActionType::BettingCapped |
HandActionType::PairOnBoard ;
}
inline bool IsAnyInfoAction(const HandActionTypeFlags& actionType)
{
return (bool)(actionType & AnyInfoAction());
}
inline HandActionType GetInfoAction(const HandActionTypeFlags& actionType)
{
return static_cast<HandActionType> ((actionType & AnyInfoAction()).underlying_value());
}
inline constexpr HandActionTypeFlags AnySummaryAction()
{
return
HandActionType::Collected |
HandActionType::MuckHand |
HandActionType::ShowHand;
}
inline HandActionType GetSummaryAction(const HandActionTypeFlags& actionType)
{
return static_cast<HandActionType> ((actionType & AnySummaryAction()).underlying_value());
}
inline bool IsAnySummaryAction(const HandActionTypeFlags& actionType)
{
return (bool)(actionType & AnySummaryAction());
}
extern const char* ActionTypeStr(const HandActionTypeFlags& actionType);
}
}
#endif<file_sep>/src/luapool.cxx
#include "luapool.hpp"
namespace a2a
{
LuaStatesPool::LuaStatesPool(std::size_t statesNum) : m_abStop(false)
{
lock_t lock(m_mutex);
m_pool.reserve(statesNum);
for (std::size_t i = 0; i < statesNum; ++i)
{
m_pool.emplace_back( std::make_shared<LuaState>() );
m_readyChunks.push(i);
}
}
LuaStatesPool::~LuaStatesPool()
{
{
lock_t lock(m_mutex);
m_abStop = true;
}
m_condReady.notify_all();
}
LuaStatesPool::PooledLuaState * LuaStatesPool::GetPooledState()
{
while (true)
{
lock_t lock(m_mutex);
if (!m_abStop && m_readyChunks.empty())
{
m_condReady.wait(lock);
}
if (m_abStop)
return nullptr;
if (!m_readyChunks.empty())
{
auto i = m_readyChunks.top();
m_readyChunks.pop();
auto& st = *m_pool[i];
return new PooledLuaState(
st, [this, &st, i]()
{
lock_t lock(m_mutex);
m_readyChunks.push(i);
m_condReady.notify_one();
});
}
}
}
LuaStatesPool & LuaStatesPool::Global()
{
static LuaStatesPool obj(std::thread::hardware_concurrency());
return obj;
}
//------------------------------------------------------------------------ Buffer
LuaStatesPool::PooledLuaState::PooledLuaState(LuaState& ref, const releaser_t& onRelease) :
m_ref(ref), m_fOnRelease(onRelease)
{
}
LuaStatesPool::PooledLuaState::~PooledLuaState()
{
m_fOnRelease();
}
}
<file_sep>/include/hhconverter_base.hpp
#ifndef INCLUDE_HHEXPORTER_HPP
#define INCLUDE_HHEXPORTER_HPP
#include <iostream>
#include <memory>
#include "plugin.hpp"
#include "handhistory.hpp"
namespace a2a
{
class HandHistoryConverterSettings : public Settings
{
public:
HandHistoryConverterSettings()
: Settings()
{}
HandHistoryConverterSettings(const JsonSettings& jsettings)
: Settings(jsettings)
{}
};
class HandHistoryConverter : public Plugin
{
public:
using Ptr = std::shared_ptr<HandHistoryConverter>;
HandHistoryConverter(const std::string& name, const Version& ver) : Plugin(name, ver) {}
virtual void Convert(std::ostream& os, const HandHistory& handHistory) const = 0;
inline void SetupConverter(const HandHistoryConverterSettings& converterSettings)
{
m_settings = converterSettings;
}
protected:
HandHistoryConverterSettings m_settings;
};
}
#endif<file_sep>/include/gamestagescol.hpp
#ifndef INCLUDE_GAMESTAGESCOL_HPP
#define INCLUDE_GAMESTAGESCOL_HPP
#include "collection.hpp"
#include "gamestage.hpp"
namespace a2a
{
class GameStages final : public Collection<GameStage, GameStages>
{
public:
static predicate_t Type_(GameStageType st);
HandActions GetActions() const;
HandActions GetActions(const HandActions::predicate_t& predicate) const;
//HandActions GetPotActions() const;
};
}
//
// inlines
//
namespace a2a
{
inline GameStages::predicate_t GameStages::Type_(GameStageType st)
{
return [st](const value_type& a) -> bool { return a->GetType() == st; };
}
}
#endif<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(a2a-poker-tools CXX)
set(SRC_ROOT ${CMAKE_SOURCE_DIR}/src)
set(TESTS_ROOT ${CMAKE_SOURCE_DIR}/tests)
set(TOOLS_ROOT ${CMAKE_SOURCE_DIR}/tools)
set(INCLUDE_ROOT ${CMAKE_SOURCE_DIR}/include)
set(EXT_ROOT ${CMAKE_SOURCE_DIR}/src/libs/src)
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
set(EXT_LIBS ${CMAKE_SOURCE_DIR}/src/libs/64-bit)
set(BIN_ROOT ${CMAKE_SOURCE_DIR}/bin/64-bit)
else()
set(EXT_LIBS ${CMAKE_SOURCE_DIR}/src/libs/32-bit)
set(BIN_ROOT ${CMAKE_SOURCE_DIR}/bin/32-bit)
endif()
link_directories( ${EXT_LIBS} )
option(LUA_SUPPORT "Luajit addons support" ON)
option(BUILD_TESTS "Build tests [catch/benchpress]" OFF)
option(BUILD_TOOLS "Build tools" ON)
function (add_target_definitions target)
get_target_property(defs ${target} COMPILE_DEFINITIONS)
if (defs MATCHES "NOTFOUND")
set(defs "")
endif ()
foreach (def ${defs} ${ARGN})
list(APPEND deflist ${def})
endforeach ()
set_target_properties(${target} PROPERTIES COMPILE_DEFINITIONS "${deflist}")
endfunction ()
set(inc_dirs ${INCLUDE_ROOT})
set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${BIN_ROOT} )
set( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${BIN_ROOT} )
set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${BIN_ROOT} )
foreach( OUTPUTCONFIG ${CMAKE_CONFIGURATION_TYPES} )
string( TOUPPER ${OUTPUTCONFIG} OUTPUTCONFIG )
set( CMAKE_RUNTIME_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${BIN_ROOT} )
set( CMAKE_LIBRARY_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${BIN_ROOT} )
set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${BIN_ROOT} )
endforeach( OUTPUTCONFIG CMAKE_CONFIGURATION_TYPES )
if(LUA_SUPPORT)
if (${CMAKE_SYSTEM_NAME} STREQUAL "Windows")
set(inc_dirs "${inc_dirs}" ${EXT_ROOT}/lua)
find_library(
LUA_LIB
NAMES lua51
PATHS ${EXT_LIBS}
)
else()
find_library(
LUA_LIB
NAMES luajit-5.1
PATHS /usr/lib /usr/local/lib
)
set(inc_dirs "${inc_dirs}" /usr/local/include/luajit-2.0)
endif()
endif()
MESSAGE(${LUA_LIB})
MESSAGE(${inc_dirs})
include_directories(${inc_dirs})
add_subdirectory ( ${SRC_ROOT} )
add_subdirectory ( ${TESTS_ROOT} )
if(BUILD_TOOLS)
add_subdirectory ( ${TOOLS_ROOT} )
endif()
<file_sep>/include/card.hpp
#ifndef INCLUDE_CARD_HPP
#define INCLUDE_CARD_HPP
#include <string>
#include <iostream>
#include "types.hpp"
namespace a2a
{
enum class CardRank
{
_2 = 0,
_3 = 1,
_4 = 2,
_5 = 3,
_6 = 4,
_7 = 5,
_8 = 6,
_9 = 7,
T = 8,
J = 9 ,
Q = 10,
K = 11,
A = 12
};
enum class CardSuit
{
hearts = 0,
diamonds = 1,
clubs = 2,
spades = 3
};
class Card
{
public:
static const int SUIT_MAX = 4;
static const int RANK_MAX = 13;
Card();
Card(int r, int s);
Card(CardRank r, CardSuit s);
void Reset(CardRank r, CardSuit s);
static Card FromString(const char*);
static Card FromString(const std::string&);
std::string ToString() const;
CardRank Rank() const;
CardSuit Suit() const;
int RankCode() const;
int SuitCode() const;
bool operator== (const Card &rhs) const;
bool operator< (const Card &rhs) const;
bool operator!= (const Card &rhs) const;
bool operator<= (const Card &rhs) const;
bool operator> (const Card &rhs) const;
bool operator>= (const Card &rhs) const;
friend std::ostream& operator<< (std::ostream& os, const Card& c);
private:
int index;
static int ReadFromString(const char*, Card&);
friend class CardSet;
friend class CardSeq;
};
}
//
// inlines
//
namespace a2a
{
inline CardRank Card::Rank() const
{
return static_cast<CardRank>(RankCode());
}
inline CardSuit Card::Suit() const
{
return static_cast<CardSuit>(SuitCode());
}
inline int Card::RankCode() const
{
return index%RANK_MAX;
}
inline int Card::SuitCode() const
{
return index / RANK_MAX;
}
inline bool Card::operator== (const Card &rhs) const { return this->index == rhs.index; }
inline bool Card::operator< (const Card &rhs) const { return this->index < rhs.index; }
inline bool Card::operator!= (const Card &rhs) const { return !(*this == rhs); }
inline bool Card::operator<= (const Card &rhs) const { return !(rhs < *this); }
inline bool Card::operator> (const Card &rhs) const { return (rhs < *this); }
inline bool Card::operator>= (const Card &rhs) const { return !(*this < rhs); }
}
#endif<file_sep>/addons/a2ahh.lua
--package.path = '../../../addons/?.lua;../../addons/?.lua;../addons/?.lua;../?.lua;' .. package.path
local ffi = require "ffi"
local bit = require("bit")
local C = ffi.C
local shl = bit.lshift
local bor = bit.bor
local band = bit.band
ffi.cdef
[[
void* hh_new();
void hh_delete(void*);
void hh_set_handid(void*, const char*);
const char* hh_get_handid(void*);
void hh_set_tournid(void*, const char*);
const char* hh_get_tournid(void*);
void hh_set_tournid(void*, const char*);
const char* hh_get_tournid(void*);
void hh_set_gametype(void*, unsigned int);
unsigned int hh_get_gametype(void*);
void hh_get_gametype_str(unsigned int, char*, int);
void hh_set_gamemode(void*, unsigned int);
unsigned int hh_get_gamemode(void*);
void hh_set_gamesite(void*, const char*);
const char* hh_get_gamesite(void*);
void hh_set_datetime(void*, double);
double hh_get_datetime(void*);
double _get_tzabbroffset(const char*);
void hh_set_timezone(void*, const char*);
const char* hh_get_timezone(void*);
void hh_set_currency(void*, unsigned int);
unsigned int _get_currencyfromstr(const char*);
const char* _get_currency_str(unsigned int);
unsigned int hh_get_currency(void*);
void hh_set_stackscurrency(void*, unsigned int);
unsigned int hh_get_stackscurrency(void*);
void hh_set_tournlvl(void*, int);
int hh_get_tournlvl(void*);
int _roman_to_int(const char*);
void _int_to_roman(int, char*, int);
void hh_set_buyin(void*, int, int, int);
int hh_get_buyin_rake(void*);
int hh_get_buyin_prizepool(void*);
int hh_get_buyin_knockout(void*);
void hh_set_ante(void*, int);
int hh_get_ante(void*);
void hh_set_cap(void*, int);
int hh_get_cap(void*);
void hh_set_blinds(void*, int, int);
int hh_get_bb(void*);
int hh_get_sb(void*);
void hh_set_blindlvls(void*, int, int);
int hh_get_bbl(void*);
int hh_get_sbl(void*);
void hh_set_tablename(void*, const char*);
const char* hh_get_tablename(void*);
void hh_set_maxplayers(void*, int);
int hh_get_maxplayers(void*);
void hh_set_button(void*, int);
int hh_get_button(void*);
void hh_set_cancelled(void*);
int hh_is_cancelled(void*);
const char* hh_get_hero(void*);
int hh_is_runtwice(void*);
int hh_has_header(void*);
int hh_add_seat(void*, const char*, int, int);
void* hh_get_seat(void*, int);
int hh_get_seats_num(void*);
void* hh_get_stage(void*, unsigned int);
void* hh_get_istage(void*, int);
int hh_get_stages_num(void*);
void* hh_get_iaction(void*, int);
int hh_get_actions_num(void*);
int hh_add_action(void* p,
unsigned int type,
const char* player,
int cash,
void* cards,
unsigned int stage,
unsigned int stageTo);
int seat_get_idx(void*);
const char* seat_get_playername(void*);
int seat_get_stack(void*);
void seat_set_stack(void*, int);
int seat_get_startstack(void*);
void seat_set_startstack(void*, int);
unsigned int seat_get_pos(void*);
const char* _get_pos_str(unsigned int);
int seat_is_fold(void*);
int seat_is_allin(void*);
int seat_get_stake(void*);
void* seat_get_cards(void*);
void* cards_new(const char*);
void cards_delete(void*);
int cards_size(void*);
int cards_visible(void*);
void cards_set_evalhint(void*, const char*);
const char* cards_get_evalhint(void*);
void cards_str(void*,const char*,char*,int);
unsigned int stage_get_type(void*);
const char* stage_get_type_str(unsigned int);
void* stage_get_seat(void*, int);
int stage_get_seats_num(void*);
void* stage_get_board(void*);
void* stage_get_pot(void*);
void* stage_get_action(void*, int);
int stage_get_actions_num(void*);
int pot_get_chips(void*);
void pot_set_rake(void*, int);
int pot_get_rake(void*);
void pot_add_sidepot(void*, int);
int pot_get_sidepots_num(void*);
int pot_get_sidepot(void*, int);
unsigned int act_get_type(void*);
const char* act_get_type_str(unsigned int);
void act_set_chips(void*, int);
int act_get_chips(void*);
int act_get_raiseup(void*);
int act_get_raiseto(void*);
void act_set_player(void*, const char*);
const char* act_get_player(void*);
void act_set_stage_type(void*, unsigned int);
unsigned int act_get_stage_type(void*);
void* act_get_cards(void*);
void act_set_cards(void*, void*);
const char* act_get_prop(void*, const char*);
void act_set_prop(void*, const char*, const char*);
void* _test_hand();
]]
char_buffer64_t = ffi.typeof("char[64]")
char_buffer256_t = ffi.typeof("char[256]")
function is_flag(...)
return band(...) ~= 0
end
function flags(...)
return bor(...)
end
CardGameType =
{
Unknown = 0,
Holdem = shl(1,0),
Omaha = shl(1, 1),
OmahaHiLo = shl(1, 2),
Omaha5c = shl(1, 3),
Omaha5cHiLo = shl(1, 4),
Courchevel = shl(1, 5),
CourchevelHiLo = shl(1, 6),
Stud7c = shl(1, 7),
Stud7cHiLo = shl(1, 8),
Razz = shl(1, 9),
Draw5c = shl(1, 10),
DrawTripple27 = shl(1, 11),
DrawSingle27 = shl(1, 12),
Badugi = shl(1, 13),
NoLimit = shl(1, 16),
PotLimit = shl(1, 17),
FixedLimit = shl(1, 18),
Mix_Game8 = shl(1, 20),
Mix_HORSE = shl(1, 21),
Mix_HOSE = shl(1, 22),
Mix_NLHPLO = shl(1, 23),
Mix_PLHPLO = shl(1, 24),
Mix_Holdem = shl(1, 25),
Mix_OmahaHiLo = shl(1, 26),
Mix_TrippleStud = shl(1, 27),
}
CardGameMode =
{
Unknown = 0,
CashGame = shl(1, 0),
Tournament = shl(1, 1),
FastFold = shl(1, 2),
Freeroll = shl(1, 3),
BuyIn = shl(1, 4),
BuyInKnockout = shl(1, 5),
Cap = shl(1, 6),
Ante = shl(1, 7),
}
CurrencyType =
{
Chips = 0,
USD = 1,
GBP = 2,
EURO = 3,
}
PokerPosition =
{
EMPTY = 0,
UTG1 = shl(1, 0),
UTG2 = shl(1, 1),
UTG3 = shl(1, 2),
UTG = 0xF,
MP1 = shl(1, 4),
MP2 = shl(1, 5),
MP3 = shl(1, 6),
MP = 0xF0,
CO = shl(1, 8),
BTN = shl(1, 9),
SB = shl(1, 10),
BB = shl(1, 11),
}
GameStageType =
{
Current = 0,
Seating = 1,
Blinds = 2,
_3rdStreet = 3,
_4thStreet = 4,
_5thStreet = 5,
_6thStreet = 6,
_DrawHands = 7,
_1stDraw = 8,
_2ndDraw = 9,
_3rdDraw = 10,
Preflop = 11,
Flop = 12,
Turn = 13,
River = 14,
Flop_2nd = 15,
Turn_2nd = 16,
River_2nd = 17,
Showdown = 18,
Showdown_2nd = 19,
Summary = 20,
Any = 255,
}
HandActionType =
{
Unknown = 0,
SmallBlind = shl(1, 0),
BigBlind = shl(1, 1),
SmallAndBigBlind = shl(1, 2),
Ante = shl(1, 3),
Return = shl(1, 4),
Fold = shl(1, 5),
Check = shl(1, 6),
Call = shl(1, 7),
BringIn = shl(1, 8),
Bet = shl(1, 9),
Raise = shl(1, 10),
Collected = shl(1, 11),
MuckHand = shl(1, 12),
ShowHand = shl(1, 13),
AllIn = shl(1, 16),
Cap = shl(1, 17),
Street = shl(1, 18),
CardsDealt = shl(1, 20),
CardsDiscard = shl(1, 21),
DeckReshuffle = shl(1, 22),
BettingCapped = shl(1, 23),
PairOnBoard = shl(1, 24),
_ForceUncalledBet = shl(1, 27),
_RaiseUpAdjust = shl(1, 28),
_UncalledBetAdjust = shl(1, 29),
_Hidden = shl(1, 30),
Any = 0xFFFFFFFF,
}
------------------------------------------------------------------- Cards
HHCards = {}
local HHCards_mt = { __index = HHCards }
function HHCards:new(x)
local ptr = nil
local _const = false
local xt = type(x)
if xt == "string" then
ptr = ffi.gc(C.cards_new(x), C.cards_delete)
elseif xt == "nil" then
ptr = ffi.gc(C.cards_new(nil), C.cards_delete)
else
ptr = x
_const = true
end
return setmetatable( {p=ptr, _const=_const}, HHCards_mt)
end
function HHCards:num()
return C.cards_size(self.p)
end
function HHCards:visible_num()
return C.cards_visible(self.p)
end
function HHCards:eval_hint(x)
if not self._const and type(x) == "string" then
C.cards_set_evalhint(self.p, x)
return x
end
return ffi.string(C.cards_get_evalhint(self.p))
end
function HHCards:str(fmt)
local buf = ffi.new(char_buffer256_t)
local f = type(fmt) == "string" and fmt or "%X"
C.cards_str(self.p, f, buf, 256)
return ffi.string(buf)
end
------------------------------------------------------------------- Seat
HHSeat = {}
local HHSeat_mt = { __index = HHSeat }
function HHSeat:new(x)
return setmetatable( {p=x}, HHSeat_mt)
end
function HHSeat:index()
return C.seat_get_idx(self.p)
end
function HHSeat:player_name()
return ffi.string(C.seat_get_playername(self.p))
end
function HHSeat:cards()
return HHCards:new(C.seat_get_cards(self.p))
end
function HHSeat:stack(x)
if (type(x)=="number") then
C.seat_set_stack(self.p, x)
return x;
end
return C.seat_get_stack(self.p)
end
function HHSeat:start_stack(x)
if (type(x)=="number") then
C.seat_set_startstack(self.p, x)
return x;
end
return C.seat_get_startstack(self.p)
end
function HHSeat:pos()
return C.seat_get_pos(self.p)
end
function HHSeat:is_pos(...)
return band(C.seat_get_pos(self.p), ...) ~= 0
end
function HHSeat:pos_str()
return ffi.string(C._get_pos_str(self:pos()))
end
function HHSeat:is_fold()
return C.seat_is_fold(self.p) ~= 0
end
function HHSeat:is_allin()
return C.seat_is_allin(self.p) ~= 0
end
function HHSeat:stake()
return C.seat_get_startstack(self.p)
end
------------------------------------------------------------------- Pot
HHPot = {}
local HHPot_mt = { __index = HHPot }
function HHPot:new(x)
return setmetatable( {p=x}, HHPot_mt)
end
function HHPot:chips()
return C.pot_get_chips(self.p)
end
function HHPot:rake(x)
if type(x) == "number" then
C.pot_set_rake(self.p)
return x
end
return C.pot_get_rake(self.p)
end
function HHPot:add_sidepot(x)
C.pot_add_sidepot(self.p,x)
end
function HHPot:sidepots()
local t = {}
local num = C.pot_get_sidepots_num(self.p)
for i=0, num-1 do
t[#t+1] = C.pot_get_sidepot(self.p, i)
end
return t
end
------------------------------------------------------------------- Action
HHAction = {}
local HHAction_mt = { __index = HHAction }
function HHAction:new(x)
return setmetatable( {p=x}, HHAction_mt)
end
function HHAction:type()
return C.act_get_type(self.p)
end
function HHAction:type_str()
return ffi.string(C.act_get_type_str(C.act_get_type(self.p)))
end
function HHAction:chips(x)
if type(x) == "number" then
C.act_set_chips(self.p, x)
return x
end
return C.act_get_chips(self.p)
end
function HHAction:raiseup()
return C.act_get_raiseup(self.p)
end
function HHAction:raiseto()
return C.act_get_raiseto(self.p)
end
function HHAction:player_name(x)
if type(x)=="string" then
C.act_set_player(self.p, x)
return x
end
return ffi.string( C.act_get_player(self.p) )
end
function HHAction:stage_type(x)
if type(x)=="number" then
C.act_set_stage_type(self.p, x)
return x
end
return C.act_get_stage_type(self.p)
end
function HHAction:cards(x)
if type(x)=="table" then
C.act_set_cards(self.p, x.p)
return x
end
return HHCards:new(C.act_get_cards(self.p))
end
function HHAction:prop(x,y)
if type(x) ~= "string" then return nil end
if y ~= nil then
local prop = tostring(y)
C.act_set_prop(self.p, x, prop)
return prop
end
local r = C.act_get_prop(self.p, x)
return r == nil and nil or ffi.string(r)
end
------------------------------------------------------------------- Stage
HHStage = {}
local HHStage_mt = { __index = HHStage }
function HHStage:new(x)
return setmetatable( {p=x}, HHStage_mt)
end
function HHStage:type()
return C.stage_get_type(self.p)
end
function HHStage:type_str()
return ffi.string(C.stage_get_type_str(C.stage_get_type(self.p)))
end
function HHStage:board()
return HHCards:new( C.stage_get_board(self.p) )
end
function HHStage:seats()
local t = {}
local num = C.stage_get_seats_num(self.p)
for i=0, num-1 do
t[#t+1] = HHSeat:new(C.stage_get_seat(self.p, i))
end
return t
end
function HHStage:pot()
return HHPot:new( C.stage_get_pot(self.p) )
end
function HHStage:actions()
local t = {}
local num = C.stage_get_actions_num(self.p)
for i=0, num-1 do
t[#t+1] = HHAction:new(C.stage_get_action(self.p, i))
end
return t
end
------------------------------------------------------------------- HandHistory
HandHistory = {}
local HandHistory_mt = { __index = HandHistory }
function HandHistory:new(x)
return setmetatable( {p = x or ffi.gc(C.hh_new(), C.hh_delete)}, HandHistory_mt)
end
-- handID
function HandHistory:hand_id(x)
if (x~=nil) then
C.hh_set_handid(self.p, type(x) == "string" and x or tostring(x))
end
return ffi.string(C.hh_get_handid(self.p))
end
-- TournamentID
function HandHistory:tourney_id(x)
if (x~=nil) then
C.hh_set_tournid(self.p, type(x) == "string" and x or tostring(x))
end
return ffi.string(C.hh_get_tournid(self.p))
end
-- GameType
function HandHistory._GameTypeStr(...)
local buf = ffi.new(char_buffer64_t)
C.hh_get_gametype_str(bor(...), buf, 64);
return ffi.string(buf);
end
function HandHistory:gametype(...)
local arg = {...}
if (#arg > 0) then
C.hh_set_gametype(self.p, bor(...))
end
return C.hh_get_gametype(self.p)
end
function HandHistory:gametype_str(...)
local arg = {...}
if (#arg > 0) then
return HandHistory._GameTypeStr(...)
end
return HandHistory._GameTypeStr(C.hh_get_gametype(self.p))
end
function HandHistory:is_gametype(...)
return band(C.hh_get_gametype(self.p), bor(...)) ~= 0
end
-- GameMode
function HandHistory:gamemode(...)
local arg = {...}
if (#arg > 0) then
C.hh_set_gamemode(self.p, bor(...))
end
return C.hh_get_gamemode(self.p)
end
function HandHistory:is_gamemode(...)
return band(C.hh_get_gamemode(self.p), bor(...)) ~= 0
end
-- GameSite
function HandHistory:site(x)
if (x~=nil) then
C.hh_set_gamesite(self.p, type(x) == "string" and x or tostring(x))
end
return ffi.string(C.hh_get_gamesite(self.p))
end
-- DateTime
function HandHistory:set_datetime(x, tz)
local offset = 0
if type(tz) == "string" then
offset = C._get_tzabbroffset(tz)
C.hh_set_timezone(self.p, tz)
end
C.hh_set_datetime(self.p, x - offset)
end
function HandHistory:datetime(tz)
local offset = 0
if type(tz) == "string" then
offset = C._get_tzabbroffset(tz)
end
return C.hh_get_datetime(self.p)+offset
end
function HandHistory:timezone()
return ffi.string(C.hh_get_timezone(self.p))
end
-- Currency
function HandHistory:currency(x)
if x~=nil then
local xt = type(x)
C.hh_set_currency(self.p, xt == "number" and x or ( xt == "string" and C._get_currencyfromstr(x) or CurrencyType.Chips ))
end
return C.hh_get_currency(self.p)
end
function HandHistory:currency_str()
return ffi.string( C._get_currency_str(C.hh_get_currency(self.p) ) )
end
function HandHistory:stacks_currency(x)
if x~=nil then
local xt = type(x)
C.hh_set_stackscurrency(self.p, xt == "number" and x or ( xt == "string" and C._get_currencyfromstr(x) or CurrencyType.Chips ))
end
return C.hh_get_stackscurrency(self.p)
end
function HandHistory:stacks_currency_str()
return ffi.string( C._get_currency_str(C.hh_get_stackscurrency(self.p) ) )
end
-- Tournament lvl
function HandHistory:tourney_lvl(x)
if x ~= nil then
local xt = type(x)
C.hh_set_tournlvl(self.p, xt == "number" and x or ( xt == "string" and C._roman_to_int(x) or 1 ))
end
return C.hh_get_tournlvl(self.p)
end
function HandHistory:tourney_lvl_roman()
local buf = ffi.new(char_buffer64_t)
C._int_to_roman(C.hh_get_tournlvl(self.p), buf, 64);
return ffi.string(buf);
end
-- buyin
function HandHistory:buyin(prizePool, rake, knockout)
C.hh_set_buyin(self.p, prizePool, type(knockout)=="number" and knockout or 0, type(rake)=="number" and rake or 0)
return prizePool
end
function HandHistory:buyin_rake()
return C.hh_get_buyin_rake(self.p)
end
function HandHistory:buyin_prize()
return C.hh_get_buyin_prizepool(self.p)
end
function HandHistory:buyin_knockout()
return C.hh_get_buyin_knockout(self.p)
end
-- limit
function HandHistory:ante(x)
if type(x) == "number" then
C.hh_set_ante(self.p, x)
return x;
end
return C.hh_get_ante(self.p)
end
function HandHistory:cap(x)
if type(x) == "number" then
C.hh_set_cap(self.p, x)
return x;
end
return C.hh_get_cap(self.p)
end
function HandHistory:blinds(x, y)
if type(x) == "number" and type(y) == "number" then
C.hh_set_blinds(self.p, x, y)
return x, y
end
return C.hh_get_sb(self.p), C.hh_get_bb(self.p)
end
function HandHistory:bb()
return C.hh_get_bb(self.p)
end
function HandHistory:sb()
return C.hh_get_sb(self.p)
end
function HandHistory:blind_lvls(x,y)
if type(x) == "number" and type(y) == "number" then
C.hh_set_blindlvls(self.p, x, y)
return x, y
end
return C.hh_get_sbl(self.p), C.hh_get_bbl(self.p)
end
function HandHistory:bb_lvl()
return C.hh_get_bbl(self.p)
end
function HandHistory:sb_lvl()
return C.hh_get_sbl(self.p)
end
-- Table name
function HandHistory:table_name(x)
if (x~=nil) then
local n = type(x) == "string" and x or "<Unknown>"
C.hh_set_tablename(self.p, n)
return n
end
return ffi.string(C.hh_get_tablename(self.p))
end
--
function HandHistory:max_players(x)
if type(x) == "number" then
C.hh_set_maxplayers(self.p, x)
return x
end
return C.hh_get_maxplayers(self.p)
end
--
function HandHistory:button(x)
if type(x) == "number" then
C.hh_set_button(self.p, x)
return x
end
return C.hh_get_button(self.p)
end
--
function HandHistory:cancel()
C.hh_set_cancelled(self.p)
return true
end
function HandHistory:is_cancelled()
return C.hh_is_cancelled(self.p) ~= 0
end
--
function HandHistory:hero_name()
return ffi.string(C.hh_get_hero(self.p))
end
--
function HandHistory:is_runtwice()
return C.hh_is_runtwice(self.p) ~= 0
end
--
function HandHistory:has_header()
return C.hh_has_header(self.p) ~= 0
end
-- Seats
function HandHistory:add_seat(name, idx, stack)
C.hh_add_seat(self.p, name, idx, stack)
end
function HandHistory:seats()
local t = {}
local num = C.hh_get_seats_num(self.p)
for i=0, num-1 do
t[#t+1] = HHSeat:new(C.hh_get_seat(self.p, i))
end
return t
end
-- Stages
function HandHistory:stages()
local t = {}
local num = C.hh_get_stages_num(self.p)
for i=0, num-1 do
t[#t+1] = HHStage:new(C.hh_get_istage(self.p, i))
end
return t
end
function HandHistory:stage(x)
return type(x) == "number" and
HHStage:new(C.hh_get_stage(self.p, x)) or
HHStage:new(C.hh_get_stage(self.p, 0))
end
-- Actions
function HandHistory:actions()
local t = {}
local num = C.hh_get_actions_num(self.p)
for i=0, num-1 do
t[#t+1] = HHAction:new(C.hh_get_iaction(self.p, i))
end
return t
end
function HandHistory:action(aType, p, c, to)
local stageTo = type(to)=="number" and to or 0
if type(p) == "string" then -- player action
if type(c) == "number" then -- cash
C.hh_add_action(self.p, aType, p, c, nil, 0, stageTo)
elseif type(c) == "table" then -- cards
C.hh_add_action(self.p, aType, p, 0, c.p, 0, stageTo)
else
C.hh_add_action(self.p, aType, p, 0, nil, 0, stageTo)
end
elseif type(p) == "number" then -- street change
if type(c) == "table" then -- only cards
C.hh_add_action(self.p, aType, nil, 0, c.p, p, stageTo)
else
C.hh_add_action(self.p, aType, nil, 0, nil, p, stageTo)
end
else
C.hh_add_action(self.p, aType, nil, 0, nil, 0, stageTo)
end
end
-------------------------------------------------------------
function RegisterA2AObject(tbl, a2aType, v, d)
return function(mt)
tbl[mt.__type] = {
type = a2aType,
version = type(v)=="number" and v or 1.0,
desc = type(d) =="string" and d or "No description"
}
end
end
<file_sep>/include/settings.hpp
#ifndef INCLUDE_SETTINGS_H
#define INCLUDE_SETTINGS_H
#include <memory>
#include "json11.hpp"
namespace a2a
{
class Settings
{
public:
using JsonSettings = Json;
Settings() : m_json(nullptr) {}
Settings(const JsonSettings& jsettings)
{
m_json = std::make_shared<JsonSettings>(jsettings);
}
virtual ~Settings()
{
}
const JsonSettings& to_json() const
{
if (m_json == nullptr)
m_json = std::make_shared<JsonSettings>();
jsonWrite(); return *m_json;
}
protected:
virtual void jsonWrite() const {}
mutable std::shared_ptr<JsonSettings> m_json;
};
}
#endif<file_sep>/src/hhlineparser_impl.cxx
#include <sstream>
#include "hhlineparser_impl.hpp"
#include "strutils.hpp"
namespace a2a
{
namespace detail
{
void LineParserImplBase::ThrowFailRead(const std::string & what, const std::string & ln)
{
std::stringstream ss;
ss << GameSiteUtils::GameSiteToString(site) << ": Failed to read '" << what << "'";
if (!ln.empty())
{
ss << std::endl << ln;
}
throw
ParseError(ss.str(), cursor);
}
void LineParserImplBase::AddAction(const HandAction::Ptr& action, GameStageType stageType)
{
try
{
hh.ProcessAction(action, stageType);
}
catch (const std::exception& err)
{
ThrowFailRead(err.what(), "");
}
}
int LineParserImplBase::ParseCash(const char * s)
{
int tr, dr, dots;
int amount = StrUtils::parse_int(s, &dr, &tr, &dots, true);
if (dr == 0) return -1;
if (dots == 0)
amount *= 100;
return amount;
}
bool LineParserImplBase::IsCancelledLine(const std::string& ln)
{
return false;
}
ParseStage LineParserImplBase::ProcessStreetChangeLine(const std::string& ln)
{
return ParseStage::None;
}
bool LineParserImplBase::ProcessLine(const std::string& ln)
{
if (parseStage != ParseStage::Header)
{
if (IsCancelledLine(ln))
{
hh.SetCancelled();
return false;
}
ParseStage ps = ProcessStreetChangeLine(ln);
if (ps != ParseStage::None)
{
parseStage = ps;
return true;
}
}
switch (parseStage)
{
case ParseStage::Header:
parseStage = ProcessHeaderLine(ln, headerLineIdx++);
break;
case ParseStage::Seating:
parseStage = ProcessSeatingLine(ln);
break;
case ParseStage::Blinds:
parseStage = ProcessBlindsLine(ln);
break;
case ParseStage::Streets:
parseStage = ProcessStreetLine(ln);
break;
case ParseStage::Showdown:
parseStage = ProcessShowdownLine(ln);
break;
case ParseStage::Summary:
parseStage = ProcessSummaryLine(ln);
break;
default:
return false;
}
return ParseStage::None != parseStage && !hh.IsCancelled();
}
bool LineParserImplBase::ProcessEmptyLine(int streak)
{
return streak < 2;
}
ParseStage LineParserImplBase::ProcessHeaderLine(const std::string& ln, int headerLineIndex) { return ParseStage::Seating; }
ParseStage LineParserImplBase::ProcessSeatingLine(const std::string& ln) { return ParseStage::Blinds; }
ParseStage LineParserImplBase::ProcessBlindsLine(const std::string& ln) { return ParseStage::Streets; }
ParseStage LineParserImplBase::ProcessStreetLine(const std::string& ln) { return ParseStage::Showdown; }
ParseStage LineParserImplBase::ProcessShowdownLine(const std::string& ln) { return ParseStage::Summary; }
ParseStage LineParserImplBase::ProcessSummaryLine(const std::string& ln) { return ParseStage::Summary; }
//////////////////////////////////////////////////////////////////////////////////////////////////
bool LineParserUtils::TryParse_A_seat_colon_player_stack(
LineParserImplBase* p,
const std::string& ln,
bool canSitOut,
bool readStackCurrency)
{
using namespace StrUtils;
static const char SEAT_START[] = "Seat ";
static const char SITTING_OUT_END[] = "out";
HandHistory& hh(p->hh);
if (!starts_with(ln, SEAT_START))
return false;
int tr, dr;
std::size_t sIdx = calen(SEAT_START);
int seatIndex = parse_int(ln.c_str() + sIdx, &dr, &tr);
if (dr == 0 || dr > 2 || seatIndex<1 || seatIndex > 10)
p->ThrowFailRead("Seat [Index]", ln);
sIdx += tr + 2;
if (sIdx>ln.size() - 1)
p->ThrowFailRead("Seat [Player name start]", ln);
std::size_t eIdx = ln.find(" (", sIdx);
if (eIdx == std::string::npos)
p->ThrowFailRead("Seat [Player name end]", ln);
if (readStackCurrency && hh.GetSeats().Empty())
hh.SetStacksCurrency(CurrencyUtils::CurrencyTypeFromUTF8Symbol(ln.c_str() + eIdx + 2));
int stack = p->ParseCash(ln.c_str() + eIdx + 2);
if (stack < 0)
p->ThrowFailRead("Seat [Stack]", ln);
if (canSitOut && ends_with(ln, SITTING_OUT_END))
return true;
hh.AddSeat(ln.substr(sIdx, eIdx - sIdx), seatIndex, stack);
return true;
}
bool LineParserUtils::TryParse__player_action(
LineParserImplBase *_this,
const std::string &ln,
const std::string &actionMark,
std::string &player)
{
std::size_t sIdx = ln.rfind(actionMark);
if (sIdx == std::string::npos)
return false;
sIdx = ln.find_last_of(": ", sIdx);
if (sIdx == std::string::npos)
return false;
sIdx = ln.find_last_not_of(": ", sIdx);
if (sIdx == std::string::npos)
return false;
std::size_t start = ln.find_first_not_of(' ');
player = ln.substr(start, sIdx - start + 1);
return true;
}
bool LineParserUtils::TryParse__player_action_amount(
LineParserImplBase *_this,
const std::string &ln,
const std::string &actionMark,
std::string &player,
int &value,
bool throwNoAmount)
{
std::size_t sIdx = ln.rfind(actionMark);
if (sIdx == std::string::npos)
return false;
value = -1;
std::size_t eIdx = sIdx + actionMark.size() + 1;
sIdx = ln.find_last_of(": ", sIdx);
if (sIdx == std::string::npos)
return false;
if (eIdx >= ln.size())
{
if (throwNoAmount)
_this->ThrowFailRead(std::string("Amount of [") + actionMark + std::string("]"), ln);
}
else
{
value = _this->ParseCash(ln.c_str() + eIdx);
if (value < 0 && throwNoAmount)
_this->ThrowFailRead(std::string("Amount of [") + actionMark + std::string("]"), ln);
}
sIdx = ln.find_last_not_of(": ", sIdx);
std::size_t start = ln.find_first_not_of(' ');
player = ln.substr(start, sIdx - start + 1 );
return true;
}
bool LineParserUtils::TryParse__player_action_amount_plus_amount(
LineParserImplBase *_this,
const std::string &ln,
const std::string &actionMark,
std::string &player,
int &value1,
int &value2)
{
if (!TryParse__player_action_amount(_this, ln, actionMark, player, value1))
return false;
std::size_t eIdx = ln.find_last_of('+');
if (eIdx == std::string::npos)
_this->ThrowFailRead(std::string("Second amount of [") + actionMark + std::string("]"), ln);
value2 = _this->ParseCash(ln.c_str() + eIdx);
return true;
}
bool LineParserUtils::TryParse_A_dealtto_player_cards(
LineParserImplBase *_this,
const std::string &ln)
{
static const char DEALT_TO[] = "Dealt to ";
using namespace StrUtils;
if (!starts_with(ln, DEALT_TO))
return false;
std::size_t rIdx = ln.rfind(" [");
if (rIdx == std::string::npos)
_this->ThrowFailRead("Dealt to [Cards start]", ln);
CardSeq cards(CardSeq::FromString(ln.c_str() + rIdx));
auto j = rIdx;
while (j != std::string::npos)
{
rIdx = j; j = ln.rfind(" [", rIdx - 1);
}
_this->AddAction(std::make_shared<HandAction>(
HandActionType::CardsDealt,
ln.substr(calen(DEALT_TO), rIdx - calen(DEALT_TO)),
cards));
return true;
}
bool LineParserUtils::TryParse__player_shows_cards_desc(
LineParserImplBase *_this,
const std::string &ln,
std::string &player,
CardSeq &cards)
{
std::size_t sIdx = ln.rfind("shows");
if (sIdx == std::string::npos)
return false;
auto cIdx = ln.find('[', sIdx);
if (cIdx == std::string::npos)
_this->ThrowFailRead("cards of [show cards action]", ln);
cards = CardSeq::FromString(ln.c_str() + cIdx);
cIdx = ln.find(']', cIdx);
if (cIdx != std::string::npos)
{
cIdx++;
if (cIdx < ln.size())
{
cIdx = ln.find_first_not_of("( ", cIdx);
if (cIdx != std::string::npos)
{
auto eIdx = ln.find_last_not_of(" )");
if (eIdx != std::string::npos && eIdx > cIdx)
cards.SetEvalHint(ln.substr(cIdx, eIdx - cIdx + 1));
}
}
}
if (sIdx == 0)
_this->ThrowFailRead(std::string("Player of [shows cards]"), ln);
sIdx--;
sIdx = ln.find_last_not_of(": ", sIdx);
std::size_t start = ln.find_first_not_of(' ');
player = ln.substr(start, sIdx - start + 1);
return true;
}
}
}
<file_sep>/addons/parsers/parser2.lua
A2ALineParser "TestParser2"
function TestParser2:HandStart()
return "*** Test2"
end 124
241
function TestParser2:Proc124essLine(ln)
print(ln) 1
return 1
end
function TestParser2:OnHandComplete()
print("[hand on complete]")
end
<file_sep>/include/seatscol.hpp
#ifndef INCLUDE_SEATSCOL_HPP
#define INCLUDE_SEATSCOL_HPP
#include <string>
#include "collection.hpp"
#include "seat.hpp"
namespace a2a
{
class Seats final : public Collection<Seat, Seats>
{
public:
static predicate_t Index_(int seatIndex);
static predicate_t Player_(const std::string& playerName);
static predicate_t NotFolded_();
static cmp_t ByIndex_();
static cmp_t ByStake_();
static cmp_t EqualByStake_();
private:
void UpdateSeat(const value_type&);
void UpdatePositions(int buttonIndex);
value_type& next(typename containter_type::iterator& i);
friend class GameStage;
};
}
//
// inlines
//
namespace a2a
{
inline Seats::predicate_t Seats::Index_(int seatIndex)
{
return [seatIndex](const value_type& a) -> bool { return a->GetIndex() == seatIndex; };
}
inline Seats::predicate_t Seats::Player_(const std::string& playerName)
{
return [&playerName](const value_type& a) -> bool { return a->GetPlayerName() == playerName; };
}
inline Seats::predicate_t Seats::NotFolded_()
{
return [](const value_type& a) -> bool { return !a->IsFold(); };
}
inline Seats::cmp_t Seats::ByIndex_()
{
return [](const value_type& a, const value_type& b) -> bool { return a->GetIndex() < b->GetIndex(); };
}
inline Seats::cmp_t Seats::ByStake_()
{
return [](const value_type& a, const value_type& b) -> bool { return a->GetStake().chips > b->GetStake().chips; };
}
inline Seats::cmp_t Seats::EqualByStake_()
{
return [](const value_type& a, const value_type& b) -> bool { return a->GetStake().chips == b->GetStake().chips; };
}
}
#endif<file_sep>/include/handactioncol.hpp
#ifndef INCLUDE_HANDACTIONCOL_HPP
#define INCLUDE_HANDACTIONCOL_HPP
#include <string>
#include "handaction.hpp"
#include "collection.hpp"
namespace a2a
{
class HandActions final : public Collection<HandAction, HandActions>
{
public:
static predicate_t Flags_(const HandActionTypeFlags& flags,
GameStageType gs = GameStageType::Any);
static predicate_t Stage_(GameStageType gs);
static predicate_t Player_(const std::string& playerName,
const HandActionTypeFlags& flags = HandActionType::Any);
static predicate_t PotActions_();
int ChipsSumm() const;
};
}
//
// inlines
//
namespace a2a
{
inline HandActions::predicate_t HandActions::Flags_(const HandActionTypeFlags & flags, GameStageType gs)
{
return
[&flags, gs](const value_type& a) -> bool {
return a->IsActionType(flags) && (gs == GameStageType::Any || gs == GameStageType::Current || a->GetStageType() == gs);
};
}
inline HandActions::predicate_t HandActions::Player_(const std::string & playerName, const HandActionTypeFlags & flags)
{
return
[&flags, &playerName](const value_type& a) -> bool {
return a->IsActionType(flags) &&
playerName == a->GetPlayerName();
};
}
inline HandActions::predicate_t HandActions::Stage_(GameStageType gs)
{
return [gs](const value_type& a) -> bool { return a->GetStageType() == gs; };
}
inline HandActions::predicate_t HandActions::PotActions_()
{
return [](const value_type& a) -> bool { return a->GetChips()!=0; };
}
}
#endif<file_sep>/include/hhparser_pac.hpp
#ifndef INCLUDE_HHPACIFICPARSER_HPP
#define INCLUDE_HHPACIFICPARSER_HPP
#include <memory>
#include "hhlineparser.hpp"
namespace a2a
{
namespace Pacific
{
namespace common
{
class common_pacific_parser : public HandHistoryLineParser
{
public:
common_pacific_parser(GameSite site, const std::string& name);
protected:
virtual const std::string& HandStart() const;
virtual ILineParserImpl* GetImplementation(HandHistory& _hh,
const HandHistoryParserSettings& _cfg,
const char*& _cursor) const;
private:
std::string m_handStart;
GameSite m_site;
};
}
class HHParser888 final : public common::common_pacific_parser
{
public:
HHParser888() : common_pacific_parser(GameSite::Pacific, "888poker") {}
};
class HHParserLotos final : public common::common_pacific_parser
{
public:
HHParserLotos() : common_pacific_parser(GameSite::Lotos, "LotosPoker") {}
};
class HHParserCassava final : public common::common_pacific_parser
{
public:
HHParserCassava() : common_pacific_parser(GameSite::Pacific, "Cassava") {}
};
class HHParserLuckyAce final : public common::common_pacific_parser
{
public:
HHParserLuckyAce() : common_pacific_parser(GameSite::Pacific, "LuckyAcePoker.com") {}
};
}
}
#endif<file_sep>/src/hhparser_ps.cxx
#include <string>
#include <sstream>
#include <stdexcept>
#include <ctime>
#include <memory>
#include <algorithm>
#include "strutils.hpp"
#include "streamutils.hpp"
#include "datetimeutils.hpp"
#include "hhparser_ps.hpp"
#include "sitesdata.hpp"
#include "handaction.hpp"
#include "stdutils.hpp"
#include "hhlineparser_impl.hpp"
namespace a2a
{
namespace detail
{
struct PokerStarsParser : public LineParserImplBase
{
PokerStarsParser(HandHistory& _hh, const HandHistoryParserSettings& _cfg, const char*& _cursor, GameSite _site) :
LineParserImplBase(_hh, _cfg, _cursor, _site)
{
}
int ParseCash(const char* s);
bool IsCancelledLine(const std::string& ln);
ParseStage ProcessStreetChangeLine(const std::string& ln);
ParseStage ProcessHeaderLine(const std::string& ln, int index);
void ProcessHeaderLine_0(const std::string& ln);
void ParseDateTime(const std::string& ln);
std::size_t ParseGameMode(const std::string& ln);
CardGameTypeFlags ExtractGameType(const std::string& ln, std::size_t &beginIdx);
std::size_t ParseGameType(const std::string& ln, std::size_t start_idx);
std::size_t ParseBuyin(const std::string& ln, std::size_t startIdx);
std::size_t ParseTournametLevel(const std::string& ln, std::size_t startIdx);
void ParseLimit(const std::string& ln, std::size_t startIdx);
void ProcessHeaderLine_1(const std::string& ln);
std::size_t ParseTableName(const std::string& ln);
std::size_t ParseMaxPlayers(const std::string& ln, std::size_t startIdx);
std::size_t ParseCheckPlayMoney(const std::string& ln, std::size_t startIdx);
void ParseButtonPosition(const std::string& ln, std::size_t startIdx);
ParseStage ProcessSeatingLine(const std::string& ln);
ParseStage ProcessBlindsLine(const std::string& ln);
ParseStage ProcessStreetLine(const std::string& ln);
bool ParseCardsDealt(const std::string & ln);
bool ParseActionLine(const std::string & ln);
bool ParseUncalledBet(const std::string& ln);
bool ParseInfoActions(const std::string& ln);
bool ParseCollected(const std::string& ln, const std::string& _pname = "");
bool ParseDoestshowhand(const std::string& ln);
bool ParseCardsDiscard(const std::string& ln);
bool ParseChat(const std::string& ln);
ParseStage ProcessShowdownLine(const std::string& ln);
bool ParseShowHand(const std::string & ln);
bool ParseMucksHand(const std::string& ln);
ParseStage ProcessSummaryLine(const std::string& ln);
bool ParsePotLine(const std::string& ln);
bool IsAllInAction(const std::string& ln);
int GetCapppedAction(const std::string& ln);
};
}
// Parser Class Methods
namespace PokerStars
{
HHParser::HHParser() : HandHistoryLineParser(GameSiteUtils::GameSiteToString(GameSite::PokerStars), Version(1, 0))
{
}
const std::string& HHParser::HandStart() const
{
static const std::string _start = "PokerStars ";
return _start;
}
ILineParserImpl* HHParser::GetImplementation(HandHistory& _hh,
const HandHistoryParserSettings& _cfg,
const char*& _cursor) const
{
//return new ParserImplementation::Parser(_hh, _cfg, _cursor);
return new detail::PokerStarsParser(_hh, _cfg, _cursor, GameSite::PokerStars);
}
}
}
///
///
///
namespace a2a
{
namespace detail
{
int PokerStarsParser::ParseCash(const char * s)
{
int tr, dr, dots;
int amount = StrUtils::parse_int(s, &dr, &tr, &dots);
if (dr == 0) return -1;
if (dots == 0 && hh.GetStacksCurrency() != CurrencyType::Chips)
amount *= 100;
return amount;
}
bool PokerStarsParser::IsCancelledLine(const std::string & ln)
{
static const char HAND_CANCELLED_START[] = "Hand cancelled";
return StrUtils::starts_with(ln, HAND_CANCELLED_START);
}
ParseStage PokerStarsParser::ProcessHeaderLine(const std::string & ln, int index)
{
switch (index)
{
case 0:ProcessHeaderLine_0(ln); break;
case 1:ProcessHeaderLine_1(ln); return ParseStage::Seating;
default: break;
}
return ParseStage::Header;
}
ParseStage PokerStarsParser::ProcessStreetChangeLine(const std::string & ln)
{
if (ln[0] != '*')
return ParseStage::None;
for (const auto& i : PokerStars::StreetStrings)
{
auto sIdx = ln.rfind(i.first);
if (sIdx != std::string::npos)
{
auto cIdx = ln.rfind('[');
if (cIdx == std::string::npos &&
i.second == GameStageType::Preflop &&
hh.IsGameType(CardGameType::Courchevel | CardGameType::CourchevelHiLo))
return ParseStage::None;
CardSeq cs;
if (cIdx != std::string::npos)
cs = CardSeq::FromString(ln.c_str() + cIdx);
AddAction(std::make_shared<HandAction>(HandActionType::Street, i.second, cs));
switch (i.second)
{
case GameStageType::Showdown:
case GameStageType::Showdown_2nd:
return ParseStage::Showdown;
case GameStageType::Summary:
return ParseStage::Summary;
default:
return ParseStage::Streets;
}
}
}
return ParseStage::None;
}
void PokerStarsParser::ProcessHeaderLine_0(const std::string & ln)
{
std::size_t peIdx = ParseGameMode(ln);
peIdx = ParseGameType(ln, peIdx);
ParseLimit(ln, peIdx);
ParseDateTime(ln);
}
void PokerStarsParser::ParseDateTime(const std::string & ln)
{
static const int COPY_RANGE = 21;
static const int TZ_RANGE = 7;
std::size_t ETpos = ln.rfind("ET");
if (ETpos == std::string::npos || ETpos < COPY_RANGE)
ThrowFailRead("DateTime [ET]", ln);
std::size_t BracketPos = ln.find_first_of('[', ETpos - COPY_RANGE);
std::size_t StartPos = ln.find_first_not_of(" [", ETpos - COPY_RANGE);
if (StartPos == std::string::npos)
ThrowFailRead("DateTime [ET]", ln);
int tr, dr;
int Y = StrUtils::parse_int(ln.c_str() + StartPos, &dr, &tr);
if (dr != 4)
ThrowFailRead("DateTime [Year]", ln);
StartPos += tr;
int M = StrUtils::parse_int(ln.c_str() + StartPos, &dr, &tr);
if (dr != 2)
ThrowFailRead("DateTime [Month]", ln);
StartPos += tr;
int D = StrUtils::parse_int(ln.c_str() + StartPos, &dr, &tr);
if (dr != 2)
ThrowFailRead("DateTime [Day]", ln);
StartPos += tr;
int H = StrUtils::parse_int(ln.c_str() + StartPos, &dr, &tr);
if (dr < 1)
ThrowFailRead("DateTime [Hours]", ln);
StartPos += tr;
int mins = StrUtils::parse_int(ln.c_str() + StartPos, &dr, &tr);
if (dr < 1)
ThrowFailRead("DateTime [Mins]", ln);
StartPos += tr;
int secs = StrUtils::parse_int(ln.c_str() + StartPos, &dr, &tr);
if (dr < 1)
ThrowFailRead("DateTime [Seconds]", ln);
hh.SetDateTimeUTC(DateTimeUtils::GetUTCTime(Y, M, D, H, mins, secs, TimeZonesType::ET));
if (BracketPos != std::string::npos)
{
std::size_t tzend = BracketPos - 2;
if (tzend < TZ_RANGE)
ThrowFailRead("DateTime [1st TmeZone]", ln);
std::size_t tzbeg = ln.find_first_of(' ', tzend - TZ_RANGE);
if (tzbeg == std::string::npos)
ThrowFailRead("DateTime [1st TmeZone]", ln);
hh.SetTimeZone(DateTimeUtils::TimeZoneFromAbbreviation(ln.substr(tzbeg + 1, tzend - tzbeg)));
assert(hh.GetTimeZone() != TimeZonesType::UTC && "Unrecognized Timezone Abbreviation");
}
}
std::size_t PokerStarsParser::ParseGameMode(const std::string & ln)
{
static const int MIN_HANDID_NUMBER_LEN = 8;
static const int SHARP_SEARCH_START = 15;
static const char FAST_FLAG_STR[] = "Zoom";
static const int ZOOM_SEARCH_START = 11;
int tr, dr;
std::size_t PosSharp = ln.find_first_of('#', SHARP_SEARCH_START);
if (PosSharp == std::string::npos)
ThrowFailRead("HandID [#]", ln);
hh.SetHandId(StrUtils::parse_int<u64>(ln.c_str() + PosSharp, &dr, &tr));
if (dr < MIN_HANDID_NUMBER_LEN)
ThrowFailRead("HandID [Number too short]", ln);
std::size_t ret = PosSharp + tr + 1;
PosSharp = ln.find_first_of('#', ret);
if (PosSharp == std::string::npos)
{
hh.SetGameMode(CardGameMode::CashGame);
if (ln.find(FAST_FLAG_STR, ZOOM_SEARCH_START, sizeof(FAST_FLAG_STR) - 1) != std::string::npos)
hh.SetGameMode(CardGameMode::FastFold);
}
else
{
hh.SetTournamentId(StrUtils::parse_int<u64>(ln.c_str() + PosSharp, &dr, &tr));
if (dr < MIN_HANDID_NUMBER_LEN)
ThrowFailRead("TournamentID [Number too short]", ln);
hh.SetGameMode(CardGameMode::Tournament);
ret = PosSharp + tr;
}
return ret;
}
CardGameTypeFlags PokerStarsParser::ExtractGameType(const std::string & ln, std::size_t & beginIdx)
{
using namespace StrUtils;
using namespace StrUtils::literals;
auto cardGame = PokerStars::ParseGame(ln, beginIdx);
if (!cardGame)
ThrowFailRead("GameType Flags [Game]", ln);
beginIdx++;
auto betType = PokerStars::ParseBetType(ln, beginIdx);
if (!betType)
ThrowFailRead("GameType Flags [Bet Type]", ln);
return cardGame | betType;
}
std::size_t PokerStarsParser::ParseGameType(const std::string & ln, std::size_t start_idx)
{
using namespace StrUtils;
static const char FREEROLL_STR[] = "Freeroll";
std::size_t startIdx, endIdx;
if (hh.IsGameMode(CardGameMode::CashGame))
{
startIdx = ln.find_first_not_of(' ', start_idx);
if (startIdx == std::string::npos)
ThrowFailRead("CashGame::GameType [Start index]", ln);
std::size_t LBraketIdx = ln.find_first_of('(', startIdx);
if (LBraketIdx == std::string::npos)
ThrowFailRead("CashGame::GameType [Left bracket index]", ln);
endIdx = LBraketIdx - 1;
auto mixGame = PokerStars::ParseMixGameType(ln, startIdx);
if (mixGame)
hh.SetGameType(mixGame);
else
hh.SetGameType(ExtractGameType(ln, startIdx));
}
else
{
startIdx = ln.find_first_not_of(' ', start_idx);
std::size_t MinusIdx = ln.find("- ", start_idx);
if (MinusIdx == std::string::npos)
ThrowFailRead("Tournament [Minus index]", ln);
endIdx = MinusIdx - 1;
std::size_t freeRoll = ln.find(FREEROLL_STR, startIdx, sizeof(FREEROLL_STR) - 1);
if (freeRoll != std::string::npos)
{
hh.SetGameMode(CardGameMode::Freeroll);
hh.SetTableCurrency(CurrencyType::USD);
startIdx += sizeof(FREEROLL_STR);
startIdx = ln.find_first_not_of(' ', startIdx);
}
else
{
hh.SetTableCurrency(CurrencyUtils::CurrencyTypeFromUTF8Symbol(ln.c_str() + startIdx));
startIdx = ParseBuyin(ln, startIdx);
}
auto mixGame = PokerStars::ParseMixGameType(ln, startIdx);
if (mixGame)
{
startIdx = ln.find_first_of('(', startIdx);
startIdx = ln.find_first_not_of('(', startIdx);
if (startIdx == std::string::npos)
ThrowFailRead("GameType Flags [Mix Game]", ln);
}
hh.SetGameType(ExtractGameType(ln, startIdx) | mixGame);
endIdx = ParseTournametLevel(ln, MinusIdx);
}
return endIdx;
}
std::size_t PokerStarsParser::ParseBuyin(const std::string & ln, std::size_t startIdx)
{
int tr, dr;
int v1 = StrUtils::parse_int(ln.c_str() + startIdx, &dr, &tr);
if (dr == 0)
ThrowFailRead("Buyin [PrizePool]", ln);
startIdx += tr;
if (startIdx >= ln.size() || ln[startIdx] != '+')
ThrowFailRead("Buyin Expected: [Knockout | Rake]", ln);
int v2 = StrUtils::parse_int(ln.c_str() + startIdx, &dr, &tr);
if (dr == 0)
ThrowFailRead("Buyin [Knockout | Rake]", ln);
startIdx += tr;
if (startIdx >= ln.size() || ln[startIdx] != '+')
hh.SetBuyin(v1, v2);
else
{
int v3 = StrUtils::parse_int(ln.c_str() + startIdx, &dr, &tr);
if (dr == 0)
ThrowFailRead("Buyin [Knockout -> Rake]", ln);
hh.SetBuyin(v1, v2, v3);
startIdx += tr;
}
// skip currency
startIdx = ln.find_first_not_of(' ', startIdx);
if (startIdx == std::string::npos)
ThrowFailRead("Tournament [Skip currency - 1]", ln);
if (hh.GetTableCurrency() != CurrencyType::Chips)
{
startIdx = ln.find_first_of(' ', startIdx);
if (startIdx == std::string::npos)
ThrowFailRead("Tournament [Skip currency - 2]", ln);
startIdx = ln.find_first_not_of(' ', startIdx);
if (startIdx == std::string::npos)
ThrowFailRead("Tournament [Skip currency - 3]", ln);
}
return startIdx;
}
std::size_t PokerStarsParser::ParseTournametLevel(const std::string & ln, std::size_t MinusIdx)
{
using namespace StrUtils;
std::size_t startIdx = ln.find_first_of('l', MinusIdx);
if (startIdx == std::string::npos || startIdx + 1 >= ln.size())
ThrowFailRead("Tournament [Level start]", ln);
std::size_t endIdx = ln.find_first_of('(', startIdx);
if (endIdx == std::string::npos || endIdx < 2)
ThrowFailRead("Tournament [Level end]", ln);
hh.SetTournamentLevel(parse_roman_invert<const char*, int>(ln.c_str() + startIdx + 1, ln.c_str() + endIdx - 2));
return endIdx;
}
void PokerStarsParser::ParseLimit(const std::string & ln, std::size_t startIdx)
{
startIdx = ln.find_first_not_of(" (", startIdx);
if (!hh.IsGameMode(CardGameMode::Tournament) && hh.IsGameType(CardGameType::AnyMixGame))
{
hh.SetGameType(ExtractGameType(ln, startIdx));
startIdx = ln.find_first_not_of(", ", startIdx);
}
if (startIdx == std::string::npos)
ThrowFailRead("Limit [start index]", ln);
if (hh.GetTableCurrency() == CurrencyType::Chips)
hh.SetTableCurrency(CurrencyUtils::CurrencyTypeFromUTF8Symbol(ln.c_str() + startIdx));
CurrencyType ct = hh.GetTableCurrency();
int tr, dr, dots;
int v1 = StrUtils::parse_int(ln.c_str() + startIdx, &dr, &tr, &dots);
if (dr == 0)
ThrowFailRead("Limit [1st number]", ln);
if (dots == 0 && ct != CurrencyType::Chips && !hh.IsGameMode(CardGameMode::Tournament))
v1 *= 100;
startIdx += tr;
if (startIdx >= ln.size() || ln[startIdx] != '/')
ThrowFailRead("Limit [2nd number start]", ln);
int v2 = StrUtils::parse_int(ln.c_str() + startIdx, &dr, &tr, &dots);
if (dr == 0)
ThrowFailRead("Limit [2nd number]", ln);
if (dots == 0 && ct != CurrencyType::Chips && !hh.IsGameMode(CardGameMode::Tournament))
v2 *= 100;
startIdx += tr;
hh.SetBlinds(v1, v2);
if (hh.IsGameMode(CardGameMode::Tournament))
return;
startIdx = ln.find_first_of("-)", startIdx);
if (startIdx == std::string::npos || ln[startIdx] == ')')
return;
int cap = StrUtils::parse_int(ln.c_str() + startIdx, &dr, &tr, &dots);
if (dr == 0 || cap == 0)
ThrowFailRead("Limit [Cap]", ln);
if (dots == 0 && ct != CurrencyType::Chips)
cap *= 100;
hh.SetCap(cap);
}
void PokerStarsParser::ProcessHeaderLine_1(const std::string & ln)
{
std::size_t peIdx = ParseTableName(ln);
peIdx = ParseMaxPlayers(ln, peIdx);
peIdx = ParseCheckPlayMoney(ln, peIdx);
ParseButtonPosition(ln, peIdx);
}
std::size_t PokerStarsParser::ParseTableName(const std::string & ln)
{
static const std::size_t NAME_START = 7;
std::size_t endIdx = ln.find_last_of('\'');
if (endIdx == std::string::npos)
ThrowFailRead("TableName [Last Dash]", ln);
hh.SetTableName(ln.substr(NAME_START, endIdx - NAME_START));
return endIdx;
}
std::size_t PokerStarsParser::ParseMaxPlayers(const std::string & ln, std::size_t startIdx)
{
startIdx = ln.find_first_not_of("' ", startIdx);
if (startIdx == std::string::npos)
ThrowFailRead("Table Max Players [number start location]", ln);
int dr;
int maxPlayers = StrUtils::parse_int(ln.c_str() + startIdx, &dr);
if (dr == 0)
ThrowFailRead("Table Max Players [number]", ln);
hh.SetTableMaxPlayers(maxPlayers);
return startIdx + dr;
}
std::size_t PokerStarsParser::ParseCheckPlayMoney(const std::string & ln, std::size_t startIdx)
{
static const char PLAY_MONEY_FLAG[] = "Play Money";
if (hh.IsGameMode(CardGameMode::Freeroll))
{
std::size_t pmfIdx = ln.rfind(PLAY_MONEY_FLAG, startIdx);
if (pmfIdx != std::string::npos)
{
hh.SetTableCurrency(CurrencyType::Chips);
startIdx = pmfIdx + sizeof(PLAY_MONEY_FLAG);
}
}
return startIdx;
}
void PokerStarsParser::ParseButtonPosition(const std::string & ln, std::size_t startIdx)
{
if (hh.GetGameType() & (CardGameType::Razz | CardGameType::Stud7c | CardGameType::Stud7cHiLo))
return;
startIdx = ln.find_first_of('#', startIdx);
if (startIdx == std::string::npos)
{
// cancelled game has no button pos sometimes
hh.SetButtonSeatIndex(0);
return;
}
int dr;
int buttonPos = StrUtils::parse_int(ln.c_str() + startIdx, &dr);
if (dr == 0)
ThrowFailRead("Table Button position [number]", ln);
hh.SetButtonSeatIndex(buttonPos);
}
ParseStage PokerStarsParser::ProcessSeatingLine(const std::string & ln)
{
return
!LineParserUtils::TryParse_A_seat_colon_player_stack(this, ln, false, true) &&
!hh.GetSeats().Empty() ?
ProcessBlindsLine(ln) :
ParseStage::Seating;
}
ParseStage PokerStarsParser::ProcessBlindsLine(const std::string & ln)
{
std::string player; int amount;
for (const auto& i : PokerStars::BlindsActionsStrings)
if (LineParserUtils::TryParse__player_action_amount(this, ln, i.second, player, amount))
{
HandActionTypeFlags aType(i.first);
if (IsAllInAction(ln))
aType |= HandActionType::AllIn;
AddAction(std::make_shared<HandAction>(aType, player, amount));
return ParseStage::Blinds;
}
return ParseStage::Blinds;
}
ParseStage PokerStarsParser::ProcessStreetLine(const std::string & ln)
{
auto isParsed =
ParseChat(ln) ||
ParseUncalledBet(ln) ||
ParseActionLine(ln) ||
ParseCardsDealt(ln) ||
ParseCardsDiscard(ln) ||
ParseCollected(ln) ||
ParseDoestshowhand(ln) ||
ParseInfoActions(ln)
;
return isParsed ? ParseStage::Streets : parseStage;
}
bool PokerStarsParser::ParseCardsDealt(const std::string & ln)
{
return LineParserUtils::TryParse_A_dealtto_player_cards(this, ln);
}
bool PokerStarsParser::ParseActionLine(const std::string & ln)
{
std::string player; int amount;
for (const auto& i : PokerStars::ActionsStrings)
if (LineParserUtils::TryParse__player_action_amount(this, ln, i.second, player, amount, false))
{
HandActionTypeFlags aType(i.first);
if (amount < 0)
{
if (aType != HandActionType::Check && aType != HandActionType::Fold)
ThrowFailRead(std::string("Amount of [") + i.second + std::string("]"), ln);
amount = 0;
}
else
{
if (aType == HandActionType::Fold)
{
//shipit1968: folds [Tc Th 2s 9c 6s 8s]
auto cIdx = ln.find('[');
if (cIdx == std::string::npos)
ThrowFailRead("cards of [folds]", ln);
CardSeq cards = CardSeq::FromString(ln.c_str() + cIdx);
AddAction(std::make_shared<HandAction>(aType, player, cards));
return true;
}
if (aType & HandActionType::Raise)
aType |= HandActionType::_RaiseUpAdjust;
if (IsAllInAction(ln))
aType |= HandActionType::AllIn;
auto capVal = GetCapppedAction(ln);
if (capVal > 0)
{
if (!hh.IsGameMode(CardGameMode::Cap))
hh.SetCap(capVal);
aType |= HandActionType::Cap;
}
}
AddAction(std::make_shared<HandAction>(aType, player, amount));
return true;
}
return false;
}
bool PokerStarsParser::ParseUncalledBet(const std::string & ln)
{
static const char UNCALLED_BET_START[] = "Uncalled bet (";
static const char UNCALLED_BET_RTO[] = "returned to ";
using namespace StrUtils;
if (StrUtils::starts_with(ln, UNCALLED_BET_START))
{
int amount = ParseCash(ln.c_str() + calen(UNCALLED_BET_START));
if (amount < 0)
ThrowFailRead("Uncalled bet [Amount]", ln);
std::size_t sIdx = ln.rfind(UNCALLED_BET_RTO);
if (sIdx == std::string::npos)
ThrowFailRead("Uncalled bet [Player Name]", ln);
sIdx += calen(UNCALLED_BET_RTO);
AddAction(std::make_shared<HandAction>(HandActionType::Return, ln.substr(sIdx), -amount));
return true;
}
return false;
}
bool PokerStarsParser::ParseInfoActions(const std::string & ln)
{
auto i = std::find_if(
PokerStars::InfoActionStrings.cbegin(),
PokerStars::InfoActionStrings.cend(),
[&ln](const action_strs_t::value_type& p) -> bool
{
return ln.find(p.second) != std::string::npos;
});
if (i == PokerStars::InfoActionStrings.end()) return false;
AddAction(std::make_shared<HandAction>(i->first));
return true;
}
bool PokerStarsParser::ParseCollected(const std::string & ln, const std::string & _pname)
{
static const char COLLECTED[] = " collected ";
static const char FROM_POT[] = " from ";
static const std::string DEFAULT_FROM = "pot";
using namespace StrUtils;
std::string player;
int amount;
if (!LineParserUtils::TryParse__player_action_amount(this, ln, "collected", player, amount, false))
return false;
std::size_t fIdx = ln.rfind(FROM_POT);
if (fIdx == std::string::npos)
ThrowFailRead("Collected source [From]", ln);
auto fromProperty(ln.substr(fIdx + calen(FROM_POT)));
HandActionTypeFlags aType(HandActionType::Collected);
if (GameStageUtils::IsAnyStreetStage(hh.GetGameStage()->GetType()))
aType |= HandActionType::_UncalledBetAdjust;
auto action = std::make_shared<HandAction>(aType, _pname.empty() ? player : _pname, amount);
if (DEFAULT_FROM != fromProperty)
action->SetProperty("from", fromProperty);
AddAction(action);
return true;
}
bool PokerStarsParser::ParseDoestshowhand(const std::string & ln)
{
std::string player;
if (!LineParserUtils::TryParse__player_action(this, ln, "doesn't show hand", player))
return false;
AddAction(std::make_shared<HandAction>(HandActionType::MuckHand, player));
return true;
}
bool PokerStarsParser::ParseCardsDiscard(const std::string & ln)
{
static const char DISCARDS[] = ": discards ";
static const char STANDSPAT[] = ": stands pat";
using namespace StrUtils;
std::size_t rIdx = ln.rfind(DISCARDS);
bool isStandsPat = false;
if (rIdx == std::string::npos)
{
rIdx = ln.rfind(STANDSPAT);
if (rIdx == std::string::npos)
return false;
isStandsPat = true;
}
int cardsNum = 0;
if (!isStandsPat)
{
int dr;
cardsNum = parse_int(ln.c_str() + rIdx + calen(DISCARDS), &dr);
if (dr == 0)
ThrowFailRead("Discards cards [Number]", ln);
std::size_t cIdx = ln.rfind(" [");
CardSeq cards = cIdx == std::string::npos ? CardSeq(cardsNum) : CardSeq::FromString(ln.c_str() + cIdx);
AddAction(std::make_shared<HandAction>(
HandActionType::CardsDiscard,
ln.substr(0, rIdx),
cards));
}
else
AddAction(std::make_shared<HandAction>(
HandActionType::CardsDiscard,
ln.substr(0, rIdx),
CardSeq()));
return true;
}
bool PokerStarsParser::ParseChat(const std::string & ln)
{
static const char CHAT_MSG[] = " said, \"";
return ln.find(CHAT_MSG) != std::string::npos;
}
ParseStage PokerStarsParser::ProcessShowdownLine(const std::string & ln)
{
auto isParsed =
ParseShowHand(ln) || ParseCollected(ln) ||
ParseMucksHand(ln);
return ParseStage::Showdown;
}
bool PokerStarsParser::ParseShowHand(const std::string & ln)
{
CardSeq cards;
std::string player;
if (!LineParserUtils::TryParse__player_shows_cards_desc(this, ln, player, cards))
return false;
AddAction(std::make_shared<HandAction>(HandActionType::ShowHand, player, cards));
return true;
}
bool PokerStarsParser::ParseMucksHand(const std::string & ln)
{
std::string player;
if (!LineParserUtils::TryParse__player_action(this, ln, "mucks hand", player))
return false;
AddAction(std::make_shared<HandAction>(HandActionType::MuckHand, player));
return true;
}
ParseStage PokerStarsParser::ProcessSummaryLine(const std::string & ln)
{
static const char SEAT_START[] = "Seat ";
static const char HAND_START[] = "Hand ";
static const char BOARD_START[] = "Board";
static const char FIRST_START[] = "FIRST ";
static const char SECOND_START[] = "SECOND ";
using StrUtils::starts_with;
using StrUtils::calen;
using StrUtils::parse_int;
if (ParsePotLine(ln))
return ParseStage::Summary;
if (!starts_with(ln, SEAT_START))
{
return
starts_with(ln, HAND_START) ||
starts_with(ln, BOARD_START) ||
starts_with(ln, FIRST_START) ||
starts_with(ln, SECOND_START) ?
ParseStage::Summary : ParseStage::None;
}
int tr, dr;
std::size_t sIdx = calen(SEAT_START);
auto summSeatIdx = parse_int(ln.c_str() + sIdx, &dr, &tr);
if (dr == 0 || dr > 2 || summSeatIdx < 1 || summSeatIdx > 10)
ThrowFailRead("Seat [Index]", ln);
sIdx += tr + 2;
std::size_t mIdx = ln.find("mucked", sIdx);
if (mIdx == std::string::npos)
return ParseStage::Summary;
mIdx = ln.find_first_of('[', mIdx + 6);
if (mIdx == std::string::npos)
return ParseStage::Summary;
CardSeq cs(CardSeq::FromString(ln.c_str() + mIdx));
if (!cs.Empty())
{
const Seat::Ptr& seat = hh.GetGameStage()->GetSeats().Get(Seats::Index_((summSeatIdx)));
if (seat != nullptr)
AddAction(std::make_shared<HandAction>(HandActionType::MuckHand, seat->GetPlayerName(), cs));
}
return ParseStage::Summary;
}
bool PokerStarsParser::ParsePotLine(const std::string & ln)
{
using StrUtils::calen;
static const char TOTAL_POT[] = "Total pot ";
static const char MAIN_POT[] = "Main pot ";
static const char SIDE_POT[] = "Side pot";
static const char RAKE[] = "Rake ";
auto sIdx = ln.find(TOTAL_POT);
if (sIdx == std::string::npos)
return false;
auto pot = ParseCash(ln.c_str() + sIdx + calen(TOTAL_POT));
if (pot < 0)
ThrowFailRead("Total pot [Amount]", ln);
Pot& handPot = hh.GetGameStage()->GetPot();
if (pot != handPot.GetChips() && !hh.IsCancelled())
{
std::stringstream ss;
ss << "Total pot Value [" << pot << " != " << handPot.GetChips() << "]" << std::endl;
ThrowFailRead(ss.str(), "");
}
auto rIdx = ln.rfind(RAKE);
if (rIdx != std::string::npos)
{
auto rake = ParseCash(ln.c_str() + rIdx + calen(RAKE));
if (rake < 0)
ThrowFailRead("Rake [Amount]", ln);
handPot.SetRake(rake);
}
sIdx = ln.find(MAIN_POT, sIdx + calen(TOTAL_POT));
if (sIdx != std::string::npos)
{
sIdx += calen(MAIN_POT);
int sPot = ParseCash(ln.c_str() + sIdx);
if (sPot < 0)
ThrowFailRead("Main pot [Amount]", ln);
handPot.AddSidePot(sPot);
sIdx = ln.find(SIDE_POT, sIdx);
while (sIdx != std::string::npos)
{
sIdx += calen(SIDE_POT); sIdx = ln.find_first_of(' ', sIdx);
sPot = ParseCash(ln.c_str() + sIdx);
if (sPot < 0)
ThrowFailRead("Side pot [Amount]", ln);
handPot.AddSidePot(sPot);
sIdx = ln.find(SIDE_POT, sIdx);
}
}
return true;
}
bool PokerStarsParser::IsAllInAction(const std::string & ln)
{
static const char ALLIN_END[] = " is all-in";
return ln.rfind(ALLIN_END) != std::string::npos;
}
int PokerStarsParser::GetCapppedAction(const std::string & ln)
{
static const char CAP_[] = "has reached the ";
std::size_t hrtIdx = ln.rfind(CAP_);
if (hrtIdx == std::string::npos)
return 0;
int cap = ParseCash(ln.c_str() + hrtIdx + StrUtils::calen(CAP_));
if (cap < 0)
ThrowFailRead("Cap [Value]", ln);
return cap;
}
}
}<file_sep>/include/handhistory.hpp
#ifndef INCLUDE_HANDHISTORY_H
#define INCLUDE_HANDHISTORY_H
#include <cassert>
#include <memory>
#include <map>
#include <vector>
#include "types.hpp"
#include "cardgame.hpp"
#include "gamesite.hpp"
#include "datetimeutils.hpp"
#include "currency.hpp"
#include "chips.hpp"
#include "gamestagescol.hpp"
#include "handactioncol.hpp"
namespace a2a
{
class HandHistory
{
public:
using Ptr = std::shared_ptr<HandHistory>;
HandHistory();
u64 GetHandId() const;
const std::string& GetHandIdStr() const;
void SetHandId(u64 handId);
void SetHandId(const char* str);
u64 GetTournamentId() const;
const std::string& GetTournamentIdStr() const;
void SetTournamentId(u64 tournamentId);
void SetTournamentId(const char* str);
const CardGameTypeFlags& GetGameType() const;
void SetGameType(const CardGameTypeFlags& gameType);
bool IsGameType(const CardGameTypeFlags& gameType) const;
bool IsGameMode(const CardGameModeFlags& gameModes) const;
void SetGameMode(const CardGameModeFlags& gameModes);
const CardGameModeFlags& GetGameMode() const;
GameSite GetGameSite() const;
const std::string& GetGameSiteStr() const;
void SetGameSite(GameSite gameSite);
void SetGameSite(const char* str);
std::time_t GetDateTimeUTC() const;
const std::time_t* GetDateTimeUTCPtr() const;
TimeZonesType GetTimeZone() const;
void SetDateTimeUTC(std::time_t gmt);
void SetTimeZone(TimeZonesType timeZone);
CurrencyType GetTableCurrency() const;
void SetTableCurrency(CurrencyType currencyType);
CurrencyType GetStacksCurrency() const;
void SetStacksCurrency(CurrencyType currencyType);
void SetBuyin(int prizePool, int rake);
void SetBuyin(int prizePool, int knockOut, int rake);
int GetBuyinRake() const;
int GetBuyinKnockout() const;
int GetBuyinPrizePool() const;
int GetTournamentLevel() const;
void SetTournamentLevel(int level);
int GetSmallBlind() const;
int GetBigBlind() const;
int GetSmallBlindLevel() const;
int GetBigBlindLevel() const;
int GetCap() const;
int GetAnte() const;
void SetSmallBlind(int smallBlind);
void SetBigBlind(int bigBlind);
void SetBlinds(int smallBlind, int bigBlind);
void SetBlindLevels(int smallBlindLvl, int bigBlindLvl);
void SetCap(int cap);
void SetAnte(int ante);
const std::string& GetTableName() const;
void SetTableName(const std::string&);
int GetTableMaxPlayers() const;
void SetTableMaxPlayers(int maxPlayers, bool adjustFromActive = false);
void SetButtonSeatIndex(int seatIdx);
int GetButtonSeatIndex() const;
const GameStage::Ptr& GetGameStage(GameStageType stageType = GameStageType::Current) const;
const GameStages& GetGameStages() const;
void AddSeat(const std::string& playerName, int seatIndex, int stack);
void RemoveSeat(const std::string& playerName);
void AddSeat(const Seat::Ptr& newSeat);
const Seats& GetSeats() const;
void ProcessAction(const HandAction::Ptr& action, GameStageType stageType = GameStageType::Current);
HandActions GetActions() const;
HandActions GetActions(const HandActions::predicate_t& predicate) const;
const std::string& GetHeroName() const;
bool WasRunTwice() const;
bool HasHeader() const;
void SetCancelled();
bool IsCancelled() const;
protected:
//
u64 m_handId;
std::string m_handIdStr;
u64 m_tournamentId;
std::string m_tournamentIdStr;
CardGameTypeFlags m_gameType;
CardGameModeFlags m_gameModeFlags;
GameSite m_gameSite;
std::string m_gameSiteStr;
std::time_t m_handDateTimeUTC;
TimeZonesType m_timeZone;
CurrencyType m_tableCurrency;
CurrencyType m_stacksCurrency;
int m_tournamentLevel;
std::string m_tableName;
//
BuyIn m_buyin;
GameLimit m_limit;
//
int m_maxPlayers;
int m_buttonSeatIndex;
//
bool m_isCancelled;
bool m_wasRunTwice;
//
std::string m_heroName;
//
GameStage::Ptr m_currentStage;
GameStages m_stages;
//
void SwitchCurrentStage(GameStageType To);
};
}
// HandHistory inlines
namespace a2a
{
inline u64 HandHistory::GetHandId() const
{
return m_handId;
}
inline u64 HandHistory::GetTournamentId() const
{
return m_tournamentId;
}
inline const CardGameTypeFlags& HandHistory::GetGameType() const
{
return m_gameType;
}
inline bool HandHistory::IsGameType(const CardGameTypeFlags& gameType) const
{
return (bool)(m_gameType & gameType);
}
inline void HandHistory::SetGameType(const CardGameTypeFlags& gameType)
{
m_gameType |= gameType;
}
inline const CardGameModeFlags& HandHistory::GetGameMode() const
{
return m_gameModeFlags;
}
inline void HandHistory::SetGameMode(const CardGameModeFlags& gameModes)
{
m_gameModeFlags |= gameModes;
}
inline bool HandHistory::IsGameMode(const CardGameModeFlags& gameModes) const
{
return (bool)(m_gameModeFlags & gameModes);
}
inline GameSite HandHistory::GetGameSite() const
{
return m_gameSite;
}
inline std::time_t HandHistory::GetDateTimeUTC() const
{
return m_handDateTimeUTC;
}
inline const std::time_t* HandHistory::GetDateTimeUTCPtr() const
{
return &m_handDateTimeUTC;
}
inline void HandHistory::SetDateTimeUTC(std::time_t gmt)
{
m_handDateTimeUTC = gmt;
}
inline void HandHistory::SetTimeZone(TimeZonesType timeZone)
{
m_timeZone = timeZone;
}
inline TimeZonesType HandHistory::GetTimeZone() const
{
return m_timeZone;
}
inline CurrencyType HandHistory::GetTableCurrency() const
{
return m_tableCurrency;
}
inline void HandHistory::SetTableCurrency(CurrencyType currencyType)
{
m_tableCurrency = currencyType;
m_stacksCurrency = currencyType;
}
inline CurrencyType HandHistory::GetStacksCurrency() const
{
return m_stacksCurrency;
}
inline void HandHistory::SetStacksCurrency(CurrencyType currencyType)
{
m_stacksCurrency = currencyType;
}
inline int HandHistory::GetBuyinRake() const
{
return m_buyin.rake;
}
inline int HandHistory::GetBuyinKnockout() const
{
return m_buyin.knockOut;
}
inline int HandHistory::GetBuyinPrizePool() const
{
return m_buyin.prizePool;
}
inline void HandHistory::SetBuyin(int prizePool, int rake)
{
//assert(
// m_buyin.knockOut == 0 &&
// m_buyin.prizePool == 0 &&
// m_buyin.rake == 0 &&
// "Buyin values already set");
m_buyin.prizePool = prizePool;
m_buyin.rake = rake;
SetGameMode(CardGameMode::BuyIn);
}
inline void HandHistory::SetBuyin(int prizePool, int knockOut, int rake)
{
//assert(
// m_buyin.knockOut == 0 &&
// m_buyin.prizePool == 0 &&
// m_buyin.rake == 0 &&
// "Buyin values already set");
m_buyin.prizePool = prizePool;
m_buyin.rake = rake;
m_buyin.knockOut = knockOut;
SetGameMode(CardGameMode::BuyIn | CardGameMode::BuyInKnockout);
}
inline int HandHistory::GetTournamentLevel() const
{
return m_tournamentLevel;
}
inline void HandHistory::SetTournamentLevel(int level)
{
//assert(m_tournamentLevel == 0 && "TournamentID already set");
m_tournamentLevel = level;
}
inline int HandHistory::GetSmallBlind() const
{
return m_limit.smallBlind;
}
inline int HandHistory::GetBigBlind() const
{
return m_limit.bigBlind;
}
inline int HandHistory::GetSmallBlindLevel() const
{
return m_limit.smallBlindLevel;
}
inline int HandHistory::GetBigBlindLevel() const
{
return m_limit.bigBlindLevel;
}
inline int HandHistory::GetCap() const
{
return m_limit.cap;
}
inline int HandHistory::GetAnte() const
{
return m_limit.ante;
}
inline void HandHistory::SetSmallBlind(int smallBlind)
{
m_limit.smallBlind = smallBlind;
if (m_limit.smallBlindLevel == 0)
m_limit.smallBlindLevel = smallBlind;
}
inline void HandHistory::SetBigBlind(int bigBlind)
{
m_limit.bigBlind = bigBlind;
if (m_limit.bigBlindLevel == 0)
m_limit.bigBlindLevel = bigBlind;
}
inline void HandHistory::SetBlinds(int smallBlind, int bigBlind)
{
SetSmallBlind(smallBlind); SetBigBlind(bigBlind);
}
inline void HandHistory::SetBlindLevels(int smallBlindLvl, int bigBlindLvl)
{
m_limit.bigBlindLevel = bigBlindLvl;
m_limit.smallBlindLevel = smallBlindLvl;
}
inline void HandHistory::SetCap(int cap)
{
m_limit.cap = cap;
SetGameMode(CardGameMode::Cap);
}
inline void HandHistory::SetAnte(int ante)
{
m_limit.ante = ante;
SetGameMode(CardGameMode::Ante);
}
inline const std::string& HandHistory::GetTableName() const
{
return m_tableName;
}
inline void HandHistory::SetTableName(const std::string& tableName)
{
m_tableName = tableName;
}
inline int HandHistory::GetTableMaxPlayers() const
{
return m_maxPlayers;
}
inline int HandHistory::GetButtonSeatIndex() const
{
return m_buttonSeatIndex;
}
inline void HandHistory::SetCancelled()
{
m_isCancelled = true;
}
inline bool HandHistory::IsCancelled() const
{
return m_isCancelled;
}
inline const std::string & HandHistory::GetHeroName() const
{
return m_heroName;
}
inline bool HandHistory::WasRunTwice() const
{
return m_wasRunTwice;
}
inline bool HandHistory::HasHeader() const
{
return m_handId != 0 &&
m_gameType != CardGameType::Unknown &&
m_gameModeFlags != CardGameMode::Unknown &&
m_maxPlayers != 0;
}
}
#endif<file_sep>/tests/pokerstarstests.cpp
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <array>
#include <deque>
#include <forward_list>
#include <list>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <memory>
#include <chrono>
#include <ctime>
//#define private public
#ifdef _MSC_VER
#pragma warning (disable: 4996)
#endif
#include "strutils.hpp"
#include "handhistory.hpp"
#include "hhconverters.hpp"
#include "hhconverter_ps.hpp"
#include "hhparsers.hpp"
#include "hhparser_ps.hpp"
#include "collection.hpp"
#include "fsysutils.hpp"
#include "filescol.hpp"
#include "hhreader.hpp"
static bool bugsBugsBugs = false;
//TEST_CASE("PokerStars Parser: BUGS")
//{
// using namespace a2a;
//
//#ifndef _MSC_VER
// return;
//#endif
//
// auto parsers = HandHistoryParsersFactory();
// auto converters = HandHistoryConvertersFactory();
//
// PokerStars::HHParserSettings psets;
// auto pp = parsers.GetParserBySite("ps", psets);
//
// PokerStars::HHConverterSettings csets;
// auto pe = converters.GetConverterBySite("ps", csets);
//
// int ftotal = 0; int htotal = 0;
//
// auto s = _searchPath("tests/hh/ps/bugs", 4);
// REQUIRE_FALSE(s.empty());
// auto dir = Directory::Open(s, true);
// FilesCollection files;
//
// while (dir->HasFilesToProcess())
// {
// dir->GetFiles(files, 6);
//
// ftotal += files.Size();
//
// HandHistory hh;
// std::string buff;
// for (const auto& f : files)
// {
//
// std::cout << ">" << f->GetFullPath() << std::endl;
// f->Read(buff);
// HandHistoryParseHelper hp(pp, buff);
// while (hp.Next())
// {
// HandHistory hh;
// try
// {
//
// hp.Parse(hh);
// htotal++;
// }
// catch (const std::exception& err)
// {
// std::cout << "ID:" << hh.GetHandId() << " ERRROR: " << err.what() << std::endl
// << "***********************************************" << std::endl;
// bugsBugsBugs = true;
// }
// }
// std::cout << "ok" << std::endl << std::endl;
// }
//
// files.Clear();
// }
//
// std::cout << "TOTAL FILES: " << ftotal << std::endl;
// std::cout << "TOTAL HANDS: " << htotal << std::endl;
//}
TEST_CASE("PokerStars Parser")
{
using namespace a2a;
if (bugsBugsBugs) return;
//auto parsers = HandHistoryParsersFactory();
auto converters = HandHistoryConvertersFactory();
//auto pp = parsers.GetParserBySite("pacific");
auto pe = converters.GetConverterBySite("ps");
int ftotal = 0; int htotal = 0;
//auto s = _searchPath("tests/hh/ps/bugs", 4);
//auto s = _searchPath("tests/hh/ps", 4);
auto s = _searchPath("tests/hh/pacific/gametype", 4);
//auto s = _searchPath("tests/hh/pacific/bugs", 4);
std::ofstream out("d:\\projects\\1.txt", std::ios::binary);
#ifdef _MSC_VER
//auto dir = Directory::Open("D:\\projects\\SampleHandHistories\\PokerStars\\CashGame", true);
auto dir = Directory::Open("D:\\projects\\SampleHandHistories\\Pacific", true);
//auto dir = Directory::Open(s, true);
#else
auto dir = Directory::Open("/media/sf_projects/SampleHandHistories/PokerStars/CashGame", true);
#endif
FilesCollection files;
while (dir->HasFilesToProcess())
{
dir->GetFiles(files, 6);
ftotal += files.Size();
HandHistory hh;
std::string buff;
for (const auto& f : files)
{
//std::cout << ">" << f->GetFullPath() << std::endl;
f->Read(buff);
try
{
HandHistoryReader hp(buff);
while (hp.Next())
{
HandHistory hh;
try
{
hp.Parse(hh);
if (s.find("bugs")!=std::string::npos)
{
pe->Convert(std::cout, hh);
std::cout << std::endl << std::endl;
}
else
{
//pe->Convert(out, hh);
//out << std::endl << std::endl;
}
// std::cout << hh.GetHandId() << std::endl;
// htotal++;
}
catch (const std::exception& err)
{
std::cout << f->GetFullPath() << std::endl;
std::cout << "ID:" << hh.GetHandId() << " ERRROR: " << err.what() << std::endl
<< "***********************************************" << std::endl;
//throw;
bugsBugsBugs = true;
}
}
htotal += hp.GetTotalParsed();
}
catch (const std::exception& err)
{
std::cout << err.what() << std::endl;
continue;
}
// std::cout << "ok" << std::endl << std::endl;
}
files.Clear();
}
std::cout << "TOTAL FILES: " << ftotal << std::endl;
std::cout << "TOTAL HANDS: " << htotal << std::endl;
}
#ifdef _MSC_VER
#pragma warning (default: 4996)
#endif
<file_sep>/addons/a2ahhparsers.lua
A2AParsers = {}
class "A2ALineParserBase"
function A2ALineParserBase:setup(x)
self.handHistory = HandHistory:new(x)
end
function A2ALineParserBase:error_msg()
return self.err or "Unexpected parsing error"
end
function A2ALineParserBase:error(x)
self.err = x; return -1
end
function A2ALineParser(n,v,d)
class (n, RegisterA2AObject(A2AParsers, "A2ALineParser", v, d)) ("A2ALineParserBase")
end
<file_sep>/src/hhparsers.cxx
#include <cassert>
#include "hhparsers.hpp"
#include "hhparser_ps.hpp"
#include "hhparser_pac.hpp"
#ifdef A2A_LUA
#include "fsysutils.hpp"
#include "filescol.hpp"
#include "lualineparser.hpp"
#endif
namespace a2a
{
//
static const std::string MANIFEST = "A2AParsers";
// core plugins
static const std::string clsName_PokerStars(GameSiteUtils::GameSiteToString(GameSite::PokerStars));
static const std::string clsName_Pacific(GameSiteUtils::GameSiteToString(GameSite::Pacific));
static const std::string clsName_Lotos(GameSiteUtils::GameSiteToString(GameSite::Lotos));
static const std::string clsName_Cassava("Cassava");
static const std::string clsName_LuckyAce("LuckyAce");
HandHistoryParsersFactory::HandHistoryParsersFactory()
: TBasePluginFactory(MANIFEST)
, m_bCoreLoaded(false)
#ifdef A2A_LUA
, m_luaState(LuaState::Global())
, m_bLuaLoaded(false)
#endif
{
}
HandHistoryParsersFactory::HandHistoryParsersFactory(const HandHistoryParserSettings& defSettings)
: TBasePluginFactory(MANIFEST), m_defaultSettings(defSettings)
, m_bCoreLoaded(false)
#ifdef A2A_LUA
, m_luaState(LuaState::Global())
, m_bLuaLoaded(false)
#endif
{
}
#ifdef A2A_LUA
HandHistoryParsersFactory::HandHistoryParsersFactory(LuaState & state)
: TBasePluginFactory(MANIFEST)
, m_bCoreLoaded(false)
, m_luaState(state)
, m_bLuaLoaded(false)
{
}
HandHistoryParsersFactory::HandHistoryParsersFactory(LuaState & state, const HandHistoryParserSettings & defSettings)
: TBasePluginFactory(MANIFEST), m_defaultSettings(defSettings)
, m_bCoreLoaded(false)
, m_luaState(state)
, m_bLuaLoaded(false)
{
}
#endif
HandHistoryParser::Ptr HandHistoryParsersFactory::GetParser(const std::string& parserName)
{
LoadCoreParsers();
if (HasClass(parserName))
{
HandHistoryParser::Ptr x(Create(parserName));
x->SetupParser(GetDefaultSettings());
return x;
}
#ifdef A2A_LUA
LoadLuaParsers();
#endif
return nullptr;
}
HandHistoryParser::Ptr HandHistoryParsersFactory::GetParser(GameSite gameSite)
{
switch (gameSite)
{
case GameSite::PokerStars:
case GameSite::PokerStarsEs:
case GameSite::PokerStarsFr:
case GameSite::PokerStarsIt:
return GetParser(clsName_PokerStars);
case GameSite::Pacific:
return GetParser(clsName_Pacific);
case GameSite::Lotos:
return GetParser(clsName_Lotos);
default:
return GetParser(GameSiteUtils::GameSiteToString(gameSite));
}
}
HandHistoryParser::Ptr HandHistoryParsersFactory::GetParserBySite(const std::string& siteName)
{
return GetParser( GameSiteUtils::GameSiteFromString(siteName) );
}
#ifdef A2A_LUA
HandHistoryParser::Ptr HandHistoryParsersFactory::CreateParser(const LuaAddon& addon) const
{
if (addon.type == "A2ALineParser")
return std::make_shared<LuaLineParser>(m_luaState, addon);
return nullptr;
}
#endif
HandHistoryParser::Ptr HandHistoryParsersFactory::FindParser(const char * memBlock, std::size_t size)
{
LoadCoreParsers();
for (const auto& obj : GetMetaCollection())
{
auto parser = GetParser(obj->Name());
if (parser->Next(memBlock, memBlock+size) != nullptr) return parser;
}
#ifdef A2A_LUA
LoadLuaParsers();
if (!m_luaState.HasAddons(m_manifestName))
return nullptr;
auto& addons(m_luaState.GetAddons(m_manifestName));
for (const auto& i : addons)
{
auto parser = CreateParser(i);
if (parser && parser->Next(memBlock, memBlock + size) != nullptr)
{
return parser;
}
}
#endif
return nullptr;
}
void HandHistoryParsersFactory::LoadCoreParsers()
{
if (m_bCoreLoaded)
return;
if (!HasClass(clsName_PokerStars))
Register<PokerStars::HHParser>(clsName_PokerStars);
if (!HasClass(clsName_Pacific))
Register<Pacific::HHParser888>(clsName_Pacific);
if (!HasClass(clsName_Lotos))
Register<Pacific::HHParserLotos>(clsName_Lotos);
if (!HasClass(clsName_Cassava))
Register<Pacific::HHParserCassava>(clsName_Cassava);
if (!HasClass(clsName_LuckyAce))
Register<Pacific::HHParserLuckyAce>(clsName_LuckyAce);
m_bCoreLoaded = true;
}
HandHistoryParsersFactory& HandHistoryParsersFactory::Global()
{
static HandHistoryParsersFactory obj;
return obj;
}
#ifdef A2A_LUA
void HandHistoryParsersFactory::LoadLuaParsers(const std::string & dir)
{
if (m_bLuaLoaded)
return;
m_bLuaLoaded = true;
if (m_luaState.HasAddons(m_manifestName))
return;
auto path = !dir.empty() ? dir : _searchPath("addons/parsers/", 4);
auto d = Directory::Open(path);
LuaAddonsVec parsers;
m_luaState.UploadAddons(m_manifestName, parsers);
if (!d->HasFilesToProcess())
return;
m_luaState.LoadSubmodule(LuaSubmodule::parsers);
for (const auto& f: d->GetFiles().Select(FilesCollection::HasExtension_(".lua")) )
{
std::string buff;
f->Read(buff);
if (buff.empty()) continue;
std::string err;
m_luaState.RunBuffer(&buff[0], buff.size(), err, f->GetPath());
// if (!err.empty())
// throw LuaError(err);
}
lua_State *L(m_luaState.luaState());
lua_getglobal(L, m_manifestName.c_str());
if (!lua_istable(L, -1))
{
lua_pop(L, 1);
m_luaState.UploadAddons(m_manifestName, parsers);
return;
}
lua_pushnil(L);
while (lua_next(L, -2) != 0)
{
LuaAddon addon;
lua_pushvalue(L, -2);
addon.name.assign(lua_tostring(L, -1));
lua_getfield(L, -2, "type");
addon.type.assign(lua_tostring(L, -1));
lua_pop(L, 1);
lua_getfield(L, -2, "version");
addon.version = Version(lua_tonumber(L, -1));
lua_pop(L, 1);
lua_getfield(L, -2, "desc");
addon.description.assign(lua_tostring(L, -1));
lua_pop(L, 1);
lua_pop(L, 2);
parsers.push_back(addon);
}
lua_pop(L, 1);
m_luaState.UploadAddons(m_manifestName, parsers);
}
#endif
/////////////////////////////
}
<file_sep>/src/hhreader.cxx
#include "hhreader.hpp"
namespace a2a
{
HandHistoryReader::HandHistoryReader(const HandHistoryParser::Ptr& parser, const std::string& s) :
m_parser(parser),
m_beg(StdUtils::begin_ptr(s)),
m_cursor(StdUtils::begin_ptr(s)),
m_end(StdUtils::end_ptr(s)),
m_total(0)
{}
HandHistoryReader::HandHistoryReader(const HandHistoryParser::Ptr& parser, const void* mem, std::size_t size) :
m_parser(parser),
m_beg(static_cast<const char*>(mem)),
m_cursor(static_cast<const char*>(mem)),
m_end(static_cast<const char*>(mem) + size),
m_total(0)
{}
HandHistoryReader::HandHistoryReader(HandHistoryParsersFactory & parsers, const std::string & s)
:
m_beg(StdUtils::begin_ptr(s)),
m_cursor(StdUtils::begin_ptr(s)),
m_end(StdUtils::end_ptr(s)),
m_total(0)
{
FindParser(parsers);
}
HandHistoryReader::HandHistoryReader(HandHistoryParsersFactory & parsers, const void * mem, std::size_t size)
:
m_beg(static_cast<const char*>(mem)),
m_cursor(static_cast<const char*>(mem)),
m_end(static_cast<const char*>(mem) + size),
m_total(0)
{
FindParser(parsers);
}
HandHistoryReader::HandHistoryReader(const std::string & s)
:
m_beg(StdUtils::begin_ptr(s)),
m_cursor(StdUtils::begin_ptr(s)),
m_end(StdUtils::end_ptr(s)),
m_total(0)
{
FindParser(HandHistoryParsersFactory::Global());
}
HandHistoryReader::HandHistoryReader(const void * mem, std::size_t size)
:
m_beg(static_cast<const char*>(mem)),
m_cursor(static_cast<const char*>(mem)),
m_end(static_cast<const char*>(mem) + size),
m_total(0)
{
FindParser(HandHistoryParsersFactory::Global());
}
void HandHistoryReader::FindParser(HandHistoryParsersFactory& factory)
{
m_parser = factory.FindParser(m_beg, m_end - m_beg);
}
bool HandHistoryReader::Next()
{
if (!m_parser)
return false;
m_cursor = m_parser->Next(m_cursor, m_end);
return m_cursor != nullptr;
}
void HandHistoryReader::Parse(HandHistory& hh)
{
if (!m_parser)
return;
try
{
m_cursor = m_parser->Parse(m_cursor, m_end, hh);
m_total++;
}
catch (const ParseError& err)
{
m_cursor = err.cursor;
throw;
}
}
HandHistory HandHistoryReader::Parse()
{
HandHistory ret;
Parse(ret);
return ret;
}
void HandHistoryReader::Reset()
{
m_cursor = m_beg;
m_total = 0;
}
const char* HandHistoryReader::Last()
{
return m_parser->Last(m_cursor, m_end);
}
}
<file_sep>/src/hhbindc.cxx
#include <string>
#include <cassert>
#include "hhbindc.h"
#include "handhistory.hpp"
#include "strutils.hpp"
using namespace a2a;
#ifdef _MSC_VER
#pragma warning (disable: 4996)
#endif
void* hh_new() {
return new HandHistory();
}
void hh_delete(void* p) {
delete static_cast<HandHistory*>(p);
}
void hh_set_handid(void* p, const char* s) {
static_cast<HandHistory*>(p)->SetHandId(s);
}
const char* hh_get_handid(void* p) {
return static_cast<HandHistory*>(p)->GetHandIdStr().c_str();
}
void hh_set_tournid(void* p, const char* s) {
static_cast<HandHistory*>(p)->SetTournamentId(s);
}
const char* hh_get_tournid(void* p) {
return static_cast<HandHistory*>(p)->GetTournamentIdStr().c_str();
}
void hh_set_gametype(void* p, unsigned int t) {
CardGameTypeFlags f; f.set_underlying_value(t);
static_cast<HandHistory*>(p)->SetGameType(f);
}
unsigned int hh_get_gametype(void* p) {
return static_cast<HandHistory*>(p)->GetGameType().underlying_value();
}
void hh_get_gametype_str(unsigned int t, char* p, int z)
{
CardGameTypeFlags f; f.set_underlying_value(t);
auto s = GameTypeUtils::CardGameTypeToStr(f);
std::strncpy(p, s.c_str(), z - 1); p[z - 1] = 0;
}
void hh_set_gamemode(void* p, unsigned int t) {
CardGameModeFlags f; f.set_underlying_value(t);
static_cast<HandHistory*>(p)->SetGameMode(f);
}
unsigned int hh_get_gamemode(void* p) {
return static_cast<HandHistory*>(p)->GetGameMode().underlying_value();
}
void hh_set_gamesite(void* p, const char* s) {
static_cast<HandHistory*>(p)->SetGameSite(s);
}
const char* hh_get_gamesite(void* p) {
return static_cast<HandHistory*>(p)->GetGameSiteStr().c_str();
}
void hh_set_datetime(void* p, double t) {
static_cast<HandHistory*>(p)->SetDateTimeUTC(static_cast<std::time_t>(t));
}
double hh_get_datetime(void* p) {
return static_cast<double>( static_cast<HandHistory*>(p)->GetDateTimeUTC() );
}
double _get_tzabbroffset(const char* s) {
return static_cast<double>( DateTimeUtils::GetTimeZoneOffset(DateTimeUtils::TimeZoneFromAbbreviation(s)) );
}
void hh_set_timezone(void* p, const char* s) {
static_cast<HandHistory*>(p)->SetTimeZone(DateTimeUtils::TimeZoneFromAbbreviation(s));
}
const char* hh_get_timezone(void* p) {
return DateTimeUtils::TimeZoneToAbbreviation( static_cast<HandHistory*>(p)->GetTimeZone() );
}
void hh_set_currency(void* p, unsigned int c) {
static_cast<HandHistory*>(p)->SetTableCurrency(
static_cast<CurrencyType>(c));
}
unsigned int _get_currencyfromstr(const char* s) {
return static_cast<unsigned int>(CurrencyUtils::CurrencyTypeFromShortStr(s));
}
const char* _get_currency_str(unsigned int v) {
return CurrencyUtils::CurrencyTypeToShortStr(static_cast<CurrencyType>(v));
}
unsigned int hh_get_currency(void* p) {
return static_cast<unsigned int>(static_cast<HandHistory*>(p)->GetTableCurrency());
}
void hh_set_stackscurrency(void* p, unsigned int c) {
static_cast<HandHistory*>(p)->SetStacksCurrency(
static_cast<CurrencyType>(c));
}
unsigned int hh_get_stackscurrency(void* p) {
return static_cast<unsigned int>(static_cast<HandHistory*>(p)->GetStacksCurrency());
}
void hh_set_tournlvl(void* p, int i) {
static_cast<HandHistory*>(p)->SetTournamentLevel(i);
}
int hh_get_tournlvl(void* p) {
return static_cast<HandHistory*>(p)->GetTournamentLevel();
}
int _roman_to_int(const char* s) {
return StrUtils::parse_roman_invert<const char*, int>(s - 1, s + strlen(s) - 1);
}
void _int_to_roman(int r, char* p, int z) {
auto s = StrUtils::int_to_roman(r);
std::strncpy(p, s.c_str(), z - 1); p[z - 1] = 0;
}
void hh_set_buyin(void* p, int pr, int k, int r) {
static_cast<HandHistory*>(p)->SetBuyin(pr, k, r);
}
int hh_get_buyin_rake(void* p) {
return static_cast<HandHistory*>(p)->GetBuyinRake();
}
int hh_get_buyin_prizepool(void* p) {
return static_cast<HandHistory*>(p)->GetBuyinPrizePool();
}
int hh_get_buyin_knockout(void* p) {
return static_cast<HandHistory*>(p)->GetBuyinKnockout();
}
void hh_set_ante(void* p, int v) {
static_cast<HandHistory*>(p)->SetAnte(v);
}
int hh_get_ante(void* p) {
return static_cast<HandHistory*>(p)->GetAnte();
}
void hh_set_cap(void* p, int v) {
static_cast<HandHistory*>(p)->SetCap(v);
}
int hh_get_cap(void* p) {
return static_cast<HandHistory*>(p)->GetCap();
}
void hh_set_blinds(void* p, int s, int b) {
static_cast<HandHistory*>(p)->SetBlinds(s,b);
}
int hh_get_bb(void* p) {
return static_cast<HandHistory*>(p)->GetBigBlind();
}
int hh_get_sb(void* p) {
return static_cast<HandHistory*>(p)->GetSmallBlind();
}
void hh_set_blindlvls(void* p, int s, int b){
static_cast<HandHistory*>(p)->SetBlindLevels(s, b);
}
int hh_get_bbl(void* p) {
return static_cast<HandHistory*>(p)->GetBigBlindLevel();
}
int hh_get_sbl(void* p) {
return static_cast<HandHistory*>(p)->GetSmallBlindLevel();
}
void hh_set_tablename(void* p, const char* s) {
static_cast<HandHistory*>(p)->SetTableName(s);
}
const char* hh_get_tablename(void* p) {
return static_cast<HandHistory*>(p)->GetTableName().c_str();
}
void hh_set_maxplayers(void* p, int v) {
static_cast<HandHistory*>(p)->SetTableMaxPlayers(v);
}
int hh_get_maxplayers(void* p) {
return static_cast<HandHistory*>(p)->GetTableMaxPlayers();
}
void hh_set_button(void* p, int v) {
static_cast<HandHistory*>(p)->SetButtonSeatIndex(v);
}
int hh_get_button(void* p) {
return static_cast<HandHistory*>(p)->GetButtonSeatIndex();
}
void hh_set_cancelled(void* p) {
static_cast<HandHistory*>(p)->SetCancelled();
}
int hh_is_cancelled(void* p) {
return static_cast<HandHistory*>(p)->IsCancelled() ? 1 : 0;
}
const char* hh_get_hero(void* p) {
return static_cast<HandHistory*>(p)->GetHeroName().c_str();
}
int hh_is_runtwice(void* p) {
return static_cast<HandHistory*>(p)->WasRunTwice() ? 1 : 0;
}
int hh_has_header(void* p) {
return static_cast<HandHistory*>(p)->HasHeader() ? 1 : 0;
}
int hh_add_seat(void* p, const char* n, int i, int s) {
try
{
static_cast<HandHistory*>(p)->AddSeat(n, i, s);
return 1;
}
catch(...)
{
}
return 0;
}
void* hh_get_seat(void* p, int i)
{
const Seats& seats = static_cast<HandHistory*>(p)->GetSeats();
return static_cast<std::size_t>(i) < seats.Size() ? seats[static_cast<std::size_t>(i)].get() : NULL;
}
int hh_get_seats_num(void* p)
{
return static_cast<int> (static_cast<HandHistory*>(p)->GetSeats().Size());
}
int seat_get_idx(void* p) {
return static_cast<Seat*>(p)->GetIndex();
}
const char* seat_get_playername(void* p) {
return static_cast<Seat*>(p)->GetPlayerName().c_str();
}
int seat_get_stack(void* p) {
return static_cast<Seat*>(p)->GetStack();
}
void seat_set_stack(void* p, int v) {
static_cast<Seat*>(p)->SetStack(v);
}
int seat_get_startstack(void* p) {
return static_cast<Seat*>(p)->GetStartStack();
}
void seat_set_startstack(void* p, int v) {
static_cast<Seat*>(p)->SetStartStack(v);
}
unsigned int seat_get_pos(void* p) {
return static_cast<unsigned int> ( static_cast<Seat*>(p)->GetPosition() );
}
int seat_is_fold(void* p) {
return static_cast<Seat*>(p)->IsFold() ? 1 : 0;
}
int seat_is_allin(void* p){
return static_cast<Seat*>(p)->IsAllIn() ? 1 : 0;
}
int seat_get_stake(void* p) {
return static_cast<Seat*>(p)->GetStake().chips;
}
void * seat_get_cards(void * p)
{
return const_cast<void*> ( reinterpret_cast<const void*> ( &( static_cast<Seat*>(p)->GetCards() ) ) );
}
const char* _get_pos_str(unsigned int v) {
return PokerPositionUtils::PokerPosToShortStr(static_cast<PokerPosition>(v)).c_str();
}
void* cards_new(const char* s) {
return s == NULL ? new CardSeq() : new CardSeq(s);
}
void cards_delete(void* p) {
delete static_cast<CardSeq*>(p);
}
int cards_size(void* p) {
return static_cast<CardSeq*>(p)->Size();
}
int cards_visible(void* p) {
return static_cast<CardSeq*>(p)->VisibleCards();
}
void cards_set_evalhint(void* p, const char* s) {
static_cast<CardSeq*>(p)->SetEvalHint(s);
}
const char* cards_get_evalhint(void* p) {
return static_cast<CardSeq*>(p)->GetEvalHint().c_str();
}
void cards_str(void* p, const char* f, char* s, int z) {
auto str ( static_cast<CardSeq*>(p)->ToString(f) );
std::strncpy(s, str.c_str(), z - 1); s[z - 1] = 0;
}
int
hh_add_action(void* p, unsigned int type, const char* player, int cash, void* cards, unsigned int stage, unsigned int stageTo)
{
try
{
HandActionTypeFlags f; f.set_underlying_value(type);
auto act = std::make_shared<HandAction>(f);
if (player != NULL)
act->SetPlayerName(player);
if (cash)
act->SetChips(cash);
if (stage)
act->SetStageType(static_cast<GameStageType>(stage));
if (cards)
act->SetCards( *static_cast<CardSeq*>(cards) );
static_cast<HandHistory*>(p)->ProcessAction(act, static_cast<GameStageType>(stageTo) );
return 1;
}
catch (...)
{
}
return 0;
}
void* hh_get_stage(void* p, unsigned int st) {
return static_cast<HandHistory*>(p)->GetGameStage(static_cast<GameStageType>(st)).get();
}
void* hh_get_istage(void* p, int i) {
const GameStages& s(static_cast<HandHistory*>(p)->GetGameStages());
return i >= 0 && i < static_cast<int>(s.Size()) ? s[static_cast<std::size_t>(i)].get() : NULL;
}
int hh_get_stages_num(void* p) {
return static_cast<int>( static_cast<HandHistory*>(p)->GetGameStages().Size() );
}
void* hh_get_iaction(void* p, int i) {
const HandActions& s(static_cast<HandHistory*>(p)->GetActions());
return i >= 0 && i < static_cast<int>(s.Size()) ? s[static_cast<std::size_t>(i)].get() : NULL;
}
int hh_get_actions_num(void* p) {
return static_cast<int>(static_cast<HandHistory*>(p)->GetActions().Size());
}
unsigned int stage_get_type(void* p) {
return static_cast<unsigned int>( static_cast<GameStage*>(p)->GetType() );
}
void* stage_get_seat(void* p, int i) {
const Seats& seats = static_cast<GameStage*>(p)->GetSeats();
return static_cast<std::size_t>(i) < seats.Size() ? seats[static_cast<std::size_t>(i)].get() : NULL;
}
int stage_get_seats_num(void* p) {
return static_cast<int> (static_cast<GameStage*>(p)->GetSeats().Size());
}
void* stage_get_board(void* p) {
return const_cast<CardSeq*> (static_cast<const CardSeq*>( ( &(static_cast<GameStage*>(p)->GetBoard()) ) ));
}
void* stage_get_pot(void* p) {
return static_cast<Pot*>((&(static_cast<GameStage*>(p)->GetPot())));
}
void* stage_get_action(void* p, int i) {
const HandActions& acts = static_cast<GameStage*>(p)->GetActions();
return static_cast<std::size_t>(i) < acts.Size() ? acts[static_cast<std::size_t>(i)].get() : NULL;
}
int stage_get_actions_num(void* p) {
return static_cast<int>(static_cast<GameStage*>(p)->GetActions().Size());
}
int pot_get_chips(void * p)
{
return static_cast<Pot*>(p)->GetChips();
}
void pot_set_rake(void *p, int c)
{
static_cast<Pot*>(p)->SetRake(c);
}
int pot_get_rake(void *p)
{
return static_cast<Pot*>(p)->GetRake();
}
void pot_add_sidepot(void * p, int sp)
{
static_cast<Pot*>(p)->AddSidePot(sp);
}
int pot_get_sidepots_num(void *p)
{
return static_cast<Pot*>(p)->GetSidePotsNum();
}
int pot_get_sidepot(void * p, int i)
{
return static_cast<Pot*>(p)->GetSidePot(i);
}
unsigned int act_get_type(void * p)
{
return static_cast<HandAction*>(p)->GetActionTypeFlags().underlying_value();
}
const char * act_get_type_str(unsigned int i)
{
HandActionTypeFlags f; f.set_underlying_value(i);
return HandActionUtils::ActionTypeStr(f);
}
void act_set_chips(void * p, int c)
{
static_cast<HandAction*>(p)->SetChips(c);
}
int act_get_chips(void * p)
{
return static_cast<HandAction*>(p)->GetChips();
}
int act_get_raiseup(void *p)
{
return static_cast<HandAction*>(p)->GetRaiseUp();
}
int act_get_raiseto(void *p)
{
return static_cast<HandAction*>(p)->GetRaiseTo();
}
void act_set_player(void *p, const char *s)
{
static_cast<HandAction*>(p)->SetPlayerName(s);
}
const char * act_get_player(void *p)
{
return static_cast<HandAction*>(p)->GetPlayerName().c_str();
}
void act_set_stage_type(void * p, unsigned int s)
{
static_cast<HandAction*>(p)->SetStageType( static_cast<GameStageType>(s));
}
unsigned int act_get_stage_type(void *p)
{
return static_cast<unsigned int>( static_cast<HandAction*>(p)->GetStageType() );
}
void * act_get_cards(void *p)
{
return static_cast<CardSeq*>(&(static_cast<HandAction*>(p)->GetCards()));
}
void act_set_cards(void *p, void *c)
{
static_cast<HandAction*>(p)->SetCards( *(static_cast<CardSeq*>(c)) );
}
const char * act_get_prop(void *p, const char *k)
{
return static_cast<HandAction*>(p)->HasProperty(k) ?
static_cast<HandAction*>(p)->GetProperty(k).c_str() :
NULL;
}
void act_set_prop(void *p, const char *k, const char *v)
{
static_cast<HandAction*>(p)->SetProperty(k, v==NULL?"":v);
}
const char* stage_get_type_str(unsigned int gs) {
return GameStageUtils::GameStageToString( static_cast<GameStageType>( gs ));
}
#ifdef _MSC_VER
#pragma warning (default: 4996)
#endif
<file_sep>/include/pluginfactory.hpp
#ifndef INCLUDE_PLUGINFACTORY_H
#define INCLUDE_PLUGINFACTORY_H
#include <memory>
#include <map>
#include "metafactory.hpp"
#include "collection.hpp"
#include "stdutils.hpp"
namespace a2a
{
template<typename P> class PluginFactory : public MetaFactory<P>
{
public:
using TMetaFactory = MetaFactory<P>;
using TMetaFactory::TMetaFactory;
using TMetaFactory::m_manifest;
PluginFactory(const std::string& pluginCategory) : TMetaFactory(pluginCategory) {}
class MetaCollection : public Collection<typename TMetaFactory::baseobj_type, MetaCollection>
{
};
MetaCollection GetMetaCollection() const
{
using namespace StdUtils;
MetaCollection ret;
for (const auto& i : m_manifest)
ret.Add(i.second);
return ret;
}
};
}
#endif
<file_sep>/src/handaction.cxx
#include <iterator>
#include <algorithm>
#include <functional>
#include "handaction.hpp"
#include "seat.hpp"
#include "gamestage.hpp"
namespace a2a
{
HandAction::HandAction(const HandActionTypeFlags& actionType)
: m_type(actionType), m_chips(0), m_stageType(GameStageType::Current), m_raiseUp(0), m_raiseTo(0)
{
}
HandAction::HandAction(const HandActionTypeFlags& actionType, const std::string& playerName, int chips)
: m_type(actionType), m_playerName(playerName), m_chips(chips), m_stageType(GameStageType::Current), m_raiseUp(0), m_raiseTo(0)
{
}
HandAction::HandAction(const HandActionTypeFlags& actionTypeFlags, GameStageType stageSwitch, const CardSeq& cards)
: m_type(actionTypeFlags), m_stageType(stageSwitch), m_chips(0),m_cards(cards), m_raiseUp(0), m_raiseTo(0)
{
}
HandAction::HandAction(const HandActionTypeFlags& actionTypeFlags,
const std::string& playerName, const CardSeq& cards)
: m_type(actionTypeFlags), m_playerName(playerName), m_chips(0), m_cards(cards), m_stageType(GameStageType::Current), m_raiseUp(0), m_raiseTo(0)
{
}
void HandAction::SetProperty(const std::string & key, const std::string & value)
{
m_properties[key] = value;
}
const std::string & HandAction::GetProperty(const std::string & key)
{
static const std::string _empty = "";
auto i = m_properties.find(key);
return i == m_properties.end() ? _empty : i->second;
}
bool HandAction::HasProperty(const std::string & key)
{
return m_properties.find(key)!=m_properties.end();
}
void HandAction::SetGameStage(const std::shared_ptr<GameStage>& hh_stage)
{
m_stageType = hh_stage->GetType();
}
void HandAction::CopySeat(const SeatPtr & seat)
{
if (seat)
m_seat = std::make_shared<Seat>(*seat);
else
m_seat.reset();
}
namespace HandActionUtils
{
const char* ActionTypeStr(const HandActionTypeFlags& actionType)
{
auto trash(HandActionTypeFlags(
HandActionType::AllIn|
HandActionType::Cap|
HandActionType::_ForceUncalledBet|
HandActionType::_RaiseUpAdjust|
HandActionType::_UncalledBetAdjust|
HandActionType::_Hidden
));
HandActionType at = static_cast<HandActionType>((actionType & ~trash).underlying_value());
switch (at)
{
case HandActionType::SmallBlind: return "Small Blind";
case HandActionType::BigBlind: return "Big Blind";
case HandActionType::SmallAndBigBlind: return "Small&Big Blind";
case HandActionType::Ante: return "Ante";
case HandActionType::Return: return "Return/Uncalled";
case HandActionType::Fold: return "Fold";
case HandActionType::Check: return "Check";
case HandActionType::Call: return "Call";
case HandActionType::BringIn: return "BringIn";
case HandActionType::Bet: return "Bet";
case HandActionType::Raise: return "Raise";
case HandActionType::Collected: return "Collected/Win";
case HandActionType::MuckHand: return "MuckHand";
case HandActionType::ShowHand: return "ShowHand";
case HandActionType::Street: return "Street";
case HandActionType::CardsDealt: return "CardsDealt";
case HandActionType::CardsDiscard: return "CardsDiscard";
case HandActionType::DeckReshuffle: return "DeckReshuffle";
case HandActionType::BettingCapped: return "BettingCapped";
case HandActionType::PairOnBoard : return "PairOnBoard";
default:
return "Unknown";
}
}
}
}<file_sep>/src/hhfilesreader.cxx
#include <cstring>
#include <string>
#include "hhfilesreader.hpp"
namespace a2a
{
HandHistoryFilesReader::HandHistoryFilesReader(factory_t& factory, files_t& files, std::size_t testBlockSize)
{
//files.Visit(files_t::MakeCache_(TEST_BLOCK_SIZE));
std::string buff;
std::unordered_map<HandHistoryParser::Ptr, FilesCollection> tmp;
for (const auto& f : files)
{
f->Read(buff, TEST_BLOCK_SIZE);
auto parser = factory.FindParser(buff);
if (parser)
tmp[parser].Add(f);
}
for (const auto& i : tmp)
m_map.emplace( i.first, std::make_shared<reader_t>(i.second) );
//for (const auto& obj : factory.GetMetaCollection())
//{
// auto parser = factory.GetParser(obj->Name());
// auto sfiles = files.Select(files_t::HasHands_(parser, TEST_BLOCK_SIZE));
// if (sfiles.Size() > 0)
// m_map[parser] = std::make_shared<reader_t>(sfiles);
//}
//files.Visit(files_t::ClearCache_());
m_current = m_map.cbegin();
}
std::size_t HandHistoryFilesReader::Read(char* mem, std::size_t buff_size)
{
while (m_current != m_map.cend())
{
std::size_t r_size = buff_size;
std::size_t tail_size = m_tail.size();
if (tail_size > 0)
{
if (tail_size > buff_size)
throw std::runtime_error("[HHMemPool::Buffer Read] MemPool Buffer overflow.");
std::memcpy(mem, &m_tail[0], tail_size);
r_size -= tail_size;
m_tail.clear();
}
if (r_size == 0)
return buff_size;
std::size_t readSize = m_current->second->Read(mem + tail_size, r_size);
r_size = readSize + tail_size;
if (r_size == 0)
{
m_current++;
continue;
}
else if (readSize == 0 && tail_size > 0)
{
m_current++;
return tail_size;
}
if (r_size == buff_size)
{
const char* end = mem + buff_size;
const char* lastHand = m_current->first->Last(mem+tail_size, end);
if (lastHand > mem)
{
r_size = lastHand - mem;
m_tail.assign(lastHand, end);
}
}
return r_size;
}
return 0;
}
}
<file_sep>/src/strutils.cxx
#include <algorithm>
#include <iterator>
#include <cassert>
#include <cstring>
#include "strutils.hpp"
#ifdef _MSC_VER
#include <codecvt>
#include <windows.h>
namespace
{
using converter_utf8 = std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t>;
using converter_ansi = std::wstring_convert<std::codecvt<wchar_t, char, std::mbstate_t>, wchar_t>;
}
#else
// ???
#endif
namespace a2a
{
namespace StrUtils
{
static constexpr char Z_diff = 'Z' - 'z';
static char ch_tolower_ansi(char in)
{
return (in > 'Z' || in < 'A') ? in : in - Z_diff;
}
static char ch_upper_ansi(char in)
{
return (in > 'z' || in < 'a') ? in : in + Z_diff;
}
void to_lower_ansi(const std::string& input, std::string& out)
{
if (out.size() < input.size())
{
if (!out.empty()) out.clear();
std::transform(input.begin(), input.end(), std::back_inserter(out), ch_tolower_ansi);
}
else
{
std::transform(input.begin(), input.end(), out.begin(), ch_tolower_ansi);
if (out.size() > input.size())
out.resize(input.size());
}
}
std::string to_lower_ansi(const std::string& input)
{
std::string ret; ret.resize(input.size()); to_lower_ansi(input, ret);
return ret;
}
void to_upper_ansi(const std::string& input, std::string& out)
{
if (out.size() < input.size())
{
if (!out.empty()) out.clear();
std::transform(input.begin(), input.end(), std::back_inserter(out), ch_upper_ansi);
}
else
{
std::transform(input.begin(), input.end(), out.begin(), ch_upper_ansi);
if (out.size() > input.size())
out.resize(input.size());
}
}
std::string to_upper_ansi(const std::string& input)
{
std::string ret; ret.resize(input.size()); to_upper_ansi(input, ret);
return ret;
}
std::wstring utf8_to_wchar(const std::string& str)
{
#ifdef _MSC_VER
int cchUTF16 = ::MultiByteToWideChar(
CP_UTF8,
0,
str.c_str(),
str.size(),
NULL,
0
);
std::wstring ret; ret.resize(cchUTF16);
int result = ::MultiByteToWideChar(
CP_UTF8,
0,
str.c_str(),
str.size(),
&ret[0],
ret.size()
);
return ret;// converter_utf8().from_bytes(str);
#else
return L"";
#endif
}
std::string wchar_to_utf8(const std::wstring& wstr) {
#ifdef _MSC_VER
return converter_utf8().to_bytes(wstr);
#else
return "";
#endif
}
const char* ReadLine(const char* beg, const char* end, std::string& t, std::size_t max_size)
{
static const std::size_t MAX_BUFF = 1024; char buff[MAX_BUFF]; *buff = 0;
if (max_size > MAX_BUFF)
throw std::invalid_argument("ReadLine: max_size > 1024");
if (beg >= end) return nullptr;
std::size_t len = end - beg;
if (len > max_size)
len = max_size;
const char *p = nullptr;
const char *_r = (const char *)std::memchr(beg, '\r', len);
const char *_n = nullptr;
if (_r)
_n = (const char *)std::memchr(beg, '\n', _r - beg);
else
_n = (const char *)std::memchr(beg, '\n', len);
if (_n)
p = _n;
if (_r && !p)
p = _r;
else if (_r) p = _r < _n ? _r : _n;
if (!p)
{
t.assign(beg, len);
return beg + len;
}
t.assign(beg, p);
auto add = ((*(p + 1) == '\r' || *(p + 1) == '\n') ? 2 : 1);
return p + add;
}
}
}
<file_sep>/include/hhlineparser.hpp
#ifndef INCLUDE_HHLINEPARSER_H
#define INCLUDE_HHLINEPARSER_H
#include <string>
#include <iostream>
#include "hhparser_base.hpp"
namespace a2a
{
struct ILineParserImpl
{
virtual bool ProcessLine(const std::string& ln) = 0;
virtual bool ProcessEmptyLine(int streak) = 0;
virtual void OnHandComplete() = 0;
virtual ~ILineParserImpl() {}
};
class HandHistoryLineParser : public HandHistoryParser
{
public:
HandHistoryLineParser(const std::string& name, const Version& ver, const std::string& descr = "")
: HandHistoryParser(name, ver, descr) { }
const char* Next(const char* beg, const char* end) const final;
const char* Last(const char* beg, const char* end) const final;
const char* Parse(const char* beg, const char* end, HandHistory& handHistory) const final;
protected:
virtual std::size_t MaxLineLen() const;
virtual std::size_t MinLineLen() const;
virtual const std::string& HandStart() const = 0;
virtual bool IsFirstLine(const std::string&) const;
virtual ILineParserImpl* GetImplementation(HandHistory& _hh,
const HandHistoryParserSettings& _cfg,
const char*& _cursor) const = 0;
private:
static const std::size_t DEFAULT_MAX_LINE_LENGTH = 150;
static const std::size_t DEFAULT_MIN_LINE_LENGTH = 8;
};
}
//
// inlines
//
namespace a2a
{
inline std::size_t HandHistoryLineParser::MaxLineLen() const
{
return DEFAULT_MAX_LINE_LENGTH;
}
inline std::size_t HandHistoryLineParser::MinLineLen() const
{
return DEFAULT_MIN_LINE_LENGTH;
}
}
#endif<file_sep>/include/player.hpp
#ifndef INCLUDE_PLAYER_H
#define INCLUDE_PLAYER_H
#include <string>
#include <memory>
#include "gamesite.hpp"
namespace a2a
{
class Player final
{
public:
using Ptr = std::shared_ptr<Player>;
Player(const std::string& name, GameSite site)
: m_name(name)
, m_site(site)
{}
const std::string& Name() const
{
return m_name;
}
private:
std::string m_name;
GameSite m_site;
};
}
#endif<file_sep>/include/hhconverter_ps.hpp
#ifndef INCLUDE_HHCONVERTER_PS_H
#define INCLUDE_HHCONVERTER_PS_H
#include "hhconverter_base.hpp"
namespace a2a
{
namespace PokerStars
{
class HHConverter final : public HandHistoryConverter
{
public:
using Ptr = std::shared_ptr<HHConverter>;
HHConverter();
void Convert(std::ostream& os, const HandHistory& handHistory) const;
};
}
}
#endif<file_sep>/tests/fsystests.cpp
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <array>
#include <deque>
#include <forward_list>
#include <list>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <memory>
#include <chrono>
#include <ctime>
//#define private public
#ifdef _MSC_VER
#pragma warning (disable: 4996)
#endif
#include "fsysutils.hpp"
#include "filescol.hpp"
#include "strutils.hpp"
using namespace a2a;
using namespace a2a::StrUtils;
TEST_CASE("Misc")
{
int tr, dr, dots;
int a = parse_int("1,99", &dr, &tr, &dots);
std::cout << a << " " << dr << ' ' << tr << ' ' << dots << std::endl;
}
//TEST_CASE("Fs")
//{
//
// std::string s(_searchPath("tests/hh/ps", 4));
//
//#ifdef _MSC_VER
// auto dir = Directory::Open(s, true);
//#else
// std::string s1(_searchPath("/home/", 4));
// auto dir = Directory::Open(s1, true);
//#endif
//
// std::cout << dir->GetFullPath() << std::endl << "----" << std::endl;
//
// auto files1 = dir->GetFiles();
// std::cout << files1.Size() << std::endl;
//
// dir->Reopen();
//
// int num = 0;
// while (dir->HasFilesToProcess())
// {
// auto files = dir->GetFilesMinTotalSize(30000);
//
// num += files.Size();
//
// int j = 0;
//
// for (const auto& f : files)
// std::cout <<"[" << j++<<"] " << f->GetFullPath() <<" " << f->FileSize() << std::endl;
//
// std::cout << "==sz=" << files.FilesTotalSize() << std::endl;
// }
// std::cout << dir->GetFullPath() << std::endl << "----" << std::endl;
// std::cout << "----------------------------------------------------------------" << std::endl;
//
// dir->Reopen();
//
// auto files = dir->GetFiles();
// std::cout << files.Size() << std::endl;
// std::cout << files.FilesTotalSize() << std::endl;
//
// REQUIRE(files1.Size() == files.Size());
// REQUIRE(files.Size() == num);
//
//}
#ifdef _MSC_VER
#pragma warning (default: 4996)
#endif
<file_sep>/include/pot.hpp
#ifndef INCLUDE_POT_HPP
#define INCLUDE_POT_HPP
#include <vector>
#include "types.hpp"
#include "handaction.hpp"
#include "seat.hpp"
namespace a2a
{
class Pot final
{
public:
Pot() : m_chips(0), m_rake(0), m_max(0) {}
int GetChips() const;
void SetChips(int chips);
void SetRake(int rake);
int GetRake() const;
using side_pots = std::vector<int>;
void AddSidePot(int sidePotSize);
int GetSidePot(int sidePotIndex) const;
std::size_t GetSidePotsNum() const;
const side_pots& GetSidePots() const;
int GetMaxStake() const;
private:
int m_chips;
int m_rake;
int m_max;
side_pots m_sidePots;
void ProcessAction(const HandAction::Ptr& action, const Seat::Ptr& seat);
void ResetNewStage();
friend class GameStage;
friend class HandHistory;
};
}
//
// inlines
//
namespace a2a
{
inline int Pot::GetChips() const
{
return m_chips;
}
inline void Pot::SetChips(int chips)
{
m_chips = chips;
}
inline int Pot::GetMaxStake() const
{
return m_max;
}
inline void Pot::ResetNewStage()
{
m_max = 0;
}
}
#endif<file_sep>/include/hhbindc.h
#ifndef INCLUDE_HHBINDC_H
#define INCLUDE_HHBINDC_H
#include "config.h"
#ifdef __cplusplus
extern "C" {
#endif
A2AHHC_API void* hh_new();
A2AHHC_API void hh_delete(void*);
A2AHHC_API void hh_set_handid(void*, const char*);
A2AHHC_API const char* hh_get_handid(void*);
A2AHHC_API void hh_set_tournid(void*, const char*);
A2AHHC_API const char* hh_get_tournid(void*);
A2AHHC_API void hh_set_tournlvl(void*, int);
A2AHHC_API int hh_get_tournlvl(void*);
A2AHHC_API int _roman_to_int(const char*);
A2AHHC_API void _int_to_roman(int, char*, int);
A2AHHC_API void hh_set_gametype(void*, unsigned int);
A2AHHC_API unsigned int hh_get_gametype(void*);
A2AHHC_API void hh_get_gametype_str(unsigned int, char*, int);
A2AHHC_API void hh_set_gamemode(void*, unsigned int);
A2AHHC_API unsigned int hh_get_gamemode(void*);
A2AHHC_API void hh_set_gamesite(void*, const char*);
A2AHHC_API const char* hh_get_gamesite(void*);
A2AHHC_API void hh_set_datetime(void*, double);
A2AHHC_API double hh_get_datetime(void*);
A2AHHC_API double _get_tzabbroffset(const char*);
A2AHHC_API void hh_set_timezone(void*, const char*);
A2AHHC_API const char* hh_get_timezone(void*);
A2AHHC_API void hh_set_currency(void*, unsigned int);
A2AHHC_API unsigned int hh_get_currency(void*);
A2AHHC_API unsigned int _get_currencyfromstr(const char*);
A2AHHC_API const char* _get_currency_str(unsigned int);
A2AHHC_API void hh_set_stackscurrency(void*, unsigned int);
A2AHHC_API unsigned int hh_get_stackscurrency(void*);
A2AHHC_API void hh_set_buyin(void*, int, int, int);
A2AHHC_API int hh_get_buyin_rake(void*);
A2AHHC_API int hh_get_buyin_prizepool(void*);
A2AHHC_API int hh_get_buyin_knockout(void*);
A2AHHC_API void hh_set_ante(void*, int);
A2AHHC_API int hh_get_ante(void*);
A2AHHC_API void hh_set_cap(void*, int);
A2AHHC_API int hh_get_cap(void*);
A2AHHC_API void hh_set_blinds(void*, int, int);
A2AHHC_API int hh_get_bb(void*);
A2AHHC_API int hh_get_sb(void*);
A2AHHC_API void hh_set_blindlvls(void*, int, int);
A2AHHC_API int hh_get_bbl(void*);
A2AHHC_API int hh_get_sbl(void*);
A2AHHC_API void hh_set_tablename(void*, const char*);
A2AHHC_API const char* hh_get_tablename(void*);
A2AHHC_API void hh_set_maxplayers(void*, int);
A2AHHC_API int hh_get_maxplayers(void*);
A2AHHC_API void hh_set_button(void*, int);
A2AHHC_API int hh_get_button(void*);
A2AHHC_API void hh_set_cancelled(void*);
A2AHHC_API int hh_is_cancelled(void*);
A2AHHC_API const char* hh_get_hero(void*);
A2AHHC_API int hh_is_runtwice(void*);
A2AHHC_API int hh_has_header(void*);
A2AHHC_API int hh_add_seat(void*, const char*, int, int);
A2AHHC_API void* hh_get_seat(void*, int);
A2AHHC_API int hh_get_seats_num(void*);
A2AHHC_API void* hh_get_stage(void*, unsigned int);
A2AHHC_API void* hh_get_istage(void*, int);
A2AHHC_API int hh_get_stages_num(void*);
A2AHHC_API void* hh_get_iaction(void*, int);
A2AHHC_API int hh_get_actions_num(void*);
A2AHHC_API int
hh_add_action(
void* p,
unsigned int type,
const char* player,
int cash, void* cards,
unsigned int stage,
unsigned int stageTo);
//
A2AHHC_API int seat_get_idx(void*);
A2AHHC_API const char* seat_get_playername(void*);
A2AHHC_API int seat_get_stack(void*);
A2AHHC_API void seat_set_stack(void*, int);
A2AHHC_API int seat_get_startstack(void*);
A2AHHC_API void seat_set_startstack(void*, int);
A2AHHC_API unsigned int seat_get_pos(void*);
A2AHHC_API const char* _get_pos_str(unsigned int);
A2AHHC_API int seat_is_fold(void*);
A2AHHC_API int seat_is_allin(void*);
A2AHHC_API int seat_get_stake(void*);
A2AHHC_API void* seat_get_cards(void*);
//
A2AHHC_API void* cards_new(const char*);
A2AHHC_API void cards_delete(void*);
A2AHHC_API int cards_size(void*);
A2AHHC_API int cards_visible(void*);
A2AHHC_API void cards_set_evalhint(void*, const char*);
A2AHHC_API const char* cards_get_evalhint(void*);
A2AHHC_API void cards_str(void*,const char*,char*,int);
//
A2AHHC_API unsigned int stage_get_type(void*);
A2AHHC_API const char* stage_get_type_str(unsigned int);
A2AHHC_API void* stage_get_seat(void*, int);
A2AHHC_API int stage_get_seats_num(void*);
A2AHHC_API void* stage_get_board(void*);
A2AHHC_API void* stage_get_pot(void*);
A2AHHC_API void* stage_get_action(void*, int);
A2AHHC_API int stage_get_actions_num(void*);
//
A2AHHC_API int pot_get_chips(void*);
A2AHHC_API void pot_set_rake(void*, int);
A2AHHC_API int pot_get_rake(void*);
A2AHHC_API void pot_add_sidepot(void*, int);
A2AHHC_API int pot_get_sidepots_num(void*);
A2AHHC_API int pot_get_sidepot(void*, int);
A2AHHC_API unsigned int act_get_type(void*);
A2AHHC_API const char* act_get_type_str(unsigned int);
A2AHHC_API void act_set_chips(void*, int);
A2AHHC_API int act_get_chips(void*);
A2AHHC_API int act_get_raiseup(void*);
A2AHHC_API int act_get_raiseto(void*);
A2AHHC_API void act_set_player(void*, const char*);
A2AHHC_API const char* act_get_player(void*);
A2AHHC_API void act_set_stage_type(void*, unsigned int);
A2AHHC_API unsigned int act_get_stage_type(void*);
A2AHHC_API void* act_get_cards(void*);
A2AHHC_API void act_set_cards(void*, void*);
A2AHHC_API const char* act_get_prop(void*, const char*);
A2AHHC_API void act_set_prop(void*, const char*, const char*);
#ifdef __cplusplus
}
#endif
#endif<file_sep>/include/handaction.hpp
#ifndef INCLUDE_HANDACTION_HPP
#define INCLUDE_HANDACTION_HPP
#include <memory>
#include <vector>
#include <unordered_map>
#include "types.hpp"
#include "handactiontype.hpp"
#include "gamestagetype.hpp"
#include "cardseq.hpp"
namespace a2a
{
class Seat;
class GameStage;
class HandAction final
{
public:
using Ptr = std::shared_ptr<HandAction>;
using SeatPtr = std::shared_ptr<Seat>;
HandAction(const HandActionTypeFlags& actionTypeFlags);
HandAction(const HandActionTypeFlags& actionTypeFlags,
const std::string& playerName, int chips = 0);
HandAction(const HandActionTypeFlags& actionTypeFlags,
GameStageType stageSwitch, const CardSeq& cards);
HandAction(const HandActionTypeFlags& actionTypeFlags,
const std::string& playerName, const CardSeq& cards);
bool IsActionType(HandActionType actionType) const;
bool IsActionType(const HandActionTypeFlags& actionTypeFlags) const;
const HandActionTypeFlags& GetActionTypeFlags() const;
int GetChips() const;
void SetChips(int chips);
int GetRaiseUp() const;
int GetRaiseTo() const;
const std::string& GetPlayerName() const;
void SetPlayerName(const std::string&);
const SeatPtr& GetSeat() const;
GameStageType GetStageType() const;
void SetStageType(GameStageType);
const CardSeq& GetCards() const;
CardSeq& GetCards();
void SetCards(const CardSeq& cards);
void SetProperty(const std::string& key, const std::string& value = "");
const std::string& GetProperty(const std::string& key);
bool HasProperty(const std::string& key);
private:
HandActionTypeFlags m_type;
int m_chips;
int m_raiseUp;
int m_raiseTo;
std::string m_playerName;
GameStageType m_stageType;
CardSeq m_cards;
SeatPtr m_seat;
void SetGameStage(const std::shared_ptr<GameStage>& hh_stage);
void CopySeat(const SeatPtr& seat);
using PropertyMap = std::unordered_map<std::string, std::string>;
PropertyMap m_properties;
friend class HandHistory;
friend class GameStage;
};
}
//
// inlines
//
namespace a2a
{
inline const std::string& HandAction::GetPlayerName() const
{
return m_playerName;
}
inline void HandAction::SetPlayerName(const std::string & name)
{
m_playerName = name;
}
inline const HandAction::SeatPtr & HandAction::GetSeat() const
{
return m_seat;
}
inline bool HandAction::IsActionType(HandActionType actionType) const
{
return (bool)(m_type & actionType);
}
inline bool HandAction::IsActionType(const HandActionTypeFlags& actionTypeFlags) const
{
return (bool)(m_type & actionTypeFlags);
}
inline const HandActionTypeFlags& HandAction::GetActionTypeFlags() const
{
return m_type;
}
inline int HandAction::GetChips() const
{
return m_chips;
}
inline void HandAction::SetChips(int chips)
{
m_chips = chips;
}
inline int HandAction::GetRaiseUp() const
{
return m_raiseUp;
}
inline int HandAction::GetRaiseTo() const
{
return m_raiseTo;
}
inline GameStageType HandAction::GetStageType() const
{
return m_stageType;
}
inline void HandAction::SetStageType(GameStageType stage)
{
m_stageType = stage;
}
inline const CardSeq & HandAction::GetCards() const
{
return m_cards;
}
inline CardSeq & HandAction::GetCards()
{
return m_cards;
}
inline void HandAction::SetCards(const CardSeq & cards)
{
m_cards = cards;
}
}
#endif<file_sep>/tests/CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(a2a-poker-tools-tests CXX)
include_directories(
${inc_dirs}
${CMAKE_SOURCE_DIR}/tests/benchpress
${CMAKE_SOURCE_DIR}/tests/catch
)
add_library(a2ahh
${common_sources}
${he_sources}
${hh_sources}
)
set_target_properties(a2ahh PROPERTIES COMPILE_DEFINITIONS "A2A_HHLIBEXPORTS=1")
if(LUA_SUPPORT)
target_link_libraries(a2ahh ${LUA_LIB})
endif()
add_library( a2ahhproc
${hh_proc_sources}
${json11_sources}
)
target_link_libraries(a2ahhproc a2ahh)
if(LUA_SUPPORT)
target_link_libraries(a2ahhproc ${LUA_LIB})
endif(LUA_SUPPORT)
if(BUILD_TESTS)
file( GLOB TESTS_SOURCES *.cpp )
foreach( testsourcefile ${TESTS_SOURCES} )
get_filename_component(testname_ext ${testsourcefile} NAME)
string( REPLACE ".cpp" "" testname ${testname_ext} )
message(${testname})
add_executable( ${testname}
${testname_ext} )
set_target_properties(${testname} PROPERTIES DEBUG_POSTFIX "d")
target_link_libraries(${testname} a2ahhproc)
endforeach( testsourcefile ${TESTS_SOURCES} )
endif(BUILD_TESTS)
file( GLOB TESTS_SOURCES *.cxx )
foreach( testsourcefile ${TESTS_SOURCES} )
get_filename_component(testname_ext ${testsourcefile} NAME)
string( REPLACE ".cxx" "" testname ${testname_ext} )
message(${testname})
add_executable( ${testname}
${testname_ext} )
set_target_properties(${testname} PROPERTIES DEBUG_POSTFIX "d")
target_link_libraries(${testname} a2ahhproc)
endforeach( testsourcefile ${TESTS_SOURCES} )
if(LUA_SUPPORT)
add_definitions(-DA2A_LUA)
endif(LUA_SUPPORT)
if(MSVC)
# add_definitions(-D_SCL_SECURE_NO_WARNINGS -wd4251)
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /O2")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}")
else(MSVC)
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11 -pthread")
endif(MSVC)
<file_sep>/tools/CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
project(a2a-poker-tools-tests CXX)
add_executable(pwhhs
#add_library(pwhhs SHARED
${common_sources}
${he_sources}
${hh_sources}
${hh_proc_sources}
${json11_sources}
pwhhs.cpp
)
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /MT /O2")
set_target_properties(pwhhs PROPERTIES DEBUG_POSTFIX "d")
if(LUA_SUPPORT)
target_link_libraries(pwhhs ${LUA_LIB})
add_executable( a2alua a2alua.cpp
${INCLUDE_ROOT}/hhbindc.h
${SRC_ROOT}/hhbindc.cxx
)
set_target_properties(a2alua PROPERTIES COMPILE_DEFINITIONS "A2A_HHLIBEXPORTS=1")
target_link_libraries(a2alua a2ahhproc)
if(MSVC)
add_definitions(-D_SCL_SECURE_NO_WARNINGS -wd4251 -DPSAPI_VERSION=1)
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} /O2 /MT")
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG}")
else(MSVC)
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} "-std=c++11 -pthread")
endif(MSVC)
endif()<file_sep>/include/version.hpp
#ifndef INCLUDE_VERSION_H
#define INCLUDE_VERSION_H
#include <cassert>
#include <cmath>
#include <iostream>
#include "types.hpp"
namespace a2a
{
class Version final
{
public:
Version(u8 major, u8 minor, u8 build = 0, u8 rev = 0) noexcept :
m_major(major), m_minor(minor), m_build(build), m_rev(rev)
{
}
Version(double ver) noexcept :
m_build(0), m_rev(0)
{
m_major = static_cast<u8>( std::trunc(ver) );
m_minor = static_cast<u8>( std::trunc(10 * (ver - m_major)) );
}
bool operator== (const Version &rhs) const
{
return
this->m_major == rhs.m_major &&
this->m_minor == rhs.m_minor &&
this->m_build == rhs.m_build &&
this->m_rev == rhs.m_rev;
}
bool operator< (const Version &rhs) const
{
return
this->m_major < rhs.m_major ||
this->m_minor < rhs.m_minor ||
this->m_build < rhs.m_build ||
this->m_rev < rhs.m_rev;
}
bool operator!= (const Version &rhs) const { return !(*this == rhs); }
bool operator<= (const Version &rhs) const { return !(rhs < *this); }
bool operator> (const Version &rhs) const { return (rhs < *this); }
bool operator>= (const Version &rhs) const { return !(*this < rhs); }
u8 Major() const { return m_major; }
u8 Minor() const { return m_minor; }
u8 Build() const { return m_build; }
u8 Revision() const { return m_rev; }
friend std::ostream& operator<< (std::ostream& os, const Version& ver)
{
os << ver.m_major << '.' << ver.m_minor;
if (ver.m_build > 0 || ver.m_rev > 0)
os << '.' << ver.m_build << '.' << ver.m_rev;
return os;
}
private:
u8 m_major;
u8 m_minor;
u8 m_build;
u8 m_rev;
};
}
#endif<file_sep>/include/collection.hpp
#ifndef INCLUDE_COLLECTION_HPP
#define INCLUDE_COLLECTION_HPP
#include <memory>
#include <vector>
#include <functional>
#include <iterator>
#include <algorithm>
#include <type_traits>
#include "stdutils.hpp"
namespace a2a
{
template <typename Item, typename Self>
class Collection
{
public:
using value_type = std::shared_ptr<Item>;
using containter_type = std::vector<value_type>;
using predicate_t = std::function<bool(const value_type&)>;
using visitor_t = std::function<void(value_type&)>;
using const_visitor_t = std::function<void(const value_type&)>;
using cmp_t = std::function<bool(const value_type&, const value_type&)>;
void Add(const value_type& item)
{
m_items.push_back(item);
}
void Add(const Self& items)
{
m_items.reserve(m_items.size() + items.Size());
m_items.insert(m_items.end(), items.cbegin(), items.cend());
}
std::size_t Size() const
{
return m_items.size();
}
bool Empty() const
{
return m_items.empty();
}
Self Select(const predicate_t& predicate) const
{
Self ret;
ret.m_items.reserve(m_items.size());
std::copy_if(m_items.cbegin(), m_items.cend(), std::back_inserter(ret.m_items), predicate);
return ret;
}
void Visit(const visitor_t& visitor)
{
std::for_each(m_items.begin(), m_items.end(), visitor);
}
void Visit(const const_visitor_t& visitor) const
{
std::for_each(m_items.cbegin(), m_items.cend(), visitor);
}
Self Cut(const predicate_t& predicate)
{
Self ret;
auto i = m_items.begin();
while (i != m_items.end())
{
if (predicate(*i))
{
ret.m_items.push_back(*i);
i = m_items.erase(i);
}
else
++i;
}
return ret;
}
void Clear()
{
m_items.clear();
}
void Clear(const predicate_t& predicate)
{
StdUtils::erase_if(m_items, predicate);
}
std::size_t Count(const predicate_t& predicate) const
{
return std::count_if(m_items.cbegin(), m_items.cend(), predicate);
}
const value_type& First() const
{
return m_items.empty() ? _null() : m_items.front();
}
const value_type& Last() const
{
return m_items.empty() ? _null() : m_items.back();
}
const value_type& Get(const predicate_t& predicate) const
{
auto i = find(predicate);
return i == m_items.cend() ? _null() : *i;
}
value_type Get(const predicate_t& predicate)
{
auto i = find(predicate);
return i == m_items.end() ? nullptr : *i;
}
bool Has(const predicate_t& predicate) const
{
return find(predicate) != m_items.cend();
}
Self Copy() const
{
Self ret; ret.m_items.reserve(m_items.size());
std::transform(m_items.cbegin(), m_items.cend(), std::back_inserter(ret.m_items),
[](const value_type& i)->value_type { return std::make_shared<Item>(*i); });
return ret;
}
void Sort(const cmp_t& cmp)
{
std::sort(m_items.begin(), m_items.end(), cmp);
}
void Unique(const cmp_t& cmp)
{
m_items.erase(std::unique(m_items.begin(), m_items.end(), cmp), m_items.end());
}
const value_type& operator[](std::size_t index) const
{
return m_items[index];
}
typename containter_type::iterator begin() { return m_items.begin(); }
typename containter_type::iterator end() { return m_items.end(); }
typename containter_type::const_iterator cbegin() const { return m_items.cbegin(); }
typename containter_type::const_iterator cend() const { return m_items.cend(); }
typename containter_type::const_iterator begin() const { return m_items.begin(); }
typename containter_type::const_iterator end() const { return m_items.end(); }
typename containter_type::reverse_iterator rbegin() { return m_items.rbegin(); }
typename containter_type::reverse_iterator rend(){ return m_items.rend(); }
typename containter_type::const_reverse_iterator crbegin() const { return m_items.crbegin(); }
typename containter_type::const_reverse_iterator crend() const { return m_items.crend(); }
typename containter_type::const_reverse_iterator rbegin() const { return m_items.crbegin(); }
typename containter_type::const_reverse_iterator rend() const { return m_items.crend(); }
protected:
containter_type m_items;
typename containter_type::iterator find(const predicate_t& predicate)
{
return std::find_if(m_items.begin(), m_items.end(), predicate);;
}
typename containter_type::const_iterator find(const predicate_t& predicate) const
{
return std::find_if(m_items.cbegin(), m_items.cend(), predicate);;
}
inline static const value_type& _null()
{
static const value_type _nullv = nullptr;
return _nullv;
}
};
}
#endif<file_sep>/include/metafactory.hpp
#ifndef INCLUDE_METAFACTORY_H
#define INCLUDE_METAFACTORY_H
#include <string>
#include <unordered_map>
#include <memory>
#include <cassert>
namespace a2a
{
template <typename Base, typename ... Args> class BaseMetaObject
{
public:
virtual std::shared_ptr<Base> Create(Args...) const = 0;
BaseMetaObject(const std::string& name) : m_name(name) { }
virtual ~BaseMetaObject() {}
const std::string& Name() const { return m_name; }
inline bool operator<(const BaseMetaObject& rhs) { return m_name < rhs.m_name; }
BaseMetaObject() = delete;
BaseMetaObject(const BaseMetaObject&) = delete;
BaseMetaObject& operator=(const BaseMetaObject&) = delete;
protected:
std::string m_name;
};
template <typename Cls, typename Base, typename ... Args> class MetaObject : public BaseMetaObject<Base, Args...>
{
public:
MetaObject(const std::string& name) : BaseMetaObject<Base, Args...>(name) {}
~MetaObject() {}
std::shared_ptr<Base> Create(Args... args) const { return std::make_shared<Cls>(std::forward<Args>(args)...); }
};
template<typename Base, typename ... Args> class MetaFactory
{
public:
typedef BaseMetaObject<Base, Args...> baseobj_type;
typedef std::unordered_map<std::string, std::shared_ptr<baseobj_type>> manifest_type;
using pair_type = typename manifest_type::value_type;
MetaFactory(const std::string& manifestName) : m_manifestName(manifestName)
{
m_manifest.reserve(8);
}
template<class Derived> inline void Register(const std::string& clsName)
{
static_assert(std::is_base_of<Base, Derived>::value, "MetaFactory:: Derived must be a descendant of Base");
m_manifest.insert(pair_type(clsName, std::make_shared<MetaObject<Derived, Base, Args...>>(clsName)) );
}
MetaFactory() = delete;
protected:
inline std::shared_ptr<Base> Create(const std::string& clsName, Args... args) const
{
auto iter = m_manifest.find(clsName);
assert(iter != m_manifest.end() && "Metafactory: Manifest has no class");
return iter->second->Create(args...);
}
inline bool HasClass(const std::string& clsName) const
{
return m_manifest.find(clsName) != m_manifest.end();
}
manifest_type m_manifest;
std::string m_manifestName;
};
}
#endif
<file_sep>/include/hhparsers.hpp
#ifndef INCLUDE_HHPARSERFACTORY_HPP
#define INCLUDE_HHPARSERFACTORY_HPP
#include "pluginfactory.hpp"
#include "hhparser_base.hpp"
#include "gamesite.hpp"
#include "stdutils.hpp"
#ifdef A2A_LUA
#include "luastate.hpp"
#endif
namespace a2a
{
class HandHistoryParsersFactory final : public PluginFactory<HandHistoryParser>
{
public:
using Ptr = std::shared_ptr<HandHistoryParsersFactory>;
HandHistoryParsersFactory();
HandHistoryParsersFactory(const HandHistoryParserSettings& defSettings);
#ifdef A2A_LUA
HandHistoryParsersFactory(LuaState& state);
HandHistoryParsersFactory(LuaState& state, const HandHistoryParserSettings& defSettings);
#endif
HandHistoryParser::Ptr GetParser(const std::string& parserName);
HandHistoryParser::Ptr GetParser(GameSite gameSite);
HandHistoryParser::Ptr GetParserBySite(const std::string& siteName);
HandHistoryParser::Ptr FindParser(const char* memBlock, std::size_t size);
template<class Container>
HandHistoryParser::Ptr FindParser(const Container& memBuffer)
{
return FindParser(StdUtils::begin_ptr(memBuffer), memBuffer.size());
}
void SetDefauleSettings(const HandHistoryParserSettings& defSettings);
const HandHistoryParserSettings& GetDefaultSettings() const;
static HandHistoryParsersFactory& Global();
private:
using TBasePluginFactory = PluginFactory<HandHistoryParser>;
using TBasePluginFactory::TBasePluginFactory;
HandHistoryParserSettings m_defaultSettings;
void LoadCoreParsers();
bool m_bCoreLoaded;
#ifdef A2A_LUA
LuaState& m_luaState;
bool m_bLuaLoaded;
void LoadLuaParsers(const std::string& dir = "");
HandHistoryParser::Ptr CreateParser(const LuaAddon& addon) const;
#endif
};
}
//
// inlines
//
namespace a2a
{
inline void HandHistoryParsersFactory::SetDefauleSettings(const HandHistoryParserSettings& defSettings)
{
m_defaultSettings = defSettings;
}
inline const HandHistoryParserSettings& HandHistoryParsersFactory::GetDefaultSettings() const
{
return m_defaultSettings;
}
}
#endif<file_sep>/src/lualineparser.cxx
#include "lualineparser.hpp"
namespace a2a
{
struct LuaLineParserImp : public ILineParserImpl
{
const char*& cursor;
HandHistory& hh;
const HandHistoryParserSettings& cfg;
LuaState& lua;
int obj_ref;
int p_func;
std::string parser_name;
LuaLineParserImp(
LuaState& luas,
HandHistory& _hh,
const HandHistoryParserSettings& _cfg,
const char*& _cursor,
int _objectRef,
const std::string& _parser_name)
:
lua(luas),
cursor(_cursor),
hh(_hh),
cfg(_cfg),
obj_ref(_objectRef),
p_func(0),
parser_name(_parser_name)
{
lua_State* L(lua.luaState());
lua_rawgeti(L, LUA_REGISTRYINDEX, obj_ref);
lua_pushstring(L, "ProcessLine");
lua_gettable(L, -2);
if (!lua_isfunction(L, -1))
{
lua_pop(L, 2);
throw LuaError("LuaLineParser : " + parser_name +" : ProcessLine method not found");
}
p_func = luaL_ref(L, LUA_REGISTRYINDEX);
if ((LUA_REFNIL == p_func) || (LUA_NOREF == p_func))
{
lua_pop(L, 1);
throw LuaError("LuaLineParser :" + parser_name + " : Failed to get registry index");
}
lua_pushstring(L, "setup");
lua_gettable(L, -2);
if (!lua_isfunction(L, -1))
{
lua_pop(L, 2);
throw LuaError("LuaLineParser " + parser_name + " : setup method not found");
}
lua_pushvalue(L, -2);
lua_pushlightuserdata(L, &hh);
if (lua_pcall(L, 2, 0, 0) != 0)
{
lua_pop(L, 2);
throw LuaError("LuaLineParser " + parser_name +" : setup method error");
}
}
~LuaLineParserImp()
{
if (p_func != 0)
luaL_unref(lua.luaState(), LUA_REGISTRYINDEX, p_func);
lua_pop(lua.luaState(), 1);
}
void OnHandComplete()
{
lua_State* L(lua.luaState());
lua_pushstring(L, "OnHandComplete");
lua_gettable(L, -2);
if (!lua_isfunction(L, -1))
{
lua_pop(L, 1);
return;
}
lua_pushvalue(L, -2);
if (lua_pcall(L, 1, 0, 0) != 0)
{
std::string err(lua_tostring(L, -1));
lua_pop(L, 1);
throw LuaError("LuaLineParser : " + parser_name + " : " +err);
}
}
bool ProcessLine(const std::string& ln)
{
lua_State* L(lua.luaState());
lua_rawgeti(L, LUA_REGISTRYINDEX, p_func);
lua_pushvalue(L, -2);
lua_pushstring(L, ln.c_str());
if (lua_pcall(L, 2, 1, 0) != 0)
{
std::string err(lua_tostring(L, -1));
lua_pop(L, 1);
throw ParseError("LuaLineParser : " + parser_name + " : " + err, cursor);
}
if (!lua_isnumber(L, -1))
{
lua_pop(L, 1);
throw ParseError("LuaLineParser : " + parser_name + " ProcessLine must return a number (<0 - error, 0 - stop, >0 continue)", cursor);
}
int ret = static_cast<int>(lua_tonumber(L, -1));
lua_pop(L, 1);
if (ret < 0)
{
lua_pushstring(L, "error_msg");
lua_gettable(L, -2);
if (!lua_isfunction(L, -1))
{
lua_pop(L, 1);
throw ParseError("LuaLineParser : " + parser_name + " error_msg function not found", cursor);
}
lua_pushvalue(L, -2);
if (lua_pcall(L, 1, 1, 0) != 0)
{
std::string err(lua_tostring(L, -1));
lua_pop(L, 1);
throw ParseError("LuaLineParser : " + parser_name + " : " + err, cursor);
}
if (!lua_isstring(L, -1))
{
lua_pop(L, 1);
throw ParseError("LuaLineParser : " + parser_name + " Unexpected parsing error", cursor);
}
std::string error(lua_tostring(L, -1));
lua_pop(L, 1);
throw ParseError("LuaLineParser : " + error, cursor);
}
return ret > 0;
}
bool ProcessEmptyLine(int streak)
{
return streak < 2;
}
};
LuaLineParser::LuaLineParser(LuaState & luas, const LuaAddon& addon)
:HandHistoryLineParser(addon.name, addon.version, addon.description), m_lua(luas), m_luaObjectRef(0)
{
lua_State* L(m_lua.luaState());
lua_getglobal(L, addon.name.c_str());
if (!lua_istable(L, -1))
{
lua_pop(L, 1);
throw LuaError( "LuaLineParser : " + addon.name + " not found");
}
if (lua_pcall(L, 0, 1, 0) != 0)
{
lua_pop(L, 1);
throw LuaError("LuaLineParser : " + addon.name + " : ctor error");
}
lua_pushstring(L, "HandStart");
lua_gettable(L, -2);
if (!lua_isfunction(L, -1))
{
lua_pop(L, 2);
throw LuaError("LuaLineParser : " + addon.name + ": HandStart method not found");
}
lua_pushvalue(L, -2);
if (lua_pcall(L, 1, 1, 0) != 0)
{
std::string err(lua_tostring(L, -1));
lua_pop(L, 2);
throw LuaError("LuaLineParser : " + addon.name + ": HandStart method : " + err);
}
if (!lua_isstring(L, -1))
{
lua_pop(L, 2);
throw LuaError("LuaLineParser : " + addon.name + ": HandStart must return a string");
}
m_handStart.assign(lua_tostring(L, -1));
if (m_handStart.empty())
{
lua_pop(L, 2);
throw LuaError("LuaLineParser : " + addon.name + ": HandStart must return not an empty string");
}
lua_pop(L, 1);
m_luaObjectRef = luaL_ref(L, LUA_REGISTRYINDEX);
if ((LUA_REFNIL == m_luaObjectRef) || (LUA_NOREF == m_luaObjectRef))
{
lua_pop(L, 1);
throw LuaError("LuaLineParser : " + addon.name + ": Failed to get registry index");
}
}
LuaLineParser::~LuaLineParser()
{
if (m_luaObjectRef != 0)
luaL_unref(m_lua.luaState(), LUA_REGISTRYINDEX, m_luaObjectRef);
}
const std::string & LuaLineParser::HandStart() const
{
return m_handStart;
}
ILineParserImpl * LuaLineParser::GetImplementation(HandHistory & _hh, const HandHistoryParserSettings & _cfg, const char *& _cursor) const
{
return new LuaLineParserImp (m_lua, _hh, _cfg, _cursor, m_luaObjectRef, GetName());
}
}
<file_sep>/src/gamestage.cxx
#include <stdexcept>
#include <sstream>
#include <iterator>
#include <algorithm>
#include <cassert>
#include "gamestage.hpp"
#include "stdutils.hpp"
#include "handhistory.hpp"
namespace a2a
{
GameStage::GameStage(HandHistory& parent)
: m_type(GameStageType::Seating)
, m_parent(parent)
, m_actionSeat(0)
{
}
const HandActions & GameStage::GetActions() const
{
return m_actions;
}
HandActions GameStage::GetActions(const HandActions::predicate_t& predicate) const
{
return m_actions.Select(predicate);
}
void GameStage::ProcessAction(const HandAction::Ptr& action)
{
using namespace HandActionUtils;
if (IsAnyInfoAction(action->GetActionTypeFlags()))
{
m_actions.Add(action);
return;
}
if (action->IsActionType(HandActionType::_UncalledBetAdjust))
{
auto uncalled = CalculateUncalled(action->GetPlayerName());
if (uncalled > 0)
{
if (action->IsActionType(HandActionType::_UncalledBetAdjust))
{
HandActionTypeFlags aType(HandActionType::Return);
if (!action->IsActionType(HandActionType::_ForceUncalledBet))
aType |= HandActionType::_Hidden;
m_parent.ProcessAction(std::make_shared<HandAction>(aType, action->GetPlayerName(), -uncalled));
}
}
}
const Seat::Ptr& seat = m_seats.Get(Seats::Player_(action->GetPlayerName()));
if (!seat)
throw std::runtime_error("Action player not found - " +
action->GetPlayerName() + ", on stage: " +
GameStageUtils::GameStageToString(m_type));
if (HandActionUtils::IsAnySummaryAction(action->GetActionTypeFlags()))
{
if (!action->GetCards().Empty())
seat->m_cards.Reset(action->GetCards());
if (!action->IsActionType(HandActionType::_Hidden))
m_actions.Add(action);
return;
}
auto cards = action->GetCards();
if (HandActionUtils::IsAnyCardAction(action->GetActionTypeFlags()))
{
if (action->IsActionType(HandActionType::CardsDiscard))
{
if (cards.VisibleCards() > 0)
seat->m_cards.Clear(cards);
}
else
{
action->CopySeat(seat);
seat->m_cards.Add(cards);
}
m_actions.Add(action);
return;
}
if (cards.Size() > 0)
seat->m_cards.Add(cards);
/*
if (m_actionSeat != 0 && !action->IsActionType(HandActionType::Return|HandActionType::_Hidden))
{
if (m_actionSeat != seat->GetSeatIndex())
{
auto s(GetSeat(m_actionSeat));
throw std::runtime_error(std::string("Expected action from: ") + s->GetPlayerName() +" got from:" + seat->GetPlayerName() +
" on " + GameStageUtils::GameStageToString(m_stage) + " actionNUm:" + std::to_string(m_actions.Size())
);
}
}
*/
auto achips = action->GetChips();
if (achips != 0)
{
if (action->IsActionType(HandActionType::Raise))
{
auto toCall = m_pot.GetMaxStake() - seat->m_stake.chips;
if (action->IsActionType(HandActionType::_RaiseUpAdjust))
{
action->m_raiseUp = achips;
action->m_raiseTo = achips + m_pot.GetMaxStake();
achips += toCall;
action->m_type &= ~HandActionTypeFlags(HandActionType::_RaiseUpAdjust);
}
else
{
action->m_raiseUp = achips - toCall;
action->m_raiseTo = achips + seat->m_stake.chips;
}
action->m_chips = achips;
}
seat->m_stack -= achips;
if (seat->m_stack <= 0)
{
seat->m_stack = 0;
action->m_type |= HandActionType::AllIn;
seat->m_stake.actionType = action->GetActionTypeFlags();
}
else if (!action->IsActionType(HandActionType::Return))
seat->m_stake.actionType = action->GetActionTypeFlags();
else
{
seat->m_stake.actionType |= HandActionType::Return;
}
if (action->IsActionType(HandActionType::AllIn))
seat->m_bAllIn = true;
if (!action->IsActionType(HandActionType::Ante))
seat->m_stake.chips += achips;
}
else if (action->IsActionType(HandActionType::Fold))
{
seat->m_bFold = true;
}
//action->m_seat = seat;
if (!action->IsActionType(HandActionType::_Hidden))
m_actions.Add(action);
if (achips != 0)
m_pot.ProcessAction(action, seat);
/*
if (m_actionSeat != 0 && !action->IsActionType(HandActionType::Return | HandActionType::_Hidden))
{
auto aSeat(s_after(m_actionSeat));
if (aSeat == nullptr)
throw std::runtime_error(std::string("Cant find next active seat after ") + std::to_string(m_actionSeat));
m_actionSeat = aSeat->GetSeatIndex();
}
*/
}
int GameStage::GetUncalledBet(const std::string & playerName) const
{
return CalculateUncalled(playerName);
}
int GameStage::CalculateUncalled(const std::string& player) const
{
auto vs = m_seats;
if (vs.Size() == 0) return 0;
vs.Sort(Seats::ByStake_());
auto at = vs[0]->GetStake().actionType;
return (vs.Size() < 2 || !HandActionUtils::IsAnyBetRaise(at) ||
!(player.empty() || vs[0]->GetPlayerName() == player))
?
0 :
vs[0]->GetStake().chips - vs[1]->GetStake().chips;
}
static void dump_seat_stakes(const Seats& s)
{
std::cout << "*****************************" << std::endl;
for (const auto& i : s)
{
std::cout << i->GetPlayerName() << "==" << i->GetStake().chips << std::endl;
}
std::cout << "*****************************" << std::endl;
}
void GameStage::CalculateSidePots()
{
auto vs = m_seats;
vs.Sort(Seats::ByStake_());
if (vs.Size() < 2)
return;
auto at = vs[0]->GetStake().actionType;
if (!HandActionUtils::IsAnyBetRaise(at) )
return;
//dump_seat_stakes(vs);
auto uncalled = vs[0]->GetStake().chips - vs[1]->GetStake().chips;
if (uncalled > 0)
m_parent.ProcessAction(std::make_shared<HandAction>(HandActionType::Return, vs[0]->GetPlayerName(), -uncalled));
}
void GameStage::ResetGameStreet()
{
//m_seats.Select()
// auto uc = CalculateUncalled();
//std::cout << " UNCALLED " << uc << std::endl;
//auto actsnum = std::count_if(vs.cbegin(), vs.cend(), [](const Seat::Ptr& s)->bool {
// return !s->IsFold() && !s->IsAllIn();
//});
m_actions.Clear();
m_pot.ResetNewStage();
if (m_type == GameStageType::Summary)
return;
for (auto& p : m_seats)
p->m_stake.Reset();
/*
seats_map tmp;
for (const auto& p : m_seats)
{
if (p.second->IsFold())
continue;
auto copySeat = std::make_shared<Seat>(*(p.second));
copySeat->m_stake.Reset();
tmp.insert(seats_map::value_type(p.first, copySeat));
}
m_seats = tmp;
*/
/*
auto vs(GetSeats());
auto actsnum = std::count_if(vs.cbegin(), vs.cend(), [](const Seat::Ptr& s)->bool {
return !s->IsFold() && !s->IsAllIn();
});
std::cout << " GAMESTAGE [" << GameStageUtils::GameStageToString(m_stage) << "] " << actsnum << std::endl;
*/
}
void GameStage::ResetActiveSeat()
{
/*
auto vs(GetSeats());
auto actsnum = std::count_if(vs.cbegin(), vs.cend(), [](const Seat::Ptr& s)->bool {
return !s->IsFold() && !s->IsAllIn();
});
if (actsnum < 2) { m_actionSeat = 0; return; }
auto aSeat =
(m_stage == GameStageType::Preflop || m_stage == GameStageType::_DrawHands) ?
s_after(PokerPosition::BB) :
s_after(PokerPosition::BTN);
if (aSeat)
{
m_actionSeat = aSeat->GetSeatIndex();
std::cout << "ACTIVE : " << aSeat->GetPlayerName() << " SEAT:" << m_actionSeat << std::endl;
}
else
m_actionSeat = 0;
*/
}
void GameStage::SetupStartingPositions()
{
m_seats.Sort(Seats::ByIndex_());
m_seats.UpdatePositions(m_parent.GetButtonSeatIndex());
}
void GameStage::CopySeats()
{
m_seats = m_seats.Copy();
}
namespace GameStageUtils
{
const char* GameStageToString(GameStageType gs)
{
switch (gs)
{
case GameStageType::Current: return "Current";
case GameStageType::Seating: return "Seating";
case GameStageType::Blinds: return "Blinds";
case GameStageType::_3rdStreet: return "3rd Street";
case GameStageType::_4thStreet: return "4th Street";
case GameStageType::_5thStreet: return "5th Street";
case GameStageType::_6thStreet: return "6th Street";
case GameStageType::_DrawHands: return "Draw cards";
case GameStageType::_1stDraw: return "1st Draw";
case GameStageType::_2ndDraw: return "2nd Draw";
case GameStageType::_3rdDraw: return "3rd Draw";
case GameStageType::Preflop: return "Preflop";
case GameStageType::Flop: return "Flop";
case GameStageType::Turn: return "Turn";
case GameStageType::River: return "River";
case GameStageType::Flop_2nd: return "2nd Flop";
case GameStageType::Turn_2nd: return "2nd Turn";
case GameStageType::River_2nd: return "2nd River";
case GameStageType::Showdown: return "Showdown";
case GameStageType::Showdown_2nd: return "2nd Showdown";
case GameStageType::Summary: return "Summary";
case GameStageType::Any: return "Any Street";
default: return "Undefined";
}
}
}
}
<file_sep>/src/seatscol.cxx
#include <iterator>
#include <algorithm>
#include <cassert>
#include "seatscol.hpp"
namespace a2a
{
void Seats::UpdateSeat(const value_type & seat)
{
auto i = find(Index_(seat->GetIndex()));
if (i == m_items.end())
Add(seat);
else
*i = seat;
}
void Seats::UpdatePositions(int buttonIndex)
{
auto num = m_items.size();
if (buttonIndex == 0 || num < 2)
return;
auto i = find(Index_(buttonIndex));
if (i == m_items.end())
return;
switch (m_items.size())
{
case 2:
{
next(i)->SetPosition(PokerPosition::SB);
next(i)->SetPosition(PokerPosition::BB);
break;
}
case 3:
{
next(i)->SetPosition(PokerPosition::BTN);
next(i)->SetPosition(PokerPosition::SB);
next(i)->SetPosition(PokerPosition::BB);
break;
}
case 4:
{
next(i)->SetPosition(PokerPosition::BTN);
next(i)->SetPosition(PokerPosition::SB);
next(i)->SetPosition(PokerPosition::BB);
next(i)->SetPosition(PokerPosition::CO);
break;
}
case 5:
{
next(i)->SetPosition(PokerPosition::BTN);
next(i)->SetPosition(PokerPosition::SB);
next(i)->SetPosition(PokerPosition::BB);
next(i)->SetPosition(PokerPosition::MP1);
next(i)->SetPosition(PokerPosition::CO);
break;
}
case 6:
{
next(i)->SetPosition(PokerPosition::BTN);
next(i)->SetPosition(PokerPosition::SB);
next(i)->SetPosition(PokerPosition::BB);
next(i)->SetPosition(PokerPosition::UTG1);
next(i)->SetPosition(PokerPosition::MP1);
next(i)->SetPosition(PokerPosition::CO);
break;
}
case 7:
{
next(i)->SetPosition(PokerPosition::BTN);
next(i)->SetPosition(PokerPosition::SB);
next(i)->SetPosition(PokerPosition::BB);
next(i)->SetPosition(PokerPosition::UTG1);
next(i)->SetPosition(PokerPosition::MP1);
next(i)->SetPosition(PokerPosition::MP2);
next(i)->SetPosition(PokerPosition::CO);
break;
}
case 8:
{
next(i)->SetPosition(PokerPosition::BTN);
next(i)->SetPosition(PokerPosition::SB);
next(i)->SetPosition(PokerPosition::BB);
next(i)->SetPosition(PokerPosition::UTG1);
next(i)->SetPosition(PokerPosition::UTG2);
next(i)->SetPosition(PokerPosition::MP1);
next(i)->SetPosition(PokerPosition::MP2);
next(i)->SetPosition(PokerPosition::CO);
break;
}
case 9:
{
next(i)->SetPosition(PokerPosition::BTN);
next(i)->SetPosition(PokerPosition::SB);
next(i)->SetPosition(PokerPosition::BB);
next(i)->SetPosition(PokerPosition::UTG1);
next(i)->SetPosition(PokerPosition::UTG2);
next(i)->SetPosition(PokerPosition::MP1);
next(i)->SetPosition(PokerPosition::MP2);
next(i)->SetPosition(PokerPosition::MP3);
next(i)->SetPosition(PokerPosition::CO);
break;
}
case 10:
{
next(i)->SetPosition(PokerPosition::BTN);
next(i)->SetPosition(PokerPosition::SB);
next(i)->SetPosition(PokerPosition::BB);
next(i)->SetPosition(PokerPosition::UTG1);
next(i)->SetPosition(PokerPosition::UTG2);
next(i)->SetPosition(PokerPosition::UTG3);
next(i)->SetPosition(PokerPosition::MP1);
next(i)->SetPosition(PokerPosition::MP2);
next(i)->SetPosition(PokerPosition::MP3);
next(i)->SetPosition(PokerPosition::CO);
break;
}
}
assert((*i)->GetIndex() == buttonIndex && "Positions Update failed");
}
Seats::value_type & Seats::next(typename containter_type::iterator & i)
{
Seats::value_type & ret(*(i++));
if (i == m_items.end())
i = m_items.begin();
return ret;
}
}
<file_sep>/include/seat.hpp
#ifndef INCLUDE_SEAT_HPP
#define INCLUDE_SEAT_HPP
#include <memory>
#include "player.hpp"
#include "chips.hpp"
#include "position.hpp"
#include "cardseq.hpp"
namespace a2a
{
class Seat final
{
public:
using Ptr = std::shared_ptr<Seat>;
Seat(const Player::Ptr& player, int tableIndex, int stack)
: m_pPlayer(player)
, m_TableIndex(tableIndex)
, m_stack(stack)
, m_startStack(stack)
, m_position(PokerPosition::EMPTY)
, m_bFold(false)
, m_bAllIn(false)
{}
int GetIndex() const;
const Player::Ptr& GetPlayer() const;
const std::string& GetPlayerName() const;
int GetStack() const;
void SetStack(int stack);
int GetStartStack() const;
void SetStartStack(int stack);
bool IsPosition(PokerPositionFlags pos) const;
PokerPosition GetPosition() const;
bool IsFold() const;
bool IsAllIn() const;
Stake GetStake() const;
const CardSeq& GetCards() const;
private:
Player::Ptr m_pPlayer;
int m_TableIndex;
int m_stack;
int m_startStack;
Stake m_stake;
PokerPosition m_position;
CardSeq m_cards;
bool m_bFold;
bool m_bAllIn;
friend class GameStage;
friend class Seats;
void SetPosition(PokerPosition pos);
};
}
//
// inlines
//
namespace a2a
{
inline int Seat::GetIndex() const
{
return m_TableIndex;
}
inline const Player::Ptr& Seat::GetPlayer() const
{
return m_pPlayer;
}
inline const std::string & Seat::GetPlayerName() const
{
return m_pPlayer->Name();
}
inline int Seat::GetStack() const
{
return m_stack;
}
inline int Seat::GetStartStack() const
{
return m_startStack;
}
inline void Seat::SetStartStack(int stack)
{
m_startStack = stack;
}
inline void Seat::SetStack(int stack)
{
m_stack = stack;
}
inline void Seat::SetPosition(PokerPosition pos)
{
m_position = pos;
}
inline bool Seat::IsPosition(PokerPositionFlags pos) const
{
return (bool)(pos & m_position);
}
inline PokerPosition Seat::GetPosition() const
{
return m_position;
}
inline bool Seat::IsFold() const
{
return m_bFold;
}
inline bool Seat::IsAllIn() const
{
return m_bAllIn || m_stack <= 0;
}
inline Stake Seat::GetStake() const
{
return m_stake;
}
inline const CardSeq & Seat::GetCards() const
{
return m_cards;
}
}
#endif<file_sep>/include/currency.hpp
#ifndef INCLUDE_CURRENCY_H
#define INCLUDE_CURRENCY_H
#include <utility>
#include <iostream>
#include "types.hpp"
namespace a2a
{
enum class CurrencyType : u8
{
Chips = 0,
USD = 1,
GBP = 2,
EURO = 3,
};
namespace CurrencyUtils
{
extern CurrencyType CurrencyTypeFromUTF8Symbol(const char*);
extern CurrencyType CurrencyTypeFromShortStr(const char*);
extern const char* CurrencyTypeToShortStr(CurrencyType currencyType);
extern void ChipsCurrencyToUTF8Stream(std::ostream& os, CurrencyType currencyType, int chips, bool empty_fraction = true);
}
}
#endif
<file_sep>/tests/pokerstarsbench.cpp
#define BENCHPRESS_CONFIG_MAIN
#ifdef _MSC_VER
#pragma warning (disable: 4996)
#pragma warning (disable: 4244)
#endif
#include <fstream>
#include <array>
#include <deque>
#include <forward_list>
#include <list>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <memory>
#include <chrono>
#include <ctime>
#include <functional>
#include <cassert>
#include <cstring>
#include <benchpress.hpp>
#include "strutils.hpp"
#include "handhistory.hpp"
#include "hhconverters.hpp"
#include "hhconverter_ps.hpp"
#include "hhparsers.hpp"
#include "hhparser_ps.hpp"
#include "collection.hpp"
#include "fsysutils.hpp"
#include "filescol.hpp"
#include "hhreader.hpp"
using namespace a2a;
void getStr(std::string& s)
{
s.clear();
auto sp = _searchPath("tests/hh/ps/multi", 4);
auto dir = Directory::Open(sp, false);
FilesCollection files;
dir->GetFiles(files, 1);
std::ifstream inFile;
files.First()->Read(s);
}
BENCHMARK("parse 1 hand", [](benchpress::context* ctx)
{
std::string str;
getStr(str);
auto parsers = HandHistoryParsersFactory();
auto pp = parsers.GetParserBySite("ps");
HandHistoryReader hp(pp, str);
ctx->reset_timer();
for (std::size_t i = 0; i < ctx->num_iterations(); ++i)
{
HandHistory hh;
try
{
hp.Next();
hp.Parse(hh);
}
catch (const std::exception& what)
{
//std::cout << hh.GetHandId() << what.what() << std::endl;
}
hp.Reset();
}
})
BENCHMARK("parse file", [](benchpress::context* ctx)
{
std::string str;
getStr(str);
auto parsers = HandHistoryParsersFactory();
auto pp = parsers.GetParserBySite("ps");
HandHistoryReader hp(pp, str);
ctx->reset_timer();
for (std::size_t i = 0; i < ctx->num_iterations(); ++i)
{
while (hp.Next())
{
HandHistory hh;
try
{
hp.Parse(hh);
}
catch (const std::exception& what)
{
//std::cout << hh.GetHandId() << what.what() << std::endl;
}
}
hp.Reset();
}
})
BENCHMARK("parse file[s]", [](benchpress::context* ctx)
{
using namespace a2a;
auto parsers = HandHistoryParsersFactory();
auto pp = parsers.GetParserBySite("ps");
auto dir = Directory::Open("D:\\libs\\SampleHandHistories\\PokerStars", true);
FilesCollection files;
dir->GetFiles(files);
std::string buff;
ctx->reset_timer();
for (const auto& f : files)
{
f->Read(buff);
HandHistoryReader hp(pp, buff);
while (hp.Next())
{
HandHistory hh;
try
{
hp.Parse(hh);
}
catch (const std::exception& err)
{
//std::cout << "ID:" << hh.GetHandId() << " ERRROR: " << err.what() << std::endl
//<< "***********************************************" << std::endl;
}
}
}
})
#ifdef _MSC_VER
#pragma warning (default: 4996)
#pragma warning (default: 4244)
#endif
<file_sep>/src/card.cxx
#include <cassert>
#include <stdexcept>
#include "card.hpp"
namespace a2a
{
Card::Card()
: Card(0, 0)
{
}
Card::Card(CardRank r, CardSuit s)
: Card(static_cast<int>(r), static_cast<int>(s))
{
}
void Card::Reset(CardRank r, CardSuit s)
{
index = (static_cast<int>(s)*RANK_MAX + static_cast<int>(r));
}
Card::Card(int r, int s)
: index(s*RANK_MAX + r)
{
}
static int char_to_rank(char c)
{
switch (c)
{
case '2': return static_cast<int>(CardRank::_2);
case '3': return static_cast<int>(CardRank::_3);
case '4': return static_cast<int>(CardRank::_4);
case '5': return static_cast<int>(CardRank::_5);
case '6': return static_cast<int>(CardRank::_6);
case '7': return static_cast<int>(CardRank::_7);
case '8': return static_cast<int>(CardRank::_8);
case '9': return static_cast<int>(CardRank::_9);
case 't':
case 'T': return static_cast<int>(CardRank::T);
case 'j':
case 'J': return static_cast<int>(CardRank::J);
case 'q':
case 'Q': return static_cast<int>(CardRank::Q);
case 'k':
case 'K': return static_cast<int>(CardRank::K);
case 'a':
case 'A': return static_cast<int>(CardRank::A);
default:
return -1;
}
}
static int char_to_suit(char c)
{
switch (c)
{
case 'c':
case 'C':
return static_cast<int>(CardSuit::clubs);
case 'd':
case 'D':
return static_cast<int>(CardSuit::diamonds);
case 'h':
case 'H':
return static_cast<int>(CardSuit::hearts);
case 's':
case 'S':
return static_cast<int>(CardSuit::spades);
default:
return -1;
};
}
int Card::ReadFromString(const char* in, Card& c)
{
assert(in != nullptr && "Card::TryFromString: NULL input");
int j = 0;
char ch = in[j]; int r = char_to_rank(ch);
while (ch && r<0)
{
ch = in[++j]; r = char_to_rank(ch);
}
if (r < 0) return 0;
int s = char_to_suit(in[++j]);
if (s < 0) return 0;
c.index = s*Card::RANK_MAX + r;
return j + 1;
}
Card Card::FromString(const char* s)
{
Card ret;
if (!ReadFromString(s, ret))
throw std::runtime_error("Failed to read Card from string: "+ (s?std::string(s):std::string("NULL")));
return ret;
}
Card Card::FromString(const std::string& s)
{
return FromString(s.c_str());
}
static const char rankCHARS[] = "23456789TJQKA";
static const char suitCHARS[] = "hdcs";
std::string Card::ToString() const
{
std::string ret;
ret += rankCHARS[RankCode()];
ret += suitCHARS[SuitCode()];
return ret;
}
std::ostream & operator<<(std::ostream & os, const Card & c)
{
return os << rankCHARS[c.RankCode()] << suitCHARS[c.SuitCode()];
}
}<file_sep>/src/hhconverters.cxx
#include "hhconverters.hpp"
namespace a2a
{
HandHistoryConvertersFactory::HandHistoryConvertersFactory() noexcept : TBasePluginFactory("HHConverters")
{
}
HandHistoryConverter::Ptr HandHistoryConvertersFactory::GetConverter(const std::string& converterName)
{
HandHistoryConverter::Ptr x = Create(converterName);
x->SetupConverter(m_defaultSettings);
return x;
}
HandHistoryConverter::Ptr HandHistoryConvertersFactory::GetConverter(GameSite gameSite)
{
switch (gameSite)
{
case GameSite::PokerStars:
case GameSite::PokerStarsEs:
case GameSite::PokerStarsFr:
case GameSite::PokerStarsIt:
{
static const std::string clsName(GameSiteUtils::GameSiteToString(GameSite::PokerStars));
if (!HasClass(clsName))
Register<PokerStars::HHConverter>(clsName);
return GetConverter(clsName);
}
default:
return GetConverter(GameSiteUtils::GameSiteToString(gameSite));
}
}
HandHistoryConverter::Ptr HandHistoryConvertersFactory::GetConverterBySite(const std::string& siteName)
{
return GetConverter(GameSiteUtils::GameSiteFromString(siteName));
}
}<file_sep>/tools/a2alua.cpp
#include <windows.h>
#include <tchar.h>
#include <exception>
#include <memory>
#include <vector>
#include <sstream>
#include <cstdint>
#include <iostream>
#include <functional>
#include <algorithm>
#include <iterator>
#include "luastate.hpp"
int _tmain(int argc, _TCHAR *argv[])
{
setlocale(LC_ALL, "en_US.UTF-8");
using namespace a2a;
if (argc < 2) {
std::cout << "a2alua <file.lua>" << std::endl;
return 1;
}
auto hTextFile = CreateFile(argv[1], GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hTextFile == INVALID_HANDLE_VALUE)
{
std::cout << "Failed to open file" << std::endl;
return 1;
}
DWORD dwFileSize = GetFileSize(hTextFile, &dwFileSize);
if (dwFileSize == 0)
{
std::cout << "Error reading file" << std::endl;
CloseHandle(hTextFile);
return 1;
}
DWORD dwBytesRead;
char *lpszText = new char[dwFileSize];
ReadFile(hTextFile, lpszText, dwFileSize, &dwBytesRead, NULL);
CloseHandle(hTextFile);
try
{
LuaState::Global().LoadSubmodule(LuaSubmodule::all);
}
catch (const std::exception& err)
{
std::cout << err.what() << std::endl;
return 1;
}
std::string err;
LuaState::Global().RunBuffer(lpszText, dwBytesRead, err, "a2alua");
delete []lpszText;
if (!err.empty()) {
std::cout << err << std::endl;
return 1;
}
return 0;
}<file_sep>/include/cardgame.hpp
#ifndef INCLUDE_CARDGAME_H
#define INCLUDE_CARDGAME_H
#include <type_traits>
#include "types.hpp"
#include "enumflags.hpp"
namespace a2a
{
// need masks for mixed games
enum class CardGameType : u32
{
// 16 bits - game
Unknown = 0,
Holdem = 1 << 0,
Omaha = 1 << 1,
OmahaHiLo = 1 << 2,
Omaha5c = 1 << 3,
Omaha5cHiLo = 1 << 4,
Courchevel = 1 << 5,
CourchevelHiLo = 1 << 6,
Stud7c = 1 << 7,
Stud7cHiLo = 1 << 8,
Razz = 1 << 9,
Draw5c = 1 << 10,
DrawTripple27 = 1 << 11,
DrawSingle27 = 1 << 12,
Badugi = 1 << 13,
AnyGame = 0x0000FFFF,
// 4 bits - bet type
NoLimit = 1 << 16,
PotLimit = 1 << 17,
FixedLimit = 1 << 18,
AnyBetType = 0x000F0000,
// 12 bits - mixed games flags
Mix_Game8 = 1 << 20,
Mix_HORSE = 1 << 21,
Mix_HOSE = 1 << 22,
Mix_NLHPLO = 1 << 23,
Mix_PLHPLO = 1 << 24,
Mix_Holdem = 1 << 25,
Mix_OmahaHiLo = 1 << 26,
Mix_TrippleStud = 1 << 27,
AnyMixGame = 0xFFF00000,
};
ENUM_FLAGS(CardGameType);
using CardGameTypeFlags = EnumFlags::flags<CardGameType>;
enum class CardGameMode : u32
{
Unknown = 0,
CashGame = 1 << 0,
Tournament = 1 << 1,
FastFold = 1 << 2, // zoom, snap etc
Freeroll = 1 << 3, // pokerstars Freeroll
BuyIn = 1 << 4, // has buying info
BuyInKnockout = 1 << 5,
Cap = 1 << 6, // nlcap
Ante = 1 << 7,
};
ENUM_FLAGS(CardGameMode);
using CardGameModeFlags = EnumFlags::flags<CardGameMode>;
namespace GameTypeUtils
{
inline constexpr CardGameType CardGame(const CardGameTypeFlags& flags)
{
return static_cast<CardGameType> ( (flags & CardGameType::AnyGame).underlying_value() );
}
inline constexpr CardGameType BetType(const CardGameTypeFlags& flags)
{
return static_cast<CardGameType> ((flags & CardGameType::AnyBetType).underlying_value());
}
inline constexpr CardGameType MixedGame(const CardGameTypeFlags& flags)
{
return static_cast<CardGameType> ((flags & CardGameType::AnyMixGame).underlying_value());
}
extern std::string CardGameTypeToStr(const CardGameTypeFlags&);
}
}
#endif
<file_sep>/include/stdutils.hpp
#ifndef INCLUDE_STDUTILS_HPP
#define INCLUDE_STDUTILS_HPP
#include <type_traits>
#include <algorithm>
#include <memory>
#include <iterator>
namespace a2a
{
namespace StdUtils
{
template< typename ContainerT, typename PredicateT >
void erase_if(ContainerT& items, const PredicateT& predicate) {
for (auto it = items.begin(); it != items.end(); ) {
if (predicate(*it)) it = items.erase(it);
else ++it;
}
};
template<typename TPair>
struct pair_second_type
{
typename TPair::second_type operator()(const TPair& p) const
{
return p.second;
}
};
template<typename TMap>
pair_second_type<typename TMap::value_type> map_second(const TMap& m)
{
return pair_second_type<typename TMap::value_type >();
}
template <class C>
inline const char* begin_ptr(const C& v)
{
return v.empty() ? nullptr : static_cast<const char*>(&v.front());
}
template <class C>
inline const char* end_ptr(const C& v)
{
return v.empty() ? nullptr : static_cast<const char*>(&v.back()) + sizeof(typename C::value_type);
}
template<typename T, typename... Args> std::unique_ptr<T> my_make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
}
}
#endif
<file_sep>/src/cardgame.cxx
#include <sstream>
#include "cardgame.hpp"
#include "sitesdata.hpp"
namespace a2a
{
namespace GameTypeUtils
{
std::string CardGameTypeToStr(const CardGameTypeFlags& t)
{
using namespace PokerStars;
std::stringstream ss;
if (t&CardGameType::AnyMixGame)
{
ss << MixGameToStr(MixedGame(t)) << " ("
<< GameToStr(CardGame(t)) << ' ' << BetTypeToStr(BetType(t)) << ')';
}
else
ss << GameToStr(CardGame(t)) << ' ' << BetTypeToStr(BetType(t));
return ss.str();
}
}
}
<file_sep>/include/lualineparser.hpp
#ifndef INCLUDE_LUALINEPARSER_HPP
#define INCLUDE_LUALINEPARSER_HPP
#include "types.hpp"
#include "hhlineparser.hpp"
#include "luastate.hpp"
namespace a2a
{
class LuaLineParser : public HandHistoryLineParser
{
public:
LuaLineParser(LuaState& luas, const LuaAddon& addon);
~LuaLineParser();
protected:
virtual const std::string& HandStart() const;
virtual ILineParserImpl* GetImplementation(HandHistory& _hh,
const HandHistoryParserSettings& _cfg,
const char*& _cursor) const;
private:
std::string m_handStart;
LuaState& m_lua;
int m_luaObjectRef;
};
}
#endif<file_sep>/include/hhfilesreader.hpp
#ifndef INCLUDE_HHFILESREADER_HPP
#define INCLUDE_HHFILESREADER_HPP
#include <unordered_map>
#include "types.hpp"
#include "hhparsers.hpp"
#include "filescol.hpp"
namespace a2a
{
class HandHistoryFilesReader final
{
public:
using parser_t = HandHistoryParser::Ptr;
using factory_t = HandHistoryParsersFactory;
using files_t = FilesCollection;
using reader_t = FilesCollectionReader;
using dict_t = std::unordered_map<parser_t, reader_t::Ptr>;
static const std::size_t TEST_BLOCK_SIZE = 512;
HandHistoryFilesReader(factory_t& factory, files_t& files, std::size_t testBlockSize = TEST_BLOCK_SIZE);
std::size_t Read(char* mem, std::size_t buff_size);
const parser_t& GetParser() const;
private:
dict_t m_map;
dict_t::const_iterator m_current;
std::string m_tail;
};
}
//
// inlines
//
namespace a2a
{
inline const HandHistoryFilesReader::parser_t& HandHistoryFilesReader::GetParser() const
{
static const parser_t _null = nullptr;
return m_current != m_map.cend() ? m_current->first : _null;
}
}
#endif<file_sep>/include/mempool.hpp
#ifndef INCLUDE_MEMPOOL_HPP
#define INCLUDE_MEMPOOL_HPP
#include <cassert>
#include <atomic>
#include <mutex>
#include <condition_variable>
#include <vector>
#include <stack>
namespace a2a
{
class MemoryPool final
{
public:
using chunk_t = std::vector<char>;
using lock_t = std::unique_lock<std::mutex>;
MemoryPool(std::size_t bufferSize, std::size_t buffersCount);
~MemoryPool();
class Buffer final
{
public:
using releaser_t = std::function<void(void)>;
Buffer(char* data, std::size_t size, const releaser_t& onRelease);
~Buffer();
char* Data() const;
std::size_t Size() const;
void Resize(std::size_t newSize);
Buffer(const Buffer&) = delete;
Buffer& operator=(const Buffer&) = delete;
private:
char* m_data;
std::size_t m_size;
releaser_t m_fOnRelease;
};
Buffer* GetBuffer();
private:
std::atomic<bool> m_abStop;
mutable std::mutex m_mutex;
std::condition_variable m_condReady;
std::stack<std::size_t> m_readyChunks;
std::vector<chunk_t> m_pool;
};
}
//
// inlines
//
namespace a2a
{
inline char* MemoryPool::Buffer::Data() const
{
return m_data;
}
inline std::size_t MemoryPool::Buffer::Size() const
{
return m_size;
}
inline void MemoryPool::Buffer::Resize(std::size_t nsize)
{
m_size = nsize;
}
}
#endif
<file_sep>/src/streamutils.cxx
#include <stdexcept>
#include <cassert>
#include <cstring>
#include "streamutils.hpp"
namespace a2a
{
namespace StreamUtils
{
std::istream& ReadLine_(std::istream& is, std::string& t, std::size_t& gcount, std::size_t max_size )
{
static const std::size_t MAX_BUFF = 1024;
char buff[MAX_BUFF]; *buff = 0;
gcount = 0;
std::istream::sentry se(is, true);
std::streambuf* sb = is.rdbuf();
int i = 0;
for (;;) {
int c = sb->sbumpc();
gcount++;
switch (c) {
case '\n':
gcount++;
t.assign(buff, i);
return is;
case '\r':
if (sb->sgetc() == '\n')
{
sb->sbumpc();
gcount++;
}
t.assign(buff, i);
return is;
case std::streambuf::traits_type::eof():
if (gcount>0) gcount--;
if (t.empty())
is.setstate(std::ios::eofbit);
t.assign(buff, i);
return is;
default:
if (max_size-- > 0 && i < MAX_BUFF - 1)
buff[i++] = (char)c;
}
}
}
std::istream& ReadLine(std::istream& is, std::string& t, std::size_t max_size)
{
std::size_t gc;
return ReadLine_(is, t, gc, max_size);
}
}
}
<file_sep>/include/cardseq.hpp
#ifndef INCLUDE_CARDSEQ_HPP
#define INCLUDE_CARDSEQ_HPP
#include <vector>
#include <string>
#include <iostream>
#include "types.hpp"
#include "card.hpp"
namespace a2a
{
class CardSeq
{
public:
CardSeq(int hiddenCards = 0) : m_hiddenCards(hiddenCards)
{}
CardSeq(const char*);
static int FromString(const char*, CardSeq&);
static CardSeq FromString(const char*);
static CardSeq FromString(const std::string&);
std::string ToString() const;
std::string ToString(const std::string& format) const;
bool Empty() const;
std::size_t Size() const;
std::size_t HiddenCards() const;
std::size_t VisibleCards() const;
bool Has(const Card&) const;
void Clear();
bool Add(const Card&);
int Add(const CardSeq&);
void Reset(const CardSeq&);
void Clear(const CardSeq&);
const std::string& GetEvalHint() const;
void SetEvalHint(const std::string& hint);
friend std::ostream& operator<< (std::ostream& os, const CardSeq& c);
std::ostream& ToStream(std::ostream& os, const std::string& format) const;
private:
using seq_t = std::vector<Card>;
int m_hiddenCards;
seq_t m_seq;
seq_t m_stash;
std::string m_evalHint;
void Stash();
};
}
//
// inlines
//
namespace a2a
{
inline bool CardSeq::Empty() const
{
return m_seq.empty();
}
inline std::size_t CardSeq::Size() const
{
return m_seq.size() + m_hiddenCards;
}
inline std::size_t CardSeq::HiddenCards() const
{
return m_hiddenCards;
}
inline std::size_t CardSeq::VisibleCards() const
{
return m_seq.size();
}
inline const std::string & a2a::CardSeq::GetEvalHint() const
{
return m_evalHint;
}
inline void a2a::CardSeq::SetEvalHint(const std::string & hint)
{
m_evalHint = hint;
}
}
#endif<file_sep>/src/gamestagescol.cxx
#include <iterator>
#include <algorithm>
#include "gamestagescol.hpp"
namespace a2a
{
HandActions GameStages::GetActions() const
{
HandActions ret;
for (auto const& i : m_items)
{
ret.Add(i->GetActions());
}
return ret;
}
HandActions GameStages::GetActions(const HandActions::predicate_t& predicate) const
{
HandActions ret;
for (auto const& i : m_items)
{
ret.Add(i->GetActions(predicate));
}
return ret;
}
}
<file_sep>/src/handactioncol.cxx
#include <iterator>
#include <algorithm>
#include "stdutils.hpp"
#include "handactioncol.hpp"
namespace a2a
{
int HandActions::ChipsSumm() const
{
int ret = 0;
for (const auto& a : m_items)
ret += a->GetChips();
return ret;
}
}
<file_sep>/src/pot.cxx
#include "pot.hpp"
#include "seat.hpp"
namespace a2a
{
void Pot::SetRake(int rake)
{
m_rake = rake;
}
int Pot::GetRake() const
{
return m_rake;
}
void Pot::AddSidePot(int sidePotSize)
{
m_sidePots.push_back(sidePotSize);
}
int Pot::GetSidePot(int sidePotIndex) const
{
return m_sidePots[sidePotIndex];
}
std::size_t Pot::GetSidePotsNum() const
{
return m_sidePots.size();
}
const Pot::side_pots & Pot::GetSidePots() const
{
return m_sidePots;
}
void Pot::ProcessAction(const HandAction::Ptr& action, const Seat::Ptr& seat)
{
auto chips = action->GetChips();
if (seat->GetStake().chips > m_max
&& !action->IsActionType(HandActionType::SmallAndBigBlind | HandActionType::Ante))
m_max = seat->GetStake().chips;
m_chips += chips;
//m_potActions.Add(action);
//std::cout << "pot+ " << chips <<" pot = " << m_chips << " max=" << m_max << std::endl;
}
}<file_sep>/src/filescol.cxx
#include "filescol.hpp"
#include "strutils.hpp"
namespace a2a
{
//---------------------------------------------------------------- FilesCollection
FilesCollection::predicate_t FilesCollection::HasHands_(const HandHistoryParser::Ptr& parser, std::size_t testBlockSize)
{
return [&parser, testBlockSize](const value_type& a) -> bool
{
std::string buff;
a->Read(buff, testBlockSize);
return parser->Next(StdUtils::begin_ptr(buff), StdUtils::end_ptr(buff)) != nullptr;
};
}
FilesCollection::predicate_t FilesCollection::HasExtension_(const std::string& ext)
{
return [&ext](const value_type& a) -> bool
{
return a->GetExt() == ext;
};
}
FilesCollection::visitor_t FilesCollection::MakeCache_(std::size_t blockSize)
{
return [blockSize](value_type& a)
{
a->ReadCache(blockSize);
};
}
FilesCollection::visitor_t FilesCollection::ClearCache_()
{
return [](value_type& a)
{
a->ClearCache();
};
}
FilesCollection::const_visitor_t FilesCollection::CalcSize_(i64& Size)
{
Size = 0;
return [&Size](const value_type& a)
{
Size+=a->FileSize();
};
}
//---------------------------------------------------------------- FilesCollectionReader
FilesCollectionReader::FilesCollectionReader(const files_t& files, bool addLineBreak) :
m_files(files), m_addLineBreak(addLineBreak), m_currIndex(0)
{
}
std::size_t FilesCollectionReader::Read(char* mem, std::size_t blockSize)
{
std::size_t tail = 0;
for (;;)
{
if (!m_is.is_open() && !nextStream())
return tail;
if (m_is.read(mem + tail, blockSize - tail))
return blockSize;
tail += static_cast<std::size_t>(m_is.gcount());
m_is.close();
if (m_addLineBreak)
{
mem[tail++] = '\n';
if (tail >= blockSize)
return blockSize;
}
}
}
bool FilesCollectionReader::nextStream()
{
if (m_currIndex >= m_files.Size())
return false;
m_files[m_currIndex++]->GetStream(m_is);
if (!m_is.is_open())
throw std::runtime_error(std::string("Failed to read file in collection: ") + m_files[m_currIndex - 1]->GetFullPath());
return true;
}
}<file_sep>/include/gamestagetype.hpp
#ifndef INCLUDE_GAMESTAGETYPE_HPP
#define INCLUDE_GAMESTAGETYPE_HPP
#include <type_traits>
namespace a2a
{
enum class GameStageType
{
Current = 0,
Seating = 1,
Blinds = 2,
//
_3rdStreet = 3,
_4thStreet = 4,
_5thStreet = 5,
_6thStreet = 6,
//
_DrawHands = 7,
_1stDraw = 8,
_2ndDraw = 9,
_3rdDraw = 10,
//
Preflop = 11,
Flop = 12,
Turn = 13,
River = 14,
Flop_2nd = 15,
Turn_2nd = 16,
River_2nd = 17,
Showdown = 18,
Showdown_2nd = 19,
Summary = 20,
Any = 255,
};
namespace GameStageUtils
{
inline constexpr bool IsAnyStreetStage(GameStageType gsType)
{
return
static_cast<std::underlying_type<GameStageType>::type>(gsType) <
static_cast<std::underlying_type<GameStageType>::type>(GameStageType::Showdown) &&
static_cast<std::underlying_type<GameStageType>::type>(gsType) >
static_cast<std::underlying_type<GameStageType>::type>(GameStageType::Blinds);
}
extern const char* GameStageToString(GameStageType gs);
}
}
#endif<file_sep>/src/datetimeutils.cxx
#include <cstring>
#include <iomanip>
#include <type_traits>
#include "datetimeutils.hpp"
#include "strutils.hpp"
namespace a2a
{
namespace DateTimeUtils
{
void LocalTimeS(struct tm *ltm, std::time_t* lt)
{
#ifdef _MSC_VER
localtime_s(ltm, lt);
#else
localtime_r(lt, ltm); // mingw ???
#endif // _MSC_VER
}
struct TZLocalOffset final
{
TZLocalOffset()
{
#ifdef _MSC_VER
_tzset(); _get_timezone(&Value);
#else
tzset();
std::time_t now = std::time(NULL);
struct tm *gm = std::gmtime(&now);
std::time_t gmt = std::mktime(gm);
struct tm *loc = std::localtime(&now);
std::time_t local = std::mktime(loc);
Value = std::difftime(local, gmt);
#endif // _MSC_VER
}
long Value;
};
std::time_t GetUTCTime(int Y, int M, int D, int h, int m, int s, TimeZonesType timeZone)
{
std::tm timeinfo;
timeinfo.tm_sec = s;
timeinfo.tm_min = m;
timeinfo.tm_hour = h;
timeinfo.tm_mday = D;
timeinfo.tm_mon = M - 1;
timeinfo.tm_year = Y - 1900;
return std::mktime(&timeinfo) - GetTimeZoneOffset(timeZone) ;
}
long GetLocalTimeZoneOffset()
{
static const TZLocalOffset LocalOffset;
return LocalOffset.Value;
}
static long constexpr _UTC(int H, int M = 0)
{
return H * 60 * 60 + M * 60;
}
static const long TZ_OFFSETS[] =
{
_UTC(0),
_UTC(1),
_UTC(10,30),
_UTC(9,30),
_UTC(-5),
_UTC(8,45),
_UTC(3),
_UTC(11),
_UTC(10),
_UTC(10),
_UTC(4,30),
_UTC(-8),
_UTC(-9),
_UTC(6),
_UTC(-3),
_UTC(-4),
_UTC(12),
_UTC(12),
_UTC(-12),
_UTC(5),
_UTC(-3),
_UTC(3),
_UTC(-3),
_UTC(9),
_UTC(8),
_UTC(0),
_UTC(-1),
_UTC(5),
_UTC(4),
_UTC(2),
_UTC(8),
_UTC(-4),
_UTC(-2),
_UTC(-3),
_UTC(6),
_UTC(6),
_UTC(3),
_UTC(11),
_UTC(2),
_UTC(6,30),
_UTC(-5),
_UTC(2),
_UTC(1),
_UTC(13,45),
_UTC(12,45),
_UTC(9),
_UTC(8),
_UTC(10),
_UTC(10),
_UTC(-4),
_UTC(-5),
_UTC(-10),
_UTC(-3),
_UTC(-3),
_UTC(-5),
_UTC(-6),
_UTC(-5),
_UTC(-1),
_UTC(7),
_UTC(4),
_UTC(7),
_UTC(10),
_UTC(5),
_UTC(-5),
_UTC(-5),
_UTC(3),
_UTC(-5),
_UTC(-4),
_UTC(3),
_UTC(2),
_UTC(0),
_UTC(-1),
_UTC(-5),
_UTC(-4),
_UTC(6),
_UTC(3),
_UTC(13),
_UTC(12),
_UTC(-3),
_UTC(-4),
_UTC(-2),
_UTC(7),
_UTC(-6),
_UTC(-9),
_UTC(4),
_UTC(-3),
_UTC(12),
_UTC(0),
_UTC(4),
_UTC(-4),
_UTC(8),
_UTC(-9),
_UTC(-10),
_UTC(8),
_UTC(8),
_UTC(7),
_UTC(9),
_UTC(7),
_UTC(3),
_UTC(6),
_UTC(4,30),
_UTC(9),
_UTC(8),
_UTC(3,30),
_UTC(5,30),
_UTC(9),
_UTC(10),
_UTC(6),
_UTC(11),
_UTC(8),
_UTC(7),
_UTC(9),
_UTC(4),
_UTC(11),
_UTC(11),
_UTC(10,30),
_UTC(14),
_UTC(12),
_UTC(12),
_UTC(10),
_UTC(-9),
_UTC(5),
_UTC(-6),
_UTC(12),
_UTC(6,30),
_UTC(4),
_UTC(3),
_UTC(-7),
_UTC(-6),
_UTC(4),
_UTC(5),
_UTC(8),
_UTC(-1),
_UTC(11),
_UTC(-2),
_UTC(11),
_UTC(7),
_UTC(6),
_UTC(5,45),
_UTC(12),
_UTC(-3),
_UTC(-11),
_UTC(13),
_UTC(12),
_UTC(-2),
_UTC(7),
_UTC(6),
_UTC(5),
_UTC(-3),
_UTC(-7),
_UTC(-5),
_UTC(12),
_UTC(12),
_UTC(10),
_UTC(13),
_UTC(8),
_UTC(5),
_UTC(-2),
_UTC(-3),
_UTC(11),
_UTC(-8),
_UTC(-7),
_UTC(9),
_UTC(-3),
_UTC(-4),
_UTC(-4),
_UTC(6),
_UTC(-5),
_UTC(4),
_UTC(-3),
_UTC(-6),
_UTC(10),
_UTC(4),
_UTC(2),
_UTC(11),
_UTC(4),
_UTC(8),
_UTC(11),
_UTC(-3),
_UTC(-11),
_UTC(3),
_UTC(-7),
_UTC(-10),
_UTC(5),
_UTC(5),
_UTC(13),
_UTC(9),
_UTC(5),
_UTC(13),
_UTC(12),
_UTC(-8),
_UTC(9),
_UTC(8),
_UTC(-2),
_UTC(-3),
_UTC(5),
_UTC(-9),
_UTC(-4),
_UTC(11),
_UTC(10),
_UTC(6),
_UTC(11),
_UTC(-10),
_UTC(12),
_UTC(-3),
_UTC(2),
_UTC(1),
_UTC(1),
_UTC(0),
_UTC(12),
_UTC(-2),
_UTC(-3),
_UTC(7),
_UTC(9),
_UTC(8),
_UTC(14),
_UTC(0),
_UTC(-11),
_UTC(-12),
_UTC(10),
_UTC(9),
_UTC(10),
_UTC(6),
_UTC(5),
_UTC(0),
_UTC(1),
};
long GetTimeZoneOffset(TimeZonesType timeZone)
{
return TZ_OFFSETS[static_cast< std::underlying_type<TimeZonesType>::type > ( timeZone ) ];
}
TimeZonesType TimeZoneFromAbbreviation(const std::string& Abbreviation)
{
using namespace StrUtils;
using namespace StrUtils::literals;
switch (str_hash(Abbreviation))
{
case "A"_hash: return TimeZonesType::A;
case "ACDT"_hash: return TimeZonesType::ACDT;
case "ACST"_hash: return TimeZonesType::ACST;
case "ACT"_hash: return TimeZonesType::ACT;
case "ACWST"_hash: return TimeZonesType::ACWST;
case "ADT"_hash: return TimeZonesType::ADT;
case "AEDT"_hash: return TimeZonesType::AEDT;
case "AEST"_hash: return TimeZonesType::AEST;
case "AET"_hash: return TimeZonesType::AET;
case "AFT"_hash: return TimeZonesType::AFT;
case "AKDT"_hash: return TimeZonesType::AKDT;
case "AKST"_hash: return TimeZonesType::AKST;
case "ALMT"_hash: return TimeZonesType::ALMT;
case "AMST"_hash: return TimeZonesType::AMST;
case "AMT"_hash: return TimeZonesType::AMT;
case "ANAST"_hash: return TimeZonesType::ANAST;
case "ANAT"_hash: return TimeZonesType::ANAT;
case "AoE"_hash: return TimeZonesType::AoE;
case "AQTT"_hash: return TimeZonesType::AQTT;
case "ART"_hash: return TimeZonesType::ART;
case "AST"_hash: return TimeZonesType::AST;
case "AT"_hash: return TimeZonesType::AT;
case "AWDT"_hash: return TimeZonesType::AWDT;
case "AWST"_hash: return TimeZonesType::AWST;
case "AZOST"_hash: return TimeZonesType::AZOST;
case "AZOT"_hash: return TimeZonesType::AZOT;
case "AZST"_hash: return TimeZonesType::AZST;
case "AZT"_hash: return TimeZonesType::AZT;
case "B"_hash: return TimeZonesType::B;
case "BNT"_hash: return TimeZonesType::BNT;
case "BOT"_hash: return TimeZonesType::BOT;
case "BRST"_hash: return TimeZonesType::BRST;
case "BRT"_hash: return TimeZonesType::BRT;
case "BST"_hash: return TimeZonesType::BST;
case "BTT"_hash: return TimeZonesType::BTT;
case "C"_hash: return TimeZonesType::C;
case "CAST"_hash: return TimeZonesType::CAST;
case "CAT"_hash: return TimeZonesType::CAT;
case "CCT"_hash: return TimeZonesType::CCT;
case "CDT"_hash: return TimeZonesType::CDT;
case "CEST"_hash: return TimeZonesType::CEST;
case "CET"_hash: return TimeZonesType::CET;
case "CHADT"_hash: return TimeZonesType::CHADT;
case "CHAST"_hash: return TimeZonesType::CHAST;
case "CHOST"_hash: return TimeZonesType::CHOST;
case "CHOT"_hash: return TimeZonesType::CHOT;
case "ChST"_hash: return TimeZonesType::ChST;
case "CHUT"_hash: return TimeZonesType::CHUT;
case "CIDST"_hash: return TimeZonesType::CIDST;
case "CIST"_hash: return TimeZonesType::CIST;
case "CKT"_hash: return TimeZonesType::CKT;
case "CLST"_hash: return TimeZonesType::CLST;
case "CLT"_hash: return TimeZonesType::CLT;
case "COT"_hash: return TimeZonesType::COT;
case "CST"_hash: return TimeZonesType::CST;
case "CT"_hash: return TimeZonesType::CT;
case "CVT"_hash: return TimeZonesType::CVT;
case "CXT"_hash: return TimeZonesType::CXT;
case "D"_hash: return TimeZonesType::D;
case "DAVT"_hash: return TimeZonesType::DAVT;
case "DDUT"_hash: return TimeZonesType::DDUT;
case "E"_hash: return TimeZonesType::E;
case "EASST"_hash: return TimeZonesType::EASST;
case "EAST"_hash: return TimeZonesType::EAST;
case "EAT"_hash: return TimeZonesType::EAT;
case "ECT"_hash: return TimeZonesType::ECT;
case "EDT"_hash: return TimeZonesType::EDT;
case "EEST"_hash: return TimeZonesType::EEST;
case "EET"_hash: return TimeZonesType::EET;
case "EGST"_hash: return TimeZonesType::EGST;
case "EGT"_hash: return TimeZonesType::EGT;
case "EST"_hash: return TimeZonesType::EST;
case "ET"_hash: return TimeZonesType::ET;
case "F"_hash: return TimeZonesType::F;
case "FET"_hash: return TimeZonesType::FET;
case "FJST"_hash: return TimeZonesType::FJST;
case "FJT"_hash: return TimeZonesType::FJT;
case "FKST"_hash: return TimeZonesType::FKST;
case "FKT"_hash: return TimeZonesType::FKT;
case "FNT"_hash: return TimeZonesType::FNT;
case "G"_hash: return TimeZonesType::G;
case "GALT"_hash: return TimeZonesType::GALT;
case "GAMT"_hash: return TimeZonesType::GAMT;
case "GET"_hash: return TimeZonesType::GET;
case "GFT"_hash: return TimeZonesType::GFT;
case "GILT"_hash: return TimeZonesType::GILT;
case "GMT"_hash: return TimeZonesType::GMT;
case "GST"_hash: return TimeZonesType::GST;
case "GYT"_hash: return TimeZonesType::GYT;
case "H"_hash: return TimeZonesType::H;
case "HADT"_hash: return TimeZonesType::HADT;
case "HAST"_hash: return TimeZonesType::HAST;
case "HKT"_hash: return TimeZonesType::HKT;
case "HOVST"_hash: return TimeZonesType::HOVST;
case "HOVT"_hash: return TimeZonesType::HOVT;
case "I"_hash: return TimeZonesType::I;
case "ICT"_hash: return TimeZonesType::ICT;
case "IDT"_hash: return TimeZonesType::IDT;
case "IOT"_hash: return TimeZonesType::IOT;
case "IRDT"_hash: return TimeZonesType::IRDT;
case "IRKST"_hash: return TimeZonesType::IRKST;
case "IRKT"_hash: return TimeZonesType::IRKT;
case "IRST"_hash: return TimeZonesType::IRST;
case "IST"_hash: return TimeZonesType::IST;
case "JST"_hash: return TimeZonesType::JST;
case "K"_hash: return TimeZonesType::K;
case "KGT"_hash: return TimeZonesType::KGT;
case "KOST"_hash: return TimeZonesType::KOST;
case "KRAST"_hash: return TimeZonesType::KRAST;
case "KRAT"_hash: return TimeZonesType::KRAT;
case "KST"_hash: return TimeZonesType::KST;
case "KUYT"_hash: return TimeZonesType::KUYT;
case "L"_hash: return TimeZonesType::L;
case "LHDT"_hash: return TimeZonesType::LHDT;
case "LHST"_hash: return TimeZonesType::LHST;
case "LINT"_hash: return TimeZonesType::LINT;
case "M"_hash: return TimeZonesType::M;
case "MAGST"_hash: return TimeZonesType::MAGST;
case "MAGT"_hash: return TimeZonesType::MAGT;
case "MART"_hash: return TimeZonesType::MART;
case "MAWT"_hash: return TimeZonesType::MAWT;
case "MDT"_hash: return TimeZonesType::MDT;
case "MHT"_hash: return TimeZonesType::MHT;
case "MMT"_hash: return TimeZonesType::MMT;
case "MSD"_hash: return TimeZonesType::MSD;
case "MSK"_hash: return TimeZonesType::MSK;
case "MST"_hash: return TimeZonesType::MST;
case "MT"_hash: return TimeZonesType::MT;
case "MUT"_hash: return TimeZonesType::MUT;
case "MVT"_hash: return TimeZonesType::MVT;
case "MYT"_hash: return TimeZonesType::MYT;
case "N"_hash: return TimeZonesType::N;
case "NCT"_hash: return TimeZonesType::NCT;
case "NDT"_hash: return TimeZonesType::NDT;
case "NFT"_hash: return TimeZonesType::NFT;
case "NOVST"_hash: return TimeZonesType::NOVST;
case "NOVT"_hash: return TimeZonesType::NOVT;
case "NPT"_hash: return TimeZonesType::NPT;
case "NRT"_hash: return TimeZonesType::NRT;
case "NST"_hash: return TimeZonesType::NST;
case "NUT"_hash: return TimeZonesType::NUT;
case "NZDT"_hash: return TimeZonesType::NZDT;
case "NZST"_hash: return TimeZonesType::NZST;
case "O"_hash: return TimeZonesType::O;
case "OMSST"_hash: return TimeZonesType::OMSST;
case "OMST"_hash: return TimeZonesType::OMST;
case "ORAT"_hash: return TimeZonesType::ORAT;
case "P"_hash: return TimeZonesType::P;
case "PDT"_hash: return TimeZonesType::PDT;
case "PET"_hash: return TimeZonesType::PET;
case "PETST"_hash: return TimeZonesType::PETST;
case "PETT"_hash: return TimeZonesType::PETT;
case "PGT"_hash: return TimeZonesType::PGT;
case "PHOT"_hash: return TimeZonesType::PHOT;
case "PHT"_hash: return TimeZonesType::PHT;
case "PKT"_hash: return TimeZonesType::PKT;
case "PMDT"_hash: return TimeZonesType::PMDT;
case "PMST"_hash: return TimeZonesType::PMST;
case "PONT"_hash: return TimeZonesType::PONT;
case "PST"_hash: return TimeZonesType::PST;
case "PT"_hash: return TimeZonesType::PT;
case "PWT"_hash: return TimeZonesType::PWT;
case "PYST"_hash: return TimeZonesType::PYST;
case "PYT"_hash: return TimeZonesType::PYT;
case "Q"_hash: return TimeZonesType::Q;
case "QYZT"_hash: return TimeZonesType::QYZT;
case "R"_hash: return TimeZonesType::R;
case "RET"_hash: return TimeZonesType::RET;
case "ROTT"_hash: return TimeZonesType::ROTT;
case "S"_hash: return TimeZonesType::S;
case "SAKT"_hash: return TimeZonesType::SAKT;
case "SAMT"_hash: return TimeZonesType::SAMT;
case "SAST"_hash: return TimeZonesType::SAST;
case "SBT"_hash: return TimeZonesType::SBT;
case "SCT"_hash: return TimeZonesType::SCT;
case "SGT"_hash: return TimeZonesType::SGT;
case "SRET"_hash: return TimeZonesType::SRET;
case "SRT"_hash: return TimeZonesType::SRT;
case "SST"_hash: return TimeZonesType::SST;
case "SYOT"_hash: return TimeZonesType::SYOT;
case "T"_hash: return TimeZonesType::T;
case "TAHT"_hash: return TimeZonesType::TAHT;
case "TFT"_hash: return TimeZonesType::TFT;
case "TJT"_hash: return TimeZonesType::TJT;
case "TKT"_hash: return TimeZonesType::TKT;
case "TLT"_hash: return TimeZonesType::TLT;
case "TMT"_hash: return TimeZonesType::TMT;
case "TOT"_hash: return TimeZonesType::TOT;
case "TVT"_hash: return TimeZonesType::TVT;
case "U"_hash: return TimeZonesType::U;
case "ULAST"_hash: return TimeZonesType::ULAST;
case "ULAT"_hash: return TimeZonesType::ULAT;
case "UYST"_hash: return TimeZonesType::UYST;
case "UYT"_hash: return TimeZonesType::UYT;
case "UZT"_hash: return TimeZonesType::UZT;
case "V"_hash: return TimeZonesType::V;
case "VET"_hash: return TimeZonesType::VET;
case "VLAST"_hash: return TimeZonesType::VLAST;
case "VLAT"_hash: return TimeZonesType::VLAT;
case "VOST"_hash: return TimeZonesType::VOST;
case "VUT"_hash: return TimeZonesType::VUT;
case "W"_hash: return TimeZonesType::W;
case "WAKT"_hash: return TimeZonesType::WAKT;
case "WARST"_hash: return TimeZonesType::WARST;
case "WAST"_hash: return TimeZonesType::WAST;
case "WAT"_hash: return TimeZonesType::WAT;
case "WEST"_hash: return TimeZonesType::WEST;
case "WET"_hash: return TimeZonesType::WET;
case "WFT"_hash: return TimeZonesType::WFT;
case "WGST"_hash: return TimeZonesType::WGST;
case "WGT"_hash: return TimeZonesType::WGT;
case "WIB"_hash: return TimeZonesType::WIB;
case "WIT"_hash: return TimeZonesType::WIT;
case "WITA"_hash: return TimeZonesType::WITA;
case "WST"_hash: return TimeZonesType::WST;
case "WT"_hash: return TimeZonesType::WT;
case "X"_hash: return TimeZonesType::X;
case "Y"_hash: return TimeZonesType::Y;
case "YAKST"_hash: return TimeZonesType::YAKST;
case "YAKT"_hash: return TimeZonesType::YAKT;
case "YAPT"_hash: return TimeZonesType::YAPT;
case "YEKST"_hash: return TimeZonesType::YEKST;
case "YEKT"_hash: return TimeZonesType::YEKT;
case "Z"_hash: return TimeZonesType::Z;
default:
return TimeZonesType::UTC;
}
}
static const char* TZ_ABBREVIATIONS[] =
{
"UTC",
"A",
"ACDT",
"ACST",
"ACT",
"ACWST",
"ADT",
"AEDT",
"AEST",
"AET",
"AFT",
"AKDT",
"AKST",
"ALMT",
"AMST",
"AMT",
"ANAST",
"ANAT",
"AoE",
"AQTT",
"ART",
"AST",
"AT",
"AWDT",
"AWST",
"AZOST",
"AZOT",
"AZST",
"AZT",
"B",
"BNT",
"BOT",
"BRST",
"BRT",
"BST",
"BTT",
"C",
"CAST",
"CAT",
"CCT",
"CDT",
"CEST",
"CET",
"CHADT",
"CHAST",
"CHOST",
"CHOT",
"ChST",
"CHUT",
"CIDST",
"CIST",
"CKT",
"CLST",
"CLT",
"COT",
"CST",
"CT",
"CVT",
"CXT",
"D",
"DAVT",
"DDUT",
"E",
"EASST",
"EAST",
"EAT",
"ECT",
"EDT",
"EEST",
"EET",
"EGST",
"EGT",
"EST",
"ET",
"F",
"FET",
"FJST",
"FJT",
"FKST",
"FKT",
"FNT",
"G",
"GALT",
"GAMT",
"GET",
"GFT",
"GILT",
"GMT",
"GST",
"GYT",
"H",
"HADT",
"HAST",
"HKT",
"HOVST",
"HOVT",
"I",
"ICT",
"IDT",
"IOT",
"IRDT",
"IRKST",
"IRKT",
"IRST",
"IST",
"JST",
"K",
"KGT",
"KOST",
"KRAST",
"KRAT",
"KST",
"KUYT",
"L",
"LHDT",
"LHST",
"LINT",
"M",
"MAGST",
"MAGT",
"MART",
"MAWT",
"MDT",
"MHT",
"MMT",
"MSD",
"MSK",
"MST",
"MT",
"MUT",
"MVT",
"MYT",
"N",
"NCT",
"NDT",
"NFT",
"NOVST",
"NOVT",
"NPT",
"NRT",
"NST",
"NUT",
"NZDT",
"NZST",
"O",
"OMSST",
"OMST",
"ORAT",
"P",
"PDT",
"PET",
"PETST",
"PETT",
"PGT",
"PHOT",
"PHT",
"PKT",
"PMDT",
"PMST",
"PONT",
"PST",
"PT",
"PWT",
"PYST",
"PYT",
"Q",
"QYZT",
"R",
"RET",
"ROTT",
"S",
"SAKT",
"SAMT",
"SAST",
"SBT",
"SCT",
"SGT",
"SRET",
"SRT",
"SST",
"SYOT",
"T",
"TAHT",
"TFT",
"TJT",
"TKT",
"TLT",
"TMT",
"TOT",
"TVT",
"U",
"ULAST",
"ULAT",
"UYST",
"UYT",
"UZT",
"V",
"VET",
"VLAST",
"VLAT",
"VOST",
"VUT",
"W",
"WAKT",
"WARST",
"WAST",
"WAT",
"WEST",
"WET",
"WFT",
"WGST",
"WGT",
"WIB",
"WIT",
"WITA",
"WST",
"WT",
"X",
"Y",
"YAKST",
"YAKT",
"YAPT",
"YEKST",
"YEKT",
"Z",
"GMT1",
};
const char* TimeZoneToAbbreviation(TimeZonesType timeZone)
{
return TZ_ABBREVIATIONS[static_cast< std::underlying_type<TimeZonesType>::type > (timeZone)];
}
std::ostream& TimeToStream(std::ostream& os, std::time_t t, const char* fmt)
{
struct tm ltm;
std::memset(<m, 0, sizeof(struct tm));
LocalTimeS(<m, &t);
#ifdef _MSC_VER
os << std::put_time(<m, fmt);
#else
char mbstr[256];
if (std::strftime(mbstr, sizeof(mbstr), fmt, <m))
os << mbstr;
#endif
return os;
}
}
}
<file_sep>/include/chips.hpp
#ifndef INCLUDE_CHIPS_H
#define INCLUDE_CHIPS_H
#include "handactiontype.hpp"
namespace a2a
{
struct BuyIn
{
int prizePool;
int rake;
int knockOut;
BuyIn()
:prizePool(0)
, rake(0)
, knockOut(0)
{}
};
struct GameLimit
{
int smallBlind;
int bigBlind;
int cap;
int ante;
int smallBlindLevel;
int bigBlindLevel;
GameLimit()
: smallBlind(0)
, bigBlind(0)
, cap(0)
, ante(0)
, smallBlindLevel(0)
, bigBlindLevel(0)
{}
};
struct Stake
{
int chips;
HandActionTypeFlags actionType;
Stake()
: chips(0)
, actionType(HandActionType::Unknown)
{
}
void Reset()
{
chips = 0; actionType = HandActionType::Unknown;
}
};
}
#endif<file_sep>/src/position.cxx
#include <map>
#include "position.hpp"
namespace a2a
{
namespace PokerPositionUtils
{
using map_t = std::map<PokerPosition, const std::string>;
static const map_t PosShortNames =
{
{ PokerPosition::BB, "BB" },
{ PokerPosition::BTN, "BTN" },
{ PokerPosition::CO, "CO" },
{ PokerPosition::EMPTY, "EMPTY" },
{ PokerPosition::MP, "MP*" },
{ PokerPosition::MP1, "MP" },
{ PokerPosition::MP2, "MP+1" },
{ PokerPosition::MP3, "MP+2" },
{ PokerPosition::SB, "SB" },
{ PokerPosition::UTG, "UTG*" },
{ PokerPosition::UTG1, "UTG" },
{ PokerPosition::UTG2, "UTG+1" },
{ PokerPosition::UTG3, "UTG+2" },
};
static const std::string _empty = "EMPTY";
const std::string& PokerPosToShortStr(PokerPosition pos)
{
auto i = PosShortNames.find(pos);
return i == PosShortNames.end() ? _empty : i->second;
}
PokerPosition PokerPosNext(PokerPosition pos)
{
switch (pos)
{
case PokerPosition::UTG1: return PokerPosition::UTG2;
case PokerPosition::UTG2: return PokerPosition::UTG3;
case PokerPosition::UTG3: return PokerPosition::MP1;
case PokerPosition::UTG: return PokerPosition::MP;
case PokerPosition::MP1: return PokerPosition::MP2;
case PokerPosition::MP2: return PokerPosition::MP3;
case PokerPosition::MP3: return PokerPosition::CO;
case PokerPosition::MP: return PokerPosition::CO;
case PokerPosition::CO: return PokerPosition::BTN;
case PokerPosition::BTN: return PokerPosition::SB;
case PokerPosition::SB: return PokerPosition::BB;
case PokerPosition::BB: return PokerPosition::UTG1;
default: return PokerPosition::EMPTY;
}
}
PokerPosition PokerPosPrev(PokerPosition pos)
{
switch (pos)
{
case PokerPosition::UTG1: return PokerPosition::BB;
case PokerPosition::UTG2: return PokerPosition::UTG1;
case PokerPosition::UTG3: return PokerPosition::UTG2;
case PokerPosition::UTG: return PokerPosition::BB;
case PokerPosition::MP1: return PokerPosition::UTG3;
case PokerPosition::MP2: return PokerPosition::MP1;
case PokerPosition::MP3: return PokerPosition::MP2;
case PokerPosition::MP: return PokerPosition::UTG;
case PokerPosition::CO: return PokerPosition::MP3;
case PokerPosition::BTN: return PokerPosition::CO;
case PokerPosition::SB: return PokerPosition::BTN;
case PokerPosition::BB: return PokerPosition::SB;
default: return PokerPosition::EMPTY;
}
}
}
}<file_sep>/include/luastate.hpp
#ifndef INCLUDE_LUASTATE_HPP
#define INCLUDE_LUASTATE_HPP
#include <memory>
#include <string>
#include <stdexcept>
#include <vector>
#include <map>
#include <unordered_map>
#include "lua.hpp"
#include "types.hpp"
#include "version.hpp"
namespace a2a
{
using lua_voidFuncion = void(*)(lua_State*);
class LuaError : public std::runtime_error
{
public:
LuaError(const std::string& str) : std::runtime_error("A2A LUA: error: " + str) {}
};
struct LuaAddon final
{
LuaAddon() : version (1,0) {}
std::string name;
std::string type;
Version version;
std::string description;
};
using LuaAddonsVec = std::vector<LuaAddon>;
using LuaAddonsMap = std::unordered_map<std::string, LuaAddonsVec>;
enum class LuaSubmodule
{
handhistory,
parsers,
all
};
class LuaState
{
public:
LuaState();
virtual ~LuaState();
LuaState(const LuaState&) = delete;
LuaState& operator=(const LuaState&) = delete;
static LuaState& Global();
lua_State* luaState();
void RunScript(const std::string& code);
void RunFile(const std::string& filename);
void RunBuffer(const char*, std::size_t, std::string& err, const std::string& chunk="");
bool HasAddons(const std::string& manifest) const;
LuaAddonsVec& GetAddons(const std::string& manifest);
void UploadAddons(const std::string& manifest, const LuaAddonsVec& addons);
void LoadSubmodule(LuaSubmodule sm);
void DbgStackDump();
private:
lua_State* L;
std::map<LuaSubmodule, bool> m_loadedSubMods;
LuaAddonsMap m_addons;
void LoadHHSubmodule();
void LoadParsersSubmodule();
static int LuaPanic(lua_State* L);
};
}
namespace a2a
{
inline bool LuaState::HasAddons(const std::string& manifest) const
{
return m_addons.find(manifest) != m_addons.end();
}
}
#endif
<file_sep>/src/CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
set(common_sources
${INCLUDE_ROOT}/config.h
${INCLUDE_ROOT}/types.hpp
${INCLUDE_ROOT}/enumflags.hpp
${INCLUDE_ROOT}/metafactory.hpp
${INCLUDE_ROOT}/collection.hpp
${INCLUDE_ROOT}/strutils.hpp
${INCLUDE_ROOT}/stdutils.hpp
${INCLUDE_ROOT}/streamutils.hpp
${INCLUDE_ROOT}/datetimeutils.hpp
${SRC_ROOT}/strutils.cxx
${SRC_ROOT}/streamutils.cxx
${SRC_ROOT}/datetimeutils.cxx
PARENT_SCOPE)
set(he_sources
${INCLUDE_ROOT}/card.hpp
${INCLUDE_ROOT}/cardset.hpp
${INCLUDE_ROOT}/cardseq.hpp
${SRC_ROOT}/card.cxx
${SRC_ROOT}/cardseq.cxx
PARENT_SCOPE)
set(hh_sources_1
${INCLUDE_ROOT}/cardgame.hpp
${INCLUDE_ROOT}/chips.hpp
${INCLUDE_ROOT}/currency.hpp
${INCLUDE_ROOT}/gamesite.hpp
${INCLUDE_ROOT}/gamestagetype.hpp
${INCLUDE_ROOT}/gamestage.hpp
${INCLUDE_ROOT}/gamestagescol.hpp
${INCLUDE_ROOT}/seat.hpp
${INCLUDE_ROOT}/seatscol.hpp
${INCLUDE_ROOT}/position.hpp
${INCLUDE_ROOT}/player.hpp
${INCLUDE_ROOT}/pot.hpp
${INCLUDE_ROOT}/handactiontype.hpp
${INCLUDE_ROOT}/handaction.hpp
${INCLUDE_ROOT}/handactioncol.hpp
${INCLUDE_ROOT}/handhistory.hpp
${SRC_ROOT}/cardgame.cxx
${SRC_ROOT}/gamestage.cxx
${SRC_ROOT}/gamestagescol.cxx
${SRC_ROOT}/gamesite.cxx
${SRC_ROOT}/currency.cxx
${SRC_ROOT}/position.cxx
${SRC_ROOT}/seatscol.cxx
${SRC_ROOT}/pot.cxx
${SRC_ROOT}/handaction.cxx
${SRC_ROOT}/handactioncol.cxx
${SRC_ROOT}/handhistory.cxx
)
set(hh_bindc_sources_1
${INCLUDE_ROOT}/hhbindc.h
${SRC_ROOT}/hhbindc.cxx
)
if(LUA_SUPPORT)
set (hh_sources
${hh_sources_1}
${hh_bindc_sources_1}
${INCLUDE_ROOT}/luastate.hpp
${SRC_ROOT}/luastate.cxx
PARENT_SCOPE )
else()
set (hh_sources
${hh_sources_1}
PARENT_SCOPE )
endif(LUA_SUPPORT)
set(hh_proc_sources_1
${INCLUDE_ROOT}/pluginbase.hpp
${INCLUDE_ROOT}/plugin.hpp
${INCLUDE_ROOT}/settings.hpp
${INCLUDE_ROOT}/version.hpp
${INCLUDE_ROOT}/pluginfactory.hpp
${INCLUDE_ROOT}/mempool.hpp
${INCLUDE_ROOT}/fsysutils.hpp
${INCLUDE_ROOT}/filescol.hpp
${INCLUDE_ROOT}/sitesdata.hpp
${INCLUDE_ROOT}/hhconverter_base.hpp
${INCLUDE_ROOT}/hhconverters.hpp
${INCLUDE_ROOT}/hhparser_base.hpp
${INCLUDE_ROOT}/hhparsers.hpp
${INCLUDE_ROOT}/hhreader.hpp
${INCLUDE_ROOT}/hhlineparser.hpp
${INCLUDE_ROOT}/hhfilesreader.hpp
${INCLUDE_ROOT}/hhparser_ps.hpp
${INCLUDE_ROOT}/hhconverter_ps.hpp
${INCLUDE_ROOT}/hhparser_pac.hpp
${SRC_ROOT}/mempool.cxx
${SRC_ROOT}/fsysutils.cxx
${SRC_ROOT}/filescol.cxx
${SRC_ROOT}/hhconverters.cxx
${SRC_ROOT}/hhparsers.cxx
${SRC_ROOT}/hhreader.cxx
${SRC_ROOT}/hhlineparser.cxx
${SRC_ROOT}/hhlineparser_impl.hpp
${SRC_ROOT}/hhlineparser_impl.cxx
${SRC_ROOT}/hhfilesreader.cxx
${SRC_ROOT}/hhparser_ps.cxx
${SRC_ROOT}/sitesdata.cxx
${SRC_ROOT}/hhconverter_ps.cxx
${SRC_ROOT}/hhparser_pac.cxx
)
if(LUA_SUPPORT)
set (hh_proc_sources
${hh_proc_sources_1}
${INCLUDE_ROOT}/lualineparser.hpp
${SRC_ROOT}/lualineparser.cxx
${INCLUDE_ROOT}/luapool.hpp
${SRC_ROOT}/luapool.cxx
PARENT_SCOPE)
else()
set (hh_proc_sources
${hh_proc_sources_1}
PARENT_SCOPE)
endif(LUA_SUPPORT)
set(json11_sources
${INCLUDE_ROOT}/json11.hpp
${SRC_ROOT}/json11.cxx
PARENT_SCOPE)
<file_sep>/addons/parsers/parser3.lua
A2ALineParser "TestParser3"
function TestParser3:HandStart()
return "*** Test"
end
function TestParser3:ProcessLine(ln)
print(ln)
return 1
end
function TestParser3:OnHandComplete()
print("[hand on complete]")
end
<file_sep>/include/cardset.hpp
#ifndef INCLUDE_CARDSET_HPP
#define INCLUDE_CARDSET_HPP
#include "types.hpp"
namespace a2a
{
class CardSet
{
};
}
#endif<file_sep>/tests/misc.cxx
#include <array>
#include <deque>
#include <forward_list>
#include <list>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <memory>
#include <chrono>
#include <ctime>
#include <chrono>
#include <thread>
#include <cassert>
#include <atomic>
#include <future>
#include <mutex>
#include <vector>
//#define private public
#ifdef _MSC_VER
#pragma warning (disable: 4996)
#endif
//#define protected public
#include "fsysutils.hpp"
#include "filescol.hpp"
#include "hhparsers.hpp"
#include "hhparser_ps.hpp"
#include "mempool.hpp"
#include "hhfilesreader.hpp"
#include "hhreader.hpp"
#include "fsysutils.hpp"
#include "filescol.hpp"
#include "strutils.hpp"
#include "handhistory.hpp"
#include "hhlineparser.hpp"
#include "hhreader.hpp"
#ifdef A2A_LUA
#include "luastate.hpp"
#include "lualineparser.hpp"
#include "luapool.hpp"
#endif
using namespace a2a;
using namespace a2a::StrUtils;
#include "hhbindc.h"
//extern "C"
//{
// A2AHHC_API void* _test_hand()
// {
// std::string test = R"(
//PokerStars Hand #148736096296: Omaha Hi/Lo Limit ($1/$2 USD) - 2016/02/13 12:11:28 ET
//Table 'Vigdis' 6-max Seat #1 is the button
//Seat 1: Wokoland ($76.79 in chips)
//Seat 2: hongkongpaul ($7.50 in chips)
//Seat 3: korjae ($47.41 in chips)
//Seat 4: vadimakr ($57.22 in chips)
//Seat 5: 0utside ($41.07 in chips)
//Seat 6: BIGMINTER ($64.42 in chips)
//hongkongpaul: posts small blind $0.50
//korjae: posts big blind $1
//*** HOLE CARDS ***
//vadimakr: calls $1
//0utside: calls $1
//BIGMINTER: folds
//Wokoland: folds
//hongkongpaul: raises $1 to $2
//korjae: folds
//vadimakr: calls $1
//0utside: calls $1
//*** FLOP *** [5c 7s 3d]
//hongkongpaul: bets $1
//vadimakr: calls $1
//0utside: folds
//*** TURN *** [5c 7s 3d] [4d]
//hongkongpaul: bets $2
//vadimakr: calls $2
//*** RIVER *** [5c 7s 3d 4d] [As]
//hongkongpaul: checks
//vadimakr: checks
//*** SHOW DOWN ***
//hongkongpaul: shows [8s 2d Qd Ac] (HI: a straight, Ace to Five; LO: 5,4,3,2,A)
//vadimakr: mucks hand
//hongkongpaul collected $6.24 from pot
//hongkongpaul collected $6.24 from pot
//*** SUMMARY ***
//Total pot $13 | Rake $0.52
//Board [5c 7s 3d 4d As]
//Seat 1: Wokoland (button) folded before Flop (didn't bet)
//Seat 2: hongkongpaul (small blind) showed [8s 2d Qd Ac] and won ($12.48) with HI: a straight, Ace to Five; LO: 5,4,3,2,A
//Seat 3: korjae (big blind) folded before Flop
//Seat 4: vadimakr mucked
//Seat 5: 0utside folded on the Flop
//Seat 6: BIGMINTER folded before Flop (didn't bet)
// )";
//
// HandHistoryReader r(test);
//
// while (r.Next())
// {
// HandHistory *hh = new HandHistory(); r.Parse(*hh);
// return hh;
// }
// return NULL;
// }
//}
//
//int main()
//{
//
// auto h = hh_new();
// hh_delete(h);
//
// try
// {
// LuaState::Global().LoadSubmodule(LuaSubmodule::handhistory);
// }
// catch (const std::exception& err)
// {
// std::cout << err.what() << std::endl;
// }
// return 0;
//}
//int main()
//{
// //LuaState::Global().LoadParsersSubmodule();
// std::string test = R"(
//
// *** Test
// line 1
//
// line 2
//
//
// lol
//
// )";
//// LuaLineParser p(LuaState::Global(), "TestParser");
//try
//{
// for (int i = 0; i < 10; i++)
// {
// HandHistoryReader r(test);
//
// while (r.Next())
// {
// HandHistory hh; r.Parse(hh);
// }
//
// std::cout << r.GetTotalParsed() << std::endl;
// }
//}
//catch(const std::exception& err)
//{
// std::cout << err.what() << std::endl;
//}
//
// //std::cout << p.HandStartTest() << std::endl;
//
//
// //s.LoadLibraries();
//
// //std::cout << "-> " << lua_gettop(s.get()) << std::endl;
// //if (lua_istable(s.get(), -1))
// //{
// // std::cout << "ITS TABLE" << std::endl;
// // if (lua_getmetatable(s.get(), -1))
// // {
// // std::cout << "-> " << lua_gettop(s.get()) << std::endl;
// // std::cout << "HAS METATABLE" << std::endl;
// // //lua_getfield(s.get(), -1, "__A2AClass");
// // //std::cout << "-> " << lua_gettop(s.get()) << std::endl;
// // //if (lua_isstring(s.get(), -1))
// // //{
// // // std::cout << "HAS __A2AClass" << std::endl;
// // //}
// // //lua_pop(s.get(), 1);
// // //std::cout << "-> " << lua_gettop(s.get()) << std::endl;
// // lua_getfield(s.get(), -2, "ProcessLine");
// // std::cout << "-> " << lua_gettop(s.get()) << std::endl;
// // if (lua_isfunction(s.get(), -1))
// // {
// // std::cout << "HAS ProcessLine" << std::endl;
// // func = luaL_ref(s.get(), LUA_REGISTRYINDEX);
// // std::cout << "ref ProcessLine = " << func << std::endl;
//
// // }
// // lua_pop(s.get(), 1);
// // }
// // lua_pop(s.get(), 1);
// // std::cout << "-> " << lua_gettop(s.get()) << std::endl;
// // lua_rawgeti(s.get(), LUA_REGISTRYINDEX, func);
// // std::cout << "-> " << lua_gettop(s.get()) << std::endl;
// // lua_pushstring(s.get(), "Hello");
// // std::cout << "-> " << lua_gettop(s.get()) << std::endl;
// // if (lua_pcall(s.get(), 1, 1, 0) != 0)
// // {
// //
// // }
// // std::cout << "-> " << lua_gettop(s.get()) << std::endl;
// //lua_close(L);
//}
int main()
{
#ifdef A2A_LUA
static const std::size_t BUFF_SIZE = 4 * 1048576;
static const std::size_t TH_NUM = std::thread::hardware_concurrency();
MemoryPool srcBufferPool(1 * 1048576, TH_NUM);
std::vector<std::future<void>> futures;
std::atomic<int> total(0);
auto parsers = std::make_shared<HandHistoryParsersFactory>();
// parsers->LoadCoreParsers();
#ifdef _MSC_VER
auto dir = Directory::Open("D:\\projects\\SampleHandHistories\\PokerStars", true);
//auto dir = Directory::Open("D:\\projects\\SampleHandHistories\\PokerStars\\CashGame\\ExtraHands", true);
#else
auto dir = Directory::Open("/media/sf_projects/SampleHandHistories", true);
#endif
//FilesCollection files;
auto start = std::chrono::steady_clock::now();
while (dir->HasFilesToProcess())
{
//dir->GetFiles(files, BUFF_SIZE/2);
const auto run = [&srcBufferPool, &total](FilesCollection _files)
{
std::unique_ptr<LuaStatesPool::PooledLuaState> pL(LuaStatesPool::Global().GetPooledState());
HandHistoryParsersFactory parsers(pL->Ref());
HandHistoryFilesReader cs(parsers, _files);
for (;;)
{
std::unique_ptr<MemoryPool::Buffer> buff(srcBufferPool.GetBuffer());
buff->Resize(cs.Read(buff->Data(), buff->Size()));
if (buff->Size() == 0)
return;
HandHistoryReader ph(cs.GetParser(), buff->Data(), buff->Size());
//std::cout << std::this_thread::get_id() << std::endl;
while (ph.Next())
{
HandHistory hh;
try
{
ph.Parse(hh);
// if (131612340948 == hh.GetHandId())
//std::cout << hh.GetHandId() << std::endl;
}
catch (const std::exception& err)
{
// std::cout << "ID:" << hh.GetHandId() << " ERRROR: " << err.what() << std::endl
// << "***********************************************" << std::endl;
}
}
total += ph.GetTotalParsed();
}
};
//while (HHMemPool::Buffer* buff = cs.Read(srcBufferPool))
//{
futures.emplace_back(std::async(
std::launch::async,
run, dir->GetFilesMinTotalSize(BUFF_SIZE / 2)
));
if (futures.size() >= TH_NUM)
{
for (auto& e : futures) {
e.wait();
}
futures.clear();
}
//
//run(buff);
//}
//files.Clear();
}
for (auto& e : futures) {
e.wait();
}
auto end = std::chrono::steady_clock::now();
std::cout << "TIME: " << std::chrono::duration <double, std::milli>(end - start).count() << std::endl;
std::cout << "TOTAL HANDS: " << total << std::endl;
#endif
return 0;
}
#ifdef _MSC_VER
#pragma warning (default: 4996)
#endif
<file_sep>/tests/luatests.cpp
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
#include <array>
#include <deque>
#include <forward_list>
#include <list>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <memory>
#include <chrono>
#include <ctime>
//#define private public
#ifdef _MSC_VER
#pragma warning (disable: 4996)
#endif
//#define protected public
#include "fsysutils.hpp"
#include "filescol.hpp"
#include "strutils.hpp"
#include "handhistory.hpp"
#include "hhlineparser.hpp"
#include "hhreader.hpp"
#include "luastate.hpp"
#include "lualineparser.hpp"
using namespace a2a;
using namespace a2a::StrUtils;
struct test
{
test()
{
std::cout << "create" << std::endl;
}
~test()
{
std::cout << "destroy" << std::endl;
}
};
#define _DECL
#ifdef _MSC_VER
#define _DECL __declspec(dllexport)
#endif
extern "C"
{
_DECL void* hh_new()
{
return new test();
}
_DECL void hh_delete(void* p)
{
assert(p);
delete static_cast<test*>(p);
}
}
TEST_CASE("lua tests")
{
//LuaState::Global().LoadParsersSubmodule();
std::string test = R"(
*** Test
line 1
line 2
lol
)";
// LuaLineParser p(LuaState::Global(), "TestParser");
try
{
for (int i = 0; i < 10; i++)
{
HandHistoryReader r(test);
while (r.Next())
{
HandHistory hh; r.Parse(hh);
}
std::cout << r.GetTotalParsed() << std::endl;
}
}
catch(const std::exception& err)
{
std::cout << err.what() << std::endl;
}
//std::cout << p.HandStartTest() << std::endl;
//s.LoadLibraries();
//std::cout << "-> " << lua_gettop(s.get()) << std::endl;
//if (lua_istable(s.get(), -1))
//{
// std::cout << "ITS TABLE" << std::endl;
// if (lua_getmetatable(s.get(), -1))
// {
// std::cout << "-> " << lua_gettop(s.get()) << std::endl;
// std::cout << "HAS METATABLE" << std::endl;
// //lua_getfield(s.get(), -1, "__A2AClass");
// //std::cout << "-> " << lua_gettop(s.get()) << std::endl;
// //if (lua_isstring(s.get(), -1))
// //{
// // std::cout << "HAS __A2AClass" << std::endl;
// //}
// //lua_pop(s.get(), 1);
// //std::cout << "-> " << lua_gettop(s.get()) << std::endl;
// lua_getfield(s.get(), -2, "ProcessLine");
// std::cout << "-> " << lua_gettop(s.get()) << std::endl;
// if (lua_isfunction(s.get(), -1))
// {
// std::cout << "HAS ProcessLine" << std::endl;
// func = luaL_ref(s.get(), LUA_REGISTRYINDEX);
// std::cout << "ref ProcessLine = " << func << std::endl;
// }
// lua_pop(s.get(), 1);
// }
// lua_pop(s.get(), 1);
// std::cout << "-> " << lua_gettop(s.get()) << std::endl;
// lua_rawgeti(s.get(), LUA_REGISTRYINDEX, func);
// std::cout << "-> " << lua_gettop(s.get()) << std::endl;
// lua_pushstring(s.get(), "Hello");
// std::cout << "-> " << lua_gettop(s.get()) << std::endl;
// if (lua_pcall(s.get(), 1, 1, 0) != 0)
// {
//
// }
// std::cout << "-> " << lua_gettop(s.get()) << std::endl;
//lua_close(L);
}
#ifdef _MSC_VER
#pragma warning (default: 4996)
#endif
<file_sep>/include/filescol.hpp
#ifndef INCLUDE_FILESCOL_HPP
#define INCLUDE_FILESCOL_HPP
#include "types.hpp"
#include "fsysutils.hpp"
#include "collection.hpp"
namespace a2a
{
class FilesCollection : public Collection<File, FilesCollection>
{
public:
static predicate_t HasHands_(const HandHistoryParser::Ptr& parser, std::size_t testBlockSize = 512);
static predicate_t HasExtension_(const std::string& ext);
static visitor_t MakeCache_(std::size_t blockSize);
static const_visitor_t CalcSize_(i64& Size);
static visitor_t ClearCache_();
i64 FilesTotalSize() const;
i64 __calcSize;
};
class FilesCollectionReader
{
public:
using Ptr = std::shared_ptr<FilesCollectionReader>;
using file_t = FilesCollection::value_type;
using files_t = FilesCollection;
FilesCollectionReader(const files_t& files, bool addLineBreak = true);
std::size_t Read(char* mem, std::size_t blockSize);
private:
files_t m_files;
std::ifstream m_is;
std::size_t m_currIndex;
bool m_addLineBreak;
bool nextStream();
};
}
//
// inlines
//
namespace a2a
{
inline i64 FilesCollection::FilesTotalSize() const
{
i64 ret;
Visit(CalcSize_(ret));
return ret;
}
}
#endif<file_sep>/include/position.hpp
#ifndef INCLUDE_POSITION_HPP
#define INCLUDE_POSITION_HPP
#include <string>
#include "types.hpp"
#include "enumflags.hpp"
namespace a2a
{
enum class PokerPosition : u32
{
EMPTY = 0,
UTG1 = 1 << 0,
UTG2 = 1 << 1,
UTG3 = 1 << 2,
UTG = 0xF,
MP1 = 1 << 4,
MP2 = 1 << 5,
MP3 = 1 << 6,
MP = 0xF0,
CO = 1 << 8,
BTN = 1 << 9,
SB = 1 << 10,
BB = 1 << 11,
};
ENUM_FLAGS(PokerPosition);
using PokerPositionFlags = EnumFlags::flags<PokerPosition>;
namespace PokerPositionUtils
{
extern const std::string& PokerPosToShortStr(PokerPosition pos);
extern PokerPosition PokerPosNext(PokerPosition pos);
extern PokerPosition PokerPosPrev(PokerPosition pos);
}
}
#endif<file_sep>/include/pluginbase.hpp
#ifndef INCLUDE_PLUGINBASE_HPP
#define INCLUDE_PLUGINBASE_HPP
#include <string>
#include "settings.hpp"
#include "version.hpp"
namespace a2a
{
class PluginSettings : public Settings
{
public:
PluginSettings()
: Settings() {}
PluginSettings(const JsonSettings& jsettings)
: Settings(jsettings) {}
///
};
struct IPlugin
{
virtual void SetupPlugin(const PluginSettings& pluginSettings) = 0;
virtual const Version& GetVersion() const = 0;
virtual const std::string& GetName() const = 0;
virtual const std::string& GetDescription() const = 0;
virtual ~IPlugin() {}
};
}
#endif<file_sep>/src/hhlineparser.cxx
#include <algorithm>
#include "hhlineparser.hpp"
#include "strutils.hpp"
namespace a2a
{
const char* HandHistoryLineParser::Next(const char* beg, const char* end) const
{
if (beg == nullptr || end == nullptr || beg >= end) return nullptr;
const char *p = beg;
const std::string& mark(HandStart());
for (;;)
{
const char *res = std::search(p, end, mark.begin(), mark.end());
if (res == end)
return nullptr;
std::string ln;
StrUtils::ReadLine(res, end, ln, MaxLineLen());
if (IsFirstLine(ln))
return res;
p = res + mark.size();
}
return nullptr;
}
const char* HandHistoryLineParser::Last(const char* beg, const char* end) const
{
const std::string& mark(HandStart());
if (beg == nullptr || end == nullptr || beg >= end) return nullptr;
auto rbeg = std::reverse_iterator<const char*>(end);
auto rend = std::reverse_iterator<const char*>(beg);
auto res = std::search(rbeg, rend, mark.rbegin(), mark.rend());
if (res == rend)
return nullptr;
return res.base() - mark.size();
}
const char* HandHistoryLineParser::Parse(const char* beg, const char* end, HandHistory& handHistory) const
{
std::string ln;
const char* cursor = beg;
const char* p = beg;
std::unique_ptr<ILineParserImpl> parser ( GetImplementation(handHistory, m_settings, cursor) );
std::size_t maxLineLen = MaxLineLen();
std::size_t minLineLen = MinLineLen();
int emptyLines = 0;
while (p = StrUtils::ReadLine(cursor, end, ln, maxLineLen))
{
if (ln.size() < minLineLen)
{
cursor = p;
if (!parser->ProcessEmptyLine(++emptyLines))
break;
continue;
}
else
emptyLines = 0;
if ((cursor > beg && IsFirstLine(ln)))
break;
cursor = p;
if (!parser->ProcessLine(ln)) break;
}
//if (!handHistory.HasHeader())
// throw ParseError("Failed to read hand history header.", cursor);
parser->OnHandComplete();
return cursor;
}
bool HandHistoryLineParser::IsFirstLine(const std::string &s) const
{
const std::string& mark(HandStart());
return s.compare(0, mark.size(), mark) == 0;
}
}
<file_sep>/src/sitesdata.cxx
#include "sitesdata.hpp"
#include <map>
#include <string>
#include <stdexcept>
namespace a2a
{
namespace PokerStars
{
using map_t = std::map<CardGameType, const std::string>;
static const map_t GameTypeStrings =
{
{ CardGameType::Holdem, "Hold'em" },
{ CardGameType::Omaha, "Omaha" },
{ CardGameType::OmahaHiLo, "Omaha Hi/Lo" },
{ CardGameType::Omaha5c, "5 Card Omaha" },
{ CardGameType::Omaha5cHiLo, "5 Card Omaha Hi/Lo" },
{ CardGameType::Courchevel, "Courchevel" },
{ CardGameType::CourchevelHiLo, "Courchevel Hi/Lo" },
{ CardGameType::Stud7cHiLo, "7 Card Stud Hi/Lo" },
{ CardGameType::Stud7c, "7 Card Stud" },
{ CardGameType::Razz, "Razz" },
{ CardGameType::Draw5c, "5 Card Draw" },
{ CardGameType::DrawTripple27, "Triple Draw 2-7 Lowball" },
{ CardGameType::DrawSingle27, "Single Draw 2-7 Lowball" },
{ CardGameType::Badugi, "Badugi" },
};
static const map_t MixGameTypeStrings =
{
{ CardGameType::Mix_Game8, "8-Game" },
{ CardGameType::Mix_HORSE, "HORSE" },
{ CardGameType::Mix_HOSE, "HOSE" },
{ CardGameType::Mix_NLHPLO, "Mixed NLH/PLO" },
{ CardGameType::Mix_PLHPLO, "Mixed PLH/PLO" },
{ CardGameType::Mix_Holdem, "Mixed Hold'em" },
{ CardGameType::Mix_OmahaHiLo, "Mixed Omaha Hi/Lo" },
{ CardGameType::Mix_TrippleStud, "Tripple Stud" },
};
static const map_t BetTypeStrings =
{
{ CardGameType::NoLimit, "No Limit" },
{ CardGameType::PotLimit, "Pot Limit" },
{ CardGameType::FixedLimit, "Limit" },
};
static CardGameTypeFlags map_search(const map_t& m, const std::string& s, std::size_t &off)
{
std::size_t lenMax = 0; CardGameTypeFlags ret (CardGameType::Unknown);
for (const map_t::value_type& p : m)
if (lenMax < p.second.size() && s.compare(off, p.second.size(), p.second) == 0)
{
lenMax = p.second.size();
ret = p.first;
}
off += lenMax;
return ret;
}
CardGameTypeFlags ParseGame(const std::string& s, std::size_t &off)
{
return map_search(GameTypeStrings, s, off);
}
CardGameTypeFlags ParseBetType(const std::string& s, std::size_t &off)
{
return map_search(BetTypeStrings, s, off);
}
CardGameTypeFlags ParseMixGameType(const std::string& s, std::size_t &off)
{
return map_search(MixGameTypeStrings, s, off);
}
static const std::string _empty = "<UNKNOWN>";
static const std::string& map_get(const map_t& m, CardGameType gt)
{
auto i = m.find(gt);
return i == m.end() ? _empty : i->second;
}
const std::string& GameToStr(CardGameType gt)
{
return map_get(GameTypeStrings, gt);
}
const std::string& BetTypeToStr(CardGameType gt)
{
return map_get(BetTypeStrings, gt);
}
const std::string& MixGameToStr(CardGameType gt)
{
return map_get(MixGameTypeStrings, gt);
}
}
}<file_sep>/include/plugin.hpp
#ifndef INCLUDE_PLUGIN_HPP
#define INCLUDE_PLUGIN_HPP
#include "pluginbase.hpp"
namespace a2a
{
class Plugin : public IPlugin
{
public:
virtual void SetupPlugin(const PluginSettings& pluginSettings);
virtual const Version& GetVersion() const;
virtual const std::string& GetName() const;
virtual const std::string& GetDescription() const;
Plugin(const std::string& name, const Version& ver, const std::string& descr = "")
: m_name(name), m_ver(ver), m_description(descr)
{}
protected:
std::string m_name;
std::string m_description;
Version m_ver;
PluginSettings m_pluginSettings;
};
//
// inlines
//
inline void Plugin::SetupPlugin(const PluginSettings& pluginSettings)
{
m_pluginSettings = pluginSettings;
}
inline const Version& Plugin::GetVersion() const
{
return m_ver;
}
inline const std::string& Plugin::GetName() const
{
return m_name;
}
inline const std::string & Plugin::GetDescription() const
{
return m_description;
}
}
#endif | 082f05d12d9410fee4b2ec9a557b84816f5a9e04 | [
"C",
"CMake",
"C++",
"Lua"
] | 101 | C++ | timeflask/timeflask-poker-tools | 386dcb0d5b1a3231cd81cbf00a91a0e2919e86d1 | bc7e612cd1da51c45cb32e8679289a93b6717303 |
refs/heads/master | <file_sep>import {StyleSheet} from 'react-native';
const styles = StyleSheet.create({
container: {
alignItems: 'center',
justifyContent: 'center',
},
search: {
flexDirection: 'row',
},
title: {
fontSize: 20,
fontWeight: 'bold',
},
description: {
fontSize: 12,
},
separator: {
marginVertical: 30,
height: 1,
width: '80%',
},
bar: {
flexGrow: 4,
},
item: {
backgroundColor: '#888888',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
field: {
paddingHorizontal: 20,
borderWidth: 1,
paddingVertical: 8
}, form: {
backgroundColor: '#888888'
}, padding: {
minHeight: "50px"
}
});
export default styles;
<file_sep># Aseguradora
Esta aplicación permite acceder a, modificar o eliminar pólizas de seguro.
## instrucciones
Para abrir en desarrollo, seguir las siguientes instrucciones:
* Instalar expo:
`npm install --global expo-cli`
* descargar el repositorio:
`git clone https://github.com/LuisChDev/aseguradora`
* instalar dependencias:
`yarn install`
* iniciar.
`yarn start`
Luego, instalar la aplicación Expo en su celular (Android o iOS). Seguir las
indicaciones de la terminal.
<file_sep>/*
* Este módulo contiene las funciones relacionadas a la comunicación con el
* servidor. Para propósitos de esta prueba, será un dummy con una base de
* simple. Debería de ser fácilde reemplazar por una conexión real.
*/
/**
* tipo para porcentajes
*/
type Percentage = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10
| 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20
| 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30
| 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40
| 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50
| 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60
| 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70
| 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80
| 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90
| 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100;
/**
* tipos de cobertura
*/
enum Cobertura {
Terremoto,
Incendio,
Robo,
Perdida,
Vida,
Accidente
}
const Cobs = {
0: "Terremoto",
1: "Incendio",
2: "Robo",
3: "Pérdida",
4: "Vida",
5: "Accidente"
}
/**
* tipos de riesgo
*/
enum Riesgo {
bajo,
medio,
medio_alto,
alto,
}
const Ries = {
0: "bajo",
1: "medio",
2: "medio-alto",
3: "alto"
}
// type Riesgo = "bajo" | "medio" | "medio-alto" | "alto"
/**
* el tipo de las polizas.
*/
type Poliza = {
// ID
id: string,
// Nombre
nombre: string,
// Descripción
descripcion: string,
// coberturas. tipo y porcentaje.
coberturas: [Cobertura, Percentage][],
// Inicio de vigencia
fecha: Date,
// periodo de cobertura (en meses)
periodo: number,
// precio de la póliza
precio: number,
// tipo de riesgo
riesgo: Riesgo
}
/**
* retorna los valores que coincidan en cualquiera de los campos.
*/
const busqueda = (cadena: string): Poliza[] => {
let matches: Poliza[] = []
for (let row in dummies) {
if (dummies[row].nombre.includes(cadena)||
dummies[row].descripcion.includes(cadena)||
dummies[row].riesgo.includes(cadena)) {
matches.push(dummies[row]);
break;
}
for (let factor in dummies[row].coberturas) {
if (Cobs[dummies[row].coberturas[factor][0]].includes(cadena)) {
matches.push(dummies[row]);
break;
}
}
}
return matches;
}
/**
* modifica los valores de la base de datos.
*/
const modifica = (poliza: Poliza): void => {
for (let i in dummies) {
if (dummies[i].id === poliza.id) {
dummies[i] = poliza;
break;
}
}
}
/**
* los datos dummy.
*/
let dummies: Poliza[] = [
{id: "2a4v98a1",
nombre: "<NAME>",
descripcion: "Este seguro protege a su vehículo de robo o pérdida.",
coberturas: [[Cobertura.Robo, 35], [Cobertura.Perdida, 40]],
fecha: new Date("2020/11/22 15:30:00"),
periodo: 12,
precio: 300000,
riesgo: "medio" as Riesgo
},
{id: "642c97bf",
nombre: "<NAME>",
descripcion: "Proteja su casa, condominio o negocio de desastres naturales.",
coberturas: [[Cobertura.Terremoto, 20], [Cobertura.Incendio, 50]],
fecha: new Date("2020/11/26 17:10:00"),
periodo: 15,
precio: 350000,
riesgo: "medio" as Riesgo
},
{id: "124feeg2",
nombre: "<NAME>",
descripcion: "Recibe protección de ataques a tu local",
coberturas: [[Cobertura.Robo, 20], [Cobertura.Incendio, 40]],
fecha: new Date("2020/11/26 17:10:00"),
periodo: 18,
precio: 500000,
riesgo: "medio-alto" as Riesgo
},
{id: "4fe2ac89",
nombre: "Protección trabajo de alto riesgo",
descripcion: "Protege a los que más quieres",
coberturas: [[Cobertura.Accidente, 40], [Cobertura.Vida, 40]],
fecha: new Date("2020/11/20 20:10:00"),
periodo: 24,
precio: 1000000,
riesgo: "alto" as Riesgo
},
]
export {busqueda, Poliza, modifica, Riesgo, Percentage, Cobertura, Cobs, Ries};
| db76b480130ee62c37e57133c8a8ef7e8fe5a38a | [
"Markdown",
"TypeScript"
] | 3 | TypeScript | LuisChDev/aseguradora | fa81b97b9f41796a0c0710bfeece596378f17d42 | 55c8fa5e391352cd17a4a65d0dc169237af05e2b |
refs/heads/master | <file_sep><?php
/**
*
*/
class MY_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library(array('ion_auth', 'form_validation'));
$this->do_migration();
}
public function do_migration($version = NULL)
{
$this->load->library('migration');
if(isset($version) && ($this->migration->version($version) === FALSE)){
$this->session->set_flashdata('message',$this->migration->error_string());
}elseif(is_null($version) && $this->migration->latest() === FALSE){
$this->session->set_flashdata('message',$this->migration->error_string());
}
}
/**
* Log the user out
*/
public function logout()
{
$this->data['title'] = "Logout";
// log the user out
$logout = $this->ion_auth->logout();
// redirect them to the login page
$this->session->set_flashdata('message', $this->ion_auth->messages());
redirect('auth/login', 'refresh');
}
}<file_sep><?php
/**
*
*/
class Users extends MY_Model
{
public $return_type = 'array';
function __construct()
{
parent::__construct();
}
}<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<?php
foreach($css_files as $file): ?>
<link type="text/css" rel="stylesheet" href="<?php echo $file; ?>" />
<?php endforeach; ?>
<?php foreach($js_files as $file): ?>
<script src="<?php echo $file; ?>"></script>
<?php endforeach; ?>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">Tridharma Dosen</a>
</div>
<div>
<ul class="nav navbar-nav">
<li><a href='<?php echo site_url('user')?>'>Dosen</a></li>
<li><a href='<?php echo site_url('user/identitas')?>'>Identitas</a></li>
<li><a href='<?php echo site_url('user/kepegawaian')?>'>Kepegawaian</a></li>
<li><a href='<?php echo site_url('user/akademik')?>'>Akademik</a></li>
<li><a href='<?php echo site_url('user/pendidikan')?>'>Pendidikan</a></li>
<li><a href='<?php echo site_url('user/pengajaran')?>'>Pengajaran</a></li>
<li><a href='<?php echo site_url('user/pengabdian_masyarakat')?>'>Pengabdian Masyarakat</a></li>
<li><a href='<?php echo site_url('user/penelitian')?>'>Penelitian</a></li>
<li><a href='<?php echo site_url('user/penunjang')?>'>Penunjang Tridharma</a></li>
</ul>
</div>
<ul class="nav navbar-nav navbar-right">
<li><a href='<?php echo site_url('auth/detail_user');?>'><span class="glyphicon glyphicon-user"></span>Profil</a></li>
<li><a href='<?php echo site_url('auth/logout');?>' class="btn btn-default"><span class="glyphicon glyphicon-log-in"></span> Logout</a></li>
</ul>
</div>
</nav>
<div style='height:20px;'></div>
<div>
<?php echo $output; ?>
</div>
</body>
</html>
<file_sep><?php
/**
*
*/
class Template
{
protected $layout;
protected $content;
protected $ci;
protected $menu;
function __construct()
{
$this->ci =&get_instance();
}
public function set_layout($view=''){
$this->layout = $view;
return $this;
}
public function set_content($content='',$data=array())
{
$data['me'] = $this->ci->router->fetch_class();
$view_path = APPPATH.'views/'.$content.'.php';
//if (!is_null($this->ci->logged_in)) {
// $data['my'] = $this->ci->logged_in;
//}
$this->content = $content;
if (file_exists($view_path)) {
$this->content = $this->ci->load->view($content,$data,true);
}
return $this;
}
public function render($custom=array())
{
$data['content'] = $this->content;
if (is_object($custom)) {
$custom = (array)$custom;
}
if ($custom) {
$data = array_merge($custom);
}
$data['me'] = $this->ci->router->fetch_class();
if ($this->menu) {
$data['menu'] = $this->menu; //ambil dari properti menu yang sudah diset melalui method set_menu($menu)
}
$data['alert'] = $this->ci->session->flashdata('alert');
//$data['navigasi'] = get_menu_by_current_user();
$data['default_c'] = $this->ci->router->default_controller;
if ($custom) {
$data = array_merge($data,$custom);
}
//if (!is_null($this->ci->logged_in)) {
// $data = array_merge($data,$this->ci->logged_in);
// $data['my'] = $this->ci->logged_in;
//}
if (!is_null($this->layout) || !empty($this->layout)) {
$this->ci->load->view($this->layout,$data);
}else{
echo 'set layout terlebih dahulu';
}
}
public function set_alert($status='',$pesan='')
{
$data['alert'] = (is_array($pesan))? implode(' ', $pesan) : $pesan;
$pesan = trim($pesan);
if (!empty($pesan)) {
$alert ='<div class="alert alert-'.$status.' alert-dismissible" role="alert">';
$alert .='<button type="button" class="close" data-dismiss="alert" aria-label="Close">';
$alert .='<span aria-hidden="true">×</span></button>';
$alert .=$pesan;
$alert .='</div>';
$this->ci->session->set_flashdata('alert',$alert);
}
return $this;
}
public function set_menu($menu=array()){
$this->menu = $menu;
return $this;
}
}<file_sep><div class="row">
<div class="col-xs-12 col-md-4">
</div>
<div class="col-xs-12 col-md-8">
<div class="panel panel-default">
<div class="panel-heading">
<h4>
detail profil
<?php echo (isset($detail['username']))? $detail['username'] : '';?>
</h4>
</div>
<div class="panel-body">
<?php if(isset($detail['first_name']) && isset($detail['last_name'])) : ?>
<div class="form-group">
<label>Nama Lengkap</label><br/>
<?php echo $detail['first_name'].' '.$detail['last_name'];?>
</div>
<?php endif; ?>
<?php if(isset($detail['email'])) : ?>
<div class="form-group">
<label>Email</label><br/>
<?php echo $detail['email'];?>
</div>
<?php endif; ?>
<?php if(isset($detail['phone'])) : ?>
<div class="form-group">
<label>No. Telp</label><br/>
<?php echo $detail['phone'];?>
</div>
<?php endif; ?>
</div>
<div class="panel-footer">
<div class="text-right">
</div>
</div>
</div>
</div>
</div><file_sep><!DOCTYPE html>
<html>
<head>
<title>Rencana Kerja</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/');?>css/bootstrap.min.css">
<style type="text/css">
.kotak{
width: 30%;
background-color: #f2f2f2;
padding: 10px;
margin: auto;
position: 20px;
margin-top: 150px;
}
input[type=text],input[type=password]{
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
</style>
<script type="text/javascript" src="<?php echo base_url('assets/');?>js/jquery-1.9.1.min.js"></script>
</head>
<body>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href=''>Tridharma Dosen</a>
</div>
<div>
<ul class="nav navbar-nav">
<li><a href='<?php echo site_url('user')?>'>Dosen</a></li>
<li><a href='<?php echo site_url('user/identitas')?>'>Identitas</a></li>
<li><a href='<?php echo site_url('user/kepegawaian')?>'>Kepegawaian</a></li>
<li><a href='<?php echo site_url('user/akademik')?>'>Akademik</a></li>
<li><a href='<?php echo site_url('user/pendidikan')?>'>Pendidikan</a></li>
<li><a href='<?php echo site_url('user/pengajaran')?>'>Pengajaran</a></li>
<li><a href='<?php echo site_url('user/pengabdian_masyarakat')?>'>Pengabdian Masyarakat</a></li>
<li><a href='<?php echo site_url('user/penelitian')?>'>Penelitian</a></li>
<li><a href='<?php echo site_url('user/penunjang')?>'>Penunjang Tridharma</a></li>
</ul>
</div>
<ul class="nav navbar-nav navbar-right">
<li><a href='<?php echo site_url('auth/detail_user');?>'><span class="glyphicon glyphicon-user"></span>Profil</a></li>
<li><a href='<?php echo site_url('auth/logout');?>' class="btn btn-default"><span class="glyphicon glyphicon-log-in"></span> Logout</a></li>
</ul>
</div>
</nav>
<div class="container">
<div class="row">
<div class="col-xs-12">
<?php echo (isset($alert))? $alert : '' ;?>
<?php echo (isset($content))? $content : '' ;?>
</div>
</div>
</div>
<script type="text/javascript" src="<?php echo base_url('assets/');?>js/tether.min.js"></script>
<script type="text/javascript" src="<?php echo base_url('assets/');?>js/bootstrap.min.js"></script>
</body>
</html><file_sep><?php defined('BASEPATH') OR exit('No direct script access allowed');
class Migration_Install_users_groups extends CI_Migration {
private $tables;
public function __construct() {
parent::__construct();
$this->load->dbforge();
$this->load->config('ion_auth', TRUE);
$this->tables = $this->config->item('tables', 'ion_auth');
}
public function up() {
// Drop table 'users_groups' if it exists
$this->dbforge->drop_table($this->tables['users_groups'], TRUE);
// Table structure for table 'users_groups'
$this->dbforge->add_field(array(
'id' => array(
'type' => 'MEDIUMINT',
'constraint' => '8',
'unsigned' => TRUE,
'auto_increment' => TRUE
),
'user_id' => array(
'type' => 'MEDIUMINT',
'constraint' => '8',
'unsigned' => TRUE
),
'group_id' => array(
'type' => 'MEDIUMINT',
'constraint' => '8',
'unsigned' => TRUE
)
));
$this->dbforge->add_key('id', TRUE);
$this->dbforge->create_table($this->tables['users_groups']);
// Dumping data for table 'users_groups'
$data = array(
array(
'user_id' => '1',
'group_id' => '1',
),
array(
'user_id' => '1',
'group_id' => '2',
)
);
$this->db->insert_batch($this->tables['users_groups'], $data);
}
public function down() {
$this->dbforge->drop_table($this->tables['users_groups'], TRUE);
}
}
<file_sep><!DOCTYPE html>
<html>
<head>
<title>Rencana Kerja</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/');?>css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/');?>font-awesome/css/font-awesome.min.css">
<script type="text/javascript" src="<?php echo base_url('assets/');?>js/jquery-1.9.1.min.js"></script>
<?php foreach($css_files as $file): ?>
<link type="text/css" rel="stylesheet" href="<?php echo $file; ?>" />
<?php endforeach; ?>
<?php foreach($js_files as $file): ?>
<script src="<?php echo $file; ?>"></script>
<?php endforeach; ?>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<?php echo anchor('user/setting','Pengaturan',array('class'=>'navbar-brand'));?>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<?php
if (
isset($menu) &&
isset($me)
) {
$list ='';
if ($menu) {
foreach ($menu as $key => $value) {
if (!in_array($value, array('__construct','index','get_instance','do_migration','logout'))) { //menu selain index dan __contruct akan ditampilkan
$list .='<li>';
$label = str_replace('_', ' ', $value); //ganti underscore dengan spasi
$label = ucwords($label); //huruf depan menjadi kapital
$list .= anchor($me.'/'.$value, $label); //pengganti tag link *<a>
$list .='</li>';
}
}
}
echo $list;
}
?>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
<ul class="dropdown-menu">
<li>
<?php echo anchor('user/index','<i class="fa fa-user"></i> Profil');?>
</li>
<li>
<?php echo anchor('user/setting','<i class="fa fa-gear"></i> Pengaturan');?>
</li>
<li role="separator" class="divider"></li>
<li>
<?php echo anchor('auth/logout','<i class="fa fa-sign-out"></i> Keluar');?>
</li>
</ul>
</li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div class="container">
<div class="row">
<div class="col-xs-12">
<?php echo (isset($alert))? $alert : '' ;?>
<?php echo (isset($content))? $content : '' ;?>
<?php echo (isset($output))? $output : '' ;?>
</div>
</div>
</div>
<script type="text/javascript" src="<?php echo base_url('assets/');?>js/tether.min.js"></script>
<script type="text/javascript" src="<?php echo base_url('assets/');?>js/bootstrap.min.js"></script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Membuat Login Dengan Codeigniter & Bootstrap | www.coderbiasa.com</title>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.6 -->
<link rel="stylesheet" href="<?php echo base_url('assets/css/bootstrap/bootstrap.min.css')?>">
<!-- Theme style -->
<link rel="stylesheet" href="<?php echo base_url('assets/css/AdminLTE.min.css')?>">
<link rel="stylesheet" href="<?php echo base_url('assets/css/fonts/font-awesome.min.css')?>">
<link rel="stylesheet" href="<?php echo base_url('assets/css/ionicons.min.css')?>">
</head>
<body class="hold-transition login-page">
<div class="login-box">
<div class="login-logo">
Login
</div>
<!-- /.login-logo -->
<div class="login-box-body">
<p class="login-box-msg">Sign in to start your session</p>
<form action="<?php echo site_url('login/proses'); ?>" method="post">
<?php if (validation_errors() || $this->session->flashdata('result_login')) { ?> //menampilkan pesan error.
<div class="alert alert-danger animated fadeInDown" role="alert">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Peringatan!</strong>
<?php echo validation_errors(); ?>
<?php echo $this->session->flashdata('result_login'); ?>
</div>
<?php } ?>
<div class="form-group has-feedback">
<input type="text" name="username" class="form-control" placeholder="Username" autofocus="true">
<span class="fa fa-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="<PASSWORD>" name="password" class="form-control" placeholder="<PASSWORD>">
<span class="fa fa-lock form-control-feedback"></span>
</div>
<div class="row">
<!-- /.col -->
<div class="col-xs-4 pull-right">
<button type="submit" id="btn_login" class="btn btn-default pull-right">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>
</div>
<center><strong>Copyright © 2017 <a href="#">Coder Biasa</a>.</strong> All rights
reserved.</br><b>Version</b> 1.0.0</center>
<!-- /.login-box-body -->
</div>
<!-- /.login-box -->
<!-- jQuery 2.2.3 -->
<script src="<?php echo base_url('assets/js/plugins/jQuery/jquery-2.2.3.min.js')?>"></script>
<!-- Bootstrap 3.3.6 -->
<script src="<?php echo base_url('assets/js/bootstrap/bootstrap.min.js')?>"></script>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<title>Login BKD</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="<?php echo base_url('assets/css/bootstrap.min.css')?>">
<style type="text/css">
.kotak{
width: 30%;
background-color: #f2f2f2;
padding: 10px;
margin: auto;
position: 20px;
margin-top: 150px;
}
input[type=text],input[type=password]{
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
</style>
</head>
<body>
<div class="kotak">
<h1><center><?php echo lang('login_heading');?></center></h1>
<div id="infoMessage"><?php echo $message;?></div>
<?php echo form_open("auth/login");?>
<p>
<?php echo lang('login_identity_label', 'identity');?>
<?php echo form_input($identity);?>
</p>
<p>
<?php echo lang('login_password_label', 'password');?>
<?php echo form_input($password);?>
</p>
<p>
<a href='#'>Registrasi</a>
</p>
<p>
<?php echo lang('login_remember_label', 'remember');?>
<?php echo form_checkbox('remember', '1', FALSE, 'id="remember"');?>
</p>
<p><?php echo form_submit('submit', lang('login_submit_btn'));?></p>
<?php echo form_close();?>
<p><a href="forgot_password"><?php echo lang('login_forgot_password');?></a></p></div>
</body>
</html>
<file_sep><?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User extends MY_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see https://codeigniter.com/user_guide/general/urls.html
*/
public function __construct()
{
parent::__construct();
$this->load->library('grocery_CRUD');
$this->load->library('template');
$this->template->set_layout('layout_grocery');
$menu = get_class_methods($this); // mengambil semua methods dalam class
$this->template->set_menu($menu);
}
public function index()
{
try{
$crud = new grocery_CRUD();
$crud->set_theme('datatables');
$crud->set_table('dosen');
$crud->set_subject('Dosen');
$crud->set_relation('NIDN','identitas','NIDN');
$crud->set_relation('id_akademik','akademik','nama_perguruan');
$crud->display_as('id_akademik','Nama Perguruan');
$crud->set_relation('id_kepegawaian','kepegawaian','status');
$crud->display_as('id_kepegawaian','Status');
$crud->set_relation('id_pendidikan','pendidikan','nama_pelatihan');
$crud->display_as('id_pendidikan','Pendidikan');
$crud->set_relation('id_pengajaran','pengajaran','nama_pengajaran');
$crud->display_as('id_pengajaran','Pengajaran');
$crud->set_relation('id_penelitian','penelitian','nama_penelitian');
$crud->display_as('id_penelitian','Judul penelitian');
$crud->set_relation('id_pengabdian','pengabdian_masyarakat','nama_pengabdian');
$crud->display_as('id_pengabdian','Pengabdian');
$crud->set_relation('id_penunjang','penunjang','nama_kegiatan');
$crud->display_as('id_penunjang','Kegiatan');
$columns = array('NIDN','id_pendidikan','id_penelitian','id_pengabdian','id_penunjang');
$fields = array('id_akademik','id_kepegawaian','id_pengajaran');
$fields = array_merge($columns,$fields);
$crud->fields($fields);
$crud->columns($columns);
$output = $crud->render();
$this->template->render($output);
}catch(Exception $e){
show_error($e->getMessage().' --- '.$e->getTraceAsString());
}
}
public function identitas($id='')
{
try{
$crud = new grocery_CRUD();
$crud->set_theme('datatables');
$crud->set_table('identitas');
$crud->set_subject('Identitas');
//$crud->set_relation('NIDN','dosen','NIDN');
$crud->required_fields('NIDN');
$crud->columns('Nama','Gelar_Depan','Gelar_Belakang','email','No_HP');
$output = $crud->render();
$this->template->render($output);
}catch(Exception $e){
show_error($e->getMessage().' --- '.$e->getTraceAsString());
}
}
public function akademik($id='')
{
try{
$crud = new grocery_CRUD();
$crud->set_theme('datatables');
$crud->set_table('akademik');
$crud->set_subject('Akademik');
//$crud->set_relation('NIDN','dosen','NIDN');
$crud->required_fields('nama_perguruan');
$crud->columns('nama_perguruan','jenis_pendidikan_tinggi','jurusan','prodi');
$output = $crud->render();
$this->template->render($output);
}catch(Exception $e){
show_error($e->getMessage().' --- '.$e->getTraceAsString());
}
}
public function kepegawaian($id='')
{
try{
$crud = new grocery_CRUD();
$crud->set_theme('datatables');
$crud->set_table('kepegawaian');
$crud->set_subject('Kepegawaian');
//$crud->set_relation('NIDN','dosen','NIDN');
$crud->required_fields('status');
$crud->columns('kementrian_induk','status','jabatan_akademikterakhir','tmt_jabatan');
$output = $crud->render();
$this->template->render($output);
}catch(Exception $e){
show_error($e->getMessage().' --- '.$e->getTraceAsString());
}
}
public function pengabdian_masyarakat($id='')
{
try{
$crud = new grocery_CRUD();
$crud->set_theme('datatables');
$crud->set_table('pengabdian_masyarakat');
$crud->set_subject('Pengabdian');
//$crud->set_relation('NIDN','dosen','NIDN');
$crud->required_fields('nama_pengabdian');
//$crud->columns('nama_pengabdian','smt','th_ajaran','SKS','masa_penugasan');
//upload bukti_penugasan
$crud->set_field_upload('bukti_penugasan','assets/uploads/files');
$output = $crud->render();
$this->template->render($output);
}catch(Exception $e){
show_error($e->getMessage().' --- '.$e->getTraceAsString());
}
}
public function penunjang($id='')
{
try{
$crud = new grocery_CRUD();
$crud->set_theme('datatables');
$crud->set_table('penunjang');
$crud->set_subject('Penunjang');
//$crud->set_relation('NIDN','dosen','NIDN');
$crud->required_fields('nama_kegiatan');
$crud->columns('nama_kegiatan','smt','th_ajaran','SKS','masa_penugasan');
$crud->set_field_upload('bukti_penugasan','assets/uploads/files');
$output = $crud->render();
$this->template->render($output);
}catch(Exception $e){
show_error($e->getMessage().' --- '.$e->getTraceAsString());
}
}
public function penelitian($id='')
{
try{
$crud = new grocery_CRUD();
$crud->set_theme('datatables');
$crud->set_table('penelitian');
$crud->set_subject('Penelitian');
//$crud->set_relation('NIDN','dosen','NIDN');
$crud->required_fields('nama_penelitian');
$crud->columns('kategori','nama_penelitian','smt','th_ajaran','laman_publikasi');
$crud->set_field_upload('bukti_penugasan','assets/uploads/files');
$output = $crud->render();
$this->template->render($output);
}catch(Exception $e){
show_error($e->getMessage().' --- '.$e->getTraceAsString());
}
}
public function pendidikan($id='')
{
try{
$crud = new grocery_CRUD();
$crud->set_theme('datatables');
$crud->set_table('pendidikan');
$crud->set_subject('Pendidikan');
//$crud->set_relation('NIDN','dosen','NIDN');
$crud->required_fields('nama_pelatihan');
$crud->columns('nama_pelatihan','smt','th_ajaran','SKS','tempat');
$crud->set_field_upload('bukti_penugasan','assets/uploads/files');
$output = $crud->render();
$this->template->render($output);
}catch(Exception $e){
show_error($e->getMessage().' --- '.$e->getTraceAsString());
}
}
public function pengajaran($id='')
{
try{
$crud = new grocery_CRUD();
$crud->set_theme('datatables');
$crud->set_table('pengajaran');
$crud->set_subject('Pengajaran');
//$crud->set_relation('NIDN','dosen','NIDN');
$crud->required_fields('nama_pengajaran');
$crud->columns('nama_pengajaran','smt','th_ajaran','SKS','jml_mhs');
$crud->set_field_upload('bukti_penugasan','assets/uploads/files');
$output = $crud->render();
$this->template->render($output);
}catch(Exception $e){
show_error($e->getMessage().' --- '.$e->getTraceAsString());
}
}
}
<file_sep><?php
/**
*
*/
class Dosen extends MY_Controller
{
function __construct(argument)
{
parent::__construct(){
}
public function index(){
}
}
}<file_sep><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href=''>Tridharma Dosen</a>
</div>
<div>
<ul class="nav navbar-nav">
<li><a href='<?php echo site_url('user')?>'>Dosen</a></li>
<li><a href='<?php echo site_url('user/identitas')?>'>Identitas</a></li>
<li><a href='<?php echo site_url('user/kepegawaian')?>'>Kepegawaian</a></li>
<li><a href='<?php echo site_url('user/akademik')?>'>Akademik</a></li>
<li><a href='<?php echo site_url('user/pendidikan')?>'>Pendidikan</a></li>
<li><a href='<?php echo site_url('user/pengajaran')?>'>Pengajaran</a></li>
<li><a href='<?php echo site_url('user/pengabdian_masyarakat')?>'>Pengabdian Masyarakat</a></li>
<li><a href='<?php echo site_url('user/penelitian')?>'>Penelitian</a></li>
<li><a href='<?php echo site_url('user/penunjang')?>'>Penunjang Tridharma</a></li>
</ul>
</div>
<ul class="nav navbar-nav navbar-right">
<li><a href='<?php echo site_url('auth/detail_user');?>'><span class="glyphicon glyphicon-user"></span>Profil</a></li>
<li><a href='<?php echo site_url('auth/logout');?>' class="btn btn-default"><span class="glyphicon glyphicon-log-in"></span> Logout</a></li>
</ul>
</div>
</nav>
<h1><<?php echo lang('index_heading');?>>ADMIN</h1>
<div id="infoMessage"><?php echo $message;?></div>
<table cellpadding=0 cellspacing=10 class="table">
<tr>
<th><?php echo lang('index_fname_th');?></th>
<th><?php echo lang('index_lname_th');?></th>
<th><?php echo lang('index_email_th');?></th>
</tr>
<?php foreach ($users as $user):?>
<tr>
<td><?php echo htmlspecialchars($user->first_name,ENT_QUOTES,'UTF-8');?></td>
<td><?php echo htmlspecialchars($user->last_name,ENT_QUOTES,'UTF-8');?></td>
<td><?php echo htmlspecialchars($user->email,ENT_QUOTES,'UTF-8');?></td>
</tr>
<?php endforeach;?>
</table>
<button><?php echo anchor('auth/create_user', lang('index_create_user_link'))?></button>
| 67bec9807455fb2a9405fc7f9623a2459b028ac6 | [
"PHP"
] | 13 | PHP | jayantitrih/rencana_kerja | eb2821cca40536e6ccace8fd285a2f12179b71f4 | 315ca11657739425b8263e94ce169dceccdef48d |
refs/heads/master | <repo_name>okola44/Ajax_Jason<file_sep>/ajax.js
// this is a json(javascript object notation)
// var theClothes=[
// {
// "name":"pants",
// "shop":"labelle",
// "type":"thrifted"
// },
// {
// "name":"dresses",
// "shop":"louisvton",
// "type":"designer"
// }
// ]
var pageCounter=1;//a variable to inreament our uls when the button is clicked
var btn=document.getElementById("btn");
var animalcontainer=document.getElementById("animal-info");
btn.addEventListener("click",function(){
var ourRequest=new XMLHttpRequest();
ourRequest.open('GET','https://learnwebcode.github.io/json-example/animals-'+pageCounter+'.json');
ourRequest.onload=function(){
var ourData=JSON.parse(ourRequest.responseText);
renderHTML(ourData);
// console.log(ourData[0]);//index 0 to get the first object in the API
};
ourRequest.send();
pageCounter++;
if(pageCounter > 3){
btn.classList.add("hide-me");//when the button is clicked a fourth time the button disappears
}
})
function renderHTML(data){
var htmlString="animals are beings too"
for(i=0;i<data.length;i++){
htmlString += "<p>" + data[i].name + " is a " + data[i].species + " that likes to eat " ;
for(ii=0;ii<data[i].foods.likes.length;ii++){
if(ii==0){
htmlString += data[i].foods.likes[ii];
}else{
htmlString += "and" + data[i].foods.likes[ii];
}
}
htmlString += 'and dislikes';
for(ii=0;ii<data[i].foods.dislikes.length;ii++){
if(ii==0){
htmlString += data[i].foods.dislikes[ii];
}else{
htmlString += "and" + data[i].foods.dislikes[ii];
}}
htmlString += ',</p>';
}
animalcontainer.insertAdjacentHTML('beforeend',htmlString);
}
| 26ad853808256b0f4779a3f162a3c0fc7c6186f0 | [
"JavaScript"
] | 1 | JavaScript | okola44/Ajax_Jason | 52a37a43fe95767d8e6584fa1e304ada526f1815 | 20d44a39a21482903bd259b3e6ba66d93557d1c9 |
refs/heads/main | <file_sep>#Ejemplo función Map
a = [1, 2, 3, 4, 5]
b = [7, 8, 9, 10, 11]
resultado = list( map(lambda x,y : x*y, a,b))
print(resultado)
<file_sep>#Ejemplo funciones de orden superior
def calcularOperacion(fuerza,m,a,):
return fuerza(m,a)
def CalcularFuerza(x,y):
if (x!=0 and y!=0):
f = x * y
else:
f = "Valores incorrectos"
return f
fuerza = calcularOperacion(CalcularFuerza, 11,3)
print('La fuerza es:' , fuerza)
<file_sep>#Ejemplo funciones recursivas
def funcionCuentaRegresiva(numero):
numero -= 1
if numero > 0:
print(numero)
funcionCuentaRegresiva(numero)
else:
print("Explosión")
funcionCuentaRegresiva(5)<file_sep>#Ejemplo funciones compuestas
def funcionCalcular(funcion,n):
return funcion(funcion(n))
def funcionSumar(a):
return a+a
print (funcionCalcular(funcionSumar,3))
<file_sep>#Ejemplo funciones lambda
funcionLambda = lambda saludoA, saludoB: saludoA +" "+saludoB + " ¿Cómo están?"
print(funcionLambda("Hola","mundo"))
<file_sep>#Ejemplo funciones puras
def funcionPura(v,t):
if (v!=0 and t!=0):
d = v * t
else:
d = 0
return d
print("La distancia es:", funcionPura(4,8))
<file_sep>#Ejemplo funcion Filter
lista_nombres = ['Edem', 'Alisson', 'Jhon', 'Luis', 'Emma','Uriel']
# filter(lambda item: item[] expresion, lista_iterable)
print(list(filter(lambda x: x[0].lower() in 'aeiou', lista_nombres))) | 3a4f050d8319a003517de4ca822645e945166039 | [
"Python"
] | 7 | Python | vimerE/Funciones_en_la_programacion_funcional_Python | 2bc02ba89df395ae321115156a69fb864ed48cfc | 651259ff9cec999eaee2c42f4e02174197d5b30e |
refs/heads/master | <repo_name>juliengk/go-utils<file_sep>/ip/ip.go
package ip
import (
"net"
)
type IP struct {
V4 []string
V6 []string
}
type Interface struct {
net.Interface
IP
}
type Interfaces map[string]*Interface
func New() Interfaces {
return make(Interfaces)
}
func (intfs Interfaces) Get() error {
ifaces, err := net.Interfaces()
if err != nil {
return err
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
return err
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
intfs.add(i, ip)
}
}
return nil
}
func (intfs Interfaces) GetIntf(intf string) *Interface {
return intfs[intf]
}
func (intfs Interfaces) IgnoreIntf(ifaces []string) {
for _, iface := range ifaces {
if _, ok := intfs[iface]; ok {
delete(intfs, iface)
}
}
}
func (intfs Interfaces) add(iface net.Interface, ip net.IP) {
ipver := 4
if !IsIPv4(ip) {
ipver = 6
}
if val, ok := intfs[iface.Name]; ok {
if ipver == 4 {
val.V4 = append(val.V4, ip.String())
} else {
val.V6 = append(val.V6, ip.String())
}
} else {
if ipver == 4 {
intfs[iface.Name] = &Interface{iface, IP{V4: []string{ip.String()}}}
} else {
intfs[iface.Name] = &Interface{iface, IP{V6: []string{ip.String()}}}
}
}
}
func IsIPv4(ip net.IP) bool {
if ip.To4() == nil {
return false
}
return true
}
<file_sep>/utils.go
package utils
import (
"fmt"
"log"
"os"
"strings"
)
func RecoverFunc() {
if r := recover(); r != nil {
log.Println("Recovered:", r)
}
}
func CreateSlice(input, sep string) []string {
result := []string{}
items := strings.Split(input, sep)
for _, item := range items {
result = append(result, strings.TrimSpace(item))
}
return result
}
func ConvertSliceToMap(sep string, slice []string) map[string]string {
result := make(map[string]string)
if len(slice) > 0 {
for _, s := range slice {
if !strings.Contains(s, sep) {
continue
}
split := strings.Split(s, sep)
result[split[0]] = split[1]
}
}
return result
}
func StringInSlice(a string, list []string, insensitive bool) bool {
for _, v := range list {
a1 := a
v1 := v
if insensitive {
a1 = strings.ToLower(a)
v1 = strings.ToLower(v)
}
if a1 == v1 {
return true
}
}
return false
}
func Exit(err error) {
fmt.Println(err)
os.Exit(1)
}
func RemoveLastChar(s string) string {
strLen := len(s) - 1
newStr := s
if strLen > 0 {
newStr = s[0:strLen]
}
return newStr
}
| 5d62c96d785b14be551aecda5d555aae7e051517 | [
"Go"
] | 2 | Go | juliengk/go-utils | d22e95cdd048e353cb595c2ce018de257e7c3e82 | 8135b53ec64c46c0cfc8a72fba2850a609380052 |
refs/heads/master | <file_sep>using Godot;
using System;
public class ropePhysics : Node2D
{
// Declare member variables here. Examples:
// private int a = 2;
// private string b = "text";
[Export]
NodePath player1;
[Export]
NodePath player2;
[Export]
float ropeLength;
[Export]
NodePath ropeDrawPath;
[Export]
int ropePoints = 3;
Line2D ropeDraw;
[Export]
float ropeMaxLength = 600;
[Export]
float ropeMinLength = 50;
[Export]
float ropePullSpeed = 10.0f;
[Export]
float ropePullForce = 10.0f;
playerMovment p1;
playerMovment p2;
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
p1 = (playerMovment)(KinematicBody2D)GetNode(player1);
p2 = (playerMovment)(KinematicBody2D)GetNode(player2);
ropeDraw = (Line2D)GetNode(ropeDrawPath);
}
// Called every frame. 'delta' is the elapsed time since the previous frame.
public override void _PhysicsProcess(float delta)
{
if (Input.IsActionPressed("player1_move_up") || Input.IsActionPressed("player2_move_up"))
{
extendRope(delta);
// GD.Print("Rope length now : " + ropeLength);
}
if (Input.IsActionPressed("player1_move_down") || Input.IsActionPressed("player2_move_down"))
{
shrinkRope(delta);
// GD.Print("Rope length now : " + ropeLength);
}
doRopePhysics(p1, p2, delta);
doRopePhysics(p2, p1, delta);
//Only pull them together if they are farther apart then rope is allowed
if(ropeLength < p2.Position.DistanceTo(p1.Position))
{
Vector2 ropePullVector = (p2.Position - p1.Position).Normalized();
if (!p1.isAnchored && !p2.isAnchored)
{ //Both moving or in air, make it damped
p1.velocity += ropePullVector * ropePullForce * 0.1f;
p2.velocity -= ropePullVector * ropePullForce * 0.1f;
}
else
{//One is anchored pull full force
p1.velocity += ropePullVector * ropePullForce;
p2.velocity -= ropePullVector * ropePullForce;
}
}
p1.move();
p2.move();
}
void shrinkRope(float delta)
{
if(ropeLength <= ropeMinLength)
{
ropeLength = ropeMinLength;
return;
}
ropeLength -= delta* ropePullSpeed;
}
void extendRope(float delta)
{
if (ropeLength >= ropeMaxLength)
{
ropeLength = ropeMaxLength;
return;
}
ropeLength += delta* ropePullSpeed;
}
void doRopePhysics(playerMovment p1,playerMovment p2,float delta)
{
if (ropeLength <= p1.Position.DistanceTo(p2.Position))
{
Vector2 ropePullVector = (p2.Position - p1.Position).Normalized();
// tug on other player
if (ropePullVector.Dot(p1.velocity) < 0)
{
if (p1.isAnchored && !p2.isAnchored)
{
p2.velocity += p1.velocity * 0.5f;
// p2.MoveAndSlide(p1.velocity * 0.5f, new Vector2(0, -1));
p1.velocity *= 0.5f;
}
}
if (ropeLength <= p1.Position.DistanceTo(p2.Position))
{
Vector2 parallelPart = (p1.velocity.Dot(ropePullVector) / ropePullVector.Dot(ropePullVector)) * ropePullVector;
if (parallelPart.Dot(ropePullVector) < 0)
{
p1.velocity -= parallelPart;
}
}
}
if (p1.hitNonWall())
{
p1.velocity = new Vector2(0, 0);
p1.velocity.y += delta * p1.gravity;
p1.velocity.y = Math.Min(p1.velocity.y, p1.maxYVel);
}
}
public override void _Process(float delta)
{
float ropeNotUsed = ropeLength - p1.Position.DistanceTo(p2.Position);
base._Process(delta);
ropeDraw.ClearPoints();
ropeDraw.AddPoint(p1.Position);
for(int i = 1;i < ropePoints; i++)
{
float lerpVal = (float)i / (float)ropePoints;
// GD.Print("Lerp val : " + lerpVal);
// GD.Print("From " + i + " /" + ropePoints);
Vector2 tempPoint = vec2Lerp(p2.Position, p1.Position, lerpVal);
if(lerpVal >= 0.5f)
{
tempPoint.y += ropeNotUsed * -(lerpVal - 1) * lerpVal;
//GD.Print("Adjusted Lerp val : " + (-(lerpVal - 1)));
}
else
{
tempPoint.y += ropeNotUsed * lerpVal *-(lerpVal - 1);
}
////GD.Print("Temp point loc : " + tempPoint);
ropeDraw.AddPoint(tempPoint);
}
ropeDraw.AddPoint(p2.Position);
}
Vector2 vec2Lerp(Vector2 p1,Vector2 p2,float val)
{
return (p1 * val) + (p2 * (1.0f - val));
}
}
<file_sep>using Godot;
using System;
public class lightFlicker : Light2D
{
// Declare member variables here. Examples:
[Export]
float period = 1;
[Export]
float maxSize = 3;
[Export]
float minSize = 2.5f;
private float sizeDiff;
private float time = 0;
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
sizeDiff = maxSize - minSize;
TextureScale = (sizeDiff / 2) * (float)Math.Sin(Math.PI / (2 * period) * time) + ((minSize + maxSize) / 2);
}
// Called every frame. 'delta' is the elapsed time since the previous frame.
public override void _Process(float delta)
{
// flicker the flame
time += delta;
TextureScale = (sizeDiff/2) * (float)Math.Sin(Math.PI/(2*period) * time) + ((minSize + maxSize)/2);
}
}
<file_sep>using Godot;
using System;
public class cameraFollow : Camera2D
{
// Declare member variables here. Examples:
// private int a = 2;
// private string b = "text";
[Export]
NodePath player1Path;
[Export]
NodePath player2Path;
Node2D p1;
Node2D p2;
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
p1 = (Node2D)GetNode(player1Path);
p2 = (Node2D)GetNode(player2Path);
}
// Called every frame. 'delta' is the elapsed time since the previous frame.
public override void _Process(float delta)
{
Vector2 avgPos = (p1.Position + p2.Position) / 2;
Position = avgPos;
}
}
<file_sep>using Godot;
using System;
public class Globals : Godot.Node
{
public const int UNIT_SIZE = 32;
}
<file_sep>using Godot;
using System;
public class timer : Node2D
{
// Declare member variables here. Examples:
// private int a = 2;
// private string b = "text";
// Called when the node enters the scene tree for the first time.
Label label;
Timer timer_;
TextureButton begin_game;
[Export]
NodePath p1;
[Export]
NodePath p2;
[Export]
NodePath hinting;
AnimatedSprite p1_;
AnimatedSprite p2_;
Label hint_field;
[Export]
NodePath timerPath;
[Export]
NodePath displayPath;
[Export]
NodePath climbButtonPath;
public override void _Ready()
{
hint_field = (Label)GetNode(hinting);
set_hint();
p1_ = (AnimatedSprite)GetNode(p1);
p2_ = (AnimatedSprite)GetNode(p2);
timer_ = (Timer)GetNode(timerPath);
label = (Label)GetNode(displayPath);
begin_game = (TextureButton)GetNode(climbButtonPath);
begin_game.Visible = false;
}
// // Called every frame. 'delta' is the elapsed time since the previous frame.
public override void _Process(float delta)
{
label.Text = ((int)timer_.TimeLeft).ToString();
if(label.Text == "0")
{
p1_.FlipH = true;
p2_.FlipH = false;
begin_game.Visible = true;
if (begin_game.Pressed)
{
GetTree().ChangeScene("res://assets/scenes/prod/main level.tscn");
}
}
}
public void set_hint()
{
Random x = new Random();
int k = x.Next(0, 3);
switch (k) {
case 0:
hint_field.Text = "Jump together for a higher jump";
break;
case 1:
hint_field.Text = "Time your jump with partner by Counting";
break;
case 2:
hint_field.Text = "For the best experience, play with a friend. Or you're a psycho.";
break;
}
}
}
<file_sep>using Godot;
using System;
public class playerMovment : KinematicBody2D
{
[Export]
NodePath animationsPath;
[Export]
float ropeLength = 300.0f;
[Export]
float wallSlideSpeed = 130.0f;
[Export]
public float maxXVel = 300.0f;
[Export]
public float maxYVel = 500.0f;
[Export]
float airDashMod = 10f;
[Export]
public float gravity = 1000f;
[Export]
int walkSpeed = 300;
int strafeSpeed = 100;
[Export]
int jumpStrength = 700;
[Export]
int player = -1;
[Export]
float wallNoSlideTime = 0.2f;
[Export]
NodePath jump1;
[Export]
NodePath jump2;
[Export]
NodePath jump3;
[Export]
NodePath fall1;
[Export]
NodePath fall2;
[Export]
NodePath fall3;
[Export]
float wallJumpCoolDown = 5.0f;
float currentWallJumpCoolDown = 0.0f;
AudioStreamPlayer jj1;
AudioStreamPlayer jj2;
AudioStreamPlayer jj3;
AudioStreamPlayer hh1;
AudioStreamPlayer hh2;
AudioStreamPlayer hh3;
int buffer_y = 0;
AnimatedSprite animations;
float currentWallNoSlideTime = 0.0f;
public bool isAnchored = false;
bool onWall = false;
bool onFloor = false;
bool wallJumpReady = true;
public float airXAccel;
public Vector2 velocity;
double maxJumpVelocity;
double minJumpVelocity;
double maxJumpHeight = 5 * Globals.UNIT_SIZE;
double minJumpHeight = 0.8 * Globals.UNIT_SIZE;
double jumpDuration = 0.5;
// Called when the node enters the scene tree for the first time.
public override void _Ready()
{
jj1 = (AudioStreamPlayer)GetNode(jump1);
jj2 = (AudioStreamPlayer)GetNode(jump2);
jj3 = (AudioStreamPlayer)GetNode(jump3);
hh1 = (AudioStreamPlayer)GetNode(fall1);
hh2 = (AudioStreamPlayer)GetNode(fall2);
hh3 = (AudioStreamPlayer)GetNode(fall3);
animations = (AnimatedSprite)GetNode(animationsPath);
airXAccel = 0;
}
// public override void _ApplyMovement (InputEvent @event)
// {
// for (i = 0; i < getSlideCOunt(); i++)
// {
// var collision = getSlideCollision(i);
// if (collision.collider.HasMethod("collideWith"))
// {
// collision.collider.collideWith(collision,self);
// }
// }
// }
public override void _Input (InputEvent @event)
{
if(@event.IsActionReleased("player2_move_jump") && velocity.y < minJumpVelocity)
{
velocity.y = (float)minJumpVelocity;
}
if (@event.IsActionReleased("player1_move_jump") && velocity.y < minJumpVelocity)
{
velocity.y = (float)minJumpVelocity;
}
}
public override void _PhysicsProcess(float delta)
{
airXAccel = 0.0f;
if (onFloor || onWall)
{
isAnchored = true;
}
else
{
isAnchored = false;
}
if (!onWall)
{
velocity.y += gravity * delta;
velocity.y = Math.Min(velocity.y, maxYVel);
}
else
{
currentWallNoSlideTime += delta;
if(currentWallNoSlideTime < wallNoSlideTime)
{
velocity.y = 0;
}
else
{
velocity.y = wallSlideSpeed;
}
//GD.Print("On the wall!");
}
if (onFloor)
{
currentWallNoSlideTime = 0;
currentWallJumpCoolDown = 0;
wallJumpReady = true;
}
if(currentWallJumpCoolDown < wallJumpCoolDown)
{
currentWallJumpCoolDown += delta;
}
else
{
wallJumpReady = true;
currentWallJumpCoolDown = 0.0f;
}
//Aight this is pretty bad I admit but w/e game jam!
if (player == 0)
{
if (Input.IsActionPressed("player1_move_left"))
{
if (onFloor)
{
velocity.x = -walkSpeed;
}
else
{
airXAccel = walkSpeed * airDashMod * delta;
if (velocity.x > -maxXVel)
{
velocity.x -= airXAccel;
}
//velocity.x = Math.Max(-maxXVel, velocity.x - airXAccel);
}
}
else if (Input.IsActionPressed("player1_move_right"))
{
if (onFloor)
{
velocity.x = walkSpeed;
}
else
{
airXAccel = walkSpeed * airDashMod * delta;
if (velocity.x < maxXVel)
{
velocity.x += airXAccel;
}
// velocity.x = Math.Min(maxXVel, velocity.x + airXAccel);
}
}
else
{
if (onFloor)
{
velocity.x = 0;
}
}
if (Input.IsActionJustPressed("player1_move_jump"))
{
if (onFloor)
{
make_jump_sound();
velocity.y = -jumpStrength;
}
if (onWall && wallJumpReady)
{
velocity.y = -jumpStrength;
wallJumpReady = false;
if (GetSlideCount() > 0 )
{
KinematicCollision2D col = GetSlideCollision(0);
velocity.x = col.Normal.x * jumpStrength *0.5f ;
// true;
}
}
}
if (velocity.x < 0)
{
animations.FlipH = false;
}
else if (velocity.x > 0)
{
animations.FlipH = true;
}
//animation stuff
if (onFloor && velocity.x != 0){
//Restarts the animation
animations.Play("run");
}else if(!onFloor && velocity.y >= walkSpeed) {
animations.Play("fall");
}else if(!onFloor) {
animations.Play("swing");
}else{
animations.Play("idle");
}
}
else
{
if (Input.IsActionPressed("player2_move_left"))
{
if (onFloor)
{
velocity.x = -walkSpeed;
}
else
{
airXAccel = walkSpeed * airDashMod * delta;
if (velocity.x > -maxXVel)
{
velocity.x -= airXAccel;
}
// velocity.x = Math.Max(-maxXVel, velocity.x - airXAccel);
}
}
else if (Input.IsActionPressed("player2_move_right"))
{
if (onFloor)
{
velocity.x = walkSpeed;
}
else
{
airXAccel = walkSpeed * airDashMod * delta;
if (velocity.x < maxXVel)
{
velocity.x += airXAccel;
}
//velocity.x = Math.Min(maxXVel, velocity.x + airXAccel);
}
}
else
{
if (onFloor)
{
velocity.x = 0;
}
}
if (Input.IsActionJustPressed("player2_move_jump"))
{
if (onFloor)
{
make_jump_sound();
velocity.y = -jumpStrength;
}
if (onWall && wallJumpReady)
{
velocity.y = -jumpStrength;
wallJumpReady = false;
if (GetSlideCount() > 0)
{
KinematicCollision2D col = GetSlideCollision(0);
velocity.x = col.Normal.x * jumpStrength * 0.5f;
// true;
}
}
}
if (velocity.x < 0)
{
animations.FlipH = false;
}
else if (velocity.x > 0)
{
animations.FlipH = true;
}
if (onFloor && velocity.x != 0){
animations.Play("run2");
}else if(!onFloor && velocity.y >= walkSpeed) {
animations.Play("fall2");
}else if(!onFloor) {
animations.Play("swing2");
}else{
animations.Play("idle2");
}
}
}
public void make_fall_sound()
{
Random rnd = new Random();
int x = rnd.Next(1, 10);
switch (x)
{
case 1:
hh1.Play();
break;
case 2:
hh2.Play();
break;
case 3:
hh3.Play();
break;
default:
break;
}
}
public void make_jump_sound()
{
Random rnd = new Random();
int x = rnd.Next(1,5);
switch (x)
{
case 1:
jj1.Play();
break;
case 2:
jj2.Play();
break;
case 3:
jj3.Play();
break;
default:
break;
}
}
public void move()
{
MoveAndSlide(velocity, new Vector2(0, -1));
onFloor = IsOnFloor();
onWall = (IsOnWall() && wallJumpReady);
}
public bool hitNonWall()
{
if (GetSlideCount() > 0 && !onFloor)
{
KinematicCollision2D col = GetSlideCollision(0);
return col.Normal.y > 0;
// true;
}
return false;
}
public void applyForce(Vector2 force)
{
velocity += force;
}
}
<file_sep>using Godot;
using System;
public class cloud : AnimatedSprite
{
// Declare member variables here. Examples:
// private int a = 2;
// private string b = "text";
// Called when the node enters the scene tree for the first time.
[Export]
public int cloud_velocity = 3;
public override void _Ready()
{
}
// // Called every frame. 'delta' is the elapsed time since the previous frame.
public override void _Process(float delta)
{
Vector2 mm = new Vector2(Position.x, Position.y);
mm.x -= cloud_velocity / 2;
Position = mm;
}
}
| 9efb5a9edd16f284c222172b6981fa94a46b0de3 | [
"C#"
] | 7 | C# | Isvan/BCGameJam2020 | 2673da06f09fe3f126a9a62e929794c1c28dc3d4 | 968901f478644265b9e9456a2ce5d4966594e32a |
refs/heads/master | <repo_name>MukandAryal/CreateRepoGithub<file_sep>/CreateRepoGithub/ViewController.swift
//
// ViewController.swift
// CreateRepoGithub
//
// Created by ksglobal on 25/09/18.
// Copyright © 2018 ksglobal. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let button:UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
button.backgroundColor = UIColor.blackColor()
button.setTitle("Button", forState: UIControlState.Normal)
//button.addTarget(self, action:#selector(self.buttonClicked), forControlEvents: .TouchUpInside)
self.view.addSubview(button)
func buttonClicked() {
print("Button Clicked")
}
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 1f9bd2e9dec4a6b09f7460993a4f20767383c396 | [
"Swift"
] | 1 | Swift | MukandAryal/CreateRepoGithub | f5fa8c7d7b0514995a846c2b9b9ab775dd55df8c | 88e4833ddf8c6b1001fed10f3503afb8c9f763de |
refs/heads/master | <repo_name>atiw003/Tasks<file_sep>/apps/tasks/controllers/user.js
// ==========================================================================
// Tasks.userController
// ==========================================================================
/*globals CoreTasks Tasks sc_require */
sc_require('lib/sha1');
/**
This controller tracks the selected User
@extends SC.ObjectController
@author <NAME>
*/
Tasks.userController = SC.ObjectController.create(Tasks.Sha1,
/** @scope Tasks.userController.prototype */ {
contentBinding: SC.Binding.oneWay('Tasks.usersController.selection'),
loginNameErrorMessage: '',
emailErrorMessage: '',
unhashedPassword: '',
isValidUserName: function() {
var name = this.get('name');
if(name === '' || name === CoreTasks.NEW_USER_NAME || name === CoreTasks.NEW_USER_NAME.loc()) return false;
var loginName = this.get('loginName');
if(loginName === '' || loginName === CoreTasks.NEW_USER_LOGIN_NAME || loginName === CoreTasks.NEW_USER_LOGIN_NAME.loc()) return false;
return true;
}.property('name', 'loginName').cacheable(),
displayLoginNameError: function() {
this.set('loginNameErrorMessage', "_InUse".loc());
},
clearLoginNameError: function() {
this.set('loginNameErrorMessage', '');
},
displayEmailError: function() {
this.set('emailErrorMessage', "_Invalid".loc());
},
clearEmailError: function() {
this.set('emailErrorMessage', '');
},
_emailDidChange: function() {
this.set('emailErrorMessage', '');
}.observes('.content.email'),
_loginNameDidChange: function() {
this.set('loginNameErrorMessage', '');
}.observes('.content.loginName'),
_unhashedPassword: '',
unhashedPassword: function(key, value) {
if (value !== undefined) {
this._unhashedPassword = value;
this.set('password', Tasks.userController.hashPassword(value));
} else {
return this._unhashedPassword;
}
}.property('_unhashedPassword').cacheable(),
hashPassword: function(password) {
return password? this.sha1Hash(password) : '';
},
_contentDidChange: function() {
var user = this.getPath('content.firstObject');
if(user) {
var password = user.get('password');
this._unhashedPassword = <PASSWORD>? '<PASSWORD>' : '';
}
}.observes('content')
});
<file_sep>/apps/tasks/core.js
// ==========================================================================
// Project: Tasks
// License: Licened under MIT license (see license.js)
// ==========================================================================
/**
"Tasks" - an agile project management tool
@extends SC.Object
@author <NAME>
@version 0.1
*/
/*globals Tasks CoreTasks */
Tasks = SC.Object.create(
/** @scope Tasks.prototype */ {
NAMESPACE: 'Tasks',
VERSION: '1.5',
isLoaded: NO, // for Lebowski
/*
* Tasks server types. Defaulted to GAE - detected/set at runtime
*/
NO_SERVER: 0x0000,
PERSEVERE_SERVER: 0x0001,
GAE_SERVER: 0x0002,
serverType: 0x0002,
/**
* A computed property to indicate whether the server is capable of sending notifications.
* @returns {Boolean} true: if connected to a server that supports notifications, false otherwise
*/
canServerSendNotifications: function() {
if(CoreTasks.get('dataSourceType') === CoreTasks.FIXTURES_DATA_SOURCE) return true; // to assist with testing via fixtures
return this.get('serverType') === this.GAE_SERVER;
}.property('serverType').cacheable(),
/**
* Returns link to Tasks application
*/
getBaseUrl: function() {
return window.location.protocol + '//' + window.location.host + window.location.pathname;
},
/**
* Returns link to Tasks help
*/
getHelpUrl: function() {
return static_url('help.html') + '?softwareMode=' + Tasks.softwareMode;
},
/**
* Sorting function based on 'name' key.
*/
nameAlphaSort: function(a,b) {
var aName = a.get('name');
var bName = b.get('name');
if(aName === bName) return 0;
else return aName > bName? 1 : -1;
},
/**
* Called by CoreTasks when data saves fail.
*
* @param (String) type of record for which save failed
*/
dataSaveErrorCallback: function(errorRecordType) {
// console.log('DEBUG: dataSaveErrorCallback(' + errorRecordType + ')');
var serverMessage = Tasks.getPath('mainPage.mainPane.serverMessage');
serverMessage.set('value', "_DataSaveError".loc() + SC.DateTime.create().toFormattedString(CoreTasks.TIME_DATE_FORMAT));
}
});
/**
Some view overrides to turn off escapeHTML for menu items in context menus and select buttons.
*/
SC.MenuItemView = SC.MenuItemView.extend({
escapeHTML: NO
});
SC.SelectButtonView = SC.SelectButtonView.extend({
escapeHTML: NO
});
SCUI.ContextMenuPane = SCUI.ContextMenuPane.extend({
exampleView: SC.MenuItemView
});
// TODO: [SG] remove hack for SCUI ComboBoxView using an SC.ButtonView since it doesn't fit unless all SC styles are overridden
SCUI.ComboBoxView.prototype.dropDownButtonView = SC.View.extend( SCUI.SimpleButton, {
classNames: 'scui-combobox-dropdown-button-view',
layout: { top: 0, right: 0, height: 24, width: 28 }
});
// TODO: [SG/EG] update SCUI.ToolTip to work with SC master (new rendering subsystem), CheckboxView still not working
// TODO: [SG/BB] make SCUI.ModalPane close button target/action overridable without snippet below
SCUI.ModalPane = SCUI.ModalPane.extend({
initMixin: function() {
var headerCloseButton = this.childViews[0].closeButton;
headerCloseButton.set('target', null);
headerCloseButton.set('action', 'close');
}
});
/**
A Standard Binding transform to localize a string in a binding.
*/
SC.Binding.toLocale = function() {
return this.transform(function(value, binding) {
var returnValue = '';
if (SC.typeOf(value) === SC.T_STRING) {
returnValue = "%@".fmt(value).loc();
}
return returnValue;
});
};
// if software mode set to false, works as a simple To Do list (Task Type/Validation are not available through GUI)
Tasks.softwareMode = document.title.match(/todo/i)? false: true;<file_sep>/spec/config.rb
# Tasks/Lebowski login tests
# Author: <NAME>, <NAME>
App.define_path 'mainPane', 'mainPage.mainPane', MainPane
USER_NAME = "SA"
PASSWORD = ""
USER_ROLE = "manager"
NEW_PROJECT_DEFAULT_NAME = "new project"
NEW_TASK_DEFAULT_NAME = "new task"
NEWUSERLOGINNAME = "euser"
NEWUSERFULLNAME = "<NAME>"
DEVELOPERUSERNAME = "Douglas Developer"
IMPORTNEWTASK = "Fred
- Imported: Feature: Medium Priority, Planned {2d} <SA> [DD] $Feature
| This is a description of the first imported task
| This is the second line of the first tasks description there are no special characters"
App.define_framework 'core_tasks', 'CoreTasks'
App.define_path 'main_pane', 'mainPage.mainPane', MainPane
App.define_path 'actions_button', 'main_pane.topBarView.actionsButton', ButtonView
App.define_path 'login_panel', 'loginPage.panel', PanelPane
App.define_paths_for 'login_panel' do |path|
path.define_path 'user_name_field', 'contentView.loginNameField', TextFieldView
path.define_path 'password_field', 'contentView.passwordField', TextFieldView
path.define_path 'login_button', 'contentView.loginButton', ButtonView
path.define_path 'login_err_msg', 'contentView.loginErrorMessageLabel', LabelView
path.define_path 'guest_signup_button', 'contentView.guestSignupButton', ButtonView
end
App.define_path 'signup_panel', 'signupPane', PanelPane
App.define_paths_for 'signup_panel' do |path|
path.define_path 'signup_prompt', 'contentView.signupPrompt', LabelView
path.define_path 'signup_button', 'contentView.signupButton', ButtonView
path.define_path 'cancel_button', 'contentView.cancelButton', ButtonView
path.define_path 'fullNameLabel', 'contentView.userInformation.fullNameLabel', LabelView
path.define_path 'fullNameField', 'contentView.userInformation.fullNameField', TextFieldView
path.define_path 'loginNameLabel', 'contentView.userInformation.loginNameLabel', LabelView
path.define_path 'loginNameField', 'contentView.userInformation.loginNameField', TextFieldView
path.define_path 'roleLabel', 'contentView.userInformation.roleLabel', LabelView
path.define_path 'roleField', 'contentView.userInformation.roleField', 'SC.SelectButtonView' # was SelectFieldView
path.define_path 'emailLabel', 'contentView.userInformation.emailLabel', LabelView
path.define_path 'emailField', 'contentView.userInformation.emailField', TextFieldView
path.define_path 'passwordLabel', 'contentView.userInformation.passwordLabel', LabelView
path.define_path 'passwordField', 'contentView.userInformation.passwordField', TextFieldView
end
<file_sep>/Buildfile
config :scui, :required => [:foundation, :calendar, :dashboard, :drawing, :linkit]
config :'core-tasks', :required => [:sproutcore, :scuds, :'scuds/local']
config :tasks, :required => [:'core-tasks', :ki, :sproutcore, :scui, :sai, :'sai/graphs'],:title=>"Tasks:Dev"
# config :tasks, :required => [:'core-tasks', :ki, :sproutcore, :scui, :sai, :'sai/graphs'],:title=>"Tasks:Demo"
# config :tasks, :required => [:'core-tasks', :ki, :sproutcore, :scui, :sai, :'sai/graphs'],:title=>"Todos:Eloqua"
# config :tasks, :required => [:'core-tasks', :ki, :sproutcore, :scui, :sai, :'sai/graphs'],:title=>"Tasks:SproutCore"
# config :tasks, :required => [:'core-tasks', :ki, :sproutcore, :scui, :sai, :'sai/graphs'],:title=>"Tasks:TPG"
# config :tasks, :required => [:'core-tasks', :ki, :sproutcore, :scui, :sai, :'sai/graphs'],:title=>"Tasks:Greenhouse"
# Local Persevere back end - prod instance
proxy '/tasks-server', :to => 'localhost:8088', :protocol => 'http'
# Local Persevere back end - test instance
# proxy '/tasks-server', :to => 'localhost:8089', :protocol => 'http'
# Local GAE back end (comment 'Persevere back end' line above, uncomment next line & replace 8091 with port of GAE application)
# proxy '/tasks-server', :to => 'localhost:8091', :protocol => 'http'
| dae2ef90a90d4a44627281d54ecd2820fbf848f2 | [
"JavaScript",
"Ruby"
] | 4 | JavaScript | atiw003/Tasks | 65fcc1e89c1ff2e26c016527539feaec340be45e | 2d6773ea347d85bc3ef340e63fc811f8a235fbd8 |
refs/heads/master | <file_sep>"""
You have a non-empty set , and you have to execute N commands given in N lines.
The commands will be pop, remove and discard.
Input Format
The first line contains integer N, the number of elements in the set .
The second line contains N space separated elements of set S.
All of the elements are non-negative integers, less than or equal to 9.
The third line contains integer N, the number of commands.
The next N lines contains either pop, remove and/or discard commands followed by their associated value.
Output Format
Print the sum of the elements of set S on a single line.
"""
"""
This is a HackerRank exercise. You can find it in the following link:
https://www.hackerrank.com/challenges/py-set-discard-remove-pop/problem
"""
n = int(input())
s = set(map(int, input().split()))
num=int(input())
l=[]
for i in range (num):
l.append(input())
for j in range(len(l)):
le=l[j].split(" ")
if(len(le)>1):
eval("s.{}({})".format(le[0],le[1]))
else:
eval("s.{}()".format(le[0]))
print(sum(s))
<file_sep>"""Complete the countApplesAndOranges function in the editor below.
It should print the number of apples and oranges that land on Sam's house, each on a separate line.
countApplesAndOranges has the following parameter(s):
s: integer, starting point of Sam's house location.
t: integer, ending location of Sam's house location.
a: integer, location of the Apple tree.
b: integer, location of the Orange tree.
apples: integer array, distances at which each apple falls from the tree.
oranges: integer array, distances at which each orange falls from the tree.
Input Format
The first line contains two space-separated integers denoting the respective values of S and T.
The second line contains two space-separated integers denoting the respective values of A and B.
The third line contains two space-separated integers denoting the respective values of M and N.
The fourth line contains M space-separated integers denoting the respective distances that each apple falls from point A.
The fifth line contains N space-separated integers denoting the respective distances that each orange falls from point B.
Print two integers on two different lines:
The first integer: the number of apples that fall on Sam's house.
The second integer: the number of oranges that fall on Sam's house.
This is a HackerRank exercise, you can find it in the following link:
https://www.hackerrank.com/challenges/apple-and-orange/problem
"""
def countApplesAndOranges(s, t, a, b, apples, oranges):
ta=0
to=0
i=0
j=0
while(i<len(apples)):
apples[i]+=a
if(apples[i]>=s and apples[i]<=t):
ta+=1
i+=1
while (j<len(oranges)):
oranges[j]+=b
if(oranges[j]>=s and oranges[j]<=t):
to+=1
j+=1
print(ta)
print(to)
st = input().split()
s = int(st[0])
t = int(st[1])
ab = input().split()
a = int(ab[0])
b = int(ab[1])
mn = input().split()
m = int(mn[0])
n = int(mn[1])
apples = list(map(int, input().rstrip().split()))
oranges = list(map(int, input().rstrip().split()))
countApplesAndOranges(s, t, a, b, apples, oranges)
<file_sep>"""Ejemplo de ejercicio de parcial.
Rellenar una matriz debajo de su diagonal y desde el codigo,
con el numero de su tamaño y todos los menores hasta el 1"""
n=int(input("Ingrese el tamaño de la matriz: "))
filas=n
columnas=0
aux=n
matriz=[[0]*n for i in range(n)]
for f in range (filas):
while(columnas<=f):
matriz[f][columnas]=aux
columnas+=1
columnas=0
aux-=1
filas=n
columnas=n
for f in range(filas):
for c in range (columnas):
print("%3d"%matriz[f][c],end=" ")
print()
<file_sep>"""Desarrollar un programa para rellenar una matriz de N x N con números enteros al
azar comprendidos en el intervalo [0,N2), de tal forma que ningún número se repita. Imprimir la matriz por pantalla."""
import random
n=int(input("Tamaño de la matriz: "))
filas=n
columnas=n
matriz=[]
matriz=[[0]*n for i in range(n)]
aux=[]
num=0
while(len(aux)<n*n):
num=random.randint(0,(n**2)-1)
if(num not in aux):
aux.append(num)
a=0
print(sorted(aux))
for f in range (filas):
for c in range(columnas):
matriz[f][c]=aux[a]
a+=1
for f in range (filas):
for c in range(columnas):
print("%3d"%matriz[f][c],end=" ")
print()
<file_sep>"""Desarrollar una función que devuelva el producto de dos números enteros por sumas sucesivas"""
def suma(a,b):
if b==0:
return 0
else:
return a + (suma(a,b-1))
a=int(input("Primer numero: "))
b=int(input("Segundo numero: "))
func=suma(a,b)
print("La multiplicacion de {} por {} da como resultado {}".format(a,b,func))<file_sep>"""Escribir una función para eliminar una subcadena de una cadena de caracteres, a
partir de una posición y cantidad de caracteres dadas, devolviendo la cadena resultante.
Escribir también un programa para verificar el comportamiento de la misma.
Escribir una función para cada uno de los siguientes casos:
a. Utilizando rebanadas
b. Sin utilizar rebanadas"""
def dele(fr,n,u): #FORMA A
aux=list(fr)
del aux[n:n+u]
aux="".join(aux)
return aux
"""def dele(fr,n,u): FORMA B
aux=list(fr)
z=n
for i in range (u):
del(aux[z])
aux="".join(aux)
return aux
"""
fr=input("Cadena: ")
n=int(input("Posicion: "))
u=int(input("cantidad de caracteres: "))
func=dele(fr,n,u)
print(func)<file_sep>def mat(filas,columnas):
matriz=[[0] * columnas for i in range(filas)]
cont=1
tx=0
aux=0
while(columnas>0):
matriz[tx][columnas-1]=cont
cont+=2
tx+=1
columnas-=1
"""for f in range (filas):
for c in range(columnas):
if(f==c):
matriz[f][c]=cont
cont+=2
"""
return matriz
n=int(input("Tamaño de matriz: "))
filas=n
columnas=n
func=mat(filas,columnas)
for f in range (filas):
for c in range(columnas):
print("%3d"%func[f][c],end=" ")
print()<file_sep>"""Escribir una función filtrar_palabras() que reciba una cadena de caracteres conteniendo una frase y un entero N,
y devuelva otra cadena con las palabras que tengan N o más caracteres de la cadena original.
Escribir también un programa para verificar el comportamiento de la misma. Hacer tres versiones de la función, para
cada uno de los siguientes casos:
a. Utilizando sólo ciclos normales
b. Utilizando listas por comprensión
c. Utilizando la función filter"""
"""def filtrar_palabras(n,fr): FORMA A
x=fr.split()
aux=[]
for i in range(len(x)):
if(len(x[i])>=n):
aux.append(x[i])
return aux"""
"""def filtrar_palabras(n,fr):
x=fr.split()
aux=[x[i] for i in range(len(x)) if(len(x[i])>=n)]
return aux"""
def filtrar_palabras(n,fr):
x=fr.split()
aux=[]
ss=list(filter(lambda x: len(x)>=n, x))
return ss
n=int(input("Numero de caracteres: "))
fr=input("Cadena: ")
func=filtrar_palabras(n,fr)
print("Las palabras formadas por mas de {} caracteres de su oracion son:\n".format(n))
for i in range (len(func)):
print(func[i])<file_sep>This Repository contains small exercises about Python that I've learned at my University and the Internet. All exercises have been tested using Thonny IDE.
<file_sep>"""permita verificar su funcionamiento, imprimiendo la matriz luego de invocar a cada función:
a. Cargar números enteros en una matriz de N x N, ingresando los datos desde
teclado.
b. Ordenar en forma ascendente cada una de las filas de la matriz.
c. Intercambiar dos filas, cuyos números se reciben como parámetro.
d. Intercambiar dos columnas dadas, cuyos números se reciben como parámetro.
e. Intercambiar una fila por una columna, cuyos números se reciben como parámetro.
f. Transponer la matriz sobre si misma. (intercambiar cada elemento Aij por Aji)
g. Calcular el promedio de los elementos de una fila, cuyo número se recibe como
parámetro.
h. Calcular el porcentaje de elementos con valor impar en una columna, cuyo número
se recibe como parámetro.
i. Determinar si la matriz es simétrica con respecto a su diagonal principal.
j. Determinar si la matriz es simétrica con respecto a su diagonal secundaria.
k. Determinar qué columnas de la matriz son palíndromos (capicúas), devolviendo
una lista con los números de las mismas."""
#FORMO UNA LISTA PARA ORDENAR Y DESPUES RELLENAR CON LOS VALORES EN ORDEN
def relleno(n):
tempo=[]
for i in range(n*n):
te=int(input("Ingrese un valor: "))
tempo.append(te)
return tempo
#ORDENO LA LISTA CON REBANDAS
def puntob(tempo,n):
x=0
u=0
fin=[]
for a in range (n*n-n):
t=tempo[x:n+u]
t.sort()
fin.append(t)
x+=n
u+=n
return fin
#IMPRIMO EN FORMA DE MATRIZ
def imprimo(orden):
filas=n
columnas=n
for f in range (filas):
for c in range(columnas):
print("%3d"%orden[f][c],end="")
print()
#CAMBIO FILAS DE LUGAR
def cambiofilas(orden):
a=int(input("fila: "))
while(a<=0 or a>n):
a=int(input("Valor invalido. Por favor, intente otra vez.\n"))
a-=1
b=int(input("Otra fila: "))
while(b<=0 or b>n):
b=int(input("Valor invalido. Por favor, intente otra vez.\n"))
b-=1
columnas=n
for c in range (columnas):
aux=orden[a][c]
orden[a][c]=orden[b][c]
orden[b][c]=aux
#CAMBIO COLUMNAS DE LUGAR
def cambiocolumnas(orden):
a=int(input("Columna: "))
while(a<=0 or a>n):
a=int(input("Valor invalido. Por favor, intente otra vez.\n"))
a-=1
b=int(input("Otra columna: "))
while(b<=0 or b>n):
b=int(input("Valor invalido. Por favor, intente otra vez.\n"))
b-=1
filas=n
for f in range(filas):
aux=orden[f][a]
orden[f][a]=orden[f][b]
orden[f][b]=aux
#CAMBIO DE LUGAR UNA FILA CON UNA COLUMNA
def columnayfila(orden):
a=int(input("fila: "))
while(a<=0 or a>n):
a=int(input("Valor invalido. Por favor, intente otra vez.\n"))
a-=1
b=int(input("Columna: "))
while(b<=0 or b>n):
b=int(input("Valor invalido. Por favor, intente otra vez.\n"))
b-=1
columnas=n
f=0
for c in range (columnas):
aux=orden[a][c]
orden[a][c]=orden[c][b]
orden[c][b]=aux
#INGRESO EL TAMAÑO DE LA MATRIZ POR TECLADO
n=int(input("tamaño matriz: "))
#LLAMO A LAS FUNCIONES
tempo=relleno(n)
orden=puntob(tempo,n)
imprimir=imprimo(orden)
print()#DEJO UN ESPACIO ENTRE LAS IMPRESIONES PARA QUE NO QUEDE TODO PEGADO
"""cfilas=cambiofilas(orden)
imprimir=imprimo(orden)
ccolumnas=cambiocolumnas(orden)
imprimir=imprimo(orden)
puntoE=columnayfila(orden)
imprimir=imprimo(orden)
Transponer la matriz sobre si misma. (intercambiar cada elemento Aij por Aji)"""
<file_sep>def cargar(matriz,u):
filas=u
columnas=u
aux=[]
d=filas*columnas
for r in range(d):
n=int(input("Ingrese un valor: "))
aux.append(n)
r=0
aux.sort()
for f in range(filas):
for c in range(columnas):
matriz[f][c]=aux[r]
r+=1
return matriz
def impr(mat,filas,columnas):
for f in range(filas):
for c in range(columnas):
print("%3d"%mat[f][c],end=" ")
print()
n=int(input("tamaño matriz: "))
filas=n
columnas=n
mat=[[0]*n for i in range(n)]
puntoA=cargar(mat,n)
pr=impr(mat,filas,columnas)
<file_sep>"""Escribir un programa que permita grabar un archivo los datos de lluvia caída durante un año.
Cada línea del archivo se grabará con el siguiente formato: <dia>;<mes>;<lluvia caída en mm> por ejemplo 25;5;319
Los datos se generarán mediante números al azar, asegurándose que las fechas sean válidas.
La cantidad de registros también será un número al azar entre 50 y 200.
Por último se solicita leer el archivo generado e
imprimir un informe en formato matricial donde cada columna represente a un mes
y cada fila corresponda a los días del mes. Imprimir además el total de lluvia caída en todo el año."""
import random
try:
arch=open(r"D:\Users\EMONEVA\Desktop\clima.txt","wt")#SE DEBE MODIFICAR LA DIRECCION PARA TEST
cant=random.randint(50,200)
n=0
while (n<=cant):
dia=random.randint(1,31)
mes=random.randint(1,12)
mm=random.randint(0,1000)
arch.write("{};{};{}\n".format(dia,mes,mm))
n+=1
except NameError:
print("???")
finally:
try:
arch.close()
except NameError:
pass<file_sep>"""Escribir una función que devuelva la cantidad de dígitos de un número entero, sin utilizar cadenas de caracteres"""
def rec(x):
if x < 9:
return 1
else:
return 1+(rec(x/10))
n=int(input("Ingrese un numero: "))
res=0
func=rec(n)
print("El numero tiene {} digitos".format(func))<file_sep>"""Escribir una funcion diasiguiente() que reciba como parámetro una fecha cualquiera expresada por tres enteros (correspondientes al dia, mes y ano) y calcule y
devuelva tres enteros correspondientes el dia siguiente al dado.
Utilizando esta funcion, desarrollar programas que permitan:
a. Sumar N dias a una fecha.
b. Calcular la cantidad de dias existentes entre dos fechas cualesquiera."""
#4 6 9 11
def diasiguiente(dia,mes,ano):
if(mes==2):
if(ano%4==0 and ano%100!=0 or ano%400==0):
if(dia<29):
dia+=1
else:
dia=1
mes+=1
else:
if(dia<28):
dia+=1
else:
dia=1
mes+=1
elif(mes==12):
if(dia<31):
dia+=1
else:
dia=1
mes=1
ano+=1
else:
if (mes in [4,6,9,11]):
if (dia<30):
dia+=1
else:
dia=1
mes+=1
else:
if (dia<31):
dia+=1
else:
dia=1
mes+=1
return dia, mes, ano
d=int(input("Ingrese dia: "))
m=int(input("Ingrese mes: "))
a=int(input("Ingrese ano: "))
dia,mes,ano=diasiguiente(d,m,a)
print("{}/{}/{}".format(dia,mes,ano))
print("\n")
da=int(input("\nIngrese el primer dia a comparar:"))
ma=int(input("Ingrese el mes :"))
anoa=int(input("Ingrese el ano :"))
db=int(input("Ingrese el segundo dia a comparar:"))
mb=int(input("Ingrese el mes :"))
anob=int(input("Ingrese el ano :"))
may=-1
#1 PARA A MAYOR 0 PARA B MAYOR
if(anoa>anob):
may=0
elif(anob>anoa):
may=1
else:
if(ma>mb):
may=1
elif(mb>ma):
may=0
else:
if(da>db):
may=1
elif(db>da):
may=0
cont=0
if(may==-1):
print("Son iguales")
elif(may==1):
while(anob>anoa):
da,ma,anoa=diasiguiente(da,ma,anoa)
cont+=1
elif(may==0):
while(anoa>anob):
db,mb,anob=diasiguiente(db,mb,anob)
cont+=1
if(ma>mb):
while(ma>mb):
db,mb,anob=diasiguiente(db,mb,anob)
cont+=1
else:
while(mb>ma):
da,ma,anoa=diasiguiente(da,ma,anoa)
cont+=1
if(da>db):
while(da>db):
db,mb,anob=diasiguiente(db,mb,anob)
cont+=1
else:
while(db>da):
da,ma,anoa=diasiguiente(da,ma,anoa)
cont+=1
if(may!=-1):
print("hay {} dias de diferencia entre ambas fechas".format(cont))
<file_sep>"""Realizar una función que devuelva el resto de dos números enteros, utilizando restas sucesivas"""
def suma(a,b):
if a<b:
return a
else:
return (suma(a-b,b))
a=int(input("Primer numero: "))
b=int(input("Segundo numero: "))
func=suma(a,b)
print("El modulo entre {} y {} da como resultado {}".format(a,b,func))<file_sep>"""Escribir una función que reciba como parámetro una tupla conteniendo una fecha
(día,mes,año) y devuelva una cadena de caracteres con la misma fecha expresada
en formato extendido. Por ejemplo, para (12,10,17) devuelve "12 de Octubre de
2017". Escribir también un programa para verificar su comportamiento."""
try:
def di(fecha,dict):
res=""
res=fecha[0]," de ", dict[fecha[1]]," de ",fecha[2]
return res
d=int(input("Ingrese dia: "))
m=int(input("Ingrese mes: "))
while(m<0 or m>12):
m=int(input("Ingrese mes: "))
a=int(input("Ingrese año: "))
fecha=d,m,a
dict={
1:"Enero",
2:"Febrero",
3:"Marzo",
4:"Abril",
5:"Mayo",
6:"Junio",
7:"Julio",
8:"Agosto",
9:"Septiembre",
10:"Octubre",
11:"Noviembre",
12:"Diciembre"
}
func= di(fecha,dict)
for i in range (len(func)):
print(func[i], end="")
except ValueError:
print("El valor ingresado no es valido")<file_sep>n=int(input("tamaño: "))
matriz=[[0]*n for i in range (n)]
filas=n
columnas=n
cont=1
for f in range(filas,-1,-1):
if(f==0):
cont=1
for c in range(columnas,-1,-1):
matriz[f-1][c-1]=cont
cont+=cont
for f in range(filas):
for c in range(columnas):
print("%3d"%matriz[f][c],end=" " )
print()
<file_sep>"""Desarrollar una función para reemplazar todas las apariciones de una palabra por
otra en una cadena de caracteres y devolver la cadena obtenida y un entero con la
cantidad de reemplazos realizados. Escribir también un programa para verificar el
comportamiento de la función."""
def rem(fr,x,z):
fr=fr.split()
for i in range(len(fr)):
if(fr[i].lower()==x.lower()):
fr[i]=z
return fr
fr=input("Ingrese su cadena: ")
x=input("Palabra: ")
z=input("Palabra a meter: ")
func=rem(fr,x,z)
func=" ".join(func)
print(func)<file_sep>#Calculate and print the number (without using strings) in order to create a triangle until N-1
for i in range(1,int(input("Insert the size of the triangle: "))):
print((10**(i)//9)*i)#This is a way to get the number without the str()
"""
Explanation for (10**(i)//9)*i:
example for number 2:
10**2 = 100
100/22 = 11,11111111111111
but 100//22 = 11
and 11*2 = 22
"""
<file_sep>ui = input("Insert the space separated values of x and k: ").split()
x = int(ui[0])
print(eval(input("Insert the polynomial to check: ")) == int(ui[1]))
<file_sep>def solve(s):
ss=list(s)
if(ss[0].isalpha()==True):
ss[0]=ss[0].capitalize()
for i in range(len(ss)):
if(ss[i]==" "):
ss[i+1]=ss[i+1].upper()
ss="".join(ss)
return ss
if __name__ == '__main__':
s = input()
result = solve(s)
print(result)<file_sep>def count_substring(string, sub_string):
return(sum([1 for i in range(0, len(string) - len(sub_string) + 1) if (string[i:(len(sub_string)+i)] == sub_string)]))
a=input("String: ")
b=input("Substring")
func=count_substring(a,b)
print("{} aparece {} veces en la cadena.".format(b,func))<file_sep>"""Escribir un programa que cuente cuántas veces se encuentra una subcadena dentro de otra cadena,
sin diferenciar mayúsculas y minúsculas.
Tener en cuenta que los caracteres de la subcadena no necesariamente deben estar en forma consecutiva dentro de la cadena,
pero sí respetando el orden de los mismos."""
cad=input("Ingrese la cadena: ")
cad=cad.lower()
p=input("Ingrese la palabra a buscar: ")
n=list(p.lower())
pos=0
w=""
i=0
while (pos!=len(cad)):
res=cad.find(n[i],pos)
if(res==-1):
break
else:
w+=cad[res]
pos=res
if(i<len(n)-1):
i+=1
else:
i=0
if(len(w)<len(n)):
print("La palabra solicitada no se encuentra en la cadena.")
if(len(w)%len(n)==0):
print("Se encontro la palabra {} veces en el texto".format(len(w)//len(n)))<file_sep>"""You and Fredrick are good friends. Yesterday, Fredrick received credit cards from ABCD Bank. He wants to verify whether his credit card numbers are valid or not. You happen to be great at regex so he is asking for your help!
A valid credit card from ABCD Bank has the following characteristics:
► It must start with a 4, 5 or 6.
► It must contain exactly 16 digits.
► It must only consist of digits (0-9).
► It may have digits in groups of 4, separated by one hyphen "-".
► It must NOT use any other separator like ' ' , '_', etc.
► It must NOT have 4 or more consecutive repeated digits.
Input Format
The first line of input contains an integer N.
The next N lines contain credit card numbers."""
"""
This is a HackerRank exercise. You can find it in the following link:
https://www.hackerrank.com/challenges/validating-credit-card-number/problem
"""
num=int(input("How many credit card numbers are you going to enter?\n"))
ll=[]
print("Enter the credit cards numbers:\n")
for o in range (num):
ll.append(input(""))
for v in range(len(ll)):
gi=0
r=0
try:
n=list(ll[v])
z=len(n)
if("-" in n):
z=len(n)-3
if(z!=16 or " " in n):
print("Invalid")
else:
if(n[0]=="4" or n[0]=="5" or n[0]=="6"):
if("-" in n):
r="".join(n)
while("-" in n):
q,w,x,y=r.split("-")
n.remove("-")
gi+=1
if(gi!=3 or len(w)!=4 or len(x)!=4 or len(y)!=4 or len(q)!=4):
print("Invalid")
else:
n=int("".join(n))
z=list(str(n))
if(str(n).isalnum()==False):
print("Invalid")
else:
for i in range (len(z)):
if (i+1<len(z) and z[i]==z[i+1] and i+4<len(z)):
if(z[i]==z[i+1]):
if(z[i]==z[i+2]):
if(z[i]==z[i+3]):
raise ValueError
print("Valid")
else:
n=int("".join(n))
z=list(str(n))
if(str(n).isalnum()==False):
print("Invalid")
for j in range (len(z)):
if (j+1<len(z) and z[j]==z[j+1] and j+4<len(z)):
if(z[j]==z[j+1]):
if(z[j]==z[j+2]):
if(z[j]==z[j+3]):
raise ValueError
print("Valid")
else:
print("Invalid")
except ValueError:
print("Invalid")
<file_sep>"""Escribir un programa que lea un archivo de texto conteniendo un conjunto de
apellidos y nombres en formato "Apellido, Nombre" y guarde en el archivo
ARMENIA.TXT los nombres de aquellas personas cuyo apellido terminan con la
cadena "IAN", en el archivo ITALIA.TXT los terminados en "INI" y en el archivo
ESPAÑA.TXT los terminados en "EZ". Descartar el resto. Ejemplo:
<NAME> –> ARMENIA.TXT
<NAME> –> ITALIA.TXT
<NAME> –> ESPAÑA.TXT
<NAME> –> descartar
El archivo de entrada puede ser creado mediante el Block de Notas o el IDLE. No
escribir un programa para generarlo."""
try:
arch=open(r"T:\nn.txt","rt")
ita=open(r"T:\ITALIA.txt","wt")
arm=open(r"T:\ARMENIA.txt","wt")
esp=open(r"T:\ESPAÑA.txt","wt")
linea=arch.readline()
while(linea):
apellido,nombre=linea.split(",")
nombre=nombre.rstrip("\n")
apellido=list(apellido)
aux=apellido[len(apellido)-3:]
au=apellido[len(apellido)-2:]
aux="".join(aux)
au="".join(au)
print(aux)
print(au)
if(aux.lower()=="ini"):
ita.writelines(linea)
elif(aux.lower()=="ian"):
arm.writelines(linea)
elif(au.lower()=="ez"):
esp.writelines(linea)
linea=arch.readline()
except SyntaxError:
print("Ups")
finally:
try:
arch.close()
ita.close()
arm.close()
esp.close()
except NameError:
pass<file_sep>"""El método index permite buscar un elemento dentro de una lista, devolviendo la
posición que éste ocupa. Sin embargo, si el elemento no pertenece a la lista se
produce una excepción de tipo ValueError. Desarrollar un programa que cargue
una lista con números enteros ingresados a través del teclado (terminando con -1)
y permita que el usuario ingrese el valor de algunos elementos para visualizar la
posición que ocupan, utilizando el método index. Si el número no pertenece a la
lista se imprimirá un mensaje de error y se solicitará otro para buscar. Abortar el
proceso al tercer error detectado. No utilizar el operador in durante la búsqueda."""
import random
cont=0
lista=[int(input("ingrese un valor: ")) for i in range (10)]
while(cont<3):
try:
n=int(input("Ingrese numero entero: "))
a=lista.index(n,0,100)
print("La posicion es {}" .format(a))
except ValueError:
print("Numero no encontrado")
cont+=1
<file_sep>"""Desarrollar una función que extraiga una subcadena de una cadena de caracteres,
indicando la posición y la cantidad de caracteres deseada. Devolver la subcadena
como valor de retorno. Escribir también un programa para verificar el comportamiento de la misma.
Ejemplo, dada la cadena El número de teléfono es 4356-7890
extraer la subcadena que comienza en la posición 25 y tiene 9 caracteres,
resultando la subcadena "4356-7890". Escribir una función para cada uno de los siguientes casos:
a. Utilizando rebanadas
b. Sin utilizar rebanadas"""
def ext(fr,n,u): #FORMA A
aux=fr[n:(n+u)]
return aux
"""def ext(fr,n,u):
zen=list(fr)
z=n
aux=[]
for i in range(n+u):
if(z<(n+u)):
aux.append(zen[z])
z+=1
aux="".join(aux)
return aux
"""
fr=input("Ingrese cadena: ")
n=int(input("Ingrese posicion: "))
u=int(input("Ingrese cantidad de caracteres: "))
func=ext(fr,n,u)
print(func)<file_sep>"""
Function Description
Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format.
timeConversion has the following parameter(s):
s: a string representing time in 12 hour format
This is a HackerRank exercise. You can find more information in the following link:
https://www.hackerrank.com/challenges/time-conversion/problem
"""
def timeConversion(s):
res=list(s)
res=res[:-2]
num=int("".join(res[:2]))
if(s[-2].upper()=="P" or num==12):
if(num==12 and s[-2].upper()=="A"):
num="00"
else:
if(num!=12):
num+=12
num=list(str(num))
res[0]=num[0]
res[1]=num[1]
res="".join(res)
return res
s = input("Insert a time: ")
result = timeConversion(s)
print(result)
<file_sep>"""Crear una lista con los cuadrados de los numeros entre 1 y N (ambos incluidos),
donde N se ingresa desde el teclado. Luego se solicita imprimir los ultimos 10 valores
de la lista."""
import random
n=int(input("Ingrese el maximo: "))
lista=[]
lista=[(i+1)**2 for i in range(n)]
if(n<=10):
for i in range(n-1,-1,-1):
print(lista[i])
else:
for i in range(10,-1,-1):
if(i>0):
print(lista[i])
<file_sep>"""Desarrollar una función para ingresar a través del teclado un número natural. La
función rechazará cualquier ingreso inválido de datos utilizando excepciones y
mostrará la razón exacta del error. Controlar que se ingrese un número, que ese
número sea entero y que sea mayor que 0. Devolver el valor ingresado cuando
éste sea correcto. Escribir también un programa que permita probar el correcto
funcionamiento de la misma."""
try:
n=list(input('ingrese un numero: '))
if("." in n):
n="".join(n)
n=float(n)
raise ValueError
else:
n="".join(n)
if(n.isdigit()==True):
assert n<0
else:
raise NameError
except AssertionError as e:
print("El numero ingresado es negativo")
except ValueError:
print('El numero ingresado no es entero')
except NameError:
print("eso es una cadena")
<file_sep>"""Desarrollar una función que determine si una cadena de caracteres es capicúa, sin
utilizar cadenas auxiliares. Escribir además un programa que permita verificar su
funcionamiento."""
def test(x):
r=len(x)-1
c=0
for i in range (len(x)):
if(x[r]!=x[i]):
c=-1
r-=1
if(c==0):
return True
else:
return False
n=input("Ingrese la cadena: ")
z=list(n.replace(" ",""))
func=test(z)
if (func):
print("Es capicua")
else:
print("No es capicua") | 8b55664086be41b0f54d8c58458ee1686289d9b5 | [
"Markdown",
"Python"
] | 31 | Python | exequielmoneva/Small-Python-Exercises | 74bbed1ac3d0191eefaa124170b60a596e7318e4 | ceb123aa1daff9ba7399f1711b68fe7d778480cf |
refs/heads/master | <file_sep># Semana_Tec_AD21
Trabajo de la semana tec herramientas computacionales grupo 600, agosto-diciembre 2021.
Trabajo realizado por:
<NAME> - A01703556,
<NAME> - A01703517
## About
Este repositorio contiene la implementación del juego buscaminas en terminal
en el que el se le permite al usuario elegir la cantidad de minas en su tablero, así
como el tamaño del mismo el cual esta determinado por la cantidad de filas y de columnas
que desee el usuario.
Este juego cuenta con la canción "cómo te atreves a volver" de Morat de fondo para hacer más
ameno el juego así como efectos de sonido para la victoria y la derrota.
## Necesario para ejecutar
Usa el administrador de paquetes [pip](https://pip.pypa.io/en/stable/) para instalar
```bash
pip install playsound
```<file_sep>import random
from threading import Thread
from playsound import playsound
import webbrowser
"<NAME> A01703556"
"<NAME> A01703517"
"Proyecto Semana_TEC AD2021"
# Función para abrir archivo de música de fondo
def Fun_mus():
playsound('Como_te_atreves.mp3')
# Definir función que llama audio
music = Thread(target=Fun_mus)
music.daemon = True
# Iniciar musica
music.start()
print("Bienvenido al buscaminas ")
# Inicializacion del estado inicial
filas = int(input("Ingrese el número de filas que desea en su tablero "))
columnas = int(input("Ingrese el número de columnas que desea en su tablero "))
numminas = int(input("Ingrese el número de minas que desea en su tablero "))
score = 0
rondas = 1
rondasParaGanar = (filas * columnas) - numminas
def crearTablero(filas, columnas):
tablero = []
for i in range(0, filas):
tablero.append([])
for j in range(0, columnas):
tablero[i].append(" * ")
return tablero
display = crearTablero(filas, columnas)
def colocarminas():
respuestas = crearTablero(filas, columnas)
for i in range(0, numminas):
posx = random.randint(0, columnas-1)
posy = random.randint(0, filas-1)
while respuestas[posy][posx] == "X":
posx = random.randint(0, columnas-1)
posy = random.randint(0, filas-1)
else:
respuestas[posy].insert(posx, "X")
respuestas[posy].pop(posx+1)
return respuestas
respuestas = colocarminas()
def verificarAlrededor(row, column):
n = 0
print("El primer indice es ", row, "El segundo indice es ", column)
# Casos del centro
if ((row > 0) and (row < len(respuestas) - 1)):
# Centro
if (column > 0) and (column < (len(respuestas) - 1)):
for i in range(row - 1, row + 2):
for j in range(column - 1, column + 2):
if respuestas[i][j] == "X":
n += 1
# Orilla iz
elif (column == 0):
for i in range(row-1, row+2):
for j in range(column, column+2):
if respuestas[i][j] == "X":
n += 1
# Orilla der
elif (column == (len(respuestas[1])-1)):
for i in range(row-1, row+2):
for j in range(column-1, column+1):
if respuestas[i][j] == "X":
n += 1
# Casos de arriba
elif (row == 0):
# Centro
if (column > 0) and (column < (len(respuestas)-1)):
for i in range(row, row+2):
for j in range(column-1, column+2):
if respuestas[i][j] == "X":
n += 1
# Orilla iz
elif (column == 0):
for i in range(row, row+2):
for j in range(column, column+2):
if respuestas[i][j] == "X":
n += 1
# Orilla der
elif (column == (len(respuestas[1])-1)):
for i in range(row, row+2):
for j in range(column-1, column+1):
if respuestas[i][j] == "X":
n += 1
# Casos de abajo
elif (row == (len(respuestas)-1)):
# Centro
if (column > 0) and (column < (len(respuestas)-1)):
for i in range(row-1, row+1):
for j in range(column-1, column+2):
if respuestas[i][j] == "X":
n += 1
# Orilla iz
elif (column == 0):
for i in range(row-1, row+1):
for j in range(column, column+2):
if respuestas[i][j] == "X":
n += 1
# Orilla der
elif (column == (len(respuestas[1])-1)):
for i in range(row-1, row+1):
for j in range(column-1, column+1):
if respuestas[i][j] == "X":
n += 1
return n
print("Este es su tablero")
while True:
# Mostrar el tablero y el puntaje
print("Tu puntuaje actual es de: ", score, "\n")
for i in display:
for j in i:
print(j, end=" ")
print("\n")
for j in i:
print('_', end='___')
print("\n")
# Usuario ingresa nueva locación
fila = int(input("Ingrese la fila: "))
columna = int(input("Ingrese la columna: "))
# Pierde
if respuestas[fila-1][columna-1] == "X":
print("Te has equivocado, había una mina. \n")
print("Obtuviste una puntuación de: ", score)
webbrowser.open('https://www.youtube.com/watch?v=UzdLXlDAHGc',
new=1,
autoraise=True)
playsound('game_over.mp3')
break
# Gana
elif rondas == rondasParaGanar:
verificar = verificarAlrededor(fila-1, columna-1)
score += verificar
print("Felicidades haz ganado el juego: \n")
print("Obtuviste una puntuación de: ", score)
playsound('victory.mp3')
webbrowser.open('https://www.youtube.com/watch?v=KXw8CRapg7k',
new=1,
autoraise=True)
break
# Sigue jugando
else:
verificar = verificarAlrededor(fila-1, columna-1)
display[fila-1].insert(columna-1, " " + str(verificar) + " ")
display[fila-1].pop(columna)
score += verificar
rondas += 1
| 192f17f703b58ad8e672377acf57f0727eac68a2 | [
"Markdown",
"Python"
] | 2 | Markdown | CesarJimenezVilleda02/Semana_Tec_AD21 | bc12db1aca1a661ba3c377dac81f3a912f7dbb17 | 43715848af29af078411e6654c36f9aa93347bb9 |
refs/heads/master | <file_sep>//
// main.cpp
// 运算符重载
//
// Created by 董依萌 on 2017/3/20.
// Copyright © 2017年 董依萌. All rights reserved.
//
#include <iostream>
using namespace std;
class time1{
int h_;
int m_;
public:
time1();
time1(int h, int m); //const 不能改变t的值
time1 operator+(const time1 & t)const;
time1 operator*(int n)const;
// 不是成员函数 不能用 const 修饰词
// 函数的第一个参数 不是类的对象 就要使用友元函数
// c=a+b == c=a.operator(b) 隐式调用a,显式调用b
// c=a+b 左侧的操作数是调用对象
// 所以 d=2*c 就要用友元函数解决
friend time1 operator*(int n,const time1 & t);
friend ostream & operator <<(ostream & os,const time1 & t);
void show();
};
time1::time1(){
h_=0;
m_=0;
}
time1::time1(int h,int m){
h_=h;
m_=m;
}
time1 time1::operator+(const time1 & t)const{
time1 sum;
sum.m_=m_+t.m_;
sum.h_=h_+t.h_+sum.m_/60;
sum.m_%=60;
return sum;
}
time1 time1::operator*(int n)const {
time1 t1;
int totle1=h_*n*60+m_*n;
t1.h_=totle1/60;
t1.m_=totle1%60;
return t1;
}
time1 operator*(int n,const time1 & t){
return t*n;
}
ostream & operator<<(ostream & os,const time1 & t){
os<<t.h_<<" <hours "<<t.m_<<" <minutes"<<endl;
return os;
}
void time1::show(){
cout<<h_<<" hours "<<m_<<" minutes"<<endl;
}
int main() {
time1 a(1,44);
time1 b(5,56);
time1 ab=a+b; //在a对象里 执行+ b
ab.show();
time1 c(2,40);
c.show();
int n=2;
time1 d=c*n; // d=n*c和前面不一样
d.show();
cout<<a<<b<<c<<d; // 输出<< 的重载
return 0;
}
| bc8bbb16f98d9c0b10821adc0e86b3d8dcd0c97f | [
"C++"
] | 1 | C++ | 2016ameng/sum | d570b7d377e58bafdd878e46526535c675c6ea41 | e2c65ddc8cf400b166733aac23175f73c211992a |
refs/heads/master | <repo_name>lmcbout/test<file_sep>/gerrit-query/src/node/git-server.ts
/*
* Copyright (C) 2018 Ericsson and others.
*
* 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
*/
import { injectable, inject } from "inversify";
import { QueryGitServer } from '../common';
import { Deferred } from "@theia/core/lib/common/promise-util";
import { GerritClientContribution } from "./GerritCliContribution";
import { ILogger } from "@theia/core";
const request = require('request');
const exec = require('child_process').exec;
// const querySite = `https://git.eclipse.org/r/projects/?b=master`;
// const querySite = `https://gitlab.com/api/v4/projects`; // gitlab
// Query projects string
const gerritProjectQuery = `projects/?b=master`;
const gitLabProjectQuery = `/api/v4/projects`;
const gitClone = `git clone `;
@injectable()
export class GitServerNode implements QueryGitServer {
@inject(GerritClientContribution)
protected readonly cliParams!: GerritClientContribution;
@inject(ILogger)
protected readonly logger!: ILogger;
protected workspaceRootUri: string | undefined = undefined;
gitLabMap = new Map();
getProject(): Promise<string | undefined> {
return this.searchForProject();
}
cloneProject(projectName: string, workspaceRoot: string): Promise<string> {
return this.cloneSelectedProject(projectName, workspaceRoot);
}
protected async searchForProject(): Promise<string> {
const deferred = new Deferred<any>();
const self = this;
const isGitlab = self.cliParams.isGitLabProject();
let querySite = `${this.cliParams.getServer()}`;
if (querySite) {
if (!querySite.toString().endsWith('/')) {
querySite = `${querySite}/${gerritProjectQuery}`;
} else {
querySite = `${querySite}${gerritProjectQuery}`;
}
}
if (isGitlab) {
this.logger.info(" Handling a GITLAB project");
querySite = `${this.cliParams.getServer()}${gitLabProjectQuery}`;
}
this.logger.info(" Query site for projects: " + querySite);
request(querySite, function (error: Error, response: any, body: any) {
let arrayProject: string[] = new Array();
if (error) {
self.logger.error('Request error: ' + error); // Print the error if one occurred
return;
}
self.logger.info('Search for Project request server side statusCode:', response && response.statusCode); // Print the response status code if a response was received
const JSON_NON_EXECUTABLE_PREFIX = ")]}'\n"; // When using Gerrit on Eclipse
// Adjust the body string to fit the JSON format
let stripBody = body;
if (body.toString().lastIndexOf(JSON_NON_EXECUTABLE_PREFIX) > -1) {
stripBody = body.substring(JSON_NON_EXECUTABLE_PREFIX.length);
}
// Verify is we use a Git Lab repo
if (isGitlab) {
const index = body.toString().indexOf('[');
const lastIndex = body.lastIndexOf("]");
stripBody = body.slice(index, lastIndex + 1);
}
self.logger.debug("Message body received: " + stripBody); // Lower debug level
let json = JSON.parse(stripBody);
// With the GitLab parser, read the value OF JSON and keep the repo url provided
if (isGitlab) {
for (const property of json) {
arrayProject.push(`${property.name}`);
self.gitLabMap.set(`${property.name}`, `${property.http_url_to_repo}`);
}
} else {
// JSON structure for Gerrit not in GitLab
for (const property in json) {
self.logger.debug(`project:${property}\n id:${json[property].id}`); // Lower debug level
arrayProject.push(`${property}`);
}
}
deferred.resolve(arrayProject.toString());
});
const content = await deferred.promise;
return Promise.resolve(content);
}
protected async cloneSelectedProject(projectName: string, workspaceRoot: string): Promise<string> {
// Eclipse projects have often 2 parts defining the project i.e. egerrit/org.eclipse.egerrit
// When cloning manually, "git clone ..." will put the project in a folder defined in
// the second portion of the name, so I decided to take a siilar approach and when it is defined,
// I use the second section of the project, otherwise I create the project with the single name
const origin = projectName.split("/", 2);
const self = this;
// Put the first or second parameter of the project for the path
let testWorkspace = `${workspaceRoot}/${origin[0]}`;
if (origin[1]) {
testWorkspace = `${workspaceRoot}/${origin[1]}`;
}
let gitCommand = `${gitClone}${this.cliParams.getServer()}/${projectName}.git`;
const isGitlab = this.cliParams.isGitLabProject();
if (isGitlab) {
gitCommand = `${gitClone} ${this.gitLabMap.get(projectName)}`;
}
self.logger.info("clone selected project command: " + gitCommand);
const deferred = new Deferred<any>();
exec(`${gitCommand} ${testWorkspace}`, function (error: any, response: any, body: any) {
if (error) {
self.logger.error('server cloneSelectedProject() error: ' + error); // Print the error if one occurred
return;
}
self.logger.info('Clone selected project server side statusCode:', response && response.statusCode); // Print the response status code if a response was received
deferred.resolve(body);
});
const content = await deferred.promise;
return Promise.resolve(content);
}
}
| cb6835f19782f8b123b0010889e6b07d0e052611 | [
"TypeScript"
] | 1 | TypeScript | lmcbout/test | 4ab95ee6d7c07e2a7f4fe94d0075dd9177f7e921 | 82ca2c45384c86987d2a822d2ab4e808f0972d6c |
refs/heads/main | <file_sep>#include <iostream>
#include <random>
#include <math.h>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
wstring string_to_wstring(string str);
string wstring_to_string(wstring wstr);
// Initial Permutation Box before 16 round operation
int Initial_Permutation[64] = {58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7};
// Expand 32bit to 48bit (32bit of half left and half right 64bit block)
int Expansion_D_Box[48] = {32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1};
// substitution box for each round ( total 16 box for 16 round operation)
int Substitution_Box[8][4][16] = {{14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13},
{15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9},
{10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12},
{7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14},
{2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3},
{12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13},
{4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12},
{13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}};
// straight permutation box for 32 input and output 32 bit at last operation in Des function
int Straight_Permutaion_D_Box[32] = {16, 7, 20, 21,
29, 12, 28, 17,
1, 15, 23, 26,
5, 18, 31, 10,
2, 8, 24, 14,
32, 27, 3, 9,
19, 13, 30, 6,
22, 11, 4, 25};
// final permutation box apply after 16 rounds
int Final_Permutation[64] = {40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25};
// Key party drop table is used to drop 8 bit to get 56 bit from key 64 bit
int Key_Party_Drop_Table[56] = {57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4};
// shift table is number of shifts in each round key generations
int Shift_Table[16] = {1, 1, 2, 2,
2, 2, 2, 2,
1, 2, 2, 2,
2, 2, 2, 1};
// Key compression table is used to change the 58 bit key to 48 bit key
int Key_Compression_Table[48] = {14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32};
// Hex table is represent all character in hex format
string Hex_Table[16] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
// convert the decimal number to binary number
string Decimal_to_Bin(int d, int length)
{
string bin = "";
if (d != 0)
{
while (d > 0)
{
bin = char('0' + d % 2) + bin;
d /= 2;
}
}
while (bin.length() < length)
{
bin = "0" + bin;
}
return bin;
}
// convert the binary number to decimal number
int Bin_to_Decimal(string bin)
{
int d = 0;
for (int i = 0; i < bin.length(); i++)
{
d += pow(2, bin.length() - 1 - i) * (bin[i] - '0');
}
return d;
}
//Get the hexadecimal value is represent in char
int getHexValue(char c)
{
switch (c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return c - '0';
case 'A':
case 'a':
return 10;
case 'B':
case 'b':
return 11;
case 'C':
case 'c':
return 12;
case 'D':
case 'd':
return 13;
case 'E':
case 'e':
return 14;
case 'F':
case 'f':
return 15;
default:
return -1;
}
}
// Check all character in string is hexadecimal
bool Check_String_All_Hex(string str)
{
for (int i = 0; i < str.length(); i++)
{
if (getHexValue(str[i]) == -1)
{
return false;
}
}
return true;
}
// Convert Binary number to Hexadecimal number
string Bin_to_Hexadecimal(string Bin)
{
string Bin_output = "";
if (Bin.length() == 0)
{
return "0";
}
for (int i = 0; i < Bin.length() / 4; i++)
{
Bin_output += Hex_Table[Bin_to_Decimal(Bin.substr(i * 4, 4))];
}
return Bin_output;
}
// convert Hexadecimal number to binary
string Hexadecimal_to_Bin(string Hex)
{
string Hex_ouput = "";
for (int i = 0; i < Hex.length(); i++)
{
Hex_ouput += Decimal_to_Bin(getHexValue(Hex[i]), 4);
}
return Hex_ouput;
}
// convert ASCII (text) to hexadecimal number
string ASCII_to_Hexadecimal(string text)
{
string bin = "";
for (unsigned char c : text)
{
bin += Decimal_to_Bin(c, 8);
}
return Bin_to_Hexadecimal(bin);
}
// Convert hexadecimal number to ASCII(text)
string Hexadecimal_to_ASCII(string Hex)
{
string Bin = Hexadecimal_to_Bin(Hex);
string ASCII = "";
for (long long i = 0; i < Bin.length() / 8; i++)
{
ASCII += (unsigned char)Bin_to_Decimal(Bin.substr(i * 8, 8));
}
return ASCII;
}
// permuataion operation with specifying table
// map the permutation box to the string
string Permute(string str, int *table, int n)
{
string permute = "";
for (int i = 0; i < n; i++)
{
permute += str[table[i] - 1];
}
return permute;
}
// shift string left to n_shifts bits
string Shift_Left(string str, int n_shifts)
{
string sh_left = "";
for (int i = 0; i < n_shifts; i++)
{
for (int j = 1; j < 28; j++)
{
sh_left += str[j];
}
sh_left += str[0];
str = sh_left;
sh_left = "";
}
return str;
}
// compute the bitwise xor str1 with str2
string Xor(string str1, string str2)
{
string result = "";
for (int i = 0; i < str1.length(); i++)
{
result += (char)(((str1[i] - '0') ^ (str2[i] - '0')) + '0');
}
return result;
}
// caculate the row value from bit 0 and bit 5 (in S-Box operation)
int Calculate_Row(string str)
{
return 2 * (str[0] - '0') + (str[5] - '0');
}
// caculate the column value from bit 1 to bit 4 (in S-Box operation)
int Calculate_Column(string str)
{
int result = 0;
for (int i = 1; i < 5; i++)
{
result += pow(2, 4 - i) * (str[i] - '0');
}
return result;
}
// Swap tow string
void Swap(string &str1, string &str2)
{
string temp = str1;
str1 = str2;
str2 = temp;
}
// DES operation can use either Encryption or Decryption operation
string Encrypt_Decrypt_64bit(string _text_64_bit, vector<string> round_key)
{
// Initial Permutation
_text_64_bit = Permute(_text_64_bit, Initial_Permutation, 64);
// split 64 bit to 32bit left and 32 bit right
string left = _text_64_bit.substr(0, 32);
string right = _text_64_bit.substr(32, 32);
for (int i = 0; i < 16; i++)
{
// Expand the 32bit right to 48 bit
string right_expanded = Permute(right, Expansion_D_Box, 48);
//xor round key with right_expanded
string xor_right = Xor(round_key[i], right_expanded);
// S boxes
string output = "";
// 8 S-boxes
for (int i = 0; i < 8; i++)
{
// caculate row and column then map to the Substitution Box
int row = Calculate_Row(xor_right.substr(i * 6, 6));
int column = Calculate_Column(xor_right.substr(i * 6, 6));
int math_S_table = Substitution_Box[i][row][column];
// the ouput is convert to binary format
output += Decimal_to_Bin(math_S_table, 4);
}
// straight Permutation D Box (32 bit input to 32 bit output)
output = Permute(output, Straight_Permutaion_D_Box, 32);
// Xor 32 bit left and output
string left_xor = Xor(output, left);
left = left_xor;
// swap the left and right at the last operation except the final round(round 16)
if (i != 15)
{
swap(left, right);
}
}
// merger left and right string
string merger = left + right;
// Final Permutaition
string cipher = Permute(merger, Final_Permutation, 64);
return Bin_to_Hexadecimal(cipher);
}
// Generate random hexadecimal key with length 16
string GenerateKey()
{
string key = "";
for (int i = 0; i < 16; i++)
{
key += Hex_Table[rand() % 16];
}
return key;
}
// Caculate the round key from input key
vector<string> Generate_Round_Key(string key)
{
vector<string> round_key;
// Get 56 bit key from 64 bit key input by maping Key_Party_Drop_table
key = Permute(key, Key_Party_Drop_Table, 56);
// split key to 28bit left and 28bit right
string left = key.substr(0, 28);
string right = key.substr(28, 28);
// caculate key for 16 round
for (int i = 0; i < 16; i++)
{
// shift left key follow the Shift_Table
left = Shift_Left(left, Shift_Table[i]);
right = Shift_Left(right, Shift_Table[i]);
// merger left and right
string merger = left + right;
// Compress key from 56 bit to 48 bit key
string roundkey = Permute(merger, Key_Compression_Table, 48);
round_key.push_back(roundkey);
}
return round_key;
}
class DES
{
private:
string key;
string iv;
public:
// Default constructor
DES()
{
// initial random seed
srand(time(NULL));
key = "";
iv = "";
}
// Constructor
DES(string key_input, string iv_input)
{
// initial random seed
srand(time(NULL));
Key_setter(key_input);
Iv_setter(iv_input);
}
// Destructor
~DES()
{
}
// Set the value for key
bool Key_setter(string key_set)
{
if (key_set.length() != 16 || !Check_String_All_Hex(key_set))
{
wcout << "key set is invalid!" << endl;
return false;
}
key = key_set;
return true;
}
// Get the key value
string Key_getter()
{
return key;
}
//Set the iv value for key
bool Iv_setter(string iv_set)
{
if (iv_set.length() != 16 || !Check_String_All_Hex(iv_set))
{
wcout << "iv set is invalid!" << endl;
return false;
}
iv = iv_set;
return true;
}
string Iv_getter()
{
return iv;
}
//random the key
void Auto_Generate_Key()
{
Key_setter(GenerateKey());
}
void Auto_Generate_IV()
{
Iv_setter(GenerateKey());
}
// Encyption operation
string Encrypt(string plaintext)
{
// check key is valid
if (key == "" || key.length() != 16)
{
wcout << "key is invalid!" << endl;
exit(EXIT_FAILURE);
}
//check iv is valid
if (iv == "" || iv.length() != 16)
{
wcout << "iv is invalid!" << endl;
exit(EXIT_FAILURE);
}
// get length plaintext
long long len_plaintext = plaintext.length();
// padding null at the end with plaintext is divisible for 64 bit block size
// Note: plaintext in ASCII format so has 8bit length for each character
while ((len_plaintext * 8) % 64 != 0)
{
//padding null at the end
plaintext = plaintext + char(0);
len_plaintext = plaintext.length();
}
// convert plaintext to Hexadecimal format
plaintext = ASCII_to_Hexadecimal(plaintext);
string ciphertext = "";
// Convert plaintext to Binary format
plaintext = Hexadecimal_to_Bin(plaintext);
wcout << "bin: " << string_to_wstring(plaintext) << endl;
// compute the round key and stored in round_key
vector<string> round_key = Generate_Round_Key(Hexadecimal_to_Bin(key));
// reserved initial vector
string iv_round = Hexadecimal_to_Bin(iv);
//split the plain text into each 64bit block then encrypt
for (long long i = 0; i < plaintext.length() / 64; i++)
{
string _text_64_bit = plaintext.substr(i * 64, 64);
_text_64_bit = Xor(_text_64_bit, iv_round);
// encrypt 64 bit and concatenate to the ciphertext
string _64_bit_ciphertext;
_64_bit_ciphertext = Encrypt_Decrypt_64bit(_text_64_bit, round_key);
ciphertext += _64_bit_ciphertext;
iv_round = Hexadecimal_to_Bin(_64_bit_ciphertext);
}
return ciphertext;
}
string Decrypt(string ciphertext)
{
string recovered_plaintext = "";
// convert the Hexadecimal to binary format
ciphertext = Hexadecimal_to_Bin(ciphertext);
// compute the round_key from specific key
vector<string> round_key = Generate_Round_Key(Hexadecimal_to_Bin(key));
// Reverse round_key for decrypt operation
reverse(round_key.begin(), round_key.end());
string iv_round = Hexadecimal_to_Bin(iv);
// split ciphertext into 64bit block then decrypt
for (long long i = 0; i < ciphertext.length() / 64; i++)
{
string plaintext_64_bit = ciphertext.substr(i * 64, 64);
// decrypt 64 bit and concatenate to the recoverd_plaintext
string _64_bit_recovered = Hexadecimal_to_Bin(Encrypt_Decrypt_64bit(plaintext_64_bit, round_key));
recovered_plaintext += Bin_to_Hexadecimal(Xor(iv_round, _64_bit_recovered));
iv_round = plaintext_64_bit;
}
return recovered_plaintext;
}
};
<file_sep>// g++ -g3 -ggdb -O0 -DDEBUG -I/usr/include/cryptopp Driver.cpp -o Driver.exe -lcryptopp -lpthread
// g++ -g -O2 -DNDEBUG -I/usr/include/cryptopp Driver.cpp -o Driver.exe -lcryptopp -lpthread
#include "cryptopp/osrng.h"
using CryptoPP::AutoSeededRandomPool;
#include <ctime>
#include <iomanip>
#include <iostream>
// library for unicode in C++
/* Vietnamese support */
/* Set _setmode()*/
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#else
#endif
#include <string>
#include <locale>
#include <codecvt>
using std::cerr;
using std::endl;
using std::wcin;
using std::wcout;
#include <string>
using std::string;
#include <cstdlib>
using std::exit;
#include "cryptopp/cryptlib.h"
using CryptoPP::Exception;
#include "cryptopp/hex.h"
using CryptoPP::HexDecoder;
using CryptoPP::HexEncoder;
#include "cryptopp/filters.h"
using CryptoPP::Redirector;
using CryptoPP::StreamTransformationFilter;
using CryptoPP::StringSink;
#include <cryptopp/files.h>
using CryptoPP::BufferedTransformation;
using CryptoPP::FileSink;
using CryptoPP::FileSource;
using CryptoPP::FileSource;
using CryptoPP::StringSource;
#include "cryptopp/des.h"
using CryptoPP::DES;
#include "cryptopp/modes.h"
using CryptoPP::CBC_CTS_Mode; //done
using CryptoPP::CBC_Mode; // done
using CryptoPP::CFB_Mode; //done
using CryptoPP::CTR_Mode; //done
using CryptoPP::ECB_Mode; // done
using CryptoPP::OFB_Mode; //done
#include "cryptopp/secblock.h"
using CryptoPP::byte;
using CryptoPP::SecByteBlock;
// CBC encrypt
double CBC_DES_Encrypt(string plain, byte *iv, SecByteBlock key, string &cipher)
{
// executation time of each Encryption operation
int start_s = clock();
double etime = 0;
// try catch exception during operation
try
{
// encrytion DES with CBC mode
CBC_Mode<DES>::Encryption e;
// set key for DES encryption scheme
e.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter adds default padding ( without argument specified)
// as required. ECB and CBC Mode must be padded
// to the block size of the cipher.
// stream StreamTransformationFilter
//pipepline the plaintext to the DES scheme (e) through StreamTransformationFilter and output to cipher string
StringSource(plain, true,
new StreamTransformationFilter(e,
new StringSink(cipher)) // StreamTransformationFilter
); // StringSource
// time done for encryption operation
int stop_s = clock();
// compute the operating execution from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// CBC decrypt
double CBC_DES_Decrypt(string cipher, byte *iv, SecByteBlock key, string &recovered)
{
int start_s = clock();
// execution time of DES decryption operation
double etime = 0;
// catch any exception during operation
try
{
// initiate DES decryption with mode CBC
CBC_Mode<DES>::Decryption d;
// set key for operation
d.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter removes
// padding as required.
// pipeline the cipher to Des Decryption scheme (d) through StreamTransformationFilter and output to recoverd string
StringSource s(cipher, true,
new StreamTransformationFilter(d,
new StringSink(recovered)) // StreamTransformationFilter
);
// time done for decryption operation // StringSource
int stop_s = clock();
// compute time for operating execution time from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// EBC encrypt
double ECB_DES_Encrypt(string plain, SecByteBlock key, string &cipher)
{
int start_s = clock();
// executation time of each Encryption operation
double etime = 0;
// try catch exception during operation
try
{
// encrytion DES with ECB mode
ECB_Mode<DES>::Encryption e;
// set key for DES encryption scheme
e.SetKey(key, key.size());
// The StreamTransformationFilter adds default padding ( without argument specified)
// as required. ECB and CBC Mode must be padded
// to the block size of the cipher.
// stream StreamTransformationFilter
//pipepline the plaintext to the DES scheme (e) through StreamTransformationFilter and output to cipher string
StringSource(plain, true,
new StreamTransformationFilter(e,
new StringSink(cipher)) // StreamTransformationFilter
); // StringSource
// time done for encryption operation
int stop_s = clock();
// compute the operating execution from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// EBC decrypt
double ECB_DES_Decrypt(string cipher, SecByteBlock key, string &recovered)
{
int start_s = clock();
// execution time of DES decryption operation
double etime = 0;
// catch any exception during operation
try
{
// initiate DES decryption with mode ECB
ECB_Mode<DES>::Decryption d;
// set key for operation
d.SetKey(key, key.size());
// The StreamTransformationFilter removes
// padding as required.
// pipeline the cipher to Des Decryption scheme (d) through StreamTransformationFilter and output to recoverd string
StringSource s(cipher, true,
new StreamTransformationFilter(d,
new StringSink(recovered)) // StreamTransformationFilter
);
// time done for decryption operation // StringSource
int stop_s = clock();
// compute time for operating execution time from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// CBC-CTS encrypt
double CBC_CTS_DES_Encrypt(string plain, byte *iv, SecByteBlock key, string &cipher)
{
int start_s = clock();
// executation time of each Encryption operation
double etime = 0;
// try catch exception during operation
try
{
// encrytion DES with CBC-CTS mode
CBC_CTS_Mode<DES>::Encryption e;
// set key for DES encryption scheme
e.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter adds default padding ( without argument specified)
// as required. ECB and CBC Mode must be padded
// to the block size of the cipher.
// stream StreamTransformationFilter
//pipepline the plaintext to the DES scheme (e) through StreamTransformationFilter and output to cipher string
StringSource(plain, true,
new StreamTransformationFilter(e,
new StringSink(cipher)) // StreamTransformationFilter
); // StringSource
// time done for encryption operation
int stop_s = clock();
// compute the operating execution from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// CBC-CTS decrypt
double CBC_CTS_DES_Decrypt(string cipher, byte *iv, SecByteBlock key, string &recovered)
{
int start_s = clock();
// execution time of DES decryption operation
double etime = 0;
// catch any exception during operation
try
{
// initiate DES decryption with mode CBC-CTS
CBC_CTS_Mode<DES>::Decryption d;
// set key for operation
d.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter removes
// padding as required.
// pipeline the cipher to Des Decryption scheme (d) through StreamTransformationFilter and output to recoverd string
StringSource s(cipher, true,
new StreamTransformationFilter(d,
new StringSink(recovered)) // StreamTransformationFilter
);
// time done for decryption operation // StringSource
int stop_s = clock();
// compute time for operating execution time from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// CFB encrypt
double CFB_DES_Encrypt(string plain, byte *iv, SecByteBlock key, string &cipher)
{
int start_s = clock();
// executation time of each Encryption operation
double etime = 0;
// try catch exception during operation
try
{
// encrytion DES with CFB mode
CFB_Mode<DES>::Encryption e;
// set key for DES encryption scheme
e.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter adds default padding ( without argument specified)
// as required. ECB and CBC Mode must be padded
// to the block size of the cipher.
// stream StreamTransformationFilter
//pipepline the plaintext to the DES scheme (e) through StreamTransformationFilter and output to cipher string
StringSource(plain, true,
new StreamTransformationFilter(e,
new StringSink(cipher)) // StreamTransformationFilter
); // StringSource
// time done for encryption operation
int stop_s = clock();
// compute the operating execution from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// CFB decrypt
double CFB_DES_Decrypt(string cipher, byte *iv, SecByteBlock key, string &recovered)
{
int start_s = clock();
// execution time of DES decryption operation
double etime = 0;
// catch any exception during operation
try
{
// initiate DES decryption with mode CFB
CFB_Mode<DES>::Decryption d;
// set key for operation
d.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter removes
// padding as required.
// pipeline the cipher to Des Decryption scheme (d) through StreamTransformationFilter and output to recoverd string
StringSource s(cipher, true,
new StreamTransformationFilter(d,
new StringSink(recovered)) // StreamTransformationFilter
);
// time done for decryption operation // StringSource
int stop_s = clock();
// compute time for operating execution time from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// CTR encrypt
double CTR_DES_Encrypt(string plain, byte *iv, SecByteBlock key, string &cipher)
{
int start_s = clock();
// executation time of each Encryption operation
double etime = 0;
// try catch exception during operation
try
{
// encrytion DES with CTR mode
CTR_Mode<DES>::Encryption e;
// set key for DES encryption scheme
e.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter adds default padding ( without argument specified)
// as required. ECB and CBC Mode must be padded
// to the block size of the cipher.
// stream StreamTransformationFilter
//pipepline the plaintext to the DES scheme (e) through StreamTransformationFilter and output to cipher string
StringSource(plain, true,
new StreamTransformationFilter(e,
new StringSink(cipher)) // StreamTransformationFilter
); // StringSource
// time done for encryption operation
int stop_s = clock();
// compute the operating execution from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// CTR decrypt
double CTR_DES_Decrypt(string cipher, byte *iv, SecByteBlock key, string &recovered)
{
int start_s = clock();
// execution time of DES decryption operation
double etime = 0;
// catch any exception during operation
try
{
// initiate DES decryption with mode CTR
CTR_Mode<DES>::Decryption d;
// set key for operation
d.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter removes
// padding as required.
// pipeline the cipher to Des Decryption scheme (d) through StreamTransformationFilter and output to recoverd string
StringSource s(cipher, true,
new StreamTransformationFilter(d,
new StringSink(recovered)) // StreamTransformationFilter
);
// time done for decryption operation // StringSource
int stop_s = clock();
// compute time for operating execution time from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// OFB encrypt
double OFB_DES_Encrypt(string plain, byte *iv, SecByteBlock key, string &cipher)
{
int start_s = clock();
// executation time of each Encryption operation
double etime = 0;
// try catch exception during operation
try
{
// encrytion DES with OFB mode
OFB_Mode<DES>::Encryption e;
// set key for DES encryption scheme
e.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter adds default padding ( without argument specified)
// as required. ECB and CBC Mode must be padded
// to the block size of the cipher.
// stream StreamTransformationFilter
//pipepline the plaintext to the DES scheme (e) through StreamTransformationFilter and output to cipher string
StringSource(plain, true,
new StreamTransformationFilter(e,
new StringSink(cipher)) // StreamTransformationFilter
); // StringSource
// time done for encryption operation
int stop_s = clock();
// compute the operating execution from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// OFB decrypt
double OFB_DES_Decrypt(string cipher, byte *iv, SecByteBlock key, string &recovered)
{
int start_s = clock();
// execution time of DES decryption operation
double etime = 0;
// catch any exception during operation
try
{
// initiate DES decryption with mode OFB
OFB_Mode<DES>::Decryption d;
// set key for operation
d.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter removes
// padding as required.
// pipeline the cipher to Des Decryption scheme (d) through StreamTransformationFilter and output to recoverd string
StringSource s(cipher, true,
new StreamTransformationFilter(d,
new StringSink(recovered)) // StreamTransformationFilter
);
// time done for decryption operation // StringSource
int stop_s = clock();
// compute time for operating execution time from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// show the result out screen (console)
void show_result(SecByteBlock key, byte *iv, int iv_length, string ciphertext, string recovered, double total_time_encrypt, double total_time_decrypt, string mode)
{
string encoded;
// clear encoded
encoded.clear();
// convert key to hex format and save to encoded string
StringSource(key, key.size(), true,
new HexEncoder(
new StringSink(encoded)) // HexEncoder
);
// StringSource
// show key in hex format
wcout << "Key: " << encoded.c_str() << endl;
if (mode != "ECB")
{
// convert iv to hex format and save to encoded string
encoded.clear();
StringSource(iv, iv_length, true,
new HexEncoder(
new StringSink(encoded)) // HexEncoder
);
// show iv in hex format
// StringSource
wcout << "iv: " << encoded.c_str() << endl;
}
// clear encoded
encoded.clear();
// convert ciphertext to hex format and save to encoded string
StringSource(ciphertext, true,
new HexEncoder(
new StringSink(encoded)) // HexEncoder
); // StringSource
// show cipher text in hex format
wcout << "Cipher text: " << encoded.c_str() << endl;
double ex_time_encrypt = total_time_encrypt / 10000; // Average execution time of 10.000 encryption running
// compute the average time of each decryption
double ex_time_decrypt = total_time_decrypt / 10000; // Average execution time of 10.000 decryption running
// compute the average time of each encryption
// show result to console screen
wcout << "Total execution time for 10.000 rounds: \t"
<< "encrypt: " << total_time_encrypt << "ms\t decrypt: " << total_time_decrypt << "ms" << endl;
// setw(41) to format output
wcout << std::setw(41) << std::left << "Execution time: \t"
<< "encrypt: " << ex_time_encrypt << "ms\tdecrypt: " << ex_time_decrypt << "ms" << endl;
// show decode message
// show decode message and convert to utf16
std::wstring str = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(recovered);
wcout << "Recoverd text: " << str << endl;
}
double Estimation_En_De_cypt_Operation(string &plain, byte *iv, SecByteBlock key, string &cipher, int mode, bool is_decryption, int loop)
{
double total_time = 0;
while (loop--)
{
// Compute total time for encryption
switch (mode)
{
case 1:
// ECB mode
if (!is_decryption)
{
total_time += ECB_DES_Encrypt(plain, key, cipher);
}
else
{
total_time += ECB_DES_Decrypt(cipher, key, plain);
}
break;
case 2:
// CBC mode
if (!is_decryption)
{
total_time += CBC_DES_Encrypt(plain, iv, key, cipher);
}
else
{
total_time += CBC_DES_Decrypt(cipher, iv, key, plain);
}
break;
case 3:
// CBC CTS mode
if (!is_decryption)
{
total_time += CBC_CTS_DES_Encrypt(plain, iv, key, cipher);
}
else
{
total_time += CBC_CTS_DES_Decrypt(cipher, iv, key, plain);
}
break;
case 4:
// CFB mode
if (!is_decryption)
{
total_time += CFB_DES_Encrypt(plain, iv, key, cipher);
}
else
{
total_time += CFB_DES_Decrypt(cipher, iv, key, plain);
}
break;
case 5:
// CTR mode
if (!is_decryption)
{
total_time += CTR_DES_Encrypt(plain, iv, key, cipher);
}
else
{
total_time += CTR_DES_Decrypt(cipher, iv, key, plain);
}
break;
case 6:
// OFB mode
if (!is_decryption)
{
total_time += OFB_DES_Encrypt(plain, iv, key, cipher);
}
else
{
total_time += OFB_DES_Decrypt(cipher, iv, key, plain);
}
break;
default:
break;
}
// save the ciphertext to show for the last loop
if (loop == 0)
{
break;
}
if (!is_decryption)
{
cipher.clear();
}
else
{
plain.clear();
}
}
return total_time;
}
SecByteBlock input_key_from_keyboard()
{
std::wstring key_input;
string input = "";
do
{
wcout << "Input key: ";
// flush all buffet before getline
fflush(stdin);
std::getline(wcin, key_input);
// convert wstring (utf8) to string (asciij)
input = std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(key_input);
if (input.length() != 8)
{
// repeat input until get correct key
wcout << "Wrong key length input. Key length must be 8 bytes!\n";
}
else
{
break;
}
} while (1);
SecByteBlock key(DES::DEFAULT_KEYLENGTH);
// convert ASCII to byte and store in key
for (int i = 0; i < DES::DEFAULT_KEYLENGTH; i++)
{
key[i] = (unsigned int)input[i];
}
return key;
}
// input bytes key
SecByteBlock key_selection()
{
SecByteBlock key(DES::DEFAULT_KEYLENGTH);
int option_input_key = 0;
do
{
wcout << endl;
wcout << "[+] Key selection:\n";
wcout << "1 - input key from keyboard\n";
wcout << "2 - input key from file\n";
wcout << "3 - generate a ramdom key\n";
wcout << "Enter option: ";
wcin >> option_input_key;
if (option_input_key >= 1 && option_input_key <= 3)
{
break;
}
else
{
// repeat until get correct input option
wcout << "Wrong input.\n";
}
} while (1);
switch (option_input_key)
{
case 1:
{
key = input_key_from_keyboard();
break;
}
case 2:
{
// reading key from file
try
{
FileSource fs("DES_key.key", false);
// create space for key
CryptoPP::ArraySink copykey(key, key.size());
//copy data from DES_key.key to key
fs.Detach(new Redirector(copykey));
fs.Pump(DES::DEFAULT_KEYLENGTH);
}
catch (CryptoPP::Exception e)
{
string error = e.GetWhat();
// print out exception when not found key file
std::wstring str = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(error);
wcout << str << endl;
exit(0);
}
break;
}
case 3:
{
AutoSeededRandomPool prng;
// generate a random bytes key
prng.GenerateBlock(key, DES::DEFAULT_KEYLENGTH);
break;
}
}
if (option_input_key != 2)
{
// save the key to file
StringSource ss(key, key.size(), true, new FileSink("DES_key.key"));
wcout << "Key has been save to DES_key.key" << endl;
}
return key;
}
// enter iv from key board
byte *input_iv_from_keyboard()
{
std::wstring iv_input;
string input = "";
do
{
wcout << "Input iv: ";
// flush all buffer before getline
fflush(stdin);
std::getline(wcin, iv_input);
// convert wstring(utf8) to string (ascii)
input = std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(iv_input);
if (input.length() != DES::BLOCKSIZE)
{
wcout << "Wrong iv length input. iv length must be 8 bytes!\n";
}
else
{
break;
}
} while (1);
byte *iv = new byte[DES::BLOCKSIZE];
// convert ascii input to byte then store in iv
for (int i = 0; i < DES::BLOCKSIZE; i++)
{
iv[i] = (unsigned int)input[i];
}
return iv;
}
// iv selection
byte *iv_selection()
{
byte *iv;
int option_input_iv = 0;
do
{
wcout << endl;
wcout << "[+] IV selection:\n";
wcout << "1 - input iv from keyboard\n";
wcout << "2 - input iv from file\n";
wcout << "3 - generate a ramdom iv\n";
wcout << "Enter option: ";
wcin >> option_input_iv;
if (option_input_iv >= 1 && option_input_iv <= 3)
{
break;
}
else
{
// repeat input until get correct option
wcout << "Wrong input.\n";
}
} while (1);
switch (option_input_iv)
{
case 1:
{
iv = input_iv_from_keyboard();
break;
}
case 2:
{
// reading key from file
try
{
iv = new byte[DES::BLOCKSIZE];
FileSource fs("DES_iv.iv", false);
// create space for key
CryptoPP::ArraySink copykey(iv, DES::BLOCKSIZE);
//copy data from DES_key.key to key
fs.Detach(new Redirector(copykey));
fs.Pump(DES::DEFAULT_KEYLENGTH);
}
catch (CryptoPP::Exception e)
{
string error = e.GetWhat();
// print out exception and exit
std::wstring str = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(error);
wcout << str << endl;
exit(0);
}
break;
}
case 3:
{
iv = new byte[DES::KEYLENGTH];
AutoSeededRandomPool prng;
// generate random bytes key
prng.GenerateBlock(iv, DES::DEFAULT_KEYLENGTH);
break;
}
}
if (option_input_iv != 2)
{
// store key to file
StringSource ss(iv, DES::BLOCKSIZE, true, new FileSink("DES_iv.iv"));
wcout << "iv has been saved to DES_iv.iv" << endl;
}
return iv;
}
int main(int argc, char *argv[])
{
/*Set mode support Vietnamese*/
#ifdef __linux__
setlocale(LC_ALL, "");
#elif _WIN32
_setmode(_fileno(stdin), _O_U16TEXT);
_setmode(_fileno(stdout), _O_U16TEXT);
#else
#endif
// set default plaintext
std::wstring wplaintext = L"Welcome to the DES encryption and decryption!";
wcout << "[+] Enter plaintext: ";
std::getline(wcin, wplaintext);
// random byte
AutoSeededRandomPool prng;
// key initiattion
SecByteBlock key(DES::DEFAULT_KEYLENGTH);
byte *iv;
int mode_option = 0;
// Select operation mode
do
{
wcout << endl;
wcout << "[+] Select operation mode: \n";
wcout << "1 - EBC mode\n";
wcout << "2 - CBC mode\n";
wcout << "3 - CBC CTS mode\n";
wcout << "4 - CFB mode\n";
wcout << "5 - CTR mode\n";
wcout << "6 - OFB mode\n";
wcout << "Enter selection (1-6): ";
wcin >> mode_option;
if (mode_option < 1 || mode_option > 6)
{
wcout << "Input wrong options!\n";
}
else
{
break;
}
} while (1);
key = key_selection();
// not set iv for ECB mode
if (mode_option != 1)
{
iv = iv_selection();
}
else
{
iv = NULL;
}
// convert input in utf16 to string
string plaintext = std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(wplaintext);
// initiate ciphertext, encoded for key in hex format, recoverd is decryption message in hex format
string ciphertext, recovered;
// initiate for time variable
// Total time for 10.000 encryption running
double total_time_encrypt = 0;
// Total time for 10.000 decryption running
double total_time_decrypt = 0;
// initiate start time
// loop for 10.000 operation
int loop = 10000;
total_time_encrypt = Estimation_En_De_cypt_Operation(plaintext, iv, key, ciphertext, mode_option, 0, loop);
total_time_decrypt = Estimation_En_De_cypt_Operation(recovered, iv, key, ciphertext, mode_option, 1, loop);
string mode_str[] = {"ECB", "CBC", "CBC CTS", "CFB", "CTR", "OFB"};
wcout << endl;
wcout << "[+] Estimation result" << endl;
show_result(key, iv, DES::BLOCKSIZE, ciphertext, recovered, total_time_encrypt, total_time_decrypt, mode_str[mode_option - 1]);
return 0;
}
<file_sep># Performance
## Hardware resources
Processor: Intel(R) Core(TM) i7-4720HQ CPU @ 2.60GHz, 2594 Mhz, 4 Core(s), 8 Logical Processor(s)
Installed Physical Memory (RAM): 8.00 GB
Total Physical Memory: 7.89 GB
## Perfomance windows 10 64 bit
OS Name Microsoft Windows 10 Home Single Language
Version 10.0.19042 Build 19042
## Thống kê (10000 vòng lặp)
| Scheme | Operation Mode | Key Length | Iv Length | Total Encryption Time ms (Windows) | Total Decryption Time ms (Windows) | Total Encryption Time ms (Linux) |Total Decryption Time ms (Linux) |
| ------ | -------------- | ---------- | ---------- | --------------------- | ----------------------- | -------------------- | ---------------------- |
| DES | CBC |64 |64 |123 |96 |107.87 |100.685 |
| DES | EBC | 64| 64| 114|105 |120.28 |102.772|
| DES | CBC CTS |64 | 64|131 |101 |118.048|101.909 |
| DES | CFB | 64|64 | 131|101 | 113.388|103.101 |
| DES | CTR |64 | 64| 124|112 | 150.037|109.551 |
| DES | OFB | 64| 64| 122|107 |113.256 |105.076 |
| AES | CBC |128 |128 |38 |21 | 19.176|17.777 |
| AES | CBC | 192|128 | 40|22 |43.897 |17.031 |
| AES | CBC | 256| 128| 38|29 | 24.551|17.843|
| AES | EBC | 128| n.a| 27|18 | 34.504|19.391 |
| AES | EBC | 192| n.a|29 | 16| 33.975|18.589 |
| AES | EBC | 256| n.a| 35|19 |29.083 |18.93 |
| AES | CBC CTS|128 | 128| 37|23 |32.654 |19.135 |
| AES | CBC CTS|192 | 128|38 |23 | 27.7| 19.166|
| AES | CBC CTS| 256|128 | 39|24 |30.504 |19.624 |
| AES | CFB |128| 128| 35| 22| 33.682| 20.856|
| AES | CFB |192| 128| 36|26 | 35.034|20.829 |
| AES | CFB |256|128 | 40| 16| 33.954| 22.35|
| AES | CTR |128| 128| 32| 25|49.484 | 35.045|
| AES | CTR |192| 128| 30|23 |23.877 |20.929 |
| AES | CTR |256|128 | 34|27 |28.616 |20.603 |
| AES | OFB |128| 128|37 |28 |32.19 | 16.322|
| AES | OFB |192| 128| 40|29 | 39.422|28.557 |
| AES | OFB |256|128 |44 | 31| 30.611|23.189 |
| AES | XTS |256| 128|41 |27 |30.611 |23.189 |
| AES | XTS |348| 128|40 | 26| 29.155|23.674 |
| AES | XTS |512|128 | 40|28 | 31.175| 24.758|
| AES | GCM |128| 1000| 33| 46| 36.056| 46.47|
| AES | GCM |192| 1000| 24| 46| 25.39|33.308 |
| AES | GCM |256|1000 |28 |48 |28.843|33.254 |
| AES | CCM |128| 10|36 |53 |37.963 |37.568 |
| AES | CCM |192| 10| 52|87 |34.64 |38.163 |
| AES | CCM |256|10 | 45|54 |35.784 |40.619 |
### DES with cryptopp library
#### CBC operation mode
windows:

linux:

#### EBC operation mode
windows:

linux:

#### CBC CTS operation mode
windows:

linux:

#### CFB operation mode
windows:

linux:

#### CTR operation mode
windows:

linux:

#### OFB operation mode
windows:

linux:

### AES with crypropp library
#### CBC operation mode
-> 128 bits key
windows:

linux:

-> 192 bits key
windows:

linux:

-> 256 bits key
windows:

linux:

#### EBC operation mode
-> 128 bits key
windows:

linux:

-> 192 bits key
windows:

linux:

-> 256 bits key
windows:

linux:

#### CBC CTS operation mode
-> 128 bits key
windows:

linux:

-> 192 bits key
windows:

linux:

-> 256 bits key
windows:

linux:

#### CFB operation mode
-> 128 bits key
windows:

linux:

-> 192 bits key
windows:

linux:

-> 256 bits key
windows:

linux:

#### CTR operation mode
-> 128 bits key
windows:

linux:

-> 192 bits key
windows:

linux:

-> 256 bits key
windows:

linux:

#### OFB operation mode
-> 128 bits key
windows:

linux:

-> 192 bits key
windows:

linux:

-> 256 bits key
windows:

linux:

#### XTS operation mode
-> 256 bits key
windows:

linux:

-> 348 bits key
windows:

linux:

-> 512 bits key
windows:

linux:

#### GCM authentication operation mode
-> authentication data : ANTN2019
-> 128 bits key - iv 1000 bytes length
windows:

linux:

-> 192 bits key
windows:

linux:

-> 256 bits key
windows:

linux:

#### CCM authentication operation mode
-> authentication data : ANTN2019
-> 128 bits key - iv 10 bytes length
windows:

linux:

-> 192 bits key
windows:

linux:

-> 256 bits key
windows:

linux:

<file_sep>// g++ -g3 -ggdb -O0 -DDEBUG -I/usr/include/cryptopp Driver.cpp -o Driver.exe -lcryptopp -lpthread
// g++ -g -O2 -DNDEBUG -I/usr/include/cryptopp Driver.cpp -o Driver.exe -lcryptopp -lpthread
#include "cryptopp/osrng.h"
using CryptoPP::AutoSeededRandomPool;
#include <ctime>
#include <iomanip>
#include <iostream>
#include "assert.h"
// library for unicode in C++
/* Vietnamese support */
/* Set _setmode()*/
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#else
#include <stdio_ext.h> // _fpurge(stdin) == fflush(stdin)
#endif
#include <string>
#include <locale>
#include <codecvt>
using std::cerr;
using std::endl;
using std::wcin;
using std::wcout;
#include <string>
using std::string;
#include <cstdlib>
using std::exit;
#include "cryptopp/cryptlib.h"
using CryptoPP::Exception;
#include "cryptopp/hex.h"
using CryptoPP::HexDecoder;
using CryptoPP::HexEncoder;
#include "cryptopp/filters.h"
using CryptoPP::Redirector;
using CryptoPP::StreamTransformationFilter;
using CryptoPP::StringSink;
#include <cryptopp/files.h>
using CryptoPP::AuthenticatedDecryptionFilter;
using CryptoPP::AuthenticatedEncryptionFilter;
using CryptoPP::BufferedTransformation;
using CryptoPP::FileSink;
using CryptoPP::FileSource;
using CryptoPP::FileSource;
using CryptoPP::StringSource;
#include "cryptopp/AES.h"
using CryptoPP::AES;
#include "cryptopp/modes.h"
#include "cryptopp/xts.h"
#include "cryptopp/gcm.h"
#include "cryptopp/ccm.h"
using CryptoPP::CBC_CTS_Mode; //done
using CryptoPP::CBC_Mode; // done
using CryptoPP::CCM;
using CryptoPP::CFB_Mode; //done
using CryptoPP::CTR_Mode; //done
using CryptoPP::ECB_Mode; // done
using CryptoPP::GCM;
using CryptoPP::GCM_TablesOption;
using CryptoPP::OFB_Mode; //done
using CryptoPP::XTS;
#include "cryptopp/secblock.h"
using CryptoPP::byte;
using CryptoPP::SecByteBlock;
const int TAG_SIZE = 16;
// CBC encrypt
double CBC_AES_Encrypt(string plain, byte *iv, SecByteBlock key, string &cipher)
{
// executation time of each Encryption operation
int start_s = clock();
double etime = 0;
// try catch exception during operation
try
{
// encrytion AES with CBC mode
CBC_Mode<AES>::Encryption e;
// set key for AES encryption scheme
e.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter adds default padding ( without argument specified)
// as required. ECB and CBC Mode must be padded
// to the block size of the cipher.
// stream StreamTransformationFilter
//pipepline the plaintext to the AES scheme (e) through StreamTransformationFilter and output to cipher string
StringSource(plain, true,
new StreamTransformationFilter(e,
new StringSink(cipher)) // StreamTransformationFilter
); // StringSource
// time done for encryption operation
int stop_s = clock();
// compute the operating execution from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
// cerr << e.what() << " here "<<endl;
exit(1);
}
// return execution time
return etime;
}
// CBC decrypt
double CBC_AES_Decrypt(string cipher, byte *iv, SecByteBlock key, string &recovered)
{
int start_s = clock();
// execution time of AES decryption operation
double etime = 0;
// catch any exception during operation
try
{
// initiate AES decryption with mode CBC
CBC_Mode<AES>::Decryption d;
// set key for operation
d.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter removes
// padding as required.
// pipeline the cipher to AES Decryption scheme (d) through StreamTransformationFilter and output to recoverd string
StringSource s(cipher, true,
new StreamTransformationFilter(d,
new StringSink(recovered)) // StreamTransformationFilter
);
// time done for decryption operation // StringSource
int stop_s = clock();
// compute time for operating execution time from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
// cerr << e.what() <<"hehe"<< endl;
exit(1);
}
// return execution time
return etime;
}
// EBC encrypt
double ECB_AES_Encrypt(string plain, SecByteBlock key, string &cipher)
{
int start_s = clock();
// executation time of each Encryption operation
double etime = 0;
// try catch exception during operation
try
{
// encrytion AES with ECB mode
ECB_Mode<AES>::Encryption e;
// set key for AES encryption scheme
e.SetKey(key, key.size());
// The StreamTransformationFilter adds default padding ( without argument specified)
// as required. ECB and CBC Mode must be padded
// to the block size of the cipher.
// stream StreamTransformationFilter
//pipepline the plaintext to the AES scheme (e) through StreamTransformationFilter and output to cipher string
StringSource(plain, true,
new StreamTransformationFilter(e,
new StringSink(cipher)) // StreamTransformationFilter
); // StringSource
// time done for encryption operation
int stop_s = clock();
// compute the operating execution from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// EBC decrypt
double ECB_AES_Decrypt(string cipher, SecByteBlock key, string &recovered)
{
int start_s = clock();
// execution time of AES decryption operation
double etime = 0;
// catch any exception during operation
try
{
// initiate AES decryption with mode ECB
ECB_Mode<AES>::Decryption d;
// set key for operation
d.SetKey(key, key.size());
// The StreamTransformationFilter removes
// padding as required.
// pipeline the cipher to AES Decryption scheme (d) through StreamTransformationFilter and output to recoverd string
StringSource s(cipher, true,
new StreamTransformationFilter(d,
new StringSink(recovered)) // StreamTransformationFilter
);
// time done for decryption operation // StringSource
int stop_s = clock();
// compute time for operating execution time from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// CBC-CTS encrypt
double CBC_CTS_AES_Encrypt(string plain, byte *iv, SecByteBlock key, string &cipher)
{
int start_s = clock();
// executation time of each Encryption operation
double etime = 0;
// try catch exception during operation
try
{
// encrytion AES with CBC-CTS mode
CBC_CTS_Mode<AES>::Encryption e;
// set key for AES encryption scheme
e.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter adds default padding ( without argument specified)
// as required. ECB and CBC Mode must be padded
// to the block size of the cipher.
// stream StreamTransformationFilter
//pipepline the plaintext to the AES scheme (e) through StreamTransformationFilter and output to cipher string
StringSource(plain, true,
new StreamTransformationFilter(e,
new StringSink(cipher)) // StreamTransformationFilter
); // StringSource
// time done for encryption operation
int stop_s = clock();
// compute the operating execution from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// CBC-CTS decrypt
double CBC_CTS_AES_Decrypt(string cipher, byte *iv, SecByteBlock key, string &recovered)
{
int start_s = clock();
// execution time of AES decryption operation
double etime = 0;
// catch any exception during operation
try
{
// initiate AES decryption with mode CBC-CTS
CBC_CTS_Mode<AES>::Decryption d;
// set key for operation
d.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter removes
// padding as required.
// pipeline the cipher to AES Decryption scheme (d) through StreamTransformationFilter and output to recoverd string
StringSource s(cipher, true,
new StreamTransformationFilter(d,
new StringSink(recovered)) // StreamTransformationFilter
);
// time done for decryption operation // StringSource
int stop_s = clock();
// compute time for operating execution time from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// CFB encrypt
double CFB_AES_Encrypt(string plain, byte *iv, SecByteBlock key, string &cipher)
{
int start_s = clock();
// executation time of each Encryption operation
double etime = 0;
// try catch exception during operation
try
{
// encrytion AES with CFB mode
CFB_Mode<AES>::Encryption e;
// set key for AES encryption scheme
e.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter adds default padding ( without argument specified)
// as required. ECB and CBC Mode must be padded
// to the block size of the cipher.
// stream StreamTransformationFilter
//pipepline the plaintext to the AES scheme (e) through StreamTransformationFilter and output to cipher string
StringSource(plain, true,
new StreamTransformationFilter(e,
new StringSink(cipher)) // StreamTransformationFilter
); // StringSource
// time done for encryption operation
int stop_s = clock();
// compute the operating execution from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// CFB decrypt
double CFB_AES_Decrypt(string cipher, byte *iv, SecByteBlock key, string &recovered)
{
int start_s = clock();
// execution time of AES decryption operation
double etime = 0;
// catch any exception during operation
try
{
// initiate AES decryption with mode CFB
CFB_Mode<AES>::Decryption d;
// set key for operation
d.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter removes
// padding as required.
// pipeline the cipher to AES Decryption scheme (d) through StreamTransformationFilter and output to recoverd string
StringSource s(cipher, true,
new StreamTransformationFilter(d,
new StringSink(recovered)) // StreamTransformationFilter
);
// time done for decryption operation // StringSource
int stop_s = clock();
// compute time for operating execution time from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// CTR encrypt
double CTR_AES_Encrypt(string plain, byte *iv, SecByteBlock key, string &cipher)
{
int start_s = clock();
// executation time of each Encryption operation
double etime = 0;
// try catch exception during operation
try
{
// encrytion AES with CTR mode
CTR_Mode<AES>::Encryption e;
// set key for AES encryption scheme
e.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter adds default padding ( without argument specified)
// as required. ECB and CBC Mode must be padded
// to the block size of the cipher.
// stream StreamTransformationFilter
//pipepline the plaintext to the AES scheme (e) through StreamTransformationFilter and output to cipher string
StringSource(plain, true,
new StreamTransformationFilter(e,
new StringSink(cipher)) // StreamTransformationFilter
); // StringSource
// time done for encryption operation
int stop_s = clock();
// compute the operating execution from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// CTR decrypt
double CTR_AES_Decrypt(string cipher, byte *iv, SecByteBlock key, string &recovered)
{
int start_s = clock();
// execution time of AES decryption operation
double etime = 0;
// catch any exception during operation
try
{
// initiate AES decryption with mode CTR
CTR_Mode<AES>::Decryption d;
// set key for operation
d.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter removes
// padding as required.
// pipeline the cipher to AES Decryption scheme (d) through StreamTransformationFilter and output to recoverd string
StringSource s(cipher, true,
new StreamTransformationFilter(d,
new StringSink(recovered)) // StreamTransformationFilter
);
// time done for decryption operation // StringSource
int stop_s = clock();
// compute time for operating execution time from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// OFB encrypt
double OFB_AES_Encrypt(string plain, byte *iv, SecByteBlock key, string &cipher)
{
int start_s = clock();
// executation time of each Encryption operation
double etime = 0;
// try catch exception during operation
try
{
// encrytion AES with OFB mode
OFB_Mode<AES>::Encryption e;
// set key for AES encryption scheme
e.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter adds default padding ( without argument specified)
// as required. ECB and CBC Mode must be padded
// to the block size of the cipher.
// stream StreamTransformationFilter
//pipepline the plaintext to the AES scheme (e) through StreamTransformationFilter and output to cipher string
StringSource(plain, true,
new StreamTransformationFilter(e,
new StringSink(cipher)) // StreamTransformationFilter
); // StringSource
// time done for encryption operation
int stop_s = clock();
// compute the operating execution from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// OFB decrypt
double OFB_AES_Decrypt(string cipher, byte *iv, SecByteBlock key, string &recovered)
{
int start_s = clock();
// execution time of AES decryption operation
double etime = 0;
// catch any exception during operation
try
{
// initiate AES decryption with mode OFB
OFB_Mode<AES>::Decryption d;
// set key for operation
d.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter removes
// padding as required.
// pipeline the cipher to AES Decryption scheme (d) through StreamTransformationFilter and output to recoverd string
StringSource s(cipher, true,
new StreamTransformationFilter(d,
new StringSink(recovered)) // StreamTransformationFilter
);
// time done for decryption operation // StringSource
int stop_s = clock();
// compute time for operating execution time from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// XTS encrypt
double XTS_AES_Encrypt(string plain, byte *iv, SecByteBlock key, string &cipher)
{
int start_s = clock();
// executation time of each Encryption operation
double etime = 0;
// try catch exception during operation
try
{
// encrytion AES with XTS mode
XTS_Mode<AES>::Encryption e;
// set key for AES encryption scheme
e.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter adds default padding ( without argument specified)
// as required. ECB and CBC Mode must be padded
// to the block size of the cipher.
// stream StreamTransformationFilter
//pipepline the plaintext to the AES scheme (e) through StreamTransformationFilter and output to cipher string
StringSource(plain, true,
new StreamTransformationFilter(e,
new StringSink(cipher)) // StreamTransformationFilter
); // StringSource
// time done for encryption operation
int stop_s = clock();
// compute the operating execution from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// XTS decrypt
double XTS_AES_Decrypt(string cipher, byte *iv, SecByteBlock key, string &recovered)
{
int start_s = clock();
// execution time of AES decryption operation
double etime = 0;
// catch any exception during operation
try
{
// initiate AES decryption with mode XTS
XTS_Mode<AES>::Decryption d;
// set key for operation
d.SetKeyWithIV(key, key.size(), iv);
// The StreamTransformationFilter removes
// padding as required.
// pipeline the cipher to AES Decryption scheme (d) through StreamTransformationFilter and output to recoverd string
StringSource s(cipher, true,
new StreamTransformationFilter(d,
new StringSink(recovered)) // StreamTransformationFilter
);
// time done for decryption operation // StringSource
int stop_s = clock();
// compute time for operating execution time from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (const CryptoPP::Exception &e)
{
// show any exception when catched
cerr << e.what() << endl;
exit(1);
}
// return execution time
return etime;
}
// GCM encrypt
double GCM_AES_Encrypt(string plain, byte *iv, SecByteBlock key, string &cipher, int iv_length, string &adata)
{
int start_s = clock();
// executation time of each Encryption operation
double etime = 0;
// try catch exception during operation
try
{
// encrytion AES with GCM mode
GCM<AES>::Encryption e;
// set key for AES encryption scheme
e.SetKeyWithIV(key, key.size(), iv, iv_length);
// Authentication Encryption Filter
AuthenticatedEncryptionFilter ef(e, new StringSink(cipher), false, TAG_SIZE);
// AuthenticatedEncryptionFilter::ChannelPut
// defines two channels: "" (empty) and "AAD"
// channel "" is encrypted and authenticated
// channel "AAD" is authenticated
ef.ChannelPut("AAD", (const byte *)adata.data(), adata.size());
ef.ChannelMessageEnd("AAD");
// Authenticated data *must* be pushed before
// Confidential/Authenticated data. Otherwise
// we must catch the BadState exception
ef.ChannelPut("", (const byte *)plain.data(), plain.size());
ef.ChannelMessageEnd("");
// time done for encryption operation
int stop_s = clock();
// compute the operating execution from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (CryptoPP::BufferedTransformation::NoChannelSupport &e)
{
// The tag must go in to the default channel:
// "unknown: this object doesn't support multiple channels"
std::wcerr << "Caught NoChannelSupport..." << endl;
std::wcerr << e.what() << endl;
std::wcerr << endl;
exit(1);
}
catch (CryptoPP::AuthenticatedSymmetricCipher::BadState &e)
{
// Pushing PDATA before ADATA results in:
// "GMC/AES: Update was called before State_IVSet"
std::wcerr << "Caught BadState..." << endl;
std::wcerr << e.what() << endl;
std::wcerr << endl;
exit(1);
}
catch (CryptoPP::InvalidArgument &e)
{
std::wcerr << "Caught InvalidArgument..." << endl;
std::wcerr << e.what() << endl;
std::wcerr << endl;
exit(1);
}
// return execution time
return etime;
}
// GCM decrypt
double GCM_AES_Decrypt(string cipher, byte *iv, SecByteBlock key, string &recovered, int iv_length, string radata, string plain)
{
int start_s = clock();
// execution time of AES decryption operation
double etime = 0;
// catch any exception during operation
try
{
// initiate AES decryption with mode GCM
GCM<AES>::Decryption d;
// set key for operation
d.SetKeyWithIV(key, key.size(), iv, iv_length);
// break the cipher text out into it's
// components: Encrypted Data and MAC value
string enc = cipher.substr(0, cipher.length() - TAG_SIZE);
string mac = cipher.substr(cipher.length() - TAG_SIZE);
// Sanity checks
assert(cipher.size() == enc.size() + mac.size());
assert(enc.size() == plain.size());
assert(mac.size() == TAG_SIZE);
// Object will not throw an exception
// during decryption\verification _if_
// verification fails.
//AuthenticatedDecryptionFilter df( d, NULL,
// AuthenticatedDecryptionFilter::MAC_AT_BEGIN );
AuthenticatedDecryptionFilter df(d, NULL,
AuthenticatedDecryptionFilter::MAC_AT_BEGIN |
AuthenticatedDecryptionFilter::THROW_EXCEPTION,
TAG_SIZE);
// The order of the following calls are important
df.ChannelPut("", (const byte *)mac.data(), mac.size());
df.ChannelPut("AAD", (const byte *)radata.data(), radata.size());
df.ChannelPut("", (const byte *)enc.data(), enc.size());
// If the object throws, it will most likely occur
// during ChannelMessageEnd()
df.ChannelMessageEnd("AAD");
df.ChannelMessageEnd("");
// If the object does not throw, here's the only
// opportunity to check the data's integrity
bool b = false;
b = df.GetLastResult();
assert(b == true);
// Remove data from channel
size_t n = (size_t)-1;
// Plain text recoverd from enc.data()
df.SetRetrievalChannel("");
n = (size_t)df.MaxRetrievable();
recovered.resize(n);
if (n > 0)
{
df.Get((byte *)recovered.data(), n);
}
assert(plain == recovered);
// time done for decryption operation // StringSource
int stop_s = clock();
// compute time for operating execution time from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (CryptoPP::InvalidArgument &e)
{
std::wcerr << "Caught InvalidArgument..." << endl;
std::wcerr << e.what() << endl;
std::wcerr << endl;
exit(1);
}
catch (CryptoPP::AuthenticatedSymmetricCipher::BadState &e)
{
// Pushing PDATA before ADATA results in:
// "GMC/AES: Update was called before State_IVSet"
std::wcerr << "Caught BadState..." << endl;
std::wcerr << e.what() << endl;
std::wcerr << endl;
exit(1);
}
catch (CryptoPP::HashVerificationFilter::HashVerificationFailed &e)
{
std::wcerr << "Caught HashVerificationFailed..." << endl;
std::wcerr << e.what() << endl;
std::wcerr << endl;
exit(1);
}
// return execution time
return etime;
}
// CCM mode
double CCM_AES_Encrypt(string plain, byte *iv, SecByteBlock key, string &cipher, int iv_length, string &adata)
{
int start_s = clock();
// executation time of each Encryption operation
double etime = 0;
// try catch exception during operation
try
{
// encrytion AES with CCM mode
CCM<AES, TAG_SIZE>::Encryption e;
// set key for AES encryption scheme
e.SetKeyWithIV(key, key.size(), iv, iv_length);
e.SpecifyDataLengths(adata.size(), plain.size(), 0);
// Authentication Encryption Filter
AuthenticatedEncryptionFilter ef(e, new StringSink(cipher), false, TAG_SIZE);
// AuthenticatedEncryptionFilter::ChannelPut
// defines two channels: "" (empty) and "AAD"
// channel "" is encrypted and authenticated
// channel "AAD" is authenticated
ef.ChannelPut("AAD", (const byte *)adata.data(), adata.size());
ef.ChannelMessageEnd("AAD");
// Authenticated data *must* be pushed before
// Confidential/Authenticated data. Otherwise
// we must catch the BadState exception
ef.ChannelPut("", (const byte *)plain.data(), plain.size());
ef.ChannelMessageEnd("");
// time done for encryption operation
int stop_s = clock();
// compute the operating execution from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (CryptoPP::BufferedTransformation::NoChannelSupport &e)
{
// The tag must go in to the default channel:
// "unknown: this object doesn't support multiple channels"
std::wcerr << "Caught NoChannelSupport..." << endl;
std::wcerr << e.what() << endl;
std::wcerr << endl;
exit(1);
}
catch (CryptoPP::AuthenticatedSymmetricCipher::BadState &e)
{
// Pushing PDATA before ADATA results in:
// "GMC/AES: Update was called before State_IVSet"
std::wcerr << "Caught BadState..." << endl;
std::wcerr << e.what() << endl;
std::wcerr << endl;
exit(1);
}
catch (CryptoPP::InvalidArgument &e)
{
std::wcerr << "Caught InvalidArgument..." << endl;
std::wcerr << e.what() << endl;
std::wcerr << endl;
exit(1);
}
// return execution time
return etime;
}
// CCM decrypt
double CCM_AES_Decrypt(string cipher, byte *iv, SecByteBlock key, string &recovered, int iv_length, string radata, string plain)
{
int start_s = clock();
// execution time of AES decryption operation
double etime = 0;
// catch any exception during operation
try
{
// initiate AES decryption with mode CCM
CCM<AES>::Decryption d;
// set key for operation
d.SetKeyWithIV(key, key.size(), iv, iv_length);
// break the cipher text out into it's
// components: Encrypted Data and MAC value
string enc = cipher.substr(0, cipher.length() - TAG_SIZE);
string mac = cipher.substr(cipher.length() - TAG_SIZE);
d.SpecifyDataLengths(radata.size(), enc.size(), 0);
// Sanity checks
assert(cipher.size() == enc.size() + mac.size());
assert(enc.size() == plain.size());
assert(mac.size() == TAG_SIZE);
AuthenticatedDecryptionFilter df(d, NULL,
AuthenticatedDecryptionFilter::MAC_AT_BEGIN |
AuthenticatedDecryptionFilter::THROW_EXCEPTION,
TAG_SIZE);
// The order of the following calls are important
df.ChannelPut("", (const byte *)mac.data(), mac.size());
df.ChannelPut("AAD", (const byte *)radata.data(), radata.size());
df.ChannelPut("", (const byte *)enc.data(), enc.size());
// If the object throws, it will most likely occur
// during ChannelMessageEnd()
df.ChannelMessageEnd("AAD");
df.ChannelMessageEnd("");
// If the object does not throw, here's the only
// opportunity to check the data's integrity
bool b = false;
b = df.GetLastResult();
assert(b == true);
// Remove data from channel
size_t n = (size_t)-1;
// Plain text recoverd from enc.data()
df.SetRetrievalChannel("");
n = (size_t)df.MaxRetrievable();
recovered.resize(n);
if (n > 0)
{
df.Get((byte *)recovered.data(), n);
}
assert(plain == recovered);
// time done for decryption operation // StringSource
int stop_s = clock();
// compute time for operating execution time from the start time to end time
etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
}
catch (CryptoPP::InvalidArgument &e)
{
std::wcerr << "Caught InvalidArgument..." << endl;
std::wcerr << e.what() << endl;
std::wcerr << endl;
exit(1);
}
catch (CryptoPP::AuthenticatedSymmetricCipher::BadState &e)
{
// Pushing PDATA before ADATA results in:
// "GMC/AES: Update was called before State_IVSet"
std::wcerr << "Caught BadState..." << endl;
std::wcerr << e.what() << endl;
std::wcerr << endl;
exit(1);
}
catch (CryptoPP::HashVerificationFilter::HashVerificationFailed &e)
{
std::wcerr << "Caught HashVerificationFailed..." << endl;
std::wcerr << e.what() << endl;
std::wcerr << endl;
exit(1);
}
// return execution time
return etime;
}
// show the result out screen (console)
void show_result(SecByteBlock key, byte *iv, int iv_length, string ciphertext, string recovered, double total_time_encrypt, double total_time_decrypt, string mode)
{
string encoded;
// clear encoded
encoded.clear();
// convert key to hex format and save to encoded string
StringSource(key, key.size(), true,
new HexEncoder(
new StringSink(encoded)) // HexEncoder
);
// StringSource
// show key in hex format
wcout << "Key: " << encoded.c_str() << endl;
if (mode != "ECB")
{
// convert iv to hex format and save to encoded string
encoded.clear();
StringSource(iv, iv_length, true,
new HexEncoder(
new StringSink(encoded)) // HexEncoder
);
// show iv in hex format
// StringSource
wcout << "iv: " << encoded.c_str() << endl;
}
// clear encoded
encoded.clear();
// convert ciphertext to hex format and save to encoded string
StringSource(ciphertext, true,
new HexEncoder(
new StringSink(encoded)) // HexEncoder
); // StringSource
// show cipher text in hex format
wcout << "Cipher text: " << encoded.c_str() << endl;
double ex_time_encrypt = total_time_encrypt / 10000; // Average execution time of 10.000 encryption running
// compute the average time of each decryption
double ex_time_decrypt = total_time_decrypt / 10000; // Average execution time of 10.000 decryption running
// compute the average time of each encryption
// show result to console screen
wcout << "Total execution time for 10.000 rounds: \t"
<< "encrypt: " << total_time_encrypt << "ms\t decrypt: " << total_time_decrypt << "ms" << endl;
// setw(41) to format output
wcout << std::setw(41) << std::left << "Execution time: \t"
<< "encrypt: " << ex_time_encrypt << "ms\tdecrypt: " << ex_time_decrypt << "ms" << endl;
// show decode message
// show decode message and convert to utf16
std::wstring str = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(recovered);
wcout << "Recoverd text: " << str << endl;
}
double Estimation_En_De_cypt_Operation(string &plain, byte *iv, SecByteBlock key, string &cipher, int mode, bool is_decryption, int loop, string &adata, int iv_length)
{
double total_time = 0;
string pdata = plain;
while (loop--)
{
// Compute total time for encryption
switch (mode)
{
case 1:
// ECB mode
if (!is_decryption)
{
total_time += ECB_AES_Encrypt(plain, key, cipher);
}
else
{
total_time += ECB_AES_Decrypt(cipher, key, plain);
}
break;
case 2:
// CBC mode
if (!is_decryption)
{
total_time += CBC_AES_Encrypt(plain, iv, key, cipher);
}
else
{
total_time += CBC_AES_Decrypt(cipher, iv, key, plain);
}
break;
case 3:
// CBC CTS mode
if (!is_decryption)
{
total_time += CBC_CTS_AES_Encrypt(plain, iv, key, cipher);
}
else
{
total_time += CBC_CTS_AES_Decrypt(cipher, iv, key, plain);
}
break;
case 4:
// CFB mode
if (!is_decryption)
{
total_time += CFB_AES_Encrypt(plain, iv, key, cipher);
}
else
{
total_time += CFB_AES_Decrypt(cipher, iv, key, plain);
}
break;
case 5:
// CTR mode
if (!is_decryption)
{
total_time += CTR_AES_Encrypt(plain, iv, key, cipher);
}
else
{
total_time += CTR_AES_Decrypt(cipher, iv, key, plain);
}
break;
case 6:
// OFB mode
if (!is_decryption)
{
total_time += OFB_AES_Encrypt(plain, iv, key, cipher);
}
else
{
total_time += OFB_AES_Decrypt(cipher, iv, key, plain);
}
break;
case 7:
//XTS mode
if (!is_decryption)
{
total_time += XTS_AES_Encrypt(plain, iv, key, cipher);
}
else
{
total_time += XTS_AES_Decrypt(cipher, iv, key, plain);
}
break;
case 8:
//GCM mode authentication
if (!is_decryption)
{
total_time += GCM_AES_Encrypt(plain, iv, key, cipher, iv_length, adata);
}
else
{
total_time += GCM_AES_Decrypt(cipher, iv, key, plain, iv_length, adata, pdata);
}
break;
case 9:
//CCM mode authentication
if (!is_decryption)
{
total_time += CCM_AES_Encrypt(plain, iv, key, cipher, iv_length, adata);
}
else
{
total_time += CCM_AES_Decrypt(cipher, iv, key, plain, iv_length, adata, pdata);
}
break;
default:
break;
}
// save the ciphertext to show for the last loop
if (loop == 0)
{
break;
}
if (!is_decryption)
{
cipher.clear();
}
else
{
plain.clear();
}
}
return total_time;
}
SecByteBlock input_key_from_keyboard(int key_length)
{
std::wstring key_input;
string input = "";
do
{
wcout << "Input key: ";
fflush(stdin);
std::getline(wcin, key_input);
input = std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(key_input);
if (input.length() != key_length)
{
wcout << "Wrong key length input. Key length must be 16 bytes!\n";
}
else
{
break;
}
} while (1);
SecByteBlock key(key_length);
for (int i = 0; i < key_length; i++)
{
key[i] = (unsigned int)input[i];
}
return key;
}
int key_length_selection(int mode)
{
int key_length_bytes;
int key1 = 16, key2 = 24, key3 = 32;
do
{
wcout << "Input key length:" << endl;
if (mode != 7)
{
wcout << "16 bytes - 128 bits key\n";
wcout << "24 bytes - 192 bits key\n";
wcout << "32 bytes - 256 bits key\n";
}
else
{
wcout << "32 bytes - 256 bits key\n";
wcout << "48 bytes - 348 bits key\n";
wcout << "64 bytes - 512 bits key\n";
key1 = 32;
key2 = 48;
key3 = 64;
}
wcout << "Enter key length: ";
wcin >> key_length_bytes;
if (key_length_bytes != key1 && key_length_bytes != key2 && key_length_bytes != key3)
{
wcout << "Wrong key length input!" << endl;
}
else
{
break;
}
} while (1);
return key_length_bytes;
}
SecByteBlock key_selection(int mode)
{
int key_length = key_length_selection(mode);
SecByteBlock key(key_length);
int option_input_key = 0;
do
{
wcout << endl;
wcout << "[+] Key selection:\n";
wcout << "1 - input key from keyboard\n";
wcout << "2 - input key from file\n";
wcout << "3 - generate a ramdom key\n";
wcout << "Enter option: ";
wcin >> option_input_key;
if (option_input_key >= 1 && option_input_key <= 3)
{
break;
}
else
{
wcout << "Wrong input.\n";
}
} while (1);
switch (option_input_key)
{
case 1:
{
key = input_key_from_keyboard(key_length);
break;
}
case 2:
{
// reading key from file
try
{
FileSource fs("AES_key.key", false);
// create space for key
CryptoPP::ArraySink copykey(key, key.size());
//copy data from AES_key.key to key
fs.Detach(new Redirector(copykey));
fs.Pump(key_length);
}
catch (CryptoPP::Exception e)
{
string error = e.GetWhat();
std::wstring str = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(error);
wcout << str << endl;
exit(1);
}
break;
}
case 3:
{
AutoSeededRandomPool prng;
prng.GenerateBlock(key, key_length);
break;
}
}
if (option_input_key != 2)
{
StringSource ss(key, key.size(), true, new FileSink("AES_key.key"));
wcout << "Key has been save to AES_key.key" << endl;
}
return key;
}
byte *input_iv_from_keyboard(int iv_length)
{
std::wstring iv_input;
string input = "";
do
{
wcout << "Input key: ";
fflush(stdin);
std::getline(wcin, iv_input);
input = std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(iv_input);
if (input.length() != iv_length)
{
wcout << "Wrong iv length input. iv length must be " << iv_length << " bytes!\n";
}
else
{
break;
}
} while (1);
byte *iv = new byte[iv_length];
for (int i = 0; i < iv_length; i++)
{
iv[i] = (unsigned int)input[i];
}
return iv;
}
long selection_iv_length_authentication_mode(int min, long long max)
{
do
{
wcout << "\n[+] IV selection for authentication mode:\n";
wcout << "Enter a iv length in range (" << min << "-" << max << "): ";
long length = 0;
wcin >> length;
if (length <= min && length > max)
{
wcout << "Wrong input iv length!\n";
}
else
{
return length;
}
} while (1);
}
byte *iv_selection(int mode, unsigned int &iv_length)
{
byte *iv;
int option_input_iv = 0;
iv_length = 16;
if (mode == 8)
{
iv_length = selection_iv_length_authentication_mode(1, 4294967295);
}
if (mode == 9)
{
iv_length = selection_iv_length_authentication_mode(7, 13);
}
do
{
wcout << endl;
wcout << "[+] IV selection:\n";
wcout << "1 - input iv from keyboard\n";
wcout << "2 - input iv from file\n";
wcout << "3 - generate a ramdom iv\n";
wcout << "Enter option: ";
wcin >> option_input_iv;
if (option_input_iv >= 1 && option_input_iv <= 3)
{
break;
}
else
{
wcout << "Wrong input.\n";
}
} while (1);
switch (option_input_iv)
{
case 1:
{
iv = input_iv_from_keyboard(iv_length);
break;
}
case 2:
{
// reading key from file
try
{
iv = new byte[iv_length];
FileSource fs("AES_iv.iv", false);
// create space for key
CryptoPP::ArraySink copykey(iv, iv_length);
//copy data from AES_key.key to key
fs.Detach(new Redirector(copykey));
fs.Pump(iv_length);
}
catch (CryptoPP::Exception e)
{
string error = e.GetWhat();
std::wstring str = std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(error);
wcout << str << endl;
exit(1);
}
break;
}
case 3:
{
iv = new byte[iv_length];
AutoSeededRandomPool prng;
prng.GenerateBlock(iv, iv_length);
break;
}
}
if (option_input_iv != 2)
{
StringSource ss(iv, iv_length, true, new FileSink("AES_iv.iv"));
wcout << "iv has been saved to AES_iv.iv" << endl;
}
return iv;
}
int main(int argc, char *argv[])
{
/*Set mode support Vietnamese*/
#ifdef __linux__
setlocale(LC_ALL, "");
#elif _WIN32
_setmode(_fileno(stdin), _O_U16TEXT);
_setmode(_fileno(stdout), _O_U16TEXT);
#else
#endif
// set default plaintext
std::wstring wplaintext = L"Welcome to the AES encryption and decryption!";
wcout << "\n[+] Enter plaintext: ";
std::getline(wcin, wplaintext);
// random byte
AutoSeededRandomPool prng;
// key initiattion
SecByteBlock key(AES::DEFAULT_KEYLENGTH);
byte *iv;
int mode_option = 0;
// Select operation mode
do
{
wcout << endl;
wcout << "[+] Select operation mode: \n";
wcout << "1 - EBC mode\n";
wcout << "2 - CBC mode\n";
wcout << "3 - CBC CTS mode\n";
wcout << "4 - CFB mode\n";
wcout << "5 - CTR mode\n";
wcout << "6 - OFB mode\n";
wcout << "7 - XTS mode\n";
wcout << "8 - GCM mode\n";
wcout << "9 - CCM mode\n";
wcout << "Enter selection (1-9): ";
wcin >> mode_option;
if (mode_option < 1 || mode_option > 9)
{
wcout << "Input wrong options!\n";
}
else
{
break;
}
} while (1);
key = key_selection(mode_option);
unsigned int iv_length = 16;
// not set iv for ECB mode
if (mode_option != 1)
{
iv = iv_selection(mode_option, iv_length);
}
else
{
iv = NULL;
}
std::wstring w_adata = L"";
string adata = "";
const int TAG_SIZE = 16;
// input authentication data for authentication mode
if (mode_option == 8 || mode_option == 9)
{
wcout << "\n[+] Enter authentication data: ";
#ifdef __linux__
__fpurge(stdin);
#elif _WIN32
fflush(stdin);
#else
#endif
std::getline(wcin, w_adata);
// convert wstring(utf8) to string
adata = std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(w_adata);
}
// convert input in utf16 to string
string plaintext = std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(wplaintext);
// initiate ciphertext, encoded for key in hex format, recoverd is decryption message in hex format
string ciphertext, recovered;
// initiate for time variable
// Total time for 10.000 encryption running
double total_time_encrypt = 0;
// Total time for 10.000 decryption running
double total_time_decrypt = 0;
// initiate start time
// loop for 10.000 operation
int loop = 10000;
total_time_encrypt = Estimation_En_De_cypt_Operation(plaintext, iv, key, ciphertext, mode_option, 0, loop, adata, iv_length);
total_time_decrypt = Estimation_En_De_cypt_Operation(recovered, iv, key, ciphertext, mode_option, 1, loop, adata, iv_length);
string mode_str[] = {"ECB", "CBC", "CBC CTS", "CFB", "CTR", "OFB", "XTS", "GCM", "CCM"};
wcout << endl;
wcout << "[+] Estimation result" << endl;
show_result(key, iv, iv_length, ciphertext, recovered, total_time_encrypt, total_time_decrypt, mode_str[mode_option - 1]);
return 0;
}
<file_sep># Performance
## Hardware resources
Processor: Intel(R) Core(TM) i7-4720HQ CPU @ 2.60GHz, 2594 Mhz, 4 Core(s), 8 Logical Processor(s)
Installed Physical Memory (RAM): 8.00 GB
Total Physical Memory: 7.89 GB
## Perfomance windows 10 64 bit
OS Name Microsoft Windows 10 Home Single Language
Version 10.0.19042 Build 19042
## Thống kê (10000 vòng lặp)
| Scheme | Operation | Platform |Total excecution time (ms) | Average execution time (ms) |
| ------ | --------- | -------- |--------------------- | ---------------------- |
| Hash | SHA224| Windows | 17 | 0.0017 |
| Hash | SHA224| Linux | 12.128 | 0.0012128 |
| Hash | SHA256| Windows | 17 | 0.0017 |
| Hash | SHA256| Linux | 12.157 | 0.0012157|
| Hash | SHA384| Windows | 16 | 0.0016 |
| Hash | SHA384| Linux | 10.751 | 0.0010751 |
| Hash | SHA512| Windows | 14 | 0.0014 |
| Hash | SHA512| Linux | 10.689 | 0.0010689 |
| Hash | SHA3-224| Windows | 23 | 0.0023|
| Hash | SHA3-224| Linux | 12.755 | 0.0012755|
| Hash | SHA3-256| Windows | 16 | 0.0016|
| Hash | SHA3-256| Linux | 12.868 | 0.0012968 |
| Hash | SHA3-384| Windows | 22 | 0.0022 |
| Hash | SHA3-384| Linux | 19.095 | 0.0019095 |
| Hash | SHA3-512| Windows | 27 | 0.0027 |
| Hash | SHA3-512| Linux | 17.793 | 0.0017793 |
| Hash | SHAKE128 (1000 ouput length)| Windows | 54 | 0.0054 |
| Hash | SHAKE128 (1000 ouput length)| Linux | 38.141 | 0.0038141 |
| Hash | SHAKE256 (1000 ouput length)| Windows | 56 | 0.0056 |
| Hash | SHAKE256 (1000 ouput length) | Linux | 48.816 | 0.0048816 |
### SHA224
- windows:

- linux:

### SHA256
- windows:

- linux:

### SHA384
- windows:

- linux:

### SHA512
- windows:

- linux:

### SHA3-224
- windows:

- linux:

### SHA3-256
- windows:

- linux:

### SHA3-384
- windows:

- linux:

### SHA3-512
- windows:

- linux:

### SHAKE224
- windows:

- linux:

### SHAKE256
- windows:

- linux:

<file_sep>// ECDSA.KeyGen.cpp : Defines the entry point for the console application.
//
#include <assert.h>
#include <ctime>
#include <stdio.h>
#include <iostream>
using std::endl;
using std::wcout;
#include <string>
using std::string;
#include "cryptopp/osrng.h"
// using CryptoPP::AutoSeededX917RNG;
using CryptoPP::AutoSeededRandomPool;
#include "cryptopp/aes.h"
using CryptoPP::AES;
#include "cryptopp/integer.h"
using CryptoPP::Integer;
#include "cryptopp/sha.h"
using CryptoPP::SHA1;
/* Convert to hex */
#include <cryptopp/hex.h>
using CryptoPP::HexDecoder;
using CryptoPP::HexEncoder;
#include "cryptopp/filters.h"
using CryptoPP::ArraySink;
using CryptoPP::SignatureVerificationFilter;
using CryptoPP::SignerFilter;
using CryptoPP::StringSink;
using CryptoPP::StringSource;
#include "cryptopp/files.h"
using CryptoPP::FileSink;
using CryptoPP::FileSource;
#include "cryptopp/eccrypto.h"
using CryptoPP::DL_GroupParameters_EC;
using CryptoPP::ECDSA;
using CryptoPP::ECP;
#include "cryptopp/oids.h"
using CryptoPP::byte;
using CryptoPP::OID;
/* Vietnamese support */
/* Set _setmode()*/
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#else
#include <stdio_ext.h> // _fpurge(stdin) == fflush(stdin)
#endif
/* String convert */
#include <locale>
using std::wstring_convert;
#include <codecvt>
using std::codecvt_utf8;
#include <fstream>
using std::cerr;
using std::endl;
using std::wcin;
using std::wcout;
using std::wstring;
/* Integer convert */
#include <sstream>
using std::ostringstream;
bool GeneratePrivateKey(const OID &oid, ECDSA<ECP, SHA1>::PrivateKey &key);
bool GeneratePublicKey(const ECDSA<ECP, SHA1>::PrivateKey &privateKey, ECDSA<ECP, SHA1>::PublicKey &publicKey);
void SavePrivateKey(const string &filename, const ECDSA<ECP, SHA1>::PrivateKey &key);
void SavePublicKey(const string &filename, const ECDSA<ECP, SHA1>::PublicKey &key);
void LoadPrivateKey(const string &filename, ECDSA<ECP, SHA1>::PrivateKey &key);
void LoadPublicKey(const string &filename, ECDSA<ECP, SHA1>::PublicKey &key);
void PrintDomainParameters(const ECDSA<ECP, SHA1>::PrivateKey &key);
void PrintDomainParameters(const ECDSA<ECP, SHA1>::PublicKey &key);
void PrintDomainParameters(const DL_GroupParameters_EC<ECP> ¶ms);
void PrintPrivateKey(const ECDSA<ECP, SHA1>::PrivateKey &key);
void PrintPublicKey(const ECDSA<ECP, SHA1>::PublicKey &key);
bool SignMessage(const ECDSA<ECP, SHA1>::PrivateKey &key, const string &message, string &signature);
bool VerifyMessage(const ECDSA<ECP, SHA1>::PublicKey &key, const string &message, const string &signature);
/* Vietnames convert function def*/
wstring string_to_wstring(const std::string &str);
string wstring_to_string(const std::wstring &str);
wstring integer_to_wstring(const CryptoPP::Integer &t);
string wstring_hex_to_string(wstring wstr);
// Signing and verifying funciton
void Sign();
void Verify();
// Input Messgase and signature for sign and verify
string Input_Message();
string Input_Signature();
// Input key
void Input_PrivateKey(ECDSA<ECP, SHA1>::PrivateKey &key);
void Input_PublicKey(ECDSA<ECP, SHA1>::PublicKey &key);
int main(int argc, char *argv[])
{
/*Set mode support Vietnamese*/
#ifdef __linux__
setlocale(LC_ALL, "");
#elif _WIN32
_setmode(_fileno(stdin), _O_U16TEXT);
_setmode(_fileno(stdout), _O_U16TEXT);
#else
#endif
try
{
do
{
wcout << endl;
wcout << "~Welcome the Elliptic Curve Digital Signature Algorithm~\n"
<< endl;
wcout << "[1] Sign message with private key\n";
wcout << "[2] Verify message with public key\n";
wcout << "[3] Exit.\n";
wcout << "Enter option: ";
int option;
wcin >> option;
if (option == 1)
{
Sign();
}
else if (option == 2)
{
Verify();
}
else if (option == 3)
{
break;
}
else
{
wcout << "Invalid Option!" << endl;
}
} while (1);
}
catch (CryptoPP::Exception &e)
{
cerr << "Caught Exception..." << endl;
cerr << e.what() << endl;
}
return 0;
}
bool GeneratePrivateKey(const OID &oid, CryptoPP::ECDSA<ECP, SHA1>::PrivateKey &key)
{
AutoSeededRandomPool prng;
key.Initialize(prng, oid);
assert(key.Validate(prng, 3));
return key.Validate(prng, 3);
}
bool GeneratePublicKey(const CryptoPP::ECDSA<ECP, SHA1>::PrivateKey &privateKey, CryptoPP::ECDSA<ECP, SHA1>::PublicKey &publicKey)
{
AutoSeededRandomPool prng;
// Sanity check
assert(privateKey.Validate(prng, 3));
privateKey.MakePublicKey(publicKey);
assert(publicKey.Validate(prng, 3));
return publicKey.Validate(prng, 3);
}
void PrintDomainParameters(const CryptoPP::ECDSA<ECP, SHA1>::PrivateKey &key)
{
PrintDomainParameters(key.GetGroupParameters());
}
void PrintDomainParameters(const CryptoPP::ECDSA<ECP, SHA1>::PublicKey &key)
{
PrintDomainParameters(key.GetGroupParameters());
}
void PrintDomainParameters(const CryptoPP::DL_GroupParameters_EC<ECP> ¶ms)
{
wcout << endl;
wcout << "Modulus:" << endl;
wcout << " " << integer_to_wstring(params.GetCurve().GetField().GetModulus()) << endl;
wcout << "Coefficient A:" << endl;
wcout << " " << integer_to_wstring(params.GetCurve().GetA()) << endl;
wcout << "Coefficient B:" << endl;
wcout << " " << integer_to_wstring(params.GetCurve().GetB()) << endl;
wcout << "Base Point:" << endl;
wcout << " X: " << integer_to_wstring(params.GetSubgroupGenerator().x) << endl;
wcout << " Y: " << integer_to_wstring(params.GetSubgroupGenerator().y) << endl;
wcout << "Subgroup Order:" << endl;
wcout << " " << integer_to_wstring(params.GetSubgroupOrder()) << endl;
wcout << "Cofactor:" << endl;
wcout << " " << integer_to_wstring(params.GetCofactor()) << endl;
}
void PrintPrivateKey(const CryptoPP::ECDSA<ECP, SHA1>::PrivateKey &key)
{
wcout << endl;
wcout << "Private Exponent:" << endl;
wcout << " " << integer_to_wstring(key.GetPrivateExponent()) << endl;
}
void PrintPublicKey(const CryptoPP::ECDSA<ECP, SHA1>::PublicKey &key)
{
wcout << endl;
wcout << "Public Element:" << endl;
wcout << " X: " << integer_to_wstring(key.GetPublicElement().x) << endl;
wcout << " Y: " << integer_to_wstring(key.GetPublicElement().y) << endl;
}
void SavePrivateKey(const string &filename, const CryptoPP::ECDSA<ECP, SHA1>::PrivateKey &key)
{
key.Save(FileSink(filename.c_str(), true /*binary*/).Ref());
}
void SavePublicKey(const string &filename, const CryptoPP::ECDSA<ECP, SHA1>::PublicKey &key)
{
key.Save(FileSink(filename.c_str(), true /*binary*/).Ref());
}
void LoadPrivateKey(const string &filename, CryptoPP::ECDSA<ECP, SHA1>::PrivateKey &key)
{
key.Load(FileSource(filename.c_str(), true /*pump all*/).Ref());
}
void LoadPublicKey(const string &filename, CryptoPP::ECDSA<ECP, SHA1>::PublicKey &key)
{
key.Load(FileSource(filename.c_str(), true /*pump all*/).Ref());
}
bool SignMessage(const CryptoPP::ECDSA<ECP, SHA1>::PrivateKey &key, const string &message, string &signature)
{
AutoSeededRandomPool prng;
signature.erase();
StringSource(message, true,
new SignerFilter(prng,
CryptoPP::ECDSA<ECP, SHA1>::Signer(key),
new StringSink(signature)) // SignerFilter
); // StringSource
return !signature.empty();
}
bool VerifyMessage(const CryptoPP::ECDSA<ECP, SHA1>::PublicKey &key, const string &message, const string &signature)
{
bool result = false;
StringSource(signature + message, true,
new SignatureVerificationFilter(
CryptoPP::ECDSA<ECP, SHA1>::Verifier(key),
new ArraySink((byte *)&result, sizeof(result))) // SignatureVerificationFilter
);
return result;
}
/* Convert interger to wstring */
wstring integer_to_wstring(const CryptoPP::Integer &t)
{
std::ostringstream oss;
oss.str("");
oss.clear();
oss << t; // pumb t to oss
std::string encoded(oss.str()); // to string
std::wstring_convert<codecvt_utf8<wchar_t>> towstring;
return towstring.from_bytes(encoded); // string to wstring
}
/* convert string to wstring */
wstring string_to_wstring(const std::string &str)
{
wstring_convert<codecvt_utf8<wchar_t>> towstring;
return towstring.from_bytes(str);
}
/* convert wstring to string */
string wstring_to_string(const std::wstring &str)
{
wstring_convert<codecvt_utf8<wchar_t>> tostring;
return tostring.to_bytes(str);
}
/* convert wstring hex to string */
string wstring_hex_to_string(wstring wstr)
{
string str;
StringSource(wstring_to_string(wstr), true, new HexDecoder(new StringSink(str)));
return str;
}
string Input_Message()
{
do
{
wcout << endl;
wcout << "[+] Input Message\n";
wcout << "[1] Message from file\n";
wcout << "[2] Message from key board\n";
wcout << "Enter option: ";
int option;
wcin >> option;
if (option == 1)
{
wcout << "Enter file name: ";
wstring filename;
#ifdef __linux__
__fpurge(stdin);
#elif _WIN32
fflush(stdin);
#else
#endif
getline(wcin, filename);
std::ifstream file;
file.open((wstring_to_string(filename)));
if (!file.is_open())
{
wcout << "Can not open file!\n";
continue;
}
string message;
#ifdef __linux__
__fpurge(stdin);
#elif _WIN32
fflush(stdin);
#else
#endif
getline(file, message);
return message;
}
else if (option == 2)
{
wstring message;
wcout << "Enter Message: ";
#ifdef __linux__
__fpurge(stdin);
#elif _WIN32
fflush(stdin);
#else
#endif
getline(wcin, message);
return wstring_to_string(message);
}
else
{
wcout << "Invalid Option!" << endl;
}
} while (1);
}
string Input_Signature()
{
do
{
wcout << endl;
wcout << "[+] Input Signature\n";
wcout << "[1] Signature from file\n";
wcout << "[2] Signature from key board\n";
wcout << "Enter option: ";
int option;
wcin >> option;
if (option == 1)
{
wcout << "Enter file name: ";
wstring filename;
#ifdef __linux__
__fpurge(stdin);
#elif _WIN32
fflush(stdin);
#else
#endif
getline(wcin, filename);
std::ifstream file;
file.open((wstring_to_string(filename)));
if (file.is_open() == false)
{
wcout << "Can not open file!\n";
continue;
}
string signature;
#ifdef __linux__
__fpurge(stdin);
#elif _WIN32
fflush(stdin);
#else
#endif
getline(file, signature);
return signature;
}
else if (option == 2)
{
wstring signature;
wcout << "Enter Signature: ";
#ifdef __linux__
__fpurge(stdin);
#elif _WIN32
fflush(stdin);
#else
#endif
getline(wcin, signature);
return wstring_hex_to_string(signature);
}
else
{
wcout << "Invalid Option!" << endl;
}
} while (1);
}
void Sign()
{
string message, signature;
// private key for signing
CryptoPP::ECDSA<ECP, SHA1>::PrivateKey privateKey;
wcout << endl;
wcout << "[+] Signing\n";
message = Input_Message();
Input_PrivateKey(privateKey);
wcout << endl;
wcout << "Message: " << string_to_wstring(message) << endl;
PrintPrivateKey(privateKey);
string hex_signature;
int loop = 10000;
bool result;
int start_s = clock();
while (loop--)
{
result = SignMessage(privateKey, message, signature);
if (result == false)
{
break;
}
if (loop != 0)
{
signature.clear();
}
}
int stop_s = clock();
double etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
if (result == true)
{
wcout << endl;
wcout << "Successfully Signing Message!" << endl
<< endl;
StringSource(signature, true, new HexEncoder(new StringSink(hex_signature)));
wcout << "Signature(hex): " << string_to_wstring(hex_signature) << endl;
wcout << "Total excecution time for 10000 loop: " << etime << "ms" << endl;
wcout << "Average execution time for 10000 loop: " << etime / 10000 << "ms" << endl;
}
else
{
wcout << "Failure Signing Message!" << endl;
}
}
void Verify()
{
string message, signature;
// Public keys for verifying
CryptoPP::ECDSA<ECP, SHA1>::PublicKey publicKey;
wcout << endl;
wcout << "[+] Verifying" << endl;
message = Input_Message();
signature = Input_Signature();
wcout << "Input the file name of public key: ";
#ifdef __linux__
__fpurge(stdin);
#elif _WIN32
fflush(stdin);
#else
#endif
wstring key_filename;
getline(wcin, key_filename);
// Load key in PKCS#9 and X.509 format
LoadPublicKey(wstring_to_string(key_filename), publicKey);
wcout << "Message: " << string_to_wstring(message) << endl;
string hex_signature;
StringSource(signature, true, new HexEncoder(new StringSink(hex_signature)));
wcout << "Signature(hex): " << string_to_wstring(hex_signature) << endl;
PrintPublicKey(publicKey);
int loop = 10000;
bool result;
int start_s = clock();
while (loop--)
{
result = VerifyMessage(publicKey, message, signature);
if (result == false)
{
break;
}
}
int stop_s = clock();
double etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
if (result == true)
{
wcout << endl;
wcout << "Successfully Verify Message!" << endl;
wcout << "Signature(hex): " << string_to_wstring(hex_signature) << endl;
wcout << "Total excecution time for 10000 loop: " << etime << "ms" << endl;
wcout << "Average execution time for 10000 loop: " << etime / 10000 << "ms" << endl;
}
else
{
wcout << "Failure Verify Message!";
}
}
void Input_PrivateKey(ECDSA<ECP, SHA1>::PrivateKey &key)
{
do
{
wcout << endl;
wcout << "[+] Input Private Key\n";
wcout << "[1] Key from file\n";
wcout << "[2] Random key and save to file\n";
wcout << "Enter Option: ";
int option;
wcin >> option;
if (option == 1)
{
wcout << "Input the file name of private key: ";
wstring key_filename;
#ifdef __linux__
__fpurge(stdin);
#elif _WIN32
fflush(stdin);
#else
#endif
getline(wcin, key_filename);
// Load key in PKCS#9 and X.509 format
LoadPrivateKey(wstring_to_string(key_filename), key);
return;
}
else if (option == 2)
{
// Generate random Keys
bool result = GeneratePrivateKey(CryptoPP::ASN1::secp160r1(), key);
if (result == true)
{
wcout << "Successfully generate key!\n";
wcout << "Input the file name to save private key: ";
wstring key_filename;
#ifdef __linux__
__fpurge(stdin);
#elif _WIN32
fflush(stdin);
#else
#endif
getline(wcin, key_filename);
// Save key in PKCS#9 and X.509 format
SavePrivateKey(wstring_to_string(key_filename), key);
CryptoPP::ECDSA<ECP, SHA1>::PublicKey publicKey;
bool result_pubKey = GeneratePublicKey(key, publicKey);
if (result_pubKey == true)
{
wcout << "Succesfully generate public key from private key\n";
wcout << "Input the file name to save public key: ";
key_filename.clear();
#ifdef __linux__
__fpurge(stdin);
#elif _WIN32
fflush(stdin);
#else
#endif
getline(wcin, key_filename);
SavePublicKey(wstring_to_string(key_filename), publicKey);
}
return;
}
else
{
wcout << "Failure generate key!\n";
continue;
}
}
else
{
wcout << "Invalid option!\n";
}
} while (1);
}
<file_sep># Task 1: Two collision messages have the same prefix string
## tạo file prefix
Tạo file prefix với 64 ký tự (63 ký tự 'A' và 1 ký tự kết thúc chuỗi)
```bash
python -c "print('A'*63)" > collision_text.txt
```

## Chạy collision với `md5collgen`:

## Kiểm tra collision của 2 file

## Kiểm tra sự khác nhau của hai file


# Seed lab report
```c
#include <iostream>
unsigned char xyz[200] = {
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41};
int main()
{
for (int i = 0; i < 200; i++)
{
std::cout << xyz[i] << " ";
}
std::cout << std::endl;
}
```
## Compile program chạy thử chương trình


## Cách khai thác

## Tạo prefix
Tìm vị trí của mảng `xyz` chia hết cho `64`:

vị trí của mảng [0x3060-0x3028]
=> vị trí kết thúc của prefix sẽ là 0x3080 % 64 == 0
`0x3080 = 12416`

## Tạo suffix
Phần collision sẽ có độ dài `128` bytes, nên phần suffix sẽ từ vị trí kết thúc của prefix cộng với 128 bytes (12416 + 128 = 12544)

## Chạy collision để generate ra hai file P và Q

Lấy phần P, Q 128 bit từ 2 file collision vừa mới được tạo:

## Nối prefix , P/Q , suffix lại với nhau

-> Chạy 2 file collision:

## Kiểm tra hash md5 của 2 file

# Task 2 : Chosen prefix attack - hai file code khác nhau có cùng hash md5
Code chương trình 1:
```c
#include <stdio.h>
int main()
{
printf("GoodGood Program !!\n");
}
```
Code chương trình 2:
```c
#include <stdio.h>
int main()
{
printf("Bad Program !!\n");
}
```
## compile thành 2 file thực thi


## Chạy hai file thực thi

## Chạy tool hashclash - chosen prefix attack

## Kết quả
thời gian chạy => gần 18h


## kiểm tra hash md5
-> md5 của 2 file sau khi chạy collision:

-> md5 của 2 file ban đầu:

<file_sep>#include <iostream>
#include <iostream>
using std::cerr;
using std::endl;
using std::string;
using std::wcin;
using std::wcout;
using std::wstring;
/* Vietnamese support */
/* Set _setmode()*/
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#else
#include <stdio_ext.h> // _fpurge(stdin) == fflush(stdin)
#endif
/* String convert */
#include <locale>
using std::wstring_convert;
#include <codecvt>
using std::codecvt_utf8;
#include "cryptopp/sha.h"
using CryptoPP::SHA224;
using CryptoPP::SHA256;
using CryptoPP::SHA384;
using CryptoPP::SHA512;
#include "cryptopp/sha3.h"
using CryptoPP::SHA3_224;
using CryptoPP::SHA3_256;
using CryptoPP::SHA3_384;
using CryptoPP::SHA3_512;
#include "cryptopp/shake.h"
using CryptoPP::SHAKE128;
using CryptoPP::SHAKE256;
#include "cryptopp/cryptlib.h"
using CryptoPP::DecodingResult;
using CryptoPP::Exception;
#include "cryptopp/filters.h"
using CryptoPP::HashFilter;
using CryptoPP::Redirector;
using CryptoPP::StringSink;
using CryptoPP::StringSource;
#include "cryptopp/files.h"
using CryptoPP::FileSink;
using CryptoPP::FileSource;
#include "cryptopp/hex.h"
using CryptoPP::HexDecoder;
using CryptoPP::HexEncoder;
//#include"cryptopp/buffrt
using namespace std;
/* Vietnames convert function def*/
/* convert string to wstring */
wstring string_to_wstring(const std::string &str)
{
wstring_convert<codecvt_utf8<wchar_t>> towstring;
return towstring.from_bytes(str);
}
/* convert wstring to string */
string wstring_to_string(const std::wstring &str)
{
wstring_convert<codecvt_utf8<wchar_t>> tostring;
return tostring.to_bytes(str);
}
template <typename T>
void Hash(string msg)
{
T hash;
wcout << "Name: " << string_to_wstring(hash.AlgorithmName()) << endl;
wcout << "Digest size: " << hash.DigestSize() << endl;
wcout << "Block size: " << hash.BlockSize() << endl;
string digest;
int loop = 10000;
int start_s = clock();
while (loop--)
{
digest.clear();
StringSource(msg, true, new HashFilter(hash, new StringSink(digest))); // StringSource
}
int stop_s = clock();
double etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
wcout << "Message: " << string_to_wstring(msg) << endl;
wcout << "Digest: " << endl;
string hash_result;
StringSource(digest, true, new HexEncoder(new StringSink(hash_result)));
wcout << string_to_wstring(hash_result) << endl;
wcout << endl;
wcout << "[+] Performance\n";
wcout << "Total execution time for 10.000 loop: " << etime << "ms\n";
wcout << "Average execution time: " << etime / 10000 << "ms" << endl;
}
template <typename T>
void Hash_Shake(string msg)
{
T hash;
while (1)
{
wcout << endl;
wcout << "Enter output length for SHAKE: ";
int size;
wcin >> size;
if (size > 0)
{
T shake(size);
hash = shake;
break;
}
wcout << endl;
wcout << "Invalid Input!!\n";
}
wcout << "Name: " << string_to_wstring(hash.AlgorithmName()) << endl;
wcout << "Digest size: " << hash.DigestSize() << endl;
wcout << "Block size: " << hash.BlockSize() << endl;
string digest;
int loop = 10000;
int start_s = clock();
while (loop--)
{
digest.clear();
StringSource(msg, true, new HashFilter(hash, new StringSink(digest))); // StringSource
}
int stop_s = clock();
double etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
wcout << "Message: " << string_to_wstring(msg) << endl;
wcout << "Digest: " << endl;
string hash_result;
StringSource(digest, true, new HexEncoder(new StringSink(hash_result)));
wcout << string_to_wstring(hash_result) << endl;
wcout << endl;
wcout << "[+] Performance\n";
wcout << "Total execution time for 10.000 loop: " << etime << "ms\n";
wcout << "Average execution time: " << etime / 10000 << "ms" << endl;
}
int main()
{
/*Set mode support Vietnamese*/
#ifdef __linux__
setlocale(LC_ALL, "");
#elif _WIN32
_setmode(_fileno(stdin), _O_U16TEXT);
_setmode(_fileno(stdout), _O_U16TEXT);
#else
#endif
wcout << "~~ Welcome to hash algorithm ~~";
int options_algo;
while (1)
{
wcout << endl;
wcout << "[+] Hash Algorithm Selection: " << endl;
wcout << "[1] SHA224\n";
wcout << "[2] SHA256\n";
wcout << "[3] SHA384\n";
wcout << "[4] SHA512\n";
wcout << "[5] SHA3-224\n";
wcout << "[6] SHA3-256\n";
wcout << "[7] SHA3-384\n";
wcout << "[8] SHA3-512\n";
wcout << "[9] SHAKE128\n";
wcout << "[10] SHAKE256\n";
wcout << "Enter option: ";
wcin >> options_algo;
if (options_algo >= 1 && options_algo <= 10)
{
break;
}
wcout << endl;
wcout << "Invalid options!!\n";
}
int options_input;
while (1)
{
wcout << endl;
wcout << "[+] Input message\n";
wcout << "[1] Input from key board\n";
wcout << "[2] Input from file\n";
wcout << "Enter option: ";
wcin >> options_input;
if (options_input == 1 || options_input == 2)
{
break;
}
wcout << endl;
wcout << "Invalid Options" << endl;
}
wstring w_input;
string msg;
if (options_input == 1)
{
wcout << endl;
wcout << "Enter message: ";
#ifdef __linux__
__fpurge(stdin);
#elif _WIN32
fflush(stdin);
#else
#endif
getline(wcin, w_input);
msg = wstring_to_string(w_input);
}
else
{
wcout << endl;
wcout << "Enter filename: ";
#ifdef __linux__
__fpurge(stdin);
#elif _WIN32
fflush(stdin);
#else
#endif
getline(wcin, w_input);
string filename = wstring_to_string(w_input);
FileSource file_to_str((const char *)(filename.data()), true, new StringSink(msg));
}
switch (options_algo)
{
case 1:
Hash<SHA224>(msg);
break;
case 2:
Hash<SHA256>(msg);
break;
case 3:
Hash<SHA384>(msg);
break;
case 4:
Hash<SHA512>(msg);
break;
case 5:
Hash<SHA3_224>(msg);
break;
case 6:
Hash<SHA3_256>(msg);
break;
case 7:
Hash<SHA3_384>(msg);
break;
case 8:
Hash<SHA3_512>(msg);
break;
case 9:
Hash_Shake<SHAKE128>(msg);
break;
case 10:
Hash_Shake<SHAKE256>(msg);
break;
}
return 0;
}<file_sep>// Sample.cpp
#include "cryptopp/rsa.h"
using CryptoPP::Integer;
using CryptoPP::InvertibleRSAFunction;
using CryptoPP::RSA;
using CryptoPP::RSAES_OAEP_SHA_Decryptor;
using CryptoPP::RSAES_OAEP_SHA_Encryptor;
#include "cryptopp/sha.h"
using CryptoPP::SHA512;
#include "cryptopp/filters.h"
using CryptoPP::PK_DecryptorFilter;
using CryptoPP::PK_EncryptorFilter;
using CryptoPP::StringSink;
using CryptoPP::StringSource;
#include "cryptopp/files.h"
using CryptoPP::FileSink;
using CryptoPP::FileSource;
#include "cryptopp/queue.h" // using for load function
using CryptoPP::ByteQueue;
#include "cryptopp/cryptlib.h"
using CryptoPP::BufferedTransformation;
using CryptoPP::DecodingResult;
using CryptoPP::Exception;
#include "cryptopp/osrng.h"
using CryptoPP::AutoSeededRandomPool;
#include "cryptopp/secblock.h"
using CryptoPP::SecByteBlock;
#include "cryptopp/cryptlib.h"
using CryptoPP::DecodingResult;
using CryptoPP::Exception;
#include <string>
using std::string;
using std::wstring;
#include <exception>
using std::exception;
#include <fstream>
#include <ctime>
#include <iostream>
using std::cerr;
using std::endl;
using std::wcin;
using std::wcout;
/* Convert to hex */
#include <cryptopp/hex.h>
using CryptoPP::HexDecoder;
using CryptoPP::HexEncoder;
#include <assert.h>
/* Vietnamese support */
/* Set _setmode()*/
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#else
#include <stdio_ext.h> // _fpurge(stdin) == fflush(stdin)
#endif
/* String convert */
#include <locale>
using std::wstring_convert;
#include <codecvt>
using std::codecvt_utf8;
/* Integer convert */
#include <sstream>
using std::ostringstream;
/* Vietnames convert function def*/
wstring string_to_wstring(const std::string &str);
string wstring_to_string(const std::wstring &str);
wstring integer_to_wstring(const CryptoPP::Integer &t);
string wstring_hex_to_string(wstring wstr);
void Print_Option();
bool Input_Key(RSA::PrivateKey &priKey, RSA::PublicKey &pubKey, int option);
bool Input_str(string &plaintext, wstring type, int option);
bool Input_Plaintext(string &plaintext);
void LoadPrivateKey(const string &filename, RSA::PrivateKey &key);
void LoadPublicKey(const string &filename, RSA::PublicKey &key);
void Load(const string &filename, BufferedTransformation &bt);
void PrintKey(RSA::PrivateKey, RSA::PublicKey);
void Encryption();
void Decryption();
int main(int argc, char *argv[])
{
try
{
/*Set mode support Vietnamese*/
#ifdef __linux__
setlocale(LC_ALL, "");
#elif _WIN32
_setmode(_fileno(stdin), _O_U16TEXT);
_setmode(_fileno(stdout), _O_U16TEXT);
#else
#endif
wcout << "~Welcome to RSA encryption and decryption~\n";
// RSA key
do
{
wcout << endl;
wcout << "[1] Encryption\n";
wcout << "[2] Decryption\n";
wcout << "[3] Exit\n";
wcout << "Enter option: ";
int option;
wcin >> option;
if (option == 1)
{
Encryption();
}
else if (option == 2)
{
Decryption();
}
else if (option == 3)
{
break;
}
else
{
wcout << "Enter invalid option!" << endl;
}
} while (1);
return 0;
}
catch (CryptoPP::Exception &e)
{
cerr << "Caught Exception..." << endl;
cerr << e.what() << endl;
}
return 0;
}
/* Convert interger to wstring */
wstring integer_to_wstring(const CryptoPP::Integer &t)
{
std::ostringstream oss;
oss.str("");
oss.clear();
oss << t; // pumb t to oss
std::string encoded(oss.str()); // to string
std::wstring_convert<codecvt_utf8<wchar_t>> towstring;
return towstring.from_bytes(encoded); // string to wstring
}
/* convert string to wstring */
wstring string_to_wstring(const std::string &str)
{
wstring_convert<codecvt_utf8<wchar_t>> towstring;
return towstring.from_bytes(str);
}
/* convert wstring to string */
string wstring_to_string(const std::wstring &str)
{
wstring_convert<codecvt_utf8<wchar_t>> tostring;
return tostring.to_bytes(str);
}
/* convert wstring hex to string */
string wstring_hex_to_string(wstring wstr)
{
string str;
StringSource(wstring_to_string(wstr), true, new HexDecoder(new StringSink(str)));
return str;
}
// convert string to char array and append '.'
char *string_to_char_array(string str)
{
char *char_array = new char[str.length() + 1];
for (long long i = 0; i < str.length(); i++)
{
char_array[i] = str[i];
}
char_array[str.length()] = str[str.length() - 1] != '.' ? '.' : '\0';
char_array[str.length() + 1] = '\0';
return char_array;
}
void Print_Option(int section)
{
if (section == 0)
{
wcout << endl;
wcout << "[+] Key Receive:\n";
wcout << "[1] Default key\n";
wcout << "[2] Input Key from keyboard\n";
wcout << "[3] Key from file\n";
wcout << "[4] Random Key\n";
wcout << "Enter option: ";
}
else if (section == 1)
{
wcout << endl;
wcout << "[+] Plaintext Receive:\n";
wcout << "[1] Plaintext from file\n";
wcout << "[2] Plaintext from keyboard\n";
wcout << "Enter opiton: ";
}
else if (section == 2)
{
wcout << endl;
wcout << "[+] Ciphertext Receive:\n";
wcout << "[1] Ciphertext from file\n";
wcout << "[2] Ciphertext from keyboard\n";
wcout << "Enter option: ";
}
else
{
}
}
Integer Input_Integer_From_KeyBoard(wstring type)
{
wcout << "Enter " << type << ": ";
#ifdef __linux__
__fpurge(stdin);
#elif _WIN32
fflush(stdin);
#else
#endif
wstring input;
getline(wcin, input);
Integer integer(string_to_char_array(wstring_to_string(input)));
return integer;
;
}
bool Input_Key(RSA::PrivateKey &priKey, RSA::PublicKey &pubKey, int option)
{
if (option == 1 || option == 2)
{
// Set default modulo in code
Integer n("4846410981144595834051566307490793697381343896224710423128515628951343458217231117432037874252600232840996183552970048297986488188077212226244686792678057510734086278546352866101187776283926699092190643468913702315967984564867051913961835489436793116464418031424835218880235184075752435084079040373932656542050632709779700538736237481952776369994823896881762875619376785125692612493931034480972363873195673281720181111896083663492650028098192854319428842352323208728652701451400150446427548974361249198594957458941121363996876490135995581669451857102327529952024078156827071590404325636682681842593578649382641424451537687916117096935551152203607652535408251516355166534540329966091264741785402970205399012778046815242736858622808551846612925327734555015748053192087589853558127112227541329078614945997264668978146192449975991441935360429784773924913605717344705581056878453562513827359652499732347965341757590409672383219933.");
// Set default p,q
Integer p("2070041337034921162083149572169930905375665857341387930631606457952881812959985939315117403539808215905534338350286302749873463300394964715420809343362978363357871095075579915306717299023788102891659001126038509582944578243570793780825890549031768986988853311731150342900713127939250537300968543513429024102417337016382187107144610745591752463844642204732806600050931639014658798658617988045429549118623796934485365988721720080167283164595860423130919045683404661.");
Integer q("2341214590471165020926482158414312505571165874936027838531308736896735499739752709215989928389807974542676541607320997432574075625871271930319215562429145521236547166843162573292918248089821014141403708229086442238417585194753085774976029937581092301900807950973951749913072766389992103094819480113474772526791149579575731620125983708319098785757574178955909279022659413859729915918259266841253082118955820267540000743077430464879671865311320495317535490933898953.");
// Set default exponential
Integer e("17.");
// Set default private exponnential
Integer d("427624498336287867710432321249187679180706814372768566746633731966295011019167451538120988904641197015382016195850298379234101898947989314080413540530416839182419377518795841126575392025052355802252115600198267851408939814547092815937809013773834686746860414537485460489432516241978156036830503562405822636063291121451150047535550366054656738528955049724861430201709716334619936396523326571850502694693735877798839509873183852661116178949840545969361368442852047439770303583410055950305513387363338669273225751311060488330736615339883783699776764058381964735514732054054157116156247928453860786149141139060976673440675272955693103958211401697181812258202166334145218653787221347405396448638751220731021682345596287551306542957710212181828111419273014049505096437202143586329840984203718887513308326630530741184861397388302669222136689944800311504205181091298247176597618508370216061312568304656822181602426983113688449933793.");
if (option == 2)
{
n = Input_Integer_From_KeyBoard(L"Modulo");
p = Input_Integer_From_KeyBoard(L"Prime p");
q = Input_Integer_From_KeyBoard(L"Prime q");
e = Input_Integer_From_KeyBoard(L"Public exponential");
d = Input_Integer_From_KeyBoard(L"Private exponential");
}
priKey.SetModulus(n);
priKey.SetPrime1(p);
priKey.SetPrime2(q);
priKey.SetPublicExponent(e);
priKey.SetPrivateExponent(d);
priKey.SetModPrime1PrivateExponent(d % (p - 1));
priKey.SetModPrime2PrivateExponent(d % (q - 1));
priKey.SetMultiplicativeInverseOfPrime2ModPrime1(q.InverseMod(p));
// Create public key from private key
pubKey = RSA::PublicKey(priKey);
}
else if (option == 4)
{
// Generate keys
AutoSeededRandomPool rng;
InvertibleRSAFunction parameters;
parameters.GenerateRandomWithKeySize(rng, 3072);
priKey = RSA::PrivateKey(parameters);
pubKey = RSA::PublicKey(parameters);
}
else if (option == 3)
{
LoadPublicKey(".\\rsa-public.key", pubKey);
LoadPrivateKey(".\\rsa-private.key", priKey);
return true;
}
else
{
wcout << "Enter invalid option\n";
return false;
}
return true;
}
void LoadPrivateKey(const string &filename, RSA::PrivateKey &key)
{
ByteQueue queue;
Load(filename, queue);
key.Load(queue);
}
void LoadPublicKey(const string &filename, RSA::PublicKey &key)
{
ByteQueue queue;
Load(filename, queue);
key.Load(queue);
}
void Load(const string &filename, BufferedTransformation &bt)
{
FileSource file(filename.c_str(), true /*pumpAll*/);
file.TransferTo(bt);
bt.MessageEnd();
}
void PrintKey(RSA::PrivateKey privateKey, RSA::PublicKey publicKey)
{
wcout << endl;
wcout << "RSA parameters:" << endl;
wcout << "Public modulo n=" << integer_to_wstring(publicKey.GetModulus()) << endl
<< endl;
wcout << "Public key e=" << integer_to_wstring(publicKey.GetPublicExponent()) << endl
<< endl;
wcout << "Private prime number p=" << integer_to_wstring(privateKey.GetPrime1()) << endl
<< endl;
wcout << "Private prime number q=" << integer_to_wstring(privateKey.GetPrime2()) << endl
<< endl;
wcout << "Secret key d=" << integer_to_wstring(privateKey.GetPrivateExponent()) << endl
<< endl;
}
void Encryption()
{
AutoSeededRandomPool rng;
RSA::PrivateKey privateKey;
RSA::PublicKey publicKey;
string plaintext, recovered, ciphertext;
int section = 0;
do
{
Print_Option(section);
int option;
wcin >> option;
if (section == 0)
{
if (Input_Key(privateKey, publicKey, option))
{
section += 1;
continue;
}
}
if (section == 1)
{
if (Input_str(plaintext, L"plaintext", option))
{
section += 1;
break;
}
}
} while (1);
wcout << "Plaintext: " << string_to_wstring(plaintext) << endl;
// Encryption
PrintKey(privateKey, publicKey);
RSAES_OAEP_SHA_Encryptor e(publicKey); // RSAES_PKCS1v15_Decryptor
int loop = 10000;
int start_s = clock();
while (loop--)
{
ciphertext.clear();
StringSource(plaintext, true,
new PK_EncryptorFilter(rng, e,
new StringSink(ciphertext)) // PK_EncryptorFilter
); // StringSource
}
int stop_s = clock();
double etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
string encoded;
encoded.clear();
StringSource(ciphertext, true,
new HexEncoder(new StringSink(encoded)));
wcout << endl;
wcout << "[+] Ciphertext: " << string_to_wstring(encoded) << endl;
wcout << "Total excecution time for 10000 loop: " << etime << "ms" << endl;
wcout << "Average execution time for 10000 loop: " << etime / 10000 << "ms" << endl;
}
void Decryption()
{
RSA::PrivateKey privateKey;
AutoSeededRandomPool rng;
RSA::PublicKey publicKey;
string recovered, ciphertext;
int section = 0;
do
{
Print_Option(section);
int option;
wcin >> option;
if (section == 0)
{
if (Input_Key(privateKey, publicKey, option))
{
section += 2;
continue;
}
}
if (section == 2)
{
if (Input_str(ciphertext, L"ciphertext", option))
{
section += 2;
break;
}
}
} while (1);
// Decryption
RSAES_OAEP_SHA_Decryptor d(privateKey);
int loop = 10000;
int start_s = clock();
while (loop--)
{
recovered.clear();
StringSource(ciphertext, true,
new PK_DecryptorFilter(rng, d,
new StringSink(recovered)) // PK_EncryptorFilter
); // StringSource
}
int stop_s = clock();
double etime = (stop_s - start_s) / double(CLOCKS_PER_SEC) * 1000;
// StringSource
wcout << endl;
wcout << "[+] Recover text: " << string_to_wstring(recovered) << endl;
wcout << "Total excecution time for 10000 loop: " << etime << "ms" << endl;
wcout << "Average execution time for 10000 loop: " << etime / 10000 << "ms" << endl;
}
bool Input_str(string &plaintext, wstring type, int option)
{
if (option == 1)
{
wcout << endl;
wcout << "[+] Enter " << type << " from file:\n";
wcout << "Enter " << type << " file name: ";
#ifdef __linux__
__fpurge(stdin);
#elif _WIN32
fflush(stdin);
#else
#endif
wstring filename_wstr;
getline(wcin, filename_wstr);
string filename = wstring_to_string(filename_wstr);
std::ifstream file;
file.open(filename);
if (!file.is_open())
{
wcout << L"File " << filename_wstr << L" không tồn tại" << endl;
exit(0);
}
string plain;
string line;
while (file.good())
{
getline(file, line);
plain += line;
}
if (wstring_to_string(type) == "ciphertext")
{
plain = wstring_hex_to_string(string_to_wstring(plain));
}
plaintext = plain;
}
else if (option == 2)
{
wcout << endl;
wcout << "[+] Enter " << type << " from keyboard:\n";
wcout << "Enter " << type << ": ";
wstring w_plaintext;
w_plaintext.clear();
#ifdef __linux__
__fpurge(stdin);
#elif _WIN32
fflush(stdin);
#else
#endif
getline(wcin, w_plaintext);
if (wstring_to_string(type) == "ciphertext")
{
plaintext = wstring_hex_to_string(w_plaintext);
}
else
{
plaintext = wstring_to_string(w_plaintext);
}
}
else
{
wcout << "Enter invalid option\n";
return false;
}
return true;
}
<file_sep>#include "AES_without_lib.h"
// library for unicode in C++
#include <fcntl.h> // _O_WTEXT
#include <io.h> //_setmode()
#include <locale>
#include <codecvt>
using std::wstring;
// convert string to wstring (ASCII to utf8)
wstring string_to_wstring(string str)
{
return std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(str);
}
// convert wstring(utf8) to string (ASCII)
string wstring_to_string(wstring wstr)
{
return std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(wstr);
}
// trim character rigth in string
string Trim_right(string str, char c)
{
while (str[str.length() - 1] == c)
{
str.erase(str.length() - 1, 1);
}
return str;
}
int main()
{
_setmode(_fileno(stdout), _O_WTEXT); // needed for output unicode
_setmode(_fileno(stdin), _O_WTEXT); // needed for input unicode
wstring plaintext = L"Welcome the AES encryption and decryption!";
AES aes;
wcout
<< plaintext << endl;
wcout << "[+] Input plaintext to encryption: ";
fflush(stdin);
getline(wcin, plaintext);
wstring wkey;
string key;
wcout << endl;
do
{
wcout << "[+] Enter key: ";
fflush(stdin);
getline(wcin, wkey);
key = ASCII_to_Hexadecimal(wstring_to_string(wkey));
} while (!aes.Key_setter(key));
wstring wiv;
string iv;
wcout << endl;
do
{
wcout << "[+] Enter iv: ";
fflush(stdin);
getline(wcin, wiv);
iv = ASCII_to_Hexadecimal(wstring_to_string(wiv));
} while (!aes.Iv_setter(iv));
wcout << endl;
wcout << "Key(hex): " << string_to_wstring(aes.Key_getter()) << endl
<< endl;
wcout << "Iv(hex): " << string_to_wstring(aes.Iv_getter()) << endl
<< endl;
wcout << "Plaintext(utf8): " << plaintext << endl
<< endl;
wcout << "\n-----Encryption-----\n";
wcout << "Plaintext (hex): " << string_to_wstring(ASCII_to_Hexadecimal(wstring_to_string(plaintext))) << endl
<< endl;
string ciphertext = aes.Encryption(wstring_to_string(plaintext));
wcout << "Ciphertext (hex): " << string_to_wstring(ciphertext) << endl
<< endl;
wcout << "\n-----Decryption-----\n";
wcout << "Ciphertext (hex): " << string_to_wstring(ciphertext) << endl
<< endl;
string encrypted = aes.Decryption(ciphertext);
wcout << "Recovered (hex): " << string_to_wstring(encrypted) << endl
<< endl;
wcout << "Recorvered ciphertext(utf8): " << string_to_wstring(Hexadecimal_to_ASCII(encrypted)) << endl;
return 0;
}
//test-> Input iterators to the initial and final positions in a range. The range used is [first,last), which includes all the characters between first and last, including the character pointed by first but not the character pointed by last.The function template argument InputIterator shall be an input iterator type that points to elements of a type convertible to char.
<file_sep># Crypto_Lab
# Lab01
Code DES and AES with library cryptopp
Task 1: Coding DES, AES using cryptopp library
Required:
+) Plaintext:
- Input from screen;
- Support Vietnamse (using setmod, UTF-16)
+) Mode of operations:
- Select mode from screen (using switch case)
- Support modes: ECB, CBC, OFB, CFB, CTR, XTS, CCM, GCM.
+) Secret key and Initialization Vector (IV) select from screen (using switch case)
Case 1: Secret key and IV are randomly chosen for each run time using random generator using CryptoPP::AutoSeededRandomPool;
Case 2: Input Secret Key and IV from screen
Case 3: Input Secret Key and IV from file
+) OS platform
- Your code can compile on both Windows and Linux;
+) Performance
- Report your hardware resources
- Report computation performance for all operations on both Windows and Linux
[Performance](Lab01/README.md)
# Lab02
Code DES and DES with out library
Required:
+) Plaintext:
- Input from screen;
- Support Vietnamese (using _setmode, UTF-16)
+) Mode of operations
Using CBC mode
+) Secret key and Initialization Vector (IV)
Input Secret Key and IV from screen
# Lab03
Code RSA Cipher (Encryption/Decryption) using CryptoPP
Required:
+) Separation Encryption function and Decryption function (using switch case)
+) Plaintext:
- Support Vietnamese (UTF-16)
- Input from screen or from file (using switch case)
+) Cyphertext:
- Input from screen or from file (using switch case)
+) Secret key/public key
- The keys load from files (for both two functions)
- The public key: >= 3072 bits
+) OS platforms
- Your code can compile on both Windows and Linux
+) Performance
- Report your hardware resources
- Report computation performance for all operations on both Windows and Linux
[Performance](Lab03/README.md)
# Lab04
Code ECC-based Digital signature with CryptoPP
Required:
+) Algorithm: ECDSA
+) Separation the signing function and the verify function (using switch case)
+) signing function; verify function
- May adopt from library or direct compute from formulas. Deploy directly from formulas will get 10/100 bonus points.
+) Message to sign:
- Input from file
- Support Vietnamese (using UTF-16)
+) ECC curve: should select from standard curves
+) Secret key/public key
- The keys load from files (for both two functions)
- The public key: >= 256 bits
+) OS platforms
- Your code can compile on both Windows and Linux
+) Performance
- Report your hardware resources
- Report computation performance for all operations on both Windows and Linux
[Performance](Lab04/README.md)
# Lab05
Required:
+) Separation all hash functions using switch case:
SHA224, SHA256, SHA384, SHA512, SHA3-224, SHA3-256, SHA3-384, SHA3-512, SHAKE128,SHAKE256
+) Plaintext:
- Support Vietnamese (UTF-16)
- Input from screen or from file (using switch case)
+) Digest:
- may choose digest output length d for SHAKE128,SHAKE256 from screen;
- digest should be encoded as hex string;
+) OS platforms
- Your code can compile on both Windows and Linux;
+) Performance
[Perfomance](Lab05/README.md)
- Report your hardware resources
- Report computation performance for all operations on both Windows and Linux
# Lab06
[Report](Lab06/README.md)
Required:
6.1 MD5 collision attacks
+) Two collision messages have the same prefix string
- Generate yourself prefix string
- Compute the two output files that have the same MD5 digest (using hashclash tool)
+) Two different C++ programs but have the same MD5;
- Code yourself two short C++ programs
- Compiler your codes code1, code2
- Run hashclash to generate two program with the same MD5 digest
Note: It takes long time to generate the output.
6.2 Length extension attacks on MAC using SHA256 in form: SHA256(k||m), k is secret key
- This one for bonus 10/100 points (does not require all students)
+) Coding self programs that can
- Automatic compute the padded part for any input (k||m);
- Compute the digest using length extension attacks with any extend string;
<file_sep>#include <iostream>
#include <random>
#include <vector>
#include <algorithm>
#include <math.h>
#include <string>
#include <bitset>
using namespace std;
wstring string_to_wstring(string str);
string wstring_to_string(wstring wstr);
//Substitution box for encryption and key expansion
int Substitution_Box[16][16] = {{0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76},
{0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0},
{0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15},
{0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75},
{0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84},
{0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf},
{0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8},
{0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2},
{0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73},
{0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb},
{0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79},
{0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08},
{0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a},
{0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e},
{0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf},
{0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16}};
// inverse substitution box for decryption
int Substitution_Box_Inverse[16][16] = {{0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb},
{0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb},
{0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e},
{0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25},
{0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92},
{0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84},
{0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06},
{0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b},
{0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73},
{0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e},
{0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b},
{0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4},
{0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f},
{0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef},
{0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61},
{0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d}};
// Galois Field multiplication matrix for encryption
const int GF_Multiplication_Matrix[4][4] = {{0x2, 0x3, 0x1, 0x1},
{0x1, 0x2, 0x3, 0x1},
{0x1, 0x1, 0x2, 0x3},
{0x3, 0x1, 0x1, 0x2}};
// Inverse Galois Field multiplication matrix for decryption
const int GF_Multiplication_Inverse_Matrix[4][4] = {{0xe, 0xb, 0xd, 0x9},
{0x9, 0xe, 0xb, 0xd},
{0xd, 0x9, 0xe, 0xb},
{0xb, 0xd, 0x9, 0xe}};
// polynominal x^8 + x^4 + x^3 + x + 1
const string GF256_Polynominal = "100011011";
// const int n_rounds = 10;
// const int n_k_words = 4;
// const int n_b_words = 4;
// constant round key
const string constant_rounds_key[10] = {"01000000",
"02000000",
"04000000",
"08000000",
"10000000",
"20000000",
"40000000",
"80000000",
"1b000000",
"36000000"};
//Get the hexadecimal value is represent in char
int getHexValue(char c)
{
switch (c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return c - '0';
case 'A':
case 'a':
return 10;
case 'B':
case 'b':
return 11;
case 'C':
case 'c':
return 12;
case 'D':
case 'd':
return 13;
case 'E':
case 'e':
return 14;
case 'F':
case 'f':
return 15;
default:
return -1;
}
}
// Check all character in string is hexadecimal
bool Check_String_All_Hex(string str)
{
for (int i = 0; i < str.length(); i++)
{
if (getHexValue(str[i]) == -1)
{
return false;
}
}
return true;
}
// Hex table is represent all character in hex format
string Hex_Table[16] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};
// convert the binary number to decimal number
int Bin_to_Decimal(string bin)
{
int d = 0;
for (int i = 0; i < bin.length(); i++)
{
d += pow(2, bin.length() - 1 - i) * (bin[i] - '0');
}
return d;
}
// convert the decimal number to binary number
string Decimal_to_Bin(int d, int length)
{
string bin = "";
if (d != 0)
{
while (d > 0)
{
bin = char('0' + d % 2) + bin;
d /= 2;
}
}
while (bin.length() < length)
{
bin = "0" + bin;
}
return bin;
}
// convert the binary number to decimal number
string Bin_to_Hexadecimal(string Bin)
{
string Bin_output = "";
if (Bin.length() == 0)
{
return "0";
}
for (int i = 0; i < Bin.length() / 4; i++)
{
Bin_output += Hex_Table[Bin_to_Decimal(Bin.substr(i * 4, 4))];
}
return Bin_output;
}
// convert Hexadecimal number to binary
string Hexadecimal_to_Bin(string Hex)
{
string Hex_ouput = "";
for (int i = 0; i < Hex.length(); i++)
{
Hex_ouput += Decimal_to_Bin(getHexValue(Hex[i]), 4);
}
return Hex_ouput;
}
// convert ASCII (text) to hexadecimal number
string ASCII_to_Hexadecimal(string text)
{
string bin = "";
for (unsigned char c : text)
{
bin += Decimal_to_Bin(c, 8);
}
return Bin_to_Hexadecimal(bin);
}
// Convert hexadecimal number to ASCII(text)
string Hexadecimal_to_ASCII(string Hex)
{
string Bin = Hexadecimal_to_Bin(Hex);
string ASCII = "";
for (long long i = 0; i < Bin.length() / 8; i++)
{
int c = Bin_to_Decimal(Bin.substr(i * 8, 8));
ASCII += (char)c;
}
return ASCII;
}
// compute the bitwise xor str1 with str2
string Xor(string str1, string str2)
{
string result = "";
for (int i = 0; i < str1.length(); i++)
{
result += (char)(((str1[i] - '0') ^ (str2[i] - '0')) + '0');
}
return result;
}
// shift string left to n_shifts bits
string Shift_Left(string str, int n_shifts)
{
string sh_left = "";
for (int i = 0; i < n_shifts; i++)
{
for (int j = 1; j < 32; j++)
{
sh_left += str[j];
}
sh_left += str[0];
str = sh_left;
sh_left = "";
}
return str;
}
// shift string right to n_shifts bits
string Shift_Right(string str, int n_shifts)
{
string sh_right = "";
for (int i = 0; i < n_shifts; i++)
{
for (int j = 0; j < 31; j++)
{
sh_right += str[j];
}
sh_right = str[31] + sh_right;
str = sh_right;
sh_right = "";
}
return str;
}
// Substitution 32bit word
string Substitution_Word(string word, bool is_inverse)
{
string temp;
for (int i = 0; i < 32; i += 8)
{
//split 4 bits left for row
string row_str = word.substr(i, 4);
int row = Bin_to_Decimal(row_str);
// split 4 bits right for column
string column_str = word.substr(i + 4, 4);
int column = Bin_to_Decimal(column_str);
int map_box;
// Inverse Substitution for decryption
if (is_inverse)
{
map_box = Substitution_Box_Inverse[row][column];
}
// Substitution for encryption
else
{
map_box = Substitution_Box[row][column];
}
temp += Decimal_to_Bin(map_box, 8);
}
return temp;
}
// Compute Key expansion for each round
void Key_Expansion(string key, string Key_Expanded[10])
{
int i = 0;
// Convert key to binary
key = Hexadecimal_to_Bin(key);
// loop for 10 rounds key
while (i < 10)
{
// get last column to preprocess key
string Last_column = key.substr(32 * 3, 32);
// shift left last column
string shift_left = Shift_Left(Last_column, 8);
// Substitution for last column
string Substitution = Substitution_Word(shift_left, 0);
// xor last column with constant rounds key
string Xor_constant_round = Xor(Substitution, Hexadecimal_to_Bin(constant_rounds_key[i]));
// xor each columns with Xor_constant_column
for (int j = 0; j < 4; j++)
{
// xor previous column with current column
Xor_constant_round = Xor(key.substr(j * 32, 32), Xor_constant_round);
// store in Key_Expanded
Key_Expanded[i] += Xor_constant_round;
}
// use the new key round for next key_expand operation
key = Key_Expanded[i];
i++;
}
}
// Read the string with vertically direction
string Read_Vertically(string text_128)
{
string vertically_string = "";
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
vertically_string += text_128.substr(32 * j + i * 8, 8);
}
}
return vertically_string;
}
//Substitution string 128 bits length for encryption and decryption
// is_inverse = 0 -> encryption
// is_inverse = 1 -> decryption
string Sub_Bytes(string plain_128, bool is_inverse)
{
string Substitution = "";
for (int i = 0; i < 4; i++)
{
Substitution += Substitution_Word(plain_128.substr(i * 32, 32), is_inverse);
}
return Substitution;
}
// shift the row left n*8 bits with n is row index (is used for encryption)
string Shift_Row_Left(string plain_128)
{
string shift = "";
for (int i = 0; i < 4; i++)
{
// shift each row 32 bits
shift += Shift_Left(plain_128.substr(i * 32, 32), i * 8);
}
return shift;
}
// shift the row right n*8 bits with n is row index (is used for decryption)
string Shift_Row_Right(string plain_128)
{
string shift = "";
for (int i = 0; i < 4; i++)
{
// shift each row with 32 bits
string sh = Shift_Right(plain_128.substr(i * 32, 32), i * 8);
shift += sh;
}
return shift;
}
// multiplication GF polynominal
string Mul_polynominal(string a, string b)
{
// n is the max degree of multiplication result
const int n = a.length() + b.length();
string result = "";
//set 8 bits 0 for result
for (int i = 0; i < n - 1; i++)
{
result += '0';
}
// implementation multiplication and modulous 2
for (int i = 0; i < a.length(); i++)
{
for (int j = 0; j < b.length(); j++)
{
result[i + j] = (char)(((result[i + j] - '0') + (a[i] - '0') * (b[j] - '0')) % 2 + '0');
}
}
return result;
}
// caculate multiplication Galosi Field 2^8 bit
string GF_256_Mul(string a, string b)
{
// compute multiplication polynominal
string result = Mul_polynominal(a, b);
// Modulous to polynominal x^8 + x^4 + x^3 + x + 1 by xor algorithm
int i = 0;
// Get the first bit 1 poition
for (i = 0; i < 7; i++)
{
if (result[i] == '1')
{
break;
}
}
// if result multiplication > x^8 + x^4 + x^3 + x + 1
if (i < 7)
{
// Implemetation Xor to get the remainder
while (i + 8 <= 14)
{
result = result.substr(0, i) + Xor(result.substr(i, 9), GF256_Polynominal) + result.substr(i + 9, 32 - 9 - i);
while (result[i] != '1' && i < 14)
{
i++;
}
}
}
// strip front to get 8 bits length
while (result.length() > 8)
{
result.replace(0, 1, "");
}
return result;
}
// Mi columsn operation
// is_inverse = 0 -> encryption
// is_inverse = 1 -> decryption
string Mix_Columns(string plain_128, bool is_inverse)
{
// read the plaintext vertically direction
plain_128 = Read_Vertically(plain_128);
// result of Mix columsn operations
string Mix = "";
// 4 loop i for 32bit columns
for (int i = 0; i < 4; i++)
{
// get column by column
string column = plain_128.substr(32 * i, 32);
// 4 loop j for GF_Multiplication_Matrix row
for (int j = 0; j < 4; j++)
{
string result = "00000000";
// 4 loop k for GF_multiplication_Matrix column and each 8 bits of column
for (int k = 0; k < 4; k++)
{
if (is_inverse)
{
// inverse for decryption
// compute inverse multiplication GF 2^8 and xor with result then store to result
result = Xor(GF_256_Mul(column.substr(k * 8, 8), Decimal_to_Bin(GF_Multiplication_Inverse_Matrix[j][k], 8)), result);
}
else
{
// for encryption
// compute multiplication GF 2^8 and xor with result then store to result
result = Xor(GF_256_Mul(column.substr(k * 8, 8), Decimal_to_Bin(GF_Multiplication_Matrix[j][k], 8)), result);
}
}
Mix += result;
}
}
return Read_Vertically(Mix);
}
// Xor each 8 bits of str1 and str2 follow row by row
string Xor_row_by_row(string str1, string str2)
{
string xor_res = "";
for (int i = 0; i < 16; i++)
{
xor_res += Xor(str1.substr(i * 8, 8), str2.substr(i * 8, 8));
}
return xor_res;
}
// Encrypt 128 bit length
string Encrypt_128(string plain_128, string key)
{
string Key_Expanded[10];
// compute the key_expanded from specific key
Key_Expansion(key, Key_Expanded);
int rounds = 0;
// convert key to binary
key = Hexadecimal_to_Bin(key);
// Add keys operation
plain_128 = Xor_row_by_row(Read_Vertically(plain_128), Read_Vertically(key));
string cipher_128 = plain_128;
//loop for 10 rounds
while (rounds < 10)
{
// Substitiontion 128 bits length operation
cipher_128 = Sub_Bytes(cipher_128, 0);
// Shift row operation
cipher_128 = Shift_Row_Left(cipher_128);
// Mix columns opeation except the tenth round (the last round)
if (rounds != 9)
{
cipher_128 = Mix_Columns(cipher_128, 0);
}
// Add keys operation and store cipher to use for the next round
cipher_128 = Xor_row_by_row(cipher_128, Read_Vertically(Key_Expanded[rounds]));
rounds++;
}
return Read_Vertically(cipher_128);
}
// Decrypt 128 bits length
string Decrypt_128(string cipher_128, string key)
{
string Key_Expanded[10];
// compute key_expanded from specific key
Key_Expansion(key, Key_Expanded);
// 10 rouds for AES oepration
int rounds = 10;
// convert key to binary
key = Hexadecimal_to_Bin(key);
string plain_128 = Read_Vertically(cipher_128);
// loop inverse 10 round for decryption
// the operation step is inverse with decryption operation step
while (rounds > 0)
{
// Addes key operation
plain_128 = Xor_row_by_row(plain_128, Read_Vertically(Key_Expanded[rounds - 1]));
// Mix columns except the tenth round
if (rounds != 10)
{
plain_128 = Mix_Columns(plain_128, 1);
}
// shift rows operation
plain_128 = Shift_Row_Right(plain_128);
// Substitution 128 bits length operation
plain_128 = Sub_Bytes(plain_128, 1);
rounds--;
}
plain_128 = Xor_row_by_row(Read_Vertically(plain_128), key);
return plain_128;
}
// Random 32 bit hexadecimal key
string GenerateKey()
{
string key = "";
for (int i = 0; i < 32; i++)
{
key += Hex_Table[rand() % 16];
}
return key;
}
class AES
{
private:
string key;
string iv;
public:
// Default constructor
AES()
{
srand(time(NULL));
key = "";
iv = "";
}
// Destructor
~AES()
{
}
// Constructor
AES(string key_input, string iv_input)
{
srand(time(NULL));
Key_setter(key_input);
Iv_setter(iv_input);
}
// Auto generate key
void Auto_Generate_Key()
{
Key_setter(GenerateKey());
}
void Auto_Generate_Iv()
{
Iv_setter(GenerateKey());
}
// set the value for key in hexadecimal
bool Key_setter(string key_input)
{
if (key_input.length() != 32 || !Check_String_All_Hex(key_input))
{
wcout << "Key input is invalid!" << endl;
return false;
}
key = key_input;
return true;
}
// get the value of key
string Key_getter()
{
return key;
}
// set the value for key in hexadecimal
bool Iv_setter(string iv_input)
{
if (iv_input.length() != 32 || !Check_String_All_Hex(iv_input))
{
wcout << "Iv input is invalid!" << endl;
return false;
}
iv = iv_input;
return true;
}
// get the value of iv
string Iv_getter()
{
return iv;
}
// Encryption full plaintext
string Encryption(string plaintext)
{
// check key is valid
if (key == "" || key.length() != 32)
{
wcout << "key is invalid!" << endl;
exit(EXIT_FAILURE);
}
// check iv is valid
if (iv == "" || iv.length() != 32)
{
wcout << "iv is invalid!" << endl;
exit(EXIT_FAILURE);
}
// get key length
long long len_plaintext = plaintext.length();
// plaintext in ASCII so it is 8 bits length
while ((len_plaintext * 8) % 128 != 0)
{
//padding in front of with null
plaintext = plaintext + char(0);
len_plaintext = plaintext.length();
}
// Convert plaintext to hexadecimal
plaintext = ASCII_to_Hexadecimal(plaintext);
string ciphertext = "";
// convert plaintext to binary
plaintext = Hexadecimal_to_Bin(plaintext);
// reserved iv
string iv_round = Hexadecimal_to_Bin(iv);
// Split plaintext into each 128 bits length the encrypt
for (long long i = 0; i < plaintext.length() / 128; i++)
{
string _text_128_bit = plaintext.substr(i * 128, 128);
_text_128_bit = Xor(_text_128_bit, iv_round);
// Encrypt 128 bits length the Concatenate to ciphertext
string _128_bit_ciphertext;
_128_bit_ciphertext = Encrypt_128(_text_128_bit, key);
ciphertext += _128_bit_ciphertext;
iv_round = _128_bit_ciphertext;
}
// return ciphertext in hexadecimal format
return Bin_to_Hexadecimal(ciphertext);
}
// Decryption full ciphertext
string Decryption(string ciphertext)
{
// check key is valid
if (key == "" || key.length() != 32)
{
wcout << "Key is invalid!" << endl;
exit(EXIT_FAILURE);
}
string recovered_plaintext = "";
// convert ciphertext to binary
ciphertext = Hexadecimal_to_Bin(ciphertext);
// reserved iv
string iv_round = Hexadecimal_to_Bin(iv);
// split ciphertext into each 128 bits length then decrypt
for (long long i = 0; i < ciphertext.length() / 128; i++)
{
string plaintext_64_bit = ciphertext.substr(i * 128, 128);
// decrypt 128 bits length the concatenate to recorverd_plaintext
string _64_bit_recovered = Decrypt_128(plaintext_64_bit, key);
recovered_plaintext += Xor(_64_bit_recovered, iv_round);
iv_round = plaintext_64_bit;
}
// return recovered_plaintext in Hexadecimal format
return Bin_to_Hexadecimal(recovered_plaintext);
}
};
<file_sep>#include "DES_without_lib.h"
// library for unicode in C++
#include <fcntl.h> // _O_WTEXT
#include <io.h> //_setmode()
#include <locale>
#include <codecvt>
using std::wstring;
// convert string to wstring (ASCII to utf8)
wstring string_to_wstring(string str)
{
return std::wstring_convert<std::codecvt_utf8<wchar_t>>().from_bytes(str);
}
// convert wstring(utf8) to string (ASCII)
string wstring_to_string(wstring wstr)
{
return std::wstring_convert<std::codecvt_utf8<wchar_t>>().to_bytes(wstr);
}
// trim character rigth in string
string Trim_right(string str, char c)
{
while (str[str.length() - 1] == c)
{
str.erase(str.length() - 1, 1);
}
return str;
}
int main()
{
_setmode(_fileno(stdout), _O_WTEXT); // needed for output unicode
_setmode(_fileno(stdin), _O_WTEXT); // needed for input unicode
wstring plaintext = L"Welcome to the DES encryption and decryption!";
wcout << plaintext << endl;
wcout << "[+] Input plaintext for encryption: ";
getline(wcin, plaintext);
DES des_operation;
wcout << "Plaintext: " << plaintext << endl;
wstring wkey;
string key;
do
{
wcout << "[+] Enter key:";
fflush(stdin);
getline(wcin, wkey);
key = ASCII_to_Hexadecimal(wstring_to_string(wkey));
} while (!des_operation.Key_setter(key));
wstring wiv;
string iv;
wcout << endl;
do
{
wcout << "[+] Enter iv: ";
fflush(stdin);
getline(wcin, wiv);
iv = ASCII_to_Hexadecimal(wstring_to_string(wiv));
} while (!des_operation.Iv_setter(iv));
wcout << endl;
wcout << "Key (hex): " << string_to_wstring(des_operation.Key_getter()) << endl
<< endl;
wcout << "Iv (hex): " << string_to_wstring(des_operation.Iv_getter()) << endl
<< endl;
wcout << "Plaintext (ASCII): " << plaintext << endl
<< endl;
wcout << "\n-----Encryption-----\n";
wcout << "Plaintext (hex): " << string_to_wstring(ASCII_to_Hexadecimal(wstring_to_string(plaintext))) << endl
<< endl;
string ciphertext = des_operation.Encrypt(wstring_to_string(plaintext));
wcout << "Ciphertext (hex): " << string_to_wstring(ciphertext) << endl
<< endl;
wcout << "\n-----Decryption-----\n";
wcout << "Ciphertext (hex): " << string_to_wstring(ciphertext) << endl
<< endl;
string encrypted = des_operation.Decrypt(ciphertext);
wcout << "Recovered (hex): " << string_to_wstring(encrypted) << endl
<< endl;
wcout << "Recorvered ciphertext(text): " << string_to_wstring(Hexadecimal_to_ASCII(encrypted)) << endl;
return 0;
}<file_sep>
# Performance
## Hardware resources
Processor: Intel(R) Core(TM) i7-4720HQ CPU @ 2.60GHz, 2594 Mhz, 4 Core(s), 8 Logical Processor(s)
Installed Physical Memory (RAM): 8.00 GB
Total Physical Memory: 7.89 GB
## Perfomance windows 10 64 bit
OS Name Microsoft Windows 10 Home Single Language
Version 10.0.19042 Build 19042
## Thống kê (10000 vòng lặp)
| Scheme | Operation | Platform |Total excecution time (ms) | Average execution time (ms) |
| ------ | --------- | -------- |--------------------- | ---------------------- |
| ECC-based Digital signature | Signing| Windows | 4864 | 0.4864 |
| ECC-based Digital signature | Signing| Linux | 3238.69 | 0.323869 |
| ECC-based Digital signature | Vefifying| Windows | 8173 | 0.8173 |
| ECC-based Digital signature | Vefifying| Linux | 7754.81 | 0.775481 |
Signing Operation
- Windows:

- Linux:

Verifying Operation
- Windows:

- Linux:

<file_sep>#include <stdio.h>
int main()
{
printf("GoodGood Program !!\n");
}<file_sep>
# Performance
## Hardware resources
Processor: Intel(R) Core(TM) i7-4720HQ CPU @ 2.60GHz, 2594 Mhz, 4 Core(s), 8 Logical Processor(s)
Installed Physical Memory (RAM): 8.00 GB
Total Physical Memory: 7.89 GB
## Perfomance windows 10 64 bit
OS Name Microsoft Windows 10 Home Single Language
Version 10.0.19042 Build 19042
## Thống kê (10000 vòng lặp)
| Scheme | Operation | Platform |Total excecution time (ms) | Average execution time (ms) |
| ------ | --------- | -------- |--------------------- | ---------------------- |
| RSA | Encryption| Windows | 802 | 0.0802 |
| RSA | Encryption| Linux | 734.207 | 0.0734207 |
| RSA | Decryption| Windows | 72860 | 7.286 |
| RSA | Decryption| Linux | 72542 | 7.2542 |
Encrypt Operation
- Windows:

- Linux:

Decrypt Operation
- Windows:

- Linux:

| 904551a7b3245869646fb11616c8cc910b31d614 | [
"Markdown",
"C++"
] | 16 | C++ | TooBunReal/Crypto_Lab | f9e4ce43661f74399394adc484278881211a0114 | 84da877089cb2e7092aa90fd9f2499df56710986 |
refs/heads/master | <file_sep>package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import presentation.SortingApp;
public class SortServlet extends HttpServlet {
private static final long serialVersionUID = 8103342601196188319L;
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// reading the user input
String inputArray = request.getParameter("input-array");
String[] arr = inputArray.split("\\ ");
int[] inputArr = new int[arr.length];
int i = 0;
for (String elem : arr) {
inputArr[i++] = Integer.parseInt(elem);
}
SortingApp webService = new SortingApp();
int[] sortedArr = webService.sort(inputArr);
request.setAttribute("inputArray", inputArr);
request.setAttribute("sortedArray", sortedArr);
request.getRequestDispatcher("/").forward(request, response);
}
}<file_sep>package presentation;
import java.rmi.RemoteException;
import com.mum.seminar.SortingWSPortType;
import com.mum.seminar.SortingWSPortTypeProxy;
public class SortingApp implements SortingWSPortType {
@Override
public int[] sort(int[] arr) throws RemoteException {
SortingWSPortType service = new SortingWSPortTypeProxy();
return service.sort(arr);
}
}
| 06ed54e0291968df476e66b5993a06ef706f93a5 | [
"Java"
] | 2 | Java | frenmanoj/WebServiceSOAP | 3ab887d559ffb75bcc205d40664ca85665cd9eb5 | da0000a3a9732939e91c1850902a4853ed1251c4 |
refs/heads/master | <file_sep># AngularJS Nereid Service

This angular module is an abstraction of the nereid service. If you are writing
an angular web application that talks to Nereid, the basic authentication can be
performed using this module. Additional service could be built using the support
features.
This module requires that the Nereid version should atleast be 3.0.4.0
## Features
1. Service for nereid authentication.
2. Directive `show-if-auth` and `hide-if-auth` for showing and hiding DOM based
on authentication.
## Demo
http://openlabs.github.io/angular-nereid/
## Dependencies
- required:
angular-base64
See `bower.json` and `index.html` in the `gh-pages` branch for a full list / more details
## Install
1. download the files using bower
* add `"angular-nereid": "latest"` to your `bower.json` file then run `bower install`
* OR run `bower install angular-nereid`
2. include the files in your app
* `nereid.min.js`
3. include the module in angular (i.e. in `app.js`) - `openlabs.angular-nereid`
See the `gh-pages` branch, files `bower.json` and `index.html` for a full example.
## Documentation
### Events/Signals
The module also broadcasts the following three events:
1. `nereid-auth:login`: When the login is successful (after the token is set).
The data returned by the server on successful login is provided as argument.
2. `nereid-auth:loginFailed`: Broadcasted when the login fails. The `response`,
`status` and `headers` are sent in an object as argument.
3. `nereid-auth:logout`: Broadcasted when the user is logged out. Remember that
logout could be triggered by the expiry of token too.
4. `nereid-auth:loginRequired`: Broadcasted when a request sent to the server
fails with 401. This is usually indicative of a wrong token or the absence
of a valid login, which is required to access the resource.
See the `nereid.js` file top comments for usage examples and documentation
https://github.com/openlabs/angular-nereid/blob/master/nereid.js
## Development
1. `git checkout gh-pages`
1. run `npm install && bower install`
2. write your code then run `grunt`
3. git commit your changes
2. copy over core files (.js and .css/.less for directives) to master branch
1. `git checkout master`
2. `git checkout gh-pages nereid.js nereid.min.js`
3. update README, CHANGELOG, bower.json, and do any other final polishing to prepare for publishing
1. git commit changes
2. git tag with the version number, i.e. `git tag v1.0.0`
4. create github repo and push
1. [if remote does not already exist or is incorrect] `git remote add origin [github url]`
2. `git push origin master --tags` (want to push master branch first so it is the default on github)
3. `git checkout gh-pages`
4. `git push origin gh-pages`
5. (optional) register bower component
1. `bower register angular-nereid [git repo url]`
### Bonus commit hooks to minify
Install git pre-commit hook:
```
cp .hooks/pre-commit.sh .git/hooks/pre-commit
```
<file_sep>Version numbers correspond to `bower.json` version
# 1.0.9
* Add permissions handling
# 1.0.8
* Refresh user info only when token exists
* Use /me as default user endpoint
# 1.0.7
* Return user as a descriptor than object
# 1.0.6
* Bugfix: call setToken after setting user data to avoid
async overwrite
# 1.0.5
* Added signal for loginRequired triggered by interceptor.
* Bugfix: Fixed the userInfoEndpoint to point to user_status.
# 1.0.4
* Added signals for login, logout and loginFailed
# 1.0.0
## Features
* Basic authentication and fetch token
<file_sep>#!/bin/sh
if [ $(git diff --cached --name-status | grep "nereid.js" -c) -ne 0 ]
then
echo "Minifying nereid.js"
grunt uglify
git add nereid.min.js
fi
| 2db8b33e3411307ad7b1bfdbc65bb971bed507d7 | [
"Markdown",
"Shell"
] | 3 | Markdown | openlabs/angular-nereid-auth | 96a96fd3d73a129b18aa12ca9cbe07ac012e13de | 76a829cbc07c749f19b4c112acd65fd309c96d87 |
refs/heads/master | <repo_name>mohsinalimat/DatabaseKit<file_sep>/Tests/sqlite_fixtures.sql
BEGIN TRANSACTION;
DROP TABLE IF EXISTS foo;
CREATE TABLE foo ("UUID" UUID_BLOB PRIMARY KEY NOT NULL, "bar" TEXT DEFAULT NULL, "baz" TEXT DEFAULT NULL, "integer" INTEGER DEFAULT NULL);
INSERT INTO "foo" VALUES(X'B89BD574493942E1B011CA8688D776CD','foobarbaz','bazbazb',1337);
INSERT INTO "foo" VALUES(X'87EE3C503C294F8B827375F93DAF7B12','fjolnir','asgeirsson',1601);
COMMIT;<file_sep>/Source/Utilities/DBInflector/irregulars.inc
@{
@"word": @"move",
@"replacement": @"moves"
},
@{
@"word": @"sex",
@"replacement": @"sexes"
},
@{
@"word": @"child",
@"replacement": @"children"
},
@{
@"word": @"man",
@"replacement": @"men"
},
@{
@"word": @"person",
@"replacement": @"people"
}
<file_sep>/Source/Utilities/DBInflector/inflections.inc
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"s"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"s$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"s"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(ax|test)is$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1es"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(octop|vir)us$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1i"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(alias|status)$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1es"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(bu)s$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ses"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(buffal|tomat)o$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1oes"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([ti])um$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1a"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"sis$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"ses
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(?:([^f])fe|([lr])f)$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1$2ves"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(hive)$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1s"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([^aeiouy]|qu)y$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ies"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(x|ch|ss|sh)$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1es"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(matr|vert|ind)ix|ex$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ices"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([m|l])ouse$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ice"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"^(ox)$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1en"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(quiz)$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1zes"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"s$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement":"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(n)ews$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ews"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([ti])a$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1um"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1\2sis"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(^analy)ses$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1sis"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([^f])ves$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1fe"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(hive)s$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(tive)s$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([lr])ves$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1f"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([^aeiouy]|qu)ies$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1y"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(s)eries$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1eries"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(m)ovies$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ovie"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(x|ch|ss|sh)es$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([m|l])ice$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ouse"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(bus)es$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(o)es$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(shoe)s$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(cris|ax|test)es$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1is"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(octop|vir)i$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1us"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(alias|status)es$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"^(ox)en" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(vert|ind)ices$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ex"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(matr)ices$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ix"
},
@{
@"type": @"singular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(quiz)zes$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"
},
@{
@"type": @"irregular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"person" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"people"
},
@{
@"type": @"irregular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"man" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"men"
},
@{
@"type": @"irregular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"child" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"children"
},
@{
@"type": @"irregular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"sex" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"sexes"
},
@{
@"type": @"irregular",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"move" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"moves"
},
@{
@"type": @"uncountable",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"equipment" options:NSRegularExpressionCaseInsensitive error:NULL]
},
@{
@"type": @"uncountable",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"move" options:NSRegularExpressionCaseInsensitive error:NULL]
},
@{
@"type": @"uncountable",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"move" options:NSRegularExpressionCaseInsensitive error:NULL]
},
@{
@"type": @"uncountable",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"move" options:NSRegularExpressionCaseInsensitive error:NULL]
},
@{
@"type": @"uncountable",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"move" options:NSRegularExpressionCaseInsensitive error:NULL]
},
@{
@"type": @"uncountable",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"move" options:NSRegularExpressionCaseInsensitive error:NULL]
},
@{
@"type": @"uncountable",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"move" options:NSRegularExpressionCaseInsensitive error:NULL]
},
@{
@"type": @"uncountable",
@"regex": [NSRegularExpression regularExpressionWithPattern:@"move" options:NSRegularExpressionCaseInsensitive error:NULL]
}
<file_sep>/README.md
DatabaseKit ReadMe
=====================
About:
======
DatabaseKit is an unbelievably straight-forward to use database framework for Objective-C.
Features:
=========
* Supports SQLite, but is built to make it easy to add support for additional SQL databases, just subclass `DBConnection`.
* Query composition done purely in Objective-C.
* If you use a connection pool or queue(Done transparently by default) then query objects are thread safe.
* If you provide a model class, then results from it's corresponding table will automatically be returned as instances of that class.
* Supports creating and migrating tables for model classes at runtime.
* Almost no code required.
Examples
=============
### Connecting:
// Open a SQLite database
DB *db = [DB withURL:[NSURL URLWithString:@"sqlite://myDb.sqlite"]];
if(err)
NSLog(@"Couldn't open database: %@.", [err localizedDescription]);
---
### Querying:
// Get the names of every person in our database
DBTable *people = db[@"people"];
DBSelectQuery *names = [people select:@"name"];
for(NSDictionary *row in [names limit:100]) {
NSLog(@"Name: %@", row[@"name"]);
}
---
// Delete really old people
[[[people delete] where:@"bornOn < %@", [NSDate distantPast]] execute];
---
// Change the name of everyone called John
[[[people update:@{ @"name": @"Percie" }] where:@"name = %@", @"John"] execute];
---
// You can create a class to represent results from a table like so:
// (Our project's class prefix is `NICE`)
@interface NICEPerson : DBModel
@property(readwrite, retain) NSString *name, *address;
- (void)introduceYourself;
@end
@implementation NICEPerson
- (void)introduceYourself
{
NSLog(@"Hi! I'm %@.", self.name);
}
@end
// And now if you perform a query
NicePerson *someone = [[people select] firstObject];
[someone introduceYourself];
<file_sep>/Source/Utilities/DBInflector/singulars.inc
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(quiz)zes$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(matr)ices$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ix"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(vert|ind)ices$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ex"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"^(ox)en" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(alias|status)es$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(octop|vir)i$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1us"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(cris|ax|test)es$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1is"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(shoe)s$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(o)es$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(bus)es$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([m|l])ice$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ouse"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(x|ch|ss|sh)es$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(m)ovies$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ovie"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(s)eries$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1eries"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([^aeiouy]|qu)ies$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1y"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([lr])ves$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1f"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(tive)s$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(hive)s$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([^f])ves$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1fe"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(^analy)ses$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1sis"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1\2sis"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([ti])a$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1um"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(n)ews$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ews"},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"s$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @""
}
<file_sep>/Source/Utilities/DBInflector/plurals.inc
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(quiz)$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1zes"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"^(ox)$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1en"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([m|l])ouse$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ice"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(matr|vert|ind)ix|ex$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ices"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(x|ch|ss|sh)$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1es"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([^aeiouy]|qu)y$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ies"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(hive)$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1s"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(?:([^f])fe|([lr])f)$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1$2ves"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"sis$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"ses"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([ti])um$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1a"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(buffal|tomat)o$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1oes"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(bu)s$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1ses"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(alias|status)$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1es"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(octop|vir)us$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1i"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"(ax|test)is$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1es"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([a-z]+)s$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1s"
},
@{
@"regex": [NSRegularExpression regularExpressionWithPattern:@"([a-z]+)$" options:NSRegularExpressionCaseInsensitive error:NULL],
@"replacement": @"$1s"
}
<file_sep>/Source/Utilities/DBInflector/uncountables.inc
@"sheep",
@"fish",
@"series",
@"species",
@"money",
@"rice",
@"information",
@"equipment"
| 1c09ae0ea78fc8d062dca082ef3d51aa1b5ac305 | [
"Markdown",
"SQL",
"C++"
] | 7 | SQL | mohsinalimat/DatabaseKit | 728a2a85e6c40845481a7844c0eb8bd21fcdb5ff | b1360894dd8efe61c9d3fb0ba9f6a8805288e9f7 |
refs/heads/master | <file_sep># https://blog.csdn.net/weixin_40449300/article/details/81051179
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Tree(object):
def __init__(self):
self.val = None
self.left = None
self.right = None
def add(self,item):
# 最后去添加,不考虑头插还是尾插
node = TreeNode(item)
if self.val is None:
self.val = node
return
queue = [self.val]
while queue:
cur_node = queue.pop(0)
if cur_node.left is None:
# 左节点为空,新加入的节点放到这个位置上
cur_node.left=node
return
else:
# 不是空的话,左节点入队
queue.append(cur_node.left)
if cur_node.right is None:
cur_node.right=node
return
else:
queue.append(cur_node.right)
class Solution(object):
def findTilt(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def sum_and_tilt(root):
if not root: # 如果是一个叶子节点的左右孩子,则是空的,没有东西可以继续遍历了!
return 0,0 # 第一个值是该节点为根的时候,它的和;第二个值是该节点的
# 总坡度(因为题目要求的是所有节点的坡度之和)
sum_left,left_tilt = sum_and_tilt(root.left)
sum_right,right_tilt = sum_and_tilt(root.right)
return sum_left+sum_right+root.val,abs(sum_left-sum_right)+left_tilt+right_tilt
sum_tree,tilt_tree = sum_and_tilt(root)
return tilt_tree
if __name__ == '__main__':
# tree = Tree()
# tree.add(1)
# tree.add(2)
# tree.add(3)
# tree.add(4)
# tree.add(5)
a = TreeNode(1)
b = TreeNode(2)
c = TreeNode(3)
d = TreeNode(4)
e = TreeNode(5)
a.left = b
a.right = c
c.right = d
d.right = e
ans = Solution()
print(ans.findTilt(a))
# 5+9+10 = 24
<file_sep># Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# 1.使用何种数据结构存储遍历路径上的节点?
# 2.在树的前序遍历时做什么?后序遍历时做什么?
# 3.如何判断一个节点为叶节点?当遍历到叶节点时应该做什么?
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
rs = []
path = []
path_value = 0
if root is None:
return rs
# return self.preorder(root,sum,path,path_value,rs) # 是None
self.preorder(root, sum, path, path_value, rs)
# 因为Python是引用传值,所以这个时候执行完preorder函数,rs已经改变了
return rs
def preorder(self,node,sum,path,path_value,rs):
# 深度遍历——前序遍历
if node is None:
return
# 此时访问node为前序遍历
# 遍历一个节点即更新一次路径值
path.append(node.val)
path_value += node.val
# print(path)
if node.right is None and node.left is None and path_value == sum:
# print(path)
# rs.append(path.copy()) # path.copy() —— leetcode ide无法通过
rs.append(path[:])
# print(rs)
# 此时访问node为中序遍历
self.preorder(node.left, sum, path, path_value, rs)
self.preorder(node.right, sum, path, path_value, rs)
# 此时访问node为后序遍历
# 遍历完成后,叶子节点出栈
# 这一块的顺序不知道到底放在哪里?
# 答:左右子树全部访问完,说明以它为根节点的这颗子树已经访问完了,
# 以它为根节点的所有可能性都尝试了,然后就换一个结点为根节点呀
del path[-1]
path_value -= node.val
#-----------------------------------------------------------------
def pathSum222(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
self.res = []
self.total = sum
def caculate(root, sum, templist):
if not root:
return
if not root.left and not root.right:
if root.val + sum == self.total:
self.res.append(templist + [root.val])
if root.left:
caculate(root.left, sum + root.val, templist + [root.val])
if root.right:
caculate(root.right, sum + root.val, templist + [root.val])
caculate(root, 0, [])
return self.res
#-----------------------------------------------------------------
def pathSum333(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
result = list()
if not root:
return result
self._pathSum(result, list(), root, sum)
return result
def _pathSum(self, result, path, node, num):
if node:
path.append(node.val)
if not node.left and not node.right and num == node.val:
result.append(path.copy())
self._pathSum(result, path, node.left, num - node.val)
self._pathSum(result, path, node.right, num - node.val)
path.pop()
if __name__ == '__main__':
a = TreeNode(5)
b = TreeNode(4)
c = TreeNode(8)
d = TreeNode(11)
e = TreeNode(13)
f = TreeNode(4)
g = TreeNode(7)
h = TreeNode(2)
i = TreeNode(5)
j = TreeNode(1)
a.right = c
a.left = b
b.left = d
d.left = g
d.right = h
c.right = f
c.left = e
f.right = j
f.left = i
sum = 22
# Solution().pathSum(a, sum)
print(Solution().pathSum(a,sum))
<file_sep># 交换二叉树的左右子树
# easy题目
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
# 如果是叶子节点,则递归结束
if root is None:
return
# if root.left and root.right:
root.left,root.right = root.right,root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
if __name__ == '__main__':
a = TreeNode(3)
b = TreeNode(9)
c = TreeNode(20)
d = TreeNode(15)
e = TreeNode(7)
a.right = c
a.left = b
c.right = e
c.left = d
print(Solution().invertTree(a))<file_sep># # 438. 找到字符串中所有字母异位词(异曲同工!!)
# class Solution(object):
# def checkInclusion(self, s1, s2):
# """
# :type s1: str
# :type s2: str
# :rtype: bool
# """
# # s1_num = []
# # for i in s1:
# # i = ord(i)-ord('a')
# # s1_num.append(i)
# # print(s1_num)
# #
# # s2_num = []
# # for i in s2:
# # i = ord(i)-ord('a')
# # s2_num.append(i)
# # print(s2_num)
# #
# #
# # lens1 = len(s1)
# # for i in range(len(s2)):
# # if sum(s1_num) == sum(s2_num[i:i+lens1]):
# # return True
# # return False
# class Solution(object):
# def checkInclusion(self, s1, s2):
# A = [ord(x) - ord('a') for x in s1]
# print(A) # [0, 1, 3]
# B = [ord(x) - ord('a') for x in s2]
# print(B) # [2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0]
#
# target = [0] * 26
# for x in A:
# target[x] += 1
# print(target)
# # abd [1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
#
# window = [0] * 26
# for i, x in enumerate(B):
# window[x] += 1
# if i >= len(A):
# window[B[i - len(A)]] -= 1
# print("start")
# print(window)
# if window == target:
# return True
# # print(window)
# return False
from collections import Counter
class Solution:
def checkInclusion(self, s1, s2):
"""
:type s1: str
:type s2: str
:rtype: bool
"""
d1, d2 = Counter(s1), Counter(s2[:len(s1)])
for start in range(len(s1), len(s2)):
if d1 == d2: return True
d2[s2[start]] += 1
d2[s2[start - len(s1)]] -= 1
print(d2)
if d2[s2[start - len(s1)]] == 0:
# print(start) # 2 3 4
del d2[s2[start - len(s1)]]
return d1 == d2
def main():
s1 = "ab"
s2 = "eidbaooo"
myResult = Solution()
# 第一个字符串的排列之一是第二个字符串的子串
print(myResult.checkInclusion(s1, s2))
if __name__ == '__main__':
main()
# def checkInclusion(self, s1, s2):
# """
# :type s1: str
# :type s2: str
# :rtype: bool
# """
# # 变成s1中的字母排列组合个数了。。。我的思路
# # 只要保证s1中的各个字母个数在s2的子串中相同即可
# c = list(set(s1))
# # 还要判断在s2中是否是连在一起的——判断是子串。
# sub_s2 = ""
# for i in range(len(s2)):
# if s2[i] in c:
# sub_s2 = s2[i:i+len(s1)]
# # 用字典统计
# return True
# return False
<file_sep># Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# # 方法一:中序遍历二叉树,结果是否是递增的,递增代表是二叉搜索树。
class Solution(object):
def isValidBST1(self, root):
res = []
self.helper(root,res)
# print(res)
for i in range(1,len(res)):
if res[i-1]>=res[i]:
return False
return True
def helper(self,root,res):
if root:
self.helper(root.left,res)
res.append(root.val)
# print(res)
self.helper(root.right,res)
return None
# 方法二,递归版本,每个结点都满足左小于它,右大于它的性质
def isValidBST(self, root):
return self.check_bst(root, float("-inf"), float("inf"))
def check_bst(self, node, left, right):
if not node:
return True
if not left < node.val < right:
return False
return (self.check_bst(node.left, left, node.val)
and self.check_bst(node.right, node.val, right))
if __name__ == '__main__':
a = TreeNode(2)
b = TreeNode(1)
c = TreeNode(3)
# d = TreeNode(3)
# e = TreeNode(6)
a.right = c
a.left = b
# c.right = e
# c.left = d
print(Solution().isValidBST(a))<file_sep># 小结:
# 层次遍历是广度优先遍历
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
queue = []
res = []
if root:
queue.append(root)
flag = 1
while queue:
cur_level, size = [], len(queue)
for i in range(size):
cur = queue.pop(0)
cur_level.append(cur.val)
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
res.append(cur_level[::flag])
flag*=-1
return res
if __name__ == '__main__':
a = TreeNode(3)
b = TreeNode(9)
c = TreeNode(20)
d = TreeNode(15)
e = TreeNode(7)
a.right = c
a.left = b
c.right = e
c.left = d
print(Solution().zigzagLevelOrder(a))<file_sep># 我的想法:用递归(脑残)
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
s = '1'
for _ in range(1, n):
nextS = ''
countC = 1
for i in range(1, len(s)+1):
if i == len(s) or s[i] != s[i-1]:
nextS += str(countC) + s[i-1]
countC = 1
else:
countC += 1
s = nextS
return s
def main():
n = 4
myResult = Solution()
print(myResult.countAndSay(n))
if __name__ == '__main__':
main()<file_sep>class Solution:
def insert(self, intervals, newInterval):
intervals.append(newInterval)
# print(intervals)
intervals.sort()
# print(intervals)
ans = [intervals[0]]
for i in range(1,len(intervals)):
if intervals[i][0]>ans[-1][1]:
# 说明没有重叠,不合并
ans.append(intervals[i])
elif intervals[i][1]>ans[-1][1]:
# 说明第一个if没有满足,相邻两个元素已经比较过了3>2,判断6>3即可
ans[-1][1] = intervals[i][1]
return ans
if __name__ == '__main__':
intervals = [[1, 3], [6, 9]]
newInterval = [2, 5]
print(Solution().insert(intervals,newInterval))
"""
def insert1(self, intervals, newInterval):
i = 0
n = len(intervals)
while i < n and newInterval[0] > intervals[i][1]:
i += 1
left = i
while i < n and newInterval[1] >= intervals[i][0]:
i += 1
right = i
# print(left, right)
if left >= n:
res = intervals + [newInterval]
elif left == right:
# print(intervals)
intervals.insert(left, newInterval)
res = intervals
else:
res = intervals[:left] + [[min(intervals[left][0],\
newInterval[0]), max(intervals[right - 1][1],
newInterval[1])]] + intervals[right:]
return res
"""
<file_sep># 判断一个数是否为丑数
class Solution(object):
# 和求质数的思路一样
# 每一个丑数必然是之前丑数与2,3或5的乘积得到的,这样下一个丑数就是用之前的丑数分别乘以2,3,5
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
# 暴力
while num>1:
if num%2==0:
num = num//2
elif num%3==0:
num = num//3
elif num%5==0:
num = num//5
else:
break
if num==1:
return True
else:
return False
if __name__ == '__main__':
num = 14
ans = Solution()
print(ans.isUgly(num))<file_sep># 给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。
# 要求算法时间复杂度必须是O(n)。
# gg
class Solution(object):
def thirdMax(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# listnum = sorted(list(set(nums))) # set之后是有序的
#
# if len(listnum)<3:
# # print(listnum)
# return max(listnum)
#
# listnum.reverse()
# return listnum[2]
def main():
nums = [2,2,2,1,3]
myResult = Solution()
print(myResult.thirdMax(nums))
if __name__ == '__main__':
main()
<file_sep># Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def printList(self,head):
while head:
print(head.val,end='->')
head = head.next
print()
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
# 思路一:使用A建立一个set,遍历B,如果有元素相等,那么第一次出现的那个元素就是交点;
# 思路二:用B的长度减去A的长度,B指针向前移动差值个元素,然后再一起遍历(这时候起点相同),遇到相同元素时,就是交点;
self.printList(headA)
self.printList(headB)
skipA = self.length(headA)
skipB = self.length(headB)
changed = skipA-skipB
print(changed)
if changed<0:
offset = 0
while headB and abs(changed) != offset:
print(abs(changed))
headB = headB.next
offset += 1
# print(headB.val)
else:
offset = 0
while headA and abs(changed) != offset:
headA = headA.next
offset += 1
while headA and headB:
if headA == headB:
# if headA.val == headB.val: # 这句报错是因为没有val
return headA
else:
headA = headA.next
headB = headB.next
return None
def length(self,head):
if head is None:
return 0
cnt = 0
cur = head
while cur:
cur = cur.next
cnt+=1
return cnt
def getIntersectionNode2(self, headA, headB):
# 为什么这个不报错?
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
lenA, lenB = 0, 0
pA = headA
pB = headB
while pA:
pA = pA.next
lenA += 1
while pB:
pB = pB.next
lenB += 1
pA = headA
pB = headB
if lenA > lenB:
for i in range(lenA - lenB):
pA = pA.next
else:
for i in range(lenB - lenA):
pB = pB.next
while pA != pB:
pA = pA.next
pB = pB.next
return pA
# 原文:https: // blog.csdn.net / qq_34364995 / article / details / 80518198
if __name__ == '__main__':
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
a.next = b
b.next = c
d = ListNode(4)
e = ListNode(5)
f = ListNode(6)
d.next = e
e.next = f
f.next = b
print(Solution().getIntersectionNode(a,d))
# 8
# [4,1,8,4,5]
# [5,0,1,8,4,5]
# 2
# 3
# Intersected at '1'(false)
# Intersected at '8'(true)
<file_sep># 你的解法应该是 O(logN) 时间复杂度的。
# 上坡必有坡顶,所以二分查找大的那一半一定会有峰值
# 规律一:如果nums[i] > nums[i+1],则在i之前一定存在峰值元素
# 规律二:如果nums[i] < nums[i+1],则在i+1之后一定存在峰值元素
"""
Conditions:
1. array length is 1 -> return the only index
2. array length is 2 -> return the bigger number's index
3. array length is bigger than 2 ->
(1) find mid, compare it with its left and right neighbors
(2) return mid if nums[mid] greater than both neighbors
(3) take the right half array if nums[mid] smaller than right neighbor
(4) otherwise, take the left half
"""
class Solution:
def findPeakElement(self, nums):
n = len(nums)
first, last = 0, n-1
while first < last:
mid = (first+last)//2
if nums[mid] > nums[mid+1] and nums[mid] > nums[mid-1]:
return mid
if nums[mid] < nums[mid+1]:
first = mid+1
else:
last = mid-1
return first # cinditions 1,2
if __name__ == '__main__':
# nums = [1, 2, 3, 1]
nums = [1, 2]
# nums = [1, 2, 1, 3, 5, 6, 4]
print(Solution().findPeakElement(nums))
<file_sep># Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseList(self, head):
# 第二次做,还是不会做
# 迭代
if (head is None) or (head.next is None):
return head
p1 = head
p2 = p1.next
p3 = p2.next
while p2:
p3 = p2.next
p2.next = p1
p1 = p2
p2 = p3
head.next = None
head = p1
return head
def recursive(self,head):
if (head==None or head.next==None):
return head
new_head = self.recursive(head.next)
head.next.next = head
head.next = None
return new_head
def reverseList1(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if (head == None):
return None
else:
pre = head
cur = head.next
pre.next = None #最开始的头节点要变成尾节点,即在后面补null使链表终结
while cur != None:
rear = cur.next
cur.next = pre
pre = cur
cur = rear
return pre
def main():
a = ListNode(1)
b = ListNode(2)
c = ListNode(3)
d = ListNode(4)
e = ListNode(5)
a.next = b
b.next = c
c.next = d
d.next = e
myresult = Solution()
print(myresult.reverseList(a))
print(myresult.recursive(a))
if __name__ == "__main__":
main()
<file_sep># 最短路径
class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
# python开根号 num_sqrt = n**0.5
# 对图中所有的点进行预处理,全都没被访问过,设置为false.
q = []
q.append((n,0))
visited = [False for _ in range(n+1)]
visited[n] = True
print(q)
while any(q): # 如果队列不为空的话,执行循环
num, step = q.pop(0) # 队列先进先出
i = 1
tNum = num-i**2
while tNum>=0:
if tNum==0:
return step+1
if not visited[tNum]: # 如果图中的节点没有被访问过
q.append((tNum,step+1))
visited[tNum]=True
print(q)
i+=1
tNum = num-i**2
def main():
n = 12
myResult = Solution()
print(myResult.numSquares(n))
if __name__ == '__main__':
main()
<file_sep># Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
flag = False
if root is None:
return flag
cur_val = 0
self.preorder(root,sum,flag,cur_val)
def preorder(self,node,sum,flag,cur_val):
if node:
cur_val += node.val
# print(cur_val)
if node.left is None and node.right is None:
return cur_val == sum
self.preorder(node.left,sum,flag,cur_val)
self.preorder(node.right,sum,flag,cur_val)
cur_val -= node.val
if __name__ == '__main__':
a = TreeNode(5)
b = TreeNode(4)
c = TreeNode(8)
d = TreeNode(11)
e = TreeNode(13)
f = TreeNode(4)
g = TreeNode(7)
h = TreeNode(2)
i = TreeNode(5)
j = TreeNode(1)
a.right = c
a.left = b
b.left = d
d.left = g
d.right = h
c.right = f
c.left = e
f.right = j
f.left = i
sum = 22
# Solution().pathSum(a, sum)
print(Solution().hasPathSum(a,sum))
<file_sep>class Solution:
def solve(self, board):
if not board or not board[0]:
return
m, n = len(board), len(board[0]) # m行,n列
for i in range(m):
for j in range(n):
if (i == 0) or (j == 0) or (i=m-1) or (j=n-1):
self.dfs(board, i, j, m, n)
for i in range(m):
for j in range(n):
if (board[i][j] == 'O'):
board[i][j] = 'X'
elif (board[i][j] == 'M'):
board[i][j] = 'O'
def dfs(board, i, j, m, n):
if i < 0 or j < 0 or i > m-1 or j > n-1:
return
if(board[i][j] != 'O') return
board[i][j] = 'M'
dfs(board, i+1, j, m, n)
dfs(board, i, j+1, m, n)
dfs(board, i-1, j, m, n)
dfs(board, i, j-1, m, n)
# print(board[0]) # ['X', 'X', 'X', 'X']
# print('XO'[0]) # X , it is amazing!!!
"""
board[:] = [['XO'[c == 'S'] for c in row] for row in board]
等于, 一个二维数组
for row in board:
for i, c in enumerate(row):
row[i] = 'XO'[c == 'S']
"""
if __name__ == '__main__':
board = [['X', 'X', 'X', 'X'],
['X', 'O', 'O', 'X'],
['X', 'X', 'O', 'X'],
['X', 'O', 'X', 'X']]
print(Solution().solve(board))
<file_sep>class Solution:
# 往上下左右四个方向进行DFS。
# 需要注意的就是访问一个字母后visited标识1,
# 当DFS调用返回后,如果还没有找完,应该让visited置0,并返回false
def exist(self, board, word):
if len(word) == 0:
return False
for i in range(len(board)):
for j in range(len(board[0])):
if self.dfs(board, word, 0, i, j):
# i,j是一开始遍历的位置
return True
return False
def dfs(self, board, word, index, x, y):
# 递归的出口
if not board or index == len(word):
return True
# 是否越界
if x < 0 or x == len(board) or y < 0 or y == len(board[0]):
return False
# 不是要找的元素
if board[x][y] != word[index]:
return False
# 这几句什么意思??
source = board[x][y]
board[x][y] = '\0' # 表示此位置已经访问过,‘1’也可以,访问过的元素不再访问
# 递归变成了四个方向的递归判断
exist = self.dfs(board, word, index + 1, x, y + 1) or self.dfs(board, word, index + 1, x, y - 1) or self.dfs(
board, word, index + 1, x + 1, y) or self.dfs(board, word, index + 1, x - 1, y)
board[x][y] = source
return exist
"""
这实际上还是一个回溯法解决的问题。例如,对于word = 'ABCCED',
我们从第一个元素开始,首先匹配到A,然后向后面寻找。
我们规定好寻找的顺序为:⬆️,➡️,⬇️,⬅️。我们接着找B,上面越界,右边找到了。
我们接着找C,上面越界,右边找到了。我们接着找C,上面越界了,右边不对,下面找到了。
接着找E,我们发现上面访问过,不再访问。接着向右查找,发现不匹配,接着向下查找,
发现越界了,接着想做查找,OK!我们所有元素匹配成功。
"""
if __name__ == "__main__":
board =[['A','B','C','E'],['S','F','C','S'],['A','D','E','E']]
word = "ABCCED"
res = Solution()
print(res.exist(board,word))
<file_sep>class Solution(object):
def fib(self, N):
"""
:type N: int
:rtype: int
"""
if __name__ == '__main__':
N = 4
print(Solution().fib(N))
<file_sep>'''
# 349
# 给定两个数组,编写一个函数来计算它们的交集。
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
rs = []
nums1 = list(set(nums1))
nums2 = list(set(nums2))
# print(nums1)
# print(nums2)
for i in nums1:
for j in nums2:
if i==j:
rs.append(i)
break
rs = list(set(rs))
return rs
# 别人的
#
# a = set(nums1)
# b = set(nums2)
# res =[]
# for i in a:
# if i in b:
res.append(i)
# return res
#
def main():
a = [4,9,5]
b = [9,4,9,8,4]
myresult = Solution()
print(myresult.intersection(a,b))
if __name__ == "__main__":
main()
'''
# 350
class Solution(object):
def intersect(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
rs = []
flag = []
for i,val_i in enumerate(nums1):
for j,val_j in enumerate(nums2):
if (val_i==val_j) and (j not in flag):
flag.append(j)
rs.append(val_i)
break
return rs
def main():
a = [1,2,2,1]
b = [2,2]
myresult = Solution()
print(myresult.intersect(a,b))
if __name__ == "__main__":
main()<file_sep># 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
# 卖出股票后,你无法在第二天买入股票 (即冷冻期为 1 天)。
# * 动态规划:dp[i]表示在第i天(0~i)所能获得的最大利润,第i天的状态由前一天是买入还是卖出还是冷冻决定
#
class Solution:
def maxProfit(self, prices):
if not prices:
return 0
n = len(prices)
buy,sell,cooldown = [0 for _ in range(n)],[0 for _ in range(n)],[0 for _ in range(n)]
# 第一天不能卖,冷冻,但是可以买入
buy[0] = -prices[0]
for i in range(1,n):
# 第i天是卖出,说明i-1也是可以卖出 or i-1是刚买入
sell[i] = max(buy[i-1]+prices[i],sell[i-1])
# 第i天是冷冻期,说明刚卖完
cooldown[i] = sell[i-1]
# 第i天是买入,说明i-1是冷冻期 or i-1天也可以买入
buy[i] = max(buy[i-1],cooldown[i-1]-prices[i])
# 一定是最后一天卖出或者最后一天冻结(刚卖完)利润最大
return max(sell[-1],cooldown[-1])
# https://blog.csdn.net/qq_17550379/article/details/82856452
if __name__ == '__main__':
prices = [1,2,3,0,2]
# 对应的交易状态为: [买入, 卖出, 冷冻期, 买入, 卖出]
print(Solution().maxProfit(prices))<file_sep>class Solution(object):
def subsets(self, nums):
item = []
result = [[]]
self.generate(0, nums, item, result)
return result
def generate(self, i, nums, item, result):
if i >= len(nums):
return
item.append(nums[i])
result.append(item[:])
# print(result)
self.generate(i + 1, nums, item, result)
item.pop()
self.generate(i + 1, nums, item, result)
item = []
result = [[]]
self.generate(0, nums, item, result)
return result
if __name__ == '__main__':
nums = [1, 2, 3]
print(Solution().subsets(nums))
# [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
<file_sep>class Solution(object):
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
n = len(nums)
rs = []
self.perm(nums,0,n,rs)
print(rs)
def perm(self, nums, p, q, rs):
if p == q:
print(nums)
rs.append(nums[:])
# 切片返回新数组,不改变原数组
for i in range(p, q):
# for i in range(p, q+1): 这里一直报错
# 遍历一个数组就是range(0, len(arr))
# 你第一次调用 传入的q是len(n),你要遍历数组 就range(0, q)就行,为啥还要+1?
nums[p], nums[i] = nums[i], nums[p]
# nums[p]=nums[i]
self.perm(nums, p+1, q, rs)
nums[p], nums[i] = nums[i], nums[p]
if __name__ == '__main__':
nums = [1,2,3]
myResult = Solution()
myResult.permute([1,2,3])
<file_sep>
# 第一次就做对了~过过过
def ReplacBlankMe(str1):
str1 = str1.split()
rs = str1[0]
for i in range(1,len(str1)):
rs += "%20"+str1[i]
# print(type(rs))
return rs
# 书中的方法
if __name__ == '__main__':
str1 = "We are happy."
print(ReplacBlankMe(str1))
<file_sep># 思路是归并排序——思路忘记了
# 用二叉搜索树完成
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.count = 0
class Solution(object):
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
pass
if __name__ == '__main__':
nums = [5,2,6,1]
print(Solution().countSmaller(nums))<file_sep>class Solution(object):
def trap(self, height):
# 根据短的那一端向高的那一端靠拢
# 然后过程中更新左右最高的柱子,来求的中间的蓄水量
# 这个蓄水量怎么求呢?area-中间一些柱子的高度
low = 0
high = len(height)-1
while low<high:
# 那么这个面积如何考虑呢?
area = (high-low)*min(height[low],height[high])-面积
if height[low]<height[high]:
area = area if (high-low)*height[low]>area else (high-low)*height[low]>area
low = low + 1
else:
# 水高由面积短的决定,此时是high短,所以由high决定
area = area if (high-low)*height[high]>area else (high-low)*height[high]>area
high = high-1
return area
if __name__ == '__main__':
height = [0,1,0,2,1,0,1,3,2,1,2,1]
print(Solution().trap(height))
<file_sep># 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。
class Solution(object):
def generateParenthesis(self, n):
"""
:type n: int
:rtype: List[str]
"""
res = []
n,m = n,0
self.generate("",n,m,res)
return res
def generate(self,str,n,m,res):
# 当前字符串,左括号个数,右括号个数,返回的结果数组
if n==0 and m==0:
# 括号都用完了
res += [str]
return res
if n>0:
self.generate(str+"(",n-1,m+1,res)
if m>0:
self.generate(str+")",n,m-1,res)
if __name__ == '__main__':
n = 3
print(Solution().generateParenthesis(n))<file_sep>class Solution(object):
def findAnagrams(self, s, p):
"""
:type s: str
:type p: str
:rtype: List[int]
"""
# 如何让bac判断三个元素都在abc中呢?
# 比如,bab虽然ab在abc中,但是,没有c所以也是错的。
def main():
s = "baa"
p = "aa"
myResult = Solution()
print(myResult.findAnagrams(s, p))
if __name__ == '__main__':
main()
# 超出时间限制
# p = sorted(p)
# len_p = len(p)
# len_s = len(s)
# flag = 0
# res = []
# for i in range(len_s-len_p+1):
# tmp = s[i:i+len_p]
# tmp = sorted(tmp)
# for j in range(len_p):
# if tmp[j] != p[j]:
# flag = 1
# break
# if not flag:
# res.append(i)
# flag=0
# return res
<file_sep># 度小满面试题 0513
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
m, n = len(word1), len(word2)
dp = [[0] * (m + 1) for _ in range(n + 1)]
# print(dp) # [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
# for _ in range(m + 1): dp[0][_] = _
# for _ in range(n + 1): dp[_][0] = _
for a in range(m+1):dp[0][a]=a
for b in range(n+1):dp[b][0]=b
# print(dp) # [[0, 1, 2, 3, 4, 5], [1, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0], [3, 0, 0, 0, 0, 0]]
for i in range(1, m + 1): # word1的个数
for j in range(1, n + 1): # word2的个数
if word1[i - 1] == word2[j - 1]:
dp[j][i] = dp[j - 1][i - 1]
else:
dp[j][i] = 1 + min(dp[j - 1][i], dp[j][i - 1], dp[j - 1][i - 1])
return dp[n][m]
if __name__ == '__main__':
word1 = "horse"
word2 = "ros"
print(Solution().minDistance(word1, word2))
<file_sep>class Solution(object):
def canJump(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
# 最远可达到的位置(index),不是落脚点,落脚点是这段中最远的位置
far = [] # 最远可以跳至的位置
for i, val in enumerate(nums):
temp = i+val
far.append(temp)
# print(far)
max_far = far[0]
jump = 0
# jump(当前位置)要<=最远能到的位置,这样才有路可以走
# 如果我现在处于的位置<最远能调到的位置,那么就一定true
while jump<len(nums) and jump<=max_far:
# 直到jump跳至数组尾部orjump超越了当前可以跳的最远位置
if far[jump]>max_far:
# 如果当前可以跳的更远,则更新max_far
max_far = far[jump]
jump += 1
if jump == len(nums):
return True
return False
if __name__ == '__main__':
nums = [2,3,1,1,4]
print(Solution().canJump(nums))<file_sep>import collections
class Solution(object):
def groupAnagramsmine(self, strs):
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
rs = []
di = dict()
index = 0
for str in strs:
tmp = []
for char in str:
tmp.append(char)
ans = "".join(sorted(tmp))
# print(ans)
if ans in di:
# di[ans] += 1
# 这里rs的下标怎么弄? 字典的value是返回list的index.
# rs[0].append(str) [['eat', 'tea', 'ate', 'nat'], ['tan'], ['bat']]
rs[di[ans]].append(str)
else:
di[ans] = index
rs.append([str])
index += 1
# print(di)
# print(rs)
return rs
def groupAnagrams(self, strs):
groups = collections.defaultdict(list)
print(list(groups))
for s in strs:
groups[tuple(sorted(s))].append(s)
return list(map(sorted, groups.values()))
def main():
strs = ["eat", "tea", "tan", "ate", "nat", "bat"]
myResult = Solution()
# 第一个字符串的排列之一是第二个字符串的子串
print(myResult.groupAnagrams(strs))
# print('----------------------------')
# import itertools
# # from itertools import permutations
# print(list(itertools.permutations([1, 2, 3], 3)))
if __name__ == '__main__':
main()<file_sep># 给定一个未排序的整数数组,找出其中没有出现的最小的正整数。
# 你的算法的时间复杂度应为O(n),并且只能使用常数级别的空间。
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if __name__ == '__main__':
nums = [1,2,0]
print(Solution().firstMissingPositive(nums))<file_sep># Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root: # 如果是叶子节点
return []
res = []
def tree_path(root,path,res):
# 说明是到了根节点,可以输出
if (root.left == None) and (root.right == None):
res.append(path+str(root.val))
return res
# 遍历左孩子
if root.left:
tree_path(root.left,path+str(root.val)+'->',res)
# 遍历右孩子
if root.right:
tree_path(root.right,path+str(root.val)+'->',res)
return res
tree_path(root,'',res)
return res
if __name__ == '__main__':
a = TreeNode(1)
b = TreeNode(2)
c = TreeNode(3)
a.left = b
a.right = c
d = TreeNode(1)
d.left = b
d.right = c
print(Solution().binaryTreePaths(a))
# ['1->2', '1->3']<file_sep># -*- coding:utf-8 -*-
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
res = []
if not root: # 如果是叶子节点
return []
res = []
def tree_path(root,path,res):
if root.left==None and root.right==None:
res.append(path+str(root.val))
return res
if root.left:
tree_path(root.left,path+str(root.val)+'->',res)
if root.right:
tree_path(root.right,path+str(root.val)+'->',res)
return res
tree_path(root,'',res)
return res
def main():
tree2 = TreeNode(2)
tree3 = TreeNode(3)
tree1 = TreeNode(1)
tree1.left = tree2
tree1.right = tree3
rs = Solution()
print(rs.binaryTreePaths(tree1))
if __name__ == '__main__':
main()
<file_sep>class Solution:
def nextPermutation(self, nums):
"""
Do not return anything, modify nums in-place instead.
"""
res = []
item = []
self.permu(nums,item,0,res)
# print(res)
def permu(self, nums, item, i, result):
if len(item)==len(nums):
result.append(item[:])
return
# item.append(nums[i])
# print(item)
for count in range(len(nums)):
self.permu(nums[:], item, i + 1, result)
if __name__ == '__main__':
nums = [1, 2, 3]
print(Solution().nextPermutation(nums))<file_sep>
# 使用栈
class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
res = 0
stack = [(-1,'(')]
for i, val in enumerate(s):
# 当前加入的元素是')',且栈顶元素是'('
if val == ')' and stack[-1][1] == '(':
stack.pop()
# 当前元素的(记录位置)下标已经弹出栈时,栈顶元素的位置
# 即为最长有效括号
res = max(res,i-stack[-1][0])
else:
stack.append((i, val))
# print(stack)
return res
def dpSolution(self,s):
n = len(s)
if n<2: return 0
# dp[i]表示第i个位置的最长有效长度
dp = [0]*n
res = 0
for i in range(1,n):
if s[i]==')' and s[i-1]=='(':
# 在历史匹配数上+2
dp[i]=dp[i-2]+2
if s[i]==')' and s[i-1]==')':
# 当前i的对称点索引是否存在
if i-dp[i-1]-1>=0:
if s[i-dp[i-1]-1]=='(':
dp[i] = dp[i-1]+dp[i-dp[i-1]-2]+2
# print(dp)
return max(dp)
if __name__ == '__main__':
# s = "(()"
s = "()(()"
# print(Solution().longestValidParentheses(s))
print(Solution().dpSolution(s))<file_sep># 实际上有两个约束条件,1. 0不能单独解码 2. 两位数必须在1与26之间。
# 这道题目实际上是用DP去做,仔细想的话,可以发现就是约束版的f(n) = f(n-1) + f(n-2);
# 其中如果是s[n-1]为0,f(n-1) = 0,f(n) = f(n-2),
# 因为0无法单独解码,而f(n-2)的条件则是必须在1与26之间,否则f(n) = f(n-1)。
class Solution:
def numDecodings(self, s):
if s == "" or s[0]=='0': return 0
dp=[1,1]
for i in range(2,len(s)+1):
if 10 <=int(s[i-2:i]) <=26 and s[i-1]!='0':#编码方式为2
dp.append(dp[i-1]+dp[i-2])
elif int(s[i-2:i])==10 or int(s[i-2:i])==20:#编码方式为1
dp.append(dp[i-2])
elif s[i-1]!='0':#编码方式为0
dp.append(dp[i-1])
else:
return 0
#print(dp[len(s)])
return dp[len(s)]
if __name__ == "__main__":
s = "12"
print(Solution().numDecodings(s))
"""
s[i-2]和s[i-1] 两个字符是10----26之间但不包括10和20这两个数时,有两种编码方式,比如23------>[“BC”,“W”],所以dp[i] = dp[i-1]+dp[i-2]
s[i-2]和s[i-1] 两个字符10或20这两个数时,有一种编码方式,比如10------>[“J”], 所以dp[i] = dp[i-2]
s[i-2]和s[i-1] 两个字符不在上述两种范围时,编码方式为零,比如27,比如01,所以dp[i] = dp[i-1
"""
<file_sep>class Solution(object):
def findKthLargest(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
if len(nums)==1:
return nums[0]
# 用sort实现list的降序排列
nums1 = sorted(nums,reverse=True)
# print(nums) [3, 2, 1, 5, 6, 4]
# print(nums1) [6, 5, 4, 3, 2, 1]
return nums1[k-1]
def main():
nums = [3,2,1,5,6,4]
k = 2
myResult = Solution()
print(myResult.findKthLargest(nums, k))
if __name__ == '__main__':
main()
<file_sep># 1.先将数组排序,从后往前遍历,先删除最后面一个,数组长度减一,如果数组中还有这个数就再减一,
# 这样就删除掉两个相同的数,如果数组中这个数唯一添加到sum列表里,最后返回这个列表。
class Solution(object):
def singleNumber(self, nums):
nums = sorted(nums)
i = len(nums)
sum = []
while i > 0:
a = nums[i - 1]
nums.remove(a)
i -= 1
if a in nums:
nums.remove(a)
i -= 1
else:
sum.append(a)
return sum
"""
class Solution(object):
def singleNumber(self, nums):
# # 超出时间限制
# rs = []
# dict = {}
# for i in nums:
# if i not in dict.keys():
# dict[i] = 1
# else:
# count = dict[i]
# count += 1
# dict[i] = count
# for key,value in dict.items():
# if value!=2:
# rs.append(key)
# if len(rs)==2:
# return rs
# 通过,优于我的字典存取
# class Solution(object):
# def singleNumber(self, nums):
# dict={}
# sum = []
# for num in nums:
# if num in dict:
# dict[num]+=1
# else:
# dict[num]=1
# for key in dict.keys():
# if dict[key]==1:
# sum.append(key)
# return sum
"""
def main():
nums = [1,2,1,3,2,5]
myResult = Solution()
print(myResult.singleNumber(nums))
if __name__ == '__main__':
main()
<file_sep>class Solution:
def canCompleteCircuit(self, gas, cost):
pass
if __name__ == '__main__':
gas = [1, 2, 3, 4, 5]
cost = [3, 4, 5, 1, 2]
print(Solution().canCompleteCircuit(gas,cost))
# https://leetcode-cn.com/problems/gas-station/<file_sep># list的每个位置都保留到目前位置,list的最大的和。
class Solution(object):
def maxSubArray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
for i in range(1,length):
num = max(nums[i]+nums[i-1],nums[i])
nums[i] = num
# print(num)
# print(nums) # [-2, 1, -2, 4, 3, 5, 6, 1, 5]
return max(nums)
def main():
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
myResult = Solution()
print(myResult.maxSubArray(nums))
if __name__ == '__main__':
main()
<file_sep># Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class SingleLinkList(object):
"""单链表"""
def __init__(self, node = None):
# 对外来说,不需要知道头结点这个属性,
# 内部使用,不暴露所以要私有化
self.__head = node
def is_empty(self):
"""链表是否为空"""
return self.__head == None
def add(self,item):
"""链表头部添加元素, 头插法"""
node = ListNode(item)
node.next = self.__head
self.__head = node
def travel(self):
"""遍历整个链表"""
cur = self.__head
while cur != None:
# if: cur.next!=None,会丢掉最后一个元素。
print(cur.val, end=' ')
cur = cur.next
print("")
class Solution(object):
# head是头结点,指向链表
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if head:
while head.val==val:
head = head.next
if head is None:
return head
pre = head
cur = pre.next
while cur != None:
if cur.val == val:
# 删除节点的时候,pre自动的就会移动
pre.next=cur.next
else:
# 如果没有删除节点,pre就没动
pre = pre.next
cur = cur.next
return head
if __name__ == '__main__':
# head = 1->2->6->3->4->5->6
ll = SingleLinkList()
ll.add(6)
ll.add(5)
ll.add(4)
ll.add(3)
ll.add(6)
ll.add(2)
ll.add(1)
ll.travel() # 1 2 6 3 4 5 6
val = 6
ans = Solution()
print(ans.removeElements(ll,val))<file_sep># 滑动窗口
class Solution:
def minWindow(self, s, t):
ls = len(s)
lt = len(t)
if not s or not t or ls < lt:
return ''
min_size = ls + 1
l = r = 0
start = 0
end = ls-1
map = {}
# 对t中的字符计数
for c in t:
map[c] = map.get(c, 0)+1
match = 0
while r < ls:
map[s[r]] = map.get(s[r], 0)-1
# 如果当前遇到的字符在map中出现过,则匹配数+1
match = match+1 if map[s[r]] >= 0 else match
# 当匹配完成时窗口左滑
if match == lt:
# 尝试左滑窗口 对之前遇到的字符出窗口
while map[s[l]] < 0:
map[s[l]] += 1
l += 1
if min_size > r - l + 1:
min_size = r - l + 1
start = l
end = r
r += 1
return '' if min_size > ls else s[start:end+1]
if __name__ == '__main__':
S = "ADOBECODEBANC"
T = "ABC"
print(Solution().minWindow(S, T))
<file_sep># 和264的区别在于,264是给定primes的个数,求第n个丑数
# 本题事先不知道primes的个数,所以t1,t2,...tn无法确定。
class Solution:
def nthSuperUglyNumber(self, n, primes):
"""
:type n: int
:type primes: List[int]
:rtype: int
"""
dp = [1] # res=[]
lenPrimes = len(primes)
idxPrimes = [0] * lenPrimes # 类似于t1,t2,t3记录位置
# print(idxPrimes) # [0, 0, 0, 0]
counter = 1
while counter < n:
min = pow(2, 32)
for i in range(0, lenPrimes):
# 找出最小值
temp = dp[idxPrimes[i]] * primes[i]
# 求最小的值
if temp < min:
min = temp
for i in range(0, lenPrimes):
# 更新最小值所在的位置,类似t1+=1
# === if res[-1] == res[t1]*2:
if min == dp[idxPrimes[i]] * primes[i]:
idxPrimes[i] += 1
print(idxPrimes)
# res.append(min(res[t1]*2, res[t2]*3, res[t3]*5))
dp.append(min)
counter += 1
# print(counter-1) # 11
# print(len(dp))# 12
return dp[counter - 1]
if __name__ == '__main__':
n = 12
primes = [2,7,13,19]
ans = Solution()
print(ans.nthSuperUglyNumber(n,primes))
<file_sep>class Solution:
def multiply(self, num1, num2):
if __name__ == '__main__':
num1 = "2"
num2 = "3"
print(Solution().multiply(num1,num2))<file_sep>class Solution:
def wordBreak(self, s, wordDict):
if s == '':
return True
if len(wordDict) == 1:
if s == wordDict[0]:
return True
else:
return False
dp = [0 for _ in range(len(s)+1)]
dp[0] = 1
for i in range(len(s)):
temp = s[:i+1]
for j in range(i+1):
if temp in wordDict and dp[j]:
dp[i+1] = 1
temp = temp[1:]
# if i==7:
# print(j,temp)
# print(i,j)
return dp[len(s)] == 1
if __name__ == '__main__':
s = "leetcode"
# print(s[:4])
# print(len(s))
wordDict = ["leet", "code"]
print(Solution().wordBreak(s, wordDict))
<file_sep>class Solution:
def jump(self, nums: List[int]) -> int:
"""
广度优先搜索,时间复杂度O(N),注意不要搜索重复的节点
"""
l = len(nums)
if l == 1: return 0
from collections import deque
q = deque()
res = 0
visited = [False for i in range(l)]
q.append(0)
visited[0] = True
while q:
for j in range(len(q)):
node = q.popleft()
for i in range(nums[node], 0, -1): # 从最大开始找有助于加快速度
new_index = node + i
if new_index >= l - 1:
return res + 1
if not visited[new_index]:
visited[new_index] = True
q.append(new_index)
res += 1
<file_sep># 回溯法
# 关键词:每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一个,
# 那么该路径不能再次进入该格子。
"""
基本思想:
0.根据给定数组,初始化一个标志位数组,初始化为false,表示未走过,true表示已经走过,不能走第二次
1.根据行数和列数,遍历数组,先找到一个与str字符串的第一个元素相匹配的矩阵元素,进入judge
2.根据i和j先确定一维数组的位置,因为给定的matrix是一个一维数组
3.确定递归终止条件:越界,当前找到的矩阵值不等于数组对应位置的值,已经走过的,这三类情况,都直接false,说明这条路不通
4.若k,就是待判定的字符串str的索引已经判断到了最后一位,此时说明是匹配成功的
5.下面就是本题的精髓,递归不断地寻找周围四个格子是否符合条件,只要有一个格子符合条件,就继续再找这个符合条件的格子的四周是否存在符合条件的格子,直到k到达末尾或者不满足递归条件就停止。
6.走到这一步,说明本次是不成功的,我们要还原一下标志位数组index处的标志位,进入下一轮的判断。
"""
class Solution:
def hasPath(self, matrix, rows, cols, path):
# write code here
for i in range(rows):
for j in range(cols):
if matrix[i*cols+j] == path[0]:
if self.find(list(matrix),rows,cols,path[1:],i,j):
return True
return False
def find(self,matrix,rows,cols,path,i,j):
if not path:
return True
matrix[i*cols+j]='0'
if j+1<cols and matrix[i*cols+j+1]==path[0]:
return self.find(matrix,rows,cols,path[1:],i,j+1)
elif j-1>=0 and matrix[i*cols+j-1]==path[0]:
return self.find(matrix,rows,cols,path[1:],i,j-1)
elif i+1<rows and matrix[(i+1)*cols+j]==path[0]:
return self.find(matrix,rows,cols,path[1:],i+1,j)
elif i-1>=0 and matrix[(i-1)*cols+j]==path[0]:
return self.find(matrix,rows,cols,path[1:],i-1,j)
else:
return False
if __name__ == '__main__':
martix = [["a","b","t","g"],["c","f","c","s"],["j","d","e","h"]]
rows = len(martix)
cols = len(martix[0])
path = [] # 就是str,
print(Solution().hasPath(martix,rows,cols,path))<file_sep># gg
# 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
# 输入: [0,1,0,3,12]
# 输出: [1,3,12,0,0]
# 必须在原数组上操作,不能拷贝额外的数组。
# 尽量减少操作次数。
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
# gg
# n = nums.count(0)
# print(n)
# for i in range(n):
# nums.remove(0)
# nums.extend([0]*n)
# print(nums)
# gg
# for i in range(len(nums)):
# if nums[i]==0:
# del nums[i]
# nums.append(0)
# return nums
# 思路三: 移动非零元素(操作次数就是非零元素的个数)
j = 0 # 记录非零元素应该换到第几个位置
for i in range(len(nums)):
if nums[i] != 0:
nums[j], nums[i] = nums[i], nums[j]
j += 1
def main():
nums = [0,1,0,3,12]
myResult = Solution()
print(myResult.moveZeroes(nums))
if __name__ == '__main__':
main()<file_sep>class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
i = 0
while i < len(nums):
if nums[i] == val:
del nums[i]
# i+=1
else:
i += 1
# print(nums)
return len(nums)
def main():
nums = [0,1,2,2,3,0,4,2]
val = 2
myResult = Solution()
print(myResult.removeElement(nums,val))
# print(range(val))
# del nums[2]
# print(nums)
if __name__ == '__main__':
main()
<file_sep>class Solution:
def simplifyPath(self,path):
pass
if __name__ == '__main__':
path = "/home/"
print(Solution().simplifyPath(path))<file_sep>class Solution:
def maxProfit(self,prices,fee):
n = len(prices)
buy = [0 for _ in range(n)] # 买入
sell = [0 for _ in range(n)] # 卖出
buy[0] = -prices[0]
for i in range(1,n):
# 如果不卖的话,此时还和i-1时一样;
# 如果卖出的话,此时的最大利润是买入时的最大利润+当前的价格-手续费
sell[i] = max(sell[i-1],buy[i-1]+prices[i]-fee)
# 如果不买的话,此时还和i-1时一样;
# 如果买的话,此时的最大利润是卖出时的最大利润-当前(买入时)的价格,手续费付一次
buy[i] = max(buy[i-1],sell[i-1]-prices[i])
return sell[-1]
if __name__ == '__main__':
prices = [1, 3, 2, 8, 4, 9]
fee = 2
print(Solution().maxProfit(prices,fee))<file_sep>class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
tmp = list(set(nums))
sumtmp = 0
for j in tmp:
sumtmp += j*2
return sumtmp-sum(nums)
def main():
listA = [4,1,2,1,2]
myResult = Solution()
print(myResult.singleNumber(listA))
if __name__ == '__main__':
main()<file_sep># -*- coding:utf-8 -*-
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if(needle==""):
return 0
if needle not in haystack:
return -1
flag = []
for i,vaL_i in enumerate(haystack):
if(vaL_i == needle[0]):
flag.append(i)
for j in flag:
for k in range(len(needle)):
if(haystack[j+k] != needle[k]):
break
if((k+1)==len(needle)):
return j
rs = j
return rs
def main():
haystack = "aaa"
needle = "aa"
rs = Solution()
print(rs.strStr(haystack,needle))
if __name__ == '__main__':
main()
<file_sep># 贪心算法
class Solution(object):
def findContentChildren(self, g, s):
g = sorted(g) # 需求
s = sorted(s) # 糖果
child = 0 # 已满足几个孩子
cookie = 0 # 尝试了几个糖果
while cookie < len(s) and child < len(g):
if g[child] <= s[cookie]:
child += 1
cookie += 1
return child
# 超出时间限制,自己写的
def findContentChildren1(self, g, s):
"""
:type g: List[int]
:type s: List[int]
:rtype: int
"""
g = sorted(g) # 需求
s = sorted(s) # 糖果
cnt = 0
flag = []
for index_g,val_g in enumerate(g):
for index_s, val_s in enumerate(s):
if val_s >= val_g and index_s not in flag:
cnt += 1
flag.append(index_s)
break
return cnt
if __name__ == '__main__':
g = [1,2]
s = [1,2,3]
print(Solution().findContentChildren(g,s))<file_sep># 给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的
# 最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
class Solution(object):
def coinChange1(self, coins, amount):
# 设dp[i]为构成金额i的最优解,即凑成总金额所需的最少的硬币个数
# 那么dp[1]=1,dp[2]=1,dp[5]=1,因为coins中有此金额,直接拿来用即可
# dp[i]=min(dp[i-1],dp[i-2],dp[i-5])+1
if amount<=0: return 0
# 初始化(这种方式初始化就不会dp越界)
max_int = 2<<31
dp = []
for i in range(amount+1):
if i not in coins:
dp.append(max_int)
else:
dp.append(1)
# 求最少硬币个数
for i in range(amount+1):
if i not in coins:
for j in range(len(coins)):
if i-coins[j]>0:
dp[i] = min(dp[i-coins[j]]+1,dp[i])
return dp[amount] if dp[amount]!=max_int else -1
def coinChange(self, coins, amount):
dp = [-1] * (amount + 1)
dp[0] = 0
for i in range(1, amount + 1):
for j in range(0, len(coins)):
if i >= coins[j] and dp[i - coins[j]] != -1:
if dp[i] == -1 or dp[i] > dp[i - coins[j]] + 1:
dp[i] = dp[i - coins[j]] + 1
return dp[amount]
if __name__ == '__main__':
coins = [1, 2, 5]
amount = 11
print(Solution().coinChange(coins,amount))
<file_sep>a = 1
b = 1
print(a is b) # True
import collections
n1 = '2500'
n2 = '0052'
print(collections.Counter(n1)==collections.Counter(n2))
str1 = "w20930"
print(str1.split('0'))
alist = [1,2,3,4,5]
for _ in range(len(alist)):
print(alist.pop())
"""
二分查找
def BiSearch(nums,k):
nums = sorted(nums)
print(nums)
low = 0
high = len(nums)-1
while low<=high:
mid = (low+high)//2
if nums[mid]==k:
return True
if nums[mid]<k:
low = mid+1
else:
high = mid-1
return -1
if __name__ == '__main__':
nums = [3,5,74,2,75,8,2,9]
k = 9
print(BiSearch(nums, k))
"""
# 浅拷贝
list1 = [[]]*3
print(list1) # [[], [], []]
list1[0].append(3) # [[3], [3], [3]]
# 是一个含有一个空列表元素的列表,所以[[]]*3表示3个指向这个空列表元素的引用,修改任何
# 一个元素都会改变整个列表
print(list1)
# 深拷贝
lists = [[] for i in range(3)]
lists[0].append(3)
lists[0].append(4)
lists[0].append(5)
print(lists) # [[3, 4, 5], [], []]
# 构建3行4列二维数组
myList = [([0] * 3) for i in range(4)]
print(myList) # [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
<file_sep>class Solution(object):
def lengthOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# dp[i]是以第i个元素结尾的最长上升子序列
if len(nums)==0:
return 0
dp = [1 for _ in range(len(nums))]
for i in range(1,len(nums)):
for j in range(i):
if nums[i] > nums[j]: # 当前元素要比之前的元素大,才可以跟在后面,构成上升
if dp[i] < dp[j]+1:
dp[i] = dp[j]+1
# print(dp[i])
# print(dp)
return max(dp)
if __name__ == '__main__':
nums = [10,9,2,5,3,7,101,18]
print(Solution().lengthOfLIS(nums))<file_sep># Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteNode(self, node):
# 只有对要删除节点node的访问权限
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
# 题目给的是删除节点,那说明这个节点可以舍弃了,我们把下一个节点的值拷贝
# 给当前要删除的节点,再删除下一个节点。
node.val = node.next.val
node.next = node.next.next
def myDelete(self,ptr,node):
if ptr:
while ptr.val == node:
ptr = ptr.next
if ptr is None:
return ptr
# ptr指向头结点,cur位于ptr的下面一个节点
cur = ptr.next
pre = ptr
while cur != None:
if cur.val == node:
pre.next = cur.next
else:
pre = pre.next
cur = cur.next
travel(ptr)
# class SingleList(object):
def strToListNode(input):
"""将list转为链表"""
numbers = input
dummyRoot = ListNode(0)
ptr = dummyRoot
for number in numbers:
ptr.next = ListNode(number)
ptr = ptr.next
ptr = dummyRoot.next
return ptr
def travel(input):
"""打印链表"""
cur = input
while cur != None:
print(cur.val, end=' ')
cur = cur.next
print("")
if __name__ == '__main__':
head = [4,5,1,9,5]
node = 5
ptr = strToListNode(head)
travel(ptr)
ans = Solution()
ans.myDelete(ptr,node)
<file_sep>import collections
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# recursion
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
else:
# 左子树高度
LD = self.maxDepth(root.left)
# 右子树高度
RD = self.maxDepth(root.right)
return max(RD,LD)+1
# queue for level order
def maxDepth2(self, root):
if not root:
return 0
tqueue, h = collections.deque(), 0
tqueue.append(root)
while tqueue:
nextlevel = collections.deque()
while tqueue:
front = tqueue.popleft()
if front.left:
nextlevel.append(front.left)
if front.right:
nextlevel.append(front.right)
tqueue = nextlevel
h += 1
return h
if __name__ == '__main__':
a = TreeNode(3)
b = TreeNode(9)
c = TreeNode(20)
d = TreeNode(15)
e = TreeNode(7)
a.right = c
a.left = b
c.right = e
c.left = d
print(Solution().maxDepth(a))<file_sep># 68. 文本左右对齐 hard
# 考察点:
class Solution:
def fullJustify(self, words, maxWidth):
if not words:
return ['']
result = []
i = 0
tmpLen = 0 # 记录当前行单词+' '的长度
counts = 0 # 记录当前行的单词个数
while i < len(words):
if tmpLen + len(words[i]) <= maxWidth:
tmpLen += len(words[i]) + 1
i += 1
counts += 1
else:
numSpace = maxWidth - tmpLen + counts # 空格总数
# print(i,numSpace,(tmpLen,counts))
if counts == 1:
result.append(words[i-1]+' '*numSpace)
else:
eachNum = numSpace // (counts-1) # 单词之间应放的空格数
restNum = numSpace % (counts-1) # 剩余空格数
tmp = ''
start = i - counts
while start < i - 1:
if restNum > 0:
# print(' ' * (eachNum + 1),eachNum + 1)
tmp = tmp + words[start] + ' ' * (eachNum + 1)
restNum -= 1
start += 1
else:
tmp = tmp + words[start] + ' ' * eachNum
start += 1
tmp = tmp + words[i-1]
result.append(tmp)
tmpLen = 0
counts = 0
# 最后一行
if counts != 0:
j = counts
tmp = ''
while j > 1:
tmp = tmp + words[i-j] + ' '
j -= 1
tmp = tmp + words[i-1]
tmp = tmp + ' ' * (maxWidth-len(tmp))
result.append(tmp)
return result
if __name__ == "__main__":
words = ["This", "is", "an", "example", "of", "text", "justification."]
maxWidth = 16
print(Solution().fullJustify(words,maxWidth))<file_sep># Definition for singly-linked list.
# 思路:
# 先把整个链表拉成一个链表,把这个链表的值全部存储在列表中,再将列表排序,新建一个链表重新一个一个指向列表的每一项
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
from queue import PriorityQueue
from heapq import heappush,heappop
class Solution(object):
def mergeKLists(self, lists):
dummy = curr = ListNode(None)
q = PriorityQueue()
for idx,node in enumerate(lists):
# 我的妈,链表竟然可以这样遍历
# print(idx,node) # TypeError: 'ListNode' object is not iterable
# 不可以这样遍历- -
if node:
q.put((node.val,idx,node))
# print(q.get()) # (1, 0, <__main__.ListNode object at 0x105d20518>)
while not q.empty():
# 最小的元素在链表尾部
_,idx,curr.next = q.get()
curr = curr.next
if curr.next:q.put((curr.next.val,idx,curr.next))
return dummy.next
## using minheap
def mergeKLists2(self, lists):
dummy = curr = ListNode(None)
heap = []
for idx, node in enumerate(lists):
if node:
heappush(heap, (node.val, idx, node))
while heap:
_, idx, curr.next = heappop(heap)
curr = curr.next
if curr.next:
heappush(heap, (curr.next.val, idx, curr.next))
return dummy.next
if __name__ == "__main__":
a = ListNode(1)
b = ListNode(4)
c = ListNode(5)
d = ListNode(1)
e = ListNode(3)
f = ListNode(4)
g = ListNode(2)
h = ListNode(6)
a.next = b
b.next = c
d.next = e
e.next = f
g.next = h
lists = [a,d,g]
print(Solution().mergeKLists(lists))
<file_sep># Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
if root is None: return None
# root为p或者root为q,说明找到了p和q其中一个
if (root is p) or (root is q): return root
# 递归调用当前节点的左子树
left = self.lowestCommonAncestor(root.left,p,q)
# 递归调用当前节点的右子树
right = self.lowestCommonAncestor(root.right,p,q)
# 若左子树找到了p,右子树找到了q,说明此时的root就是公共祖先
if left and right: return root
# 若左子树是none,右子树不是,说明右子树找到了A或B
if not left: return right
# # 若右子树是none,左子树不是,说明左子树找到了A或B
if not right:return left
# 如果左边,右边都没找到呢?
def lowestCommonAncestor_gg(self, root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
p_path, p_result = [], []
self.dfs(root, p, p_path, p_result)
q_path, q_result = [], []
self.dfs(root, q, q_path, q_result)
# 求最短的那dfs个路径
# print("p:",p_result)
# print("q:",q_result)
if len(p_result)<len(q_result):
path_len = len(p_result)
else:
path_len = len(q_result)
result = TreeNode(0)
for i in range(path_len):
if p_result[i].val == q_result[i].val:
result = p_result[i]
return result
def dfs(self,node,search,path,result):
# 先序遍历(深度优先遍历)
# node:正在遍历的结点;search:希望遍历到的结点
if node:
# 当node为空或已找到search结点,finish=1为找到
path.append(node)
while path:
node = path.pop()
result.append(node)
# print(result)
if node.val == search.val:
return result
if node.right:
path.append(node.right)
if node.left:
path.append(node.left)
return result
if __name__ == '__main__':
a = TreeNode(3)
b = TreeNode(5)
c = TreeNode(6)
d = TreeNode(2)
e = TreeNode(7)
f = TreeNode(4)
g = TreeNode(1)
h = TreeNode(0)
i = TreeNode(8)
a.right = g
a.left = b
b.left = c
b.right = d
d.left = e
d.right = f
g.right = i
g.left = h
p = TreeNode(5)
q = TreeNode(1)
print(Solution().lowestCommonAncestor(a,p,q))<file_sep>a = [[1,2],[3,4],[5,6]]
count = 0
for i in a:
i.append(10)
print(i)
print(count)
index = 4.0
print(int(index))
<file_sep># Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
elif abs(self.maxDepth(root.left) - self.maxDepth(root.right)) > 1:
return False
# 以下没想到
else:
return self.isBalanced(root.left) and self.isBalanced(root.right)
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
else:
# 左子树高度
LD = self.maxDepth(root.left)
# 右子树高度
RD = self.maxDepth(root.right)
return max(RD, LD) + 1
if __name__ == '__main__':
a = TreeNode(3)
b = TreeNode(9)
c = TreeNode(20)
d = TreeNode(15)
e = TreeNode(7)
a.right = c
a.left = b
c.right = e
c.left = d
print(Solution().isBalanced(a))<file_sep>
# 要求时间复杂度O(N)
# Python solution using hash
class Solution(object):
def twoSum(self, nums, target):
if len(nums) <= 1:
return False
buff_dict = {}
for i in range(len(nums)):
if nums[i] in buff_dict:
return [buff_dict[nums[i]], i]
else:
buff_dict[target - nums[i]] = i
if __name__ == '__main__':
nums = [2, 7, 11, 15]
target = 9
print(Solution().twoSum(nums,target))<file_sep># 快排排序
def QuickSort(nums,l,r):
i = l
j = r
if(i<j): # 大循环,控制整个
temp = nums[i] # 以第一个元素作为比较标准,比它大的都移到后面,比它小的都移到前面
while(i!=j): # 小循环,控制当前处理的一段
while(j>i and nums[j]>temp): j-=1
if(i<j): # 从右向左,找到了比temp小的元素
nums[i]=nums[j]
i+=1 # 别忘了!!
while(i<j and nums[i]<temp): i+=1
if(i<j):
nums[j]=nums[i]
j-=1
nums[i]=temp
QuickSort(nums,l,i-1)
QuickSort(nums,i+1,r)
return nums
# 冒泡排序
def BubbleSort(nums):
n = len(nums)-1 # 从最后一个元素开始,然后n-1,n-2,因为此时已经有了最大的冒到最后。
for i in range(n,-1,-1): # 控制未排序的长短,已经冒上来的(位于最后)不再做处理
flag = 0
for j in range(1,i+1,1): # 对未排序的部分,进行两两交换比较
if(nums[j-1]>nums[j]):
nums[j-1],nums[j] = nums[j],nums[j-1]
flag = 1
if(flag==0): # 没有数据进行交换
return nums
# 简单选择排序
def SelectSort(nums):
n = len(nums)
for i in range(0,n,1):
k = i
# 从无序序列中挑出一个最小的元素
for j in range(i+1,n,1):
if nums[k]>nums[j]:
k = j
# 最小元素与无序序列第一个元素交换
nums[k],nums[i]=nums[i],nums[k]
return nums
# 堆排序
def Sift(nums,low,high):
i = low
j = 2*i+1
# temp存储父节点
# temp = nums[i]
# 与孩子节点做比较,建堆
while(j<=high):
# 找到最大的那个孩子
if(j<high and nums[j]<nums[j+1]):
j+=1
# 父亲和孩子交换
if nums[i]<nums[j]:
nums[i],nums[j]=nums[j],nums[i]
# 继续向下调整
i = j
j = 2*i+1
else:
break
# nums[i]=temp
def heapSort(nums):
n = len(nums)-1 # 这里不减1是因为nums是完全二叉树,元素的存储必须从1开始。
# 从第一个非叶子节点开始构建初始堆
for i in range(n//2,-1,-1):
Sift(nums,i,n)
# 进行n-1次循环完成堆排序
for i in range(n,0,-1):
# 换出根节点,将其放在最终位置(根节点和最后一个元素交换)
nums[0],nums[i]=nums[i],nums[0]
# 在减少了1个元素的无序序列中进行调整(剩余部分调整堆)
Sift(nums,0,i-1)
return nums
def MergeSort(nums):
pass
if __name__ == '__main__':
nums = [49,38,65,200,97,76,13,27,49,100,-1]
print("快排:",QuickSort(nums,0,len(nums)-1))
print("冒泡:",BubbleSort(nums))
print("堆排序:",heapSort(nums))
print("简单选择:",SelectSort(nums))
print("归并:",MergeSort(nums))<file_sep># Definition for singly-linked list.
from functools import reduce
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
sum = self.convertNum(l1)+self.convertNum(l2)
sum = list(map(int,str(sum)))[::-1] # 807->[8, 0, 7]
p = ListNode(0)
head = p
for i in sum:
node = ListNode(i)
p.next = node
p = p.next
return head.next
def convertNum(self,node):
nums = []
while node:
nums.append(node.val)
node = node.next
# 将[2,4,3]转为243
nums = nums[::-1]
combine = reduce((lambda nums,y : nums*10+y),nums)
return combine
if __name__ == '__main__':
l1 = ListNode(2)
a = ListNode(4)
b = ListNode(3)
l1.next = a
a.next = b
l2 = ListNode(5)
c = ListNode(6)
d = ListNode(4)
l2.next = c
c.next = d
print(Solution().addTwoNumbers(l1,l2))<file_sep>def findnum(nums,k):
pass
if __name__ == '__main__':
nums = [[],[],[],[]]
k = 7
print(findnum(nums,k))<file_sep>class Solution:
def spiralOrder(self, matrix):
res = []
row = len(matrix)
col = len(matrix[0])
x1,y1 = 0,0
x2,y2 = row-1,col-1
while x1 <= x2 and y1 <= y2:
# print(x1,y1)
for i in range(x1, x2+1):
res.append(martix[y1][i])
# print(martix[y1][i])
for j in range(y1+1,y2+1):
res.append(martix[j][x2])
# print(martix[j][x2])
# print(x2,y2)
# print('-----')
if x1<x2 and y1<y2:
for i in range(x2-1,x1,-1):
res.append(martix[y2][i])
# print(martix[y2][i])
# print('------')
for j in range(y2,y1,-1):
res.append(martix[j][x1])
# print(martix[j][x1])
x1 += 1
y1 += 1
x2 -= 1
y2 -= 1
return res
if __name__ == '__main__':
martix = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
print(Solution().spiralOrder(martix))
# # result = list()
# # if not matrix:
# # return result
# # r, c = len(matrix), len(matrix[0])
# # x1, y1, x2, y2 = 0, 0, c - 1, r - 1
# # while x1 <= x2 and y1 <= y2:
# # print(x1,y1)
# # for i in range(x1, x2 + 1):
# # result.append(matrix[y1][i])
# #
# # for j in range(y1 + 1, y2 + 1):
# # result.append(matrix[j][x2])
# # if x1 < x2 and y1 < y2:
# # for i in range(x2 - 1, x1, -1):
# # result.append(matrix[y2][i])
# #
# # for j in range(y2, y1, -1):
# # result.append(matrix[j][x1])
# #
# # x1 += 1
# # y1 += 1
# # x2 -= 1
# # y2 -= 1
# #
# # return result<file_sep># 设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
#
# 注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
class Solution:
def maxProfit(self, prices):
n = len(prices)
sell1,sell2 = 0,0
# 一开始不能卖,但是可以买
buy1,buy2 = -prices[0],-prices[0]
# 只要考虑当天买和之前买哪个收益更高,当天卖和之前卖哪个收益更高
for i in range(1,n):
# i时刻的最大利润
buy1 = max(buy1,-prices[i])
# 当天卖出总的收益就是buy+prices[i]
sell1 = max(sell1,buy1+prices[i])
buy2 = max(buy2, sell1-prices[i])
sell2 = max(sell2, buy2+prices[i])
# 卖一次的收益大,还是卖两次的收益大
print(sell1)
print(sell2)
return max(sell1,sell2)
# https://blog.csdn.net/qq_17550379/article/details/83620892
if __name__ == '__main__':
prices = [3,3,5,0,0,3,1,4]
print(Solution().maxProfit(prices))<file_sep># 一个256*256的二维数组,逆时针旋转90度
def Rotate(nums):
row = len(nums)
# print(row)
column = len(nums[0])
# print(column)
B = [[0 for _ in range(row)] for _ in range(column)]
print(B)
for i in range(row):
for j in range(column-1,-1,-1):
# print(j)
B[i][j] = nums[j][row-1-i]
return B
if __name__ == '__main__':
nums = [[1,2,3],
[4,5,6],
[7,8,9]]
print(nums)
print("Rotating...")
print(Rotate(nums))<file_sep># 找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
# 说明:
# 所有数字都是正整数。
# 解集不能包含重复的组合。
class Solution:
def combinationSum3(self, k, n):
path=[]
result=[]
nums = [i for i in range(1,10)]
self.dfs(nums,k,n,0,path,result)
return result
def dfs(self,nums,k,n,start,path,result):
if len(path)==k and n==0 and path not in result:
result.append(path[:])
return
for i in range(start,len(nums)):
if nums[i]>n or k<0:
return
# k-=1
path.append(nums[i])
self.dfs(nums,k,n-nums[i],i+1,path,result)
# k+=1
path.pop()
if __name__ == '__main__':
k = 3
n = 9
print(Solution().combinationSum3(k,n))<file_sep># ac
class Solution(object):
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = s.lower()
# print(s)
news = ""
# s[1].is
for i in range(len(s)):
if s[i].isalnum(): # 题目要求:只考虑字母和数字字符
news+=s[i]
# print(news)
# news = 'aba'
length = len(news)
for i in range(length//2):
if news[i] != news[length-i-1]:
return False
return True
def main():
s = "A man, a plan, a canal: Panama"
myResult = Solution()
print(myResult.isPalindrome(s))
if __name__ == '__main__':
main()<file_sep>class Solution(object):
def minimumTotal(self, triangle):
"""
:type triangle: List[List[int]]
:rtype: int
"""
dp = [[0 for _ in range(len(row))] for row in triangle]
row = len(triangle)
for j in range(row):
dp[row-1][j] = triangle[row-1][j]
# for row_dp in dp:
# print(row_dp)
for i in range(row-2,-1,-1):
for j in range(i,-1,-1):
dp[i][j] = min(dp[i+1][j],dp[i+1][j+1])+triangle[i][j]
# for row_dp in dp:
# print(row_dp)
return dp[0][0]
if __name__ == '__main__':
# triangle = [[-10]]
triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
# print(triangle[0][0]) # 2
# print(triangle[2][1]) # 5
for row in triangle:
print(row)
# [2]
# [3, 4]
# [6, 5, 7]
# [4, 1, 8, 3]
# print(Solution().minimumTotal(triangle))<file_sep>class Solution(object):
def findMedianSortedArrays(self, A, B):
m, n = len(A), len(B)
if m>n:
A,B,m,n = B,A,n,m
if n == 0:
return -1
imin,imax,half_len = 0,m,(m+n+1)/2
while imin<=imax:
i = (imin+imax)/2
j = half_len-i
if i < m and B[j-1]>A[i]:
# B[i-1]<=A[i],说明A[i]太小了,那么需要增大i,增大
# i的时候要保证不能不能超过取值范围m
imin = i+1
elif i > 0 and A[i-1]>B[j]:
# 应该A[i-1]<=B[j],说i太大了
imax = i-1
else:
# i is perfect
if i==0: max_of_left=B[j-1]
elif j==0: max_of_left=A[i-1]
else: max_of_left=max(A[i-1],B[j-1])
# 如果是奇数区间
if (m+n)%2==1:return max_of_left
if i==m: min_of_right = B[j]
elif j==n: min_of_right=A[i]
else: min_of_right=min(A[i],B[j])
return (max_of_left+min_of_right)/2.0
# left_part | right_part
# A[0], A[1], ..., A[i - 1] | A[i], A[i + 1], ..., A[m - 1]
# B[0], B[1], ..., B[j - 1] | B[j], B[j + 1], ..., B[n - 1]
if __name__ == '__main__':
nums1 = [1, 2]
nums2 = [3, 4]
print(Solution().findMedianSortedArrays(nums1,nums2))
<file_sep># 找出第 n 个丑数
class Solution:
def nthUglyNumber(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 0:
return False
t1 = 0
t2 = 0
t3 = 0
res = [1]
while len(res) < n:
# 长度可以代表第几个
res.append(min(res[t1]*2, res[t2]*3, res[t3]*5))
print(res)
if res[-1] == res[t1]*2:
t1 += 1 # t1代表2所产生的丑数到第几步了
if res[-1] == res[t2]*3:
t2 += 1
if res[-1] == res[t3]*5:
t3 += 1
return res[-1]
if __name__ == '__main__':
n = 10
ans = Solution()
print(ans.nthUglyNumber(n))
<file_sep># 《剑指offer》面试题3
# using hash
def FindHash(nums):
n = len(nums)
if n==0:
return -1
nums_dict={}
for i in range(n):
if nums[i] not in nums_dict:
nums_dict[nums[i]] = i
else:
return nums[i]
return -1
def FindExchange(nums):
pass
# 题目二:不修改数组找出重复的数字
def Find2(nums):
pass
if __name__ == '__main__':
nums = [2,3,1,0,2,5,3]
# nums = []
print("第一题:")
print(FindHash(nums))
print(FindExchange(nums))
print("----------------")
print("第二题:")
print(Find2(nums))<file_sep>class Solution(object):
def lengthOfLongestSubstring(self, s):
hash_map = {}
left,res = 0,0
for i in range(len(s)): # i就是now,
# 如果当前字符从没出现过,或者是出现了,但不包含在当前窗口内:
if s[i] not in hash_map or left>hash_map[s[i]]:
res = max(res,i-left+1)
else:
left = hash_map[s[i]]+1
hash_map[s[i]] = i
print(hash_map)
return res
def lengthOfLongestSubstringPiggy(self, s):
"""
:type s: str
:rtype: int
"""
# if len(s)==1:
# return 1
hash_map = {}
max_len = 0
i,j = 0,0
for index,val in enumerate(s):
if index==0:
hash_map[val] = index
if val not in hash_map or hash_map[val] > i:
hash_map[val] = index
j += 1
else:
i,j = hash_map[val]+1,hash_map[val]+1
hash_map[val] = index
# print(i)
cur_len = j - i + 1
if cur_len > max_len:
max_len = cur_len
return max_len
if __name__ == '__main__':
s = "dvdf"
print(Solution().lengthOfLongestSubstring(s))<file_sep>class Solution:
def maxProfit(self, prices):
# 贪心算法,今天比明天赚就买入
profit = 0
for i in range(len(prices)-1):
if prices[i]<prices[i+1]:
profit += prices[i+1]-prices[i]
print(profit)
# 还可以用dp做
if __name__ == '__main__':
prices = [7,1,5,3,6,4]
print(Solution().maxProfit(prices))<file_sep># 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
# 递归
def inorderTraversal_recursive(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
self.helper(root,res)
return res
def helper(self,root,res):
if root:
self.helper(root.left,res)
res.append(root.val)
self.helper(root.right,res)
# 迭代
def inorderTraversal(self, root):
stack,res = [],[]
cur = root
while stack or cur:
while cur:
# travel to each node's left child, till reach the left leaf
stack.append(cur)
cur = cur.left
if stack: # 可以省略
# this node has no left child
cur = stack.pop()
# so let's append the node value
res.append(cur.val)
cur = cur.right
return res
if __name__ == '__main__':
a = TreeNode(1)
b = TreeNode(2)
c = TreeNode(3)
a.right = b
b.left = c
print(Solution().inorderTraversal(a))<file_sep>class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
# 单调队列
res = []
queue = []
n = len(nums)
if (n == 0 or k < 1 or n < k): return res
if k==1: return nums
for i in range(len(nums)):
while queue and queue[0]<i-k+1:
queue.pop(0)
while queue and queue[0]<nums[i]:
queue.pop()
queue.append(nums[i])
if i>=k-1:
res.append(queue[0])
return res
# 暴力求解
def maxSlidingWindow1(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if len(nums)==0:
return [0]
rs = []
for i in range(len(nums)-k+1):
tmp = max(nums[i:i+k])
rs.append(tmp)
return rs
if __name__ == '__main__':
nums = [7,2,4]
# [1, 3, -1, -3, 5, 3, 6, 7]
k = 2
print(Solution().maxSlidingWindow(nums,k))
<file_sep># 贪心
# 前一个数字比后一个数字大,则删掉前面的数字
class Solution(object):
def removeKdigits(self, num, k):
"""
:type num: str
:type k: int
:rtype: str
"""
#
if k==len(num):
return '0'
stack = []
for i in num:
while stack and k and i<stack[-1]:
stack.pop()
k -= 1
stack.append(i)
# 12345,k=3的时候
while k:
stack.pop()
k-=1
if stack is None:
return '0'
# 处理 10200,k=1的时候
print(stack)
print("".join(stack).lstrip('0')) #
# ['0', '2', '0', '0']
# 200
return "".join(stack).lstrip('0') or "0"
if __name__ == '__main__':
num = "10"
k = 1
print(Solution().removeKdigits(num,k))<file_sep>class Solution:
def permuteUnique(self, nums):
result = []
self.dfs(nums,0,[],result)
print(list(result))
def dfs(self,nums,start,path,result):
if len(path)==len(nums):
if path not in result:
result.append(path[:])
return
for i in range(start,len(nums)):
path.append(nums[i])
self.dfs(nums,i+1,path,result)
# path.pop()
if __name__ == '__main__':
nums = [1,1,2]
print(Solution().permuteUnique(nums))
<file_sep>class Solution:
def numTrees(self, n):
dp = [0]*(n+1)
dp[0],dp[1] = 1,1
for i in range(2,n+1):
for j in range(i):
dp[i] += dp[j]*dp[i-j-1]
return dp[n]
"""
假设n个节点存在二叉排序树的个数是G(n),令f(i)
为以i为根的二叉搜索树的个数
即有: G(n) = f(1) + f(2) + f(3) + f(4) + ... + f(n)
n为根节点,当i为根节点时,其左子树节点个数为[1, 2, 3, ..., i - 1],右子树节点个数为[i + 1, i + 2, ...n],
所以当i为根节点时,其左子树节点个数为i - 1
个,右子树节点为n - i,即f(i) = G(i - 1) * G(n - i),
上面两式可得: G(n) = G(0) * G(n - 1) + G(1) * (n - 2) + ... + G(n - 1) * G(0)
"""
if __name__ == '__main__':
# 给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
# 二叉搜索树:左边比它大,右边比它小
n = 3
print(Solution().numTrees(n))<file_sep># Definition for a Node.
class Node:
def __init__(self, val, neighbors):
self.val = val
self.neighbors = neighbors
class Solution:
def cloneGraph(self, node):
collect={}
def search(node):
if not node:
return
newnode=Node(node.val,[])
collect[node]=newnode
for i in node.neighbors:
if i not in collect:
newnode.neighbors.append(search(i))
else:
newnode.neighbors.append(collect[i])
return newnode
return search(node)
if __name__ == '__main__':
<file_sep>class Solution:
def mySqrt(self, x):
left = 1
right = x//2
if(x == 0):
return 0
def search(l, r):
if(int(l) >= int(r)):
return int(l)
mid = (l+r) / 2
if(mid*mid>x):
return search(l, mid)
elif(mid*mid<x):
return search(mid, right)
else:
return int(mid)
return search(left, right)
# if x<=0:
# return -1
# else:
# low = 0
# high = x
# mid = (low+high)//2
# while abs(mid*mid-x)!=0:
# if mid*mid>x:
# high = mid
# else:
# low = mid
# mid = (low+high)/2
# return mid
# gg2
# if x == 0:
# return 0
# i = 1; j = x / 2 + 1
# while( i <= j ):
# center = ( i + j ) / 2
# if center ** 2 == x:
# return center
# elif center ** 2 > x:
# j = center - 1
# else:
# i = center + 1
# return int(j)
if __name__ == '__main__':
x = 8
print(Solution().mySqrt(x))<file_sep>nums = "abc"
print(id(nums)) # 4540322232
a = nums[1:2] # 4525767688
print(a) # b
print(id(a)) # 4540204792 # 切片重新分配了地址
print(nums) # abc
print(id(nums)) # 4540322232
b = nums[:]
print(b) # abc
print(id(b)) # 4540322232 # 和nums的地址相同,因为string是基本数据类型!!!
print(nums) # abc
print(id(nums)) # 4540322232
nums = "123abc"
print(b) # abc
print(id(b)) # 不随着nums新改变而改变 4540322232
print(nums) # 123abc
print(id(nums)) # 分配了新的地址,与b(=之前的nums)的地址不同, 4541753304
# 堆内存栈内存、深浅拷贝,是针对复杂数据类型—-—对象、列表、字典这种
rs = []
print(id(rs)) # 4356762632
rs.append(3)
rs.append(4)
print(rs) # [3, 4]
print(id(rs)) # 4356762632
new_rs = rs[:]
print(new_rs) # [3, 4]
print(id(new_rs)) # 4356797640, 这里和上面的string就不同了,这里地址就变化了
rs.append([5,6])
print(new_rs) # [3, 4]
y_train = [1,2,3,4,5,2,3]
y = y_train[1:4]
y = 1
print(y)
print(y_train)
aaa = "1234"
print(aaa[:-1])
import math
num11=20.5
print(math.ceil(num11))<file_sep>class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
# nums1[m:m+n]=nums2[:n]
# nums1.sort()
# return nums1
# 比nums1当前元素大的都向后添加,比当前小的,当前向后移动
while m > 0 and n > 0:
if nums1[m - 1] >= nums2[n - 1]:
nums1[m + n - 1] = nums1[m - 1]
m = m - 1
else:
nums1[m + n - 1] = nums2[n - 1]
n = n - 1
if n > 0:
nums1[:n] = nums2[:n]
print(nums1)
def main():
nums1 = [1,2,3,0,0,0]
m = 3
nums2 = [2,5,6]
n = 3
myResult = Solution()
print(myResult.merge(nums1, m, nums2, n))
if __name__ == '__main__':
main()<file_sep># 有一个样例没有通过16/17,超出时间限制,说明不让暴力求解。
# 输入: numbers = [2, 7, 11, 15], target = 9
# 输出: [1,2]
# 解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
class Solution(object):
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
"""
暴力
for i in range(len(numbers)):
rs = []
left = target-numbers[i]
# print(left)
# rs.append(i+1)
for j in range(i+1,len(numbers)):
# print("j")
# print(j)
if numbers[j] == left:
# print("true")
# rs.append(j+1)
return [i+1,j+1]
# print(rs)
return None
"""
# 有序数据,利用快排
# 我们可以这样想,我们首先判断首尾两项的和是不是target,如果比target小,
# 那么我们左边+1位置的数(比左边位置的数大)再和右相相加,继续判断。如果比target大,
# 那么我们右边-1位置的数(比右边位置的数小)再和左相相加,继续判断。我们通过这样不断放缩的过程,
# 就可以在O(n)的时间复杂度内找到对应的坐标位置。(这和快速排序的思路很相似)
#
l=0
r=len(numbers)-1
while l<r:
if numbers[l]+numbers[r]==target:
return [l+1,r+1]
elif numbers[l]+numbers[r]<target:
l+=1
else:
r-=1
def main():
numbers = [2, 7, 11, 15]
target = 9
myResult = Solution()
print(myResult.twoSum(numbers, target))
if __name__ == '__main__':
main()<file_sep># 给定一个可能包含重复元素的整数数组 nums,
# 返回该数组所有可能的子集(幂集)。
# 说明:解集不能包含重复的子集。
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = [[]]
nums.sort() # 这句话好神奇,加了就对了 (说明:解集不能包含重复的子集。)
self.dfs(0, [], nums, res)
return res
def dfs(self, i, item, nums, res):
if i >= len(nums):
return
item.append(nums[i]) # 每个阶段的元素
res.append(item[:])
self.dfs(i+1,item,nums,res)
item.pop()
self.dfs(i+1,item,nums,res)
if __name__ == '__main__':
nums = [1,2,2]
print(Solution().subsetsWithDup(nums))
"""
class Solution(object):
def subsetsWithDup(self, nums):
path = []
result = []
nums.sort()
self.dfs(nums,0,path,result)
return result
def dfs(self,nums,start,path,result):
if path not in result:
result.append(path[:])
# 需要一个出口
if start == len(nums): # 之前报错,改了这里
return
for i in range(start,len(nums)):
path.append(nums[i])
self.dfs(nums,i+1,path,result)
path.pop()
"""
# 输入:
# [4,4,4,1,4]
# 输出:
# [[],[4],[4,4],[4,4,4],[4,4,4,1],[4,4,4,1,4],[4,4,4,4],[4,4,1],[4,4,1,4],[4,1],[4,1,4],[1],[1,4]]
# 预期:
# [[],[1],[1,4],[1,4,4],[1,4,4,4],[1,4,4,4,4],[4],[4,4],[4,4,4],[4,4,4,4]]<file_sep># Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
listNode = []
cur = head
while cur:
listNode.append(cur.val)
cur = cur.next
if len(listNode) == 0:
return True
curList = listNode[::-1]
return curList == listNode
# dummyRoot = ListNode(0)
# ptr = dummyRoot
# for i in curList:
# ptr.next = ListNode(i)
# ptr = ptr.next
# ptr = dummyRoot.next
# return ptr == head
if __name__ == '__main__':
head = [1,2]<file_sep>class Solution(object):
def searchRange(self, nums, target):
result = []
# print(self.leftbound(nums,target))
# print(self.rightbound(nums, target))
result.append(self.leftbound(nums, target))
result.append(self.rightbound(nums,target))
return result
def rightbound(self,nums,target):
low = 0
high = len(nums)-1
while low<=high:
mid = (low+high)//2
if target == nums[mid]:
if mid==len(nums)-1 or nums[mid+1]>target:
return mid
low = mid+1
elif nums[mid]>target:
high = mid-1
else:
low = mid+1
return -1
def leftbound(self, nums, target):
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
if target == nums[mid]:
if mid == 0 or target > nums[mid-1]:
return mid
high = mid-1
elif nums[mid] > target:
high = mid - 1
else:
low = mid + 1
return -1
if __name__ == '__main__':
nums = [5, 7, 7, 8, 8, 10]
target = 8
print(Solution().searchRange(nums,target))
<file_sep>class Solution:
def numIslands(self, grid):
if __name__ == '__main__':
grid = [[1, 1, 1, 1, 0],
[1, 1, 0, 1, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 0, 0]]
print(Solution().numIslands(grid))
<file_sep># 给定一个数组 candidates 和一个目标数 target ,
# 找出 candidates 中所有可以使数字和为 target 的组合。
# candidates 中的每个数字在每个组合中只能使用一次。
# -----------------------------------------------
# 递归的时候将 idx 加 1(需判断是否超出candidates的范围),另外由于题目输入的candidates可能包含相同的元素,
# 所以我们需要对得到的答案进行去重处理。
class Solution:
def combinationSum2(self, candidates, target):
path=[]
result=[]
candidates.sort()
self.dfs(candidates,target,0,path,result)
return result
# 我的想法是每次找过的元素都标记一下,然后下次找的时候就不可以选这个了
# i+1表明一个数字只能使用一次
def dfs(self,candidates,target,start,path,result):
# 判断出口
if target == 0 and path not in result:
result.append(path[:])
return
# 开始循环遍历
for i in range(start,len(candidates)):
if candidates[i]>target:
return
# i+1表明一个数字只能使用一次,这样下次递归的循环就从i+1开始了
self.dfs(candidates,target-candidates[i],i+1,path+[candidates[i]],result)
# https://blog.csdn.net/weixin_41958153/article/details/80936849
if __name__ == '__main__':
# candidates = [10, 1, 2, 7, 6, 1, 5]
candidates = [2,5,2,1,2]
target = 5
print(Solution().combinationSum2(candidates, target))<file_sep># 给定一个无重复元素的数组 candidates 和一个目标数 target ,
# 找出 candidates 中所有可以使数字和为 target 的组合。
# candidates 中的数字可以无限制重复被选取。
class Solution:
def combinationSum(self, candidates, target):
result = []
item = []
candidates.sort() # 首先要排序,必不可少,记得归纳总结这里,什么时候要排序??
self.dfs(candidates,target,0,item,result)
return result
def dfs(self,candidates,target,start,item,result):
if target==0:
# print(item)
result.append(item[:])
return
for i in range(start,len(candidates)):
# 剪枝
if candidates[i]>target:
return
self.dfs(candidates,target-candidates[i],i,item+[candidates[i]],result)
if __name__ == '__main__':
candidates = [2, 3, 6, 7]
target = 7
print(Solution().combinationSum(candidates,target))<file_sep>class Solution(object):
def isMatch(self, s, p):
import re
# re.match(pattern, string, flags=0)
# pattern 匹配的正则表达式
# string 要匹配的字符串(长的)
# re.I不区分大小写
match = re.match(p, s, re.I)
# 匹配成功re.match方法返回一个匹配的对象,否则返回None。
#
# 我们可以使用group(num) 或 groups() 匹配对象函数来获取匹配表达式。
print(match) # <_sre.SRE_Match object; span=(0, 1), match='a'>
print(match.group()) # a
if match is not None:
return match.group() == s
elif match is None:
return s == None
else:
return False
if __name__ == '__main__':
s = "aabd"
p = "a"
print(Solution().isMatch(s,p))<file_sep># del[1:3]删除指定区间
class Solution(object):
def compress22(self, chars):
# 双指针
pass
def compress(self, chars):
left = i = 0
while i < len(chars):
char, length = chars[i], 1
while (i + 1) < len(chars) and char == chars[i + 1]:
length, i = length + 1, i + 1
chars[left] = char
if length > 1:
len_str = str(length)
chars[left + 1:left + 1 + len(len_str)] = len_str
left += len(len_str)
left, i = left + 1, i + 1
return left
def compress_no_in_place(self, chars):
"""
:type chars: List[str]
:rtype: int
"""
char_map = {}
for index,val in enumerate(chars):
if val not in char_map:
char_map[val] = 1
else:
cnt = char_map[val]
cnt += 1
char_map[val] = cnt
rs = []
for key in char_map:
rs.append(key)
if char_map[key] == 1:
continue
else:
rs.append(str(char_map[key]))
print(rs)
length = "".join(rs)
return len(length)
def main():
chars = ["a","a","b","b","c","c","c"]
myResult = Solution()
print(myResult.compress(chars))
if __name__ == '__main__':
main()<file_sep>from pythonds.basic.stack import Stack
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
str1 = str(x).split('-')
# print(str1)
if len(str1)>1:
temp = '-'+str1[1][::-1]
if int(temp)>-2**31 and int(temp)<2**31-1:
return int(temp)
return 0
else:
if int(str1[0][::-1])>-2**31 and int(str1[0][::-1])<2**31-1:
return int(str1[0][::-1])
return 0
def reverse1(self, x):
"""
:type x: int
:rtype: int
"""
rs = []
pos = 0
flag=0
# listx = list(map(int, str(x)))
if str(x)[0]=='-':
flag = 1
x = str(x)[1:]
listx = list(map(int, str(x)))
revlistx = listx[::-1]
# print(revlistx)
for i in range(len(revlistx)):
if revlistx[i]!=0:
pos = i
break
# print(pos)
for j in range(pos,len(listx)):
rs.append(revlistx[j])
# print(rs)
tmp = ''.join(list(map(str,rs)))
# print(tmp)
if flag:
if int('-'+tmp)>-2**31 and int('-'+tmp)<2**31-1:
return int('-'+tmp)
else: return 0
if int(tmp) > -2 ** 31 and int(tmp) < 2 ** 31 - 1:
return int(tmp)
else: return 0
def main():
x = 1534236469
myResult = Solution()
print(myResult.reverse(x))
if __name__ == '__main__':
main()<file_sep># 马拉车算法——Manacher 算法
#
# 现将字符串通过添加特定字符'#',变成奇数个数。对新字符串使用中心扩展发即可,中心扩展法得到的半径就是子串的长度。
#
# 先转化字符串'35534321' ----> '#3#5#5#3#4#3#2#1#',然后求出以每个元素为中心的最长回文子串的长度。
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
# manacher 算法
s = '#' + '#'.join('{}'.format(s)) + '#'
lens=len(s)
max_str = ""
max_length = 0
for i in range(lens):
cur_length,cur_str = self.getLength(s,i)
if cur_length>max_length:
max_length = cur_length
max_str = cur_str
return max_str.replace('#','')
def getLength(self,s,index):
length = 0
string = s[index]
for i in range(1,index+1):
# 从index开始的原因是:从当前词开始向两边扩散
if i+index<len(s) and s[index-i]==s[index+i]:
length+=1
string = s[index-i:index+i]
else:
break
return length,string
"""
# 枚举实现——超时
max_length=0
max_string=""
for i in range(len(s)):
tmp = ""
for letter in s[i:len(s)]:
tmp+=letter
if tmp==tmp[::-1]:
if len(tmp)>max_length:
max_length=len(tmp)
max_string=tmp
return max_string
"""
if __name__ == '__main__':
s = "babad"
myResult = Solution()
print(myResult.longestPalindrome(s))<file_sep># -*- coding:utf-8 -*-
class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
rs = []
for i, val_i in enumerate(findNums):
flag = 0
for j, val_j in enumerate(nums):
if (val_j == val_i):
flag = 1
if (flag and val_j > val_i):
rs.append(val_j)
break
if (j == len(nums) - 1):
rs.append(-1)
return rs
def main():
nums1 = [2, 4]
nums2 = [1, 2, 3, 4]
myresult = Solution()
print(myresult.nextGreaterElement(nums1, nums2))
if __name__ == "__main__":
main()
<file_sep># Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
p = ListNode(0)
head = p
while l1 and l2:
if l1.val<l2.val:
p.next = l1
l1 = l1.next
p = p.next
else:
p.next = l2
l2 = l2.next
p = p.next
if l1:
p.next = l1
if l2:
p.next = l2
head = head.next
# self.printList(head)
return head
def printList(self,head):
while head:
print(head.val)
head = head.next
# def getLength(self,head):
# length = 0
# while head:
# length += 1
# head=head.next
# return length
if __name__ == '__main__':
l1 = ListNode(2)
a = ListNode(3)
b = ListNode(4)
l1.next = a
a.next = b
l2 = ListNode(1)
c = ListNode(3)
d = ListNode(5)
l2.next = c
c.next = d
print(Solution().mergeTwoLists(l1,l2))
<file_sep># 百度笔试(贪心+优先队列)
# 假设汽车油箱的容量是无限的,其中最初有 startFuel 升燃料。它每行驶 1 英里就会用掉 1 升汽油。
# 当汽车到达加油站时,它可能停下来加油,将所有汽油从加油站转移到汽车中。
# 为了到达目的地,汽车所必要的最低加油次数是多少?如果无法到达目的地,则返回 -1 。
# 注意:如果汽车到达加油站时剩余燃料为 0,它仍然可以在那里加油。如果汽车到达目的地时剩余燃料为 0,仍然认为它已经到达目的地。
class Solution:
def minRefuelStops(self, target,startFuel,stations):
if __name__ == '__main__':
target = 100, startFuel = 10, stations = [[10, 60], [20, 30], [30, 30], [60, 40]]
print(Solution().minRefuelStops(target,startFuel,stations))
# 我们出发时有 10 升燃料。
# 我们开车来到距起点 10 英里处的加油站,消耗 10 升燃料。将汽油从 0 升加到 60 升。
# 然后,我们从 10 英里处的加油站开到 60 英里处的加油站(消耗 50 升燃料),
# 并将汽油从 10 升加到 50 升。然后我们开车抵达目的地。
# 我们沿途在1两个加油站停靠,所以返回 2 。
<file_sep>class Solution(object):
def canFinish(self, numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
if __name__ == '__main__':
numCourses = [[1, 0]]
prerequisites = [[1, 0]]
"""
点的集合。
该方法的每一步总是输出当前无前趋(即入度为零)的顶点。为避免每次选入度为 0 的顶点时扫描整个存储空间,可设置一个队列暂存所有入度为 $0$ 的顶点。
具体做法如下:
1、在开始排序前,扫描对应的存储空间,将入度为 0 的顶点均入队列。
2、只要队列非空,就从队首取出入度为 0 的顶点,将这个顶点输出到结果集中,并且将这个顶点的所有邻接点的入度减 1,在减 1 以后,发现这个邻接点的入度为 0 ,就继续入队。
"""
<file_sep># 求abc和def的全排列
# 全排列就是回溯, 求最短路径也是DFS
# DFS
class Solution(object):
def letterCombinations(self, digits):
"""
:type digits: str
:rtype: List[str]
"""
# 存储结果的数组
res = []
inputstr = []
if len(digits) == 0:
return res
hash_map = {0:"",1:"",2:"abc",3:"def",4:"ghi",5:"jkl",6:"mno",7:"pqrs",8:"tuv",9:"wxyz"}
for i in digits:
inputstr.append(hash_map[int(i)])
# print(inputstr) # ['abc', 'def']
# 闭包
def dfs(cur_str,i,res):
if len(cur_str)==len(inputstr): # abc def ghi
res.append(cur_str)
return
for count in range(len(inputstr[i])): # abc
dfs(cur_str+inputstr[i][count],i+1,res)
dfs("",0,res)
return res
if __name__ == '__main__':
digits ="23"
print(Solution().letterCombinations(digits))<file_sep>class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
# 递归求解,但超出时间限制
# if n == 1:
# return 1
# elif n == 2:
# return 2
# else:
# return (self.climbStairs(n-1)+self.climbStairs(n-2))
# 动态规划求解,两个if判断是我之前没想到的,
# 当n==1的时候,我dp[1]=2就是越界,之前没考虑到。
if n==0:
return 0
if n==1:
return 1
dp = [0 for _ in range(n)]
dp[0]=1
dp[1]=2
for i in range(2,n):
dp[i]=dp[i-1]+dp[i-2]
# print(dp)
return dp[n-1]
if __name__ == '__main__':
n = 5
print(Solution().climbStairs(n))<file_sep>
# lc300是求最长上升子序列的长度是是多少,是求len
# 这道题是求最长上升子序列那个最长的那个一共有多少个,多少组,有多少个可能性构成
class Solution:
def findNumberOfLIS(self, nums):
res = 0
max_len = 1
# dp[i]是以第i个元素结尾的最长递增子序列的长度
dp = [1 for _ in range(len(nums))]
# 每个递增序列对应的子序列的个数
cnt = [1 for _ in range(len(nums))]
for i in range(1,len(nums)):
for j in range(i):
if nums[i]>nums[j] and dp[i] < dp[j]+1:
dp[i] = dp[j]+1
cnt[i] = cnt[j]
elif nums[i]>nums[j] and dp[i] == dp[j]+1:
cnt[i] += cnt[j]
max_len = max(max_len,dp[i])
# print(dp)
# print(cnt)
for k in range(len(nums)):
if dp[k] == max_len:
res += cnt[k]
return res
if __name__ == '__main__':
nums = [2,2,2,2,2]
print(Solution().findNumberOfLIS(nums))
<file_sep>class Solution:
def judgeSquareSum(self, c):
"""
:type c: int
:rtype: bool
"""
d = {}
for i in range(0,int(c**0.5)+1):
d[i * i] = 1
if c - i*i in d:
return True
return False
"""
class Solution(object):
def judgeSquareSum(self, c):
clist = [] # 用列表超出时间限制,所以用字典比用列表快
# a = round(pow(c,0.5)) # 下取整
# a = math.ceil(a) # 上取整
num = int(c**0.5)
# print(num)
for i in range(num+1):
# print(clist)
if i*i not in clist:
clist.append(i * i)
# print(c-i*i)
if c-i*i in clist:
return True
return False
"""
if __name__ == '__main__':
c = 4
ans = Solution()
print(ans.judgeSquareSum(c))<file_sep>class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
for i in range(len(t)):
if t[i] not in s:
return False
return True
# or
# return sorted(s)==sorted(t)
# 字符串中str.count(i),计算单个字母出现的次数
# or
# if len(t) != len(s):
# return False
# c = set(t)
# for i in c:
# if t.count(i) != s.count(i):
# return False
# return True
def main():
s = "aacc"
t = "ccac"
myResult = Solution()
print(myResult.isAnagram(s, t))
if __name__ == '__main__':
main()
<file_sep># 给定一个排序数组,你需要在原地删除重复出现的元素,
# 使得每个元素最多出现两次,返回移除后数组的新长度。
# 27,26,283思路相同
class Solution:
def removeDuplicates(self, nums):
i = 2 # 每个元素最多出现两次
lens = len(nums)-1
while i<lens:
if nums[i]==nums[i-2]:
del nums[i]
lens -=1
else:
i += 1
return len(nums)
def test(self,nums):
print(nums.count(1)) # 3
if __name__ == "__main__":
# nums = [1,1,1,2,2,3]
nums = [0,0,1,1,1,1,2,3,3]
# nums = [1,1,1,1]
res = Solution()
print(res.removeDuplicates(nums))
# Solution().test(nums)<file_sep># 贪心
# 452. 用最少数量的箭引爆气球 !! 最
<file_sep>class Solution:
def combinationSum4(self, nums, target):
def dfs(self):
if __name__ == '__main__':
nums = [1, 2, 3]
target = 4
print(Solution().combinationSum4(nums,target))<file_sep># 二分查找
class Solution(object):
def searchInsert(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
low = 0
high = len(nums)-1
while(low <= high):
mid = (low+high)//2
if target == nums[mid]:
return mid
elif target < nums[mid]:
high = mid-1
else:
low = mid+1
# 如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
return low
if __name__ == '__main__':
nums = [1, 3, 5, 6]
target = 2
print(Solution().searchInsert(nums, target))<file_sep>class Solution:
def rotate(self, matrix):
"""
Do not return anything, modify matrix in-place instead.
"""
n = len(matrix)
for i in range(n):
for j in range(i+1,n):
matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j]
# print(matrix) # 沿着轴翻转
for i in range(n):
for j in range(n//2):
matrix[i][j],matrix[i][n-j-1]=matrix[i][n-j-1],matrix[i][j]
print(matrix) # 沿着中轴,镜像翻转
if __name__ == '__main__':
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(Solution().rotate(matrix))<file_sep>from string import ascii_lowercase
class Solution(object):
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
rs = [S]
def flip(ch):
if ch in ascii_lowercase:
return ch.upper()
else:
return ch.lower()
# one line
# return ch.upper() if ch in ascii_lowercase else ch.lower()
for i in range(len(S)):
if S[i].lower() not in ascii_lowercase: # 说明当前字母是数字
continue
else:
ans = []
for cur_s in rs:
# print(i,cur_s)
tmp = cur_s[:i]+flip(cur_s[i])+cur_s[i+1:]
ans.append(tmp)
rs+=ans
# print(rs)
# ['1ab2', '1Ab2']
# ['1ab2', '1Ab2', '1aB2', '1AB2']
return rs
def letterCasePermutation1(self, S):
"""
:type S: str
:rtype: List[str]
"""
res = [""]
print(len(res)) # 1
for s in S:
# print(s)
if not s.isalpha():
for i in range(len(res)):
# print(i) # 0 1 0 1 2 3
res[i] += s
else:
for i in range(len(res)):
# print(i) # 0 0 1
tmp = res[i]
res[i] += s.lower()
# print(i, res)
res.append(tmp + s.upper())
print(i, res)
return res
def main():
S = "1ab2"
myResult = Solution()
# 第一个字符串的排列之一是第二个字符串的子串
print(myResult.letterCasePermutation(S))
if __name__ == '__main__':
main()<file_sep># Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
cur = head
count = 1
while cur != None:
count += 1
cur = cur.next
mid = (count-1) // 2 + 1
point = 1
cur = head
if mid == 1:
return head
while cur != None:
if point != mid:
point += 1
cur = cur.next
else:
return cur
# INPUT:[1,2,3,4,5] RETURN: [3,4,5]
# INPUT:[1,2,3,4,5,6] RETURN: [4,5,6]
if __name__ == '__main__':
head = [1,2,3,4,5]<file_sep># 动态规划
class Solution(object):
def countSubstrings(self, s):
"""
:type s: str
:rtype: int
"""
new_word = []
for i in range(len(s)):
for k in range(1,len(s)):
# print(k)
if i+k > len(s):
end = len(s)
print(end)
new_word.append(s[i:end])
break
else:
new_word.append(s[i:i+k])
print(new_word)
count = 0
while len(new_word):
length = len(new_word)
tmpword = new_word[::-1] # 反转字符串
if (length == 1):
count += 1
continue
else:
for i, val_i in enumerate(new_word):
if (i > (length / 2 - 1)):
count+=1
continue
if (val_i != tmpword[i]):
continue
count+=1
new_word = new_word[:-1]
print(count)
def main():
s = "abc"
myResult = Solution()
print(myResult.countSubstrings(s))
if __name__ == '__main__':
main()<file_sep># 给定不同面额的硬币和一个总金额。写出函数来计算可以凑成总金额的硬币组合数。
# 假设每一种面额的硬币有无限个。
class Solution:
def change(self, amount, coins):
# dp[i]是构成金额i的硬币数目
dp = [0 for _ in range(amount)]
for i in range(amount):
for j in range(len(coins)):
dp[i] = dp[i - coins[j]] + 1
if __name__ == '__main__':
amount = 5
coins = [1, 2, 5]
print(Solution().change(amount,coins))<file_sep>class Solution(object):
def wiggleMaxLength(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
# 在连续递增,递减时,只保留首尾元素
def wigglelength(type,nums):
if (len(nums)==0): return 0
# pre来保存已生成的摆动序列的最后一个值
pre,cnt = nums[0],1
for i in range(1,len(nums)):
if type and pre<nums[i]:
cnt+=1
type = False
elif not type and pre>nums[i]:
cnt+=1
type=True
pre = nums[i] # 摆动序列的最后一个值
return cnt
# 后比前大,遍历一次; 前比后大,遍历一次
return max(wigglelength(True,nums),wigglelength(False,nums))
if __name__ == '__main__':
nums = [1,2,3,4,5,6,7,8,9]
print(Solution().wiggleMaxLength(nums))<file_sep>class Solution:
def findOrder(self, numCourses, prerequisites):
# 拓扑排序
if numCourses < 2:
return [0]
rd = [0]*numCourses
edges = [[] for i in range(numCourses)]
for li in prerequisites:
for i in range(len(li)-1):
rd[li[i]] += 1
for i in range(1, len(li)):
edges[li[i]].append(li[i-1])
stack = []
for i in range(numCourses):
if rd[i] == 0:
stack.append(i)
ans = []
while stack:
tmp = stack.pop()
ans.append(tmp)
for i in range(len(edges[tmp])):
y = edges[tmp][i]
rd[y] -= 1
if rd[y] == 0:
stack.append(y)
if len(ans) == numCourses:
return ans
return []
if __name__ == '__main__':
numCourses = 2
prerequisites = [[1, 0]]
print(Solution().findOrder(numCourses, prerequisites))
"""
这个问题相当于查找一个循环是否存在于有向图中。如果存在循环,则不存在拓扑排序,因此不可能选取所有课程进行学习。
通过 DFS 进行拓扑排序
拓扑排序也可以通过 BFS 完成。
"""
<file_sep>class Solution(object):
def maxProfit(self, prices):
# 贪心
# 在价格最低的时候买入,差价最大的时候卖出
if len(prices) < 2:
return 0
minval = prices[0]
profit = 0
for val in prices:
minval = min(minval,val)
# print(minval)
profit = max(profit,val-minval)
# print(profit)
return profit
# dp
# 只要考虑当天买和之前买哪个收益更高,当天卖和之前卖哪个收益更高
if __name__ == '__main__':
prices = [7,6,4,3,1]
print(Solution().maxProfit(prices))<file_sep>"""
给定一个由许多词根组成的词典和一个句子。你需要将句子中的所有继承词用词根替换掉。
如果继承词有许多可以形成它的词根,则用最短的词根替换它。
"""
class Solution(object):
def replaceWords(self, dict, sentence):
"""
:type dict: List[str]
:type sentence: str
:rtype: str
"""
# root_dict = set(dict)
# raws = sentence.split()
# res = []
# for raw in raws:
# flag = False
# for i in range(0, len(raw)):
# prefix = raw[0:i + 1]
# if prefix in root_dict:
# res.append(prefix)
# flag = True
# break
# if flag == False:
# res.append(raw)
# return ' '.join(res)
myDict = set(dict)
res = [] # res由字符串变为列表就不内存溢出了
for word in sentence.split(): # 字符串按空格划分
cur_word = ""
for i,ch in enumerate(word):
cur_word += ch
if cur_word in myDict:
res.append(cur_word)
break
if i==len(word)-1:
res.append(word)
return " ".join(res)
def main():
dict = ["cat", "bat", "rat"]
sentence = "the cattle was rattled by the battery"
myresult = Solution()
print(myresult.replaceWords(dict, sentence))
if __name__ == "__main__":
main()
<file_sep># 滑动窗口
class Solution:
def minSubArrayLen(self, s, nums):
if __name__ == '__main__':
s = 7
nums = [2, 3, 1, 2, 4, 3]
print(Solution().minSubArrayLen(s, nums))
<file_sep>class Solution(object):
def maxArea(self, height):
# 暴力 43/50
# res = 0
# for i in range(len(height)-1): # i是起始点
# for j in range(1,len(height)): # j是终止点
# w = j-i
# h = min(height[i],height[j])
# res = max(res,w*h)
# return res
# 贪心——谁短谁不要
if not height or len(height) == 1:
return 0
low = 0
high = len(height)-1
area = (high-low)*min(height[low],height[high])
while low<high:
if height[low]<height[high]: # 谁短谁不要,low短
area = area if area>height[low]*(high-low) else height[low]*(high-low)
low += 1
else:
# high短
area = area if area>height[high]*(high-low) else height[high]*(high-low)
high -= 1
return area
if __name__ == '__main__':
height = [1,8,6,2,5,4,8,3,7]
print(Solution().maxArea(height))<file_sep>import numpy as np
a = "loveleetcode"
print(a[:-1])
print(a[-5::-1]) # octeelevol
nums1 = [1,2,3]
nums2 = []
print(nums1+nums2) # [1, 2, 3]
for i in range(4):
i = i + 3
print(i)
n = 1
print(n//3)
nums = [10,3,8,9,4]
nums.sort()
print(nums)
print("-----------")
scales = 2**np.arange(3,6)
print(scales)
import re
a = "Hello world!How are you?My friend.Tom"
print(re.split(" |!|\?|\.", a))
sss = "abc"
print(sss[2:3]) #c
print(sss[2:4]) #c
print(sss[2:5]) #c
a = [5, 2, 3, 1, 4]
print(sorted(a)) # 升序
print(a)
# [1, 2, 3, 4, 5]
# [5, 2, 3, 1, 4] sorted不改变原list
print(sorted(a,reverse=True)) # 实现降序
# [5, 4, 3, 2, 1]
import os
import sys
# 打开文件
path = "/Users/weiwenjing/Documents/2018spring"
dirs = os.listdir(path)
# 是一个列表 ['.DS_Store', 'conference', '卡纳赫拉.jpg', 'project', '人工智能前沿']
print(dirs)
print('--------------------------------------')
# 输出所有文件和文件夹
for file in dirs:
print(file)
# .DS_Store
# conference
# 卡纳赫拉.jpg
# project
# 人工智能前沿
# 求均值
L = [1,2,3,4,5]
print(np.mean(L))
# del[1:3]删除指定区间
L2 = [1,2,3,4,5]
del L2[1:3]
print(L2) # [1, 4, 5],删除1,2下标
del L2[0]
print(L2) # [4, 5],删除0下标
# del L2
# print(L2) # NameError: name 'L2' is not defined
a = [0, 2, 2, 3]
a.remove(2)
print(a) # [0, 2, 3],删除指定元素
b = [4, 3, 5]
print(b.pop(1)) # 3
print(b) # [4, 5]
s = "abcdefs"
print(s[0:3])
c = "acbed"
print(sorted(c))
seats = [0,1,1,0,0,0]
print(seats.index(1))
alist = [1,2,3,4]
print(alist[0:3:2]) # [1, 3]
print(alist[1:]) # [2, 3, 4]
print(alist[2:]) # [2, 3, 4]
print(alist[3:]) # [4]
print(alist[4:]) # []
ii = 5
print(ii//2+1)
listNode = [1,2,3]
print(listNode[::-1])
for i in range(4):
print(i) # 0,1,2,3
A = [1,2,3]
print("origin A:{}".format(A))
A[0] = A[2]
print("changed A:{}".format(A))
colors = ['b','a','c','d']
for i in range(0,len(colors)):
print(i,colors[i])
a = [0 for _ in range(3)]
# b = [a for _ in range(3)]
# print(b) # [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
b = [list(a) for _ in range(3)]
print(b) # [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(0):
print(i) # 啥也不输出
print('')
print('-----------------2019/1/3--------------------------')
rs = ['123','245','345']
for s in rs:
print(s)
# 123
# 245
# 345
n1 = list(np.full((1,3),2))
n2 = list(np.full((1,3),3))
n3 = list(np.full((1,3),4))
m = n1+n2+n3
# print(m[0,:])
# print(m)
A = [[1,2,3,4,5,6],
[7,8,9,10,11,12],
[13,14,15,16,17,18]]
A = np.mat(A)
print(A[0,:]) # [[1 2 3 4 5 6]]
print(A[0,:1]) #[[1]]
print(A[0,:4]) # [[1 2 3 4]]
print(A[0,:5]) # [[1 2 3 4 5]]
"""
# 用列表生成m行n列的矩阵
m,n = map(int,input().split())
matrix = [[0]*(m)]*(n)
print(matrix)
# 2 3
# [[0, 0], [0, 0], [0, 0]]
# 这种方式生成的矩阵存在一定的问题,比如,无法给特定位置的元素赋值,例如:
matrix[1][1] = 9
print(matrix)
# [[0, 9], [0, 9], [0, 9]]
# 可见,第二列的元素全部被赋值为9了
# 采用numpy生成想要维度的矩阵
x,y = map(int,input().split())
a = np.ones((x+1,y+1))
print(a)
# [[1. 1. 1. 1. 1.]
# [1. 1. 1. 1. 1.]
# [1. 1. 1. 1. 1.]]
a[1][1] = 9
print(a)
# [[1. 1. 1. 1. 1.]
# [1. 9. 1. 1. 1.]
# [1. 1. 1. 1. 1.]]
"""
# x,y = map(int,input().split())
x,y = 2,4
A = np.ones((x+1,y+1))
for i in range(0,x+1):
A[i][0] = i
for j in range(1,y+1):
A[i][j] = A[i][j-1]+1
print(A)
# [[ 1. 1. 1. 1. 1.]
# [ 1. 2. 3. 4. 5.]
# [ 1. 3. 6. 10. 15.]]
abc = [1,2,3,4]
del abc[-1]
print(abc) # [1, 2, 3]
print(abc[-2])
<file_sep># -*- coding:utf-8 -*-
class Solution(object):
def checkRecord(self, s):
"""
:type s: str
:rtype: bool
"""
n=len(s)
count_A,count_L=0,0
for i in range(n):
if s[i]=='A':
count_A += 1
if count_A>1:
return False
if s[i]=='L':
count_L += 1
if count_L>2:
return False
if s[i] != 'L':
count_L=0
return True
def main():
s = "LLPPPLL"
myresult = Solution()
print(myresult.checkRecord(s))
if __name__ == "__main__":
main()
| cdcadada190adde0c41890f2fec45d12d126e8ce | [
"Python"
] | 125 | Python | kt8506/Leetcode | 56730ff8cf432dda08bb56a0e783400d0375af69 | bd2d55ea635268a4f6521599e35d58224e9e7e5e |
refs/heads/master | <repo_name>dvrylc/discoversounds<file_sep>/README.md
# discoversounds
> Music discovery tool
<file_sep>/app/components/ArtistRow.jsx
import React from 'react';
import ArtistLink from './ArtistLink';
class ArtistRow extends React.Component {
render() {
var artist = this.props.artist;
console.log(artist.name);
var backgroundUrl = artist.images.length > 0 ?
`url('${artist.images[artist.images.length - 1].url}')` :
'#283593';
var styles = {
background: backgroundUrl,
backgroundRepeat: 'no-repeat',
backgroundSize: 'cover',
backgroundPosition: 'center'
}
return (
<div className="artist-row">
<div className="img" style={styles} />
<span className="artist">{artist.name}</span>
<ArtistLink artist={artist.name} handleNewSearch={this.props.handleNewSearch} />
</div>
);
}
}
export default ArtistRow;
<file_sep>/app/components/SearchBox.jsx
import React from 'react';
import SuperAgent from 'superagent/lib/client';
class SearchBox extends React.Component {
// Constructor
constructor() {
super();
this.handleChange = this.handleChange.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
}
// Lifecycle
componentDidUpdate() {
if (this.props.triggerNewSearch) {
this.props.handleRelatedArtists([]);
this.triggerSearch();
}
}
// Functions
triggerSearch() {
this.getArtistID(this.props.initialArtist)
.then(this.getRelatedArtists)
.then(this.props.handleRelatedArtists)
.catch(this.props.handleSearchError);
}
getArtistID(initialArtist) {
// Query for artist ID and return promise
return new Promise((fulfill, reject) => {
SuperAgent
.get(`https://api.spotify.com/v1/search?q=${encodeURIComponent(initialArtist)}&type=artist&limit=5`)
.end((err, res) => {
if (err) throw err;
var matchingArtists = res.body.artists.items;
matchingArtists.forEach(artist => {
if (artist.name.toUpperCase() === initialArtist.toUpperCase()) {
fulfill(artist.id);
}
});
reject('Artist not found');
});
});
}
getRelatedArtists(artistID) {
// Query for related artists and return promise
return new Promise((fulfill, reject) => {
SuperAgent
.get(`https://api.spotify.com/v1/artists/${artistID}/related-artists`)
.end((err, res) => {
if (err) throw err;
fulfill(res.body.artists);
});
});
}
// Event handlers
handleChange(e) {
this.props.handleSearchChange(e.target.value);
}
handleKeyDown(e) {
/*
If user hits Enter and artist field is not blank,
trigger a new search
*/
if (e.key === 'Enter' && this.props.initialArtist !== '') {
// Blur the input
e.target.blur();
this.triggerSearch();
}
}
// Render
render() {
return (
<div className="search">
<input
value={this.props.initialArtist}
onChange={this.handleChange}
onKeyDown={this.handleKeyDown}
placeholder="Enter an artist"
autoComplete="off" autoCorrect="off" autoCapitalize="off" spellCheck="false"
/>
</div>
);
}
}
export default SearchBox;
<file_sep>/app/components/ArtistList.jsx
import React from 'react';
import ArtistRow from './ArtistRow';
class ArtistList extends React.Component {
render() {
if (this.props.error) {
return (
<div className="artist-list">
<span className="error-message">{this.props.errorMessage}</span>
</div>
);
} else {
var artistRows = this.props.artists.map((artist, index) => {
return <ArtistRow key={index} artist={artist} handleNewSearch={this.props.handleNewSearch} />
});
return (
<div className="artist-list">
{artistRows}
</div>
);
}
}
}
export default ArtistList;
<file_sep>/app/main.js
import React from 'react';
import ReactDOM from 'react-dom';
import './style.scss';
import Header from './components/Header';
import SearchBox from './components/SearchBox';
import ArtistList from './components/ArtistList';
class App extends React.Component {
// Constructor
constructor() {
super();
this.handleRelatedArtists = this.handleRelatedArtists.bind(this);
this.handleSearchChange = this.handleSearchChange.bind(this);
this.handleSearchError = this.handleSearchError.bind(this);
this.handleNewSearch = this.handleNewSearch.bind(this);
this.state = {
error: false,
errorMessage: '',
initialArtist: '',
relatedArtists: [],
triggerNewSearch: false
}
}
// Event listeners
handleRelatedArtists(artists) {
this.setState({
error: false,
errorMessage: '',
relatedArtists: artists,
triggerNewSearch: false
});
}
handleSearchChange(artist) {
this.setState({
initialArtist: artist
});
}
handleSearchError(err) {
this.setState({
error: true,
errorMessage: err,
initialArtist: '',
relatedArtists: [],
triggerNewSearch: false
});
}
handleNewSearch(artist) {
this.setState({
initialArtist: artist,
triggerNewSearch: true
});
}
// Render
render() {
return (
<div id="app">
<Header />
<SearchBox
initialArtist={this.state.initialArtist}
triggerNewSearch={this.state.triggerNewSearch}
handleRelatedArtists={this.handleRelatedArtists}
handleSearchChange={this.handleSearchChange}
handleSearchError={this.handleSearchError}
/>
<ArtistList
error={this.state.error}
errorMessage={this.state.errorMessage}
artists={this.state.relatedArtists}
handleNewSearch={this.handleNewSearch}
/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app-container'));
| 9f7be9c44af7faabc0dc3bfb014742990087081f | [
"Markdown",
"JavaScript"
] | 5 | Markdown | dvrylc/discoversounds | e5e6bab07ccbc7a083d8a842f31e7732aef96ab9 | 2b1d4f081e27ef119bfaa753407d57dc06b9ccc1 |
refs/heads/master | <file_sep>// set up ======================================================================
var express = require('express');
var app = express(); // create our app w/ express
var mongoose = require('mongoose'); // mongoose for mongodb
var port = process.env.PORT || 8080; // set the port
var database = require('./config/database'); // load the database config
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var q = require('q');
var oauthserver = require('oauth2-server');
// var loadash = require('loadash');
// configuration ===============================================================
mongoose.connect("mongodb://ranjoy.ghosh88:<EMAIL>:55930/storedata"); // Connect to remote MongoDB instance.
app.use(express.static('./public')); // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended': 'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
app.oauth = oauthserver({
model: require('./appServer/utilities/authModel.js'),
grants: ['client_credentials', 'password'],
debug: true
});
app.all('/oauth/token', app.oauth.grant());
app.use(app.oauth.errorHandler());
// routes ======================================================================
require('./appServer/apis/customerAuth.js')(app);
require('./appServer/apis/customerDetails.js')(app);
// require('./appServer/apis/customerFeedback.js')(app);
require('./appServer/apis/fileProcesses.js')(app);
app.route('/*').get(function(req, res) {
return res.sendFile(__dirname + '/public/index.html');
});
// listen (start app with node server.js) ======================================
app.listen(port);
console.log("App listening on port " + port);
<file_sep># votingapp
Download test.zip
unzip the file run below commands to run it
npm install
node server.js
username and password testing123
| 94ce5c85372d4bf81a8864395a092b834c66822a | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | ranjoyghosh88/votingapp | 08b1fd7c790bd4bfa9012c5aa5dff4630a9a63f6 | c0fd2637218491dd9cd2b40ff0763418cde6ec25 |
refs/heads/master | <file_sep>/**
* Created by Haoran(<NAME> on 2016/10/31.
*/
import java.io.*;
import java.util.*;
class Main{
static String ReadLn(int maxLength){ // utility function to read from stdin,
// Provided by Programming-challenges, edit for style only
byte line[] = new byte [maxLength];
int length = 0;
int input = -1;
try{
while (length < maxLength){//Read untill maxlength
input = System.in.read();
if ((input < 0) || (input == '\n')) break; //or untill end of line ninput
line [length++] += input;
}
if ((input < 0) && (length == 0)) return null; // eof
return new String(line, 0, length);
}catch (IOException e){
return null;
}
}
public static void main(String args[]) // entry point from OS
{
Main myWork = new Main(); // Construct the bootloader
myWork.Begin(); // execute
}
void Begin(){
// Your program here
String s1;
while((s1 = Main.ReadLn(255)) != null) {
StringTokenizer idata = new StringTokenizer(s1);
int i1 = Integer.parseInt(idata.nextToken());
int i2 = Integer.parseInt(idata.nextToken());
int max = work(i1,i2);
System.out.println(i1 + " " + i2 + " " + max);
}
}
// You can insert more classes here if you want.
static int parse(long i){
int j = 1;
while (i != 1){
if (i%2 == 0)
i/=2;
else i = 3*i +1;
j++;
}
return j;
}
static int work(int i1, int i2){
int min = 0;
if(i2 < i1) {
int temp = i1;
i1 = i2;
i2 = temp;
}
for(int i = i1; i<=i2;i++){
if(parse(i) > min)
min = parse(i);
}
return min;
}
}
| 61dc2f336eacbef55e1f66a4e6024cd4ae1af7b1 | [
"Java"
] | 1 | Java | kasperyhr/uva-100-pc-110101 | 0b92386c8898fcc84397f14decb13972ba222243 | 9c0eb5f3e88cd38a02f5af5833b0cf0a9d312e2a |
refs/heads/main | <repo_name>mendsalbert/react-native-try<file_sep>/screens/Home.js
import React from "react"
import { View, Text, StyleSheet, SafeAreaView, ScrollView } from "react-native"
import { FontAwesome5 } from "@expo/vector-icons"
import { MaterialCommunityIcons } from "@expo/vector-icons"
import { Feather } from "@expo/vector-icons"
const DeviceDataScreen = () => {
return (
<SafeAreaView>
<ScrollView>
<View style={styles.mainContainer}>
<View style={styles.sensorContainer}>
<View style={styles.sensor}>
<Text style={styles.number}>20F</Text>
<FontAwesome5
style={styles.icon}
name="temperature-low"
size={24}
color="white"
/>
<Text style={styles.text}>Temperature</Text>
</View>
<View style={styles.sensor}>
<Text style={styles.number}>50%</Text>
<MaterialCommunityIcons
style={styles.icon}
name="air-humidifier"
size={24}
color="white"
/>
<Text style={styles.text}>Humidity</Text>
</View>
<View style={styles.sensor3}>
<Text style={styles.number}>20C</Text>
<MaterialCommunityIcons
style={styles.icon}
name="coolant-temperature"
size={24}
color="white"
/>
<Text style={styles.text}>Heat sensor</Text>
</View>
<View style={styles.camera}>
{/* <Text style={styles.number}>20C</Text> */}
<Feather
style={styles.icon}
name="video"
size={24}
color="white"
/>
<Text style={styles.text}>Live View</Text>
</View>
<View style={styles.camera}>
{/* <Text style={styles.number}>20C</Text> */}
<Feather
style={styles.icon}
name="video"
size={24}
color="white"
/>
<Text style={styles.text}>Live View</Text>
</View>
</View>
<View></View>
</View>
</ScrollView>
</SafeAreaView>
)
}
const styles = StyleSheet.create({
mainContainer: {
flex: 1,
backgroundColor: "#121212",
width: "100%",
},
sensorContainer: {
marginHorizontal: 8,
marginVertical: 27,
width: "90%",
flexDirection: "row",
// flex: 1,
flexWrap: "wrap",
alignContent: "center",
justifyContent: "center",
},
text: {
color: "white",
textAlign: "center",
},
number: {
color: "#fb5b5a",
textAlign: "center",
fontSize: 40,
},
sensor: {
backgroundColor: "#1d1d1d",
padding: 23,
shadowColor: "black",
// width: 130,
// height: "70%",
// width: 120,
// height: 120,
margin: 10,
borderRadius: 6,
flexDirection: "column",
justifyContent: "center",
alignContent: "center",
alignSelf: "center",
},
sensor3: {
width: "90%",
backgroundColor: "#1d1d1d",
margin: 10,
borderRadius: 6,
padding: 23,
},
camera: {
width: "90%",
backgroundColor: "#1d1d1d",
margin: 10,
borderRadius: 6,
padding: 23,
},
icon: {
// backgroundColor: "red",
fontSize: 40,
alignSelf: "center",
},
})
export default DeviceDataScreen
<file_sep>/navigations/MainNavigator.js
import React from "react"
import {
createStackNavigator,
HeaderBackground,
HeaderTitle,
} from "@react-navigation/stack"
import { NavigationContainer } from "@react-navigation/native"
import { Platform } from "react-native"
import Colors from "../constants/Colors"
import AuthScreen from "../screens/user/Auth"
import HomeScreen from "../screens/Home"
const StackNavigator = createStackNavigator()
const ShopNavigator = () => {
const isLoggedIn = true
return (
<NavigationContainer>
<StackNavigator.Navigator>
{!isLoggedIn ? (
<StackNavigator.Screen
name="AuthScreen"
component={AuthScreen}
options={{ headerTransparent: true, headerTitle: "" }}
/>
) : (
<StackNavigator.Screen
name="Home"
component={HomeScreen}
options={{
headerTransparent: true,
headerTitle: "",
headerTintColor: "white",
}}
/>
)}
</StackNavigator.Navigator>
</NavigationContainer>
)
}
export default ShopNavigator
// const ProductsNavigation = createStackNavigator(
// {
// productsOverview: ProductOverviewScreen,
// },
// {
// defaultNavigationOptions: {
// headerStyle: {
// backgroundColor: Platform.OS === "android" ? Colors.primary : "",
// },
// headerTintColor: Platform.OS === "android" ? "white" : Colors.primary,
// },
// }
// )
// export default createAppContainer(ProductsNavigation)
| a201b330b4afac7df0826f7c88414e1eae539b94 | [
"JavaScript"
] | 2 | JavaScript | mendsalbert/react-native-try | 5388624f7b6da330fe64b3259c23063d7025dfa2 | 851506b6949624dc8ff21cf7781d19148704b023 |
refs/heads/master | <file_sep>package org.firstinspires.ftc.teamcode;
import com.qualcomm.robotcore.eventloop.opmode.OpMode;
import com.qualcomm.robotcore.hardware.DcMotor;
public class LearningTest extends OpMode {
public DcMotor leftMotor;
@Override
public void init() {
}
@Override
public void loop() {
telemetry.addData("speed", leftMotor.getPower());
}
}
| 1c3884ae5cff892e4a8a1603d0a2ade744c51dc6 | [
"Java"
] | 1 | Java | Team8097/TeamBotcats2016-2017 | 0942323f3319ce0c79e0aa9d2940493844efbf6d | 41e7e2144876b6700b465a6c892b1eca593d2666 |
refs/heads/master | <repo_name>lockc/java-dev<file_sep>/design-pattrerns/src/main/java/sandbox/lockc/patterns/behavioural/visitor/BookPrettyPrintVisitor.java
package sandbox.lockc.patterns.behavioural.visitor;
import sandbox.lockc.patterns.behavioural.visitor.api.Visitor;
import sandbox.lockc.patterns.behavioural.visitor.domain.Book;
public class BookPrettyPrintVisitor implements Visitor<Book> {
@Override
public void visit(Book book) {
StringBuilder sb = new StringBuilder();
sb.append("Title: ").append(book.getTitle()).append("\n")
.append("Author: ").append(book.getAuthor()).append("\n")
.append("ISBN: ").append(book.getISBN()).append("\n")
.append("Published: ").append(book.getPublised()).append("\n");
System.out.println(sb.toString());
}
}
<file_sep>/java7/java7-cert/src/main/java/sandbox/lockc/javacert/localization/ListResourceBundles.java
package sandbox.lockc.javacert.localization;
import java.util.Locale;
import java.util.ResourceBundle;
public class ListResourceBundles {
public static void main(String[] args) {
Locale locale = Locale.getDefault();
// String base = "sandbox.lockc.javacert.localization.ListResourceBundles.ResBundle";
String base = "sandbox.lockc.javacert.localization.ResBundle";
ResourceBundle messages = ResourceBundle.getBundle(base, locale);
printMessages(messages);
messages = ResourceBundle.getBundle(base, Locale.FRENCH);
printMessages(messages);
}
private static void printMessages(ResourceBundle bundle) {
System.out.println(String.format("----------- %s --------------", bundle.getLocale()));
System.out.println(bundle.getString("1"));
System.out.println(bundle.getString("2"));
System.out.println(bundle.getString("3"));
System.out.println(bundle.getString("4"));
}
}
<file_sep>/java7/java7-cert/src/main/java/sandbox/lockc/javacert/concurrency/ThreadClass.java
package sandbox.lockc.javacert.concurrency;
public class ThreadClass {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
Thread.currentThread().wait();
}
}
<file_sep>/recipes-service/src/main/java/recipes/client/ClientApp.java
package recipes.client;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import recipes.domain.Ingredient;
import recipes.domain.Recipe;
import recipes.domain.RecipeBook;
public class ClientApp {
private static Client client = ClientBuilder.newClient();
public static void main(String[] args) {
createRecipe();
}
public static void createRecipe() {
RecipeBook recipeBook = new RecipeBook();
recipeBook.setId(3);
Ingredient i = new Ingredient();
i.setDescription("Yummy stuff");
List<Ingredient> ingredients = new ArrayList<Ingredient>();
ingredients.add(i);
Recipe r = new Recipe();
r.setName("Test Meal 1");
r.setPageNumber(12);
r.setRecipeBook(recipeBook);
r.setIngredients(ingredients);
WebTarget webTarget = client.target("http://localhost:8080/recipes");
Invocation.Builder invocationBuilder =
webTarget.request(MediaType.APPLICATION_XML);
Response response = invocationBuilder.put(Entity.entity(r, MediaType.APPLICATION_XML), Response.class);
System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
}
public static void deleteRecipe() {
RecipeBook recipeBook = new RecipeBook();
recipeBook.setId(3);
Ingredient i = new Ingredient();
i.setDescription("Yummy stuff");
List<Ingredient> ingredients = new ArrayList<Ingredient>();
ingredients.add(i);
Recipe r = new Recipe();
r.setName("Test Meal 1");
r.setPageNumber(12);
r.setRecipeBook(recipeBook);
r.setIngredients(ingredients);
WebTarget webTarget = client.target("http://localhost:8080/recipes");
Invocation.Builder invocationBuilder =
webTarget.request(MediaType.APPLICATION_XML);
Response response = invocationBuilder.put(Entity.entity(r, MediaType.APPLICATION_XML), Response.class);
System.out.println(response.getStatus());
System.out.println(response.readEntity(String.class));
}
}
<file_sep>/java8/java8-examples/src/main/java/lockc/java8/lambda/ConstructorReferencesExample2.java
package lockc.java8.lambda;
public class ConstructorReferencesExample2 {
public static void main(String[] args) {
SomeClass someClass = new SomeClass("THE THING");
someClass.print();
// From this ...
SomeOtherClass someOtherClass2 = someClass.switchTo(new Switcher<SomeClass, SomeOtherClass>() {
@Override
public SomeOtherClass switchIt(SomeClass it) {
return new SomeOtherClass(it.value);
}
});
someOtherClass2.print();
// to this ...
SomeOtherClass someOtherClass1 = someClass.switchTo(it -> {
return new SomeOtherClass(it.value);
});
// to this ...
someOtherClass1 = someClass.switchTo(it -> new SomeOtherClass(it.value));
someOtherClass1.print();
// to this ...
SomeOtherClass someOtherClass = someClass.switchTo(SomeOtherClass::new);
someOtherClass.print();
// and visa versa
SomeClass someClass2 = someOtherClass.switchTo(SomeClass::new);
someClass2.print();
}
@FunctionalInterface
private static interface Switcher<T, S> {
S switchIt(T it);
}
private static class SomeClass {
private String value;
public <T> SomeClass(T value) {
this.value = value.toString();
}
public <S> S switchTo(Switcher<SomeClass, S> switcher) {
return switcher.switchIt(this);
}
public void print() {
System.out.println(super.toString() + " : " + this.toString());
}
@Override
public String toString() {
return value;
}
}
private static class SomeOtherClass {
private String value;
public <T> SomeOtherClass(T value) {
this.value = value.toString();
}
public <S> S switchTo(Switcher<SomeOtherClass, S> switcher) {
return switcher.switchIt(this);
}
public void print() {
System.out.println(super.toString() + " : " + this.toString());
}
@Override
public String toString() {
return value;
}
}
}
<file_sep>/design-pattrerns/src/main/java/sandbox/lockc/patterns/behavioural/chain/other/ChainHandler.java
package sandbox.lockc.patterns.behavioural.chain.other;
public interface ChainHandler {
void handle(Request request);
}
<file_sep>/design-pattrerns/README.md
# Design Patterns
A Java project to demonstrate a variety of design patterns within each of these categories:
* Creational Patterns
* Structural Patterns
* Behavioural patterns
<file_sep>/recipes/src/main/resources/joins and unions.sql
# Where clause
select r.id RECIPE_ID, r.name RECIPE_NAME, r.page_no PAGE,
rb.id RECIPE_BOOK_ID, rb.name RECIPE_BOOK_NAME
from recipes r, recipe_books rb
where r.recipe_book_id = rb.id
# Inner Join - The INNER JOIN keyword selects all rows from both tables as long as there is a match between the columns in both tables
select r.id, r.name, r.page_no
from recipes r
inner join recipe_books rb
on r.recipe_book_id = rb.id
# Union - The UNION operator is used to combine the result-set of two or more SELECT statements. Removes duplicates
select r.recipe_book_id from recipes r
union
select rb.id from recipe_books rb
# Union All - The UNION ALL operator is used to combine the result-set of two or more SELECT statements. Contains duplicates
select r.recipe_book_id from recipes r
union all
select rb.id from recipe_books rb
select r.id RECIPE_ID, r.name RECIPE_NAME, r.page_no PAGE,
rb.id RECIPE_BOOK_ID, rb.name RECIPE_BOOK_NAME
from recipes r, recipe_books rb
where r.recipe_book_id = rb.id
and r.id = 375
union
select i.id, i.recipe_id, i.desc, i.id, i.id from ingredients i
where i.recipe_id = 375 <file_sep>/design-pattrerns/src/main/java/sandbox/lockc/patterns/behavioural/strategy/Client.java
package sandbox.lockc.patterns.behavioural.strategy;
public class Client {
public static void main(String[] args) {
SimpleCalculator calc = new SimpleCalculator();
calc.calculate(10, 2, new DivideStrategy());
calc.calculate(10, 2, new MultiplyStrategy());
calc.calculate(10, 2, new AddStrategy());
calc.calculate(10, 2, new SubtractStrategy());
}
}
<file_sep>/design-pattrerns/src/main/java/sandbox/lockc/patterns/creational/abstractfactory/RedCar.java
package sandbox.lockc.patterns.creational.abstractfactory;
public class RedCar implements AbstractCar {
private String colour;
@Override
public void polish() {
}
@Override
public void paint() {
colour = "RED";
}
@Override
public void assemble() {
}
@Override
public String getColour() {
return colour;
}
}
<file_sep>/java7/java7-cert/src/main/java/sandbox/lockc/javacert/nio/PathStuff.java
package sandbox.lockc.javacert.nio;
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathStuff {
public static void main(String[] args) {
/* ********************************
* normalize - resolves redundant elements
* ********************************/
/*
* prints '/home'
*/
Path p = Paths.get("/home/./lockc/../.");
System.out.println(p.normalize());
/* ********************************
* relativize -
* ********************************/
/*
* prints 'git'
*/
Path p1 = Paths.get("/home/lockc/");
Path p2 = Paths.get("/home/lockc/git");
System.out.println(p1.relativize(p2));
/*
* prints '..'
*/
p1 = Paths.get("/home/lockc/git");
p2 = Paths.get("/home/lockc/");
System.out.println(p1.relativize(p2));
/*
* prints 'sub'
*/
p1 = Paths.get("target");
p2 = Paths.get("target/sub");
System.out.println(p1.relativize(p2));
/* ********************************
* resolve - merges two paths
* ********************************/
/*
* prints 'a/b/c/d'
*/
p1 = Paths.get("a/b/");
p2 = Paths.get("c/d");
System.out.println(p1.resolve(p2));
/*
* prints '/a/b/c/d'
*/
p1 = Paths.get("/a/b/");
p2 = Paths.get("c/d");
System.out.println(p1.resolve(p2));
/*
* prints '/c/d'
*/
p1 = Paths.get("a/b/");
p2 = Paths.get("/c/d");
System.out.println(p1.resolve(p2));
/*
* prints '/c/d'
*/
p1 = Paths.get("/a/b/");
p2 = Paths.get("/c/d");
System.out.println(p1.resolve(p2));
/*
* prints 'a'
*/
p1 = Paths.get("/home/lockc/a/b/c/d");
System.out.println(p1.subpath(2, 3).toString());
/*
* prints 'a'
*/
p1 = Paths.get("/home/lockc/a/b/c/d");
System.out.println(p1.getName(2).toString());
}
}
<file_sep>/java8/java8-examples/src/main/java/lockc/java8/streams/StreamCreation.java
package lockc.java8.streams;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Stream;
/**
* This class shows some examples of how to generate a stream
*
* @author clock
*/
public class StreamCreation {
public static void main(String[] args) {
example1();
example2();
example3();
example4();
example5();
}
/**
* Example using {@link Stream#of(Object[])} varargs to create a stream
*/
public static void example1() {
Stream<String> stream = Stream.of("one", "two", "three", "four");
doSomethingWithStream(stream, 't');
}
/**
* Example using {@link Stream#of(Object[])} with an Array to create a stream
*/
public static void example2() {
String[] strings = {"one", "two", "three", "four"};
Stream<String> stream = Stream.of(strings);
doSomethingWithStream(stream, 'f');
}
/**
* Example using {@link Stream#builder()}
*/
public static void example3() {
Stream<Object> stream = Stream.builder().add("one").add("two").add("three").add("four").add("five").build();
doSomethingWithStream(stream, 'o');
}
/**
* Example using the {@link Collection#stream()} method
*/
public static void example4() {
List<String> numbers = new ArrayList<>();
numbers.add("one");
numbers.add("two");
numbers.add("three");
numbers.add("four");
Stream<String> stream = numbers.stream();
doSomethingWithStream(stream, 'o');
numbers.spliterator();
}
public static void example5() {
String[] strings = {"one", "two", "three", "four"};
Stream<Object> stream = Arrays.stream(strings);
doSomethingWithStream(stream, 'o');
}
public static void doSomethingWithStream(Stream<?> stream, char c) {
long startsWithT = stream.filter(s -> {
if(s instanceof String) {
return ((String) s).charAt(0) == c;
}
return false;
}).count();
System.out.println(String.format("Numbers that start with 't' : %s", startsWithT));
}
/**
* This actually creates a continuous stream and will never complete execution
*/
public static void exampleX() {
Stream<String> stream = Stream.generate(new Supplier<String>() {
@Override
public String get() {
System.out.println("StreamCreation.get");
return "One";
}
});
doSomethingWithStream(stream, 'f');
}
}
<file_sep>/algorithms/src/main/java/sandbox/lockc/algos/sorting/InsertionSort.java
package sandbox.lockc.algos.sorting;
import java.util.Arrays;
/**
* An example implementation of an insertion sort algorithm.
*
* @see "Algorithms Unlocked by <NAME>. Page 35, Chapter 3."
*
* @author lockc
*
*/
public class InsertionSort {
public static void main(String[] args) {
int[] numbers = new int[] {
9, 2, 88, 3, 3, 4, 7, 1, 5, 6, 7, 7, 8, 9, 10, 3
};
System.out.println(Arrays.toString(insertionSort(numbers)));
}
public static int[] insertionSort(int[] numbers) {
int n = numbers.length;
for(int i = 1; i < n; i++) {
int key = numbers[i];
int j = i - 1;
while(j >= 0 && numbers[j] > key) {
numbers[j + 1] = numbers[j];
j--;
}
numbers[j + 1] = key;
}
return numbers;
}
}
<file_sep>/design-pattrerns/src/main/java/sandbox/lockc/patterns/behavioural/chain/other/Chainable.java
package sandbox.lockc.patterns.behavioural.chain.other;
public interface Chainable {
void doChain();
}
<file_sep>/mango-test/src/test/java/lockc/mango/test/LineSorterTest.java
package lockc.mango.test;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.List;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
public class LineSorterTest {
@Test(dataProvider="lineSorterData")
public void testLineSorter(List<String> input, List<String> expected) {
LineSorter lineSorter = new LineSorter();
List<String> actual = lineSorter.sortLines(input);
assertEquals(actual, expected);
}
@DataProvider
public Object[][] lineSorterData() throws IOException {
return new Object[][] {
{
FileHandler.readLines(Paths.get("src/main/resources/input.txt")),
FileHandler.readLines(Paths.get("src/main/resources/expectedOutput.txt"))
}
};
}
}
<file_sep>/java7/java7-cert2/src/main/java/sandbox/lockc/javacert/localization/I18NSample.java
package sandbox.lockc.javacert.localization;
import java.util.*;
/*
* http://docs.oracle.com/javase/tutorial/i18n/intro/index.html
*
*/
public class I18NSample {
public static void fallbackToDefaultBundle() {
Locale locale = Locale.getDefault();
ResourceBundle messages = ResourceBundle.getBundle("DefaultBundle", locale);
printMessages(messages);
locale = Locale.FRANCE;
messages = ResourceBundle.getBundle("DefaultBundle", locale);
printMessages(messages);
messages = ResourceBundle.getBundle("DefaultBundle");
printMessages(messages);
}
public static void messagesBundle() {
Locale currentLocale;
ResourceBundle messages;
currentLocale = new Locale("de", "DE");
// currentLocale = Locale.getDefault();
messages = ResourceBundle.getBundle("MessagesBundle", currentLocale);
printMessages(messages);
}
static public void main(String[] args) {
fallbackToDefaultBundle();
}
private static void printMessages(ResourceBundle bundle) {
System.out.println(String.format("----------- %s --------------", bundle.getLocale()));
System.out.println(bundle.getString("greetings"));
System.out.println(bundle.getString("inquiry"));
System.out.println(bundle.getString("farewell"));
}
}
<file_sep>/java7/java7-cert/src/main/java/sandbox/lockc/javacert/localization/TheLocale.java
package sandbox.lockc.javacert.localization;
import java.util.Locale;
public class TheLocale {
public static void main(String[] args) {
Locale.GERMAN.getDisplayCountry();
// identifyingAvailableLocales();
creatingLocales();
}
public static void creatingLocales() {
printLocale(Locale.getDefault(), Locale.ENGLISH);
printLocale(Locale.getDefault());
/*
* Constructor
*/
Locale.setDefault(new Locale("zh", "CH"));
printLocale(Locale.getDefault(), Locale.ENGLISH);
printLocale(Locale.getDefault());
Locale.setDefault(new Locale("en", "GB"));
printLocale(Locale.getDefault(), Locale.ENGLISH);
printLocale(Locale.getDefault());
// incorrect
Locale.setDefault(new Locale("en_GB"));
printLocale(Locale.getDefault(), Locale.ENGLISH);
printLocale(Locale.getDefault());
// incorrect
Locale.setDefault(new Locale("en-GB"));
printLocale(Locale.getDefault(), Locale.ENGLISH);
printLocale(Locale.getDefault());
/*
* forLanguageTag - Returns a locale for the specified IETF BCP 47 language tag string.
*/
Locale.setDefault(Locale.forLanguageTag("en-GB"));
printLocale(Locale.getDefault(), Locale.ENGLISH);
printLocale(Locale.getDefault());
// incorrect
Locale.setDefault(Locale.forLanguageTag("en_GB"));
printLocale(Locale.getDefault(), Locale.ENGLISH);
printLocale(Locale.getDefault());
/*
* Constants
*/
Locale.setDefault(Locale.CANADA_FRENCH);
printLocale(Locale.getDefault(), Locale.ENGLISH);
printLocale(Locale.getDefault());
/*
* Builder class
*/
Locale.setDefault(new Locale.Builder().setLanguage("th").setRegion("TH").setScript("Thai").build());
printLocale(Locale.getDefault(), Locale.ENGLISH);
printLocale(Locale.getDefault());
}
public static void identifyingAvailableLocales() {
for(Locale locale : Locale.getAvailableLocales()) {
printLocale(locale);
}
}
private static void printLocale(Locale locale) {
System.out.println(String.format("Locale Code %s: Language %s (%s), Country %s (%s), Script %s (%s), Variant %s (%s), Display Name %s ",
locale.toString(),
locale.getLanguage(),
locale.getDisplayLanguage(),
locale.getCountry(),
locale.getDisplayCountry(),
locale.getScript(),
locale.getDisplayScript(),
locale.getVariant(),
locale.getDisplayVariant(),
locale.getDisplayName()));
}
private static void printLocale(Locale locale, Locale inLocale) {
System.out.println(String.format("Locale Code %s: Language %s (%s), Country %s (%s), Script %s (%s), Variant %s (%s), Display Name %s ",
locale.toString(),
locale.getLanguage(),
locale.getDisplayLanguage(inLocale),
locale.getCountry(),
locale.getDisplayCountry(inLocale),
locale.getScript(),
locale.getDisplayScript(inLocale),
locale.getVariant(),
locale.getDisplayVariant(inLocale),
locale.getDisplayName()));
}
}
<file_sep>/java7/java7-cert/src/main/java/sandbox/lockc/javacert/concurrency/ForkJoinFrameowrk.java
package sandbox.lockc.javacert.concurrency;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class ForkJoinFrameowrk {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21);
SumTask task = new SumTask(numbers);
// will use internal common pool
System.out.println(task.compute());
// will use our pool
ForkJoinPool pool = new ForkJoinPool(4);
Integer result = pool.invoke(task);
System.out.println(result);
}
@SuppressWarnings("serial")
public static class SumTask extends RecursiveTask<Integer> {
private List<Integer> numbers;
public SumTask(List<Integer> numbers) {
this.numbers = numbers;
}
@Override
public Integer compute() {
if(numbers.size() <= 5) {
int sum = 0;
for(Integer number : numbers) {
sum += number;
}
return sum;
} else {
List<Integer> firstList = numbers.subList(0, (numbers.size() / 2));
List<Integer> secondList = numbers.subList(numbers.size() / 2, numbers.size());
SumTask firstHalf = new SumTask(firstList);
firstHalf.fork();
SumTask secondHalf = new SumTask(secondList);
return firstHalf.join() + secondHalf.compute();
}
}
}
}
<file_sep>/java7/java7-cert/src/main/java/sandbox/lockc/javacert/localization/ResBundle.java
package sandbox.lockc.javacert.localization;
import java.util.ListResourceBundle;
// Default bundle
public class ResBundle extends ListResourceBundle {
@Override
public Object[][] getContents() {
return contents;
}
static final Object[][] contents = {
{"1", "Default One"},
{"2", "Default Two"},
{"3", "Default Three"},
{"4", "Default Four"}
};
}<file_sep>/java7/java7-cert2/src/main/java/sandbox/lockc/javacert/enhancements/TheSwitchStatement.java
package sandbox.lockc.javacert.enhancements;
public class TheSwitchStatement {
}
<file_sep>/java7/java7-cert2/src/main/java/sandbox/lockc/javacert/jdbc/JDBCStuff.java
package sandbox.lockc.javacert.jdbc;
public class JDBCStuff {
public static void main(String[] args) {
ResultSet.
}
}
<file_sep>/design-pattrerns/src/main/java/sandbox/lockc/patterns/behavioural/chain/ConcreteOneChainHandler.java
package sandbox.lockc.patterns.behavioural.chain;
import java.util.Objects;
public class ConcreteOneChainHandler extends AbstractChainHandler
{
public ConcreteOneChainHandler(ChainHandler successor)
{
super(successor);
}
@Override
public void handle()
{
System.out.println(this.getClass().getSimpleName());
if (Objects.nonNull(successor)) {
successor.handle();
}
}
}
<file_sep>/design-pattrerns/src/main/java/sandbox/lockc/patterns/behavioural/visitor/domain/Picture.java
package sandbox.lockc.patterns.behavioural.visitor.domain;
import java.util.Date;
import sandbox.lockc.patterns.behavioural.visitor.api.Visitable;
import sandbox.lockc.patterns.behavioural.visitor.api.Visitor;
public class Picture implements Visitable<Picture> {
private String title;
private String artist;
private Date finished;
private String style;
public Picture(String title, String artist, Date finished, String style) {
super();
this.title = title;
this.artist = artist;
this.finished = finished;
this.style = style;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public Date getFinished() {
return finished;
}
public void setFinished(Date finished) {
this.finished = finished;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
@Override
public void accept(Visitor<Picture> visitor) {
visitor.visit(this);
}
}
<file_sep>/java8/java8-examples/src/main/java/lockc/java8/interfaces/DefaultMethods.java
package lockc.java8.interfaces;
/**
* Created by Chris on 26/02/2017.
*/
public interface DefaultMethods {
int add(int firstNumber, int secondNumber);
int subtract(int firstNumber, int secondNumber);
default int multiply(int firstNumber, int secondNumber) {
return firstNumber * secondNumber;
}
default int divide(int firstNumber, int secondNumber) {
return firstNumber / secondNumber;
}
}
<file_sep>/design-pattrerns/src/main/java/sandbox/lockc/patterns/structural/adapter/Target.java
package sandbox.lockc.patterns.structural.adapter;
import java.util.List;
public interface Target {
List<String> getListOfStrings();
}
<file_sep>/collections/src/main/java/sandbox/lockc/collections/PersonComparator.java
package sandbox.lockc.collections;
import java.util.Comparator;
public class PersonComparator implements Comparator<Person> {
/**
* Compare by last name first, then first name and finally age to
* distinguish between Person objects.
*/
@Override
public int compare(Person o1, Person o2) {
int last = o1.getLastName().compareTo(o2.getLastName());
if(last != 0) return last;
int first = o1.getFirstName().compareTo(o2.getFirstName());
if(first != 0) return first;
int age = o1.getAge() == o2.getAge() ? 0 : ageDifference(o1.getAge(), o2.getAge());
return (age != 0 ? age : 0);
}
private int ageDifference(int a, int b) {
return a - b;
}
}
<file_sep>/recipes/src/main/java/recipes/dao/RecipeXmlDao.java
/**
*
*/
package recipes.dao;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.springframework.core.io.Resource;
import recipes.domain.Recipe;
import recipes.domain.RecipeBook;
import recipes.domain.Recipes;
import recipes.serialisation.XmlSerialiser;
/**
* @author lockc
*
*/
public class RecipeXmlDao implements RecipeDao {
private Resource xmlResource;
private String xml;
public RecipeXmlDao(Resource xmlResource) {
this.xmlResource = xmlResource;
}
/* (non-Javadoc)
* @see recipe.dao.RecipeDao#getAllRecipes()
*/
@Override
public List<Recipe> getAllRecipes() {
try {
// loadXml(System.getProperty("user.dir") + System.getProperty("file.separator") + "recipes.xml");
loadXml(xmlResource);
} catch (IOException e) {
e.printStackTrace();
return new ArrayList<Recipe>();
}
Recipes recipes = null;
try {
recipes = (Recipes) new XmlSerialiser().deserialise(xml, Recipes.class);
} catch (Exception e) {
e.printStackTrace();
}
return recipes != null ? recipes.getRecipes() : new ArrayList<Recipe>();
}
@Override
public void addRecipe(Recipe recipe) {
// TODO Auto-generated method stub
}
@Override
public List<RecipeBook> getRecipeBooks() {
// TODO Auto-generated method stub
return null;
}
@Override
public RecipeBook getRecipeBook(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public void addRecipeBook(RecipeBook recipeBook) {
// TODO Auto-generated method stub
}
@Override
public Recipe getRecipe(int recipeId) {
// TODO Auto-generated method stub
return null;
}
@Override
public void updateRecipe(Recipe recipe) {
// TODO Auto-generated method stub
}
private void loadXml(Resource resource) throws IOException {
// in = this.getClass().getClassLoader().getResourceAsStream(file);
InputStreamReader is = new InputStreamReader(resource.getInputStream());
StringBuilder sb=new StringBuilder();
BufferedReader br = new BufferedReader(is);
String read = br.readLine();
while(read != null) {
sb.append(read);
read =br.readLine();
}
xml = sb.toString();
}
@Override
public void deleteIngredients(Recipe recipe) {
// TODO Auto-generated method stub
}
@Override
public void deleteRecipe(Recipe recipe) {
// TODO Auto-generated method stub
}
}
<file_sep>/recipes/src/main/java/recipes/serialisation/Serialiser.java
package recipes.serialisation;
import java.io.UnsupportedEncodingException;
import javax.xml.bind.JAXBException;
public interface Serialiser {
public String serialise(Object object) throws JAXBException;
public Object deserialise(String value, Class<?> clazz) throws JAXBException, UnsupportedEncodingException;
}
<file_sep>/design-pattrerns/src/main/java/sandbox/lockc/patterns/behavioural/visitor/BookSimplePrintVisitor.java
package sandbox.lockc.patterns.behavioural.visitor;
import sandbox.lockc.patterns.behavioural.visitor.api.Visitor;
import sandbox.lockc.patterns.behavioural.visitor.domain.Book;
public class BookSimplePrintVisitor implements Visitor<Book> {
@Override
public void visit(Book book) {
StringBuilder sb = new StringBuilder();
sb.append(book.getTitle()).append(";")
.append(book.getAuthor()).append(";")
.append(book.getISBN()).append(";")
.append(book.getPublised()).append("\n");
System.out.println(sb.toString());
}
}
<file_sep>/generics/src/main/java/sandbox/lockc/generics/bounded/Box.java
package sandbox.lockc.generics.bounded;
import java.util.Objects;
/**
*
* PECS:
*
* Producer
* Extends
* Consumer
* Super
*
*
* @author lockc
*
* @param <T> Is a 'type parameter' and with <code>Box\<String\></code> 'String' is a 'type argument'.
*/
public class Box<T> {
private T t;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
/**
* A generic bounded method
*
* @param u
*/
public <U> void inspect(U u) {
System.out.println(">>>>");
if (Objects.nonNull(t)) System.out.println("T: " + t.getClass().getName());
System.out.println("U: " + u.getClass().getName());
System.out.println("<<<<");
}
}
<file_sep>/recipes-service/src/main/java/recipes/domain/Link.java
package recipes.domain;
import java.net.URI;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Link {
private String relation;
private URI target;
@XmlAttribute(name = "rel")
public String getRelation() {
return relation;
}
public Link setRelation(String relation) {
this.relation = relation;
return this;
}
@XmlAttribute(name = "href")
public URI getTarget() {
return target;
}
public Link setTarget(URI target) {
this.target = target;
return this;
}
//
// @Override
// public int hashCode() {
// return new HashCodeBuilder()
// .append(target)
// .append(relation)
// .toHashCode();
// }
//
// @Override
// public boolean equals(Object obj) {
// if (!(obj instanceof Link)){
// return false;
// }
//
// if (this == obj){
// return true;
// }
//
// Link other = (Link) obj;
//
// return new EqualsBuilder()
// .append(target,other.getTarget())
// .append(relation, other.getRelation())
// .isEquals();
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Object#toString()
// */
// @Override
// public String toString() {
// return new ToStringBuilder(this).append("relation", getRelation()).append("target", getTarget()).toString();
// }
}
<file_sep>/concurrency/src/main/java/lockc/java/concurrency/notthreadsafe/Counter.java
package lockc.java.concurrency.notthreadsafe;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.annotation.concurrent.NotThreadSafe;
/**
* Race condition exists getting the counter and adding 1. thread A increments counter
* and is currently at 7 at same time thread B increments counter which is sees as 7
* thread A adds one and thread B adds one, they both set to 8.
*
* Another race condition thread A is incrementing the counter but thread B calls getCounter
* as same time, thread B gets stale data as thread A is in the middle of updating the counter.
*
* counter = counter + 1 is not atomic!
*
* @author lockc
*
*/
@NotThreadSafe
public class Counter {
private int counter;
public int getCounter() {
return counter;
}
public void incrementCounter() throws InterruptedException {
counter = counter + 1;
}
public static void main(String[] args) {
final Counter counter = new Counter();
ExecutorService service = Executors.newFixedThreadPool(10);
for(int x = 0; x < 10; x++) {
service.execute(new Runnable() {
public void run() {
while(counter.getCounter() < 100) {
try {
counter.incrementCounter();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(counter.getCounter());
}
}
});
}
service.shutdown();
}
}
<file_sep>/recipes/src/main/resources/sql.sql
select * from recipes where name = 'test 8';
select * from ingredients where recipe_id = 455;
delete from ingredients where recipe_id = 455;
select * from recipes;
select * from recipe_books;
select * from ingredients;
delete from recipes;
delete from ingredients;
delete from recipe_books;
insert into recipes(NAME, RECIPE_BOOK_ID, PAGE_NO) values ('Nice meal', 1, 23);
insert into recipe_books(NAME) values ('book 2');
insert into ingredients(RECIPE_ID, DESC) values(1, 'tomatoes');
insert into ingredients(RECIPE_ID, DESC) values(1, 'garlic');<file_sep>/recipes/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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>lockc.projects</groupId>
<artifactId>recipes</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Recipes</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.7</java.version>
<onejar.version>1.4.4</onejar.version>
<spring.version>3.2.7.RELEASE</spring.version>
<hibernate.version>4.3.2.Final</hibernate.version>
<sqlite.version>3.7.2</sqlite.version>
<log4j.version>1.2.14</log4j.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>${sqlite.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<version>${onejar.version}</version>
<executions>
<execution>
<configuration>
<mainClass>recipes.app.RecipeApp</mainClass>
</configuration>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<file_sep>/concurrency/src/main/java/lockc/java/concurrency/threadsafe/ImmutableCounter.java
package lockc.java.concurrency.threadsafe;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.annotation.concurrent.Immutable;
import javax.annotation.concurrent.NotThreadSafe;
import javax.annotation.concurrent.ThreadSafe;
/**
*
* A class is immutable when:
*
* - Its state cannot be modified after construction
* - All its fields are final
* - It is properly constructed i.e. the this reference does not escape during construction
*
* @author lockc
*
*/
@Immutable
@ThreadSafe
public class ImmutableCounter {
private final int counter;
public ImmutableCounter(int counter) {
this.counter = counter;
}
public int getCounter() {
return counter;
}
public static void main(String[] args) {
new CounterWatch().run();
}
@NotThreadSafe
private static class CounterWatch {
private static volatile ImmutableCounter staticCounter;
public void run() {
ExecutorService service = Executors.newFixedThreadPool(10);
staticCounter = new ImmutableCounter(0);
for(int x = 0; x < 10; x++) {
service.execute(new Runnable() {
public void run() {
while(staticCounter.getCounter() < 200) {
staticCounter = new ImmutableCounter(staticCounter.getCounter() + 1);
System.out.println(this.hashCode() + " " + staticCounter.getCounter());
}
}
});
}
service.shutdown();
}
}
}
<file_sep>/java8/java8-examples/src/main/java/lockc/java8/lambda/ConstructorReferencesExample3.java
package lockc.java8.lambda;
/**
* This example shows constructor references in the simplest form.
*
* We define a Switcher in four ways:
*
* - an anonymous class,
* - a lambda function syntax
* - a short lambda function syntax
* - a constructor reference syntax.
*
*
* What this does is declare a generic Switcher who's switchIt method
* takes a single String argument and returns a SomeClass based on the T
* and S type parameters. The constructor reference syntax is
* saying, create a Switcher instance who's implementation constructs
* a new SomeClass and try and match a constructor signature of
* SomeClass with a single String constructor based on the method
* signature of the functional interface.
*
* @author lockc
*
*/
public class ConstructorReferencesExample3 {
public static void main(String[] args) {
// From this ...
Switcher<String, SomeClass> switcher0 = new Switcher<String, SomeClass>() {
@Override
public SomeClass switchIt(String it) {
return new SomeClass(it);
}
};
SomeClass sc0 = SomeClass.switchTo(switcher0, "anonymous class");
sc0.print();
// To this ...
Switcher<String, SomeClass> switcher1 = (it) -> {
return new SomeClass(it);
};
SomeClass sc1 = SomeClass.switchTo(switcher1, "lambda function synta");
sc1.print();
// To this ...
Switcher<String, SomeClass> switcher9 = (it) -> new SomeClass(it);
SomeClass sc9 = SomeClass.switchTo(switcher9, "shorthand lambda function syntax");
sc9.print();
// To this ...
Switcher<String, SomeClass> switcher2 = SomeClass::new;
SomeClass sc2 = SomeClass.switchTo(switcher2, "lambda constructor reference ");
sc2.print();
/*
* compiler error - String.class has no constructor that
* takes a SomeClass
*/
// Switcher<SomeClass, String> switcher4 = String::new;
// Just to show from String to String because the String class
// also has a constructor that takes a string
Switcher<String, String> switcher3 = String::new;
String s = SomeClass.switchTo(switcher3, "hello");
System.out.println(s.getClass().getName() + " : " + s);
/**
* These examples show constructor references in an even simpler
* form, the Creator functional interface simply constructs
* new objects and returns them. Here the Creator interface
* has a method that takes no arguments, hence the compiler
* tries to match the no-arg constructor of each object type.
*/
Creator<Object> object = Object::new;
Object obj = SomeClass.create(object);
System.out.println(obj.toString());
Creator<String> string = String::new;
String str = SomeClass.create(string);
System.out.println(str.toString());
Creator<SomeClass> someClass = SomeClass::new;
SomeClass sc = SomeClass.create(someClass);
System.out.println(sc.toString());
}
/**
*
* @author lockc
*
* @param <T> from type
* @param <S> to type
*/
@FunctionalInterface
private static interface Switcher<T, S> {
/**
* A method that takes a T and converts it to an S
*
* @param it
* @return the converted object
*/
S switchIt(T it);
}
@FunctionalInterface
private static interface Creator<T> {
T createIt();
}
/**
* Some class that provides a static switchTo method to illustrate the examples
*
* @author lockc
*
*/
private static class SomeClass {
private String value;
public SomeClass() {
}
/**
* A generic constructor allows conversion from any type so the compiler
* doesn't complain it cannot find a constructor. We could just as well put
* the following but this would mean only String<i>s<i> could be converted
* because the compiler would complain.
*
* <pre>
*
*
*
* public <T> SomeClass(T value) {
*
* this.value = value.toString();
* }
* </pre>
*
* @param value
*/
public <T> SomeClass(T value) {
this.value = value.toString();
}
public static <T, S> S switchTo(Switcher<T, S> switcher, T t) {
return switcher.switchIt(t);
}
public static <T> T create(Creator<T> creator) {
return creator.createIt();
}
public void print() {
System.out.println(super.toString() + " : " + this.toString());
}
@Override
public String toString() {
return value;
}
}
}
<file_sep>/recipes/src/main/java/recipes/domain/Ingredients.java
/**
*
*/
package recipes.domain;
import java.util.ArrayList;
/**
* @author lockc
*
*/
@SuppressWarnings("serial")
public class Ingredients extends ArrayList<Ingredient> {
}
<file_sep>/java8/java8-examples/src/main/java/lockc/java8/lambda/ConstructorReferencesExample4.java
package lockc.java8.lambda;
public class ConstructorReferencesExample4 {
public static void main(String[] args) {
/**
* This shows constructor references in the simplest form
*/
// From this ...
Switcher<String, String, SomeClass> switcher0 = new Switcher<String, String, SomeClass>() {
@Override
public SomeClass switchIt(String it1, String it2) {
return new SomeClass(it1 + " " + it2);
}
};
SomeClass sc0 = SomeClass.switchTo(switcher0, "hello", "there");
sc0.print();
// To this ...
Switcher<String, String, SomeClass> switcher1 = (it1, it2) -> new SomeClass(it1, it2);
SomeClass sc1 = SomeClass.switchTo(switcher1, "hello", "there");
sc1.print();
// to this ...
Switcher<String, String, SomeClass> switcher2 = SomeClass::new;
SomeClass sc2 = SomeClass.switchTo(switcher2, "hello", "there");
sc2.print();
/*
* compiler error - String.class has no constructor that
* takes 2 string parameters
*/
// Switcher<String, String, String> switcher3 = String::new;
}
@FunctionalInterface
private static interface Switcher<T, U, S> {
S switchIt(T it1, U it2);
}
private static class SomeClass {
private String value;
public <T> SomeClass(T value) {
this.value = value.toString();
}
public <T> SomeClass(T value, T value2) {
this.value = value.toString() + " " + value2.toString();
}
public static <T, U, S> S switchTo(Switcher<T, U, S> switcher, T t, U u) {
return switcher.switchIt(t, u);
}
public void print() {
System.out.println(super.toString() + " : " + this.toString());
}
@Override
public String toString() {
return value;
}
}
}
<file_sep>/recipes/src/main/java/recipes/gui/RecipesWindow.java
package recipes.gui;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import recipes.app.RecipeEditorDelegate;
import recipes.dao.RecipeDao;
import recipes.domain.Recipe;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class RecipesWindow {
private RecipeDao dao;
private List<Recipe> allRecipes;
private List<Recipe> selectedRecipes;
private JFrame frame;
private JList<Recipe> listAvailable;
private JList<Recipe> listSelected;
private DefaultListModel<Recipe> resultListSelected = new DefaultListModel<Recipe>();
private DefaultListModel<Recipe> resultListAvailable = new DefaultListModel<Recipe>();
private JButton btnAddMeal;
private JButton btnRemoveMeal;
private JButton btnShoppingList;
private JButton btnAddRecipe;
private JButton btnEditRecipe;
private RecipesWindow(RecipeDao dao) {
this.dao = dao;
initialize();
}
public static RecipesWindow newInstance(RecipeDao dao) {
return new RecipesWindow(dao);
}
public void show() {
selectedRecipes = new ArrayList<Recipe>();
registerEvents();
populateAvailable();
frame.setVisible(true);
}
private void populateAvailable() {
clearAvailable();
allRecipes = dao.getAllRecipes();
for(Recipe available : allRecipes) {
resultListAvailable.addElement(available);
}
frame.getContentPane().validate();
}
private void clearAvailable() {
resultListAvailable.clear();
}
private void registerEvents() {
btnAddMeal.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Object[] values = listAvailable.getSelectedValues();
for(Object value : values) {
resultListSelected.addElement((Recipe)value);
resultListAvailable.remove(resultListAvailable.indexOf(value));
selectedRecipes.add(findRecipe(String.valueOf(value)));
}
}
});
btnRemoveMeal.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Object[] values = listSelected.getSelectedValues();
for(Object value : values) {
resultListAvailable.addElement((Recipe)value);
resultListSelected.remove(resultListSelected.indexOf(value));
selectedRecipes.remove(findRecipe(String.valueOf(value)));
}
}
});
btnShoppingList.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
createShoppingList();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnAddRecipe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
RecipeEditor editor = RecipeEditor.newInstance(new RecipeEditorDelegate(dao, null));
editor.disableDeleteButton();
editor.show();
editor.registerWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent arg0) {
populateAvailable();
}
});
}
});
btnEditRecipe.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Recipe recipe = (Recipe) listAvailable.getSelectedValues()[0];
RecipeEditor editor = RecipeEditor.newInstance(new RecipeEditorDelegate(dao, recipe));
editor.show();
editor.registerWindowListener(new WindowAdapter() {
@Override
public void windowClosed(WindowEvent arg0) {
populateAvailable();
}
});
}
});
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 728, 539);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(733, 542));
panel.setBorder(null);
panel.setBounds(0, 11, 704, 475);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblAvailableMeals = new JLabel("Available meals");
lblAvailableMeals.setBounds(31, 6, 258, 14);
panel.add(lblAvailableMeals);
JLabel lblSelectedMeals = new JLabel("Selected meals");
lblSelectedMeals.setBounds(425, 6, 258, 14);
panel.add(lblSelectedMeals);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(31, 26, 258, 410);
panel.add(scrollPane);
listAvailable = new JList<Recipe>();
listAvailable.setVisibleRowCount(20);
scrollPane.setViewportView(listAvailable);
listAvailable.setModel(resultListAvailable);
btnAddMeal = new JButton(">>");
btnAddMeal.setBounds(320, 210, 62, 23);
panel.add(btnAddMeal);
btnRemoveMeal = new JButton("<<");
btnRemoveMeal.setBounds(320, 245, 62, 23);
panel.add(btnRemoveMeal);
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(425, 26, 258, 410);
panel.add(scrollPane_1);
listSelected = new JList<Recipe>();
scrollPane_1.setViewportView(listSelected);
listSelected.setModel(resultListSelected);
btnShoppingList = new JButton("Create shopping list...");
btnShoppingList.setBounds(425, 452, 258, 23);
panel.add(btnShoppingList);
btnAddRecipe = new JButton("Add");
btnAddRecipe.setBounds(31, 451, 117, 25);
panel.add(btnAddRecipe);
btnEditRecipe = new JButton("Edit");
btnEditRecipe.setBounds(172, 451, 117, 25);
panel.add(btnEditRecipe);
}
private void createShoppingList() throws Exception {
StringBuilder builder = new StringBuilder();
for(Recipe recipe : selectedRecipes) {
builder.append(recipe.toShoppingListItem());
}
String list = builder.toString();
String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "ShoppingList.txt";
System.out.println(filePath);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filePath);
fos.write(list.getBytes());
fos.write(0);
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.close();
}
}
private Recipe findRecipe(String name) {
for(Recipe recipe : allRecipes) {
if(recipe.getName().equalsIgnoreCase(name)) {
return recipe;
}
}
return null;
}
}
<file_sep>/design-pattrerns/src/main/java/sandbox/lockc/patterns/behavioural/chain/Client.java
package sandbox.lockc.patterns.behavioural.chain;
public class Client
{
public static void main(String[] args)
{
ChainHandler chainHandler3 = new ConcreteThreeChainHandler(null);
ChainHandler chainHandler2 = new ConcreteTwoChainHandler(chainHandler3);
ChainHandler chainHandler1 = new ConcreteOneChainHandler(chainHandler2);
chainHandler1.handle();
}
}
<file_sep>/java7/java7-cert2/src/main/java/sandbox/lockc/javacert/nio/PathStuff.java
package sandbox.lockc.javacert.nio;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.nio.file.WatchService;
import java.sql.SQLException;
import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveAction;
import java.util.concurrent.RecursiveTask;
public class PathStuff {
public static void main(String[] args) {
/* ********************************
* normalize
* ********************************/
/*
* prints '/home'
*/
Path p = Paths.get("/home/lockc/../.");
System.out.println(p.normalize());
/* ********************************
* relativize
* ********************************/
/*
* prints 'git'
*/
Path p1 = Paths.get("/home/lockc/");
Path p2 = Paths.get("/home/lockc/git");
System.out.println(p1.relativize(p2));
/*
* prints '..'
*/
p1 = Paths.get("/home/lockc/git");
p2 = Paths.get("/home/lockc/");
System.out.println(p1.relativize(p2));
/*
* prints 'sub'
*/
p1 = Paths.get("target");
p2 = Paths.get("target/sub");
System.out.println(p1.relativize(p2));
/*
*
*/
System.out.println(p1.resolve(p2));
}
}
<file_sep>/java7/java7-cert/src/main/java/sandbox/lockc/javacert/nio/FilesStuff.java
package sandbox.lockc.javacert.nio;
public class FilesStuff {
public static void main(String[] args) {
}
}
<file_sep>/java7/java7-cert/src/main/java/sandbox/lockc/javacert/localization/NumberFormatting.java
package sandbox.lockc.javacert.localization;
import java.text.Format;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public class NumberFormatting {
public static void main(String[] args) {
List<Locale> locales = Arrays.asList(Locale.UK, Locale.US, Locale.ITALY, Locale.GERMANY);
System.out.println("-----------------------------");
System.out.println("Currencies");
System.out.println("-----------------------------");
for(Locale locale : locales) {
Format formatter = NumberFormat.getCurrencyInstance(locale);
System.out.println(locale.getDisplayCountry(locale) + " " + formatter.format(2.56));
}
System.out.println("-----------------------------");
System.out.println("Numbers");
System.out.println("-----------------------------");
for(Locale locale : locales) {
Format formatter = NumberFormat.getNumberInstance(locale);
System.out.println(locale.getDisplayCountry(locale) + " " + formatter.format(1234567890.45543));
}
System.out.println("-----------------------------");
System.out.println("Integers");
System.out.println("-----------------------------");
for(Locale locale : locales) {
Format formatter = NumberFormat.getIntegerInstance(locale);
System.out.println(locale.getDisplayCountry(locale) + " " + formatter.format(1234567890.68678));
}
System.out.println("-----------------------------");
System.out.println("Percent");
System.out.println("-----------------------------");
for(Locale locale : locales) {
Format formatter = NumberFormat.getPercentInstance(locale);
System.out.println(locale.getDisplayCountry(locale) + " " + formatter.format(97.8));
}
}
}
<file_sep>/java7/java7-cert2/src/main/java/sandbox/lockc/javacert/designpatterns/DaoDesignPattern.java
package sandbox.lockc.javacert.designpatterns;
public class DaoDesignPattern {
interface MyDao {
}
}
<file_sep>/java7/java7-cert/src/main/java/sandbox/lockc/javacert/nio/FindingFiles.java
package sandbox.lockc.javacert.nio;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
public class FindingFiles {
public static void main(String[] args) throws IOException {
Files.walkFileTree(Paths.get("/home/lockc"), new FileFinderVisitor("glob:*.java"));
Files.walkFileTree(Paths.get("."), new FileFinderVisitor("glob:FindingFiles.java"));
Files.walkFileTree(Paths.get("."), new FileFinderVisitor("regex:FindingFiles.java"));
Files.walkFileTree(Paths.get("."), new FileFinderVisitor("blah:FindingFiles.java"));
}
public static class FileFinderVisitor extends SimpleFileVisitor<Path> {
public FileFinderVisitor(String pattern) {
this.matcher = FileSystems.getDefault().getPathMatcher(pattern);
}
private PathMatcher matcher;
@Override
public FileVisitResult preVisitDirectory(Path path,
BasicFileAttributes attrs) throws IOException {
find(path);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path path,
BasicFileAttributes attrs) throws IOException {
find(path);
return FileVisitResult.CONTINUE;
}
public void find(Path path) {
Path name = path.getFileName();
if(matcher.matches(name)) {
System.out.println("Found : " + path.toString());
}
}
}
}
<file_sep>/java7/java7-cert/src/main/java/sandbox/lockc/javacert/enhancements/CatchBlocks.java
package sandbox.lockc.javacert.enhancements;
public class CatchBlocks {
}
<file_sep>/design-pattrerns/src/main/java/sandbox/lockc/patterns/behavioural/visitor/PicturePrettyPrintVisitor.java
package sandbox.lockc.patterns.behavioural.visitor;
import sandbox.lockc.patterns.behavioural.visitor.api.Visitor;
import sandbox.lockc.patterns.behavioural.visitor.domain.Picture;
public class PicturePrettyPrintVisitor implements Visitor<Picture> {
@Override
public void visit(Picture picture) {
StringBuilder sb = new StringBuilder();
sb.append("Title: ").append(picture.getTitle()).append("\n")
.append("Author: ").append(picture.getArtist()).append("\n")
.append("ISBN: ").append(picture.getStyle()).append("\n")
.append("Published: ").append(picture.getFinished()).append("\n");
System.out.println(sb.toString());
}
}
<file_sep>/java8/java8-examples/src/main/java/lockc/java8/interfaces/DefaultMethodsExample1.java
package lockc.java8.interfaces;
public class DefaultMethodsExample1 {
public static void main(String[] args) {
Man man = new Man();
man.sayHello("Chris");
Woman woman = new Woman();
woman.sayHello("Sheila");
}
private static interface Person {
default void sayHello(String name) {
System.out.println("hello " + name);
}
default void sayGoodbye(String name) {
System.out.println("goodbye " + name);
}
}
private static class Man implements Person {
@Override
public void sayHello(String name) {
Person.super.sayHello(name);
System.out.println("hello " + name + " man!");
}
}
private static class Woman implements Person {
// look no impl ...
}
}
<file_sep>/design-pattrerns/src/main/java/sandbox/lockc/patterns/structural/facade/HolidayBookerFacade.java
package sandbox.lockc.patterns.structural.facade;
public class HolidayBookerFacade {
private FlightBooker flightBooker = new FlightBooker();
private HotelBooker hotelBooker = new HotelBooker();
private HireCarBooker hireCarBooker = new HireCarBooker();
public void bookHoliday() {
flightBooker.bookFlight();
hotelBooker.bookHotel();
hireCarBooker.bookHireCar();
}
}
<file_sep>/recipes/src/main/java/recipes/dao/RecipeDao.java
/**
*
*/
package recipes.dao;
import java.util.List;
import recipes.domain.Ingredient;
import recipes.domain.Recipe;
import recipes.domain.RecipeBook;
/**
* @author lockc
*
*/
public interface RecipeDao {
List<Recipe> getAllRecipes();
List<RecipeBook> getRecipeBooks();
RecipeBook getRecipeBook(String name);
Recipe getRecipe(int recipeId);
void addRecipeBook(RecipeBook recipeBook);
void addRecipe(Recipe recipe);
void updateRecipe(Recipe recipe);
void deleteIngredients(Recipe recipe);
void deleteRecipe(Recipe recipe);
}
<file_sep>/recipes-service/src/main/java/recipes/dao/RecipeDaoJdbcImpl.java
package recipes.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import recipes.domain.Ingredient;
import recipes.domain.RecipeBook;
import recipes.domain.Recipe;
public class RecipeDaoJdbcImpl extends JdbcDaoSupport implements RecipeDao {
@Override
public List<Recipe> getAllRecipes() {
return doGetAllRecipes();
}
@Override
public List<Recipe> getAllRecipesShallow() {
return doGetAllRecipesShallow();
}
@Override
public Recipe getRecipe(int recipeId) {
return doGetRecipe(recipeId);
}
@Override
public List<RecipeBook> getRecipeBooks() {
return doGetRecipeBooks();
}
@Override
public RecipeBook getRecipeBook(String name) {
return doGetRecipeBook(name);
}
@Override
public void addRecipeBook(RecipeBook recipeBook) {
// TODO Auto-generated method stub
}
@Override
public int addRecipe(Recipe recipe) {
doInsertRecipe(recipe);
int recipeId = getRecipeId(recipe.getName());
recipe.setRecipeId(recipeId);
doInsertIngredients(recipe);
return recipeId;
}
@Override
public void updateRecipe(Recipe recipe) {
doUpdateRecipe(recipe);
doDeleteIngredients(recipe);
doInsertIngredients(recipe);
}
@Override
public void deleteIngredients(Recipe recipe) {
doDeleteIngredients(recipe);
}
@Override
public void deleteRecipe(Recipe recipe) {
doDeleteIngredients(recipe);
doDeleteRecipe(recipe.getRecipeId());
}
private void doUpdateRecipe(final Recipe recipe) {
getJdbcTemplate().update(new PreparedStatementCreator() {
String sql = "update recipes set name=?, recipe_book_id=?, page_no=? "
+ "where id=?";
@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, recipe.getName());
ps.setInt(2, recipe.getRecipeBook().getId());
ps.setInt(3, recipe.getPageNumber());
ps.setInt(4, recipe.getRecipeId());
return ps;
}
});
}
private void doDeleteIngredients(Recipe recipe) {
final int recipeId = recipe.getRecipeId();
getJdbcTemplate().update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
String sql = "delete from ingredients where recipe_id = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, recipeId);
return ps;
}
});
}
private void doDeleteRecipe(final int recipeId) {
getJdbcTemplate().update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
String sql = "delete from recipes where id = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, recipeId);
return ps;
}
});
}
private List<RecipeBook> doGetRecipeBooks() {
return getJdbcTemplate().query(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
return con.prepareStatement("select r.id, r.name from recipe_books r");
}
},
new ResultSetExtractor<List<RecipeBook>>() {
@Override
public List<RecipeBook> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<RecipeBook> recipeBookList = new ArrayList<>();
while(rs.next()) {
RecipeBook rb = new RecipeBook();
rb.setId(rs.getInt(1));
rb.setName(rs.getString(2));
recipeBookList.add(rb);
}
rs.close();
return recipeBookList;
}
});
}
private List<Recipe> doGetAllRecipes() {
return getJdbcTemplate().query(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
return con.prepareStatement("select r.id, r.name, r.recipe_book_id, r.page_no from recipes r");
}
},
new ResultSetExtractor<List<Recipe>>() {
@Override
public List<Recipe> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Recipe> recipeList = new ArrayList<>();
while(rs.next()) {
Recipe r = new Recipe();
r.setRecipeId(rs.getInt(1));
r.setName(rs.getString(2));
r.setPageNumber(rs.getInt(4));
RecipeBook recipeBook = doGetRecipeBook(rs.getInt(3));
r.setRecipeBook(recipeBook);
List<Ingredient> ingredients = doGetIngredients(rs.getInt(1));
r.setIngredients(ingredients);
recipeList.add(r);
}
rs.close();
return recipeList;
}
});
}
private List<Recipe> doGetAllRecipesShallow() {
return getJdbcTemplate().query(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
return con.prepareStatement("select r.id, r.name, r.recipe_book_id, r.page_no from recipes r");
}
},
new ResultSetExtractor<List<Recipe>>() {
@Override
public List<Recipe> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Recipe> recipeList = new ArrayList<>();
while(rs.next()) {
Recipe r = new Recipe();
r.setRecipeId(rs.getInt(1));
r.setName(rs.getString(2));
r.setPageNumber(rs.getInt(4));
recipeList.add(r);
}
rs.close();
return recipeList;
}
});
}
private Recipe doGetRecipe(int recipeId) {
String sql = "select r.id, r.name, r.recipe_book_id, r.page_no from recipes r where r.id = ?";
return getJdbcTemplate().queryForObject(sql, new RowMapper<Recipe>() {
@Override
public Recipe mapRow(ResultSet rs, int rowNum) throws SQLException {
Recipe r = new Recipe();
r.setRecipeId(rs.getInt(1));
r.setName(rs.getString(2));
r.setPageNumber(rs.getInt(4));
RecipeBook recipeBook = doGetRecipeBook(rs.getInt(3));
r.setRecipeBook(recipeBook);
List<Ingredient> ingredients = doGetIngredients(rs.getInt(1));
r.setIngredients(ingredients);
return r;
}
}, recipeId);
}
private void doInsertRecipe(final Recipe recipe) {
getJdbcTemplate().update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
PreparedStatement ps = con.prepareStatement("insert into recipes "
+ "(name, recipe_book_id, page_no) values (?, ?, ?)");
ps.setString(1, recipe.getName());
ps.setInt(2, recipe.getRecipeBook().getId());
ps.setInt(3, recipe.getPageNumber());
return ps;
}
});
}
private void doInsertIngredients(final Recipe recipe) {
final List<Ingredient> ingredients = recipe.getIngredients();
getJdbcTemplate().batchUpdate("insert into ingredients (recipe_id, description) values (?, ?)", new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setInt(1, recipe.getRecipeId());
ps.setString(2, ingredients.get(i).getDescription());
}
@Override
public int getBatchSize() {
return ingredients.size();
}
});
}
private int getRecipeId(String name) {
return getJdbcTemplate().queryForObject("select r.id from recipes r where r.name = ?", Integer.class, name);
}
private RecipeBook doGetRecipeBook(int id) {
String sql = "select r.id, r.name from recipe_books r where r.id = ?";
return getJdbcTemplate().queryForObject(sql, new RowMapper<RecipeBook>() {
@Override
public RecipeBook mapRow(ResultSet rs, int rowNum) throws SQLException {
RecipeBook b = new RecipeBook();
b.setId(rs.getInt(1));
b.setName(rs.getString(2));
return b;
}
}, id);
}
private List<Ingredient> doGetIngredients(final int recipeId) {
return getJdbcTemplate().query(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con)
throws SQLException {
PreparedStatement ps = con.prepareStatement("select i.id, i.recipe_id, i.description "
+ "from ingredients i where i.recipe_id = ?");
ps.setInt(1, recipeId);
return ps;
}
},
new ResultSetExtractor<List<Ingredient>>() {
@Override
public List<Ingredient> extractData(ResultSet rs) throws SQLException,
DataAccessException {
List<Ingredient> ingredients = new ArrayList<>();
while(rs.next()) {
Ingredient i = new Ingredient();
i.setId(rs.getInt(1));
i.setRecipeId(rs.getInt(2));
i.setDescription(rs.getString(3));
ingredients.add(i);
}
rs.close();
return ingredients;
}
});
}
private RecipeBook doGetRecipeBook(String name) {
String sql = "select r.id, r.name from recipe_books r where r.name = ?";
return getJdbcTemplate().queryForObject(sql, new RowMapper<RecipeBook>() {
@Override
public RecipeBook mapRow(ResultSet rs, int rowNum) throws SQLException {
RecipeBook b = new RecipeBook();
b.setId(rs.getInt(1));
b.setName(rs.getString(2));
return b;
}
}, name);
}
}
<file_sep>/recipes-service/src/main/java/recipes/domain/RecipeBook.java
package recipes.domain;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@SuppressWarnings("serial")
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class RecipeBook implements Serializable {
@XmlElement(required = true)
private int id;
@XmlElement(required = true)
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return getName();
}
@Override
public boolean equals(Object object) {
if(object == this) return true;
if(!(object instanceof RecipeBook)) return false;
RecipeBook book = (RecipeBook) object;
if(book.getId() != this.getId()) return false;
if(!book.getName().equals(this.getName())) return false;
return true;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + id;
result = 31 * result + name.hashCode();
return result;
}
}
<file_sep>/design-pattrerns/src/main/java/sandbox/lockc/patterns/creational/abstractfactory/AbstractCarFacory.java
package sandbox.lockc.patterns.creational.abstractfactory;
public interface AbstractCarFacory {
AbstractCar makeCar();
}
<file_sep>/design-pattrerns/src/main/java/sandbox/lockc/patterns/behavioural/chain/AbstractChainHandler.java
package sandbox.lockc.patterns.behavioural.chain;
public abstract class AbstractChainHandler implements ChainHandler
{
protected ChainHandler successor;
protected AbstractChainHandler(ChainHandler successor)
{
this.successor = successor;
}
}
<file_sep>/recipes-service/src/main/java/recipes/serialisation/Serialiser.java
package recipes.serialisation;
public interface Serialiser {
public String serialise(Object object) throws SerialisationException;
public Object deserialise(String value, Class<?> clazz) throws SerialisationException;
}
<file_sep>/java7/java7-cert/src/main/java/sandbox/lockc/javacert/concurrency/SemaphoreSyncroniser.java
package sandbox.lockc.javacert.concurrency;
import java.util.concurrent.Semaphore;
public class SemaphoreSyncroniser {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(1);
UserThread user1 = new UserThread(semaphore, "Kate");
UserThread user2 = new UserThread(semaphore, "Heath");
UserThread user3 = new UserThread(semaphore, "Abigail");
UserThread user4 = new UserThread(semaphore, "Riff");
user1.start();
user2.start();
user3.start();
user4.start();
}
public static class UserThread extends Thread {
private Semaphore resource;
private String name;
public UserThread(Semaphore resource, String name) {
this.resource = resource;
this.name = name;
}
@Override
public void run() {
try {
System.out.println(name + " is waiting to use the resource.");
resource.acquire();
System.out.println(name + " is using the resource.");
Thread.sleep(3000);
resource.release();
System.out.println(name + " has finished using the resource.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
<file_sep>/generics/README.md
# Java Generics
<file_sep>/algorithms/src/main/java/sandbox/lockc/algos/searching/SentinelLinearSearch.java
package sandbox.lockc.algos.searching;
public class SentinelLinearSearch {
public static void main(String[] args) {
int[] numbers = new int[] {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10
};
System.out.println(sentinelLinearSearch(numbers, 5));
}
public static int sentinelLinearSearch(int[] numbers, int x) {
int n = numbers.length - 1;
int last = numbers[n];
// Replace the last. e.g. the sentinel
numbers[n] = x;
// loop until we find a value equally x
int i = 0;
while (numbers[i] != x) {
i++;
}
// replace the last element with it original value
numbers[n] = last;
// now check
if(i < n || numbers[n] == x) {
return i;
}
return -1;
}
}
| 0b9642854b4a543b11ecd3b0463d93c816f72d88 | [
"Markdown",
"Java",
"Maven POM",
"SQL"
] | 58 | Java | lockc/java-dev | 7a721dac809469b787b5e417fb70e3f77f2a6f6b | e531d6e647ad90cafb7a35a3601fc205336598e5 |
refs/heads/master | <repo_name>solraiver/blog<file_sep>/README.txt
study Git and other intresting items<file_sep>/blog/src/Sol/BlogBundle/SolBlogBundle.php
<?php
namespace Sol\BlogBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class SolBlogBundle extends Bundle
{
}
<file_sep>/blog/README.md
blog
====
A Symfony project created on February 1, 2016, 7:29 pm.
| 12d13ed05edb6f94f00171b29e93925b527ad44c | [
"Markdown",
"Text",
"PHP"
] | 3 | Text | solraiver/blog | 1c6fd799717db1f9cf4d1935edec1fc4ed3d996a | 7468c42143e0acefd0f3ea71a08bf933020d50ed |
refs/heads/main | <repo_name>eymc/part_iii<file_sep>/setup.py
#Copyright 2014-2020 MathWorks, Inc.
from distutils.core import setup
from distutils.command.build_py import build_py
import os
import sys
import platform
# UPDATE_IF_PYTHON_VERSION_ADDED_OR_REMOVED : search for this string in codebase
# when support for a Python version must be added or removed
_supported_versions = ['2.7', '3.7', '3.8']
_ver = sys.version_info
_version = '{0}.{1}'.format(_ver[0], _ver[1])
if not _version in _supported_versions:
raise EnvironmentError('MATLAB Engine for Python supports Python version'
' 2.7, 3.7, and 3.8, but your version of Python '
'is %s' % _version)
_dist = "dist"
_matlab_package = "matlab"
_engine_package = "engine"
_arch_filename = "_arch.txt"
_py_arch = platform.architecture()
_system = platform.system()
_py_bitness =_py_arch[0]
class BuildEngine(build_py):
@staticmethod
def _find_arch(predicate):
_bin_dir = predicate
_arch = None
_archs = ["win64", "glnxa64", "maci64", "win32"]
_arch_bitness = {"glnxa64": "64bit", "maci64": "64bit",
"win32": "32bit", "win64": "64bit"}
_system_to_arch = {"Windows": "win64", "Linux": "glnxa64", "Darwin": "maci64"}
_arch_from_system = _system_to_arch[_system]
if os.access(os.path.join(_bin_dir, _arch_from_system), os.F_OK):
_arch = _arch_from_system
if _arch is None:
raise EnvironmentError('The installation of MATLAB is corrupted. '
'Please reinstall MATLAB or contact '
'Technical Support for assistance.')
if _py_bitness != _arch_bitness[_arch]:
raise EnvironmentError('%s Python does not work with %s MATLAB. '
'Please check your version of Python' %
(_py_bitness, _arch_bitness[_arch]))
return _arch
def _generate_arch_file(self, target_dir):
_arch_file_path = os.path.join(target_dir, _arch_filename)
_cwd = os.getcwd()
_parent = os.pardir # '..' for Windows and POSIX
_bin_dir = os.path.join(_cwd, _parent, _parent, _parent, 'bin')
_engine_dir = os.path.join(_cwd, _dist, _matlab_package, _engine_package)
_extern_bin_dir = os.path.join(_cwd, _parent, _parent, _parent, 'extern', 'bin')
_arch = self._find_arch(_bin_dir)
_bin_dir = os.path.join(_bin_dir, _arch)
_engine_dir = os.path.join(_engine_dir, _arch)
_extern_bin_dir = os.path.join(_extern_bin_dir, _arch)
try:
_arch_file = open(_arch_file_path, 'w')
_arch_file.write(_arch + os.linesep)
_arch_file.write(_bin_dir + os.linesep)
_arch_file.write(_engine_dir + os.linesep)
_arch_file.write(_extern_bin_dir + os.linesep)
_arch_file.close()
except IOError:
raise EnvironmentError('You do not have write permission '
'in %s ' % target_dir)
def run(self):
build_py.run(self)
_target_dir = os.path.join(self.build_lib, _matlab_package, _engine_package)
self._generate_arch_file(_target_dir)
if __name__ == '__main__':
setup(
name="matlabengineforpython",
version="R2021a",
description='A module to call MATLAB from Python',
author='MathWorks',
url='https://www.mathworks.com/',
platforms=['Linux', 'Windows', 'MacOS'],
package_dir={'': 'dist'},
packages=['matlab','matlab.engine','matlab._internal'],
cmdclass={'build_py': BuildEngine}
)
| 9a0d575e1e2ea1471935102da478d922682a6cb8 | [
"Python"
] | 1 | Python | eymc/part_iii | a8e562f82cfe86443ac8208f5c8f3f047f7167b9 | 23e9012fbe25b3bf47ac716ae27fd022c7ab9084 |
refs/heads/master | <file_sep>const imagemin = require('imagemin')
const imageminMozjpeg = require('imagemin-mozjpeg')
const imageminPngquant = require('imagemin-pngquant')
const recursive = require('recursive-readdir')
const ProgressBar = require('progress')
const prompt = require('prompt')
const fs = require('fs-utils')
const { minify } = require('./minify.js')
console.log('Image minifier begin')
prompt.start();
const qualityValidation = {
name: 'quality',
description: 'Enter quality value between 1~100 (%)',
type: 'integer',
conform: value => {
if(Number.isInteger(value) && value > 0 && value <= 100) {
return true
}
return false
},
message: 'quality must be an integer and range between 1~100',
default: 20
}
const sourcePathValidation = {
name: 'sourcePath',
description: 'Enter full path of source images are stored at',
type: 'string',
conform: path => {
if (fs.isDir(path)) {
return true
}
return false
},
message: 'Inserted source path does not exist or invalid',
required: true
}
const destinationPathValidation = {
name: 'destinationPath',
description: 'Enter full path of destination to be stored at',
type: 'string',
conform: path => {
if (fs.isDir(path)) {
return true
}
return false
},
message: 'Inserted destination path does not exist or invalid',
required: true
}
prompt.get([sourcePathValidation, destinationPathValidation, qualityValidation], function (err, result) {
const sourcePath = result.sourcePath
const destinationPath = result.destinationPath
const quality = result.quality
minify(sourcePath, destinationPath, quality)
});
<file_sep># Minify
It's an application to reduce file size of .png and .jpg images by lowering quality of the image.
- It can inherit file structure (eg. nested) of source images to destination path
- It supports .png and .jpg
- Quality of the image can be between range of 1 ~ 100 (%)
### Tech
Minify uses a number of open source projects:
- [imaginmin](https://github.com/imagemin/imagemin)
- [imageminMozjpeg](https://github.com/imagemin/imagemin-mozjpeg)
- [imageminPngquant](https://github.com/imagemin/imagemin-pngquant)
- and more
### Installation & Run
Minify requires [Node.js](https://nodejs.org/) v6+ to run.
```sh
$ cd minify
$ npm install && npm start
```
Application will ask user to insert followings:
- sourcePath (directory, where source images are located at)
- destinationPath (directory, where minified images will be stored at)
- quality (number within range between 1~100 (%) )
### Todos
- Write Tests
- Support SVG
- Make it exportable
- Import default configuration from template (if provided)
License
----
MIT
| 67f0512c8cbafa4d0074ba4934fe43d33c54d475 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | hcho112/minify | 5051b3ce3f8538fa7c4603f264a9fc759b5fe174 | 80b2d95b2b9a830ef27e694f5894ca44c0da1743 |
refs/heads/master | <repo_name>anshulgoyal12/MavenJava<file_sep>/src/test/java/Selenium/RestAPITest.java
package Selenium;
import org.testng.annotations.Test;
public class RestAPITest {
@Test
public void test5(){
System.out.println("Test 5");
}
@Test
public void test6(){
System.out.println("Test 6");
}
}
| 0ead182db347cdc1844db087d1d64ecc2335fc7c | [
"Java"
] | 1 | Java | anshulgoyal12/MavenJava | e4ff17aa0e93c12633c1e66f3c99eb9f5bfef66e | d52556d1ba90fd751da65b7b675775a7e8ff046c |
refs/heads/master | <file_sep>self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "a945c59f2487e342621e7d925198392b",
"url": "/counterApp/index.html"
},
{
"revision": "227b249837679904932d",
"url": "/counterApp/static/css/main.0faff425.chunk.css"
},
{
"revision": "9394425a6b8574bfd50e",
"url": "/counterApp/static/js/2.87faeb51.chunk.js"
},
{
"revision": "e88a3e95b5364d46e95b35ae8c0dc27d",
"url": "/counterApp/static/js/2.87faeb51.chunk.js.LICENSE.txt"
},
{
"revision": "227b249837679904932d",
"url": "/counterApp/static/js/main.aead32dc.chunk.js"
},
{
"revision": "4ab041058d13b83b6e0c",
"url": "/counterApp/static/js/runtime-main.1f18d933.js"
}
]); | 2ff5585328128cc001e374993719c7814734f4eb | [
"JavaScript"
] | 1 | JavaScript | Pacho04/counterApp | e750d42a0d83d2e02c9dd7076ff4e9b8071251b2 | 28f1b968fb2a2c6c4c66fefa885279be978ff2fc |
refs/heads/master | <file_sep>
// Pozivanje id-a doktori i ubacivanje u konstantu
const doktori = document.getElementById('doktori');
let kartica = ``;
// For loop da prodje kroz sve korisnike i pravi kartice za svakog posebno
for (let i = 0; i < korisnici.results.length; i++) {
const doktor = korisnici.results[i];
kartica += `
<div class="col-sm-12 col-md-4 col-lg-4 col-xl-4>
<div class="card">
<div class="card-body">
<img src="${doktor.picture.large}" value=" class="card-img-top" alt="${doktor.name.first}">
<h5 class="card-title velikoSlovo">${doktor.name.first} ${doktor.name.last}</h5>
<h5>${doktor.name.specijalnost}</h5>
<p class="card-text">Email: ${doktor.email}</p>
</div>
</div>
</div>
`
}
// Ispisivanje na html stranicu
doktori.innerHTML = kartica
var dugme = $('#button');
// Scroll funkcija koja pod uslovom dodaje klasu/dugme ili brise
$(window).scroll(function () {
if ($(window).scrollTop() > 300) {
dugme.addClass('show');
} else {
dugme.removeClass('show');
}
});
// Click funkcija koja vraca korisnika na pocetak stranice za 300 milisekundi
dugme.on('click', function (e) {
e.preventDefault();
$('html, body').animate({ scrollTop: 0 }, '300');
});
<file_sep>
// Kreiranje forme i postavljanje atributa
function makeReservation() {
let form = document.createElement("form");
form.setAttribute("method", "post");
// Na koji mail korisnik salje svoje podatke
form.setAttribute("action", "https://formspree.io/<EMAIL>@<EMAIL>");
document.body.appendChild(form);
form.submit();
}
let dugme = $('#button');
// Scroll funkcija koja pod uslovom dodaje klasu/dugme ili brise
$(window).scroll(function () {
if ($(window).scrollTop() > 300) {
dugme.addClass('show');
} else {
dugme.removeClass('show');
}
});
// Click funkcija koja vraca korisnika na pocetak stranice za 300 milisekundi
dugme.on('click', function (e) {
e.preventDefault();
$('html, body').animate({ scrollTop: 0 }, '300');
});<file_sep>Pacijenti � doktori � zakazivanje
Zavrsni rad:
Na sajtu postoje 4 stranice:
Pocetna
Zakazivanje
O nama
Prijavi se
Pocetna stranica :
Prikazuje strucni tim doktora I njihove specijalnosti kao I kartice sa mogucim specijalistickim pregledima.
Zakazivanje stranica:
Prikazuje formu u koju korisnik unosi svoje podatke, bira doktora i datum zeljenog pregleda.
O nama stranica:
nudi vise informacija o klinici.
Prijavi se stranica:
logIn stranica za prijavu pacijenata koji su vec posetili kliniku, pacijent je logovanjem u mogucnosti da vidi istoriju svojih prethodnih pregleda.
Prijavi se:
<NAME>: korisnicko ime: milos lozinka: 123
<NAME>: korisnicko ime: ivan lozinka: 1234
<file_sep>
// U konstantu pacijenti napravljeni objekti za logIn i podaci o istoriji pacijenata
const pacijenti = {
"results": [{ "username": "milos", "password": "123", "fullName": "<NAME>", "datum": "25.04.2019", "JMBG": "0202993722229", "anamneza": "Leči se od 2016.god od povišenog pritiska", "terapija": "Enalapril 2,5mg 1 dnevno", "kontrola": "Za dva meseca" },
{ "username": "ivan", "password": "<PASSWORD>", "fullName": "<NAME>", "datum": "17.03.2019", "JMBG": "3108993722228", "anamneza": "Dva dana se oseća nestabilno i ima vrtoglavicu", "terapija": "Urutal 8mg", "kontrola": "Kontrola za dve nedelje sa osnovnim laboratorijskim analizama" }]
}
// Funkcija za postavljanje cookie-ja
function setCookie(cname, cvalue, exdays) {
let d = new Date();
// Postavljanje vremena koliko cookie traje
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
let expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + "; path=/";
}
function getCookie(cname) {
let name = cname + "=";
let decodedCookie = decodeURIComponent(document.cookie);
let ca = decodedCookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
// LogIn funkcija
function logIn() {
// Pakuje u promenjivu vrednosti unete u username i password
let userName = document.getElementById('username').value;
let password = document.getElementById('password').value;
// Provera da li su tacni username i password
for (let i = 0; i < pacijenti.results.length; i++) {
let pacijent = pacijenti.results[i];
if (pacijent.username === userName && pacijent.password === password) {
// Ako je uspesno ulogovali ste se
alert("Ulogovali ste se");
// Postavljanje cookie-a, pozivanje promenjive pacijent i hvatanje odredjenog property-a
setCookie("trenutniKorisnik", pacijent.fullName, 365);
setCookie("trenutnaLozinka", pacijent.password, 365);
setCookie("datumPregleda", pacijent.datum, 365);
setCookie("jedBroj", pacijent.JMBG, 365);
setCookie('anamneza', pacijent.anamneza, 365);
setCookie("terapija", pacijent.terapija, 365);
setCookie("kontrola", pacijent.kontrola, 365);
return 0;
}
}
// Ukoliko korisnik je uneo pogresne podatke ostani na istoj stranici
$(document).ready(
function greska() {
window.location.href = "logIn.html";
},
alert("Ne postoji korisnik ili je sifra pogresna")
)
}
// Ispisivanje trenutnog ulogovanog korsnika u navigacioni bar
function postaviTrenutnogKorisnika() {
let trenutniKorisnik = getCookie("trenutniKorisnik");
let korisnik = document.getElementById("trenutniKorisnik");
korisnik.innerHTML = trenutniKorisnik;
if (trenutniKorisnik) {
let element = document.getElementById("milos");
element.style.display = "none";
}
}
function prikaziKorisnika() {
// Ubacivanje u promenjivu i pozivanje cookie-a u zavisnosti od property-ja
let imePrezime = getCookie("trenutniKorisnik");
let datum = getCookie("datumPregleda");
let jedinstveniBroj = getCookie('jedBroj');
let anamneza = getCookie('anamneza');
let terapija = getCookie('terapija');
let kontrola = getCookie('kontrola');
// Ispisivanje podataka u html stranicu/tabelu
let fullName = document.getElementById('fullName');
fullName.innerHTML = imePrezime;
let datumPregleda = document.getElementById('datum');
datumPregleda.innerHTML = datum;
let jmbg = document.getElementById('jmbg');
jmbg.innerHTML = jedinstveniBroj;
let anamneza1 = document.getElementById('anamneza');
anamneza1.innerHTML = anamneza;
let terapija1 = document.getElementById('terapija');
terapija1.innerHTML = terapija;
let kontrola1 = document.getElementById('kontrola');
kontrola1.innerHTML = kontrola;
}
// logout funkcija
function logOut() {
setCookie("trenutniKorisnik", "", 365);
setCookie("trenutnaLozinka", "", 365);
}
var dugme = $('#button');
// Scroll funkcija koja pod uslovom dodaje klasu/dugme ili brise
$(window).scroll(function () {
if ($(window).scrollTop() > 300) {
dugme.addClass('show');
} else {
dugme.removeClass('show');
}
});
// Click funkcija koja vraca korisnika na pocetak stranice za 300 milisekundi
dugme.on('click', function (e) {
e.preventDefault();
$('html, body').animate({ scrollTop: 0 }, '300');
}); | 3fffaa5b36fadc112a1c63621d10bae431787d2e | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | Milos1993/zakazivanje-lekara-zavrsni-rad | aa78f4f93eeabbe66296425dd092c8ff270a3011 | 4e8f4d4d080bbbbc74c17dd28b994aadba6b8af5 |
refs/heads/master | <repo_name>RogoGit/RogoPip<file_sep>/Weblab3/web3/src/main/java/org/rogisa/beans/DotsCollectionBean.java
package org.rogisa.beans;
import java.io.Serializable;
import java.util.ArrayList;
public class DotsCollectionBean implements Serializable {
private ArrayList<DotMaker> areaDots;
public DotsCollectionBean(ArrayList<DotMaker> areaDots) {
this.areaDots = areaDots;
}
public DotsCollectionBean() {
}
public void addDot(String kx, String ky, String rad) {
if (this.areaDots==null) {this.areaDots=new ArrayList<>();}
DotMaker newDot = new DotMaker();
newDot.setKx(Double.parseDouble(kx));
newDot.setKy(Double.parseDouble(ky));
newDot.setRad(Double.parseDouble(rad));
newDot.areaCheck();
areaDots.add(newDot);
}
public ArrayList<DotMaker> getAreaDots() {
return areaDots;
}
}
<file_sep>/Weblab3/web3/build.gradle
plugins {
id 'java'
id 'war'
}
group 'org.rogisa'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
providedCompile group: 'javax.servlet', name: 'javax.servlet-api', version: '3.1.0'
compile group: 'com.sun.faces', name: 'jsf-api', version: '2.2.18'
compile group: 'com.sun.faces', name: 'jsf-impl', version: '2.2.18'
compile group: 'org.primefaces', name: 'primefaces', version: '6.2'
testCompile group: 'junit', name: 'junit', version: '4.11'
testCompile group: 'junit', name: 'junit', version: '4.12'
}
<file_sep>/Weblab3/web3/build/libs/exploded/web3-1.0-SNAPSHOT.war/MainPageScripts.js
var dotArray = []; /// пусть будет пока
var inputRad = document.getElementById("fieldsForm:rad");
var oldRad = 1;
function getMousePos() {
return {
x: (event.clientX - 390) / 180,
y: -(event.clientY - 340) / 180
};
}
function makeNewDot() {
var aX = document.getElementById("AreaForm:AreaX");
var aY = document.getElementById("AreaForm:AreaY");
var aR = document.getElementById("AreaForm:AreaR");
aX.value = getMousePos().x;
aY.value = getMousePos().y;
aR.value = inputRad.value;
document.forms["AreaForm"].submit();
}
function resizeArea() {
var newRad = inputRad.value;
var dots = document.querySelectorAll("circle[name='dot']");
for (var i = 0; i < dots.length; i++) {
var cx = (dots[i].cx.animVal.value - 190) * oldRad / newRad + 190;
var cy = (dots[i].cy.animVal.value - 210) * oldRad / newRad + 210;
dots[i].setAttribute("cx", cx);
dots[i].setAttribute("cy", cy);
oldRad = inputRad.value;
}
}
<file_sep>/RogoPip2/web/Js.js
var areaRads = [1,2,3,4,5];
const FETCH_TIMEOUT = 3200;
var ifOK = true;
for (k=0; k<5; k++) {
areaRads[k] = [];
}
var rad = 0;
window.onload = function() {
var canv = document.getElementById("CheckArea");
var canvDraw = canv.getContext("2d");
canv.addEventListener("click",listener,true);
drawArea();
};
function listener(evt) {
let txt,m;
let didTimeOut = false;
var canv = document.getElementById("CheckArea");
var canvDraw = canv.getContext("2d");
ifOK = true;
m = document.getElementById("errors");
var mousePos = getMousePos(canv, evt);
var color;
//var value = [];
/* */
txt = "Точка обрабатывается...";
m.classList.remove("hidden");
document.getElementById("errors").innerHTML = txt;
document.getElementById("kXarea").value = (mousePos.x-200)/40;
document.getElementById("kYarea").value = -(mousePos.y-200)/40;
document.getElementById("radArea").value = rad;
evt.preventDefault();
const formData = new FormData(document.querySelector('#checker2'));
const params = new URLSearchParams();
for(const pair of formData.entries()){
params.append(pair[0], pair[1]);
}
//console.log(ifOK);
//console.log(didTimeOut);
new Promise(function(resolve, reject) {
const timeout = setTimeout(function() {
didTimeOut = true;
reject(new Error('Request timed out'));
}, FETCH_TIMEOUT);
fetch('', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: params.toString()
}).then(response => response.text()).then(htmlTable => document.querySelector('#results').insertAdjacentHTML('beforeend', htmlTable))
.then(function(response) {
// Clear the timeout as cleanup
clearTimeout(timeout);
if(!didTimeOut) {
console.log('fetch good! ', response);
ifOK = true;
resolve(response);
}
})
.catch(function(err) {
console.log(err);
ifOK = false;
// Rejection already happened with setTimeout
if(didTimeOut) return;
// Reject with error
reject(err);
});
})
.then(function() {
ifOK = true;
// Request success and no timeout
console.log('good promise, no timeout! ');
canv.addEventListener('click',listener,true);
if (ifInside(mousePos.x,mousePos.y,rad)) {
canvDraw.beginPath();
canvDraw.moveTo(mousePos.x,mousePos.y);
canvDraw.arc(mousePos.x,mousePos.y,2,0,2*Math.PI,false);
canvDraw.fillStyle = 'green';
canvDraw.fill();
color = 'green';
} else
{
canvDraw.beginPath();
canvDraw.moveTo(mousePos.x,mousePos.y);
canvDraw.arc(mousePos.x,mousePos.y,2,0,2*Math.PI,false);
canvDraw.fillStyle = 'red';
canvDraw.fill();
color = 'red';
}
var value = [mousePos.x,mousePos.y,2,0,2*Math.PI,false,color];
areaRads[rad-1].push(value);
document.getElementById("errors").innerHTML = "Готово";
})
.catch(function(err) {
// Error: response error, request timeout or runtime error
ifOK = false;
// alert("Серверные проблемы");
document.getElementById("errors").innerHTML = "ВНИМАНИЕ! Проблемы с сервером!";
console.log('promise error! ', err);
ifOK = true;
});
// canv.removeEventListener('click',listener,true);
}
function drawArea() {
// if (chk)
var canv = document.getElementById("CheckArea");
var canvDraw = canv.getContext("2d");
rad = document.getElementById("AreaRad").value;
canvDraw.clearRect(0,0,canv.width,canv.height);
var backGround = new Image();
backGround.src = 'Coordinates.png';
canvDraw.drawImage(backGround, 0, 0);
canvDraw.beginPath();
canvDraw.moveTo(200,200);
canvDraw.arc(200,200,rad*20,0,0.5*Math.PI,false);
canvDraw.lineTo(200,200);
canvDraw.fillStyle = 'LightBlue';
canvDraw.fill();
canvDraw.stroke();
canvDraw.beginPath();
canvDraw.rect(200-rad*40,200,200-(200-rad*40),200-(200-rad*20));
canvDraw.fillStyle = 'LightBlue';
canvDraw.fill();
canvDraw.stroke();
canvDraw.beginPath();
canvDraw.moveTo(200,200);
canvDraw.lineTo(200,200-rad*40);
canvDraw.lineTo(200+rad*20,200);
canvDraw.closePath();
canvDraw.fillStyle = 'LightBlue';
canvDraw.fill();
canvDraw.stroke();
canv.removeEventListener('click',listener,true);
if (ifOK) canv.addEventListener('click',listener,true);
if (areaRads[rad-1].length!==0 && ifOK) { //-1
for (l=0; l<areaRads[rad-1].length; l++) { //-1
canvDraw.beginPath();
canvDraw.moveTo(areaRads[rad-1][l][0],areaRads[rad-1][l][1]);
canvDraw.arc(areaRads[rad-1][l][0],areaRads[rad-1][l][1],areaRads[rad-1][l][2],areaRads[rad-1][l][3],areaRads[rad-1][l][4],areaRads[rad-1][l][5]);
canvDraw.fillStyle = areaRads[rad-1][l][6];
canvDraw.fill(); }
}
}
///////////////////////////////////////////////////////////////////////////
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function ifInside(x,y,nesRad) {
// var rad = document.getElementById("AreaRad").value;
if ((x>=200) && (y>=200) && ((Math.pow((x-200),2) + Math.pow((y-200),2)) <= Math.pow((nesRad*20),2))) {return true;}
if ((x>=200) && (y<=200) && ((200-(200+(y-200)))<=((-2)*(x-200)+nesRad*40))) {return true;}
if ((x<=200) && (y>=200) && (x>=(200-(nesRad*40))) && (y<=(200+(nesRad*20)))) {return true;}
return false;
}
function checkValid(e) {
var x, er, text;
// let ifOK = true;
let didTimeOut = false;
var canv = document.getElementById("CheckArea");
var canvDraw = canv.getContext("2d");
er = document.getElementById("errors");
x = document.getElementById("enter").value;
x = x.replace(',','.');
if (isNaN(x) || (x=='')) {
text = "Ошибка! Координата X - не число";
er.classList.remove("hidden");
document.getElementById("errors").innerHTML = text;
e.preventDefault();
return false;
} else {
if(x < -5 || x > 3) {
text = " Ошибка! Координата X должна быть от -5 до 3";
er.classList.remove("hidden");
document.getElementById("errors").innerHTML = text;
e.preventDefault();
return false;
} else {
text = "Данные верны";
er.classList.add("hidden");
document.getElementById("errors").innerHTML = text;
e.preventDefault();
const formData = new FormData(document.querySelector('#checkForm'));
const params = new URLSearchParams();
for(const pair of formData.entries()){
params.append(pair[0], pair[1]);
}
document.getElementById("errors").classList.remove("hidden");
document.getElementById("errors").innerHTML = "Точка обрабатывается...";
////////////////////
new Promise(function(resolve, reject) {
const timeout = setTimeout(function() {
didTimeOut = true;
reject(new Error('Request timed out'));
}, FETCH_TIMEOUT);
fetch('', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: params.toString()
}).then(response => response.text()).then(htmlTable => document.querySelector('#results').insertAdjacentHTML('beforeend', htmlTable))
.then(function(response) {
// Clear the timeout as cleanup
clearTimeout(timeout);
if(!didTimeOut) {
console.log('fetch good! ', response);
ifOK = true;
resolve(response);
}
})
.catch(function(err) {
console.log(err);
ifOK = false;
// Rejection already happened with setTimeout
if(didTimeOut) return;
// Reject with error
reject(err);
});
})
.then(function() {
ifOK = true;
// Request success and no timeout
console.log('good promise, no timeout! ');
canv.addEventListener('click',listener,true);
let color2;
var kkx = document.getElementById("enter").value*40+200;
var kky = document.getElementById("kYY").value*(-40)+200;
if (ifInside(kkx,kky,rad)) {
canvDraw.beginPath();
canvDraw.moveTo(kkx,kky);
canvDraw.arc(kkx,kky,2,0,2*Math.PI,false);
canvDraw.fillStyle = 'green';
canvDraw.fill();
color2 = 'green';
} else {
canvDraw.beginPath();
canvDraw.moveTo(kkx,kky);
canvDraw.arc(kkx,kky,2,0,2*Math.PI,false);
canvDraw.fillStyle = 'red';
canvDraw.fill();
color2 = 'red';
}
var value2 = [kkx,kky,2,0,2*Math.PI,false,color2];
areaRads[rad-1].push(value2);
document.getElementById("errors").innerHTML = "Готово";
//drawArea();
})
.catch(function(err) {
// Error: response error, request timeout or runtime error
ifOK = false;
// alert("Серверные проблемы");
document.getElementById("errors").innerHTML = "ВНИМАНИЕ! Проблемы с сервером!";
console.log('promise error! ', err);
ifOK = true;
});
//////////////////////////////
return true; }
}
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('check').addEventListener('click', submit);
});
<file_sep>/Weblab3/web3/settings.gradle
rootProject.name = 'web3'
| ae1d80127933dc64e34e218034361a0960489f73 | [
"JavaScript",
"Java",
"Gradle"
] | 5 | Java | RogoGit/RogoPip | 8d763d9c2cc2394b761098bf3e94c95065e43d28 | 5c707ec7429d43e182c4ee651eb5c625ceb936b0 |
refs/heads/master | <repo_name>reaperhulk/srslog<file_sep>/net_conn.go
package srslog
import (
"fmt"
"net"
"os"
"time"
)
// netConn has an internal net.Conn and adheres to the serverConn interface,
// allowing us to send syslog messages over the network.
type netConn struct {
conn net.Conn
}
// writeString formats syslog messages using time.RFC3339 and includes the
// hostname, and sends the message to the connection.
func (n *netConn) writeString(p Priority, hostname, tag, msg string) error {
timestamp := time.Now().Format(time.RFC3339)
_, err := fmt.Fprintf(n.conn, "<%d>%s %s %s[%d]: %s",
p, timestamp, hostname,
tag, os.Getpid(), msg)
return err
}
// close the network connection
func (n *netConn) close() error {
return n.conn.Close()
}
<file_sep>/writer_test.go
package srslog
import (
"testing"
)
func TestCloseNonOpenWriter(t *testing.T) {
w := Writer{}
err := w.Close()
if err != nil {
t.Errorf("should not fail to close if there is nothing to close")
}
}
func TestWriteAndRetryFails(t *testing.T) {
w := Writer{network: "udp", raddr: "fakehost"}
n, err := w.writeAndRetry(LOG_ERR, "nope")
if err == nil {
t.Errorf("should fail to write")
}
if n != 0 {
t.Errorf("should not write any bytes")
}
}
func TestDebug(t *testing.T) {
done := make(chan string)
addr, sock, srvWG := startServer("udp", "", done)
defer sock.Close()
defer srvWG.Wait()
w := Writer{
priority: LOG_ERR,
tag: "tag",
hostname: "hostname",
network: "udp",
raddr: addr,
}
w.Lock()
err := w.connect()
if err != nil {
t.Errorf("failed to connect: %v", err)
w.Unlock()
}
w.Unlock()
defer w.Close()
err = w.Debug("this is a test message")
if err != nil {
t.Errorf("failed to debug: %v", err)
}
checkWithPriorityAndTag(t, LOG_DEBUG, "tag", "hostname", "this is a test message", <-done)
}
func TestInfo(t *testing.T) {
done := make(chan string)
addr, sock, srvWG := startServer("udp", "", done)
defer sock.Close()
defer srvWG.Wait()
w := Writer{
priority: LOG_ERR,
tag: "tag",
hostname: "hostname",
network: "udp",
raddr: addr,
}
w.Lock()
err := w.connect()
if err != nil {
t.Errorf("failed to connect: %v", err)
w.Unlock()
}
w.Unlock()
defer w.Close()
err = w.Info("this is a test message")
if err != nil {
t.Errorf("failed to info: %v", err)
}
checkWithPriorityAndTag(t, LOG_INFO, "tag", "hostname", "this is a test message", <-done)
}
func TestNotice(t *testing.T) {
done := make(chan string)
addr, sock, srvWG := startServer("udp", "", done)
defer sock.Close()
defer srvWG.Wait()
w := Writer{
priority: LOG_ERR,
tag: "tag",
hostname: "hostname",
network: "udp",
raddr: addr,
}
w.Lock()
err := w.connect()
if err != nil {
t.Errorf("failed to connect: %v", err)
w.Unlock()
}
w.Unlock()
defer w.Close()
err = w.Notice("this is a test message")
if err != nil {
t.Errorf("failed to notice: %v", err)
}
checkWithPriorityAndTag(t, LOG_NOTICE, "tag", "hostname", "this is a test message", <-done)
}
func TestWarning(t *testing.T) {
done := make(chan string)
addr, sock, srvWG := startServer("udp", "", done)
defer sock.Close()
defer srvWG.Wait()
w := Writer{
priority: LOG_ERR,
tag: "tag",
hostname: "hostname",
network: "udp",
raddr: addr,
}
w.Lock()
err := w.connect()
if err != nil {
t.Errorf("failed to connect: %v", err)
w.Unlock()
}
w.Unlock()
defer w.Close()
err = w.Warning("this is a test message")
if err != nil {
t.Errorf("failed to warn: %v", err)
}
checkWithPriorityAndTag(t, LOG_WARNING, "tag", "hostname", "this is a test message", <-done)
}
func TestErr(t *testing.T) {
done := make(chan string)
addr, sock, srvWG := startServer("udp", "", done)
defer sock.Close()
defer srvWG.Wait()
w := Writer{
priority: LOG_ERR,
tag: "tag",
hostname: "hostname",
network: "udp",
raddr: addr,
}
w.Lock()
err := w.connect()
if err != nil {
t.Errorf("failed to connect: %v", err)
w.Unlock()
}
w.Unlock()
defer w.Close()
err = w.Err("this is a test message")
if err != nil {
t.Errorf("failed to err: %v", err)
}
checkWithPriorityAndTag(t, LOG_ERR, "tag", "hostname", "this is a test message", <-done)
}
func TestCrit(t *testing.T) {
done := make(chan string)
addr, sock, srvWG := startServer("udp", "", done)
defer sock.Close()
defer srvWG.Wait()
w := Writer{
priority: LOG_ERR,
tag: "tag",
hostname: "hostname",
network: "udp",
raddr: addr,
}
w.Lock()
err := w.connect()
if err != nil {
t.Errorf("failed to connect: %v", err)
w.Unlock()
}
w.Unlock()
defer w.Close()
err = w.Crit("this is a test message")
if err != nil {
t.Errorf("failed to crit: %v", err)
}
checkWithPriorityAndTag(t, LOG_CRIT, "tag", "hostname", "this is a test message", <-done)
}
func TestAlert(t *testing.T) {
done := make(chan string)
addr, sock, srvWG := startServer("udp", "", done)
defer sock.Close()
defer srvWG.Wait()
w := Writer{
priority: LOG_ERR,
tag: "tag",
hostname: "hostname",
network: "udp",
raddr: addr,
}
w.Lock()
err := w.connect()
if err != nil {
t.Errorf("failed to connect: %v", err)
w.Unlock()
}
w.Unlock()
defer w.Close()
err = w.Alert("this is a test message")
if err != nil {
t.Errorf("failed to alert: %v", err)
}
checkWithPriorityAndTag(t, LOG_ALERT, "tag", "hostname", "this is a test message", <-done)
}
func TestEmerg(t *testing.T) {
done := make(chan string)
addr, sock, srvWG := startServer("udp", "", done)
defer sock.Close()
defer srvWG.Wait()
w := Writer{
priority: LOG_ERR,
tag: "tag",
hostname: "hostname",
network: "udp",
raddr: addr,
}
w.Lock()
err := w.connect()
if err != nil {
t.Errorf("failed to connect: %v", err)
w.Unlock()
}
w.Unlock()
defer w.Close()
err = w.Emerg("this is a test message")
if err != nil {
t.Errorf("failed to emerg: %v", err)
}
checkWithPriorityAndTag(t, LOG_EMERG, "tag", "hostname", "this is a test message", <-done)
}
| 9b733d29408c8bfb2ab34d191f4acc5baae1ef97 | [
"Go"
] | 2 | Go | reaperhulk/srslog | 40908562a941b533797e465606a2e8643b20bcf7 | b748e13d6d8c85b98e3f393cc31bf6e4a6f11a33 |
refs/heads/master | <repo_name>NobodyCH/selenium_bot_thc-game.com_public<file_sep>/main.py
from selenium import webdriver
import datetime
import time
def login_func(username, password):
driver = webdriver.Chrome()
driver.get('http://thc-game.com')
mail_field = driver.find_element_by_name("thclogin_name")
mail_field.send_keys(username)
pass_field = driver.find_element_by_name("thclogin_pass")
pass_field.send_keys(<PASSWORD>)
pass_field.submit()
driver.switch_to.frame(driver.find_element_by_xpath(" / html / frameset / frame"))
check_activity(driver)
return driver
def skillen(driver,input_skilltype):
print("waehle skillen")
driver.find_element_by_xpath('//*[@id="hmenu"]/table[1]/tbody/tr[2]/td[2]/nav/a[11]').click()
if input_skilltype == "1":
print("eingabe erkannt")
driver.find_element_by_xpath('//*[@id="skilltable"]/tbody/tr[3]/td[4]/form').click()
element = driver.find_element_by_xpath('//*[@id="skilltable"]/tbody/tr[3]/td[5]')
timer = element.text
h, m, s = timer.split(':')
sleep_time = int(datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s)).total_seconds())
print("Skille: " + str(sleep_time) + " sekunden!")
time.sleep(sleep_time+1)
elif input_skilltype == "2":
driver.find_element_by_xpath('//*[@id="skilltable"]/tbody/tr[4]/td[4]/form').click()
element = driver.find_element_by_xpath('//*[@id="skilltable"]/tbody/tr[4]/td[5]')
timer = element.text
h, m, s = timer.split(':')
sleep_time = int(datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s)).total_seconds())
print("Skille: " + str(sleep_time) + " sekunden!")
time.sleep(sleep_time+1)
elif input_skilltype == "3":
driver.find_element_by_xpath('//*[@id="skilltable"]/tbody/tr[5]/td[4]/form').click()
element = driver.find_element_by_xpath('//*[@id="skilltable"]/tbody/tr[5]/td[5]')
timer = element.text
h, m, s = timer.split(':')
sleep_time = int(datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s)).total_seconds())
print("Skille: " + str(sleep_time) + " sekunden!")
time.sleep(sleep_time+1)
elif input_skilltype == "4":
driver.find_element_by_xpath('//*[@id="skilltable"]/tbody/tr[6]/td[4]/form').click()
element = driver.find_element_by_xpath('//*[@id="skilltable"]/tbody/tr[6]/td[5]')
timer = element.text
h, m, s = timer.split(':')
sleep_time = int(datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s)).total_seconds())
print("Skille: " + str(sleep_time) +" sekunden!")
time.sleep(sleep_time+1)
elif input_skilltype == "5":
driver.find_element_by_xpath('//*[@id="skilltable"]/tbody/tr[7]/td[4]/form').click()
element = driver.find_element_by_xpath('//*[@id="skilltable"]/tbody/tr[7]/td[5]')
timer = element.text
h, m, s = timer.split(':')
sleep_time = int(datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s)).total_seconds())
print("Skille: " + str(sleep_time) + " sekunden!")
time.sleep(sleep_time+1)
elif input_skilltype == "6":
driver.find_element_by_xpath('//*[@id="skilltable"]/tbody/tr[8]/td[4]/form').click()
element = driver.find_element_by_xpath('//*[@id="skilltable"]/tbody/tr[8]/td[5]')
timer = element.text
h, m, s = timer.split(':')
sleep_time = int(datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s)).total_seconds())
print("Skille: " + str(sleep_time) + " sekunden!")
time.sleep(sleep_time+1)
def insert_check(skill_type):
if skill_type is None:
skill_type = input("Bitte wähle was du Skillen willst [1] Stärke [2] Geschik usw.. [1-6]: ")
if skill_type == "1" or skill_type == "2" or skill_type == "3" or skill_type == "4" or skill_type == "5" or skill_type == "6":
print("Skilltyp erkannt!")
return skill_type
else:
skill_type = None
insert_check(skill_type)
def sleep_gangster():
needsleep = driver.find_element_by_xpath('//*[@id="gangsterInfoDiv"]/table/tbody/tr[3]/td[2]')
txt = needsleep.text
numberprocent, pattern = txt.split()
if float(numberprocent) <= 9:
driver.find_element_by_xpath('//*[@id="hmenu"]/table[1]/tbody/tr[2]/td[2]/nav/a[2]').click()
driver.find_element_by_xpath('//*[@id="gangster"]/div[5]/table/tbody/tr[1]/td[2]/form/input').click()
element = driver.find_element_by_xpath('// *[ @ id = "stimer"]')
timer = element.text
h, m, s = timer.split(':')
sleep_time = int(datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s)).total_seconds())
print("Aktion: Schlafen " + str(sleep_time) + " Sekunden")
driver.find_element_by_xpath('//*[@id="hmenu"]/table[1]/tbody/tr[2]/td[2]/nav/a[2]').click()
time.sleep(sleep_time)
elif float(numberprocent) >= 10:
print("genug Energie weiter gehts!")
def check_login(driver):
print("Loging Prüfen..")
gangsterinfo = driver.find_element_by_xpath('//*[@id="gangsterInfoDiv"]/table/tbody/tr[2]/td[1]')
print("ok")
health = str(gangsterinfo.text)
if health == "Health:":
print("du bist noch eingeloggt")
else:
login_func(username,password)
def action(username, password, driver, input_skilltype):
try:
while True:
sleep_gangster()
print("gehe zu skillen")
skillen(driver, input_skilltype)
check_login(driver)
except:
print("fail")
driver.quit()
main(input_skilltype)
def main(skill_type):
global username, password, driver
# Globale Variablen
username = "here your mail"
password = "<PASSWORD>"
input_skilltype = insert_check(skill_type)
driver = login_func(username, password)
action(username, password, driver, input_skilltype)
def check_activity(driver):
element = driver.find_element_by_xpath('//*[@id="gangsterInfoDiv"]/table/tbody/tr[8]/td[2]')
activity = element.text
print(activity)
if activity == "schlafen":
element_task = driver.find_element_by_xpath('//*[@id="overview1"]')
do_wait_task(element_task, activity, driver)
elif activity == "skillen":
element_task = driver.find_element_by_xpath('//*[@id="overview2"]')
do_wait_task(element_task, activity, driver)
elif activity == "keine aktivitaet":
print("kein Skill am laufen")
def do_wait_task(element_task, activity, driver):
activity_schlafen = element_task.text
print(activity_schlafen)
if activity_schlafen == "fertig":
print("Hui dein Skill ist abgelaufen aber nicht aktualisiert.. aktualisieren..")
driver.find_element_by_xpath('//*[@id="hmenu"]/table[1]/tbody/tr[2]/td[2]/nav/a[11]').click()
driver.find_element_by_xpath('//*[@id="hmenu"]/table[1]/tbody/tr[2]/td[2]/nav/a[2]').click()
else:
h, m, s = activity_schlafen.split(':')
sleep_time = int(datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s)).total_seconds())
print("Du bist noch am " + activity + ", erstmal warten: " + str(sleep_time) + " sekunden!")
time.sleep(sleep_time + 1)
if __name__ == "__main__":
skill_type = None
main(skill_type)
| a0653ffb2e564b3fa0d48ee8cfad8a0dcaaa7551 | [
"Python"
] | 1 | Python | NobodyCH/selenium_bot_thc-game.com_public | ae97fb4ab76b839f1c44223ff7b975843d3d4441 | 2b15a2053ca9122371e5c1125cb09082a777c3c6 |
refs/heads/master | <repo_name>decisionnguyen/typer<file_sep>/src/delta/__tests__/diff-test.ts
import { makeDiffDelta } from '@delta/diff'
describe('@delta/diff', () => {
describe('makeDiffDelta', () => {
it('should find the minimal set of diff operations', () => {
const text1 = 'A\n'
const text2 = 'A\nB\n'
expect(makeDiffDelta(text1, text2, {})).toEqual({
ops: [{ retain: 2 }, { insert: 'B\n' }],
})
})
it('should not be greedy with words', () => {
const text1 = 'A\nB C'
const text2 = 'A\nB DEF'
expect(makeDiffDelta(text1, text2, {})).toEqual({
ops: [{ retain: 4 }, { insert: 'DEF' }, { delete: 1 }],
})
})
it('should apply text attributes to characters within a line', () => {
const text1 = 'A\nBC'
const text2 = 'A\nBCDEF'
expect(makeDiffDelta(text1, text2, { weight: 'bold' })).toEqual({
ops: [{ retain: 4 }, { insert: 'DEF', attributes: { weight: 'bold' } }],
})
})
it('should not apply text attributes to newline characters', () => {
const text1 = 'A\nBC'
const text2 = 'A\nBCDEF\nGHI'
expect(makeDiffDelta(text1, text2, { weight: 'bold' })).toEqual({
ops: [
{ retain: 4 },
{ insert: 'DEF', attributes: { weight: 'bold' } },
{ insert: '\n' },
{ insert: 'GHI', attributes: { weight: 'bold' } },
],
})
})
})
})
<file_sep>/src/model/blocks.ts
import { GenericOp } from '@delta/operations'
import last from 'ramda/es/last'
import Op from 'quill-delta/dist/Op'
import { Block } from './Block'
export type BlockType = 'image' | 'text'
export interface BlockDescriptor {
/**
* Inclusive begining of Op slice index.
*/
startSliceIndex: number
/**
* Exclusive end of Op slice index.
*/
endSliceIndex: number
/**
* The offset to apply to selection.
*/
selectableUnitsOffset: number
/**
* The number of selectable units.
*/
numOfSelectableUnits: number
blockIndex: number
maxBlockIndex: number
kind: BlockType
opsSlice: GenericOp[]
}
function opsToBlocks(blocks: Block[], currentValue: GenericOp, i: number, l: GenericOp[]): Block[] {
if (currentValue.insert === undefined) {
return blocks
}
const kind: BlockType = typeof currentValue.insert === 'string' ? 'text' : 'image'
let lastGroup: Block = last(blocks) as Block
const isFirstGroup = !lastGroup
if (isFirstGroup) {
lastGroup = new Block(
{
kind,
opsSlice: [],
startSliceIndex: 0,
endSliceIndex: 0,
numOfSelectableUnits: 0,
selectableUnitsOffset: 0,
blockIndex: 0,
maxBlockIndex: l.length - 1,
},
blocks,
)
blocks.push(lastGroup)
}
const lastBlockDesc = lastGroup.descriptor
if (lastBlockDesc.kind !== kind || (kind === 'image' && !isFirstGroup)) {
const kindOps = [currentValue]
const newGroup: Block = new Block(
{
kind,
opsSlice: kindOps,
numOfSelectableUnits: Op.length(currentValue),
startSliceIndex: lastBlockDesc.endSliceIndex,
endSliceIndex: lastBlockDesc.endSliceIndex + 1,
blockIndex: lastBlockDesc.blockIndex + 1,
selectableUnitsOffset: lastBlockDesc.numOfSelectableUnits + lastBlockDesc.selectableUnitsOffset,
maxBlockIndex: l.length - 1,
},
blocks,
)
blocks.push(newGroup)
} else {
lastBlockDesc.opsSlice.push(currentValue)
lastBlockDesc.numOfSelectableUnits += Op.length(currentValue)
lastBlockDesc.endSliceIndex += 1
}
return blocks
}
export function groupOpsByBlocks(ops: GenericOp[]): Block[] {
return ops.reduce<Block[]>(opsToBlocks, [])
}
<file_sep>/src/core/Transforms.ts
import prop from 'ramda/es/prop'
import groupBy from 'ramda/es/groupBy'
import { StyleProp, TextStyle, ViewStyle } from 'react-native'
import invariant from 'invariant'
import { TextOp } from '@delta/operations'
import { Attributes } from '@delta/attributes'
const attributeNameGetter = prop('attributeName') as (
t: Transforms.GenericSpec<Attributes.GenericValue, Transforms.TargetType>,
) => string
export function textTransformListToDict<A extends Attributes.GenericValue, T extends Transforms.TargetType>(
list: Transforms.GenericSpec<A, T>[],
): Transforms.Dict<A, T> {
return groupBy(attributeNameGetter)(list) as Transforms.Dict<A, T>
}
/**
* A set of definitions related to text and arbitrary content transforms.
*
* @public
*/
declare namespace Transforms {
/**
* The target type of a transform.
*/
export type TargetType = 'block' | 'text'
/**
* A {@link (Transforms:namespace).GenericSpec} which `attributeActiveValue` is `true`.
*
* @public
*/
export type BoolSpec<T extends TargetType = 'block'> = GenericSpec<true, T>
/**
* A mapping of attribute names with their corresponding transformation description.
*
* @internal
*/
export interface Dict<A extends Attributes.GenericValue, T extends TargetType> {
[attributeName: string]: GenericSpec<A, T>[]
}
/**
* Default text attributes names.
*
* @public
*/
export type TextAttributeName = 'bold' | 'italic' | 'textDecoration'
/**
* Description of a generic transform.
*
* @public
*/
export interface GenericSpec<A extends Attributes.GenericValue, T extends TargetType> {
/**
* The name of the attribute.
*
* @remarks
*
* Multiple {@link (Transforms:namespace).GenericSpec} can share the same `attributeName`.
*/
attributeName: string
/**
* The value of the attribute when this transform is active.
*/
activeAttributeValue: A
/**
* The style applied to the target block when this transform is active.
*/
activeStyle: T extends 'block' ? ViewStyle : TextStyle
}
export type Specs<T extends 'text' | 'block' = 'text'> = GenericSpec<Attributes.TextValue, T>[]
}
/**
* An entity which responsibility is to provide styles from text transforms.
*
* @public
*/
class Transforms {
private textTransformsDict: Transforms.Dict<Attributes.TextValue, 'text'>
public constructor(textTransformSpecs: Transforms.GenericSpec<Attributes.TextValue, 'text'>[]) {
this.textTransformsDict = textTransformListToDict(textTransformSpecs)
}
/**
* Produce react styles from a text operation.
*
* @param op - text op.
*
* @internal
*/
public getStylesFromOp(op: TextOp): StyleProp<TextStyle> {
const styles: StyleProp<TextStyle> = []
if (op.attributes) {
for (const attributeName of Object.keys(op.attributes)) {
if (op.attributes != null && attributeName !== '$type') {
const attributeValue = op.attributes[attributeName]
let match = false
if (attributeValue !== null) {
for (const candidate of this.textTransformsDict[attributeName] || []) {
if (candidate.activeAttributeValue === attributeValue) {
styles.push(candidate.activeStyle)
match = true
}
}
invariant(
match,
`A Text Transform must be specified for attribute "${attributeName}" with value ${JSON.stringify(
attributeValue,
)}`,
)
}
}
}
}
return styles
}
}
export { Transforms }
export const booleanTransformBase = {
activeAttributeValue: true as true,
}
export const boldTransform: Transforms.BoolSpec<'text'> = {
...booleanTransformBase,
attributeName: 'bold',
activeStyle: {
fontWeight: 'bold',
},
}
export const italicTransform: Transforms.BoolSpec<'text'> = {
...booleanTransformBase,
attributeName: 'italic',
activeStyle: {
fontStyle: 'italic',
},
}
export const underlineTransform: Transforms.GenericSpec<'underline', 'text'> = {
activeAttributeValue: 'underline',
attributeName: 'textDecoration',
activeStyle: {
textDecorationStyle: 'solid',
textDecorationLine: 'underline',
},
}
export const strikethroughTransform: Transforms.GenericSpec<'strikethrough', 'text'> = {
activeAttributeValue: 'strikethrough',
attributeName: 'textDecoration',
activeStyle: {
textDecorationStyle: 'solid',
textDecorationLine: 'line-through',
},
}
/**
* @public
*/
export const defaultTextTransforms: Transforms.GenericSpec<Attributes.TextValue, 'text'>[] = [
boldTransform,
italicTransform,
underlineTransform,
strikethroughTransform,
]
<file_sep>/src/hooks/use-bridge.ts
import { buildBridge, Bridge } from '@core/Bridge'
import { Images } from '@core/Images'
import { useMemo } from 'react'
/**
* React hook which returns a bridge.
*
* @remarks One bridge instance should exist for one document renderer instance.
* @param deps - A list of values which should trigger, on change, the creation of a new {@link (Bridge:interface)} instance.
* @public
*/
export function useBridge<ImageSource = Images.StandardSource>(deps: unknown[] = []): Bridge<ImageSource> {
// eslint-disable-next-line react-hooks/exhaustive-deps
return useMemo(() => buildBridge<ImageSource>(), deps)
}
<file_sep>/src/components/GenericBlockInput/TextBlockInput/TextChangeSession.ts
import { Selection, SelectionShape } from '@delta/Selection'
import { DeltaChangeContext } from '@delta/DeltaChangeContext'
export class TextChangeSession {
private selectionBeforeChange: SelectionShape | null = null
private selectionAfterChange: SelectionShape | null = null
private textAfterChange: string | null = null
public getDeltaChangeContext(): DeltaChangeContext {
if (this.selectionAfterChange === null) {
throw new Error('selectionAfterChange must be set before getting delta change context.')
}
if (this.selectionBeforeChange === null) {
throw new Error('selectionBeforeChange must be set before getting delta change context.')
}
return new DeltaChangeContext(
Selection.fromShape(this.selectionBeforeChange),
Selection.fromShape(this.selectionAfterChange),
)
}
public setTextAfterChange(textAfterChange: string) {
this.textAfterChange = textAfterChange
}
public setSelectionBeforeChange(selectionBeforeChange: SelectionShape) {
this.selectionBeforeChange = selectionBeforeChange
}
public setSelectionAfterChange(selectionAfterChange: SelectionShape) {
this.selectionAfterChange = selectionAfterChange
}
public getTextAfterChange() {
if (this.textAfterChange === null) {
throw new Error('textAfterChange is not set.')
}
return this.textAfterChange
}
}
<file_sep>/src/delta/DeltaBuffer.ts
import Delta from 'quill-delta'
export class DeltaBuffer {
private chunks: Delta[] = []
public push(...delta: Delta[]) {
this.chunks.push(...delta)
}
public compose() {
return this.chunks.reduce((prev, curr) => prev.concat(curr), new Delta())
}
}
<file_sep>/src/model/__tests__/Block-test.ts
import { buildEmptyDocument, Document } from '@model/document'
import { buildTextOp, GenericOp } from '@delta/operations'
import { groupOpsByBlocks } from '@model/blocks'
import { buildDummyImageOp } from '@test/document'
describe('@model/Block', () => {
function buildDocContentWithSel(start: number, end: number, ops?: GenericOp[]): Document {
const obj = {
...buildEmptyDocument(),
currentSelection: { start, end },
}
return ops ? { ...obj, ops } : obj
}
function createContext(start: number, end: number, ops: GenericOp[]) {
const doc: Document = buildDocContentWithSel(start, end, ops)
const blocks = groupOpsByBlocks(ops)
return {
doc,
blocks,
}
}
describe('isFocused', () => {
it('should return true when active area matches block', () => {
const { blocks, doc } = createContext(0, 3, [buildTextOp('Hel')])
expect(blocks.length).toBe(1)
const block = blocks[0]
expect(block.isFocused(doc)).toBe(true)
})
it('should return false when active area overflows block', () => {
const { blocks, doc } = createContext(0, 4, [buildTextOp('Hel')])
expect(blocks.length).toBe(1)
const block = blocks[0]
expect(block.isFocused(doc)).toBe(false)
})
it('should return false when active area is outside of block', () => {
const { blocks, doc } = createContext(3, 4, [buildTextOp('Hel')])
expect(blocks.length).toBe(1)
const block = blocks[0]
expect(block.isFocused(doc)).toBe(false)
})
it('should return false when selection is of length 0, touching the end of this block and the next block', () => {
const ops = [buildDummyImageOp(), buildTextOp('Hel\n')]
const { blocks, doc } = createContext(1, 1, ops)
expect(blocks.length).toBe(2)
const textBlock = blocks[1]
const imageBlock = blocks[0]
expect(textBlock.isFocused(doc)).toBe(true)
expect(imageBlock.isFocused(doc)).toBe(false)
})
})
describe('updateTextAttributesAtSelection', () => {
it('should update text attributes', () => {
const ops = [buildTextOp('Y', { bold: true }), buildTextOp('\n')]
const { blocks, doc } = createContext(0, 1, ops)
expect(blocks.length).toBe(1)
const textBlock = blocks[0]
expect(textBlock.updateTextAttributesAtSelection(doc).selectedTextAttributes).toMatchObject({
bold: true,
})
})
})
describe('applyTextTransformToSelection', () => {
it('should apply transform to a selection encompassing a text block', () => {
const ops = [buildTextOp('Lol\n')]
const { blocks, doc } = createContext(0, 3, ops)
expect(blocks.length).toBe(1)
const textBlock = blocks[0]
expect(textBlock.applyTextTransformToSelection('bold', true, doc).ops).toMatchObject([
buildTextOp('Lol', { bold: true }),
buildTextOp('\n'),
])
})
it('should not apply transform to a selection encompassing a non-text block', () => {
const ops = [buildTextOp('Lol'), buildDummyImageOp(), buildTextOp('\n')]
const { blocks, doc } = createContext(3, 4, ops)
expect(blocks.length).toBe(3)
const imageBlock = blocks[1]
expect(imageBlock.applyTextTransformToSelection('bold', true, doc).ops).toMatchObject(ops)
})
})
describe('getScopedSelection', () => {
it('should return a selection which is relative to the block coordinates', () => {
const ops = [buildTextOp('Lol'), buildDummyImageOp(), buildTextOp('\n')]
const { blocks, doc } = createContext(3, 4, ops)
expect(blocks.length).toBe(3)
const imageBlock = blocks[1]
expect(imageBlock.getBlockScopedSelection(doc.currentSelection)).toMatchObject({ start: 0, end: 1 })
})
})
describe('getSelectedOps', () => {
it('should return ops which are selected in document', () => {
const ops = [buildTextOp('Lol'), buildDummyImageOp(), buildTextOp('\n')]
const { blocks, doc } = createContext(3, 4, ops)
expect(blocks.length).toBe(3)
const imageBlock = blocks[1]
expect(imageBlock.getSelectedOps(doc)).toMatchObject([buildDummyImageOp()])
})
})
describe('isEntirelySelected', () => {
it('should return true when the current selection exactly matches the block boundaries', () => {
const ops = [buildTextOp('Lol'), buildDummyImageOp(), buildTextOp('\n')]
const { blocks, doc } = createContext(3, 4, ops)
expect(blocks.length).toBe(3)
const imageBlock = blocks[1]
expect(imageBlock.isEntirelySelected(doc)).toBe(true)
})
it('should return false when the current selection partly matches the block boundaries', () => {
const ops = [buildTextOp('Lol'), buildDummyImageOp(), buildTextOp('\n')]
const { blocks, doc } = createContext(4, 4, ops)
expect(blocks.length).toBe(3)
const imageBlock = blocks[1]
expect(imageBlock.isEntirelySelected(doc)).toBe(false)
})
})
describe('insertOrReplaceAtSelection', () => {
it('should replace when selection length is more then 0', () => {
const ops = [buildTextOp('Lol'), buildDummyImageOp(), buildTextOp('\n')]
const { blocks, doc } = createContext(3, 4, ops)
expect(blocks.length).toBe(3)
const imageBlock = blocks[1]
expect(imageBlock.insertOrReplaceAtSelection({ type: 'text', content: 'L' }, doc).ops).toMatchObject([
buildTextOp('LolL\n'),
])
})
})
describe('remove', () => {
it('should remove the whole block when not the first block', () => {
const ops = [buildTextOp('Lol'), buildDummyImageOp(), buildTextOp('\n')]
const { blocks, doc } = createContext(3, 4, ops)
expect(blocks.length).toBe(3)
const imageBlock = blocks[1]
expect(imageBlock.remove(doc).ops).toMatchObject([buildTextOp('Lol\n')])
})
it('should replace the block with a default block when the only block', () => {
const ops = [buildTextOp('L\n')]
const { blocks, doc } = createContext(0, 2, ops)
expect(blocks.length).toBe(1)
const textBlock = blocks[0]
expect(textBlock.remove(doc).ops).toMatchObject([buildTextOp('\n')])
})
})
})
<file_sep>/src/delta/LineWalker.ts
import { GenericOp } from './operations'
import { getLineType, GenericLine } from './lines'
import Delta from 'quill-delta'
import { GenericRichContent, isGenericDelta } from './generic'
import { Selection } from './Selection'
import { Attributes } from '@delta/attributes'
export interface DocumentLine extends GenericLine {
delta: Delta
lineType: Attributes.LineType
// lineTypeIndex: number
}
export class LineWalker {
public readonly ops: GenericOp[]
public constructor(arg: GenericOp[] | GenericRichContent) {
this.ops = isGenericDelta(arg) ? arg.ops : arg
}
public eachLine(predicate: (line: DocumentLine) => void) {
let firstLineCharAt = 0
new Delta(this.ops).eachLine((delta, attributes, index) => {
const beginningOfLineIndex = firstLineCharAt
const endOfLineIndex = beginningOfLineIndex + delta.length()
firstLineCharAt = endOfLineIndex + 1 // newline
const lineType = getLineType(attributes)
const lineRange = Selection.fromBounds(beginningOfLineIndex, endOfLineIndex)
predicate({
lineRange,
delta,
lineType,
index,
})
})
}
public getLines() {
const lines: DocumentLine[] = []
this.eachLine(l => lines.push(l))
return lines
}
}
<file_sep>/src/model/__tests__/document-test.ts
import { Document, applyTextTransformToSelection } from '@model/document'
import { Selection } from '@delta/Selection'
import mergeLeft from 'ramda/es/mergeLeft'
describe('@model/document', () => {
describe('applyTextTransformToSelection', () => {
it('applying text attributes to empty selection should result in cursor attributes matching these attributes', () => {
const document: Document = {
currentSelection: Selection.fromBounds(1),
ops: [{ insert: 'F' }],
lastDiff: [],
selectedTextAttributes: {},
schemaVersion: 1,
}
const diff = applyTextTransformToSelection('weight', 'bold', document)
expect(diff.selectedTextAttributes).toMatchObject({
weight: 'bold',
})
expect(diff.selectedTextAttributes).toMatchObject({
weight: 'bold',
})
})
it('successively applying text attributes to empty selection should result in the merging of those textAttributesAtCursor', () => {
const documentContent1: Document = {
currentSelection: Selection.fromBounds(1),
ops: [{ insert: 'F' }],
lastDiff: [],
selectedTextAttributes: {},
schemaVersion: 1,
}
const diff1 = applyTextTransformToSelection('weight', 'bold', documentContent1)
const documentContent2 = mergeLeft(diff1, documentContent1)
const diff2 = applyTextTransformToSelection('italic', true, documentContent2)
expect(diff2.selectedTextAttributes).toMatchObject({
weight: 'bold',
italic: true,
})
})
it('setting cursor attributes should apply to inserted text', () => {
const documentContent1: Document = {
currentSelection: Selection.fromBounds(1, 2),
ops: [{ insert: 'FP\n' }],
lastDiff: [],
selectedTextAttributes: {},
schemaVersion: 1,
}
const diff = applyTextTransformToSelection('weight', 'bold', documentContent1)
expect(diff).toMatchObject({
ops: [{ insert: 'F' }, { insert: 'P', attributes: { weight: 'bold' } }, { insert: '\n' }],
selectedTextAttributes: { weight: 'bold' },
})
})
it('unsetting cursor attributes should propagate to inserted text', () => {
const documentContent1: Document = {
currentSelection: Selection.fromBounds(1, 2),
ops: [{ insert: 'F' }, { insert: 'P', attributes: { weight: 'bold' } }, { insert: '\n' }],
selectedTextAttributes: { weight: 'bold' },
lastDiff: [],
schemaVersion: 1,
}
const diff = applyTextTransformToSelection('weight', null, documentContent1)
expect(diff).toMatchObject({
ops: [{ insert: 'FP\n' }],
selectedTextAttributes: {
weight: null,
},
})
})
})
})
<file_sep>/src/core/Bridge.ts
import { Attributes } from '@delta/attributes'
import { Endpoint } from './Endpoint'
import { Images } from './Images'
/**
* A set of definitions related to the {@link (Bridge:interface)} interface.
*
* @public
*/
declare namespace Bridge {
/**
* An event which signals the intent to modify the content touched by current selection.
*/
export type ControlEvent = 'APPLY_ATTRIBUTES_TO_SELECTION' | 'INSERT_OR_REPLACE_AT_SELECTION'
/**
* Block content to insert.
*/
export interface ImageElement<Source> {
type: 'image'
description: Images.Description<Source>
}
export interface TextElement {
type: 'text'
content: string
}
/**
* Content to insert.
*/
export type Element<ImageSource> = ImageElement<ImageSource> | TextElement
/**
* Listener to selected text attributes changes.
*/
export type SelectedAttributesChangeListener = (selectedAttributes: Attributes.Map) => void
/**
* Listener to attribute overrides.
*
*/
export type AttributesOverrideListener = (attributeName: string, attributeValue: Attributes.GenericValue) => void
/**
* Listener to line type overrides.
*
*/
export type LineTypeOverrideListener = (lineType: Attributes.LineType) => void
/**
*
* @internal
*/
export type InsertOrReplaceAtSelectionListener<ImageSource> = <D extends {}>(element: Element<ImageSource>) => void
/**
* An object representing an area of events happening by the mean of external controls.
*
* @remarks
*
* This object exposes methods to trigger such events, and react to internal events.
*/
export interface ControlEventDomain<ImageSource> {
/**
* Insert an element at cursor or replace if selection exists.
*
* @internal
*/
insertOrReplaceAtSelection: (element: Element<ImageSource>) => void
/**
* Switch the given attribute's value depending on the current selection.
*
* @param attributeName - The name of the attribute to edit.
* @param attributeValue - The value of the attribute to edit. Assigning `null` clears any former truthy value.
*/
applyTextTransformToSelection: (attributeName: string, attributeValue: Attributes.TextValue) => void
}
/**
* An object representing an area of events happening inside the {@link (Typer:class)}.
*
* @privateRemarks
*
* This object exposes methods to trigger such events, and react to external events.
*
* @internal
*/
export interface SheetEventDomain<ImageSource> {
/**
* Listen to text attributes alterations in selection.
*/
addApplyTextTransformToSelectionListener: (owner: object, listener: AttributesOverrideListener) => void
/**
* Listen to insertions of text or blocks at selection.
*/
addInsertOrReplaceAtSelectionListener: (
owner: object,
listener: InsertOrReplaceAtSelectionListener<ImageSource>,
) => void
/**
* Dereference all listeners registered for this owner.
*/
release: (owner: object) => void
}
}
/**
* An abstraction responsible for event dispatching between the {@link (Typer:class)} and external controls.
*
* @remarks It also provide a uniform access to custom rendering logic.
*
* @internalRemarks
*
* We are only exporting the type to force consumers to use the build function.
*
* @public
*/
interface Bridge<ImageSource> {
/**
* Get {@link (Bridge:namespace).SheetEventDomain | sheetEventDom}.
*
* @internal
*/
getSheetEventDomain: () => Bridge.SheetEventDomain<ImageSource>
/**
* Get this bridge {@link (Bridge:namespace).ControlEventDomain}.
*
* @remarks
*
* The returned object can be used to react from and trigger {@link (Typer:class)} events.
*/
getControlEventDomain: () => Bridge.ControlEventDomain<ImageSource>
/**
* End of the bridge's lifecycle.
*
* @remarks
*
* One would typically call this method during `componentWillUnmout` hook.
*/
release: () => void
}
// eslint-disable-next-line @typescript-eslint/class-name-casing
class _Bridge<ImageSource> implements Bridge<any> {
private outerEndpoint = new Endpoint<Bridge.ControlEvent>()
private controlEventDom: Bridge.ControlEventDomain<ImageSource> = {
insertOrReplaceAtSelection: (element: Bridge.Element<ImageSource>) => {
this.outerEndpoint.emit('INSERT_OR_REPLACE_AT_SELECTION', element)
},
applyTextTransformToSelection: (attributeName: string, attributeValue: Attributes.GenericValue) => {
this.outerEndpoint.emit('APPLY_ATTRIBUTES_TO_SELECTION', attributeName, attributeValue)
},
}
private sheetEventDom: Bridge.SheetEventDomain<ImageSource> = {
addApplyTextTransformToSelectionListener: (owner: object, listener: Bridge.AttributesOverrideListener) => {
this.outerEndpoint.addListener(owner, 'APPLY_ATTRIBUTES_TO_SELECTION', listener)
},
addInsertOrReplaceAtSelectionListener: (
owner: object,
listener: Bridge.InsertOrReplaceAtSelectionListener<ImageSource>,
) => {
this.outerEndpoint.addListener(owner, 'INSERT_OR_REPLACE_AT_SELECTION', listener)
},
release: (owner: object) => {
this.outerEndpoint.release(owner)
},
}
public constructor() {
this.sheetEventDom = Object.freeze(this.sheetEventDom)
this.controlEventDom = Object.freeze(this.controlEventDom)
}
public getSheetEventDomain(): Bridge.SheetEventDomain<ImageSource> {
return this.sheetEventDom
}
public getControlEventDomain(): Bridge.ControlEventDomain<ImageSource> {
return this.controlEventDom
}
/**
* End of the bridge's lifecycle.
*
* @remarks
*
* One would typically call this method during `componentWillUnmout` hook.
*/
public release() {
this.outerEndpoint.removeAllListeners()
}
}
/**
* Build a bridge instance.
*
* @public
*/
function buildBridge<ImageSource = Images.StandardSource>(): Bridge<ImageSource> {
return new _Bridge<ImageSource>()
}
const BridgeStatic = _Bridge
const Bridge = {}
export { Bridge, buildBridge, BridgeStatic }
<file_sep>/src/components/GenericBlockInput/types.ts
import { BlockDescriptor } from '@model/blocks'
import { BlockController } from '@components/BlockController'
import { SelectionShape } from '@delta/Selection'
export interface StandardBlockInputProps {
descriptor: BlockDescriptor
controller: BlockController
isFocused: boolean
overridingScopedSelection: SelectionShape | null
}
/**
* @public
*/
export interface FocusableInput {
/**
* Focus programatically.
*/
focus: () => void
}
<file_sep>/src/delta/lines.ts
import { Selection } from './Selection'
import { Attributes } from './attributes'
/**
* An interface representing a line of text.
*
* @remarks
*
* Given `documentText` the string representing all characters of a document and `line`
* any instance complying with this interface extracted from `documentText`, the following must
* be true:
*
* ```ts
* documentText.substring(line.lineRange.start, line.lineRange.end) === extractTextFromDelta(line.delta)
* ```
* @internal
*/
export interface GenericLine {
index: number
lineRange: Selection
}
export function isLineInSelection(selection: Selection, { lineRange }: GenericLine) {
const { start: beginningOfLineIndex, end: endOfLineIndex } = lineRange
return (
(selection.start >= beginningOfLineIndex && selection.start <= endOfLineIndex) ||
(selection.start <= endOfLineIndex && selection.end >= beginningOfLineIndex)
)
}
export function getLineType(lineAttributes?: Attributes.Map): Attributes.LineType {
return lineAttributes && lineAttributes.$type ? (lineAttributes.$type as Attributes.LineType) : 'normal'
}
<file_sep>/src/components/types.ts
import PropTypes from 'prop-types'
import { Document } from '@model/document'
import { Toolbar } from './Toolbar'
import { Images } from '@core/Images'
export const OpsPropType = PropTypes.arrayOf(PropTypes.object)
const documentShape: Record<keyof Document, any> = {
ops: OpsPropType,
currentSelection: PropTypes.object,
selectedTextAttributes: PropTypes.object,
lastDiff: OpsPropType,
schemaVersion: PropTypes.number,
}
const controlSpecsShape: Record<keyof Toolbar.DocumentControlSpec, any> = {
IconComponent: PropTypes.func.isRequired,
actionType: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.symbol]).isRequired,
iconProps: PropTypes.object,
actionOptions: PropTypes.any,
}
export const DocumentPropType = PropTypes.shape(documentShape)
export const ToolbarLayoutPropType = PropTypes.arrayOf(
PropTypes.oneOfType([PropTypes.symbol, PropTypes.shape(controlSpecsShape)]),
)
const imagesHookShape: Record<keyof Images.Hooks<any>, any> = {
onImageAddedEvent: PropTypes.func,
onImageRemovedEvent: PropTypes.func,
}
export const ImageHooksType = PropTypes.shape(imagesHookShape)
export const TextTransformSpecsType = PropTypes.arrayOf(PropTypes.object)
<file_sep>/src/components/defaults.ts
import { StandardImageComponent } from '@core/Images'
import { defaultTextTransforms } from '@core/Transforms'
export const defaults = {
spacing: 15,
ImageComponent: StandardImageComponent,
textTransformsSpecs: defaultTextTransforms,
underlayColor: 'rgba(30,30,30,0.3)',
imageHooks: {},
}
<file_sep>/src/delta/__tests__/Text-test.ts
import { Text } from '@delta/Text'
import { Selection } from '@delta/Selection'
import zip from 'ramda/es/zip'
describe('@delta/Text', () => {
describe('getSelectionEncompassingLines', () => {
it('should encompass line when the start touches the end of line', () => {
const text = new Text('ABC\nDEF\n')
expect(text.getSelectionEncompassingLines(Selection.fromBounds(3))).toMatchObject({
start: 0,
end: 3,
})
})
it('should encompass line when the start touches the beginning of a line', () => {
const text = new Text('ABC\nDEF\n')
expect(text.getSelectionEncompassingLines(Selection.fromBounds(4))).toMatchObject({
start: 4,
end: 7,
})
})
it('should encompass two lines when start touches the end of a line and end touches the beginning of its sibling', () => {
const text = new Text('ABC\nDEF\n')
expect(text.getSelectionEncompassingLines(Selection.fromBounds(3, 4))).toMatchObject({
start: 0,
end: 7,
})
})
})
describe('select', () => {
it('should return a Text instance wihch is an absolutely positionned substring of `this`', () => {
const text = new Text('BCD', 1)
const subText = text.select(Selection.fromBounds(1, 3))
expect(subText.raw).toBe('BC')
expect(subText.beginningIndex).toBe(1)
})
})
describe('substring', () => {
it('should return a substring which origin is the beginning of index', () => {
const text = new Text('BCD', 1)
const subtext = text.substring(1, 3)
expect(subtext).toBe('BC')
})
})
describe('charAt', () => {
it('should return a character document positionned', () => {
const text = new Text('BCD', 1)
expect(text.charAt(1)).toBe('B')
})
})
describe('getLines', () => {
it('should split lines by newline characters', () => {
const fullText = 'AB\nCD'
const text = new Text(fullText)
expect(text.getLines().length).toBe(2)
})
it('should produce line ranges complying with the substring contract', () => {
const fullText = 'AB\nCD'
const textLines = ['AB', 'CD']
const text = new Text(fullText)
const lines = text.getLines()
for (const [line, textLine] of zip(lines, textLines)) {
expect(fullText.substring(line.lineRange.start, line.lineRange.end)).toBe(textLine)
}
})
it('should produce line ranges for which the character at range.end is a newline except for last line', () => {
const fullText = 'AB\nCD'
const text = new Text(fullText)
const lines = text.getLines()
for (const line of lines.slice(0, 1)) {
expect(fullText.charAt(line.lineRange.end)).toBe('\n')
}
})
})
})
<file_sep>/src/delta/Selection.ts
import invariant from 'invariant'
/**
* A serializable object representing a selection of items in the {@link (Typer:class)}.
*
* @public
*/
export interface SelectionShape {
/**
* **Inclusive** first item index in selection.
*/
readonly start: number
/**
* **Exclusive** last item index in selection.
*/
readonly end: number
}
/**
* A class representing a range of character indexes.
* This range can represent a selection of those characters.
*
*/
export class Selection implements SelectionShape {
public readonly start: number
public readonly end: number
private constructor(start: number, end?: number) {
invariant(end === undefined || end - start >= 0, 'start must be equal or inferior to end')
this.start = start
this.end = typeof end === 'number' ? end : start
}
public static between(one: number, two: number) {
return Selection.fromBounds(Math.min(one, two), Math.max(one, two))
}
public static fromBounds(start: number, end?: number) {
return new Selection(start, end)
}
public static fromShape({ start, end }: SelectionShape) {
return new Selection(start, end)
}
/**
* Informs wether or not an index touches this range.
*
* @remarks
*
* ```ts
* const selection = Selection.fromBounds(1, 3)
* selection.touchesIndex(0) // false
* selection.touchesIndex(1) // true
* selection.touchesIndex(2) // true
* selection.touchesIndex(3) // true
* selection.touchesIndex(4) // false
* ```
*
* @param selectionIndex - The index to test.
*/
public touchesIndex(selectionIndex: number): boolean {
return selectionIndex >= this.start && selectionIndex <= this.end
}
/**
* Informs wether or not a selection has at least one index in
* common with another selection.
*
* @param selection - The selection to which this test should apply.
*/
public touchesSelection(selection: Selection): boolean {
const lowerBound = selection.start
const upperBound = selection.end
return this.touchesIndex(lowerBound) || this.touchesIndex(upperBound)
}
public intersectionLength(selection: Selection) {
const intersection = this.intersection(selection)
return intersection ? intersection.length() : 0
}
/**
*
* @param selection - The selection to which this test should apply.
*/
public intersection(selection: Selection): Selection | null {
const maximumMin = Math.max(this.start, selection.start)
const minimumMax = Math.min(this.end, selection.end)
if (maximumMin < minimumMax) {
return Selection.fromBounds(maximumMin, minimumMax)
}
return null
}
public move(position: number): SelectionShape {
const { start, end } = this
return {
start: start + position,
end: end + position,
}
}
public toShape(): SelectionShape {
const { start, end } = this
return {
start,
end,
}
}
public length(): number {
return this.end - this.start
}
}
<file_sep>/src/delta/diff.ts
import { diffChars } from 'diff'
import Delta from 'quill-delta'
import { Attributes } from './attributes'
function getDeltasFromTextDiff(oldText: string, newText: string, attributes?: Attributes.Map) {
const changes = diffChars(oldText, newText)
let delta = new Delta()
for (const change of changes) {
if (change.added) {
const lines: string[] = change.value.split('\n')
delta = lines.reduce((d, line, i) => {
let next = d.insert(line, attributes)
if (i < lines.length - 1) {
next = next.insert('\n')
}
return next
}, delta)
} else if (change.removed && change.count) {
delta = delta.delete(change.value.length)
} else if (change.count) {
delta = delta.retain(change.value.length)
}
}
return delta
}
export function makeDiffDelta(oldText: string, nuText: string, textAttributes: Attributes.Map): Delta {
return getDeltasFromTextDiff(oldText, nuText, textAttributes)
}
<file_sep>/src/model/Block.ts
import { BlockDescriptor } from './blocks'
import { Document, applyTextTransformToSelection, buildEmptyDocument } from './document'
import { SelectionShape, Selection } from '@delta/Selection'
import Delta from 'quill-delta'
import { ImageKind, GenericOp } from '@delta/operations'
import { DocumentDelta } from '@delta/DocumentDelta'
import { Attributes } from '@delta/attributes'
import { Bridge } from '@core/Bridge'
import { DocumentDeltaAtomicUpdate } from '@delta/DocumentDeltaAtomicUpdate'
function elementToInsertion(
element: Bridge.Element<any>,
document: Document,
): [ImageKind<any> | string, Attributes.Map?] {
if (element.type === 'text') {
return [element.content, document.selectedTextAttributes]
}
const imageOpIns: ImageKind<any> = { kind: 'image', ...element.description }
return [imageOpIns]
}
function getSelectionAfterTransform(diff: Delta, document: Document): SelectionShape {
const nextPosition = diff.transformPosition(document.currentSelection.start)
return {
start: nextPosition,
end: nextPosition,
}
}
// TODO handle cursor move attributes
export class Block {
public readonly descriptor: BlockDescriptor
private blocks: Block[]
public get kind() {
return this.descriptor.kind
}
public constructor(descriptor: BlockDescriptor, blocks: Block[]) {
this.descriptor = descriptor
this.blocks = blocks
}
public isFirst(): boolean {
return this.descriptor.blockIndex === 0
}
public isLast(): boolean {
return this.descriptor.blockIndex === this.descriptor.maxBlockIndex
}
private applyCursorTranslationToDocument(position: number, document: Document): Document {
const nextSelection: SelectionShape = {
start: position,
end: position,
}
return {
...document,
currentSelection: nextSelection,
}
}
private applyDiffToDocument(lastDiff: Delta, document: Document): Document {
const current = new Delta(document.ops)
const nextDelta = current.compose(lastDiff)
const nextOps = nextDelta.ops
const nextSelection = getSelectionAfterTransform(lastDiff, document)
return {
...document,
currentSelection: nextSelection,
ops: nextOps,
lastDiff: lastDiff.ops,
}
}
/**
* Mutate block-scoped ops in the document.
*
* @param blockScopedDiff - The diff delta to apply to current block.
* @param document - The document.
*
* @returns The resulting document ops.
*/
private applyBlockScopedDiff(blockScopedDiff: Delta, document: Document): Document {
return this.applyDiffToDocument(
new Delta().retain(this.descriptor.selectableUnitsOffset).concat(blockScopedDiff),
document,
)
}
private getPreviousBlock(): Block | null {
if (this.isFirst()) {
return null
}
return this.blocks[this.descriptor.blockIndex - 1]
}
private getNextBlock(): Block | null {
if (this.isLast()) {
return null
}
return this.blocks[this.descriptor.blockIndex + 1]
}
public getDocumentSelection(blockScopedSelection: SelectionShape): SelectionShape {
return {
start: blockScopedSelection.start + this.descriptor.selectableUnitsOffset,
end: blockScopedSelection.end + this.descriptor.selectableUnitsOffset,
}
}
public getBlockScopedSelection(documentSelection: SelectionShape): SelectionShape | null {
const start = documentSelection.start - this.descriptor.selectableUnitsOffset
const end = documentSelection.end - this.descriptor.selectableUnitsOffset
if (start < 0 || end > this.descriptor.numOfSelectableUnits) {
return null
}
return {
start,
end,
}
}
public getSelectedOps(document: Document): GenericOp[] {
const delta = new DocumentDelta(document.ops)
return delta.getSelected(Selection.fromShape(document.currentSelection)).ops
}
private shouldFocusOnLeftEdge() {
return this.kind === 'text' || this.descriptor.blockIndex === 0
}
public isFocused({ currentSelection }: Document): boolean {
const { selectableUnitsOffset, numOfSelectableUnits } = this.descriptor
const lowerBoundary = selectableUnitsOffset
const upperBoundary = selectableUnitsOffset + numOfSelectableUnits
const nextBlock = this.getNextBlock()
const isCursor = currentSelection.end - currentSelection.start === 0
const isCursorTouchingRightEdge = isCursor && currentSelection.end === upperBoundary
const isCursorTouchingLeftEdge = isCursor && currentSelection.start === lowerBoundary
if (isCursorTouchingRightEdge) {
return nextBlock == null || !nextBlock.shouldFocusOnLeftEdge()
}
if (isCursorTouchingLeftEdge) {
return this.shouldFocusOnLeftEdge()
}
return (
currentSelection.start >= lowerBoundary &&
currentSelection.start <= upperBoundary &&
currentSelection.end <= upperBoundary
)
}
public isEntirelySelected({ currentSelection: { start, end } }: Document) {
return (
start === this.descriptor.selectableUnitsOffset &&
end === this.descriptor.selectableUnitsOffset + this.descriptor.numOfSelectableUnits
)
}
public updateTextAttributesAtSelection(document: Document): Document {
const docDelta = new DocumentDelta(document.ops)
const deltaAttributes = docDelta.getSelectedTextAttributes(Selection.fromShape(document.currentSelection))
return {
...document,
selectedTextAttributes: deltaAttributes,
}
}
public applyAtomicDeltaUpdate(
{ diff, selectionAfterChange }: DocumentDeltaAtomicUpdate,
document: Document,
): Document {
return {
...this.applyBlockScopedDiff(diff, document),
currentSelection: this.getDocumentSelection(selectionAfterChange),
}
}
public applyTextTransformToSelection(
attributeName: string,
attributeValue: Attributes.GenericValue,
document: Document,
): Document {
if (this.kind !== 'text') {
return document
}
return {
...document,
...applyTextTransformToSelection(attributeName, attributeValue, document),
}
}
/**
* Insert element at selection.
*
* @remarks If selection is of length 1+, replace the selectable units encompassed by selection.
*
* @param element - The element to be inserted.
* @param document - The document.
*
* @returns The resulting document.
*/
public insertOrReplaceAtSelection(element: Bridge.Element<any>, document: Document): Document {
const deletionLength = document.currentSelection.end - document.currentSelection.start
const diff = new Delta()
.retain(document.currentSelection.start)
.delete(deletionLength)
.insert(...elementToInsertion(element, document))
return this.applyDiffToDocument(diff, document)
}
/**
* Remove this block. If this block is the first block, replace with default text block.
*
* @param document - The document to which it should apply.
*/
public remove(document: Document): Document {
if (this.isFirst() && this.isLast()) {
return buildEmptyDocument()
}
const diff = new Delta().retain(this.descriptor.selectableUnitsOffset).delete(this.descriptor.numOfSelectableUnits)
return this.applyDiffToDocument(diff, document)
}
public updateSelection(blockScopedSelection: SelectionShape, document: Document): Document {
const nextSelection = {
start: this.descriptor.selectableUnitsOffset + blockScopedSelection.start,
end: this.descriptor.selectableUnitsOffset + blockScopedSelection.end,
}
return {
...document,
currentSelection: nextSelection,
}
}
/**
* Select the whole block.
*
* @param document - The document to which the mutation should apply.
*
* @returns The resulting document.
*/
public select(document: Document): Document {
const nextSelection = {
start: this.descriptor.selectableUnitsOffset,
end: this.descriptor.selectableUnitsOffset + this.descriptor.numOfSelectableUnits,
}
return {
...document,
currentSelection: nextSelection,
}
}
/**
* Remove one selectable unit before cursor.
*
* @param document The document to which the mutation should apply.
*
* @returns The resulting document.
*/
public removeOneBefore(document: Document): Document {
if (this.isFirst()) {
return document
}
const diff = new Delta().retain(this.descriptor.selectableUnitsOffset - 1).delete(1)
const prevBlock = this.getPreviousBlock() as Block
if (prevBlock.kind === 'image') {
return prevBlock.select(document)
}
return this.applyDiffToDocument(diff, document)
}
public moveBefore(document: Document): Document {
if (this.isFirst()) {
return document
}
const positionBeforeBlock = this.descriptor.selectableUnitsOffset - 1
return this.applyCursorTranslationToDocument(positionBeforeBlock, document)
}
public moveAfter(document: Document): Document {
if (this.isLast()) {
return document
}
const positionAfterBlock = this.descriptor.selectableUnitsOffset + this.descriptor.numOfSelectableUnits
return this.applyCursorTranslationToDocument(positionAfterBlock, document)
}
}
<file_sep>/src/components/BlockController.ts
import { Block } from '@model/Block'
import { Document } from '@model/document'
import { SelectionShape } from '@delta/Selection'
import { DocumentDeltaAtomicUpdate } from '@delta/DocumentDeltaAtomicUpdate'
import { ImageOp } from '@delta/operations'
import { Images } from '@core/Images'
export interface DocumentProvider {
getDocument: () => Document
updateDocument: (document: Document) => void
getImageHooks: () => Images.Hooks<any>
overrideSelection: (overridingSelection: SelectionShape) => void
}
export class BlockController {
private block: Block
private provider: DocumentProvider
public constructor(block: Block, provider: DocumentProvider) {
this.block = block
this.provider = provider
}
private getDocument(): Document {
return this.provider.getDocument()
}
private updateDocumentContent(document: Document) {
this.provider.updateDocument(document)
}
private onBlockDeletion() {
if (this.block.kind === 'image') {
const [imageOp] = this.block.getSelectedOps(this.getDocument()) as [ImageOp<any>]
const hooks = this.provider.getImageHooks()
hooks.onImageRemovedEvent && hooks.onImageRemovedEvent(imageOp.insert)
}
}
public updateSelectionInBlock(blockScopedSelection: SelectionShape, override?: boolean) {
const nextDocument = this.block.updateSelection(blockScopedSelection, this.getDocument())
this.updateDocumentContent(nextDocument)
if (override) {
this.provider.overrideSelection(nextDocument.currentSelection)
}
}
public applyAtomicDeltaUpdateInBlock(documentDeltaUpdate: DocumentDeltaAtomicUpdate) {
this.updateDocumentContent(this.block.applyAtomicDeltaUpdate(documentDeltaUpdate, this.getDocument()))
}
public selectBlock() {
this.updateDocumentContent(this.block.select(this.getDocument()))
}
public removeCurrentBlock() {
this.updateDocumentContent(this.block.remove(this.getDocument()))
this.onBlockDeletion()
}
public insertOrReplaceTextAtSelection(character: string) {
const actionWillDeleteBlock = this.block.isEntirelySelected(this.getDocument())
this.updateDocumentContent(
this.block.insertOrReplaceAtSelection({ type: 'text', content: character }, this.getDocument()),
)
actionWillDeleteBlock && this.onBlockDeletion()
}
public removeOneBeforeBlock() {
this.updateDocumentContent(this.block.removeOneBefore(this.getDocument()))
}
public moveAfterBlock() {
this.updateDocumentContent(this.block.moveAfter(this.getDocument()))
}
public moveBeforeBlock() {
const nextDoc = this.block.moveBefore(this.getDocument())
this.updateDocumentContent(nextDoc)
}
}
<file_sep>/src/delta/__tests__/DocumentDelta-test.ts
// tslint:disable: no-string-literal
import { Attributes } from '@delta/attributes'
import { Selection } from '@delta/Selection'
import { mockDeltaChangeContext, mockSelection } from '@test/delta'
import { GenericRichContent } from '@delta/generic'
import { isLineInSelection } from '@delta/lines'
import { mockDocumentDelta } from '@test/document'
import { LineWalker } from '@delta/LineWalker'
fdescribe('@delta/DocumentDelta', () => {
// The idea is to expose operations on different kind of blocks
// Giving support for text blocks, ordered and unordered lists, headings
describe('eachLine', () => {
it('should handle lines', () => {
const textDelta = mockDocumentDelta([
{ insert: 'eheh' },
{ insert: '\n', attributes: { $type: 'misc' } },
{ insert: 'ahah' },
{ insert: '\n', attributes: { $type: 'rand' } },
{ insert: 'ohoh\n\n' },
])
const lines: GenericRichContent[] = []
const attributes: Attributes.Map[] = []
textDelta['delta'].eachLine((l, a) => {
attributes.push(a)
lines.push(l)
})
expect(lines).toEqual([
{ ops: [{ insert: 'eheh' }] },
{ ops: [{ insert: 'ahah' }] },
{ ops: [{ insert: 'ohoh' }] },
{ ops: [] },
])
expect(attributes).toEqual([{ $type: 'misc' }, { $type: 'rand' }, {}, {}])
})
})
describe('applyTextDiff', () => {
it('should reproduce a delete operation when one character was deleted', () => {
const newText = 'Hello worl\n'
const originalDelta = mockDocumentDelta([{ insert: 'Hello world\n' }])
const changeContext = mockDeltaChangeContext(11, 10)
const diff = originalDelta.applyTextDiff(newText, changeContext)
const { delta } = diff
expect(delta.ops).toEqual([{ insert: newText }])
})
it('should reproduce a delete operation when two or more characters were deleted', () => {
const newText = 'Hello \n'
const originalDelta = mockDocumentDelta([{ insert: 'Hello world\n' }])
const changeContext = mockDeltaChangeContext(6, 6, 11)
const { delta } = originalDelta.applyTextDiff(newText, changeContext)
expect(delta.ops).toEqual([{ insert: newText }])
})
it('should reproduce a delete operation when multiple lines were deleted', () => {
const newText = 'A\nB\n'
const originalDelta = mockDocumentDelta([{ insert: 'A\nBC\nD\n' }])
const changeContext = mockDeltaChangeContext(3, 3, 6)
const { delta } = originalDelta.applyTextDiff(newText, changeContext)
expect(delta.ops).toEqual([{ insert: 'A\nB\n' }])
})
it('should reproduce an insert operation when one character was inserted', () => {
const newText = 'Hello world\n'
const originalDelta = mockDocumentDelta([{ insert: 'Hello worl\n' }])
const changeContext = mockDeltaChangeContext(10, 11)
const { delta } = originalDelta.applyTextDiff(newText, changeContext)
expect(delta.ops[0].insert).toBe(newText)
})
it('should reproduce an insert operation when two or more characters were inserted', () => {
const newText = 'Hello world\n'
const originalDelta = mockDocumentDelta([{ insert: 'Hello \n' }])
const changeContext = mockDeltaChangeContext(6, 11)
const { delta } = originalDelta.applyTextDiff(newText, changeContext)
expect(delta.ops).toEqual([{ insert: newText }])
})
it('should reproduce an insert operation when multiple lines were inserted', () => {
const newText = 'Hello world\nFoo\nBar\n'
const originalDelta = mockDocumentDelta([{ insert: 'Hello world\n' }])
const changeContext = mockDeltaChangeContext(11, 19)
const { delta } = originalDelta.applyTextDiff(newText, changeContext)
expect(delta.ops).toEqual([{ insert: newText }])
})
it('should reproduce a replace operation when one character was replaced', () => {
const newText = 'Hello worlq\n'
const originalDelta = mockDocumentDelta([{ insert: 'Hello world\n' }])
const changeContext = mockDeltaChangeContext(10, 11, 11)
const { delta } = originalDelta.applyTextDiff(newText, changeContext)
expect(delta.ops).toEqual([{ insert: newText }])
})
it('should reproduce a replace operation when two ore more characters were replaced', () => {
const newText = 'Hello cat\n'
const originalDelta = mockDocumentDelta([{ insert: 'Hello world\n' }])
const changeContext = mockDeltaChangeContext(6, 9, 11)
const { delta } = originalDelta.applyTextDiff(newText, changeContext)
expect(delta.ops).toEqual([{ insert: newText }])
})
it("should reproduce a replace operation when cursor didn't move, but the text was replaced on the same line as cursor", () => {
// This would happen with keyboard suggestions
const newText = 'Hello cat\n'
const originalDelta = mockDocumentDelta([{ insert: 'Hello pet\n' }])
const changeContext = mockDeltaChangeContext(9, 9)
const { delta } = originalDelta.applyTextDiff(newText, changeContext)
expect(delta.ops).toEqual([{ insert: newText }])
})
it('should reproduce a replace operation when cursor moved, but the change occurred out of cursor boundaries, in the same line', () => {
// This would happen with keyboard suggestions
const newText = 'Hello petty\n'
const originalDelta = mockDocumentDelta([{ insert: 'Hello cat\n' }])
const changeContext = mockDeltaChangeContext(9, 11)
const { delta } = originalDelta.applyTextDiff(newText, changeContext)
expect(delta.ops).toEqual([{ insert: newText }])
})
it('should not append a newline character to delta after inserting a character at the begening of a newline', () => {
const newText = 'Hello world\nH\n'
const changeContext = mockDeltaChangeContext(11, 12)
const originalDelta = mockDocumentDelta([{ insert: 'Hello world\n' }])
const { delta } = originalDelta.applyTextDiff(newText, changeContext)
expect(delta.ops).toEqual([{ insert: 'Hello world\nH\n' }])
})
it('should keep text attributes when removing a line', () => {
const originalDelta = mockDocumentDelta([
{ insert: '\n' },
{ insert: 'L', attributes: { bold: true } },
{ insert: '\n' },
])
const newText = 'L\n'
const changeContext = mockDeltaChangeContext(1, 0)
const { delta, diff } = originalDelta.applyTextDiff(newText, changeContext)
expect(diff.ops).toEqual([{ delete: 1 }, { retain: 2 }])
expect(delta.ops).toEqual([{ insert: 'L', attributes: { bold: true } }, { insert: '\n' }])
})
it('should keep text attributes when inserting a line', () => {
const originalDelta = mockDocumentDelta([
{ insert: '\n' },
{ insert: 'L', attributes: { bold: true } },
{ insert: '\n' },
])
const newText = '\nL\n\n'
const changeContext = mockDeltaChangeContext(2, 3)
const { delta, diff } = originalDelta.applyTextDiff(newText, changeContext)
expect(diff.ops).toEqual([{ retain: 2 }, { insert: '\n' }, { retain: 1 }])
expect(delta.ops).toEqual([{ insert: '\n' }, { insert: 'L', attributes: { bold: true } }, { insert: '\n\n' }])
})
it('it should handle insertion of a newline character from the middle of a line', () => {
const newText = 'Hello \nworld\n'
const changeContext = mockDeltaChangeContext(6, 7)
const originalDelta = mockDocumentDelta([{ insert: 'Hello world\n' }])
const { delta } = originalDelta.applyTextDiff(newText, changeContext)
expect(delta.ops).toEqual([{ insert: 'Hello \nworld\n' }])
})
it('should not remove newline character when reaching the beginning of a line', () => {
const changeContext = mockDeltaChangeContext(3, 2)
const newText = 'A\n\nC\n'
const originalDelta = mockDocumentDelta([{ insert: 'A\nB\nC\n' }])
const { delta } = originalDelta.applyTextDiff(newText, changeContext)
expect(delta.ops).toEqual([{ insert: 'A\n\nC\n' }])
})
// These four tests are skipped because we removed line-wise logic, which couldn't properly
// handle some edge-cases.
xit('should keep the line type at selection start when reproducing a multiline replace operation', () => {
const newText = 'A\n'
const originalDelta = mockDocumentDelta([
{ insert: 'A' },
{ insert: '\n', attributes: { $type: 'custom' } },
{ insert: 'B\nC\n' },
])
const changeContext = mockDeltaChangeContext(1, 1, 5)
const { delta } = originalDelta.applyTextDiff(newText, changeContext)
expect(delta.ops).toEqual([{ insert: 'A' }, { insert: '\n', attributes: { $type: 'custom' } }])
})
xit('should retain newline character after inserting a newline character to keep the current linetype, if that line type is not propagable', () => {
const newText = 'Hello world\n'
const changeContext = mockDeltaChangeContext(11, 12)
const originalDelta = mockDocumentDelta([
{ insert: 'Hello world' },
{ insert: '\n', attributes: { $type: 'misc' } },
])
const { delta } = originalDelta.applyTextDiff(newText, changeContext)
expect(delta.ops).toEqual([
{ insert: 'Hello world' },
{ insert: '\n', attributes: { $type: 'misc' } },
{ insert: '\n' },
])
})
xit('should not propagate the previous line type to the newline after replacing a newline character, if that line type is not propagable', () => {
const newText = 'Hello worl\n'
const changeContext = mockDeltaChangeContext(10, 11, 11)
const originalDelta = mockDocumentDelta([
{ insert: 'Hello world' },
{ insert: '\n', attributes: { $type: 'misc' } },
])
const { delta } = originalDelta.applyTextDiff(newText, changeContext)
expect(delta.ops).toEqual([
{ insert: 'Hello worl' },
{ insert: '\n', attributes: { $type: 'misc' } },
{ insert: '\n' },
])
})
xit('should retain first newline character and remove next newline when removing newline', () => {
const changeContext = mockDeltaChangeContext(2, 1)
const newText = 'A\nC\n'
const originalDelta = mockDocumentDelta([
{ insert: 'A' },
{ insert: '\n', attributes: { $type: 'custom' } },
{ insert: '\nC\n' },
])
const { delta } = originalDelta.applyTextDiff(newText, changeContext)
expect(delta.ops).toEqual([{ insert: 'A' }, { insert: '\n', attributes: { $type: 'custom' } }, { insert: 'C\n' }])
})
})
describe('applyTextTransformToSelection', () => {
it('should clear attribute if its name and value are present in each operation of the selection', () => {
const delta = mockDocumentDelta([
{ insert: 'prefix', attributes: { untouched: true } },
{ insert: 'test', attributes: { textDecoration: 'underline' } },
{ insert: 'test', attributes: { textDecoration: 'underline', bold: true } },
{ insert: 'suffix', attributes: { untouched: true } },
])
const selection = Selection.fromShape({
start: 6,
end: 14,
})
const { delta: finalDelta } = delta.applyTextTransformToSelection(selection, 'textDecoration', 'underline')
expect(finalDelta.ops).toEqual([
{ insert: 'prefix', attributes: { untouched: true } },
{ insert: 'test' },
{ insert: 'test', attributes: { bold: true } },
{ insert: 'suffix', attributes: { untouched: true } },
])
})
it('should replace attribute if its name is present in each operation but its value is at least different once', () => {
const delta = mockDocumentDelta([
{ insert: 'prefix', attributes: { untouched: true } },
{ insert: 'test', attributes: { textDecoration: 'underline' } },
{ insert: 'test', attributes: { textDecoration: 'strikethrough' } },
{ insert: 'suffix', attributes: { untouched: true } },
])
const selection: Selection = Selection.fromShape({
start: 6,
end: 14,
})
const { delta: finalDelta } = delta.applyTextTransformToSelection(selection, 'textDecoration', 'underline')
expect(finalDelta.ops).toEqual([
{ insert: 'prefix', attributes: { untouched: true } },
{ insert: 'testtest', attributes: { textDecoration: 'underline' } },
{ insert: 'suffix', attributes: { untouched: true } },
])
})
it('should assign attribute if it is absent at least in one operation of the selection', () => {
const delta = mockDocumentDelta([
{ insert: 'prefix', attributes: { untouched: true } },
{ insert: 'test', attributes: { textDecoration: 'underline' } },
{ insert: 'test', attributes: {} },
{ insert: 'suffix', attributes: { untouched: true } },
])
const selection: Selection = Selection.fromShape({
start: 6,
end: 14,
})
const { delta: finalDelta } = delta.applyTextTransformToSelection(selection, 'textDecoration', 'underline')
expect(finalDelta.ops).toEqual([
{ insert: 'prefix', attributes: { untouched: true } },
{ insert: 'testtest', attributes: { textDecoration: 'underline' } },
{ insert: 'suffix', attributes: { untouched: true } },
])
})
it('should assign attribute if it is absent at least in one operation of the selection and override other values', () => {
const delta = mockDocumentDelta([
{ insert: 'prefix', attributes: { untouched: true } },
{ insert: 'test', attributes: { textDecoration: 'underline' } },
{ insert: 'test', attributes: { textDecoration: 'strikethrough' } },
{ insert: 'test', attributes: {} },
{ insert: 'suffix', attributes: { untouched: true } },
])
const selection: Selection = Selection.fromShape({
start: 6,
end: 18,
})
const { delta: finalDelta } = delta.applyTextTransformToSelection(selection, 'textDecoration', 'underline')
expect(finalDelta.ops).toEqual([
{ insert: 'prefix', attributes: { untouched: true } },
{ insert: 'testtesttest', attributes: { textDecoration: 'underline' } },
{ insert: 'suffix', attributes: { untouched: true } },
])
})
})
describe('getSelectedTextAttributes', () => {
it('should ignore attributes which are not present throughout the selection', () => {
const delta = mockDocumentDelta([
{ insert: 'prefix', attributes: { untouched: true } },
{ insert: 'test', attributes: { bold: true } },
{ insert: 'test', attributes: { italic: true } },
{ insert: 'suffix', attributes: { untouched: true } },
])
const selection: Selection = Selection.fromShape({
start: 6,
end: 14,
})
const attributes = delta.getSelectedTextAttributes(selection)
expect(attributes).toEqual({})
})
it('should ignore nil attributes', () => {
const delta = mockDocumentDelta([
{ insert: 'prefix', attributes: { untouched: true } },
{ insert: 'test', attributes: { bold: null } },
{ insert: 'test', attributes: { bold: undefined } },
{ insert: 'suffix', attributes: { untouched: true } },
])
const selection: Selection = Selection.fromShape({
start: 6,
end: 14,
})
const attributes = delta.getSelectedTextAttributes(selection)
expect(attributes).toEqual({})
})
it('should ignore empty attributes', () => {
const delta = mockDocumentDelta([
{ insert: 'prefix', attributes: { untouched: true } },
{ insert: 'test', attributes: { bold: true } },
{ insert: 'test' },
{ insert: 'suffix', attributes: { untouched: true } },
])
const selection: Selection = Selection.fromShape({
start: 6,
end: 14,
})
const attributes = delta.getSelectedTextAttributes(selection)
expect(attributes).toEqual({})
})
it('should discard values when a conflict occurs', () => {
const delta = mockDocumentDelta([
{ insert: 'prefix', attributes: { untouched: true } },
{ insert: 'test', attributes: { textDecoration: 'underline' } },
{ insert: 'test', attributes: { textDecoration: 'strike' } },
{ insert: 'suffix', attributes: { untouched: true } },
])
const selection: Selection = Selection.fromShape({
start: 6,
end: 14,
})
const attributes = delta.getSelectedTextAttributes(selection)
expect(attributes).toEqual({})
})
it('should keep values present throughout the selection', () => {
const delta = mockDocumentDelta([
{ insert: 'prefix', attributes: { untouched: true } },
{ insert: 'test', attributes: { textDecoration: 'strike', bold: true } },
{ insert: 'test', attributes: { textDecoration: 'strike' } },
{ insert: 'suffix', attributes: { untouched: true } },
])
const selection: Selection = Selection.fromShape({
start: 6,
end: 14,
})
const attributes = delta.getSelectedTextAttributes(selection)
expect(attributes).toEqual({ textDecoration: 'strike' })
})
it('should skip newlines', () => {
const delta = mockDocumentDelta([
{ insert: 'prefix\n', attributes: { untouched: true } },
{ insert: 'test\ntest\n', attributes: { bold: true } },
{ insert: 'suffix', attributes: { untouched: true } },
])
const selection: Selection = Selection.fromShape({
start: 7,
end: 17,
})
const attributes = delta.getSelectedTextAttributes(selection)
expect(attributes).toEqual({ bold: true })
})
})
describe('getSelectionEncompassingLines', () => {
it('should encompass characters left to starting cursor', () => {
const delta = mockDocumentDelta([{ insert: 'Hello\n' }])
expect(delta['getSelectionEncompassingLines'](mockSelection(2, 6))).toEqual(mockSelection(0, 6))
})
it('should encompass characters right to ending cursor', () => {
const delta = mockDocumentDelta([{ insert: 'Hello\n' }])
expect(delta['getSelectionEncompassingLines'](mockSelection(0, 4))).toEqual(mockSelection(0, 6))
})
it('should not encompass lines outside cursor scope', () => {
const delta = mockDocumentDelta([{ insert: 'All right\n' }, { insert: 'Hello\n' }, { insert: 'Felling good\n' }])
expect(delta['getSelectionEncompassingLines'](mockSelection(10, 14))).toEqual(mockSelection(10, 16))
})
})
describe('getLineTypeInSelection', () => {
it('should return "normal" when all lines attributes are empty', () => {
const delta = mockDocumentDelta([
{ insert: 'hi\n' },
{ insert: 'feeling great', attributes: { bold: true } },
{ insert: '\n' },
])
expect(delta.getLineTypeInSelection(mockSelection(0, 18))).toEqual('normal')
})
it('should return "normal" when at least one line attributes is empty', () => {
const delta = mockDocumentDelta([
{ insert: 'hi\n' },
{ insert: 'feeling great', attributes: { bold: true } },
{ insert: '\n', attributes: { $type: 'misc' } },
{ insert: 'Felling good' },
{ insert: '\n', attributes: { $type: 'rand' } },
])
expect(delta.getLineTypeInSelection(mockSelection(0, 31))).toEqual('normal')
})
it('should return "misc" when all line types are "misc"', () => {
const delta = mockDocumentDelta([
{ insert: 'hi' },
{ insert: '\n', attributes: { $type: 'misc' } },
{ insert: 'feeling great', attributes: { bold: true } },
{ insert: '\n', attributes: { $type: 'misc' } },
{ insert: 'Felling good' },
{ insert: '\n', attributes: { $type: 'misc' } },
])
expect(delta.getLineTypeInSelection(mockSelection(0, 31))).toEqual('misc')
})
it('should return "normal" when all line types are different', () => {
const delta = mockDocumentDelta([
{ insert: 'hi' },
{ insert: '\n', attributes: { $type: 'misc' } },
{ insert: 'feeling great', attributes: { bold: true } },
{ insert: '\n', attributes: { $type: 'rand' } },
{ insert: 'Felling good' },
{ insert: '\n', attributes: { $type: 'misc' } },
])
expect(delta.getLineTypeInSelection(mockSelection(0, 31))).toEqual('normal')
})
it('should take into account lines which are not fully selected', () => {
const delta = mockDocumentDelta([{ insert: 'hi' }, { insert: '\n', attributes: { $type: 'misc' } }])
expect(delta.getLineTypeInSelection(mockSelection(0, 1))).toEqual('misc')
})
})
describe('isLineInSelection', () => {
const document = mockDocumentDelta([{ insert: 'A\nBC\nD\n' }])
const lines = new LineWalker(document.ops).getLines()
const firstLine = lines[0]
const secondLine = lines[1]
it('should match when the start selection index equals the begening of line index', () => {
expect(isLineInSelection(mockSelection(0, 1), firstLine)).toBe(true)
})
it('should match when the end selection index equals the end of line index', () => {
expect(isLineInSelection(mockSelection(1, 1), firstLine)).toBe(true)
expect(isLineInSelection(mockSelection(4, 4), secondLine)).toBe(true)
})
it('should match when the start selection index is strictly inferior to the begening of line index and the end selection index is equal or superior to the begening of line index', () => {
expect(isLineInSelection(mockSelection(1, 4), secondLine)).toBe(true)
expect(isLineInSelection(mockSelection(1, 2), secondLine)).toBe(true)
})
it('should not match when the start selection index is gthen the end of line index', () => {
expect(isLineInSelection(mockSelection(2, 2), firstLine)).toBe(false)
expect(isLineInSelection(mockSelection(5, 5), secondLine)).toBe(false)
})
})
})
<file_sep>/src/index.ts
/**
*
* Typeskill, the Operational-Transform Based (React) Native Rich Text library.
*
* @remarks
*
* **Introduction**
*
* The library exposes:
*
* - The {@link (Typer:class)} component, a support for editing {@link (Document:type)};
* - The {@link (Print:type)} component, a display for {@link (Document:type)};
* - The {@link (Toolbar:class)} component, which permits text transforms on current selection.
*
* **Controlled components**
*
* {@link (Typer:class)} and {@link (Print:type)} components are [controlled components](https://reactjs.org/docs/forms.html#controlled-components).
* You need to pass them a {@link Document | `document`} prop which you can initialize with {@link buildEmptyDocument}.
*
* **Triggering actions from external controls**
*
* A {@link (Bridge:interface)} instance must be shared between a {@link (Typer:class)} and any control component such as {@link (Toolbar:class)}.
* The {@link (Bridge:interface)} instance can be instantiated with {@link buildBridge}.
* Actions can be triggered with the help of the object returned by {@link (Bridge:interface).getControlEventDomain}.
*
* Such actions include:
*
* - inserting media content;
* - (un)setting text attributes (bold, italic).
*
* Selection change events can also be listened to with `add...Listener` methods.
* {@link (Bridge:interface).release} must be call from the component holding a reference to the {@link (Bridge:interface)} instance,
* during `componentWillUnmount` hook.
*
* @packageDocumentation
*/
/* Exported values */
export { Typer } from '@components/Typer'
export { Print } from '@components/Print'
export { Bridge, buildBridge } from '@core/Bridge'
export { Toolbar, DocumentControlAction, CONTROL_SEPARATOR, buildVectorIconControlSpec } from '@components/Toolbar'
export { useBridge } from '@hooks/use-bridge'
export { useDocument } from '@hooks/use-document'
export { Transforms, defaultTextTransforms } from '@core/Transforms'
/* Exported types and interfaces */
export { GenericControlAction } from '@components/Toolbar'
export { Attributes } from '@delta/attributes'
export { GenericRichContent } from '@delta/generic'
export { GenericOp, TextOp, ImageOp, BlockOp, ImageKind } from '@delta/operations'
export { Document, buildEmptyDocument, cloneDocument } from '@model/document'
export { SelectionShape } from '@delta/Selection'
export { Images } from '@core/Images'
export { DocumentRendererProps } from '@components/DocumentRenderer'
export { FocusableInput } from '@components/GenericBlockInput'
<file_sep>/src/model/document.ts
import { Attributes } from '@delta/attributes'
import { SelectionShape, Selection } from '@delta/Selection'
import { GenericOp } from '@delta/operations'
import clone from 'ramda/es/clone'
import { DocumentDelta } from '@delta/DocumentDelta'
import mergeLeft from 'ramda/es/mergeLeft'
/**
* A serializable object representing rich content.
*
* @public
*/
export interface Document {
/**
* A list of operations as per deltajs definition.
*/
readonly ops: GenericOp[]
/**
* A contiguous range of selectable items.
*/
readonly currentSelection: SelectionShape
/**
* The attributes encompassed by {@link Document.currentSelection} or the attributes at cursor.
* `null` values represent attributes to be removed.
*/
readonly selectedTextAttributes: Attributes.Map
/**
* The diff ops which were used to produce current ops by combining previous ops.
*/
readonly lastDiff: GenericOp[]
/**
* The document shape versionning.
*
* @remarks This attribute might only change between major releases, and is intended to very rarely change.
* It is also guaranteed that if there were any, the library would offer tools to handle schema migrations.
*
*/
readonly schemaVersion: number
}
/**
* An async callback aimed at updating the document.
*
* @param nextDocument - The next document.
*
* @public
*/
export type DocumentUpdater = (nextDocument: Document) => Promise<void>
/**
* Build an empty document.
*
* @public
*/
export function buildEmptyDocument(): Document {
return {
currentSelection: { start: 0, end: 0 },
ops: [{ insert: '\n' }],
selectedTextAttributes: {},
lastDiff: [],
schemaVersion: 1,
}
}
/**
* Clone a peace of {@link Document | document}.
*
* @param content - The content to clone
*
* @public
*/
export function cloneDocument(content: Document): Document {
return {
ops: clone(content.ops),
currentSelection: content.currentSelection,
selectedTextAttributes: content.selectedTextAttributes,
lastDiff: content.lastDiff,
schemaVersion: content.schemaVersion,
}
}
export function applyTextTransformToSelection(
attributeName: string,
attributeValue: Attributes.GenericValue,
document: Document,
): Pick<Document, 'ops' | 'selectedTextAttributes' | 'lastDiff'> {
const { currentSelection, ops, selectedTextAttributes } = document
const delta = new DocumentDelta(ops)
const selection = Selection.fromShape(currentSelection)
// Apply transforms to selection range
const userAttributes = { [attributeName]: attributeValue }
const atomicUpdate = delta.applyTextTransformToSelection(selection, attributeName, attributeValue)
const nextSelectedAttributes = mergeLeft(userAttributes, selectedTextAttributes)
return {
selectedTextAttributes: nextSelectedAttributes,
ops: atomicUpdate.delta.ops,
lastDiff: atomicUpdate.diff.ops,
}
}
<file_sep>/src/test/document.ts
import { DocumentDelta } from '@delta/DocumentDelta'
import { GenericOp, buildImageOp, ImageOp } from '@delta/operations'
export function mockDocumentDelta(ops?: GenericOp[]): DocumentDelta {
return new DocumentDelta(ops)
}
export function buildDummyImageOp(uri = 'A'): ImageOp<any> {
return buildImageOp({ height: 10, width: 10, source: { uri } })
}
<file_sep>/CHANGELOG.md
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
## [1.0.0](https://github.com/typeskill/typeskill/compare/v0.11.0-alpha.0...v1.0.0) (2020-02-19)
### Bug Fixes
* **package:** update ramda to version 0.27.0 ([b80ef9a](https://github.com/typeskill/typeskill/commit/b80ef9a))
* unexhaustive hook dependency ([c1ae14d](https://github.com/typeskill/typeskill/commit/c1ae14d))
### Features
* add useDocument and useBridge hooks ([0e96b53](https://github.com/typeskill/typeskill/commit/0e96b53))
## [0.11.0-alpha.0](https://github.com/typeskill/typeskill/compare/v0.10.0-beta.19...v0.11.0-alpha.0) (2019-10-04)
### ⚠ BREAKING CHANGES
* removed `disableMultipleAttributeEdits` Typer prop.
Since this behavior has been proven default on iOS, Typeskill will try
to enforce the same one on Android by default. To make the API more
explicit, it has been found best to rename the prop to narrow the scope
to Android.
### Bug Fixes
* add missing hook dependency ([fa84b1c](https://github.com/typeskill/typeskill/commit/fa84b1c))
* overriding selection iOS doesn't work ([8f38a0b](https://github.com/typeskill/typeskill/commit/8f38a0b))
### Features
* add `androidDisableMultipleAttributeEdits` Typer prop ([348eecb](https://github.com/typeskill/typeskill/commit/348eecb))
<file_sep>/src/delta/__tests__/Selection-test.ts
// tslint:disable:no-unused-expression
import { Selection } from '@delta/Selection'
describe('@delta/Selection', () => {
describe('constructor', () => {
it('should throw when start lower then end', () => {
expect(() => {
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
new Selection(0, -1)
}).toThrow()
})
})
describe('touchesIndex', () => {
it('should be true with index strictly equals selection end', () => {
const selection = Selection.fromBounds(0, 1)
expect(selection.touchesIndex(1)).toBe(true)
})
it("should be false when index doesn't touch the edge of selection", () => {
const selection = Selection.fromBounds(0, 1)
expect(selection.touchesIndex(2)).toBe(false)
})
})
describe('touchesSelection', () => {
it('should be true when param selection touches the upper edge of selection', () => {
const selection = Selection.fromBounds(0, 1)
expect(selection.touchesSelection(Selection.fromBounds(1, 1))).toBe(true)
})
it("should be false when param selection doesn't touch the edge of selection", () => {
const selection = Selection.fromBounds(0, 1)
expect(selection.touchesSelection(Selection.fromBounds(2, 2))).toBe(false)
})
})
describe('intersection', () => {
it('should return a selection of length 1 when selection 2 has one cell overlapping over selection 1', () => {
const selection1 = Selection.fromBounds(0, 2)
const selection2 = Selection.fromBounds(1, 3)
expect(selection1.intersection(selection2)).toMatchObject({
start: 1,
end: 2,
})
})
it('should return null when selection 2 start equals selection 1 end', () => {
const selection1 = Selection.fromBounds(0, 2)
const selection2 = Selection.fromBounds(2, 3)
expect(selection1.intersection(selection2)).toBeNull()
})
it('should return null when selection 2 start is superior to selection 1 end', () => {
const selection1 = Selection.fromBounds(0, 2)
const selection2 = Selection.fromBounds(3, 4)
expect(selection1.intersection(selection2)).toBeNull()
})
})
})
<file_sep>/src/components/GenericBlockView/types.d.ts
import { BlockDescriptor } from '@model/blocks'
export interface StandardBlockViewProps {
descriptor: BlockDescriptor
}
<file_sep>/src/delta/generic.ts
import { GenericOp } from './operations'
import Delta from 'quill-delta'
import hasPath from 'ramda/es/hasPath'
/**
* A generic interface for instances describing rich content.
*
* @public
*/
export interface GenericRichContent {
/**
* An array of operations.
*/
readonly ops: GenericOp[]
/**
* @returns The length of the underlying rich text representation.
* This length represents the number of cursor positions in the document.
*/
readonly length: () => number
}
export function extractTextFromDelta(delta: GenericRichContent): string {
return delta.ops.reduce(
(acc: string, curr: GenericOp) => (typeof curr.insert === 'string' ? acc + curr.insert : acc),
'',
)
}
export function isGenericDelta(arg: unknown): arg is GenericRichContent {
return arg && hasPath(['ops'], arg)
}
export function isMutatingDelta(delta: GenericRichContent): boolean {
const iterator = Delta.Op.iterator(delta.ops)
let shouldOverride = false
while (iterator.hasNext()) {
const next = iterator.next()
if (!next.retain || next.attributes != null) {
shouldOverride = true
break
}
}
return shouldOverride
}
<file_sep>/src/delta/operations.ts
import { Attributes } from './attributes'
import Op from 'quill-delta/dist/Op'
import reduce from 'ramda/es/reduce'
import { Images } from '@core/Images'
/**
* An atomic operation representing changes to a document.
*
* @remarks
*
* This interface is a redefinition of {@link quilljs-delta#Op}.
*
* @public
*/
export interface GenericOp {
/**
* A representation of inserted content.
*/
readonly insert?: string | object
/**
* A delete operation.
*
* @internal
*/
readonly delete?: number
/**
* A retain operation
*
* @internal
*/
readonly retain?: number
/**
* A set of attributes describing properties of the content.
*/
readonly attributes?: Attributes.Map
}
/**
* An operation referring to text.
*
* @public
*/
export interface TextOp extends GenericOp {
/**
* {@inheritdoc GenericOp.insert}
*/
readonly insert?: string
/**
* {@inheritdoc GenericOp.attributes}
*/
readonly attributes?: Attributes.Map
}
/**
* A description of an image to be persisted in the document.
*
* @public
*/
export interface ImageKind<Source> extends Images.Description<Source> {
kind: 'image'
}
/**
* An operation referring to an image.
*
* @public
*/
export type ImageOp<Source> = BlockOp<ImageKind<Source>>
/**
* An operation referring to a block.
*
* @public
*/
export interface BlockOp<T extends object> extends GenericOp {
/**
* {@inheritdoc GenericOp.insert}
*/
readonly insert: T
/**
* {@inheritdoc GenericOp.attributes}
*/
readonly attributes?: Attributes.Map
}
export function isTextOp(op: GenericOp): op is TextOp {
return typeof op.insert === 'string'
}
export const computeOpsLength = reduce((curr: number, prev: GenericOp) => Op.length(prev) + curr, 0 as number)
export function buildTextOp(text: string, attributes?: Attributes.Map) {
return attributes
? {
insert: text,
attributes,
}
: { insert: text }
}
export function buildImageOp<Source>(description: Images.Description<Source>): ImageOp<Source> {
return {
insert: {
kind: 'image',
...description,
},
}
}
<file_sep>/src/components/styles.ts
import { StyleSheet, ViewStyle } from 'react-native'
const zeroMargin: ViewStyle = {
margin: 0,
marginBottom: 0,
marginEnd: 0,
marginHorizontal: 0,
marginLeft: 0,
marginRight: 0,
marginStart: 0,
marginTop: 0,
marginVertical: 0,
}
export function overridePadding(padding: number) {
return {
padding,
paddingBottom: padding,
paddingEnd: padding,
paddingHorizontal: padding,
paddingLeft: padding,
paddingRight: padding,
paddingStart: padding,
paddingTop: padding,
paddingVertical: padding,
}
}
const zeroPadding: ViewStyle = overridePadding(0)
export const genericStyles = StyleSheet.create({
zeroMargin,
zeroPadding,
/**
* As of React Native 0.60, merging padding algorithm doesn't
* allow more specific spacing attributes to override more
* generic ones. As such, we must override all.
*/
zeroSpacing: { ...zeroMargin, ...zeroPadding },
})
<file_sep>/.github/ISSUE_TEMPLATE/bug_report.md
---
name: 🐛 Report a bug
about: Report a reproducible or regression bug.
labels: 'bug'
---
## Environment
- @typeskill/typer: <!-- Please add the used versions/branches -->
<!-- Run `react-native info` in your terminal and paste its contents bello ```. -->
```
```
## Tested Devices
<!-- For each device you have tested, report the result of your manual tests.
If the bug is not the same on different devices, please open one ticket for each.
Report 'failed' if the bug happened on this device, 'passed' if the bug did not happen on this device.
Ideally, please attempt tests on at least one iOS and one Android device or *mulator. -->
- iPhone X, ios 12.3: **<!-- failed | passed -->**
- One Plus 5, Cyanogen 9.3: **<!-- failed | passed -->**
- Android emulator v172.16.58.3, Android 8.0: **<!-- failed | passed -->**
- XCode simulator 11.0, ios 12.1: **<!-- failed | passed -->**
## Description
<!-- Describe your issue in detail. It is also very appreciated to add a GIF. -->
## Reproduction
<!-- Try to reproduce the bug with the debugger: https://github.com/typeskill/debugger. Either use the expo project, or quickly setup your own following the instructions in debugger README. -->
<!-- IF you can reproduce the steps with the debugger, enumerate these steps. For each step, copy and paste the document source.
The last line after the enumeration is the discussion about what was expected and what happened instead after last step.
Android Reproduction from the Expo Project:
1. Type "Thansk" ; Android Google Keyboard would suggest "Thanks" instead
2. Press "Thanks" ; "Thanks" should be printed now.
3. Press spacebar
"Thanks" has been overridden with "Thansk" while it shouldn't have.
OTHERWISE, you should provide a minimal example: https://stackoverflow.com/help/mcve in the form of a git repository. -->
<file_sep>/src/delta/DocumentDelta.ts
import Delta from 'quill-delta'
import { getTextAttributes, Attributes } from './attributes'
import { Selection, SelectionShape } from './Selection'
import { GenericOp } from './operations'
import mergeRight from 'ramda/es/mergeRight'
import pickBy from 'ramda/es/pickBy'
import head from 'ramda/es/head'
import { GenericRichContent, extractTextFromDelta } from './generic'
import { DeltaDiffComputer } from './DeltaDiffComputer'
import { DeltaChangeContext } from './DeltaChangeContext'
import { DocumentLine, LineWalker } from './LineWalker'
import { DocumentDeltaAtomicUpdate } from './DocumentDeltaAtomicUpdate'
export class DocumentDelta implements GenericRichContent {
public get ops() {
return this.delta.ops
}
private delta: Delta
private text: string | null = null
public constructor(arg?: GenericOp[] | DocumentDelta | Delta) {
this.delta = arg instanceof DocumentDelta ? new Delta(arg.delta) : new Delta(arg)
}
private getText(): string {
if (this.text !== null) {
return this.text
}
this.text = extractTextFromDelta(this.delta)
return this.text
}
/**
* @returns a Selection which encompasses all characters in lines traversed by incoming `selection`
*
* @param selection - The selection touching lines.
*/
private getSelectionEncompassingLines(selection: Selection): Selection {
let accumulatedLength = 0
let newSelectionStart = selection.start
let newSelectionEnd = selection.end
let isUpperBoundFrozen = false
this.delta.eachLine(l => {
if (selection.start > accumulatedLength - 1) {
newSelectionStart = accumulatedLength
}
accumulatedLength += l.length() + 1
if (selection.end < accumulatedLength && !isUpperBoundFrozen) {
newSelectionEnd = accumulatedLength
isUpperBoundFrozen = true
}
})
return Selection.fromBounds(newSelectionStart, newSelectionEnd)
}
/**
* @param selection - The selection to extract the subdelta from.
* @returns The DocumentDelta representing selection
*
*/
public getSelected(selection: Selection): DocumentDelta {
return this.create(this.delta.slice(selection.start, selection.end))
}
public compose(delta: Delta): DocumentDelta {
return this.create(this.delta.compose(delta))
}
public create(delta: Delta): DocumentDelta {
return new DocumentDelta(delta)
}
public length() {
return this.delta.length()
}
public concat(delta: Delta | DocumentDelta) {
return this.create(this.delta.concat(delta instanceof DocumentDelta ? delta.delta : delta))
}
public eachLine(predicate: (line: DocumentLine) => void) {
new LineWalker(this.delta).eachLine(predicate)
}
/**
* Compute a diff between this document delta text and return the resulting atomic update.
* The first one is the strict result of applying the text diff, while the second one
* it the result of applying normalization rules (i.e. prefixes rules for text modifying line types).
*
* @remarks
*
* `cursorTextAttributes` will by applied to inserted characters if and only if `deltaChangeContext.selectionBeforeChange` is of length 0.
*
* @param newText - The changed text.
* @param deltaChangeContext - The context in which the change occurred.
* @param cursorTextAttributes - Text attributes at cursor.
* @returns The resulting atomic update from applying the text diff.
*/
public applyTextDiff(
newText: string,
deltaChangeContext: DeltaChangeContext,
cursorTextAttributes: Attributes.Map = {},
): DocumentDeltaAtomicUpdate {
const oldText = this.getText()
const computer = new DeltaDiffComputer(
{
cursorTextAttributes,
newText,
oldText,
context: deltaChangeContext,
},
this,
)
const { delta } = computer.toDeltaDiffReport()
return new DocumentDeltaAtomicUpdate(this.compose(delta), delta, deltaChangeContext.selectionAfterChange)
}
/**
* Determine the line type of given selection.
*
* @remarks
*
* **Pass algorithm**:
*
* If each and every line has its `$type` set to one peculiar value, return this value.
* Otherwise, return `"normal"`.
*
* @param selection - the selection to which line type should be inferred.
* @returns the line type encompassing the whole selection.
*/
public getLineTypeInSelection(selection: Selection): Attributes.LineType {
// TODO inspect inconsistencies between this getSelectionEncompassingLines and Text::getSelectionEncompassingLine
const selected = this.getSelected(this.getSelectionEncompassingLines(selection))
const lineAttributes: Attributes.Map[] = []
selected.delta.eachLine((l, a) => {
lineAttributes.push(a)
})
const firstAttr = head<Attributes.Map>(lineAttributes)
let type: Attributes.LineType = 'normal'
if (firstAttr) {
if (firstAttr.$type == null) {
return 'normal'
}
type = firstAttr.$type as Attributes.LineType
}
const isType = lineAttributes.every(v => v.$type === type)
if (isType) {
return type
}
return 'normal'
}
/**
* Returns the attributes encompassing the given selection.
* This attribute should be used for user feedback after selection change.
*
* @remarks
*
* The returned attributes depend on the selection size:
*
* - When selection size is `0`, this function returns attributes of the closest character before cursor.
* - When selection size is `1+`, this function returns a merge of each set of attributes (see merge algorithm bellow).
*
* **Merge algorithm**:
*
* - for an attribute to be merged in the remaining object, it must be present in every operation traversed by selection;
* - operations consisting of one newline character insert should be ignored during the traversal, and thus line attributes ignored;
* - if one attribute name has conflicting values within the selection, none of those values should be picked in the remaining object;
* - any attribute name with a nil value (`null` or `undefined`) should be ignored in the remaining object.
*
* @param selection - the selection from which text attributes should be extracted
* @returns The resulting merged object
*/
public getSelectedTextAttributes(selection: SelectionShape): Attributes.Map {
let realSelection = Selection.fromShape(selection)
if (selection.start === selection.end) {
if (selection.start === 0) {
return {}
}
realSelection = Selection.fromBounds(selection.start - 1, selection.end)
}
const deltaSelection = this.getSelected(realSelection)
const attributesList = deltaSelection.delta
.filter(op => typeof op.insert === 'string' && op.insert !== '\n')
.map(op => op.attributes || {})
const attributes = attributesList.reduce(mergeRight, {})
const realAttributes = pickBy((value: Attributes.GenericValue, attributeName: string) =>
attributesList.every(localValue => localValue[attributeName] === value),
)(attributes)
return getTextAttributes(realAttributes)
}
/**
* Switch the given attribute's value depending on the state of the given selection:
*
* - if **all characters** in the selection have the `attributeName` set to `attributeValue`, **clear** this attribute for all characters in this selection
* - otherwise set `attributeName` to `attributeValue` for all characters in this selection
*
* @param selectionBeforeChange - The boundaries to which the transforms should be applied
* @param attributeName - The attribute name to modify
* @param attributeValue - The attribute value to assign
*/
public applyTextTransformToSelection(
selectionBeforeChange: Selection,
attributeName: string,
attributeValue: Attributes.GenericValue,
): DocumentDeltaAtomicUpdate {
const allOperationsMatchAttributeValue = this.getSelected(selectionBeforeChange).ops.every(
op => !!op.attributes && op.attributes[attributeName] === attributeValue,
)
if (allOperationsMatchAttributeValue) {
const clearAllDelta = new Delta()
clearAllDelta.retain(selectionBeforeChange.start)
clearAllDelta.retain(selectionBeforeChange.length(), { [attributeName]: null })
return new DocumentDeltaAtomicUpdate(this.compose(clearAllDelta), clearAllDelta, selectionBeforeChange)
}
const replaceAllDelta = new Delta()
replaceAllDelta.retain(selectionBeforeChange.start)
replaceAllDelta.retain(selectionBeforeChange.length(), { [attributeName]: attributeValue })
return new DocumentDeltaAtomicUpdate(this.compose(replaceAllDelta), replaceAllDelta, selectionBeforeChange)
}
}
<file_sep>/etc/typer.api.md
## API Report File for "@typeskill/typer"
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).
```ts
import { Component } from 'react';
import { ComponentType } from 'react';
import { FunctionComponent } from 'react';
import { ScrollViewProps } from 'react-native';
import { StyleProp } from 'react-native';
import { TextStyle } from 'react-native';
import { ViewStyle } from 'react-native';
// @public
export namespace Attributes {
export type GenericValue = object | TextValue | undefined;
export type LineType = 'normal' | 'quoted';
export interface Map {
// (undocumented)
readonly [k: string]: GenericValue;
}
export type TextValue = boolean | string | number | null;
}
// @public
export interface BlockOp<T extends object> extends GenericOp {
readonly attributes?: Attributes.Map;
readonly insert: T;
}
// @public
export namespace Bridge {
export type AttributesOverrideListener = (attributeName: string, attributeValue: Attributes.GenericValue) => void;
export type ControlEvent = 'APPLY_ATTRIBUTES_TO_SELECTION' | 'INSERT_OR_REPLACE_AT_SELECTION';
export interface ControlEventDomain<ImageSource> {
applyTextTransformToSelection: (attributeName: string, attributeValue: Attributes.TextValue) => void;
// @internal
insertOrReplaceAtSelection: (element: Element<ImageSource>) => void;
}
export type Element<ImageSource> = ImageElement<ImageSource> | TextElement;
export interface ImageElement<Source> {
// (undocumented)
description: Images.Description<Source>;
// (undocumented)
type: 'image';
}
// @internal (undocumented)
export type InsertOrReplaceAtSelectionListener<ImageSource> = <D extends {}>(element: Element<ImageSource>) => void;
export type LineTypeOverrideListener = (lineType: Attributes.LineType) => void;
export type SelectedAttributesChangeListener = (selectedAttributes: Attributes.Map) => void;
// @internal
export interface SheetEventDomain<ImageSource> {
addApplyTextTransformToSelectionListener: (owner: object, listener: AttributesOverrideListener) => void;
addInsertOrReplaceAtSelectionListener: (owner: object, listener: InsertOrReplaceAtSelectionListener<ImageSource>) => void;
release: (owner: object) => void;
}
// (undocumented)
export interface TextElement {
// (undocumented)
content: string;
// (undocumented)
type: 'text';
}
}
// @public
export interface Bridge<ImageSource> {
getControlEventDomain: () => Bridge.ControlEventDomain<ImageSource>;
// @internal
getSheetEventDomain: () => Bridge.SheetEventDomain<ImageSource>;
release: () => void;
}
// @public (undocumented)
export const Bridge: {};
// @public
export function buildBridge<ImageSource = Images.StandardSource>(): Bridge<ImageSource>;
// @public
export function buildEmptyDocument(): Document;
// @public
export function buildVectorIconControlSpec<A extends GenericControlAction, T extends Toolbar.VectorIconMinimalProps>(IconComponent: ComponentType<T & Toolbar.TextControlMinimalIconProps>, actionType: A, name: string, options?: Pick<Toolbar.GenericControlSpec<A, T>, 'actionOptions' | 'iconProps'>): Toolbar.GenericControlSpec<A, T>;
// @public
export function cloneDocument(content: Document): Document;
// @public
export const CONTROL_SEPARATOR: unique symbol;
// @public (undocumented)
export const defaultTextTransforms: Transforms.GenericSpec<Attributes.TextValue, 'text'>[];
// @public
export interface Document {
readonly currentSelection: SelectionShape;
readonly lastDiff: GenericOp[];
readonly ops: GenericOp[];
readonly schemaVersion: number;
readonly selectedTextAttributes: Attributes.Map;
}
// @public
export enum DocumentControlAction {
INSERT_IMAGE_AT_SELECTION = 4,
SELECT_TEXT_BOLD = 0,
SELECT_TEXT_ITALIC = 1,
SELECT_TEXT_STRIKETHROUGH = 3,
SELECT_TEXT_UNDERLINE = 2
}
// @public
export interface DocumentRendererProps<ImageSource> {
contentContainerStyle?: StyleProp<ViewStyle>;
document: Document;
documentStyle?: StyleProp<ViewStyle>;
ImageComponent?: Images.Component<ImageSource>;
maxMediaBlockHeight?: number;
maxMediaBlockWidth?: number;
ScrollView?: ComponentType<any>;
scrollViewProps?: ScrollViewProps;
spacing?: number;
style?: StyleProp<ViewStyle>;
textStyle?: StyleProp<TextStyle>;
textTransformSpecs?: Transforms.Specs<'text'>;
}
// @public (undocumented)
export interface FocusableInput {
focus: () => void;
}
// @public
export type GenericControlAction = string | symbol | number;
// @public
export interface GenericOp {
readonly attributes?: Attributes.Map;
// @internal
readonly delete?: number;
readonly insert?: string | object;
// @internal
readonly retain?: number;
}
// @public
export interface GenericRichContent {
// (undocumented)
readonly length: () => number;
readonly ops: GenericOp[];
}
// @public
export interface ImageKind<Source> extends Images.Description<Source> {
// (undocumented)
kind: 'image';
}
// @public
export type ImageOp<Source> = BlockOp<ImageKind<Source>>;
// @public
export namespace Images {
// (undocumented)
export type Component<Source> = ComponentType<ComponentProps<Source>>;
// (undocumented)
export interface ComponentProps<Source> {
readonly description: Description<Source>;
readonly printDimensions: Dimensions;
}
// (undocumented)
export interface Description<Source> {
// (undocumented)
readonly height: number;
// (undocumented)
readonly source: Source;
// (undocumented)
readonly width: number;
}
// (undocumented)
export interface Dimensions {
// (undocumented)
readonly height: number;
// (undocumented)
readonly width: number;
}
export interface Hooks<Source> {
readonly onImageAddedEvent?: (description: Description<Source>) => void;
readonly onImageRemovedEvent?: (description: Description<Source>) => void;
}
// (undocumented)
export interface StandardSource {
// (undocumented)
uri: string;
}
}
// @public
export namespace Print {
export type Props<ImageSource> = DocumentRendererProps<ImageSource>;
}
// @public
export class Print<ImageSource = Images.StandardSource> extends Component<Print.Props<ImageSource>> {
}
// @public
export interface SelectionShape {
readonly end: number;
readonly start: number;
}
// @public
export interface TextOp extends GenericOp {
readonly attributes?: Attributes.Map;
readonly insert?: string;
}
// @public
export namespace Toolbar {
export type DocumentControlSpec<T extends object = {}> = GenericControlSpec<DocumentControlAction, T>;
// (undocumented)
export interface GenericControlSpec<A extends GenericControlAction, T extends object> {
actionOptions?: any;
actionType: A;
IconComponent: ComponentType<TextControlMinimalIconProps & T>;
iconProps?: T extends Toolbar.VectorIconMinimalProps ? Toolbar.VectorIconMinimalProps : Partial<T>;
}
export interface IconButtonProps extends IconButtonSpecs {
// (undocumented)
IconComponent: ComponentType<TextControlMinimalIconProps>;
// (undocumented)
iconProps?: object;
// (undocumented)
onPress?: () => void;
// (undocumented)
selected: boolean;
// (undocumented)
style?: StyleProp<ViewStyle>;
}
// (undocumented)
export interface IconButtonSpecs {
activeButtonBackgroundColor: string;
activeButtonColor: string;
iconSize: number;
inactiveButtonBackgroundColor: string;
inactiveButtonColor: string;
}
export type Layout = (DocumentControlSpec<any> | typeof CONTROL_SEPARATOR | GenericControlSpec<any, any>)[];
export interface Props<ImageSource, ImageOptions = any> extends Partial<IconButtonSpecs> {
bridge: Bridge<ImageSource>;
buttonSpacing?: number;
contentContainerStyle?: StyleProp<ViewStyle>;
document: Document;
layout: Layout;
onInsertImageError?: (e: Error) => void;
onPressCustomControl?: <A extends GenericControlAction>(actionType: A, actionOptions?: any) => void;
pickOneImage?: (options?: ImageOptions) => Promise<Images.Description<ImageSource>>;
separatorColor?: string;
style?: StyleProp<ViewStyle>;
}
export interface TextControlMinimalIconProps {
color?: string;
size?: number;
}
export interface VectorIconMinimalProps {
name: string;
}
}
// @public
export class Toolbar<ImageSource = Images.StandardSource, ImageOptions = any> extends Component<Toolbar.Props<ImageSource, ImageOptions>> {
IconButton: FunctionComponent<Toolbar.IconButtonProps>;
}
// @public
export namespace Transforms {
export type BoolSpec<T extends TargetType = 'block'> = GenericSpec<true, T>;
// @internal
export interface Dict<A extends Attributes.GenericValue, T extends TargetType> {
// (undocumented)
[attributeName: string]: GenericSpec<A, T>[];
}
export interface GenericSpec<A extends Attributes.GenericValue, T extends TargetType> {
activeAttributeValue: A;
activeStyle: T extends 'block' ? ViewStyle : TextStyle;
attributeName: string;
}
// (undocumented)
export type Specs<T extends 'text' | 'block' = 'text'> = GenericSpec<Attributes.TextValue, T>[];
export type TargetType = 'block' | 'text';
export type TextAttributeName = 'bold' | 'italic' | 'textDecoration';
}
// @public
export class Transforms {
constructor(textTransformSpecs: Transforms.GenericSpec<Attributes.TextValue, 'text'>[]);
// @internal
getStylesFromOp(op: TextOp): StyleProp<TextStyle>;
}
// @public
export namespace Typer {
export interface Props<ImageSource> extends DocumentRendererProps<ImageSource> {
androidDisableMultipleAttributeEdits?: boolean;
bridge: Bridge<ImageSource>;
debug?: boolean;
disableSelectionOverrides?: boolean;
imageHooks?: Images.Hooks<ImageSource>;
onDocumentUpdate?: (nextDocumentContent: Document) => void;
readonly?: boolean;
underlayColor?: string;
}
}
// @public
export class Typer<ImageSource = Images.StandardSource> extends Component<Typer.Props<ImageSource>> implements FocusableInput {
// (undocumented)
focus: () => void;
}
// @public
export function useBridge<ImageSource = Images.StandardSource>(deps?: unknown[]): Bridge<ImageSource>;
// @public
export function useDocument(initialDocument?: Document): [Document, import("react").Dispatch<import("react").SetStateAction<Document>>];
```
<file_sep>/src/test/delta.ts
import invariant from 'invariant'
import { DeltaChangeContext } from '@delta/DeltaChangeContext'
import { Selection } from '@delta/Selection'
// A function to mock a change context
export function mockDeltaChangeContext(
beforeStart: number,
afterStart: number,
beforeEnd?: number,
): DeltaChangeContext {
invariant(beforeEnd === undefined || beforeEnd > beforeStart, '')
return new DeltaChangeContext(Selection.fromBounds(beforeStart, beforeEnd), Selection.fromBounds(afterStart))
}
export function mockSelection(start: number, end?: number): Selection {
return Selection.fromBounds(start, end)
}
<file_sep>/src/model/BlockAssembler.ts
import { Block } from './Block'
import { groupOpsByBlocks } from './blocks'
import { Document } from './document'
import { Bridge } from '@core/Bridge'
import { Attributes } from '@delta/attributes'
import { DocumentDelta } from '@delta/DocumentDelta'
import { SelectionShape } from '@delta/Selection'
/**
* An object to manipulate blocks.
*/
export class BlockAssembler {
private blocks: Block[]
private document: Document
public constructor(document: Document) {
this.document = document
this.blocks = groupOpsByBlocks(document.ops)
}
private getActiveBlock(): Block | null {
for (const block of this.blocks) {
if (block.isFocused(this.document)) {
return block
}
}
return null
}
public getBlocks(): Block[] {
return this.blocks
}
public insertOrReplaceAtSelection(element: Bridge.Element<any>): Document {
const activeBlock = this.getActiveBlock() as Block
return activeBlock.insertOrReplaceAtSelection(element, this.document)
}
public updateTextAttributesAtSelection(): Document {
const document = this.document
const docDelta = new DocumentDelta(document.ops)
const deltaAttributes = docDelta.getSelectedTextAttributes(document.currentSelection)
return {
...document,
selectedTextAttributes: deltaAttributes,
}
}
public applyTextTransformToSelection(attributeName: string, attributeValue: Attributes.GenericValue): Document {
const activeBlock = this.getActiveBlock() as Block
return activeBlock.applyTextTransformToSelection(attributeName, attributeValue, this.document)
}
public getActiveBlockScopedSelection(): SelectionShape {
const activeBlock = this.getActiveBlock() as Block
return activeBlock.getBlockScopedSelection(this.document.currentSelection) as SelectionShape
}
}
<file_sep>/src/core/Endpoint.ts
import { EventEmitter, ListenerFn } from 'eventemitter3'
interface ListenerDescriptor<E extends string, L extends Function> {
listener: L
eventType: E
}
export class Endpoint<InnerEventType extends string> {
private owners = new WeakMap<object, ListenerDescriptor<InnerEventType, (...args: unknown[]) => unknown>[]>()
private domain = new EventEmitter()
public addListener(owner: object, eventType: InnerEventType, listener: ListenerFn) {
this.domain.addListener(eventType, listener)
const listeners = this.owners.get(owner) || []
listeners.push({
eventType,
listener,
})
this.owners.set(owner, listeners)
}
public emit(eventType: InnerEventType, ...payload: unknown[]): void {
this.domain.emit(eventType, ...payload)
}
public release(owner: object) {
const descriptors = this.owners.get(owner)
if (descriptors) {
for (const { listener, eventType } of descriptors) {
this.domain.removeListener(eventType, listener)
}
}
this.owners.delete(owner)
}
public removeAllListeners() {
this.domain.removeAllListeners()
}
}
<file_sep>/src/components/Print.ts
import { Component } from 'react'
import { DocumentRenderer, DocumentRendererProps, DocumentRendererState } from './DocumentRenderer'
import { BlockAssembler } from '@model/BlockAssembler'
import { Images } from '@core/Images'
/**
* A set of definitions relative to {@link (Print:class)} component.
* @public
*/
export declare namespace Print {
/**
* {@link (Print:class)} properties.
*/
export type Props<ImageSource> = DocumentRendererProps<ImageSource>
}
type PrintState = DocumentRendererState
// eslint-disable-next-line @typescript-eslint/class-name-casing
class _Print extends DocumentRenderer<Print.Props<any>> {
public static displayName = 'Print'
public static propTypes = DocumentRenderer.propTypes
public static defaultProps = DocumentRenderer.defaultProps
public state: PrintState = {
containerWidth: null,
}
public render() {
this.assembler = new BlockAssembler(this.props.document)
return this.renderRoot(this.assembler.getBlocks().map(this.renderBlockView))
}
}
/**
* A component solely responsible for viewing {@link Document | document}.
*
* @public
*
*/
export declare class Print<ImageSource = Images.StandardSource> extends Component<Print.Props<ImageSource>> {}
exports.Print = _Print
<file_sep>/src/delta/attributes.ts
import mergeAll from 'ramda/es/mergeAll'
import reject from 'ramda/es/reject'
import isNil from 'ramda/es/isNil'
import omit from 'ramda/es/omit'
/**
* A set of definitions for {@link GenericOp} attributes.
*
* @public
*/
export declare namespace Attributes {
/**
* Possible values for a text transform.
*
* @public
*/
export type TextValue = boolean | string | number | null
/**
* An attribute value.
*
* @public
*/
export type GenericValue = object | TextValue | undefined
/**
* A set of attributes applying to a {@link GenericOp}.
*
* @public
*/
export interface Map {
readonly [k: string]: GenericValue
}
/**
* A special text attribute value applied to a whole line.
*
* @remarks
*
* There can be only one text line type attribute active at once.
*
* @public
*/
export type LineType = 'normal' | 'quoted'
}
const rejectNil = reject(isNil)
/**
* Create a new object with the own properties of the first object merged with the own properties of the second object and so on.
* If a key exists in both objects, the value from the endmost object will be used.
*
* @remarks
*
* `null` values are removed from the returned object.
*
* @param attributes - the attributes object to merge
*/
export function mergeAttributesRight(...attributes: Attributes.Map[]): Attributes.Map {
return rejectNil(mergeAll<Attributes.Map[]>(attributes))
}
export const getTextAttributes = omit(['$type'])
<file_sep>/src/delta/__tests__/LineWalker-test.ts
import { mockDocumentDelta } from '@test/document'
import { LineWalker } from '@delta/LineWalker'
import zip from 'ramda/es/zip'
describe('@delta/LineWalker', () => {
describe('getLines', () => {
it('should group lines by trailing newline characters', () => {
const delta = mockDocumentDelta([{ insert: 'AB\nCD\n' }])
const walker = new LineWalker(delta)
const lines = walker.getLines()
expect(lines.length).toBe(2)
})
it('should produce line ranges complying with the substring contract', () => {
const textLines = ['AB', 'CD']
const fullText = 'AB\nCD\n'
const delta = mockDocumentDelta([{ insert: fullText }])
const walker = new LineWalker(delta)
const lines = walker.getLines()
for (const [line, textLine] of zip(lines, textLines)) {
expect(fullText.substring(line.lineRange.start, line.lineRange.end)).toBe(textLine)
}
})
it('should produce line ranges for which the character at range.end is a newline', () => {
const fullText = 'AB\nCD\n'
const delta = mockDocumentDelta([{ insert: fullText }])
const walker = new LineWalker(delta)
const lines = walker.getLines()
for (const line of lines) {
expect(fullText.charAt(line.lineRange.end)).toBe('\n')
}
})
})
})
<file_sep>/src/model/__tests__/BlockAssembler-test.ts
import { BlockAssembler } from '@model/BlockAssembler'
import { buildEmptyDocument, Document } from '@model/document'
import { buildTextOp } from '@delta/operations'
import { buildDummyImageOp } from '@test/document'
describe('@model/Document', () => {
describe('updateTextAttributesAtSelection', () => {
it('should not update attributes when selection matches a non-text block', () => {
const document: Document = {
...buildEmptyDocument(),
ops: [buildTextOp('L'), buildDummyImageOp()],
currentSelection: {
start: 2,
end: 2,
},
}
const assembler = new BlockAssembler(document)
expect(assembler.updateTextAttributesAtSelection().selectedTextAttributes).toMatchObject({})
})
})
})
<file_sep>/src/test/vdom.ts
import { NativeSyntheticEvent, TextInputSelectionChangeEventData } from 'react-native'
import { ReactTestInstance } from 'react-test-renderer'
export function mockSelectionChangeEvent(
start: number,
end: number,
): NativeSyntheticEvent<TextInputSelectionChangeEventData> {
return { nativeEvent: { selection: { start, end } } } as NativeSyntheticEvent<TextInputSelectionChangeEventData>
}
export function flattenTextChild(instance: ReactTestInstance): string[] {
const children: string[] = []
if (Array.isArray(instance.children)) {
for (const inst of instance.children) {
if (typeof inst !== 'string') {
children.push(...flattenTextChild(inst))
} else {
children.push(inst)
}
}
}
return children
}
<file_sep>/src/model/__tests__/blocks-test.ts
import { groupOpsByBlocks, BlockDescriptor } from '@model/blocks'
import { buildTextOp } from '@delta/operations'
import prop from 'ramda/es/prop'
import { buildDummyImageOp } from '@test/document'
describe('@model/blocks', () => {
describe('groupOpsByBlocks', () => {
it('should group text ops together', () => {
const blocks = groupOpsByBlocks([buildTextOp('Hello'), buildTextOp('Great')])
expect(blocks.length).toBe(1)
const expectedDesc: BlockDescriptor = {
blockIndex: 0,
kind: 'text',
startSliceIndex: 0,
endSliceIndex: 2,
opsSlice: [buildTextOp('Hello'), buildTextOp('Great')],
numOfSelectableUnits: 10,
selectableUnitsOffset: 0,
maxBlockIndex: 1,
}
expect(blocks[0].descriptor).toMatchObject(expectedDesc)
})
it('should split groups of different kind', () => {
const helloOp = buildTextOp('Hello')
const greatOp = buildTextOp('Great')
const imgOp = buildDummyImageOp()
const blocks = groupOpsByBlocks([helloOp, greatOp, imgOp])
expect(blocks.length).toBe(2)
expect(blocks.map(prop('descriptor'))).toMatchObject([
{
blockIndex: 0,
kind: 'text',
startSliceIndex: 0,
endSliceIndex: 2,
opsSlice: [helloOp, greatOp],
numOfSelectableUnits: 10,
selectableUnitsOffset: 0,
},
{
blockIndex: 1,
kind: 'image',
startSliceIndex: 2,
endSliceIndex: 3,
opsSlice: [imgOp],
numOfSelectableUnits: 1,
selectableUnitsOffset: 10,
},
] as BlockDescriptor[])
})
it('should handle empty ops', () => {
const blocks = groupOpsByBlocks([buildTextOp('')])
expect(blocks.length).toBe(1)
expect(blocks.map(prop('descriptor'))).toMatchObject([
{
blockIndex: 0,
kind: 'text',
startSliceIndex: 0,
endSliceIndex: 1,
opsSlice: [buildTextOp('')],
numOfSelectableUnits: 0,
selectableUnitsOffset: 0,
},
] as BlockDescriptor[])
})
it('should create a new group for each sibling image', () => {
const blocks = groupOpsByBlocks([buildDummyImageOp('A'), buildDummyImageOp('B')])
expect(blocks.length).toBe(2)
expect(blocks.map(prop('descriptor'))).toMatchObject([
{
blockIndex: 0,
kind: 'image',
startSliceIndex: 0,
endSliceIndex: 1,
opsSlice: [buildDummyImageOp('A')],
numOfSelectableUnits: 1,
selectableUnitsOffset: 0,
},
{
blockIndex: 1,
kind: 'image',
startSliceIndex: 1,
endSliceIndex: 2,
opsSlice: [buildDummyImageOp('B')],
numOfSelectableUnits: 1,
selectableUnitsOffset: 1,
},
] as BlockDescriptor[])
})
})
})
<file_sep>/src/delta/DeltaDiffComputer.ts
import Delta from 'quill-delta'
import { DocumentDelta } from './DocumentDelta'
import { Attributes, mergeAttributesRight } from './attributes'
import { DeltaChangeContext } from './DeltaChangeContext'
import { Text } from './Text'
import { Selection } from './Selection'
import { makeDiffDelta } from './diff'
export enum NormalizeOperation {
INSERT_LINE_TYPE_PREFIX,
INVESTIGATE_DELETION,
CHECK_LINE_TYPE_PREFIX,
}
export interface DeltaDiffReport {
delta: Delta
}
interface TextDiffContext {
readonly textAttributes: Attributes.Map
readonly lineAttributes: Attributes.Map
readonly lineTypeBeforeChange: Attributes.LineType
readonly context: DeltaChangeContext
readonly oldText: Text
readonly newText: Text
}
export interface DeltaDiffModel {
readonly oldText: string
readonly newText: string
readonly context: DeltaChangeContext
readonly cursorTextAttributes: Attributes.Map
}
export class DeltaDiffComputer {
private readonly diffContext: TextDiffContext
public constructor(model: DeltaDiffModel, delta: DocumentDelta) {
const { context, cursorTextAttributes, newText: newTextRaw, oldText: oldTextRaw } = model
const selectedTextAttributes = delta.getSelectedTextAttributes(context.selectionBeforeChange)
const selectionBeforeChangeLength = context.selectionBeforeChange.end - context.selectionBeforeChange.start
const textAttributes = selectionBeforeChangeLength
? selectedTextAttributes
: mergeAttributesRight(selectedTextAttributes, cursorTextAttributes)
const lineTypeBeforeChange = delta.getLineTypeInSelection(context.selectionBeforeChange)
const oldText = new Text(oldTextRaw)
const newText = new Text(newTextRaw)
const lineAttributes = lineTypeBeforeChange === 'normal' ? {} : { $type: lineTypeBeforeChange }
this.diffContext = {
context,
oldText,
newText,
textAttributes,
lineAttributes,
lineTypeBeforeChange,
}
}
private computeGenericDelta(originalText: Text, diffContext: TextDiffContext): Delta {
const { context, newText, textAttributes } = diffContext
const lineBeforeChangeSelection = originalText.getSelectionEncompassingLines(context.selectionBeforeChange)
const lineAfterChangeSelection = newText.getSelectionEncompassingLines(context.selectionAfterChange)
const lineChangeContext = new DeltaChangeContext(lineBeforeChangeSelection, lineAfterChangeSelection)
const selectionTraversalBeforeChange = lineChangeContext.deleteTraversal()
const selectionTraversalAfterChange = Selection.between(
selectionTraversalBeforeChange.start,
lineAfterChangeSelection.end,
)
const textBeforeChange = originalText.select(selectionTraversalBeforeChange)
const textAfterChange = newText.select(selectionTraversalAfterChange)
const delta = new Delta()
.retain(selectionTraversalBeforeChange.start)
.concat(makeDiffDelta(textBeforeChange.raw, textAfterChange.raw, textAttributes))
.retain(originalText.length - selectionTraversalBeforeChange.end)
return delta
}
public toDeltaDiffReport(): DeltaDiffReport {
const { oldText } = this.diffContext
const delta = this.computeGenericDelta(oldText, this.diffContext)
return { delta }
}
}
<file_sep>/src/components/GenericBlockInput/TextBlockInput/TextChangeSessionBehavior.ts
import { NativeSyntheticEvent, TextInputSelectionChangeEventData } from 'react-native'
import { TextChangeSession } from './TextChangeSession'
import { DocumentDeltaAtomicUpdate } from '@delta/DocumentDeltaAtomicUpdate'
import { Selection, SelectionShape } from '@delta/Selection'
import { TextOp } from '@delta/operations'
import { DocumentDelta } from '@delta/DocumentDelta'
import { Attributes } from '@delta/attributes'
export interface TextChangeSessionOwner {
getTextChangeSession: () => TextChangeSession | null
setTextChangeSession: (textChangeSession: TextChangeSession | null) => void
updateOps: (documentDeltaUpdate: DocumentDeltaAtomicUpdate) => void
getBlockScopedSelection: () => SelectionShape | null
getOps: () => TextOp[]
getAttributesAtCursor: () => Attributes.Map
updateSelection: (selection: SelectionShape) => void
clearTimeout: () => void
setTimeout: (callback: () => void, duration: number) => void
}
export interface TextChangeSessionBehavior {
handleOnTextChanged: (owner: TextChangeSessionOwner, nextText: string) => void
handleOnSelectionChanged: (
owner: TextChangeSessionOwner,
event: NativeSyntheticEvent<TextInputSelectionChangeEventData>,
) => void
}
function applySelectionChange(owner: TextChangeSessionOwner, textChangeSession: TextChangeSession) {
const ops = owner.getOps()
const documentDeltaUpdate = new DocumentDelta(ops).applyTextDiff(
textChangeSession.getTextAfterChange(),
textChangeSession.getDeltaChangeContext(),
owner.getAttributesAtCursor(),
)
owner.setTextChangeSession(null)
owner.updateOps(documentDeltaUpdate)
}
const IOS_TIMEOUT_DURATION = 10
/**
* As of RN61 on iOS, selection changes happens before text change.
*/
export const iosTextChangeSessionBehavior: TextChangeSessionBehavior = {
handleOnSelectionChanged(owner, { nativeEvent: { selection } }) {
owner.clearTimeout()
const textChangeSession = new TextChangeSession()
textChangeSession.setSelectionBeforeChange(owner.getBlockScopedSelection() as SelectionShape)
textChangeSession.setSelectionAfterChange(selection)
owner.setTextChangeSession(textChangeSession)
owner.setTimeout(() => {
owner.setTextChangeSession(null)
owner.updateSelection(selection)
}, IOS_TIMEOUT_DURATION)
},
handleOnTextChanged(owner, nextText) {
owner.clearTimeout()
const textChangeSession = owner.getTextChangeSession()
if (textChangeSession !== null) {
textChangeSession.setTextAfterChange(nextText)
applySelectionChange(owner, textChangeSession)
}
},
}
/**
* As of RN61 on Android, text changes happens before selection change.
*/
export const androidTextChangeSessionBehavior: TextChangeSessionBehavior = {
handleOnTextChanged(owner, nextText) {
const textChangeSession = new TextChangeSession()
textChangeSession.setTextAfterChange(nextText)
textChangeSession.setSelectionBeforeChange(owner.getBlockScopedSelection() as Selection)
owner.setTextChangeSession(textChangeSession)
},
handleOnSelectionChanged(owner, { nativeEvent: { selection } }) {
const nextSelection = Selection.between(selection.start, selection.end)
const textChangeSession = owner.getTextChangeSession()
if (textChangeSession !== null) {
textChangeSession.setSelectionAfterChange(nextSelection)
applySelectionChange(owner, textChangeSession)
} else {
owner.updateSelection(nextSelection)
}
},
}
<file_sep>/src/delta/Text.ts
import { Selection } from './Selection'
import { GenericLine } from './lines'
export interface TextLine extends GenericLine {
text: string
}
/**
* Intermediary entity between pure text and {@link quill-delta#Delta the Delta class}.
*
* @remarks
*
* A Text instance represents an absolute-positionned part of the document.
* We refer to absolute coordinates as **Document coordinates** or index, and relative
* coordinates as **Text coordiantes** or index.
*/
export class Text {
public readonly raw: string
public readonly beginningIndex: number = 0
public constructor(rawText: string, beginningIndex?: number) {
this.raw = rawText
this.beginningIndex = beginningIndex || 0
}
private documentToTextIndex(documentIndex: number) {
return documentIndex - this.beginningIndex
}
private textToDocumentIndex(textIndex: number) {
return textIndex + this.beginningIndex
}
public get length() {
return this.raw.length
}
/**
*
* @param from Document index of the first character to select.
* @param to Document index of the last + 1 character to select.
*/
public substring(from: number, to: number): string {
return this.raw.substring(this.documentToTextIndex(from), this.documentToTextIndex(to))
}
/**
*
* @param documentIndex
*/
public charAt(documentIndex: number): string {
return this.raw.charAt(this.documentToTextIndex(documentIndex))
}
/**
*
* @param documentSelection Document coordinates of selection.
* @returns A new {@link Text} instance which is a substring of `this` instance with Document coordiantes.
*/
public select(documentSelection: Selection): Text {
return new Text(this.substring(documentSelection.start, documentSelection.end), documentSelection.start)
}
/**
* Builds the selection matching lines touched by the param `selection`.
*
* @remarks
*
* For N characters, there are N+1 selection indexes. In the example bellow,
* each character is surrounded by two cursor positions reprented with crosses (`†`).
*
* `†A†B†\n†C†D†\n†`
*
* **Encompassing**
*
* The selection encompassing a line always excludes the index referring to the end of the
* trailing newline character.
* In the example above, the selection `[1, 2]` would match this line: `[0, 2]` with characters `'AB'`.
* The selection `[4, 5]` would match the line `[3, 5]` with characters `'CD'`.
*
* **Multiple lines**
*
* When multiple lines are touched by the param `selection`, indexes referring
* to the end of the trailing newline character in sibling lines are included.
*
* Therefore, in the above example, applying the selection `[2, 3]` to this function
* would result in the following selection: `[0, 5]`.
*
* @param documentSelection Document relative selection to which this algorithm apply.
*/
public getSelectionEncompassingLines(documentSelection: Selection): Selection {
let textStart = documentSelection.start - this.beginningIndex
let textEnd = documentSelection.end - this.beginningIndex
while (textStart > 0 && this.raw.charAt(textStart - 1) !== '\n') {
textStart -= 1
}
while (textEnd < this.raw.length && this.raw.charAt(textEnd) !== '\n') {
textEnd += 1
}
return Selection.fromBounds(this.textToDocumentIndex(textStart), this.textToDocumentIndex(textEnd))
}
/**
* @returns A list of lines complying with the {@link GenericLine} contract.
*/
public getLines(): TextLine[] {
let charIndex = this.beginningIndex - 1
let lineIndex = -1
const lines = this.raw.split('\n')
return lines.map(text => {
const start = charIndex + 1
charIndex = start + text.length
lineIndex += 1
const lineRange = Selection.fromBounds(start, charIndex)
return {
text,
lineRange,
index: lineIndex,
}
})
}
}
<file_sep>/src/delta/DeltaChangeContext.ts
import { Selection } from './Selection'
export class DeltaChangeContext {
public readonly selectionBeforeChange: Selection
public readonly selectionAfterChange: Selection
public constructor(selectionBeforeChange: Selection, selectionAfterChange: Selection) {
this.selectionAfterChange = selectionAfterChange
this.selectionBeforeChange = selectionBeforeChange
}
public lowerLimit() {
return Math.min(this.selectionAfterChange.start, this.selectionBeforeChange.start)
}
public upperLimit() {
return Math.max(this.selectionAfterChange.end, this.selectionBeforeChange.end)
}
public deleteTraversal(): Selection {
return Selection.fromBounds(
Math.min(this.selectionBeforeChange.start, this.selectionAfterChange.start),
this.selectionBeforeChange.end,
)
}
public isInsertion() {
return this.selectionBeforeChange.start < this.selectionAfterChange.end
}
public isDeletion() {
return this.selectionBeforeChange.end > this.lowerLimit()
}
}
<file_sep>/src/hooks/use-document.ts
import { Document, buildEmptyDocument } from '@model/document'
import { useState } from 'react'
/**
* React hook to store and update the document.
*
* @remarks If you just need an initial document value, use {@link buildEmptyDocument} instead.
*
* @param initialDocument - The initial value.
* @public
*/
export function useDocument(initialDocument: Document = buildEmptyDocument()) {
return useState(initialDocument)
}
<file_sep>/types/typer.d.ts
/**
*
* Typeskill, the Operational-Transform Based (React) Native Rich Text library.
*
* @remarks
*
* **Introduction**
*
* The library exposes:
*
* - The {@link (Typer:class)} component, a support for editing {@link (Document:type)};
* - The {@link (Print:type)} component, a display for {@link (Document:type)};
* - The {@link (Toolbar:class)} component, which permits text transforms on current selection.
*
* **Controlled components**
*
* {@link (Typer:class)} and {@link (Print:type)} components are [controlled components](https://reactjs.org/docs/forms.html#controlled-components).
* You need to pass them a {@link Document | `document`} prop which you can initialize with {@link buildEmptyDocument}.
*
* **Triggering actions from external controls**
*
* A {@link (Bridge:interface)} instance must be shared between a {@link (Typer:class)} and any control component such as {@link (Toolbar:class)}.
* The {@link (Bridge:interface)} instance can be instantiated with {@link buildBridge}.
* Actions can be triggered with the help of the object returned by {@link (Bridge:interface).getControlEventDomain}.
*
* Such actions include:
*
* - inserting media content;
* - (un)setting text attributes (bold, italic).
*
* Selection change events can also be listened to with `add...Listener` methods.
* {@link (Bridge:interface).release} must be call from the component holding a reference to the {@link (Bridge:interface)} instance,
* during `componentWillUnmount` hook.
*
* @packageDocumentation
*/
/// <reference types="react" />
import { Component } from 'react';
import { ComponentType } from 'react';
import { FunctionComponent } from 'react';
import { ScrollViewProps } from 'react-native';
import { StyleProp } from 'react-native';
import { TextStyle } from 'react-native';
import { ViewStyle } from 'react-native';
/**
* A set of definitions for {@link GenericOp} attributes.
*
* @public
*/
export declare namespace Attributes {
/**
* Possible values for a text transform.
*
* @public
*/
export type TextValue = boolean | string | number | null;
/**
* An attribute value.
*
* @public
*/
export type GenericValue = object | TextValue | undefined;
/**
* A set of attributes applying to a {@link GenericOp}.
*
* @public
*/
export interface Map {
readonly [k: string]: GenericValue;
}
/**
* A special text attribute value applied to a whole line.
*
* @remarks
*
* There can be only one text line type attribute active at once.
*
* @public
*/
export type LineType = 'normal' | 'quoted';
}
/**
* An operation referring to a block.
*
* @public
*/
export declare interface BlockOp<T extends object> extends GenericOp {
/**
* {@inheritdoc GenericOp.insert}
*/
readonly insert: T;
/**
* {@inheritdoc GenericOp.attributes}
*/
readonly attributes?: Attributes.Map;
}
/**
* A set of definitions related to the {@link (Bridge:interface)} interface.
*
* @public
*/
export declare namespace Bridge {
/**
* An event which signals the intent to modify the content touched by current selection.
*/
export type ControlEvent = 'APPLY_ATTRIBUTES_TO_SELECTION' | 'INSERT_OR_REPLACE_AT_SELECTION';
/**
* Block content to insert.
*/
export interface ImageElement<Source> {
type: 'image';
description: Images.Description<Source>;
}
export interface TextElement {
type: 'text';
content: string;
}
/**
* Content to insert.
*/
export type Element<ImageSource> = ImageElement<ImageSource> | TextElement;
/**
* Listener to selected text attributes changes.
*/
export type SelectedAttributesChangeListener = (selectedAttributes: Attributes.Map) => void;
/**
* Listener to attribute overrides.
*
*/
export type AttributesOverrideListener = (attributeName: string, attributeValue: Attributes.GenericValue) => void;
/**
* Listener to line type overrides.
*
*/
export type LineTypeOverrideListener = (lineType: Attributes.LineType) => void;
/**
*
* @internal
*/
export type InsertOrReplaceAtSelectionListener<ImageSource> = <D extends {}>(element: Element<ImageSource>) => void;
/**
* An object representing an area of events happening by the mean of external controls.
*
* @remarks
*
* This object exposes methods to trigger such events, and react to internal events.
*/
export interface ControlEventDomain<ImageSource> {
/**
* Insert an element at cursor or replace if selection exists.
*
* @internal
*/
insertOrReplaceAtSelection: (element: Element<ImageSource>) => void;
/**
* Switch the given attribute's value depending on the current selection.
*
* @param attributeName - The name of the attribute to edit.
* @param attributeValue - The value of the attribute to edit. Assigning `null` clears any former truthy value.
*/
applyTextTransformToSelection: (attributeName: string, attributeValue: Attributes.TextValue) => void;
}
/**
* An object representing an area of events happening inside the {@link (Typer:class)}.
*
* @privateRemarks
*
* This object exposes methods to trigger such events, and react to external events.
*
* @internal
*/
export interface SheetEventDomain<ImageSource> {
/**
* Listen to text attributes alterations in selection.
*/
addApplyTextTransformToSelectionListener: (owner: object, listener: AttributesOverrideListener) => void;
/**
* Listen to insertions of text or blocks at selection.
*/
addInsertOrReplaceAtSelectionListener: (owner: object, listener: InsertOrReplaceAtSelectionListener<ImageSource>) => void;
/**
* Dereference all listeners registered for this owner.
*/
release: (owner: object) => void;
}
}
/**
* An abstraction responsible for event dispatching between the {@link (Typer:class)} and external controls.
*
* @remarks It also provide a uniform access to custom rendering logic.
*
* @internalRemarks
*
* We are only exporting the type to force consumers to use the build function.
*
* @public
*/
export declare interface Bridge<ImageSource> {
/**
* Get {@link (Bridge:namespace).SheetEventDomain | sheetEventDom}.
*
* @internal
*/
getSheetEventDomain: () => Bridge.SheetEventDomain<ImageSource>;
/**
* Get this bridge {@link (Bridge:namespace).ControlEventDomain}.
*
* @remarks
*
* The returned object can be used to react from and trigger {@link (Typer:class)} events.
*/
getControlEventDomain: () => Bridge.ControlEventDomain<ImageSource>;
/**
* End of the bridge's lifecycle.
*
* @remarks
*
* One would typically call this method during `componentWillUnmout` hook.
*/
release: () => void;
}
export declare const Bridge: {};
/**
* Build a bridge instance.
*
* @public
*/
export declare function buildBridge<ImageSource = Images.StandardSource>(): Bridge<ImageSource>;
/**
* Build an empty document.
*
* @public
*/
export declare function buildEmptyDocument(): Document;
/**
* Utility function to build {@link (Toolbar:class)} controls from {@link https://www.npmjs.com/package/react-native-vector-icons | react-native-vector-icons}.
*
* @param IconComponent - The icon {@link react#ComponentType} such as `MaterialCommunityIcons`
* @param actionType - The control action performed when this control is actionated.
* @param name - The name of the icon within the `IconComponent` set.
*
* @returns An object describing this control.
*
* @public
*/
export declare function buildVectorIconControlSpec<A extends GenericControlAction, T extends Toolbar.VectorIconMinimalProps>(IconComponent: ComponentType<T & Toolbar.TextControlMinimalIconProps>, actionType: A, name: string, options?: Pick<Toolbar.GenericControlSpec<A, T>, 'actionOptions' | 'iconProps'>): Toolbar.GenericControlSpec<A, T>;
/**
* Clone a peace of {@link Document | document}.
*
* @param content - The content to clone
*
* @public
*/
export declare function cloneDocument(content: Document): Document;
/**
* Constant used within a {@link (Toolbar:namespace).Layout} to denote a separator.
*
* @public
*/
export declare const CONTROL_SEPARATOR: unique symbol;
/**
* @public
*/
export declare const defaultTextTransforms: Transforms.GenericSpec<Attributes.TextValue, 'text'>[];
/**
* A serializable object representing rich content.
*
* @public
*/
export declare interface Document {
/**
* A list of operations as per deltajs definition.
*/
readonly ops: GenericOp[];
/**
* A contiguous range of selectable items.
*/
readonly currentSelection: SelectionShape;
/**
* The attributes encompassed by {@link Document.currentSelection} or the attributes at cursor.
* `null` values represent attributes to be removed.
*/
readonly selectedTextAttributes: Attributes.Map;
/**
* The diff ops which were used to produce current ops by combining previous ops.
*/
readonly lastDiff: GenericOp[];
/**
* The document shape versionning.
*
* @remarks This attribute might only change between major releases, and is intended to very rarely change.
* It is also guaranteed that if there were any, the library would offer tools to handle schema migrations.
*
*/
readonly schemaVersion: number;
}
/**
* Actions which can be triggered with the {@link (Toolbar:class)} component to alter document.
*
* @public
*/
export declare enum DocumentControlAction {
/**
* Switch bold formatting in the selected text.
*/
SELECT_TEXT_BOLD = 0,
/**
* Switch italic formatting in the selected text.
*/
SELECT_TEXT_ITALIC = 1,
/**
* Switch underline formatting in the selected text.
*/
SELECT_TEXT_UNDERLINE = 2,
/**
* Switch strikethrough formatting in the selected text.
*/
SELECT_TEXT_STRIKETHROUGH = 3,
/**
* Insert an image at selection.
*/
INSERT_IMAGE_AT_SELECTION = 4
}
/**
* A generic interface for components displaying {@link Document | document}.
*
* @remarks There are 3 styles props:
*
* ```
* +------------------------------+
* | style (ScrollView) |
* | +--------------------------+ |
* | | contentContainerStyle | |
* | | +----------------------+ | |
* | | | documentStyle | | |
* | | | | | |
* ```
*
* @public
*/
export declare interface DocumentRendererProps<ImageSource> {
/**
* The {@link Document | document} to display.
*/
document: Document;
/**
* The image component to render.
*
* @remarks The component MUST fit within the passed {@link Images.ComponentProps.printDimensions} prop.
*/
ImageComponent?: Images.Component<ImageSource>;
/**
* A collection of text transforms.
*/
textTransformSpecs?: Transforms.Specs<'text'>;
/**
* Default text style.
*/
textStyle?: StyleProp<TextStyle>;
/**
* The max width of a media block.
*
* @remarks If the container width is smaller than this width, the first will be used to frame media.
*/
maxMediaBlockWidth?: number;
/**
* The max height of a media block.
*/
maxMediaBlockHeight?: number;
/**
* The spacing unit.
*
* @remarks It is used:
*
* - Between two adjacent blocks;
* - Between container and document print.
*/
spacing?: number;
/**
* Component style.
*/
style?: StyleProp<ViewStyle>;
/**
* Style applied to the content container.
*
* @remarks This prop MUST NOT contain padding or margin rules. Such spacing rules will be zero-ed.
* Instead, {@link DocumentRendererProps.spacing | `spacing`} prop will add spacing between the edge of the scrollview and container.
*/
contentContainerStyle?: StyleProp<ViewStyle>;
/**
* Styles applied to the closest view encompassing rich content.
*
* @remarks This prop MUST NOT contain padding rules. Such padding rules will be zero-ed. Instead, use margin rules.
*/
documentStyle?: StyleProp<ViewStyle>;
/**
* Any {@link react-native#ScrollView} props you wish to pass.
*
* @remarks
*
* - Do not pass `style` prop as it will be overriden by this component `style` props;
* - Do not pass `keyboardShouldPersistTaps` because it will be forced to `"always"`.
*/
scrollViewProps?: ScrollViewProps;
/**
* The component to replace RN default {@link react-native#ScrollView}.
*/
ScrollView?: ComponentType<any>;
}
/**
* @public
*/
export declare interface FocusableInput {
/**
* Focus programatically.
*/
focus: () => void;
}
/**
* Any actions which can be triggered with the {@link (Toolbar:class)} component.
*
* @public
*/
export declare type GenericControlAction = string | symbol | number;
/**
* An atomic operation representing changes to a document.
*
* @remarks
*
* This interface is a redefinition of {@link quilljs-delta#Op}.
*
* @public
*/
export declare interface GenericOp {
/**
* A representation of inserted content.
*/
readonly insert?: string | object;
/**
* A delete operation.
*
* @internal
*/
readonly delete?: number;
/**
* A retain operation
*
* @internal
*/
readonly retain?: number;
/**
* A set of attributes describing properties of the content.
*/
readonly attributes?: Attributes.Map;
}
/**
* A generic interface for instances describing rich content.
*
* @public
*/
export declare interface GenericRichContent {
/**
* An array of operations.
*/
readonly ops: GenericOp[];
/**
* @returns The length of the underlying rich text representation.
* This length represents the number of cursor positions in the document.
*/
readonly length: () => number;
}
/**
* A description of an image to be persisted in the document.
*
* @public
*/
export declare interface ImageKind<Source> extends Images.Description<Source> {
kind: 'image';
}
/**
* An operation referring to an image.
*
* @public
*/
export declare type ImageOp<Source> = BlockOp<ImageKind<Source>>;
/**
* A set of definitions related to images.
*
* @public
*/
export declare namespace Images {
export interface StandardSource {
uri: string;
}
export interface Description<Source> {
readonly source: Source;
readonly width: number;
readonly height: number;
}
export interface Dimensions {
readonly width: number;
readonly height: number;
}
export type Component<Source> = ComponentType<ComponentProps<Source>>;
export interface ComponentProps<Source> {
/**
* The dimensions this component MUST occupy.
*/
readonly printDimensions: Dimensions;
/**
* The image description.
*/
readonly description: Description<Source>;
}
/**
* An object used to locate and render images.
*/
export interface Hooks<Source> {
/**
* Callback fired when an image has been successfully inserted.
*/
readonly onImageAddedEvent?: (description: Description<Source>) => void;
/**
* Callback fired when an image has been removed.
*/
readonly onImageRemovedEvent?: (description: Description<Source>) => void;
}
}
/**
* A set of definitions relative to {@link (Print:class)} component.
* @public
*/
export declare namespace Print {
/**
* {@link (Print:class)} properties.
*/
export type Props<ImageSource> = DocumentRendererProps<ImageSource>;
}
/**
* A component solely responsible for viewing {@link Document | document}.
*
* @public
*
*/
export declare class Print<ImageSource = Images.StandardSource> extends Component<Print.Props<ImageSource>> {
}
/**
* A serializable object representing a selection of items in the {@link (Typer:class)}.
*
* @public
*/
export declare interface SelectionShape {
/**
* **Inclusive** first item index in selection.
*/
readonly start: number;
/**
* **Exclusive** last item index in selection.
*/
readonly end: number;
}
/**
* An operation referring to text.
*
* @public
*/
export declare interface TextOp extends GenericOp {
/**
* {@inheritdoc GenericOp.insert}
*/
readonly insert?: string;
/**
* {@inheritdoc GenericOp.attributes}
*/
readonly attributes?: Attributes.Map;
}
/**
* A set of definitions related to the {@link (Toolbar:class)} component.
*
* @public
*/
export declare namespace Toolbar {
export interface GenericControlSpec<A extends GenericControlAction, T extends object> {
/**
* The react {@link react#ComponentType} representing the rendered icon.
*
* @remarks
*
* - This icon component is expected to at least support {@link (Toolbar:namespace).TextControlMinimalIconProps}.
* - The component will optionally receive `iconProps`.
* - The icon should have a transparent background.
*/
IconComponent: ComponentType<TextControlMinimalIconProps & T>;
/**
* The action performed when the control is actionated.
*/
actionType: A;
/**
* Any value to be passed to action hook.
*/
actionOptions?: any;
/**
* The props passed to `IconComponent`
*/
iconProps?: T extends Toolbar.VectorIconMinimalProps ? Toolbar.VectorIconMinimalProps : Partial<T>;
}
/**
* An object describing a control which alter the document.
*/
export type DocumentControlSpec<T extends object = {}> = GenericControlSpec<DocumentControlAction, T>;
/**
* Declaratively describes the layout of the {@link (Toolbar:class)} component.
*/
export type Layout = (DocumentControlSpec<any> | typeof CONTROL_SEPARATOR | GenericControlSpec<any, any>)[];
export interface IconButtonSpecs {
/**
* Button background when a control is not in active state.
*/
inactiveButtonBackgroundColor: string;
/**
* Button icon color when a control is not in active state.
*/
inactiveButtonColor: string;
/**
* Button icon color when a control is in active state.
*/
activeButtonBackgroundColor: string;
/**
* Button background when a control is in active state.
*/
activeButtonColor: string;
/**
* Icon size.
*/
iconSize: number;
}
/**
* Props of the {@link (Toolbar:class)} component.
*/
export interface Props<ImageSource, ImageOptions = any> extends Partial<IconButtonSpecs> {
/**
* The instance to be shared with the {@link (Typer:class)}.
*/
bridge: Bridge<ImageSource>;
/**
* The {@link Document | document}.
*/
document: Document;
/**
* An array describing the resulting layout of this component.
*/
layout: Layout;
/**
* An async function that returns a promise resolving to the {@link Images.Description | description} of an image.
*
* @remarks The corresponding {@link (Toolbar:namespace).GenericControlSpec.actionOptions} will be passed to this function.
*/
pickOneImage?: (options?: ImageOptions) => Promise<Images.Description<ImageSource>>;
/**
* A callback fired when pressing a custom control.
*/
onPressCustomControl?: <A extends GenericControlAction>(actionType: A, actionOptions?: any) => void;
/**
* A callback fired when inserting an image results in an error.
*/
onInsertImageError?: (e: Error) => void;
/**
* The color of the separator.
*
* @remarks
*
* A separator can be defined by inserting {@link CONTROL_SEPARATOR} constant to the `layout` prop.
*/
separatorColor?: string;
/**
* Style of the root component.
*/
style?: StyleProp<ViewStyle>;
/**
* Style of the container component encompassing all controls.
*/
contentContainerStyle?: StyleProp<ViewStyle>;
/**
* The space between two buttons.
*/
buttonSpacing?: number;
}
/**
* Props for {@link (Toolbar:class).IconButton} component.
*/
export interface IconButtonProps extends IconButtonSpecs {
selected: boolean;
IconComponent: ComponentType<TextControlMinimalIconProps>;
onPress?: () => void;
style?: StyleProp<ViewStyle>;
iconProps?: object;
}
/**
* The props passed to every icon {@link react#ComponentType}.
*/
export interface TextControlMinimalIconProps {
/**
* Icon color.
*
* @remarks
*
* The color varies depending on the active state.
* Will receive {@link (Toolbar:namespace).IconButtonSpecs.inactiveButtonColor} when not active and
* {@link (Toolbar:namespace).IconButtonSpecs.activeButtonColor} when active.
*/
color?: string;
/**
* Icon size.
*/
size?: number;
}
/**
* The shape of expected props to an icon from {@link https://www.npmjs.com/package/react-native-vector-icons | react-native-vector-icons}.
*/
export interface VectorIconMinimalProps {
/**
* Icon name.
*/
name: string;
}
}
/**
* A component to let user control the {@link (Typer:class)} through a {@link (Bridge:interface)}.
*
* @public
*/
export declare class Toolbar<ImageSource = Images.StandardSource, ImageOptions = any> extends Component<Toolbar.Props<ImageSource, ImageOptions>> {
/**
* A button component displayed inside a toolbar.
*/
IconButton: FunctionComponent<Toolbar.IconButtonProps>;
}
/**
* A set of definitions related to text and arbitrary content transforms.
*
* @public
*/
export declare namespace Transforms {
/**
* The target type of a transform.
*/
export type TargetType = 'block' | 'text';
/**
* A {@link (Transforms:namespace).GenericSpec} which `attributeActiveValue` is `true`.
*
* @public
*/
export type BoolSpec<T extends TargetType = 'block'> = GenericSpec<true, T>;
/**
* A mapping of attribute names with their corresponding transformation description.
*
* @internal
*/
export interface Dict<A extends Attributes.GenericValue, T extends TargetType> {
[attributeName: string]: GenericSpec<A, T>[];
}
/**
* Default text attributes names.
*
* @public
*/
export type TextAttributeName = 'bold' | 'italic' | 'textDecoration';
/**
* Description of a generic transform.
*
* @public
*/
export interface GenericSpec<A extends Attributes.GenericValue, T extends TargetType> {
/**
* The name of the attribute.
*
* @remarks
*
* Multiple {@link (Transforms:namespace).GenericSpec} can share the same `attributeName`.
*/
attributeName: string;
/**
* The value of the attribute when this transform is active.
*/
activeAttributeValue: A;
/**
* The style applied to the target block when this transform is active.
*/
activeStyle: T extends 'block' ? ViewStyle : TextStyle;
}
export type Specs<T extends 'text' | 'block' = 'text'> = GenericSpec<Attributes.TextValue, T>[];
}
/**
* An entity which responsibility is to provide styles from text transforms.
*
* @public
*/
export declare class Transforms {
private textTransformsDict;
constructor(textTransformSpecs: Transforms.GenericSpec<Attributes.TextValue, 'text'>[]);
/**
* Produce react styles from a text operation.
*
* @param op - text op.
*
* @internal
*/
getStylesFromOp(op: TextOp): StyleProp<TextStyle>;
}
/**
* A set of definitions relative to {@link (Typer:class)} component.
*
* @public
*/
export declare namespace Typer {
/**
* {@link (Typer:class)} properties.
*/
export interface Props<ImageSource> extends DocumentRendererProps<ImageSource> {
/**
* The {@link (Bridge:interface)} instance.
*
* @remarks This property MUST NOT be changed after instantiation.
*/
bridge: Bridge<ImageSource>;
/**
* Callbacks on image insertion and deletion.
*/
imageHooks?: Images.Hooks<ImageSource>;
/**
* Handler to receive {@link Document| document} updates.
*
*/
onDocumentUpdate?: (nextDocumentContent: Document) => void;
/**
* Disable edition.
*/
readonly?: boolean;
/**
* Customize the color of image controls upon activation.
*/
underlayColor?: string;
/**
* In debug mode, active block will be highlighted.
*/
debug?: boolean;
/**
* Disable selection overrides.
*
* @remarks
*
* In some instances, the typer will override active text selections. This will happen when user press the edge of a media block:
* the selection will be overriden in order to select the preceding or following text input closest selectable unit.
*
* However, some versions of React Native have an Android bug which can trigger a `setSpan` error. If such errors occur, you should disable selection overrides.
* {@link https://github.com/facebook/react-native/issues/25265}
* {@link https://github.com/facebook/react-native/issues/17236}
* {@link https://github.com/facebook/react-native/issues/18316}
*/
disableSelectionOverrides?: boolean;
/**
* By default, when user select text and apply transforms, the selection will be overriden to stay the same and allow user to apply multiple transforms.
* This is the normal behavior on iOS, but not on Android. Typeksill will by default enforce this behavior on Android too.
* However, when this prop is set to `true`, such behavior will be prevented on Android.
*/
androidDisableMultipleAttributeEdits?: boolean;
}
}
/**
* A component solely responsible for editing {@link Document | document}.
*
* @remarks This component is [controlled](https://reactjs.org/docs/forms.html#controlled-components).
*
* You MUST provide:
*
* - A {@link Document | `document`} prop to render contents. You can initialize it with {@link buildEmptyDocument};
* - A {@link (Bridge:interface) | `bridge` } prop to share document-related events with external controls;
*
* You SHOULD provide:
*
* - A `onDocumentUpdate` prop to update its state.
*
* @public
*
*/
export declare class Typer<ImageSource = Images.StandardSource> extends Component<Typer.Props<ImageSource>> implements FocusableInput {
focus: () => void;
}
/**
* React hook which returns a bridge.
*
* @remarks One bridge instance should exist for one document renderer instance.
* @param deps - A list of values which should trigger, on change, the creation of a new {@link (Bridge:interface)} instance.
* @public
*/
export declare function useBridge<ImageSource = Images.StandardSource>(deps?: unknown[]): Bridge<ImageSource>;
/**
* React hook to store and update the document.
*
* @remarks If you just need an initial document value, use {@link buildEmptyDocument} instead.
*
* @param initialDocument - The initial value.
* @public
*/
export declare function useDocument(initialDocument?: Document): [Document, import("react").Dispatch<import("react").SetStateAction<Document>>];
export { }
<file_sep>/README.md
<h1 align="center">
<code>
@typeskill/typer
</code>
</h1>
<p align="center">
<em>
Typeskill, the Operational-Transform Based (React) Native Rich Text Library.
</em>
</p>
<p align="center">
<a href="https://www.npmjs.com/package/@typeskill/typer" alt="Npm Version">
<img src="https://img.shields.io/npm/v/@typeskill/typer.svg" /></a>
<img src="https://img.shields.io/badge/platforms-android%20|%20ios%20|%20windows-lightgrey.svg" />
<img src="https://img.shields.io/npm/l/@typeskill/typer.svg"/>
<a href="https://github.com/typeskill/typer/issues?q=is%3Aissue+is%3Aopen+label%3A%22scheduled+feature%22" >
<img src="https://img.shields.io/github/issues-raw/typeskill/typer/scheduled%20feature.svg?label=scheduled%20feature&colorB=125bba" alt="scheduled features" />
</a>
</p>
<p align="center">
<a href="https://circleci.com/gh/typeskill/typer">
<img src="https://circleci.com/gh/typeskill/typer.svg?style=shield" alt="Circle CI" />
</a>
<a href="https://codecov.io/gh/typeskill/typer">
<img src="https://codecov.io/gh/typeskill/typer/branch/master/graph/badge.svg" alt="Code coverage">
</a>
<a href="https://github.com/typeskill/typer/issues?q=is%3Aissue+is%3Aopen+label%3Abug">
<img src="https://img.shields.io/github/issues-raw/typeskill/typer/bug.svg?label=open%20bugs" alt="open bugs">
</a>
<img alt="Greenkeeper badge" src="https://badges.greenkeeper.io/typeskill/typer.svg">
<a href="https://snyk.io/test/github/typeskill/typer">
<img alt="vulnerabilities" src="https://snyk.io/test/github/typeskill/typer/badge.svg">
</a>
</p>
<p align="center">
<code>
npm install --save @typeskill/typer
</code>
</p>
<p align="center">
<img width="400" src="https://raw.githubusercontent.com/typeskill/typeskill/HEAD/images/screenshot.png" alt="Typeskill screenshot">
</p>
<p align="center">
<a href="https://expo.io/@jsamr/typeskill-showcase">
<strong>Give it a try on Expo</strong>
</a>
<br/><br/>
<a href="https://expo.io/@jsamr/typeskill-showcase">
<img src="https://raw.githubusercontent.com/typeskill/typeskill/HEAD/images/qr-showcase.png" alt="Expo QR code">
</a>
<br/>
<a href="#trying-locally">You can also run it locally in seconds</a>
</p>
## Features & design principles
### Design
- Extensively **modular** architecture: Typeskill handles the logic, you chose the layout;
- No bloated/clumsy `WebView` ; this library only relies on (React) **Native** components;
- Fully [controlled components](https://reactjs.org/docs/forms.html#controlled-components);
- Based on the reliable [Delta](https://github.com/quilljs/delta) **operational transform** library from [quilljs](https://github.com/quilljs).
### Features
- Support for **arbitrary embedded contents**;
- Support for **arbitrary controllers** with the `Bridge` class;
- JSON-**serializable** rich content.
<a name="trying-locally" />
## Trying locally
*Prerequisite: you must have `npm` and `expo-cli` globally installed*
``` bash
git clone https://github.com/typeskill/examples/tree/master
cd examples/expo-showcase
npm install
expo start
```
## Architecture & example
### Introduction
The library exposes two components to render documents:
- The `Typer` component is responsible for **editing** a document;
- The `Print` component is responsible for **displaying** a document.
### Definitions
- A *document* is a JSON-serializable object describing rich content;
- A *document renderer* is any controlled component which renders a document—i.e. `Typer` or `Print`;
- The *master component* is referred to as the component containing and controlling the document renderer;
- A *document control* is any controlled component owned by the master component capable of altering the document—i.e. `Typer` or `Toolbar`;
- An *external [document] control* is any document control which is not a document renderer—i.e. `Toolbar` or any custom control.
### The shape of a Document
A document is an object describing rich content and the current selection. Its `op` field is an array of operational transforms implemented with [delta library](https://github.com/quilljs/delta). Its `schemaVersion` guarantees retro-compatibility in the future and, if needed, utilities to convert from one version to the other.
To explore the structure in seconds, the easiest way is with the debugger: [`@typeskill/debugger`](https://github.com/typeskill/debugger).
### Controlled components
Document renderers and controls are **[controlled components](https://reactjs.org/docs/forms.html#controlled-components)**, which means you need to define how to store the state from a master component, or through a store architecture such as a Redux. [You can study `Editor.tsx`, a minimal example master component.](https://github.com/typeskill/examples/blob/master/expo-minimal/src/Editor.tsx)
### A domain of shared events
Document renderers need an invariant `Bridge` instance prop.
The bridge has two responsibilities:
- To convey actions such as *insert an image at selection* or *change text attributes in selection* from external controls;
- To notify selection attributes changes to external controls.
A `Bridge` instance must be hold by the master component, and can be shared with any external control such as `Toolbar` to operate on the document.
**Remarks**
- The `Bridge` constructor **is not exposed**. You must consume the `buildBridge` function or `useBridge` hook instead;
- To grasp how the bridge is interfaced with the `Toolbar` component, you can [read its implementation](src/components/Toolbar.tsx).
### Robustness
This decoupled design has the following advantages:
- the logic can be tested independently from React components;
- the library consumer can integrate the library to fit its graphical and architectural design;
- support for arbitrary content in the future.
### Minimal example
Bellow is a simplified snippet [from the minimal expo example](https://github.com/typeskill/examples/tree/master/expo-minimal) to show you how the `Toolbar` can be interfaced with the `Typer` component.
You need a linked `react-native-vector-icons` or `@expo/vector-icons` if you are on expo to make this example work.
```jsx
import React from 'react';
import { View } from 'react-native';
import {
Typer,
Toolbar,
DocumentControlAction,
buildVectorIconControlSpec,
useBridge,
useDocument,
} from '@typeskill/typer';
/** NON EXPO **/
import { MaterialCommunityIcons } from 'react-native-vector-icons/MaterialCommunityIcons';
/** EXPO **/
// import { MaterialCommunityIcons } from '@expo/vector-icons'
function buildMaterialControlSpec(actionType, name) {
return buildVectorIconControlSpec(MaterialCommunityIcons, actionType, name);
}
const toolbarLayout = [
buildMaterialControlSpec(
DocumentControlAction.SELECT_TEXT_BOLD,
'format-bold',
),
buildMaterialControlSpec(
DocumentControlAction.SELECT_TEXT_ITALIC,
'format-italic',
),
buildMaterialControlSpec(
DocumentControlAction.SELECT_TEXT_UNDERLINE,
'format-underline',
),
buildMaterialControlSpec(
DocumentControlAction.SELECT_TEXT_STRIKETHROUGH,
'format-strikethrough-variant',
),
];
export function Editor() {
const [document, setDocument] = useDocument();
const bridge = useBridge();
return (
<View style={{ flex: 1 }}>
<Typer
document={document}
onDocumentUpdate={setDocument}
bridge={bridge}
maxMediaBlockHeight={300}
/>
<Toolbar document={document} layout={toolbarLayout} bridge={bridge} />
</View>
);
}
```
### API Contract
You need to comply with this contract to avoid bugs:
- The `Bridge` instance should be instantiated by the master component with `buildBridge`, during mount or with `useBridge` hook;
- There should be exactly one `Bridge` instance for one document renderer.
## API Reference
[**Typescript definitions**](types/typer.d.ts) provide an exhaustive and curated documentation reference. The comments are [100% compliant with tsdoc](https://github.com/microsoft/tsdoc) and generated with Microsoft famous [API Extractor](https://api-extractor.com/) utility. [**These definitions follow semantic versioning.**](https://semver.org/)
Please note that `props` definitions are namespaced. For example, if you are looking at `Toolbar` component definitions, you should look for `Props` definition inside `Toolbar` namespace.
## Inspecting and reporting bugs
[`@typeskill/debugger`](https://github.com/typeskill/debugger) is a tool to inspect and reproduce bugs. If you witness a bug, please try a reproduction on the debugger prior to reporting it.
## Customizing
### Integrating your image picker
Typeskill won't chose a picker on your behalf, as it would break its commitment to modular design.
You can check [`Editor.tsx` component](https://github.com/typeskill/examples/blob/master/expo-showcase/src/Editor.tsx) from [the showcase expo example](https://github.com/typeskill/examples/tree/master/expo-showcase) to see how to integrate your image picker.
<file_sep>/src/core/__tests__/Transforms-test.ts
import { Transforms, textTransformListToDict } from '@core/Transforms'
import {
defaultTextTransforms,
boldTransform,
italicTransform,
underlineTransform,
strikethroughTransform,
} from '@core/Transforms'
describe('@core/TextTransformsRegistry', () => {
describe('textTransformListToDict', () => {
it('should transform list to dictionnary', () => {
const dict = textTransformListToDict(defaultTextTransforms)
expect(dict).toEqual({
bold: [boldTransform],
italic: [italicTransform],
textDecoration: [underlineTransform, strikethroughTransform],
})
})
})
describe('getStylesFromOp', () => {
it('should merge styles from OP', () => {
const registry = new Transforms(defaultTextTransforms)
expect(
registry.getStylesFromOp({
insert: 'A',
attributes: {
textDecoration: 'underline',
bold: true,
italic: true,
},
}),
).toEqual(
expect.arrayContaining([
{
textDecorationStyle: 'solid',
textDecorationLine: 'underline',
},
{
fontWeight: 'bold',
},
{
fontStyle: 'italic',
},
]),
)
})
})
})
<file_sep>/src/delta/DocumentDeltaAtomicUpdate.ts
import { Selection } from './Selection'
import { DocumentDelta } from './DocumentDelta'
import Delta from 'quill-delta'
export class DocumentDeltaAtomicUpdate {
private readonly _selectionAfterChange: Selection
public readonly delta: DocumentDelta
public readonly diff: Delta
public constructor(delta: DocumentDelta, diff: Delta, selectionAfterChange: Selection) {
this._selectionAfterChange = selectionAfterChange
this.delta = delta
this.diff = diff
}
public get selectionAfterChange() {
return this._selectionAfterChange
}
}
| 47b6d2561ce6065a0190f8ce699d228afe409939 | [
"Markdown",
"TypeScript"
] | 50 | TypeScript | decisionnguyen/typer | 55a6d51211d1903eca27857dbd723db686fccd74 | a9bc6a9d2716e56cdd9a8c89b8c43dbd282bac6d |
refs/heads/master | <file_sep># phone-musice-pro<file_sep>var gulp = require('gulp');
var htmlclean = require('gulp-htmlclean');
//压缩js
var uglify = require('gulp-uglify');
//去掉调试
var debug = require('gulp-strip-debug');
//压缩图片
var imagemin = require('gulp-imagemin');
//less解析
var less = require('gulp-less');
//css压缩
var cleancss = require('gulp-clean-css')
//css3属性标注
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
//链接服务器
var connect = require('gulp-connect');
process.env.NODE_ENV = 'development'
var Dev = process.env.NODE_ENV == 'development'
console.log(process.env.NODE_ENV);
var Ourl = {
src:'./src',
dist:'./dist',
img:'./img',
}
// 文件加载输出
gulp.task('html',function(){
var page = gulp.src(Ourl.src + "/html/*")
.pipe(connect.reload())
if(!Dev){
page.pipe(htmlclean())
}
page.pipe(gulp.dest(Ourl.dist + "/html"));
})
gulp.task('css',function(){
var page = gulp.src(Ourl.src + "/css/*")
.pipe(connect.reload())
.pipe(less())
.pipe(postcss([autoprefixer()]))
if(!Dev){
page.pipe(cleancss())
}
page.pipe(gulp.dest(Ourl.dist + "/css"));
})
gulp.task('img',function(){
gulp.src(Ourl.src + "/img/*")
.pipe(imagemin())
.pipe(gulp.dest(Ourl.dist + "/img"));
})
gulp.task('js',function(){
var page = gulp.src(Ourl.src + "/js/*")
.pipe(connect.reload())
if(!Dev){
page.pipe(uglify()).pipe(debug())
}
page.pipe(gulp.dest(Ourl.dist + "/js"));
})
//创建服务连接
gulp.task('connect',function(){
connect.server({
port:8088,
livereload:true,
})
})
//创建实时监听任务
gulp.task('watch',function(){
gulp.watch(Ourl.src + '/html/*',['html']);
gulp.watch(Ourl.src + '/css/*',['css']);
gulp.watch(Ourl.src + '/js/*',['js']);
// gulp.watch(Ourl.src + '/*',['html','js','css'])
})
//任务流启动
gulp.task('default',['html','js','css','img','connect','watch']);<file_sep>/* 1 获取数据
2 渲染页面
3 绑定事件
4 控制播放
*/
var nowIndex = 0,
len,
datalist,
changepro = false,
audio = player.audioManager;
// console.log(audio);
getData("../../mock/data.json");
function getData(url){
$.ajax({
// type:'GET',
url:url,
success:function(data){
len = data.length;
datalist = data;
audio.getaudio(data[0].audio);
player.render(data[0]);
player.pross.rendTime(0,data[0].duration);
bindEvent();
player.songList(data);
},
error:function(){
console.log('error')
}
})
}
function plays(){
audio.status == "pause" ? audio.play() : audio.pause();
audio.status == "pause" ? $('.play','.wrapper').removeClass('playing'): $('.play','.wrapper').addClass('playing');
}
function trun(){
if(audio.status == 'play'){
$('.song-showimg img','.wrapper').addClass('playing');
if(!audio.paused()){
$('.song-showimg img','.wrapper').css('animation-play-state','running');
}
}else if(audio.status == 'pause' && audio.paused()){
console.log('paused');
$('.song-showimg img','.wrapper').css('animation-play-state','paused');
}
}
function bindEvent(){
var curwidth = $('.pro','.wrapper').width(),
starttime = 0,
pro = 0,
left = $('.pro','.wrapper').offset().left;
$('.pro-btn','.wrapper').on('touchstart',function(e){
if(audio.status == "play"){
$('.play','.wrapper').trigger('click')
}
})
$('.pro-btn','.wrapper').on('touchmove',function(e){
// strat = e.target.offsetLeft;
var move = e.touches[0].clientX - left;
player.pross.initstart();
pro = parseInt((move/ curwidth)*100);
if(pro <= 100 && pro >=0){
starttime = parseInt((pro/100)*datalist[nowIndex].duration) ;
}
player.pross.changePross(pro, starttime);
})
$('.pro-btn','.wrapper').on('touchend',function(e){
$('.play','.wrapper').trigger('click');
})
$('.prev','.wrapper').on('click',function(){
nowIndex ? nowIndex -- : nowIndex = len -1 ;
player.render(datalist[nowIndex]);
audio.getaudio(datalist[nowIndex].audio);
player.pross.rendTime(0,datalist[nowIndex].duration);
starttime = pro = 0;
player.pross.initstart();
if(audio.status == 'play'){
$('.play','.wrapper').trigger('click')
setTimeout(function(){
trun();
},100);
}
});
$('.play','.wrapper').on('click',function(){
if(starttime){
starttime = player.pross.getstart() || starttime;
audio.audio.currentTime = starttime;
}
plays();
trun();
player.pross.changeAnimate(starttime, audio.status);
});
$('.next','.wrapper').on('click',function(){
nowIndex == len -1 ? nowIndex = 0 : nowIndex ++;
player.render(datalist[nowIndex]);
audio.getaudio(datalist[nowIndex].audio);
player.pross.rendTime(0,datalist[nowIndex].duration);
starttime = pro = 0;
player.pross.initstart();
if(audio.status == 'play'){
$('.play','.wrapper').trigger('click')
$('.play','.wrapper').trigger('click')
setTimeout(function(){
trun();
},100);
}
});
$('.like','.wrapper').on('click',function(){
datalist[nowIndex].isLike ? datalist[nowIndex].isLike = false : datalist[nowIndex].isLike = true;
datalist[nowIndex].isLike ? $('.like','.wrapper').addClass('liking'):$('.like','.wrapper').removeClass('liking');
})
$('.playlist','.wrapper').on('click',function(){
$('.songlist').toggleClass('show');
})
$('.songlist','.wrapper').on('click','li',function(){
// console.log($(this).attr('data-list'));
nowIndex = $(this).attr('data-list');
player.render(datalist[nowIndex]);
audio.getaudio(datalist[nowIndex].audio);
starttime = pro = 0;
player.pross.changePross(pro, starttime);
if(audio.status == 'play'){
$('.play','.wrapper').trigger('click')
$('.play','.wrapper').trigger('click')
setTimeout(function(){
trun();
},100);
}
})
$('.close','.wrapper').on('click',function(){
$('.songlist').removeClass('show');
})
}<file_sep>(function($,tar){
function songList(data){
var str = ``;
data.forEach(function(e,index){
str += `<li data-list=${index}>${e.song}</li>`
});
$('.songlist','.wrapper').append(str);
}
tar.songList = songList;
})(window.$,window.player || (window.player = {}))<file_sep>/* 1 初始化渲染页面 (歌曲图片 title)
2 绑定事件渲染(like ben)
*/
(function ($, tar){
function renderImg(url){
var img = new Image();
img.src = url;
img.onload = function(){
$(".song-showimg",'.wrapper').html(img);
tar.blurImg(img, $('body'))
};
}
function renderTitle(data){
$('.song-title','.wrapper').html(`<div class="song-name">${data.song}</div>
<div class="song-songer">${data.singer}</div>
<div class="song-album">${data.album}</div>`)
}
function renderLike(like){
like.isLike ? $('.like','.wrapper').addClass('liking'):$('.like','.wrapper').removeClass('liking');
}
tar.render = function (data){
renderImg(data.image);
renderTitle(data);
renderLike(data)
}
})(window.$,window.player || (window.player = {}))
<file_sep>(function($, tar){
var duration,
animationId = null,
start = 0;
function changeAnimate(alltime,status){
if(animationId && status == 'pause'){
cancelAnimationFrame(animationId);
}else if(status == 'play'){
alltime = alltime > start ? alltime: start;
// console.log(alltime,status,start);
startPross(alltime);
}
return;
}
function timeFormat(time){
var m = Math.floor(time/60);
var s = time - m*60;
m = m >= 10 ? '' + m : '0' + m ;
s = s >= 10 ? '' + s : '0' + s ;
return m + ':' + s;
}
function rendTime(start, end){
duration = end ;
$('.start').html(timeFormat(start));
$('.end').html(timeFormat(end));
}
function startPross(alltime){
var starttime = new Date().getTime();
function pross(){
// console.log(start);
if(alltime){
var curtime = new Date().getTime() + alltime*1000;
}else{
var curtime = new Date().getTime();
}
var pro = (curtime - starttime) / (duration*1000);
start = parseInt((curtime - starttime)/1000);
pro = parseInt(pro*100);
changePross(pro , start)
animationId = requestAnimationFrame(pross);
if(pro >=100){
// console.log(start)
start = 0;
$('.next','.wrapper').trigger('click');
}
}
pross();
}
function changePross(pro, start){
if(pro<100){
$('.pro-show').css('width',pro + '%');
}
// console.log(pro)
rendTime(start, duration);
}
tar.pross = {
// timeFormat,
// timeFormat,
changeAnimate,
rendTime,
startPross,
changePross,
initstart: function(){
start = 0;
},
getstart: function(){
return start;
}
}
}(window.$, window.player = player || {})) | 69e4c9a4b38ef4864066890ecaae711a9e2678a2 | [
"Markdown",
"JavaScript"
] | 6 | Markdown | Jhongtao/phone-musice-pro | 1f8c56c29f1b94c4b3df80a6c5477c9430816dda | e5e02175c7cc862bb9b646e2bafd7d901c219b4c |
refs/heads/master | <repo_name>mturch/fast-dates.js<file_sep>/test/fast-date.test.js
const { FastDate } = require('./../src/main')
describe('FastDate methods', () => {
it('FastDate:constructor() should behave like Date:constructor() method', () => {
let dateO = new Date().setSeconds(0, 0)
let dateN = new FastDate().setSeconds(0, 0)
expect(dateN).toBe(dateO)
dateO = new Date('2017-01-01')
dateN = new FastDate('2017-01-01')
expect(dateN.valueOf()).toEqual(dateO.valueOf())
dateO = new Date(2017, 1, 1)
dateN = new FastDate(2017, 1, 1)
expect(dateN.valueOf()).toEqual(dateO.valueOf())
})
it('FastDate:getDate() should behave like Date:getDate() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getDate()).toEqual(dateO.getDate())
})
it('FastDate:getDay() should behave like Date:getDay() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getDay()).toEqual(dateO.getDay())
})
it('FastDate:getFullYear() should behave like Date:getFullYear() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getFullYear()).toEqual(dateO.getFullYear())
})
it('FastDate:getHours() should behave like Date:getHours() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getHours()).toEqual(dateO.getHours())
})
it('FastDate:getMilliseconds() should behave like Date:getMilliseconds() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getMilliseconds()).toEqual(dateO.getMilliseconds())
})
it('FastDate:getMinutes() should behave like Date:getMinutes() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getMinutes()).toEqual(dateO.getMinutes())
})
it('FastDate:getMonth() should behave like Date:getMonth() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getMonth()).toEqual(dateO.getMonth())
})
it('FastDate:getSeconds() should behave like Date:getSeconds() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getSeconds()).toEqual(dateO.getSeconds())
})
it('FastDate:getTime() should behave like Date:getTime() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getTime()).toEqual(dateO.getTime())
})
it('FastDate:getTimezoneOffset() should behave like Date:getTimezoneOffset() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getTimezoneOffset()).toEqual(dateO.getTimezoneOffset())
})
it('FastDate:getUTCDate() should behave like Date:getUTCDate() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getUTCDate()).toEqual(dateO.getUTCDate())
})
it('FastDate:getUTCDay() should behave like Date:getUTCDay() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getUTCDay()).toEqual(dateO.getUTCDay())
})
it('FastDate:getUTCFullYear() should behave like Date:getUTCFullYear() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getUTCFullYear()).toEqual(dateO.getUTCFullYear())
})
it('FastDate:getUTCHours() should behave like Date:getUTCHours() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getUTCHours()).toEqual(dateO.getUTCHours())
})
it('FastDate:getUTCMilliseconds() should behave like Date:getUTCMilliseconds() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getUTCMilliseconds()).toEqual(dateO.getUTCMilliseconds())
})
it('FastDate:getUTCMinutes() should behave like Date:getUTCMinutes() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getUTCMinutes()).toEqual(dateO.getUTCMinutes())
})
it('FastDate:getUTCMonth() should behave like Date:getUTCMonth() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getUTCMonth()).toEqual(dateO.getUTCMonth())
})
it('FastDate:getUTCSeconds() should behave like Date:getUTCSeconds() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getUTCSeconds()).toEqual(dateO.getUTCSeconds())
})
it('FastDate:getYear() should behave like Date:getYear() method', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.getYear()).toEqual(dateO.getYear())
})
it('FastDate:toDateString() should behave like Date:toDateString()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.toDateString()).toEqual(dateO.toDateString())
})
it('FastDate:toISOString() should behave like Date:toISOString()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.toISOString()).toEqual(dateO.toISOString())
})
it('FastDate:toJSON() should behave like Date:toJSON()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.toJSON()).toEqual(dateO.toJSON())
})
it('FastDate:toGMTString() should behave like Date:toGMTString()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.toGMTString()).toEqual(dateO.toGMTString())
})
it('FastDate:toLocaleDateString() should behave like Date:toLocaleDateString()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.toLocaleDateString()).toEqual(dateO.toLocaleDateString())
})
it('FastDate:toLocaleString() should behave like Date:toLocaleString()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.toLocaleString()).toEqual(dateO.toLocaleString())
})
it('FastDate:toLocaleTimeString() should behave like Date:toLocaleTimeString()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.toLocaleTimeString()).toEqual(dateO.toLocaleTimeString())
})
it('FastDate:toString() should behave like Date:toString()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.toString()).toEqual(dateO.toString())
})
it('FastDate:toTimeString() should behave like Date:toTimeString()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.toTimeString()).toEqual(dateO.toTimeString())
})
it('FastDate:toUTCString() should behave like Date:toUTCString()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.toUTCString()).toEqual(dateO.toUTCString())
})
it('FastDate:valueOf() should behave like Date:valueOf()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.valueOf()).toEqual(dateO.valueOf())
})
it('FastDate:setDate() should behave like Date:setDate()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.setDate(10)).toEqual(dateO.setDate(10))
})
it('FastDate:setFullYear() should behave like Date:setFullYear()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.setFullYear(2016)).toEqual(dateO.setFullYear(2016))
expect(dateN.setFullYear(2016, 10)).toEqual(dateO.setFullYear(2016, 10))
expect(dateN.setFullYear(2016, 10, 11)).toEqual(dateO.setFullYear(2016, 10, 11))
})
it('FastDate:setHours() should behave like Date:setHours()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.setHours(10)).toEqual(dateO.setHours(10))
expect(dateN.setHours(10, 10)).toEqual(dateO.setHours(10, 10))
expect(dateN.setHours(10, 10, 10)).toEqual(dateO.setHours(10, 10, 10))
expect(dateN.setHours(10, 10, 10, 999)).toEqual(dateO.setHours(10, 10, 10, 999))
})
it('FastDate:setMilliseconds() should behave like Date:setMilliseconds()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.setMilliseconds()).toEqual(dateO.setMilliseconds())
expect(dateN.setMilliseconds(100)).toEqual(dateO.setMilliseconds(100))
})
it('FastDate:setMinutes() should behave like Date:setMinutes()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.setMinutes()).toEqual(dateO.setMinutes())
expect(dateN.setMinutes(10)).toEqual(dateO.setMinutes(10))
expect(dateN.setMinutes(10, 10)).toEqual(dateO.setMinutes(10, 10))
expect(dateN.setMinutes(10, 10, 555)).toEqual(dateO.setMinutes(10, 10, 555))
})
it('FastDate:setMonth() should behave like Date:setMonth()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.setMonth(10)).toEqual(dateO.setMonth(10))
expect(dateN.setMonth(10, 5)).toEqual(dateO.setMonth(10, 5))
})
it('FastDate:setSeconds() should behave like Date:setSeconds()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.setSeconds()).toEqual(dateO.setSeconds())
expect(dateN.setSeconds(10)).toEqual(dateO.setSeconds(10))
expect(dateN.setSeconds(10, 15)).toEqual(dateO.setSeconds(10, 15))
})
it('FastDate:setTime() should behave like Date:setTime()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.setTime()).toEqual(dateO.setTime())
expect(dateN.setTime(0)).toEqual(dateO.setTime(0))
expect(dateN.setTime(9182)).toEqual(dateO.setTime(9182))
})
it('FastDate:setUTCDate() should behave like Date:setUTCDate()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.setUTCDate()).toEqual(dateO.setUTCDate())
expect(dateN.setUTCDate(10)).toEqual(dateO.setUTCDate(10))
})
it('FastDate:setUTCFullYear() should behave like Date:setUTCFullYear()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.setUTCFullYear(2016)).toEqual(dateO.setUTCFullYear(2016))
expect(dateN.setUTCFullYear(2016, 10)).toEqual(dateO.setUTCFullYear(2016, 10))
expect(dateN.setUTCFullYear(2016, 10, 11)).toEqual(dateO.setUTCFullYear(2016, 10, 11))
})
it('FastDate:setUTCHours() should behave like Date:setUTCHours()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.setUTCHours(10)).toEqual(dateO.setUTCHours(10))
expect(dateN.setUTCHours(10, 10)).toEqual(dateO.setUTCHours(10, 10))
expect(dateN.setUTCHours(10, 10, 10)).toEqual(dateO.setUTCHours(10, 10, 10))
expect(dateN.setUTCHours(10, 10, 10, 999)).toEqual(dateO.setUTCHours(10, 10, 10, 999))
})
it('FastDate:setUTCMilliseconds() should behave like Date:setUTCMilliseconds()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.setUTCMilliseconds()).toEqual(dateO.setUTCMilliseconds())
expect(dateN.setUTCMilliseconds(100)).toEqual(dateO.setUTCMilliseconds(100))
})
it('FastDate:setUTCMinutes() should behave like Date:setUTCMinutes()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.setUTCMinutes()).toEqual(dateO.setUTCMinutes())
expect(dateN.setUTCMinutes(10)).toEqual(dateO.setUTCMinutes(10))
expect(dateN.setUTCMinutes(10, 10)).toEqual(dateO.setUTCMinutes(10, 10))
expect(dateN.setUTCMinutes(10, 10, 555)).toEqual(dateO.setUTCMinutes(10, 10, 555))
})
it('FastDate:setUTCMonth() should behave like Date:setUTCMonth()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.setUTCMonth()).toEqual(dateO.setUTCMonth())
expect(dateN.setUTCMonth(10)).toEqual(dateO.setUTCMonth(10))
expect(dateN.setUTCMonth(10, 5)).toEqual(dateO.setUTCMonth(10, 5))
})
it('FastDate:setUTCSeconds() should behave like Date:setUTCSeconds()', () => {
const dateO = new Date()
const dateN = new FastDate(dateO)
expect(dateN.setUTCSeconds()).toEqual(dateO.setUTCSeconds())
expect(dateN.setUTCSeconds(10)).toEqual(dateO.setUTCSeconds(10))
expect(dateN.setUTCSeconds(10, 15)).toEqual(dateO.setUTCSeconds(10, 15))
})
it('FastDate:isJustDate() should return dates created with args like "2017-01-01" and (2017, 0, 1)', () => {
expect(new FastDate(2017, 0, 1).isJustDate()).toBeTruthy()
expect(new FastDate('2017-01-01').isJustDate()).toBeTruthy()
expect(new FastDate(2017, 0, 1, 10, 10, 10, 0).isJustDate()).toBeFalsy()
expect(new FastDate('2017-01-01T10:10:10.000Z').isJustDate()).toBeFalsy()
})
})
<file_sep>/README.md
# Fast-dates
This project looks forward to do Date operations fast, really fast.
## Install
```bash
npm install fast-dates
```
Or
```bash
yarn add fast-dates
```
## Usage
```javascript
const fastDates = require('fast-dates');
console.log(workingDaysDiff('2017-10-11T12:12:12.000Z', '2017-10-27T12:12:12.000Z', true)) // 12 days
console.log(workingDaysDiff('2017-10-11T12:12:12.000Z', '2017-10-27T00:12:12.000Z', true)) // 11.5 days
```
## Features
- Working Days Diff
```javascript
/**
* Get difference in days between two dates excluding weekends.
* Also you can give an array of dates to be excluded from the result.
*
* @param {any} from starting Date
* @param {any} to target Date
* @param {boolean} [precise=false] if true, will return a float number
* @param {any} [exclude=[]] days to be excluded
* @returns Number
*/
function workingDaysDiff (from, to, precise = false, exclude = []) { ...}
```
<file_sep>/src/main.js
const msPerMinute = 60000
const msPerHour = 60 * msPerMinute // Day in milliseconds
const msPerDay = 24 * msPerHour
const offset = (new Date()).getTimezoneOffset() * msPerMinute
const bind = Function.bind
const unbind = bind.bind(bind)
function instantiate (constructor, args) {
return new (unbind(constructor, null).apply(null, args))()
}
function FastDate () {
if (arguments.length > 0 && arguments[0] instanceof FastDate) {
this._arg = arguments[0]._arg
this.justDate = arguments[0].justDate
this._date = new Date(arguments[0].valueOf())
} else if (arguments.length === 3) {
this._arg = `${arguments[0]}-0${arguments[1] + 1}-0${arguments[2]}`.replace(/-0(\d\d)/, '-$1')
this.justDate = true
this._date = instantiate(Date, arguments)
} else if (arguments.length === 1 && typeof arguments[0] === 'string') {
this._arg = arguments[0]
this.justDate = this._arg.length === 10
this._date = new Date(arguments[0]) // instantiate(Date, arguments)
} else {
this._arg = arguments
this._date = instantiate(Date, arguments)
}
this.justDate = this.justDate || false
}
function d () {
return instantiate(FastDate, arguments)
}
FastDate.Now = Date.Now
FastDate.parse = Date.parse
FastDate.UTC = Date.UTC
FastDate.prototype.isJustDate = function () {
return this.justDate
}
FastDate.prototype.toDate = function () {
return this._date
}
FastDate.prototype.isBusinessDay = function (exclude = []) {
if (this.getLocaleDay() === 0 || this.getLocaleDay() === 6) return false
return exclude.indexOf(this.getEpochDay()) === -1
}
FastDate.prototype.getDate = function () { return this._date.getDate.apply(this._date, arguments) }
FastDate.prototype.getDay = function () { return this._date.getDay.apply(this._date, arguments) }
FastDate.prototype.getLocaleDay = function () { return this.justDate ? this.getUTCDay() : this.getDay() }
FastDate.prototype.getFullYear = function () { return this._date.getFullYear.apply(this._date, arguments) }
FastDate.prototype.getHours = function () { return this._date.getHours.apply(this._date, arguments) }
FastDate.prototype.getMilliseconds = function () { return this._date.getMilliseconds.apply(this._date, arguments) }
FastDate.prototype.getMinutes = function () { return this._date.getMinutes.apply(this._date, arguments) }
FastDate.prototype.getMonth = function () { return this._date.getMonth.apply(this._date, arguments) }
FastDate.prototype.getSeconds = function () { return this._date.getSeconds.apply(this._date, arguments) }
FastDate.prototype.getTime = function () { return this._date.getTime.apply(this._date, arguments) }
FastDate.prototype.getTimezoneOffset = function () { return this._date.getTimezoneOffset.apply(this._date, arguments) }
FastDate.prototype.getUTCDate = function () { return this._date.getUTCDate.apply(this._date, arguments) }
FastDate.prototype.getUTCDay = function () { return this._date.getUTCDay.apply(this._date, arguments) }
FastDate.prototype.getUTCFullYear = function () { return this._date.getUTCFullYear.apply(this._date, arguments) }
FastDate.prototype.getUTCHours = function () { return this._date.getUTCHours.apply(this._date, arguments) }
FastDate.prototype.getUTCMilliseconds = function () { return this._date.getUTCMilliseconds.apply(this._date, arguments) }
FastDate.prototype.getUTCMinutes = function () { return this._date.getUTCMinutes.apply(this._date, arguments) }
FastDate.prototype.getUTCMonth = function () { return this._date.getUTCMonth.apply(this._date, arguments) }
FastDate.prototype.getUTCSeconds = function () { return this._date.getUTCSeconds.apply(this._date, arguments) }
FastDate.prototype.getYear = function () { return this._date.getYear.apply(this._date, arguments) }
FastDate.prototype.setDate = function () { return this._date.setDate.apply(this._date, arguments) }
FastDate.prototype.setFullYear = function () { return this._date.setFullYear.apply(this._date, arguments) }
FastDate.prototype.setHours = function () {
this.justDate = false
return this._date.setHours.apply(this._date, arguments)
}
FastDate.prototype.setMilliseconds = function () { return this._date.setMilliseconds.apply(this._date, arguments) }
FastDate.prototype.setMinutes = function () { return this._date.setMinutes.apply(this._date, arguments) }
FastDate.prototype.setMonth = function () { return this._date.setMonth.apply(this._date, arguments) }
FastDate.prototype.setSeconds = function () { return this._date.setSeconds.apply(this._date, arguments) }
FastDate.prototype.setTime = function () { return this._date.setTime.apply(this._date, arguments) }
FastDate.prototype.setUTCDate = function () { return this._date.setUTCDate.apply(this._date, arguments) }
FastDate.prototype.setUTCFullYear = function () { return this._date.setUTCFullYear.apply(this._date, arguments) }
FastDate.prototype.setUTCHours = function () { return this._date.setUTCHours.apply(this._date, arguments) }
FastDate.prototype.setUTCMilliseconds = function () { return this._date.setUTCMilliseconds.apply(this._date, arguments) }
FastDate.prototype.setUTCMinutes = function () { return this._date.setUTCMinutes.apply(this._date, arguments) }
FastDate.prototype.setUTCMonth = function () { return this._date.setUTCMonth.apply(this._date, arguments) }
FastDate.prototype.setUTCSeconds = function () { return this._date.setUTCSeconds.apply(this._date, arguments) }
FastDate.prototype.toDateString = function () { return this._date.toDateString.apply(this._date, arguments) }
FastDate.prototype.toISOString = function () { return this._date.toISOString.apply(this._date, arguments) }
FastDate.prototype.toJSON = function () { return this._date.toJSON.apply(this._date, arguments) }
FastDate.prototype.toGMTString = function () { return this._date.toGMTString.apply(this._date, arguments) }
FastDate.prototype.toLocaleDateString = function () { return this._date.toLocaleDateString.apply(this._date, arguments) }
FastDate.prototype.toLocaleString = function () { return this._date.toLocaleString.apply(this._date, arguments) }
FastDate.prototype.toLocaleTimeString = function () { return this._date.toLocaleTimeString.apply(this._date, arguments) }
FastDate.prototype.toString = function () { return this._date.toString.apply(this._date, arguments) }
FastDate.prototype.toTimeString = function () { return this._date.toTimeString.apply(this._date, arguments) }
FastDate.prototype.toUTCString = function () { return this._date.toUTCString.apply(this._date, arguments) }
FastDate.prototype.valueOf = function () { return this._date.valueOf.apply(this._date, arguments) }
function startOf (date, interval = 'd') {
if (interval === 'd' || interval === 'day') {
return d(d(date).setHours(0, 0, 0, 0))
}
throw new Error('Not implemented yet')
}
function endOf (date, interval = 'd') {
if (interval === 'd' || interval === 'day') {
return d(d(date).setHours(23, 59, 59, 999))
}
throw new Error('Not implemented yet')
}
function getExcludedDays (from, to, exclude = []) {
const f = startOf(from, 'd').getEpochDay()
const t = endOf(to, 'd').getEpochDay()
return exclude.filter((exc) => {
return (exc.getEpochDay() >= f && exc.getEpochDay() <= t && exc.isBusinessDay())
}).map(exc => getEpochDay(exc))
}
function validate (from, to, exclude) {
if (to < from) throw new Error('From date is grater than to date.')
if (!Array.isArray(exclude)) throw new Error('Exclude arg should be an array of Dates')
}
function getEpochDay (date) {
return parseInt((date.isJustDate() ? date.getTime() : date.getTime() - offset) / msPerDay, 10)
}
function getDiscountedHours (from, to, exclude = []) {
let sDay = from.getLocaleDay()
let eDay = to.getLocaleDay()
let t = d(to)
if (eDay === 6 || exclude.indexOf(t.getEpochDay()) !== -1) {
t = d(to.getTime() - 1)
t.justDate = to.justDate
eDay = t.getLocaleDay()
}
let discount = 0
if (sDay - eDay > 1) discount += -48
if ((sDay === 0 && eDay !== 6) || (eDay === 6 && sDay !== 0)) discount += -24
sDay = !(sDay === 0 || sDay === 6) ? from.getEpochDay() : null
eDay = !(eDay === 0 || eDay === 6) ? to.getEpochDay() : null
const tEpoch = t.getEpochDay()
const fEpoch = from.getEpochDay()
exclude.forEach((exc) => {
if (exc > tEpoch || exc <= fEpoch) return
discount += -24
const excDay = (exc % 7) - 3
discount += (excDay === sDay) ? -24 : 0
discount += (excDay === eDay && eDay !== sDay) ? -24 : 0
})
return discount
}
function prepareFrom (from, exclude = []) {
if (from.isBusinessDay(exclude)) return from
return prepareFrom(startOf(from.valueOf() + msPerDay, 'd'))
}
function prepareTo (to, exclude = []) {
if (to.isBusinessDay(exclude)) return to.isJustDate() ? d(endOf(new Date(to.valueOf()).setUTCHours(0, 0, 0, 0) + msPerDay, 'd') + 1) : d(to + (to.carryValue || 0))
let t = d(endOf(to.isJustDate() ? (startOf(to, 'd').valueOf() + msPerDay) : to, 'd'))
t = endOf(t.valueOf() - msPerDay, 'd')
t.carryValue = 1
return prepareTo(t, exclude)
}
/**
* Get difference in days between two dates excluding weekends.
* Also you can give an array of dates to be excluded from the result.
*
* @param {any} from starting Date
* @param {any} to target Date
* @param {boolean} [precise=false] if true, will return a float number
* @param {any} [exclude=[]] days to be excluded
* @returns Number
*/
function workingDaysDiff (from, to, precise = false, exclude = []) {
validate(from, to, exclude)
const exc = getExcludedDays(from, to, exclude)
const f = prepareFrom(d(from), exc)
const t = prepareTo(d(to), exc)
let h = (t - f) / msPerHour
if (h <= 0) return 0
const weeks = Math.floor((t.getEpochDay() - f.getEpochDay()) / 7)
h -= weeks * 48
if (weeks === 0 && f.getLocaleDay() < 6 && t.getLocaleDay() > 1 && t.getLocaleDay() < f.getLocaleDay()) {
h -= (7 - (f.getLocaleDay() + t.getLocaleDay())) * 24
}
h += getDiscountedHours(f, t, exc)
return precise ? h / 24 : Math.floor(h / 24)
}
FastDate.prototype.getEpochDay = function () {
return getEpochDay(this)
}
module.exports = exports = {
FastDate,
workingDaysDiff,
_internals: {
getExcludedDays,
validate,
getEpochDay,
getDiscountedHours,
prepareFrom,
prepareTo,
startOf,
endOf,
d
}
}
| b8c9e067436d9d4c1f31b92fe0db7967e591ec9e | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | mturch/fast-dates.js | 9fa7c8d1cb05dfc84294b548971e276243edbc33 | 21b0bbc67b9fc7a0b9db4d23ae8081175357925a |
refs/heads/master | <repo_name>vieiraLeo/projeto_lariguet_maven<file_sep>/src/main/java/br/com/projeto/controller/listaController.java
package br.com.projeto.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class listaController {
}
<file_sep>/src/main/java/br/com/projeto/dao/DbManager.java
package br.com.projeto.dao;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;
public class DbManager {
private Connection conn;
private PreparedStatement statement;
//Criando conexão com o banco
public void getConnection() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3305/test","root","tobegreat");
this.conn = conn;
}
//metodo de execução de queries
private void executeSql(String sql) throws SQLException{
this.statement.executeUpdate();
}
//metodo de fechamento da conexão
public void closeConnection() throws SQLException{
this.conn.close();
}
//método de busca de clientes
public ArrayList<String> selectClientes(String query) throws SQLException{
this.statement = this.conn.prepareStatement(query);
ResultSet result = this.statement.executeQuery();
ArrayList<String> array = new ArrayList<String>();
while(result.next()){
array.add(result.getString("nome"));
}
return array;
}
}
<file_sep>/src/main/java/br/com/projeto/controller/Controle.java
package br.com.projeto.controller;
import java.io.IOException;
import java.sql.Connection;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.com.projeto.dao.DbManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
@WebServlet
public class Controle extends HttpServlet {
private static final long serialVersionUID = 1L;
private DbManager db = new DbManager();
public ArrayList<String> findClientes (){
ArrayList<String> array = new ArrayList<String>();
try{
this.db.getConnection();
array = this.db.selectClientes("select nome from clientes");
this.db.closeConnection();
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}
return array;
}
}
| 73aafbb09333ab4ebb3185d43a0c8e3c987b1afc | [
"Java"
] | 3 | Java | vieiraLeo/projeto_lariguet_maven | ad48ddab76688e81afd324e650495bc0e119ab70 | c1d4496cd9435cb65288127189184051cf31b7e0 |
refs/heads/master | <file_sep>ESPN_ID_TO_TEAM = { #ESPN's team id : team
1: "DJ",
2: "Nick",
3: "Tim",
4: "Joe",
5: "Davey",
6: "Jason",
7: "Ben",
8: "Drew",
9: "Luke",
10: "Jack",
11: "Tony",
12: "Dano"
}
STATS_TAGS = {
0: "Wins",
1: "Losses",
2: "Ties",
3: "Points For",
4: "Points Against"
}
STATS_IDS = {
0: "wins",
1: "losses",
2: "ties",
3: "pointsFor",
4: "pointsAgainst"
}
AXES_LABELS = {
0: "Games",
1: "Points",
2: "% of Games"
}
<file_sep>import requests
import pandas as pd
import json
import matplotlib.pyplot as plt
import seaborn as sns
import os
#NOTE: This was the initial test to track matchup. It is still being developed, so it is not a full part of the application at the moment.
teamDict = { #team id : team
1: "DJ",
2: "Nick",
3: "Tim",
4: "Joe",
5: "Davey",
6: "Jason",
7: "Ben",
8: "Drew",
9: "Luke",
10: "Jack",
11: "Tony",
12: "Dano"
}
def main():
currentDirectory = os.path.dirname(os.path.abspath(__file__))
cookieFile = os.path.join(currentDirectory, 'cookies.txt')
leagueID = 368182
seasonID = 2019
view = "mMatchup"
currentUrl = "http://fantasy.espn.com/apis/v3/games/ffl/seasons/" + str(seasonID) + "/segments/0/leagues/" + str(leagueID)
#initial http request
cookies = open(cookieFile, "r").readlines()
r = requests.get(currentUrl,
params={"view" : view},
cookies={"SWID": cookies[0].strip(),
"espn_s2": cookies[1].strip()})
data = r.json() #Need to add '[0]' directly to end for historical url
#Create matchup DataFrame
matchupDF = [[
game['matchupPeriodId'],
teamDict[game['home']['teamId']], game['home']['totalPoints'],
teamDict[game['away']['teamId']], game['away']['totalPoints']
] for game in data['schedule']]
matchupDF = pd.DataFrame(matchupDF, columns=['Week', 'Team1', 'Score1', 'Team2', 'Score2'])
matchupDF['Type'] = ['Regular' if w<=14 else 'Playoff' for w in matchupDF['Week']]
#Compare scores to generate win/loss DataFrame
wlMarginDF = matchupDF.assign(Margin1 = matchupDF['Score1'] - matchupDF['Score2'],
Margin2 = matchupDF['Score2'] - matchupDF['Score1'])
wlMarginDF = (wlMarginDF[['Week', 'Team1', 'Margin1', 'Type']]
.rename(columns={'Team1': 'Team', 'Margin1': 'Margin'})
.append(wlMarginDF[['Week', 'Team2', 'Margin2', 'Type']]
.rename(columns={'Team2': 'Team', 'Margin2': 'Margin'}))
)
#Plot results
fig, ax = plt.subplots(1,1, figsize=(16,6))
order = [teamDict[1], teamDict[2], teamDict[3], teamDict[4], teamDict[5], teamDict[6], teamDict[7], teamDict[8], teamDict[9], teamDict[10], teamDict[11], teamDict[12]]
sns.boxplot(x='Team', y='Margin', hue='Type',
data=wlMarginDF,
palette='muted',
order=order)
ax.axhline(0, ls='--')
ax.set_xlabel('')
ax.set_title('Win/Loss Margins')
plt.show()<file_sep>from ESPN_FFB.constants import STATS_TAGS, AXES_LABELS
from ESPN_FFB.figure_options import (is_all_time_point_figure, is_all_time_record_figure,
is_adjusted_figure_option)
class AxesLabels():
def __init__(self, figure_option: int):
if is_all_time_record_figure(figure_option):
self._set_all_time_record_labels(figure_option)
elif is_all_time_point_figure(figure_option):
self._set_all_time_point_labels()
else:
self.x_labels = None
self.y_label = None
def _set_all_time_record_labels(self, figure_option: int):
self.x_labels = [STATS_TAGS.get(0), STATS_TAGS.get(1), STATS_TAGS.get(2)]
if is_adjusted_figure_option(figure_option):
self.y_label = AXES_LABELS.get(2)
else:
self.y_label = AXES_LABELS.get(0)
def _set_all_time_point_labels(self):
self.x_labels = [STATS_TAGS.get(3), STATS_TAGS.get(4)]
self.y_label = AXES_LABELS.get(1)
<file_sep>import numpy as np
from ESPN_FFB.constants import ESPN_ID_TO_TEAM, STATS_IDS
from ESPN_FFB.figure_options import (is_all_time_point_figure, is_all_time_record_figure,
is_adjusted_figure_option)
class LeagueInfo:
def __init__(self, league_id: int = 368182, first_year: int = 2014):
self.cached_responses = list()
self.league_id = league_id
self.first_year = first_year
def set_league(self, league_id: int, first_year: int):
self.cached_responses = list()
self.league_id = league_id
self.first_year = first_year
def clear_cache(self):
self.cached_responses.clear()
def is_cache_empty(self):
return len(self.cached_responses) == 0
def get_figure_heights(self, figure_option) -> list:
all_team_stats = self._format_response_as_dict()
figure_heights = _strip_irrelevant_figure_heights(figure_option, all_team_stats)
figure_heights = self._adjust_per_game_if_necessary(
figure_heights, all_team_stats, figure_option)
return figure_heights
def _format_response_as_dict(self) -> dict:
formatted_response = dict()
for request in self.cached_responses:
formatted_response = _format_all_teams_single_season(request, formatted_response)
formatted_response = _round_formatted_response(formatted_response)
return formatted_response
def _adjust_per_game_if_necessary(self, figure_heights: list, all_team_stats: dict, figure_option: int):
if is_adjusted_figure_option(figure_option) is False:
return figure_heights
for team in ESPN_ID_TO_TEAM:
games_played = self._all_time_total_games_played(team, all_team_stats)
figure_heights[team - 1] = self._adjust_per_game(team, figure_heights, games_played)
return figure_heights
def _all_time_total_games_played(self, team: int, all_team_stats: dict):
return sum(all_team_stats.get(team)[:3])
def _adjust_per_game(self, team: int, figure_heights: list, games_played: int) -> list:
team_stats = figure_heights[team - 1]
for stat in range(len(team_stats)):
team_stat_value = team_stats[stat] / games_played
team_stat_value = convert_to_percent_if_record_stats(team_stats, team_stat_value)
team_stats[stat] = round(team_stat_value, 1)
return team_stats
def _format_all_teams_single_season(request: dict, formatted_response: dict) -> dict:
for team in request['teams']:
formatted_response = _format_team_single_season(formatted_response, team)
return formatted_response
def _format_team_single_season(formatted_response: dict, team: dict) -> dict:
running_record = formatted_response.get(team['id'], [0] * len(STATS_IDS))
new_record_addition = [0] * len(STATS_IDS)
for stat in STATS_IDS:
stat_this_season = team['record']['overall'][str(STATS_IDS.get(stat))]
new_record_addition[stat] = stat_this_season
running_record = np.add(running_record, new_record_addition)
formatted_response.update({team['id']: running_record.tolist()})
return formatted_response
def _round_formatted_response(formatted_response: dict) -> dict:
for team in formatted_response:
formatted_response.update({team: [round(x) for x in formatted_response.get(team)]})
return formatted_response
def _strip_irrelevant_figure_heights(figure_option: int, all_team_stats: dict) -> list:
figure_heights = list()
relevant_slice = _get_relevant_slice(figure_option)
for team in ESPN_ID_TO_TEAM:
figure_heights.insert(team, all_team_stats.get(team)[
relevant_slice[0]:relevant_slice[1]])
return figure_heights
def _get_relevant_slice(figure_option: int):
if is_all_time_record_figure(figure_option):
relevant_slice = [0, 3]
elif is_all_time_point_figure(figure_option):
relevant_slice = [3, 5]
return relevant_slice
def convert_to_percent_if_record_stats(team_stats: list, team_stat_value: float):
if len(team_stats) == 3:
team_stat_value *= 100
return team_stat_value
<file_sep>import unittest
import os
import datetime
import json
import main
from ESPN_FFB.axes_labels import AxesLabels
from ESPN_FFB.url_info import URLInfo, _is_year_active, _is_september_date_after_nfl_start
from ESPN_FFB.league_info import LeagueInfo
from ESPN_FFB.constants import STATS_TAGS, AXES_LABELS, ESPN_ID_TO_TEAM
from ESPN_FFB.figure_options import FIGURE_OPTIONS
def get_sample_json():
current_directory = os.path.dirname(os.path.abspath(__file__))
open_file = open(os.path.join(current_directory, "sampleData.json"))
sample_json = list()
sample_json.append(json.load(open_file))
open_file.close()
return sample_json
class ApplicationWindowTests(unittest.TestCase):
def setUp(self):
self.league_info = LeagueInfo()
self.league_info.cached_responses = get_sample_json()
def test_sample_json_exists(self):
self.assertGreater(len(self.league_info.cached_responses), 0)
def test_clear_cache(self):
main.FFB.on_click_clear_cache_button(self.league_info)
self.assertFalse(self.league_info.cached_responses) #Empty list = false
#Rebuild
self.league_info.cached_responses = get_sample_json()
def test_record_figure_heights(self):
for figure_option in range(0, 2):
figure_heights = self.league_info.get_figure_heights(figure_option)
for team in ESPN_ID_TO_TEAM:
self.assertEqual(
len(figure_heights[team - 1]), 3,
"League info is not returning the right number " \
"of bar heights for Record figures.")
for figure_option in range(2, 4):
figure_heights = self.league_info.get_figure_heights(figure_option)
for team in ESPN_ID_TO_TEAM:
self.assertEqual(
len(figure_heights[team - 1]), 2,
"League info is not returning the right number " \
"of bar heights for Points figures.")
def test_axes_labels(self):
raw_data_figures = [FIGURE_OPTIONS.get(0), FIGURE_OPTIONS.get(1)]
season_adjusted_figures = [FIGURE_OPTIONS.get(2), FIGURE_OPTIONS.get(3)]
for figure_option in raw_data_figures:
axes_labels = AxesLabels(figure_option)
self.assert_axes_labels_not_none(axes_labels)
self.assertEqual(axes_labels.x_labels, [
STATS_TAGS.get(0), STATS_TAGS.get(1), STATS_TAGS.get(2)])
self.assertIn(axes_labels.y_label, [AXES_LABELS.get(2), AXES_LABELS.get(0)])
for figure_option in season_adjusted_figures:
axes_labels = AxesLabels(figure_option)
self.assert_axes_labels_not_none(axes_labels)
self.assertEqual(axes_labels.x_labels, [STATS_TAGS.get(3), STATS_TAGS.get(4)])
self.assertEqual(axes_labels.y_label, AXES_LABELS.get(1))
axes_labels = AxesLabels(-1)
self.assertIsNone(axes_labels.x_labels)
self.assertIsNone(axes_labels.y_label)
def assert_axes_labels_not_none(self, axes_labels: AxesLabels):
self.assertIsNotNone(axes_labels.x_labels)
self.assertIsNotNone(axes_labels.y_label)
def test_url_info(self):
view = "mTeam"
league_id = 368182
first_season = 2014
current_directory = os.path.dirname(os.path.abspath(__file__))
parent_directory = os.path.abspath(os.path.join(current_directory, os.pardir))
print(parent_directory)
url_info = URLInfo(view, self.league_info)
first_season_url_expected = "https://fantasy.espn.com/apis/v3/games/ffl/leagueHistory" \
f"/{league_id}?seasonId={first_season}"
url_count = len(url_info.urls)
self.assertEqual(first_season_url_expected, url_info.urls[url_count - 1])
def test_is_year_active(self):
current_year = datetime.datetime.now().year
for i in range(1, 6):
self.assertTrue(
_is_year_active(current_year - i),
f"Previous year {current_year - i} not considered active.")
self.assertFalse(
_is_year_active(current_year + i),
f"Future year {current_year + i} considered active.")
def test_is_september_date_after_nfl_start(self):
self.assert_september_dates_after_nfl_start()
self.assert_september_dates_before_nfl_start()
def assert_september_dates_after_nfl_start(self):
years_and_days_to_check = [
[2019, 26], [2019, 16], [2019, 18],
[2018, 20], [2018, 27],
[2017, 11], [2017, 13]
]
for year_and_day in years_and_days_to_check:
date = datetime.date(year_and_day[0], 9, year_and_day[1])
self.assertTrue(
_is_september_date_after_nfl_start(date),
f"Date {date} is after NFL start, but your code disagrees.")
def assert_september_dates_before_nfl_start(self):
years_and_days_to_check = [
[2019, 1], [2019, 5], [2019, 7],
[2018, 3], [2018, 8],
[2017, 1], [2017, 9]
]
for year_and_day in years_and_days_to_check:
date = datetime.date(year_and_day[0], 9, year_and_day[1])
self.assertFalse(
_is_september_date_after_nfl_start(date),
f"Date {date} is before NFL start, but your code disagrees.")
if __name__ == "__main__":
unittest.main()
<file_sep>import matplotlib.pyplot as plt
import numpy as np
from ESPN_FFB.axes_labels import AxesLabels
from ESPN_FFB.url_info import URLInfo
from ESPN_FFB.league_info import LeagueInfo
from ESPN_FFB.constants import ESPN_ID_TO_TEAM
from ESPN_FFB.figure_options import FIGURE_OPTIONS
def generate_all_time_graph(league_info: LeagueInfo, figure_option: int) -> bool:
url_info = URLInfo("mTeam", league_info)
if league_info.is_cache_empty():
league_info.cached_responses, success = url_info.get_formatted_espn_data()
if success is False:
return False
axes_labels = AxesLabels(figure_option)
figure_heights = league_info.get_figure_heights(figure_option)
prepare_figure(figure_option, figure_heights, axes_labels)
plt.show()
return True
def prepare_figure(figure_option, figure_heights: list, axes_labels: AxesLabels):
x_ticks = np.arange(len(axes_labels.x_labels))
figure, axes = plt.subplots(figsize=(16, 6))
assign_figure_attributes(
axes_labels, x_ticks, axes,
FIGURE_OPTIONS.get(figure_option))
prepare_figure_bars(figure_heights, x_ticks, figure, axes)
def assign_figure_attributes(axes_labels: AxesLabels, x_ticks, axes, title: str):
axes.set_ylabel(axes_labels.y_label)
axes.set_title(title)
axes.set_xticks(x_ticks)
axes.set_xticklabels(axes_labels.x_labels)
def prepare_figure_bars(figure_heights: list, x_ticks, fig, axes, width: float = 0.075):
rects = generate_bars_per_team(figure_heights, x_ticks, axes, width)
add_bar_labels(axes, rects)
axes.legend(fontsize='medium', shadow=True, title='Teams', title_fontsize='large')
fig.tight_layout()
def generate_bars_per_team(figure_heights: list, x_ticks, axes, width: float = 0.075):
bars = []
i = width*-6
for team in ESPN_ID_TO_TEAM:
bars.append(
axes.bar(
x_ticks + i,
figure_heights[team - 1],
width,
label=ESPN_ID_TO_TEAM.get(team),
linewidth=1,
edgecolor='black')
)
i += width
return bars
def add_bar_labels(axes, group_rects: list, vertical_offset: int = 3):
for rects in group_rects:
for rect in rects:
height = rect.get_height()
if height == 0:
continue
axes.annotate('{}'.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, vertical_offset),
textcoords="offset points",
ha='center', va='bottom')
if __name__ == "__main__": #For Testing Purposes
TEST_JSON = list()
generate_all_time_graph(TEST_JSON, 3)
generate_all_time_graph(TEST_JSON, 1)
<file_sep>from tkinter import *
from tkinter import messagebox
from tkinter.ttk import *
import os
from ESPN_FFB.all_time_standings import generate_all_time_graph
from ESPN_FFB.figure_options import FIGURE_OPTIONS
from ESPN_FFB.league_info import LeagueInfo
from functools import partial
def start_application():
""" Creates main window for the user to interact with.
"""
application_window = generate_window()
application_window.mainloop()
def generate_window() -> Tk:
window = ApplicationWindow()
window.geometry('1000x700')
window.title('Fumbled From Birth')
Grid.rowconfigure(window, 0, weight=1)
Grid.columnconfigure(window, 0, weight=1)
return window
class ApplicationWindow(Tk):
def __init__(self):
super().__init__()
self.league_info = LeagueInfo()
self.generate_frame()
self.set_icon()
self.generate_commands()
self.generate_buttons()
self.generate_advanced_options()
def generate_frame(self):
self.layout_frame = Frame(self)
self.layout_frame.grid(row=0, column=0, sticky=N+S+E+W)
for x in range(2):
Grid.rowconfigure(self.layout_frame, x, weight=1)
for y in range(2):
Grid.columnconfigure(self.layout_frame, y, weight=1)
def set_icon(self):
photo = self.get_icon()
self.iconphoto(False, photo)
def get_icon(self) -> PhotoImage:
current_directory = os.path.dirname(os.path.abspath(__file__))
return PhotoImage(file=os.path.join(current_directory, 'icon.gif'))
def generate_commands(self):
self.all_time_record_command = partial(
on_click_all_time,
self.league_info,
FIGURE_OPTIONS.get("All Time Record"))
self.all_time_record_adjusted_command = partial(
on_click_all_time,
self.league_info,
FIGURE_OPTIONS.get("All Time Record - Adjusted (%)"))
self.all_time_points_command = partial(
on_click_all_time,
self.league_info,
FIGURE_OPTIONS.get("All Time Points"))
self.all_time_points_adjusted_command = partial(
on_click_all_time,
self.league_info,
FIGURE_OPTIONS.get("All Time Points - Adjusted (Per Game)"))
self.clear_cache_command = partial(on_click_clear_cache_button, self.league_info)
def generate_buttons(self):
self.all_time_record_button = Button(
self.layout_frame,
command=self.all_time_record_command,
text="All Time Records")
self.all_time_record_adjusted_button = Button(
self.layout_frame,
command=self.all_time_record_adjusted_command,
text="All Time Record - Adjusted (%)")
self.all_time_points_button = Button(
self.layout_frame,
command=self.all_time_points_command,
text="All Time Points")
self.all_time_points_adjusted_button = Button(
self.layout_frame,
command=self.all_time_points_adjusted_command,
text="All Time Points - Adjusted (Per Game)")
self.assign_buttons_to_grid()
def assign_buttons_to_grid(self):
self.all_time_record_button.grid(column=0, row=0, sticky=N+S+E+W)
self.all_time_record_adjusted_button.grid(column=1, row=0, sticky=N+S+E+W)
self.all_time_points_button.grid(column=0, row=1, sticky=N+S+E+W)
self.all_time_points_adjusted_button.grid(column=1, row=1, sticky=N+S+E+W)
def generate_advanced_options(self):
self.advanced_options_menu = Menu(self)
self.clear_cache_item = Menu(self.advanced_options_menu, tearoff=0)
self.clear_cache_item.add_command(
label='Clear cached data',
command=self.clear_cache_command)
self.advanced_options_menu.add_cascade(
label='Advanced Options',
menu=self.clear_cache_item)
self.config(menu=self.advanced_options_menu)
def on_click_all_time(league_info: LeagueInfo, figure_option: int):
""" Command to execute when a button related to All Time stats is clicked. """
if generate_all_time_graph(league_info, figure_option) is False:
messagebox.showerror(
'Unable to retrieve full league history',
'One or more requests to ESPN failed. Verify you have a stable internet connection.')
def on_click_clear_cache_button(league_info: LeagueInfo):
""" Clears any cached data from previous requests. Will force new requests to be triggered
the next time we try to create any graphs.
"""
league_info.clear_cache()
<file_sep>FIGURE_OPTIONS = {
"All Time Record": 0,
"All Time Record - Adjusted (%)": 1,
"All Time Points": 2,
"All Time Points - Adjusted (Per Game)": 3,
0: "All Time Record",
1: "All Time Record - Adjusted (%)",
2: "All Time Points",
3: "All Time Points - Adjusted (Per Game)"
}
def is_all_time_point_figure(figure) -> bool:
""" Returns True if a given figure option is related to All Time Points.
Expects either string or int from dictionary FIGURE_FIGURE_OPTIONS.
"""
if figure in [
FIGURE_OPTIONS.get("All Time Points"),
FIGURE_OPTIONS.get("All Time Points - Adjusted (Per Game)")]:
return True
elif figure in [FIGURE_OPTIONS.get(2), FIGURE_OPTIONS.get(3)]:
return True
else:
return False
def is_all_time_record_figure(figure) -> bool:
""" Returns True if a given figure option is related to All Time Records.
Expects either string or int from dictionary FIGURE_FIGURE_OPTIONS.
"""
if figure in [
FIGURE_OPTIONS.get("All Time Record"),
FIGURE_OPTIONS.get("All Time Record - Adjusted (%)")]:
return True
elif figure in [FIGURE_OPTIONS.get(0), FIGURE_OPTIONS.get(1)]:
return True
else:
return False
def is_adjusted_figure_option(figure: int) -> bool:
if figure == FIGURE_OPTIONS.get("All Time Points - Adjusted (Per Game)"):
return True
elif figure == FIGURE_OPTIONS.get("All Time Record - Adjusted (%)"):
return True
return False
<file_sep>import ESPN_FFB.ffb_stats as FFB
if __name__ == "__main__":
FFB.start_application()
<file_sep>import datetime
import os
from multiprocessing import Pool
from sys import exc_info
import requests
from ESPN_FFB.league_info import LeagueInfo
class URLInfo:
def __init__(self, view: str, league_info: LeagueInfo):
self.urls = self._get_urls(league_info)
self.view = view
cookies = self._get_cookies()
self.swid = cookies[0].strip()
self.espn_s2 = cookies[1].strip()
def _get_cookies(self) -> list:
current_directory = os.path.dirname(os.path.abspath(__file__))
cookie_file = os.path.join(current_directory, 'cookies.txt')
try:
open_cookie_file = open(cookie_file, "r")
cookies = open_cookie_file.readlines()
open_cookie_file.close()
except:
raise Exception(f'Unable to open cookie file. Reported error: {exc_info()[0]}')
return cookies
def _get_urls(self, league_info: LeagueInfo, year: int = datetime.datetime.now().year) -> list:
""" Returns list of URLs for ESPNs fantasy football APIs.
Will create one URL per year, starting from the passed in year
until the first season of the league.
If no year is supplied, will start at the current year.
"""
urls = list()
if year < league_info.first_year:
return urls
if _is_year_active(year) is False:
year -= 1
while year >= league_info.first_year:
if len(urls) < 2: #Adding this check because 2 years currently use active url
urls.append(self._construct_url_current(league_info.league_id, year))
else:
urls.append(self._construct_url_historical(league_info.league_id, year))
year -= 1
return urls
def _construct_url_current(self, league_id: int, year: int) -> str:
"""
Constructs "active" URLs for ESPN fantasy football.
Active URLs appear to be used for the last 2 seasons.
"""
return "http://fantasy.espn.com/apis/v3/games/ffl/seasons" \
f"/{year}/segments/0/leagues/{league_id}"
def _construct_url_historical(self, league_id: int, year: int) -> str:
"""
Constructs "historical" URLs for ESPN fantasy football.
Historical URLs appear to be used for seasons more than 2 years back.
"""
return "https://fantasy.espn.com/apis/v3/games/ffl/leagueHistory" \
f"/{league_id}?seasonId={year}"
def get_formatted_espn_data(self):
responses, all_requests_successful = self._request_espn_data()
parsed_response = list()
for response in responses:
if 'leagueHistory' in response.url:
response = response.json()[0]
else:
response = response.json()
parsed_response.append(response)
return parsed_response, all_requests_successful
def _request_espn_data(self):
success = True
process_pool = Pool()
try:
responses = process_pool.map(self._get_single_espn_response, self.urls)
except requests.exceptions.ConnectionError:
success = False
return responses, success
def _get_single_espn_response(self, url: str) -> list:
response = requests.get(
url,
params={"view": self.view},
cookies={"SWID": self.swid,
"espn_s2": self.espn_s2})
return response
def _is_year_active(year: int) -> bool:
""" NFL seasons start the weekend after the first Monday of September.
Reference: https://en.wikipedia.org/wiki/NFL_regular_season
"""
current_date = datetime.date.today()
if year < current_date.year:
return True
if current_date.month != 9:
if current_date.month < 9:
return False
else:
return True
return _is_september_date_after_nfl_start(current_date)
def _is_september_date_after_nfl_start(date: datetime.date):
day = date.day
if day < 13:
first_monday = _get_first_september_monday(date.year)
if first_monday + 6 > day:
return False
return True
def _get_first_september_monday(year: int):
for day in range(1, 8):
date = datetime.date(year, 9, day)
if date.weekday() == 0: #Monday == 0
return day
| 502c7dd1cec70c8696ae1e28727a8539995f6ed3 | [
"Python"
] | 10 | Python | david-hu23/FFBStats | 79a0220a0d05039184d35c7b141fd4adb0ff1949 | aacdcfa2ffe4ba7486fd5570f5c3d601f70ff933 |
refs/heads/master | <repo_name>mbalug/mdv_python<file_sep>/engine.py
class Engine:
def __init__(self):
self.uart_buffer = []
self.tcp_buffer = []
def snd_uart_to_tcp(self, msg):
print("APPENDING UART MESSAGE")
self.uart_buffer.append(msg)
def snd_tcp_to_uart(self, msg):
self.tcp_buffer.append(msg)
def get_to_uart_messages(self):
buffer = self.tcp_buffer
self.tcp_buffer = []
return buffer
def get_to_tcp_messages(self):
buffer = self.uart_buffer
self.uart_buffer = []
return buffer
<file_sep>/cpp/mdv_engine/main.cpp
#include "tcp_server.h"
#include <boost/asio.hpp>
int main(int argc, char* argv[])
{
try
{
// if (argc != 2)
// {
// std::cerr << "Usage: async_tcp_echo_server <port>\n";
// return 1;
// }
boost::asio::io_context io_service;
// namespace std; // For atoi.
mdv::TcpServer s(io_service, 8081);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
<file_sep>/main.cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
int main(int argc, char* argv[]) {
struct termios serial;
char* str = "Hello\n";
char buffer[10];
int socket = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
if (socket == -1) {
perror("/dev/ttyS0");
return -1;
}
if (tcgetattr(socket, &serial) < 0) {
perror("Getting configuration");
return -1;
}
cfsetispeed(&serial,B9600); // set rx to 9600
cfsetospeed(&serial,B9600); // set tx to 9600
// Flush serial configuration
serial.c_iflag = 0;
serial.c_oflag = 0;
serial.c_lflag = 0;
serial.c_cflag = 0;
// tcflush(socket, TCIFLUSH); -> discard old rx buffer data
// serial.c_cc[VMIN] = 0;
// serial.c_cc[VTIME] = 0;
serial.c_cflag &= ~(CSIZE | PARENB | CSTOPB);
serial.c_cflag = CS8 | CREAD | CLOCAL;
// setup tx config
serial.c_oflag &= ~(OCRNL | ONLCR | ONLRET |
ONOCR | OFILL | OLCUC | OPOST | CRTSCTS);
// setup rx config
serial.c_iflag &= ~(IXON | IXOFF | IXANY); /* Disable XON/XOFF flow control both i/p and o/p */
serial.c_iflag &= ~(ICANON | ECHO | ECHOE | ISIG); /* No Cannonical mode */
tcsetattr(socket, TCSANOW, &serial); // Apply configuration
// Attempt to send and receive
printf("Sending: %s\n", str);
int wcount = write(socket, str, strlen(str));
if (wcount < 0) {
perror("Write");
return -1;
}
else {
printf("Sent %d characters\n", wcount);
}
sleep(1);
int rcount = read(socket, buffer, sizeof(buffer));
printf("Received %d\n", rcount);
if (rcount < 0) {
perror("Read");
return -1;
}
else {
printf("Received %d characters\n", rcount);
}
buffer[rcount] = '\0';
printf("Received: %s\n", buffer);
close(socket);
}<file_sep>/cpp/boost_serial/main.cpp
#include <iostream>
#include "SimpleSerial.h"
using namespace std;
using namespace boost;
//arm-linux-gnueabihf-g++ main.cpp -L/home/home/src/boost/lib -lboost_system -lpthread -I/home/home/src/boost/include
int main(int argc, char* argv[])
{
try {
SimpleSerial serial("/dev/ttyS0",9600);
serial.writeString("Hello world\n");
cout<<serial.readLine()<<endl;
} catch(boost::system::system_error& e)
{
cout<<"Error: "<<e.what()<<endl;
return 1;
}
}<file_sep>/uart.py
import sys
import threading
import time
import serial
class Uart():
def __init__(self,eng):
self.engine = eng
self.ser = serial.Serial('/dev/ttyS0', 9600)
self.data_to_send = []
self.stop_rcv_thread = True
self.uart_active = True
self.thread = threading.Thread(target=Uart.rcvThread,args=(self,))
self.thread3 = threading.Thread(target=Uart.threadSender,args=(self,))
def startUart(self):
self.thread.start()
self.thread3.start()
def stopUart(self):
self.stop_rcv_thread = True
self.stop_rcv_thread = False
self.thread.join()
self.thread3.join()
def rcvThread(self):
while self.stop_rcv_thread:
line = self.ser.readline().decode()
#self.ser.write(line.encode())
self.engine.snd_uart_to_tcp(line)
# if line != '':
print("UART RCV" + line)
print("UART THREAD RCV DONE")
def threadSender(self):
print("Thread uart send is started")
time.sleep(1)
while self.uart_active:
time.sleep(0.1)
if len(self.data_to_send) > 0:
msg=self.data_to_send[0]
self.data_to_send.remove(self.data_to_send[0])
print("Sending over UART", msg.encode())
self.ser.write(msg.encode())
print("UART THREAD SENDER DONE")
def sendData(self,data):
self.data_to_send.append(data)<file_sep>/mdv.py
import tcpclient
import time
import engine
import uart
import subprocess
import signal
import os
import sys
#process = subprocess.Popen(['/usr/local/bin/mjpg_streamer', '-o', 'output_http.so', '-i', 'input_raspicam.so -fps 15'])
#/usr/local/bin/mjpg_streamer -o output_http.so -i "input_raspicam.so -fps 15"
eng = engine.Engine()
uart = uart.Uart(eng)
uart.startUart()
srv = tcpclient.TCPClient(eng,'192.168.5.1',8081)
srv.startServer()
done = False
def signal_handler(sig, frame):
print('You pressed Ctrl+C!')
sys.exit()
global done
srv.stopServer()
uart.stopUart()
done = True
#process.terminate()
signal.signal(signal.SIGINT, signal_handler)
while done == False:
to_uart = eng.get_to_uart_messages()
if len(to_uart)>0:
for item in to_uart:
uart.sendData(item)
to_tcp = eng.get_to_tcp_messages()
if len(to_tcp)>0:
for item in to_tcp:
srv.sendData(item)
time.sleep(0.1)
<file_sep>/tcpclient.py
import socket
import sys
import threading
import time
class TCPClient:
def __init__(self, engine, host, port):
self.eng = engine
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created')
#Bind socket to local host and port
try:
self.socket.bind((host, port))
except socket.error as msg:
print ('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
print ('Socket bind complete')
self.socket.listen(10)
print ('Socket now listening')
self.tcp_active=False
self.stop_client_thread = False
self.wait_for_connection = True
self.data_to_send = []
self.thread = threading.Thread(target=TCPClient.waitConnection,args=(self,))
def startServer(self):
self.thread.start()
def stopServer(self):
self.wait_for_connection = False
self.stop_client_thread = True
self.thread.join()
def waitConnection(self):
while self.wait_for_connection:
conn, addr = self.socket.accept()
print ('Connected with ' + addr[0] + ':' + str(addr[1]))
thread1 = threading.Thread(target=TCPClient.clientthread,args=(self,conn,))
thread1.start()
self.socket.close()
thread1.join()
print("TCP THREAD WAITCONN DONE")
def clientthread(self, conn):
thread3 = threading.Thread(target=TCPClient.threadSender,args=(self,conn,))
thread3.start()
self.tcp_active= True
while not self.stop_client_thread:
#Receiving from client
data = conn.recv(1024)
print(data)
reply = 'OK...' + data.decode()
if not data:
self.tcp_active= False
thread3.join()
break
self.eng.snd_tcp_to_uart(data.decode())
print("Sending:" + reply)
conn.sendall(reply.encode())
thread3.join()
conn.close()
print("TCP THREAD client DONE")
def threadSender(self,conn):
print("Thread is startd")
time.sleep(1)
while self.tcp_active:
time.sleep(0.1)
if len(self.data_to_send) > 0:
msg=self.data_to_send[0]
self.data_to_send.remove(self.data_to_send[0])
print("Sending over tcp")
conn.sendall(msg.encode())
print("TCP THREAD SENDER DONE")
def sendData(self,data):
self.data_to_send.append(data) | 6226b6fa9e765729b7ecab0c20794e1f229140d9 | [
"Python",
"C++"
] | 7 | Python | mbalug/mdv_python | b55003543ffc30a6d4f521a276f48d0b9790480f | c377219d202a2c171e24219c1e3be11a50d18fef |
refs/heads/master | <repo_name>ilajil/Twilio-Quest-Game-Javascript<file_sep>/freightScanner.js
function scan(stringArr){
let contrabandCount = 0;
stringArr.forEach(function(item) {
if(item == 'contraband'){
contrabandCount++;
}
});
return contrabandCount;
}
const numItems = scan(['dog', 'contraband', 'cat', 'zippers', 'contraband']);
console.log('Number of "contraband": ' + numItems);
<file_sep>/freightFilter.js
function scanAndFilter(freightItems, forbiddenString){
let filteredItems = [];
filteredItems = freightItems.filter(name => !name.includes(forbiddenString));
console.log(filteredItems)
return filteredItems;
}
const filtered = scanAndFilter(['dog', 'ray gun', 'cat', 'zippers', 'ray gun'], 'ray gun' );
console.log('Filtered Items');
console.log(filtered);<file_sep>/chestConfiguration.js
var verifiedUser = Boolean(true);
var accessLevel = Number(7);
var favoriteRobot = String('Cedric');<file_sep>/construction.js
function construct (name){
let person = {
name : name,
material : 'human',
assemble : true,
duration :1000
}
return person;
}
const somePerson = construct('Kevin');
console.log('name is: ' + somePerson.name);
console.log('duration is: ' + somePerson.duration);<file_sep>/freightMutator.js
function mutate(shippingItems)
{
let mutatedItems = [];
shippingItems.forEach(function(item)
{
mutatedItems.push(item.toUpperCase());
})
return mutatedItems;
}
const cargo = ['apples', 'ray guns', 'oranges'];
const mutatedCargo = mutate(cargo);
console.log("The results of mutated item is" + mutatedCargo);<file_sep>/getFirstAmountSorted.js
function getFirstAmountSorted(inputArray, numberOfItems){
let amountS = inputArray.sort();
let newArr = amountS.slice(0,numberOfItems);
return newArr;
}
const newArray = getFirstAmountSorted(['cat', 'apple', 'bat'], 2);
console.log(newArray);
<file_sep>/laserConfiguration.js
var laserStatus = String('OFF');<file_sep>/targetingSolution.js
class TargetingSolution{
constructor(config) {
this.config = config;
this.x = config.x;
this.y = config.y;
this.z = config.z;
}
target(){
return `(${this.x}, ${this.y}, ${this.z})`;
}
}
const data = new TargetingSolution({
x : 10,
y : 12,
z :25
})
console.log(data.target()); <file_sep>/addFirstToLast.js
function addFirstToLast(inputArray){
//declare fist and last to be empty
let firstandlast = '';
let f=inputArray[0];
let l = inputArray[inputArray.length-1];
//
if(inputArray.length>0){
firstandlast = f + l;
}
return firstandlast;
}
console.log(addFirstToLast(['first', 'second', 'third']));
console.log(addFirstToLast(['golden','terrier']));
console.log(addFirstToLast(['cheerio']));
console.log(addFirstToLast([]));
<file_sep>/consoleTable.js
// Create a one dimensional array
// capable of storing 3 objects
let letters = new Array(3); // Indices 0,1,2
// Loop through the array, adding a
// new array to each location
for (let i = 0; i < letters.length; i++) {
letters[i] = new Array(3);// new array of 3 locations
}
// Put items in the 2D array
letters[0][0]='a';
letters[0][1]='f';
letters[0][2]='k';
letters[1][0]='b';
letters[1][1]='g';
letters[1][2]='l';
letters[2][0]='c';
letters[2][1]='h';
letters[2][2]='m';
// Display the 2D Array
console.table(letters);
console.log(letters);<file_sep>/ducktypium.js
class Ducktypium {
constructor(color) {
// your code here
this.color = color;
this.calibrationSequence = new Array();
switch(color){
case "red":
break;
case "blue":
break;
case "yellow":
break;
default:
throw new Error('Please insert the right color')
}
}
// your code here
calibrate(y){
var newArr = y.sort((a, b) => a-b)
this.calibrationSequence = newArr.map(x => x * 3);
}
refract(x){
if(this.color === "red"){
if(x === "red"){
return "red";
}else if(x === "blue"){
return "purple";
}else if(x === "yellow"){
return "orange";
}
}
if(this.color === "blue"){
if(x === "red"){
return "purple";
}else if(x === "yellow"){
return "green";
}else if(x === "blue"){
return "blue";
}
}
if(this.color === "yellow"){
if(x === "red"){
return "orange";
}else if(x === "yellow"){
return "yellow";
}else if(x === "blue"){
return "green";
}
}
}
}
// The following lines of code are not required for the solution, but can be
// used by you to test your solution.
const dt = new Ducktypium('red');
console.log(dt.color); // prints 'red'
console.log(dt.refract('blue')); // prints 'purple'
console.log(dt.refract('red')); // prints 'red'
dt.calibrate([3, 5, 1]);
console.log(dt.calibrationSequence); // prints [3, 9, 15]<file_sep>/laserPower.js
function calculatePower(arrOfNum){
let result = arrOfNum.reduce((sum, current) => sum + current*2, 0);
return result;
}
const laserPower = calculatePower([1, 3, 8]);
console.log('Required laser power is ' + laserPower); | e1b8da906fe93d7f3e482d6d5060bd8e79b12129 | [
"JavaScript"
] | 12 | JavaScript | ilajil/Twilio-Quest-Game-Javascript | f93235f96df97879a4d812d6d5e909c2c3d4bc1c | 5b81203596b12394fe53f0ab6dd0b19721a4c418 |
refs/heads/master | <repo_name>Owen-Ng/Pong<file_sep>/Pong/src/Pong/Ball.java
package Pong;
import java.awt.Color;
import java.awt.Graphics;
public class Ball {
double xvel, yvel, x ,y;
public Ball() {
x = 500;
y = 500;
xvel = -1;
yvel = -1;
}
public void move() {
x += 2*xvel;
y += 2*yvel;
if (y< 100) {
yvel = -yvel;
}
else if (y>900) {
yvel = -yvel;
}
}
public void ballcollision(racket p1, racket p2) {
if (x <= 40) {
if (y >= p1.getY() && y <= p1.getY() + 50) {
xvel = -xvel;
yvel = -1;
}
else if (y>= p1.getY() + 51 && y <= p1.getY() + 100) {
xvel = -xvel;
yvel = 1;
}
}
if (x >= 960) {
if (y >= p2.getY() && y <= p2.getY() + 50) {
xvel = -xvel;
yvel = -1;
}
else if (y >= p2.getY() +51 && y <= p2.getY() + 100) {
xvel = -xvel;
yvel = 1;
}
}
}
public int GetX() {
return (int)x;
}
public int GetY() {
return (int)y;
}
public void draw(Graphics g) {
g.setColor(Color.white);
g.fillOval((int)x-10, (int)y-10, 10, 10);
}
}
<file_sep>/Pong/src/Pong/CPUracket.java
package Pong;
import java.awt.Color;
import java.awt.Graphics;
public class CPUracket implements racket {
double y, yvel;
boolean upAccel, downAccel;
int player, x;
final double gravity = 0.5;
Ball b;
public CPUracket(int player, Ball b) {
upAccel = false;
downAccel = false;
this.b = b;
y = 210;
yvel = 0;
if (player == 1)
x = 20;
else
x = 960;
}
public void draw(Graphics g) {
g.setColor(Color.white);
g.fillRect(x, (int) y, 20, 100);
// TODO Auto-generated method stub
}
public void move() {
// TODO Auto-generated method stub
y = b.GetY() - 15;
if (y < 100) {
y = 50;
} else if (y > 800) {
y = 800;
}
}
public int getY() {
// TODO Auto-generated method stub
return (int) y;
}
}
<file_sep>/Pong/src/Pong/Court.java
package Pong;
import java.applet.*;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JApplet;
import java.awt.Color;
import java.awt.Font;
public class Court extends Applet implements Runnable, KeyListener{
private int W = 1000, H = 1000;
Thread thread;
myracket p1;
CPUracket p2;
Ball b1;
myracket h2;
boolean gamestarted;
boolean onev1;
public void init() {
this.resize(W,H);
this.addKeyListener(this);
b1 = new Ball();
p1 = new myracket(1);
p2 = new CPUracket(2, b1);
h2 = new myracket(2);
thread = new Thread(this);
thread.start();
}
public void paint(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, W, H);
if (b1.GetX() < 0 || b1.GetX() > 1000) {
g.setColor(Color.RED);
g.drawString("Game Over", 500, 450);
}
else if (!gamestarted) {
g.setColor(Color.BLUE);
g.setFont(new Font("TimesRoman", Font.PLAIN, 30));
g.drawString("Press ENTER to play with AI", 260, 470);
g.setColor(Color.RED);
g.setFont(new Font("TimesRoman", Font.PLAIN, 35));
g.drawString("Press x for 1v1", 285, 520);
}
else {
g.setColor(Color.WHITE);
g.drawLine(0, 900, 1000,900 );
g.drawLine(0, 100, 1000, 100);
g.drawLine(W/2, 0, W/2, 1000);
if (!onev1) {
p1.draw(g);
b1.draw(g);
p2.draw(g);
}
else {
p1.draw(g);
b1.draw(g);
h2.draw(g);
}
}
}
public void update(Graphics g) {
paint(g);
}
public void run() {
while (true) {
if (gamestarted) {
if(onev1) {
p1.move();
h2.move();
b1.move();
b1.ballcollision(p1, h2);
repaint();
}
else {
p1.move();
p2.move();
b1.move();
b1.ballcollision(p1, p2);
repaint();
}
}
try {
Thread.sleep(10);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
if (e.getKeyCode () == KeyEvent.VK_UP) {
p1.setupAccel(true);
}
else if (e.getKeyCode() == KeyEvent.VK_W) {
h2.setupAccel(true);
}
else if (e.getKeyCode() == KeyEvent.VK_S) {
h2.setdownAccel(true);
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
p1.setdownAccel(true);
}
else if (e.getKeyCode() == KeyEvent.VK_ENTER) {
gamestarted = true;
}
else if (e.getKeyCode() == KeyEvent.VK_X) {
gamestarted = true;
onev1 = true;
}
}
public void keyReleased(KeyEvent e) {
if (e.getKeyCode () == KeyEvent.VK_UP) {
p1.setupAccel(false);
}
else if (e.getKeyCode () == KeyEvent.VK_W) {
h2.setupAccel(false);
}
else if (e.getKeyCode() == KeyEvent.VK_S) {
h2.setdownAccel(false);
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
p1.setdownAccel(false);
}
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
| e3b8ef39237e81ccbfa3d41ef4a8a14333156a91 | [
"Java"
] | 3 | Java | Owen-Ng/Pong | 0e1548a13f6a63b05e052b18f38476ceef0f2eab | d3b52204b184a70a228782b5a6f1ebffa72e9ba0 |
refs/heads/master | <file_sep>from __future__ import (absolute_import, division, print_function,unicode_literals)
import datetime
import backtrader as bt
from backtrader.dataseries import TimeFrame
import backtrader.feeds as btfeeds
# import matplotlib.pyplot as plt
# plt.rcParams["font.sans-serif"] = ["SimHei"]
# plt.rcParams["axes.unicode_minus"] = False
#########################################################################################
# data
#########################################################################################
# 1、loading CSVData # 通达信导出的数据
class MyTDXCSVData(btfeeds.GenericCSVData):
params = (
('fromdate', datetime.datetime(2020, 5, 20)),
('todate', datetime.datetime(2020, 5, 23)),
('nullvalue', 0.0),
('dtformat', '%Y/%m/%d'),
('tmformat', '%H%M%S'),
('timeframe', TimeFrame.Minutes),
('datetime', 0),
('time', 1),
('open', 2),
('high', 3),
('low', 4),
('close', 5),
('volume', 6),
('openinterest', -1)
)
#########################################################################################
# 策略
#########################################################################################
# 1、随机random,概率大于0.5就买入,出现连续5根k线下跌或连续30根k线上涨则卖出。待实现。。。
# 移动平均线策略
# Create a subclass of Strategy to define the indicators and logic
class SmaCross(bt.Strategy):
params = (
('maperiod', 15),
)
def log(self, txt, dt=None):
''' Logging function fot this strategy'''
dt = dt or self.datas[0].datetime.datetime(0)
print('%s, %s' % (dt.isoformat(), txt))
def __init__(self):
# Keep a reference to the "close" line in the data[0] dataseries
self.dataclose = self.datas[0].close
# To keep track of pending orders and buy price/commission
self.order = None
self.buyprice = None
self.buycomm = None
self.sma = bt.indicators.MovingAverageSimple(self.datas[0], period=self.params.maperiod)
# Indicators for the plotting show
bt.indicators.ExponentialMovingAverage(self.datas[0], period=25)
bt.indicators.WeightedMovingAverage(self.datas[0], period=25).subplot = True
bt.indicators.StochasticSlow(self.datas[0])
bt.indicators.MACDHisto(self.datas[0])
rsi = bt.indicators.RSI(self.datas[0])
bt.indicators.SmoothedMovingAverage(rsi, period=10)
bt.indicators.ATR(self.datas[0]).plot = False
bt.indicators.
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
# Buy/Sell order submitted/accepted to/by broker - Nothing to do
return
# Check if an order has been completed
# Attention: broker could reject order if not enough cash
if order.status in [order.Completed]:
if order.isbuy():
self.log(
'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price,
order.executed.value,
order.executed.comm))
self.buyprice = order.executed.price
self.buycomm = order.executed.comm
else: # Sell
self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
(order.executed.price,
order.executed.value,
order.executed.comm))
self.bar_executed = len(self)
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log('Order Canceled/Margin/Rejected')
self.order = None
def notify_trade(self, trade):
if not trade.isclosed:
return
self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' %
(trade.pnl, trade.pnlcomm))
def next(self):
# Simply log the closing price of the series from the reference
self.log('Close, %.2f' % self.dataclose[0])
# Check if an order is pending ... if yes, we cannot send a 2nd one
if self.order:
return
# Check if we are in the market
if not self.position:
# Not yet ... we MIGHT BUY if ...
if self.dataclose[0] > self.sma[0]:
# BUY, BUY, BUY!!! (with all possible default parameters)
self.log('BUY CREATE, %.2f' % self.dataclose[0])
# Keep track of the created order to avoid a 2nd order
self.order = self.buy()
else:
if self.dataclose[0] < self.sma[0]:
# SELL, SELL, SELL!!! (with all possible default parameters)
self.log('SELL CREATE, %.2f' % self.dataclose[0])
# Keep track of the created order to avoid a 2nd order
self.order = self.sell()
if __name__ == '__main__':
cerebro = bt.Cerebro() # create a "Cerebro" engine instance
cerebro.addstrategy(SmaCross) # Add the trading strategy
data = MyTDXCSVData(dataname='C2105.csv')
cerebro.adddata(data) # Add the data feed
# Set our desired cash start
cerebro.broker.setcash(100000.0)
# Add a FixedSize sizer according to the stake
cerebro.addsizer(bt.sizers.FixedSize, stake=10)
# Set the commission - 0.1% ... divide by 100 to remove the %
cerebro.broker.setcommission(commission=0.001)
# Print out the starting conditions
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
# Run over everything
cerebro.run(maxcpus=1)
# Print out the final result
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.plot(start=0) # and plot it with a single command
| 0ab2355d6c384f8637c3b2c6b17db57e8473f468 | [
"Python"
] | 1 | Python | blackxer/backTest | 7b9edb55a2cb77a0ff61e100c8e041f359fbdf30 | 244fc6be1b626457d475ac57fc4fd368079342d6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.