Saturday, August 15, 2020

Railway Oriented Programming In CSharp

 Railway Oriented Programming My Implementation In CSharp





Error handling using ROP



Implementation of Either Monad using Interface

public interface IResult<T>
{
TResult Match<TResult>(
Func<T, TResult> onSuccess,
Func<ErrorType, TResult> onError
);
IResult<TResult> Map<TResult>(Func<T, TResult> f);
IResult<TResult> Bind<TResult>(Func<T, IResult<TResult>> f);
}
public class Success<T> : IResult<T>
{
private readonly T _results;
public Success(T results)
{
_results = results;
}
public TResult Match<TResult>(Func<T, TResult> onSuccess, Func<ErrorType, TResult> _) => onSuccess(_results);
public IResult<TResult> Map<TResult>(Func<T, TResult> f) => new Success<TResult>(f(_results));
public IResult<TResult> Bind<TResult>(Func<T, IResult<TResult>> f) => f(_results);
}
public class Error<T> : IResult<T>
{
private readonly ErrorType _error;
public Error(ErrorType error)
{
_error = error;
}
public TResult Match<TResult>(Func<T, TResult> _, Func<ErrorType, TResult> onError) => onError(_error);
public IResult<TResult> Map<TResult>(Func<T, TResult> _) => new Error<TResult>(_error);
public IResult<TResult> Bind<TResult>(Func<T, IResult<TResult>> _) => new Error<TResult>(_error);
}
view raw Result.cs hosted with ❤ by GitHub

Keeping all our errors in a single enum

public enum ErrorType
{
NameCanNotBeBlank,
EmailCanNotBeBlank,
EmailNotValid,
UserNotFound,
DatabaseUpdateError,
EmailNotSend
}
view raw ErrorType.cs hosted with ❤ by GitHub

Github Repo

Example taken from Railway Oriented Programming



Tuesday, October 1, 2019

Parsing escape backslashes invalid JSON

let data = jsonData.replace(/(^\{.*"Data":")(.*)("\}$)/,"$2")
let x = JSON.parse(data)



Sunday, September 15, 2019

A Very Functional QuickSort


public static IEnumerable<T> QuickSort<T>(IEnumerable<T> A)
{
int size = A.Count();
var pivot = size > 1 ? A.ToList()[new Random().Next(0, size - 1)] : default(T);
return size > 1
? QuickSort<T>(A.Where(x => Comparer<T>.Default.Compare(x, pivot) < 0))
.Concat(A.Where(x => Comparer<T>.Default.Compare(x, pivot) == 0))
.Concat(QuickSort<T>(A.Where(x => Comparer<T>.Default.Compare(x, pivot) > 0)))
: A;
}

Monday, October 22, 2018

Image convert to Base64 (from file to string)


<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function readFile() {
if (this.files && this.files[0]) {
var FR= new FileReader();
FR.addEventListener("load", function(e) {
document.getElementById("img").src = e.target.result;
document.getElementById("b64").innerHTML = e.target.result;
});
FR.readAsDataURL( this.files[0] );
}
}
document.getElementById("imgFile").addEventListener("change", readFile);
});
</script>
</head>
<body>
<input id="imgFile" onload="readFile();" type="file" /><br>
<div id="b64"></div>
<img id="img" width="100" height="100"/>
</body>
</html>

Demo:


Thursday, March 1, 2018

Random Restart Hill Climbing For N Queen

Hill climbing is an optimization technique which is a local search algorithm. It is an algorithm that starts with a random solution to a problem. By changing a single element of the solution it attempts to find a better solution. Hill climbing is sometimes called greedy local search because it grabs a good neighbor state without thinking ahead about where to go next.
To find a global maxima random restart hill climbing is used. Random restart hill climbing is a series of hill climbing searches. From randomly generated initial state until a goal is found.

board setup: n queens, one queen per column
successors : The successors of a state are all possible states generated by moving a single queen to another square in the same column. Meaning, there are n queens on the board and each queen can move to n-1 defined positions. So, each state has n*(n-1) successors.
heuristic cost function h : h is the number of pairs of queens that are attacking each other
Basic hill climbing creates a random state of the board. Then it finds the highest value successor of the current state(for n queen the lowest valued successor), which is called the neighbor. If the heuristic cost value of the neighbor is less than the heuristic cost value of the current state, then the neighbor becomes the current state. If not then the current solution is the minima of the current hill.
What random restart does is, it runs the hill climbing until the global minima is found. In each hill climbing, it creates a new initial state of the board then runs the hill climbing algorithm to find the minima of the hill. It stops when the global minima is reached.
h(board)
1  returns the number of attacking pair on board

highest_valued_successor_of_current(current)
1  best_h  
2  best_successor  NULL
3  while(new successor can be created)
4      successor  new_successor(current)
5      if h(successor) < best_h 
6           best_h  h(successor)
7           best_successor  successor
8  return successor


hill_climbing()
1  current  A random state of the board
2  while(1)
3      neighbor  highest_valued_successor_of_current(current)
4      if h(neighbor) >= h(current) 
5           return current
6      neighbor  current

