From 9465097aa530f7195db2bf7d957000897e9d566b Mon Sep 17 00:00:00 2001 From: FollieHiyuki Date: Wed, 19 Jan 2022 22:32:57 +0700 Subject: [PATCH] Update and reorganize --- README.md | 2 +- c/TuringMachine/CMakeLists.txt | 8 + c/TuringMachine/command.c | 80 ++++++++++ c/TuringMachine/command.txt | 9 ++ c/TuringMachine/declaration.h | 51 +++++++ c/TuringMachine/description.c | 60 ++++++++ c/TuringMachine/description.txt | 2 + c/TuringMachine/index.c | 22 +++ c/TuringMachine/input.txt | 2 + c/TuringMachine/main.c | 125 ++++++++++++++++ c/TuringMachine/menu.c | 19 +++ c/TuringMachine/output.txt | 37 +++++ c/TuringMachine/run.c | 141 ++++++++++++++++++ .../BasicInterpreter}/Program.txt | 0 .../BasicInterpreter}/result.txt | 0 .../InterpreterAlpha/InterpreterAlpha.java | 0 .../src/InterpreterAlpha/Lexer.java | 0 .../src/InterpreterAlpha/Parser.java | 0 .../InterpreterAlphaTest.java | 0 .../test/InterpreterAlpha/LexerTest.java | 0 .../SymbolTableBuilderTest.java | 0 lua/math.lua | 54 +++++++ lua/string.lua | 29 ++++ python/SocketPractice/Client.py | 62 ++++++++ python/SocketPractice/Server.py | 66 ++++++++ python/SocketPractice/utility.py | 14 ++ watermark.ipynb => python/watermark.ipynb | 0 27 files changed, 782 insertions(+), 1 deletion(-) create mode 100644 c/TuringMachine/CMakeLists.txt create mode 100644 c/TuringMachine/command.c create mode 100644 c/TuringMachine/command.txt create mode 100644 c/TuringMachine/declaration.h create mode 100644 c/TuringMachine/description.c create mode 100644 c/TuringMachine/description.txt create mode 100644 c/TuringMachine/index.c create mode 100644 c/TuringMachine/input.txt create mode 100644 c/TuringMachine/main.c create mode 100644 c/TuringMachine/menu.c create mode 100644 c/TuringMachine/output.txt create mode 100644 c/TuringMachine/run.c rename {BasicInterpreter => java/BasicInterpreter}/Program.txt (100%) rename {BasicInterpreter => java/BasicInterpreter}/result.txt (100%) rename {BasicInterpreter => java/BasicInterpreter}/src/InterpreterAlpha/InterpreterAlpha.java (100%) rename {BasicInterpreter => java/BasicInterpreter}/src/InterpreterAlpha/Lexer.java (100%) rename {BasicInterpreter => java/BasicInterpreter}/src/InterpreterAlpha/Parser.java (100%) rename {BasicInterpreter => java/BasicInterpreter}/test/InterpreterAlpha/InterpreterAlphaTest.java (100%) rename {BasicInterpreter => java/BasicInterpreter}/test/InterpreterAlpha/LexerTest.java (100%) rename {BasicInterpreter => java/BasicInterpreter}/test/InterpreterAlpha/SymbolTableBuilderTest.java (100%) create mode 100644 lua/math.lua create mode 100644 lua/string.lua create mode 100644 python/SocketPractice/Client.py create mode 100644 python/SocketPractice/Server.py create mode 100644 python/SocketPractice/utility.py rename watermark.ipynb => python/watermark.ipynb (100%) diff --git a/README.md b/README.md index eb6c64b..8f7c69c 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,3 @@ -## Practice +# Practice Bunch of crappy code I wrote for practicing which serves no purpose. diff --git a/c/TuringMachine/CMakeLists.txt b/c/TuringMachine/CMakeLists.txt new file mode 100644 index 0000000..01473ad --- /dev/null +++ b/c/TuringMachine/CMakeLists.txt @@ -0,0 +1,8 @@ +cmake_minimum_required(VERSION 3.14) +project(TuringMachine C) + +set(CMAKE_C_STANDARD 11) + +include_directories(.) + +add_executable(TuringMachine main.c declaration.h command.c description.c index.c menu.c run.c) \ No newline at end of file diff --git a/c/TuringMachine/command.c b/c/TuringMachine/command.c new file mode 100644 index 0000000..7d8a523 --- /dev/null +++ b/c/TuringMachine/command.c @@ -0,0 +1,80 @@ +#include "declaration.h" + +void loadCommand(turing *t, char *nameFile) { + FILE *in; + in = fopen(nameFile, "r"); + if (in == NULL) { + printf("The file '%s' was not opened", nameFile); + exit(-1); + } + + printf("\nCommands:\n"); + int commandNumb = 1, N = 0; + t->commands = malloc((N + 1) * sizeof(command)); + int numb; + while (fscanf(in, "%d. ", &numb) != EOF) { + command tran; + char symbol1, symbol2, dir, state1, state2; + + if (numb <= 0) { + printf("Error in '%s' file. There may only be commands from [1...] interval \n", nameFile); + fclose(in); + exit(0); + } + if (numb != commandNumb) { + printf("Error in '%s' file. Command numbers must be in order \n", nameFile); + fclose(in); + exit(0); + } + commandNumb++; + + fscanf(in, "%c ", &state1); + fscanf(in, "%c ", &symbol1); + fscanf(in, "%c ", &symbol2); + fscanf(in, "%c ", &dir); + fscanf(in, "%c", &state2); + + tran.number = numb; + tran.state1 = stateIndex(t, state1); + + if (tran.state1 == -1) { + printf("Error in '%s' file", nameFile); + printf("\nIn the command %d, state %c isn't contained in the set of states of your Turing machine", numb, + state1); + fclose(in); + exit(0); + } + tran.symbol1 = symbolIndex(t, symbol1); + if (tran.symbol1 == -1) { + printf("\nError in '%s' file", nameFile); + printf("\nIn the commnand %d, symbol %c isn't contained in the alphabet of your Turing machine", numb, + symbol1); + fclose(in); + exit(0); + } + tran.symbol2 = symbolIndex(t, symbol2); + if (tran.symbol2 == -1) { + printf("\nError in 'command.txt' file"); + printf("\nIn the commnand %d, symbol %c isn't contained in the alphabet of your Turing machine", numb, + symbol2); + fclose(in); + exit(0); + } + tran.dir = dir; + tran.state2 = stateIndex(t, state2); + if (tran.state2 == -1) { + printf("\nError in '%s' file", nameFile); + printf("\nIn the command %d, state %c isn't contained in the set of states of your Turing machine", numb, + state2); + fclose(in); + exit(0); + } + + t->commands[N] = tran; + printf("%d. %c %c %c %c %c\n", numb, state1, symbol1, symbol2, dir, state2); + N++; + t->commands = realloc(t->commands, (N + 1) * sizeof(command)); + } + t->commandsNumb = N; + fclose(in); +} diff --git a/c/TuringMachine/command.txt b/c/TuringMachine/command.txt new file mode 100644 index 0000000..3771750 --- /dev/null +++ b/c/TuringMachine/command.txt @@ -0,0 +1,9 @@ +1. a 1 1 R a +2. a 0 0 R a +3. a B B L b +4. b 0 1 L c +5. b 1 0 L b +6. b B 1 L S +7. c 0 0 L c +8. c B B R S +9. c 1 1 L c \ No newline at end of file diff --git a/c/TuringMachine/declaration.h b/c/TuringMachine/declaration.h new file mode 100644 index 0000000..3c3d186 --- /dev/null +++ b/c/TuringMachine/declaration.h @@ -0,0 +1,51 @@ +#ifndef DECLARATION_H +#define DECLARATION_H + +#include +#include +#include +#include +#include + +#define ENTER 10 + +typedef struct { + int number; + int state1; //Тут сохраняется индекс состояния, при котором выплоняется команд, в массиве states + int symbol1; //Тут сохраняется индекс символа, при котором выплоняется команд, в массиве symbols + int symbol2; //Тут сохраняется индекс символа, который нужен записать в ячейку, в массиве symbols + char dir; //просто направление сдвига головки + int state2; //Тут сохраняется индекс состояния, в которое нужно перейти, в массиве states +} command; + +typedef struct tapeT tapeT; +struct tapeT { + int symbol; + tapeT *left; + tapeT *right; +}; + +typedef struct { + int statesNumb; // кол-во используемых состояний + char *states;//множество состояний + int symbolsNumb;// кол-во используемых символов + char *symbols;//альфавит + int state;// состояние в головке + int commandsNumb;//число команд + command *commands;//команды + tapeT *tape;// лента +} turing; + +int menu(int lastNumb); + +int stateIndex(turing *t, char state); //нахождение номер индекса состояния state в states +int symbolIndex(turing *t, char symbol); //нахождение номер индекса symbol в symbols +void loadCommand(turing *t, char *nameFile); //загрузка команд из текстового файла + +command findCommand(turing *t, char stateCurrent, char symbolCurrent);//нахождение нужной команды из список всех команд + +void run(turing *t, bool step, char *nameFile); + +void loadDescription(turing *t, char *nameFile); //загрузка описание машины из текстового файла + +#endif diff --git a/c/TuringMachine/description.c b/c/TuringMachine/description.c new file mode 100644 index 0000000..5356748 --- /dev/null +++ b/c/TuringMachine/description.c @@ -0,0 +1,60 @@ +#include "declaration.h" + +void loadDescription(turing *t, char *nameFile) { + FILE *in; + in = fopen(nameFile, "r"); + if (in == NULL) { + printf("The file '%s' was not opened", nameFile); + exit(-1); + } + bool testForS = false, testForBlank = false; + + printf("States: "); + int N = 0; + char c; + t->states = malloc((N + 1) * sizeof(char)); + fscanf(in, "%c", &c); + while (c != '\n') { + t->states[N] = c; + if (t->states[N] == 'S') { + testForS = true; + } + printf("%c ", t->states[N]); + fscanf(in, "%c", &c); + N++; + t->states = realloc(t->states, (N + 1) * sizeof(char)); + } + t->statesNumb = N; + + if (!testForS) { + printf("\nError in file '%s'", nameFile); + printf("\nThe set of states doesn't contain state STOP(S). Add S to it, please!"); + fclose(in); + exit(0); + } + + printf("\nAlphabet: "); + N = 0; + t->symbols = malloc((N + 1) * sizeof(char)); + while (fscanf(in, "%c", &c) != EOF) { + t->symbols[N] = c; + if (t->symbols[N] == 'B') testForBlank = true; + printf("%c ", t->symbols[N]); + N++; + t->symbols = realloc(t->symbols, (N + 1) * sizeof(char)); + } + t->symbolsNumb = N; + + if (!testForBlank) { + printf("\nError in file '%s'", nameFile); + printf("\nThe alphabet doesn't contain symbol Blank(B). Add B to it, please!"); + fclose(in); + exit(0); + } + + t->symbolsNumb++; + t->symbols[t->symbolsNumb - 1] = ' '; + printf("%c ", t->symbols[t->symbolsNumb - 1]); + + fclose(in); +} diff --git a/c/TuringMachine/description.txt b/c/TuringMachine/description.txt new file mode 100644 index 0000000..4ea2036 --- /dev/null +++ b/c/TuringMachine/description.txt @@ -0,0 +1,2 @@ +abcS +01B \ No newline at end of file diff --git a/c/TuringMachine/index.c b/c/TuringMachine/index.c new file mode 100644 index 0000000..96246fa --- /dev/null +++ b/c/TuringMachine/index.c @@ -0,0 +1,22 @@ +#include "declaration.h" + +int stateIndex(turing *t, char state) { + + int i; + for (i = 0; i < t->statesNumb; i++) { + if (t->states[i] == state) { + return i; + } + } + return -1; +} + +int symbolIndex(turing *t, char symbol) { + int i; + for (i = 0; i < t->symbolsNumb; i++) { + if (t->symbols[i] == symbol) { + return i; + } + } + return -1; +} diff --git a/c/TuringMachine/input.txt b/c/TuringMachine/input.txt new file mode 100644 index 0000000..9983d0a --- /dev/null +++ b/c/TuringMachine/input.txt @@ -0,0 +1,2 @@ +a +10011 \ No newline at end of file diff --git a/c/TuringMachine/main.c b/c/TuringMachine/main.c new file mode 100644 index 0000000..8fc02ec --- /dev/null +++ b/c/TuringMachine/main.c @@ -0,0 +1,125 @@ +#include "declaration.h" + +void loadTape(turing *t, char *nameFile) { + FILE *in; + in = fopen(nameFile, "r"); + if (in == NULL) { + printf("The file '%s' was not opened", nameFile); + exit(-1); + } + char state, linefeed; + fscanf(in, "%c", &state); + t->state = stateIndex(t, state); + printf("\nInitial state: %c\n", state); + if (t->state == -1) { + printf("Error in file '%s'\n", nameFile); + printf("Initial state %c isn't contained in the set of states of your Turing machine", state); + fclose(in); + exit(0); + } + fscanf(in, "%c", &linefeed); + if (linefeed != '\n') { + printf("Error in file '%s'. There may only be linefeed after initial state\n", nameFile); + fclose(in); + exit(0); + } + + t->tape = NULL; + char x; + fscanf(in, "%c ", &x); + printf("Initial tape: %c", x); + if (symbolIndex(t, x) == -1) { + printf("Error in '%s' file. Symbol %c isn't contained in the alphabet of your Turing machine", nameFile, x); + fclose(in); + exit(0); + } + if (t->tape == NULL) { + t->tape = malloc(sizeof(tapeT)); + t->tape->symbol = symbolIndex(t, x); + t->tape->right = NULL; + t->tape->left = NULL; + } + tapeT *temp_tape; + temp_tape = t->tape; + while (!feof(in)) { + fscanf(in, "%c ", &x); + printf("%c", x); + if (symbolIndex(t, x) == -1) { + printf("Error in '%s' file. Symbol %c isn't contained in the alphabet of your Turing machine", nameFile, x); + fclose(in); + exit(0); + } + if (temp_tape->right == NULL) { + tapeT *tmp_tp = temp_tape; + temp_tape->right = malloc(sizeof(tapeT)); + if (temp_tape->right == NULL) { + printf("Not enough memory for tape \n"); + exit(103); + } + temp_tape = temp_tape->right; + temp_tape->symbol = symbolIndex(t, x); + temp_tape->right = NULL; + temp_tape->left = tmp_tp; + } + } + printf("\n"); + fclose(in); + +} + +int main(int argc, char *args[]) { + if (argc != 5) { + printf("Error: input.txt description.txt command.txt output.txt \n"); + return -1; + } + bool ifLoadTape = false; + int menuNumb = 0, lastNumb = 4; + turing *t = malloc(sizeof(turing)); + loadDescription(t, args[2]); + loadCommand(t, args[3]); + while (menuNumb != 4) { + menuNumb = menu(lastNumb); + switch (menuNumb) { + case 1: + loadTape(t, args[1]); + ifLoadTape = true; + break; + case 2: + if (ifLoadTape == false) { + printf("Initial tape wasn't loaded. Load tape, please!\n"); + break; + } + run(t, false, args[4]); + ifLoadTape = false; + break; + case 3: + if (ifLoadTape == false) { + printf("Initial tape wasn't loaded. Load tape, please!\n"); + break; + } + run(t, true, args[4]); + ifLoadTape = false; + break; + case 4: + break; + default: + break; + } + } + + if (t->commands != NULL) + free(t->commands); + if (ifLoadTape) { + while (t->tape->left) { + tapeT *tmp; + tmp = t->tape; + t->tape = t->tape->left; + free(tmp); + } + t->tape = t->tape->left; + free(t->tape); + } + if (t != NULL) + free(t); + return 0; +} diff --git a/c/TuringMachine/menu.c b/c/TuringMachine/menu.c new file mode 100644 index 0000000..639a946 --- /dev/null +++ b/c/TuringMachine/menu.c @@ -0,0 +1,19 @@ +#include "declaration.h" + +int menu(int lastNumb) { + int number, ret; + printf("Modes of the machine:\n" + "1. Load tape \n" + "2. Run\n" + "3. Run step\n" + "4. Exit\n"); + while (1) { + printf("\nInput ordinal number of modes(1->%d)", lastNumb); + ret = scanf("%d", &number);; + if (ret == 1 && (number >= 1 && number <= lastNumb)) break; + fflush(stdin); + printf("Error. Number must be in the interval [1..%d]", lastNumb); + break; + } + return number; +} diff --git a/c/TuringMachine/output.txt b/c/TuringMachine/output.txt new file mode 100644 index 0000000..106a7c9 --- /dev/null +++ b/c/TuringMachine/output.txt @@ -0,0 +1,37 @@ +[1] 0 0 1 1 + +1. a 1 1 R a + 1 [0] 0 1 1 + +2. a 0 0 R a + 1 0 [0] 1 1 + +2. a 0 0 R a + 1 0 0 [1] 1 + +1. a 1 1 R a + 1 0 0 1 [1] + +1. a 1 1 R a + 1 0 0 1 1 [ ] + +3. a B B L b + 1 0 0 1 [1] + +5. b 1 0 L b + 1 0 0 [1] 0 + +5. b 1 0 L b + 1 0 [0] 0 0 + +4. b 0 1 L c + 1 [0] 1 0 0 + +7. c 0 0 L c +[1] 0 1 0 0 + +9. c 1 1 L c +[ ] 1 0 1 0 0 + +8. c B B R S + [1] 0 1 0 0 diff --git a/c/TuringMachine/run.c b/c/TuringMachine/run.c new file mode 100644 index 0000000..2743ce8 --- /dev/null +++ b/c/TuringMachine/run.c @@ -0,0 +1,141 @@ +#include "declaration.h" + +command findCommand(turing *t, char stateCurrent, char symbolCurrent) { + // find by state + command *resTrans1 = malloc(t->symbolsNumb * sizeof(command)); + command resTrans; + int j = 0; + for (int i = 0; i < t->commandsNumb; i++) { + if (t->states[t->commands[i].state1] == stateCurrent) { + resTrans1[j] = t->commands[i]; + j++; + } + } + // find by symbol + for (int i = 0; i < t->symbolsNumb - 1; i++) { + if (t->symbols[resTrans1[i].symbol1] == symbolCurrent) { + resTrans = resTrans1[i]; + } + } + free(resTrans1); + return resTrans; +} + +void run(turing *t, bool step, char *nameFile) { + int key; + char stepCommand[5]; + FILE *output; + output = fopen(nameFile, "w"); + if (output == NULL) { + printf("The file '%s' was not opened\n", nameFile); + exit(-1); + } + if (step) printf(" - next step, stop - stop, run - run\n"); + tapeT *tempTape = t->tape; + int idPrint = 0, i = 0; + command currentTrans; + while (1) { + if (i != 0) { + fprintf(output, "\n%d. %c %c %c %c %c\n", currentTrans.number, t->states[currentTrans.state1], + t->symbols[currentTrans.symbol1], t->symbols[currentTrans.symbol2], currentTrans.dir, + t->states[currentTrans.state2]); + printf("%d. %c %c %c %c %c", currentTrans.number, t->states[currentTrans.state1], + t->symbols[currentTrans.symbol1], t->symbols[currentTrans.symbol2], currentTrans.dir, + t->states[currentTrans.state2]); + printf("\nCurrent state: %c\n", t->states[currentTrans.state2]); + } + i++; + tapeT *tape = t->tape; + while (tape->left != NULL) { + tape = tape->left; + } + int idPrint1 = 0; + while (tape->right != NULL) { + if (idPrint1 == idPrint) { + fprintf(output, "[%c]", t->symbols[tape->symbol]); + printf("[%c]", t->symbols[tape->symbol]); + idPrint1++; + } else { + fprintf(output, " %c ", t->symbols[tape->symbol]); + printf(" %c ", t->symbols[tape->symbol]); + idPrint1++; + } + tape = tape->right; + } + if (idPrint1 == idPrint) { + fprintf(output, " [%c] ", t->symbols[tape->symbol]); + printf(" [%c] ", t->symbols[tape->symbol]); + } else { + fprintf(output, " %c ", t->symbols[tape->symbol]); + printf(" %c ", t->symbols[tape->symbol]); + } + fprintf(output, "\n"); + printf("\n"); + + if (t->states[t->state] == 'S') { + fclose(output); + return; + } + + if (t->symbols[tempTape->symbol] == ' ') { + currentTrans = findCommand(t, t->states[t->state], 'B'); + printf("1 \n"); + } else { + currentTrans = findCommand(t, t->states[t->state], t->symbols[tempTape->symbol]); + } + if (t->symbols[currentTrans.symbol2] == 'B') { + tempTape->symbol = t->symbolsNumb - 1; + } else { + tempTape->symbol = currentTrans.symbol2; + } + if (currentTrans.dir == 'R') { + idPrint++; + if (tempTape->right == NULL) { + tempTape->right = malloc(sizeof(tapeT)); + + + tapeT *tt = tempTape->right; + tt->left = tempTape; + tt->right = NULL; + tt->symbol = t->symbolsNumb - 1; + } + tempTape = tempTape->right; + } else { + idPrint--; + if (tempTape->left == NULL) { + tempTape->left = malloc(sizeof(tapeT)); + + + tapeT *tt = tempTape->left; + tt->right = tempTape; + tt->left = NULL; + tt->symbol = t->symbolsNumb - 1; + idPrint = 0; + } + tempTape = tempTape->left; + } + + t->state = currentTrans.state2; + + if (step) { + while (1) { + key = getc(stdin); + if (key == ENTER) break; + ungetc(key, stdin); + scanf(" %4s", stepCommand); + fflush(stdin); + if (!strcmp(stepCommand, "run")) { + step = false; + break; + } + if (!strcmp(stepCommand, "stop")) { + fclose(output); + return; + } + printf("error"); + fflush(stdin); + } + } + + } +} diff --git a/BasicInterpreter/Program.txt b/java/BasicInterpreter/Program.txt similarity index 100% rename from BasicInterpreter/Program.txt rename to java/BasicInterpreter/Program.txt diff --git a/BasicInterpreter/result.txt b/java/BasicInterpreter/result.txt similarity index 100% rename from BasicInterpreter/result.txt rename to java/BasicInterpreter/result.txt diff --git a/BasicInterpreter/src/InterpreterAlpha/InterpreterAlpha.java b/java/BasicInterpreter/src/InterpreterAlpha/InterpreterAlpha.java similarity index 100% rename from BasicInterpreter/src/InterpreterAlpha/InterpreterAlpha.java rename to java/BasicInterpreter/src/InterpreterAlpha/InterpreterAlpha.java diff --git a/BasicInterpreter/src/InterpreterAlpha/Lexer.java b/java/BasicInterpreter/src/InterpreterAlpha/Lexer.java similarity index 100% rename from BasicInterpreter/src/InterpreterAlpha/Lexer.java rename to java/BasicInterpreter/src/InterpreterAlpha/Lexer.java diff --git a/BasicInterpreter/src/InterpreterAlpha/Parser.java b/java/BasicInterpreter/src/InterpreterAlpha/Parser.java similarity index 100% rename from BasicInterpreter/src/InterpreterAlpha/Parser.java rename to java/BasicInterpreter/src/InterpreterAlpha/Parser.java diff --git a/BasicInterpreter/test/InterpreterAlpha/InterpreterAlphaTest.java b/java/BasicInterpreter/test/InterpreterAlpha/InterpreterAlphaTest.java similarity index 100% rename from BasicInterpreter/test/InterpreterAlpha/InterpreterAlphaTest.java rename to java/BasicInterpreter/test/InterpreterAlpha/InterpreterAlphaTest.java diff --git a/BasicInterpreter/test/InterpreterAlpha/LexerTest.java b/java/BasicInterpreter/test/InterpreterAlpha/LexerTest.java similarity index 100% rename from BasicInterpreter/test/InterpreterAlpha/LexerTest.java rename to java/BasicInterpreter/test/InterpreterAlpha/LexerTest.java diff --git a/BasicInterpreter/test/InterpreterAlpha/SymbolTableBuilderTest.java b/java/BasicInterpreter/test/InterpreterAlpha/SymbolTableBuilderTest.java similarity index 100% rename from BasicInterpreter/test/InterpreterAlpha/SymbolTableBuilderTest.java rename to java/BasicInterpreter/test/InterpreterAlpha/SymbolTableBuilderTest.java diff --git a/lua/math.lua b/lua/math.lua new file mode 100644 index 0000000..cc23ad1 --- /dev/null +++ b/lua/math.lua @@ -0,0 +1,54 @@ +#!/usr/bin/env lua5.3 + +-- NOTE: Lua uses double-precision float and 64-bit integer +-- (except when being specifically compiled with single-precision float and 32-bit integer) +-- Double-precision floating-point number: exact integers up to 2^53 +-- [1 bit](sign) + [11 bits](exponent) + [53 bits (52 explicitly stored)](fraction) +-- Single-precision floating-point number: exact integers up to 2^24 +-- [1 bit](sign) + [8 bits](exponent) + [24 bits (23 explicitly stored)](fraction) + +-- Integer wraps around +-- Below are max(min)imum presentable integers +print(math.maxinteger == 0x7fffffffffffffff) -- 2^63 - 1 +print(math.mininteger == 0x8000000000000000) + +-- Convert ineger to float (up to 2^53) +print(math.type(3 + 0.0)) +-- Force a number to be integer (has no fractional part) +local function cond2int(x) + return math.tointeger(x) or x +end +print(math.type(3.0 | 0)) +print(math.tointeger(356.00)) +print(math.tointeger(5.6)) +print(cond2int(5.6)) + +-- Hex numbers are auto-converted to dec +print(0xffa4) + +-- NOTE: operators of floats/integers returns a float/integer +-- Exception: division always returns a float. Use `//` to get an integer division +print(3 / 2) +print(math.pi // 1.2) + +-- Rounding decimal digits +local pi = math.pi +print(pi - pi % 0.0001) + +-- Radian is used by default +print(math.sin(30)) +print(math.deg(2 * math.pi)) + +-- Unbiased rounding number function (haft-integers are rounded to the nearest even integer) +-- Using simply math.floor(x + 0.5) will always round the number up (eg. 2.5 -> 3) +-- also 2^52 + 0.5 cannot be represent (2^52 -> 2^53 has fixed interval 1) +local function round(x) + local f = math.floor(x) + if x == f or (x % 2.0 == 0.5) then + return f + else + return math.floor(x + 0.5) + end +end +print(round(2.5)) +print(round(3.5)) diff --git a/lua/string.lua b/lua/string.lua new file mode 100644 index 0000000..2fe2ee6 --- /dev/null +++ b/lua/string.lua @@ -0,0 +1,29 @@ +-- Strings are immutable +-- 'modify' it by using another string +local a = 'one string' +local b = string.gsub('one string', 'one', 'another') +print(a) +print(b) + +-- Length +print(#"Count the length") + +-- C-like escape sequences +print("Backslash inside quotes: '\\'") +print('Backslash inside quotes: \'\\\'') + +-- utf-8 +print('\x42 is the letter B') +print('\u{3b1} is alpha') + +-- Querk +print('Notice the ]] below?') +print [===[a[b[i]] = x]===] +--[====[ Wow comment too +Still inside the comment +]====] print('Normal text here') + +-- \z skips all subsequent space characters +local data = '\x00\x01\x02\x03\x04\x05\x06\x07\z + \x08\x09\x0A\x0B\x0C\x0D\x0E\x0F' +print(data) diff --git a/python/SocketPractice/Client.py b/python/SocketPractice/Client.py new file mode 100644 index 0000000..d6cf65f --- /dev/null +++ b/python/SocketPractice/Client.py @@ -0,0 +1,62 @@ +import socket +from utility import wait_for_acknowledge + +# initiate connection +client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + +server_addr = (socket.gethostname(), 2019) # change here for sending to another machine in LAN +client.connect(server_addr) +print(f"Connected to server!") + +client.settimeout(5) # limit each communication time to 5s + +# listening to server command +print("Client is now waiting for server's command.") +cmd_from_server = wait_for_acknowledge(client, "Start sending image.") + +# send an ACK +imgCount_from_server = 0 +if cmd_from_server == "Start sending image.": + print("Command \"Start sending image.\" received.") + print("Sending ACK...") + client.sendall(bytes("ACK", "utf-8")) + try: + print("Client is now waiting for the number of images.") + imgCount_from_server = int(wait_for_acknowledge(client, str(3))) + + except: + raise ValueError("Number of images received is buggy.") + +if imgCount_from_server > 0: + print("Number of images to receive: ", imgCount_from_server) + print("Sending ACK...") + client.sendall(bytes("ACK", "utf-8")) + +print(f"Client is now eceiving {imgCount_from_server} images.") + +for i in range(imgCount_from_server): + index = i + 1 + file = f"./imgfromserver{index}.jpg" + try: # check for existing file, will overwrite + f = open(file, "x") + f.close() + except: + pass + finally: + f = open(file, "wb") + print(f"\tReceiving image {index}") + imgsize = int(wait_for_acknowledge(client, str(3))) + print(f"\tImage size of {imgsize}B received by Client") + print("Sending ACK...") + client.sendall(bytes("ACK", "utf-8")) + buff = client.recv(imgsize) + f.write(buff) + f.close() + print(f"File {file} received!") + print("Sending ACK...") + client.sendall(bytes("ACK", "utf-8")) + # a = wait_for_acknowledge(client,"This is done.") + +print("All images received.") +print("Closing connection.") +client.close() diff --git a/python/SocketPractice/Server.py b/python/SocketPractice/Server.py new file mode 100644 index 0000000..c105583 --- /dev/null +++ b/python/SocketPractice/Server.py @@ -0,0 +1,66 @@ +import socket +from os import listdir +from re import findall +from utility import wait_for_acknowledge + +"""Global Var""" +buff_size = 1024 +fileList = [file for file in listdir() if findall(r'.jpg',file) != []] #include all .jpg photos in that directory +#fileList = ['jihyo.jpg','dami.jpg','uju.jpg'] #images to be sent over to client + +#initiate connection +s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +server_addr = (socket.gethostname(), 2019) #change here for sending to another machine in LAN +s.bind(server_addr) +s.listen(5) + +client, address = s.accept() +print(f"Connection from {address} has been established!") + +#Send message to client to notify about sending image +print("Server sending command: \"Start sending image.\"") +client.sendall(bytes("Start sending image." ,"utf-8")) + +#wait for reply from client +print("Server is now waiting for acknowledge from client.") +ack_from_client = wait_for_acknowledge(client,"ACK") +if ack_from_client != "ACK": + raise ValueError('Client does not acknowledge command.') + +#Send message to client to notify about sending image +imgCount = len(fileList) +print("Server sends the number of images to be transfered client.") +client.sendall(bytes(str(imgCount) ,"utf-8")) + +#wait for reply from client +print("Server is now waiting for acknowledge from client.") +ack_from_client = wait_for_acknowledge(client,"ACK") +if ack_from_client != "ACK": + raise ValueError('Client does not acknowledge img count.') + + +print("Server will now send the images.",end='') +for file in fileList: + + img = open(file, 'rb') + b_img = img.read() + imgsize = len(b_img) + client.sendall(bytes(str(imgsize) ,"utf-8")) + print(f"\t sending image {file} size of {imgsize}B.") + + print("Server is now waiting for acknowledge from client.") + ack_from_client = wait_for_acknowledge(client,"ACK") + if ack_from_client != "ACK": + raise ValueError('Client does not acknowledge img size.') + client.sendall(b_img) + img.close() + print(f"Image {file} sent!") + + print("Server is now waiting for acknowledge from client.") + ack_from_client = wait_for_acknowledge(client,"ACK") + if ack_from_client != "ACK": + raise ValueError('Client does not acknowledge image transfer completion.') + + +print("All images sent.\nClosing connection.") +client.close() diff --git a/python/SocketPractice/utility.py b/python/SocketPractice/utility.py new file mode 100644 index 0000000..95082cd --- /dev/null +++ b/python/SocketPractice/utility.py @@ -0,0 +1,14 @@ +def wait_for_acknowledge(client, response): + """ + Waiting for this response to be sent from the other party + """ + amount_received = 0 + amount_expected = len(response) + + msg = str() + while amount_received < amount_expected: + data = client.recv(16) + amount_received += len(data) + msg += data.decode("utf-8") + # print(msg) + return msg diff --git a/watermark.ipynb b/python/watermark.ipynb similarity index 100% rename from watermark.ipynb rename to python/watermark.ipynb