random_restart_hill_climbing()
1  final_h  
2  best_board  NULL
3  while(final_h != 0)
4       result  hill_climbing()
5       now_h  h(result)
6       if final_h > now_h
7            final_h  now_h
8            best_board  result
9  return best_board
FINAL:
Total Iteration needed : 13
number of conflict on final board : 0
board:
0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0
0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0
view raw output.txt hosted with ❤ by GitHub
#include<bits/stdc++.h>
using namespace std;
#define si 16 /// 16 queen
///for generating random numbers
random_device rseed;
mt19937 rgen(rseed()); // mersenne_twister
uniform_int_distribution<int> idist(0,si-1); // [0,15]
int iteration = 0;
void show_board(vector<int> a){
int b[si][si];
memset(b,0,sizeof(b));
for(int i=0;i<a.size();i++){
b[a[i]][i] = 1;
}
for(int i=0;i<si;i++){
for(int j=0;j<si;j++){
cout<<b[i][j]<<" ";
}
cout<<"\n";
}
}
vector<int> make_node(){
vector<int> board;
bool vis[20];
memset(vis,false,sizeof(vis));
srand(time(0));
for(int i=1;i<=si;i++){
int num = idist(rgen);
while(vis[num]==true)
num = idist(rgen);
board.push_back(num);
vis[num] = true;
}
return board;
}
int h(vector<int> current){
int val,row1,col1,row2,col2;
val = 0;
for(int i=0;i<current.size();i++){
row1 = current[i];
col1 = i;
for(int j=i+1;j<current.size();j++){
row2 = current[j];
col2 = j;
if((row1==row2) || (col1==col2) || (abs(row1-row2)==abs(col1-col2)) ){
val++;
}
}
}
return val;
}
vector<int> get_highest_valued_successor_of_current(vector<int> current){
vector<int> successor,best_successor;
int best_h = INT_MAX;
int row,col;
for(int i=0;i<current.size();i++){
row = current[i];
col = i;
for(int j=0;j<si;j++){
if(row == j) continue;
current[i] = j;
successor = current;
current[i] = row;
int now = h(successor);
if(now<best_h){
best_successor = successor;
best_h = now;
}
}
}
return best_successor;
}
vector<int> hill_climbing(){
/// index is the column number of the queen and the value is the row number
vector<int> current = make_node();
vector<int> neighbor;
while(1){
neighbor = get_highest_valued_successor_of_current(current);
if(h(neighbor)>=h(current)) return current;
current = neighbor;
}
}
vector<int> random_restart_hill_climbing(){
int val = INT_MAX;
vector<int> best;
iteration = 0;
while(val!=0){
iteration++;
vector<int> result = hill_climbing();
int now = h(result);
if(val>=now){
best = result;
val = now;
}
}
return best;
}
int main(){
vector<int> result = random_restart_hill_climbing();
cout<<"FINAL:\n";
cout<<"Total Iteration needed : "<<iteration<<"\n";
cout<<"number of conflict on final board : "<<h(result)<<"\n";
cout<<"board: \n";
show_board(result);
return 0;
}

Saturday, January 27, 2018

Use of CFGs for Parsing OPEN

We can think of using CFGs to detect various language constructs in the token streams freed from simple
syntactic and semantic errors, as it is easier to describe the constructs with CFGs. But CFGs are hard to
apply practically. In this session we first exercise on simpler implementations of CFGs, and then
implement the FIRST and FOLLOW functions that facilitate efficient parsing algorithms for practical
problems.

Session 5 by Nafis Islam on Scribd


#include<bits/stdc++.h>
using namespace std;
int i=0,f=0,l;
string st;
void A() {
if (st[i] == 'a') {
i++;
f=1;
}
else {
f=0;
return;
}
if (i<l-1) A();
}
void B() {
if (st[i] == 'b') {
i++;
f=1;
return;
}
else {
f=0;
return;
}
}
void S() {
if (st[i] == 'b'){
i++;
f = 1;
return;
}
else {
A();
if (f) { B(); return;}
}
}
int main(){
freopen("i1.txt","r",stdin);
freopen("o1.txt","w",stdout);
while(getline(cin,st)){
f = 0;
i = 0;
l = st.size();
S();
if(l==i && f){
cout<<"valid\n";
}
else{
cout<<"invalid\n";
}
}
}
view raw grammar1.cpp hosted with ❤ by GitHub
b
ab
aab
aaab
view raw i1.txt hosted with ❤ by GitHub
valid
valid
valid
valid
view raw oi.txt hosted with ❤ by GitHub

#include<bits/stdc++.h>
using namespace std;
int i=0,f=0,l;
string s;
void X(){
if(s[i]=='b'){
i++;
f = 1;
}
else{
f = 0;
return;
}
if(s[i]=='b'){
i++;
f = 1;
if(i!=l-1) X();
}
else if(s[i]=='c'){
i++;
f = 1;
if(i!=l-1) X();
}
else{
f = 0;
return;
}
}
void A(){
if(s[i]=='a'){
i++;
f = 1;
}
else return;
if(i!=l-1){
X();
}
if(i==l-1 && f){
if(s[i]=='d'){
f = 1;
i++;
return;
}
else{
f = 0;
return;
}
}
}
int main(){
freopen("i2.txt","r",stdin);
freopen("o2.txt","w",stdout);
while(getline(cin,s)){
f = 0;
i = 0;
l = s.size();
A();
if(l==i && f){
cout<<"valid\n";
}
else{
cout<<"invalid\n";
}
}
}
view raw grammar2.cpp hosted with ❤ by GitHub
asasfas
bba
ba
abbd
view raw i2.txt hosted with ❤ by GitHub
invalid
invalid
invalid
valid
view raw out.txt hosted with ❤ by GitHub

#include<bits/stdc++.h>
using namespace std;
vector<string>sp,ke,ri;
map<string,string>mp,mpp;
string ans;
bool isTERMINAL(char a){
if(a>='A' && a<='Z') return true;
return false;
}
void FIRST(string key){
string val = mp[key];
if(isTERMINAL(val[0])){
string p = "";
p += val[0];
FIRST(p);
}
else{
ans += val[0];
ans += ",";
int flag = 0;
for(int i=0;i<val.size();i++){
if(val[i]=='|'){
flag = 1;
continue;
}
if(flag){
ans += val[i];
}
}
}
}
void FOLLOW(string key,int z){
int flag = 0;
for(int i=0;i<ri.size();i++){
if (ri[i].find(key) != string::npos) {
if(key.size()==1){
for(int j=0;j<ri[i].size();j++){
if(ri[i][j]==key[0]){
if(j+1<ri.size() && ri[i][j+1]!='\''){
flag = 1;
if(isTERMINAL(ri[i][j+1])==false){
if(z==0)ans += "$,";
ans += ri[i][j+1];
}
else{
string g = ri[i];
g.erase(0,1);
FIRST(g);
if(z==0)ans += "$,";
FOLLOW(mpp[ri[i]],1);
}
break;
}
}
}
}
else{
flag = 1;
for(int j=0;j+1<ri[i].size();j++){
if(ri[i][j]==key[0] && ri[i][j+1]==key[1]){
if(j+2>=ri[i].size()){
FOLLOW(mpp[ri[i]],1);
if(z==0)ans += ",$";
}
else{
}
}
}
break;
}
}
if(flag) break;
}
}
string remove_space(string s){
string p="";
for(int i=0;i<s.size();i++){
if(s[i]!=' ') p = p + s[i];
}
return p;
}
int main(){
freopen("input.txt","r",stdin);
freopen("out.txt","w",stdout);
string s;
while(getline(cin,s)){
sp.push_back(remove_space(s));
}
for(int i=0;i<sp.size();i++){
int flag = 0;
string key="",val="";
for(int j=0;j<sp[i].size();j++){
if(sp[i][j]=='='){
flag = 1;
continue;
}
if(flag==0) key += sp[i][j];
else val += sp[i][j];
}
mp[key] = val;
ke.push_back(key);
}
cerr<<"FIRST: \n\n";
cout<<"FIRST: \n\n";
for(int i=0;i<ke.size();i++){
ans = "";
FIRST(ke[i]);
cerr<<"FIRST("<<ke[i]<<")"<<" = {"<<ans<<"}\n";
cout<<"FIRST("<<ke[i]<<")"<<" = {"<<ans<<"}\n";
}
for(int i=0;i<ke.size();i++){
string val = mp[ke[i]];
string v = "";
for(int j=0;j<val.size();j++){
if(val[j]=='|') break;
v += val[j];
}
mp[ke[i]] = v;
mpp[v] = ke[i];
ri.push_back(v);
}
cerr<<"\nFOLLOW: \n\n";
cout<<"\nFOLLOW: \n\n";
for(int i=0;i<ke.size();i++){
ans = "";
FOLLOW(ke[i],0);
cerr<<"FOLLOW("<<ke[i]<<")"<<" = {"<<ans<<"}\n";
cout<<"FOLLOW("<<ke[i]<<")"<<" = {"<<ans<<"}\n";
}
}
E = TE'
E' = +TE' | #
T = FT'
T' = *FT' | #
F = (E) | id
view raw input.txt hosted with ❤ by GitHub
FIRST:
FIRST(E) = {(,id}
FIRST(E') = {+,#}
FIRST(T) = {(,id}
FIRST(T') = {*,#}
FIRST(F) = {(,id}
FOLLOW:
FOLLOW(E) = {$,)}
FOLLOW(E') = {),$}
FOLLOW(T) = {+,$,)}
FOLLOW(T') = {+,),$}
FOLLOW(F) = {*,$,+,)}
view raw output.txt hosted with ❤ by GitHub

Football Player Transfer Prediction

Football Player Transfer Prediction Using Different Classifiers Project Report :  Football Player Transfer Prediction Report ...