branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>dangerousHobo/polish-notation-roman-numeral-calculator<file_sep>/tests/add.c
#include <stdlib.h>
#include "unity.h"
#include "roman.h"
#include "add.h"
void test_add_I_I(void)
{
roman_t r; //final roman numeral
int a = roman_to_arabic("I");
int b = roman_to_arabic("I");
TEST_ASSERT_EQUAL_INT(0, arabic_to_roman(a+b, &r));
TEST_ASSERT_EQUAL_STRING("II", (char*)r);
}
void test_add_I_II(void)
{
roman_t r; //final roman numeral
int a = roman_to_arabic("I");
int b = roman_to_arabic("II");
TEST_ASSERT_EQUAL_INT(0, arabic_to_roman(a+b, &r));
TEST_ASSERT_EQUAL_STRING("III", (char*)r);
}
void test_add_I_III(void)
{
roman_t r; //final roman numeral
int a = roman_to_arabic("I");
int b = roman_to_arabic("III");
TEST_ASSERT_EQUAL_INT(0, arabic_to_roman(a+b, &r));
TEST_ASSERT_EQUAL_STRING("IV", (char*)r);
}
void test_add_I_IV(void)
{
roman_t r; //final roman numeral
int a = roman_to_arabic("I");
int b = roman_to_arabic("IV");
TEST_ASSERT_EQUAL_INT(0, arabic_to_roman(a+b, &r));
TEST_ASSERT_EQUAL_STRING("V", (char*)r);
}
void test_add_I_V(void)
{
roman_t r; //final roman numeral
int a = roman_to_arabic("I");
int b = roman_to_arabic("V");
TEST_ASSERT_EQUAL_INT(0, arabic_to_roman(a+b, &r));
TEST_ASSERT_EQUAL_STRING("VI", (char*)r);
}
void test_add_IV_I(void)
{
roman_t r; //final roman numeral
int a = roman_to_arabic("IV");
int b = roman_to_arabic("I");
TEST_ASSERT_EQUAL_INT(0, arabic_to_roman(a+b, &r));
TEST_ASSERT_EQUAL_STRING("V", (char*)r);
}
void test_add_IV_V(void)
{
roman_t r; //final roman numeral
int a = roman_to_arabic("IV");
int b = roman_to_arabic("V");
TEST_ASSERT_EQUAL_INT(0, arabic_to_roman(a+b, &r));
TEST_ASSERT_EQUAL_STRING("IX", (char*)r);
}
void test_add_X_XXX(void)
{
roman_t r; //final roman numeral
int a = roman_to_arabic("X");
int b = roman_to_arabic("XXX");
TEST_ASSERT_EQUAL_INT(0, arabic_to_roman(a+b, &r));
TEST_ASSERT_EQUAL_STRING("XL", (char*)r);
}
void test_add_failure_1(void)
{
roman_t r; //final roman numeral
int a = roman_to_arabic("G");
int b = roman_to_arabic("I");
TEST_ASSERT_EQUAL_INT(-1, arabic_to_roman(a+b, &r));
}
void test_add_failure_2(void)
{
roman_t r; //final roman numeral
int a = roman_to_arabic("I");
int b = roman_to_arabic("MMMCMXCIX");
TEST_ASSERT_EQUAL_INT(-1, arabic_to_roman(a+b, &r));
}
void run_tests_addition(void)
{
RUN_TEST(test_add_I_I);
RUN_TEST(test_add_I_II);
RUN_TEST(test_add_I_III);
RUN_TEST(test_add_I_IV);
RUN_TEST(test_add_I_V);
RUN_TEST(test_add_IV_I);
RUN_TEST(test_add_IV_V);
RUN_TEST(test_add_X_XXX);
RUN_TEST(test_add_failure_1);
RUN_TEST(test_add_failure_2);
}
<file_sep>/tests/sub.c
#include <stdlib.h>
#include "unity.h"
#include "roman.h"
#include "sub.h"
void test_sub_I_II(void)
{
roman_t r; //final roman numeral
int a = roman_to_arabic("I");
int b = roman_to_arabic("II");
TEST_ASSERT_EQUAL_INT(0, arabic_to_roman(b-a, &r));
TEST_ASSERT_EQUAL_STRING("I", (char*)r);
}
void test_sub_I_V(void)
{
roman_t r; //final roman numeral
int a = roman_to_arabic("I");
int b = roman_to_arabic("V");
TEST_ASSERT_EQUAL_INT(0, arabic_to_roman(b-a, &r));
TEST_ASSERT_EQUAL_STRING("IV", (char*)r);
}
void test_sub_I_VI(void)
{
roman_t r; //final roman numeral
int a = roman_to_arabic("I");
int b = roman_to_arabic("VI");
TEST_ASSERT_EQUAL_INT(0, arabic_to_roman(b-a, &r));
TEST_ASSERT_EQUAL_STRING("V", (char*)r);
}
void test_sub_failure_zero(void)
{
roman_t r; //final roman numeral
int a = roman_to_arabic("I");
int b = roman_to_arabic("I");
TEST_ASSERT_EQUAL_INT(-1, arabic_to_roman(b-a, &r));
}
void test_sub_failure_negative(void)
{
roman_t r; //final roman numeral
int a = roman_to_arabic("V");
int b = roman_to_arabic("I");
TEST_ASSERT_EQUAL_INT(-1, arabic_to_roman(b-a, &r));
}
void run_tests_subtraction(void)
{
RUN_TEST(test_sub_I_II);
RUN_TEST(test_sub_I_V);
RUN_TEST(test_sub_I_VI);
RUN_TEST(test_sub_failure_zero);
RUN_TEST(test_sub_failure_negative);
}
<file_sep>/tests/main.c
#include <stdlib.h>
#include "unity.h"
#include "add.h"
#include "sub.h"
#include "roman2arabic.h"
#include "arabic2roman.h"
int main(void)
{
UNITY_BEGIN();
run_tests_addition();
run_tests_subtraction();
run_tests_roman_to_arabic();
run_tests_arabic_to_roman();
return UNITY_END();
}<file_sep>/src/calc.c
/*
* <NAME>
* 2016-09-19
* Roman Numeral Polish notation calculator
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "roman.h"
void usage(char **argv)
{
printf("Usage: %s [+|-] RomanNumeral RomanNumeral\n", argv[0]);
}
int main(int argc, char **argv)
{
if (4 != argc) {
usage(argv);
return 1;
}
roman_t r; //final roman numeral
int a = roman_to_arabic(argv[2]);
int b = roman_to_arabic(argv[3]);
if (0 >= a || 0 >= b) {
puts("Invalid Roman Numeral");
return 1;
}
if (0 == strncmp("+", argv[1], 1)) {
if (0 != arabic_to_roman(a + b, &r)) {
puts("Failed to preform the addition");
return 1;
}
} else if (0 == strncmp("-", argv[1], 1)) {
if (0 != arabic_to_roman(b - a, &r)) {
puts("Failed to preform the subtraction");
return 1;
}
} else {
puts("Unknown operation");
usage(argv);
return 1;
}
// Print result
printf("%s\n", r);
free(r);
return 0;
}
<file_sep>/src/roman.h
#ifndef roman_h_
#define roman_h_
#define MAX_ARABIC 3999
#define MAX_ROMAN_LENGTH 9
typedef char* roman_t;
typedef unsigned int arabic_t;
int arabic_to_roman(arabic_t a, roman_t* r);
int roman_to_arabic(const roman_t r);
#endif // roman_h_
<file_sep>/src/roman.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "roman.h"
/* map arabic numerals to roman numerals */
struct map_elem {
arabic_t arabic;
roman_t roman;
};
struct map_elem rmap[] = {
{1, "I"},
{4, "IV"},
{5, "V"},
{9, "IX"},
{10, "X"},
{40, "XL"},
{50, "L"},
{90, "XC"},
{100, "C"},
{400, "CD"},
{500, "D"},
{900, "CM"},
{1000, "M"},
};
#define MAP_ELEM_LENGTH 13
// Convert arabic numeral a to roman numeral stored in r.
// Zero returned on success, negative value on error.
int arabic_to_roman(arabic_t a, roman_t* r)
{
if (1 > a || MAX_ARABIC < a) // arabic out of accepted range
return -1;
// Allocate vector for roman numerals
*r = calloc((MAX_ROMAN_LENGTH+1),sizeof(char)); //+1 for '\0'
if (NULL == *r)
return errno;
int idx = MAP_ELEM_LENGTH-1; //last index in mapped roman numeral list
// Build roman numeral
do {
struct map_elem v = rmap[idx];
if (a >= v.arabic) {
strcat((char*)*r, v.roman);
a = a - v.arabic;
} else {
idx--;
}
} while ((0 < a) && (0 <= idx));
if (0 != a) {
free(r);
return -1;
}
return 0;
}
// See if we can match rmn with a roman numeral in rmap, len specifies how
// many elements in rmn we should be looking at.
// Returns its arabic value, negative value returned if no match was found.
int match(const roman_t rmn, size_t len)
{
int idx;
for (idx = 0; idx < MAP_ELEM_LENGTH; idx++) {
if (0 == strncmp(rmap[idx].roman, rmn, len))
return rmap[idx].arabic;
}
return -1;
}
// Convert passed roman numeral r to arabic.
// Arabic value returned, negative value returned on error.
int roman_to_arabic(const roman_t r)
{
arabic_t a = 0; //initial arabic value
int idx = 0; //initial start index
int m = 0; //initial match value
do {
// Try to match next two roman numeral characters
if (2 <= strlen((char*)r)-idx) {
m = match(&r[idx], 2);
if (0 < m) {
a = a + m;
idx = idx + 2;
continue;
}
}
// Couldn't find match, try just first character
m = match(&r[idx], 1);
if (0 < m) {
a = a + m;
idx++;
continue;
}
// Failure, couldn't match the character as a roman numeral
return -1;
} while (idx < strlen((char*)r));
return a;
}
<file_sep>/tests/sub.h
#ifdef _subtraction_test_h_
#define _subtraction_test_h_
void test_sub_I_II(void);
void test_sub_I_V(void);
void test_sub_I_VI(void);
void test_sub_failure_zero(void);
void test_sub_failure_negative(void);
void run_tests_subtraction(void);
#endif
<file_sep>/tests/roman2arabic.c
#include <stdlib.h>
#include "unity.h"
#include "roman.h"
#include "roman2arabic.h"
void test_r2a_1(void)
{
roman_t r = "I";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 1);
}
void test_r2a_2(void)
{
roman_t r = "II";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 2);
}
void test_r2a_3(void)
{
roman_t r = "III";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 3);
}
void test_r2a_4(void)
{
roman_t r = "IV";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 4);
}
void test_r2a_5(void)
{
roman_t r = "V";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 5);
}
void test_r2a_6(void)
{
roman_t r = "VI";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 6);
}
void test_r2a_7(void)
{
roman_t r = "VII";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 7);
}
void test_r2a_8(void)
{
roman_t r = "VIII";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 8);
}
void test_r2a_9(void)
{
roman_t r = "IX";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 9);
}
void test_r2a_10(void)
{
roman_t r = "X";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 10);
}
void test_r2a_11(void)
{
roman_t r = "XI";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 11);
}
void test_r2a_15(void)
{
roman_t r = "XV";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 15);
}
void test_r2a_19(void)
{
roman_t r = "XIX";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 19);
}
void test_r2a_20(void)
{
roman_t r = "XX";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 20);
}
void test_r2a_25(void)
{
roman_t r = "XXV";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 25);
}
void test_r2a_30(void)
{
roman_t r = "XXX";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 30);
}
void test_r2a_40(void)
{
roman_t r = "XL";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 40);
}
void test_r2a_49(void)
{
roman_t r = "XLIX";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 49);
}
void test_r2a_50(void)
{
roman_t r = "L";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 50);
}
void test_r2a_90(void)
{
roman_t r = "XC";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 90);
}
void test_r2a_100(void)
{
roman_t r = "C";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 100);
}
void test_r2a_400(void)
{
roman_t r = "CD";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 400);
}
void test_r2a_500(void)
{
roman_t r = "D";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 500);
}
void test_r2a_900(void)
{
roman_t r = "CM";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 900);
}
void test_r2a_1000(void)
{
roman_t r = "M";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 1000);
}
void test_r2a_3999(void)
{
roman_t r = "MMMCMXCIX";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, 3999);
}
void test_r2a_fail_invalid_char(void)
{
roman_t r = "G";
int ret;
ret = roman_to_arabic(r);
TEST_ASSERT_EQUAL_INT(ret, -1);
}
/* Tests for roman_to_arabic to suite */
void run_tests_roman_to_arabic(void)
{
RUN_TEST(test_r2a_1);
RUN_TEST(test_r2a_2);
RUN_TEST(test_r2a_3);
RUN_TEST(test_r2a_4);
RUN_TEST(test_r2a_5);
RUN_TEST(test_r2a_6);
RUN_TEST(test_r2a_7);
RUN_TEST(test_r2a_8);
RUN_TEST(test_r2a_9);
RUN_TEST(test_r2a_10);
RUN_TEST(test_r2a_11);
RUN_TEST(test_r2a_15);
RUN_TEST(test_r2a_19);
RUN_TEST(test_r2a_20);
RUN_TEST(test_r2a_25);
RUN_TEST(test_r2a_30);
RUN_TEST(test_r2a_40);
RUN_TEST(test_r2a_49);
RUN_TEST(test_r2a_50);
RUN_TEST(test_r2a_90);
RUN_TEST(test_r2a_100);
RUN_TEST(test_r2a_400);
RUN_TEST(test_r2a_500);
RUN_TEST(test_r2a_900);
RUN_TEST(test_r2a_1000);
RUN_TEST(test_r2a_3999);
RUN_TEST(test_r2a_fail_invalid_char);
}
<file_sep>/README.md
# Polish notation Roman Numeral Calculator
This packages builds a library `libroman.a` for converting from Roman numeral to Arabic numeral and from Arabic numeral to Roman Numeral.
A small calculator program is also built (`src/calc`) that handles addition and subtraction in Polish notation.
Written for this coding exercise: http://codingdojo.org/cgi-bin/index.pl?KataRomanCalculator
## Building
make
make test
## Unity Unit Testing
The Unity unit testing framework is used. https://www.throwtheswitch.org/unity
....
-----------------------
70 Tests 0 Failures 0 Ignored
OK
## Calculator
> ./src/calc + II II
>> IV
> ./src/calc - IV X
>> VI
> ./src/calc - I E
>> Invalid Roman Numeral
> ./src/calc - I I
>> Failed to preform the subtraction
### Built and Tested on
* Kubuntu 18.04
* GNU Make 4.1
* GCC 7.2.0 and Clang 5.0
<file_sep>/tests/arabic2roman.h
#ifdef _arabic2roman_test_h_
#define _arabic2roman_test_h_
void test_a2r_1(void);
void test_a2r_2(void);
void test_a2r_3(void);
void test_a2r_4(void);
void test_a2r_5(void);
void test_a2r_6(void);
void test_a2r_7(void);
void test_a2r_8(void);
void test_a2r_9(void);
void test_a2r_10(void);
void test_a2r_11(void);
void test_a2r_15(void);
void test_a2r_19(void);
void test_a2r_20(void);
void test_a2r_25(void);
void test_a2r_30(void);
void test_a2r_40(void);
void test_a2r_49(void);
void test_a2r_50(void);
void test_a2r_90(void);
void test_a2r_100(void);
void test_a2r_400(void);
void test_a2r_500(void);
void test_a2r_900(void);
void test_a2r_1000(void);
void test_a2r_3999(void);
void test_a2r_fail_large(void);
void test_a2r_fail_zero(void);
void run_tests_arabic_to_roman(void);
#endif
<file_sep>/Makefile
PATHU = tests/unity/
PATHS = src/
PATHT = tests/
PATHB = build/
AR = ar
CC = clang-5.0
CFLAGS = -Wall -I$(PATHU) -I$(PATHS) -I$(PATHT) -g -O0
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
all: src/libroman.a src/calc
src/libroman.a: src/roman.o
$(AR) rcs $@ $?
src/calc: src/calc.o src/libroman.a
$(CC) $(CFLAGS) $? -o $@
#test: tests/main.o tests/arabic2roman.o tests/roman2arabic.o tests/add.o tests/sub.o src/libroman.a
test: $(PATHU)unity.o $(PATHT)add.o $(PATHT)sub.o $(PATHT)roman2arabic.o $(PATHT)arabic2roman.o $(PATHT)main.o $(PATHS)libroman.a
$(CC) $(CFLAGS) -static $? -o tests/testme
./tests/testme
clean:
rm -f $(PATHT)*.o
rm -f $(PATHT)testme
rm -f $(PATHU)*.o
rm -f $(PATHS)*.a
rm -f $(PATHS)*.o
rm -f $(PATHS)calc
.PHONY: all test clean
<file_sep>/tests/roman2arabic.h
#ifdef _roman2arabic_test_h_
#define _roman2arabic_test_h_
void test_r2a_1(void);
void test_r2a_2(void);
void test_r2a_3(void);
void test_r2a_4(void);
void test_r2a_5(void);
void test_r2a_6(void);
void test_r2a_7(void);
void test_r2a_8(void);
void test_r2a_9(void);
void test_r2a_10(void);
void test_r2a_11(void);
void test_r2a_15(void);
void test_r2a_19(void);
void test_r2a_20(void);
void test_r2a_25(void);
void test_r2a_30(void);
void test_r2a_40(void);
void test_r2a_49(void);
void test_r2a_50(void);
void test_r2a_90(void);
void test_r2a_100(void);
void test_r2a_400(void);
void test_r2a_500(void);
void test_r2a_900(void);
void test_r2a_1000(void);
void test_r2a_3999(void);
void test_r2a_fail_invalid_char(void);
void run_tests_roman_to_arabic(void);
#endif
<file_sep>/tests/arabic2roman.c
#include <stdlib.h>
#include "unity.h"
#include "roman.h"
#include "arabic2roman.h"
void test_a2r_1(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(1, &r);
TEST_ASSERT_EQUAL_STRING(r, "I");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_2(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(2, &r);
TEST_ASSERT_EQUAL_STRING(r, "II");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_3(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(3, &r);
TEST_ASSERT_EQUAL_STRING(r, "III");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_4(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(4, &r);
TEST_ASSERT_EQUAL_STRING(r, "IV");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_5(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(5, &r);
TEST_ASSERT_EQUAL_STRING(r, "V");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_6(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(6, &r);
TEST_ASSERT_EQUAL_STRING(r, "VI");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_7(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(7, &r);
TEST_ASSERT_EQUAL_STRING(r, "VII");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_8(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(8, &r);
TEST_ASSERT_EQUAL_STRING(r, "VIII");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_9(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(9, &r);
TEST_ASSERT_EQUAL_STRING(r, "IX");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_10(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(10, &r);
TEST_ASSERT_EQUAL_STRING(r, "X");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_11(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(11, &r);
TEST_ASSERT_EQUAL_STRING(r, "XI");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_15(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(15, &r);
TEST_ASSERT_EQUAL_STRING(r, "XV");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_19(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(19, &r);
TEST_ASSERT_EQUAL_STRING(r, "XIX");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_20(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(20, &r);
TEST_ASSERT_EQUAL_STRING(r, "XX");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_25(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(25, &r);
TEST_ASSERT_EQUAL_STRING(r, "XXV");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_30(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(30, &r);
TEST_ASSERT_EQUAL_STRING(r, "XXX");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_40(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(40, &r);
TEST_ASSERT_EQUAL_STRING(r, "XL");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_49(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(49, &r);
TEST_ASSERT_EQUAL_STRING(r, "XLIX");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_50(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(50, &r);
TEST_ASSERT_EQUAL_STRING(r, "L");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_90(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(90, &r);
TEST_ASSERT_EQUAL_STRING(r, "XC");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_100(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(100, &r);
TEST_ASSERT_EQUAL_STRING(r, "C");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_400(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(400, &r);
TEST_ASSERT_EQUAL_STRING(r, "CD");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_500(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(500, &r);
TEST_ASSERT_EQUAL_STRING(r, "D");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_900(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(900, &r);
TEST_ASSERT_EQUAL_STRING(r, "CM");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_1000(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(1000, &r);
TEST_ASSERT_EQUAL_STRING(r, "M");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_3999(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(3999, &r);
TEST_ASSERT_EQUAL_STRING(r, "MMMCMXCIX");
TEST_ASSERT_EQUAL_INT(ret, 0);
if (0 == ret) free(r);
}
void test_a2r_fail_large(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(4000, &r);
TEST_ASSERT_EQUAL_INT(ret, -1);
if (0 == ret) free(r);
}
void test_a2r_fail_zero(void)
{
roman_t r;
int ret;
ret = arabic_to_roman(0, &r);
TEST_ASSERT_EQUAL_INT(ret, -1);
if (0 == ret) free(r);
}
/* Tests for arabic_to_roman to suite */
void run_tests_arabic_to_roman(void)
{
RUN_TEST(test_a2r_1);
RUN_TEST(test_a2r_2);
RUN_TEST(test_a2r_3);
RUN_TEST(test_a2r_4);
RUN_TEST(test_a2r_5);
RUN_TEST(test_a2r_6);
RUN_TEST(test_a2r_7);
RUN_TEST(test_a2r_8);
RUN_TEST(test_a2r_9);
RUN_TEST(test_a2r_10);
RUN_TEST(test_a2r_11);
RUN_TEST(test_a2r_15);
RUN_TEST(test_a2r_19);
RUN_TEST(test_a2r_20);
RUN_TEST(test_a2r_25);
RUN_TEST(test_a2r_30);
RUN_TEST(test_a2r_40);
RUN_TEST(test_a2r_49);
RUN_TEST(test_a2r_50);
RUN_TEST(test_a2r_90);
RUN_TEST(test_a2r_100);
RUN_TEST(test_a2r_400);
RUN_TEST(test_a2r_500);
RUN_TEST(test_a2r_900);
RUN_TEST(test_a2r_1000);
RUN_TEST(test_a2r_3999);
RUN_TEST(test_a2r_fail_large);
RUN_TEST(test_a2r_fail_zero);
}
<file_sep>/tests/add.h
#ifdef _addition_test_h_
#define _addition_test_h_
void test_add_I_I(void);
void test_add_I_I(void);
void test_add_I_II(void);
void test_add_I_III(void);
void test_add_I_IV(void);
void test_add_I_V(void);
void test_add_IV_I(void);
void test_add_IV_V(void);
void test_add_X_XXX(void);
void test_add_failure_1(void);
void test_add_failure_2(void);
void run_tests_addition(void);
#endif
| cac0614b8946cb6138cdcb40fb35f1d7ffdb7eeb | [
"Markdown",
"C",
"Makefile"
] | 14 | C | dangerousHobo/polish-notation-roman-numeral-calculator | 6c9cc1733849d8cf7a5c74593b0b2f52abc0f161 | 4cb1ad7ba9a049e4a7243f67238d9ce418172920 |
refs/heads/master | <file_sep>Hooks.off();
Hooks.on ('renderExtraSheet', async (data) => {
// Let's do some stuff if this extra is a Condition and we haven't already created the boxes for it.
var extra = data.object;
var actor = data.actor;
//Split the condition name and number of boxes
var split = extra.data.name.split("_");
if (split.length >1){
//This means we haven't initialised this field yet.
var name = split[0];
var boxes = split[1];
var boxString="";
for (let i = 0; i<boxes; i++){
boxString += `<input type="checkbox" data-id="${name}"></input>`;
}
await actor.updateEmbeddedEntity("OwnedItem", {
_id:extra._id,
name:`${name}`,
"data.description.value":`${boxString}`
});
}
})
Hooks.on ('closeExtraSheet', async (data) => {
var extra = data.object;
var actor = data.actor;
if (extra.data.name.includes("Condition") || extra.data.name.includes("condition")){
var cba = document.querySelectorAll(`input[data-id="${extra.data.name}"]:checked`); // Checked boxes
var cbb = document.querySelectorAll(`input[data-id="${extra.data.name}"]`) // Unchecked boxes
var boxString = "";
for (let i = 0; i < cba.length; i++){
boxString+=`<input type="checkbox" data-id="${extra.data.name}" checked></input>`
}
for (let i = 0; i < (cbb.length - cba.length); i++){
boxString+=`<input type="checkbox" data-id="${extra.data.name}"></input>`
}
await actor.updateEmbeddedEntity("OwnedItem", {
_id:extra._id,
"data.description.value":`${boxString}`
});
}
})<file_sep># FateConditions
Requires NicK East's Fate Core system.
To use, simply create an Extra on a character with a name that contains the word Condition (or condition) in any format, and ends with an underscore and a number.
When you save the extra, it will immediately be populated with a set of checkboxes equal to the number after the underscore and the name will be changed to remove the underscore and the number.
Don't use more than one underscore in your condition name or this won't work.
| 0f52b0b9c6c4ea944f3765f11e8c28c405be409e | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | redeyed-archive/FateConditions | 931d049573841c1b59b469d25cb197f918f9a8df | 0d66d0d9769cc68b168d50bd9e9fad4fcdfe1275 |
refs/heads/master | <repo_name>dongjaepark/sudoku-solver<file_sep>/houghlinetransform.py
import numpy as np
from sympy import *
# Create image with 20x20 pixel
img = np.zeros((20,20), dtype=np.int)
# Draw 2 lines corresponding with the above image
# Every pixel lying on the line will have a value of 1
# Draw line d1, length = 15
for i in range(0, 15):
img[i+1][7] = 1
# Draw line d2, length = 8
for i in range(11, 19):
img[12][i] = 1
# Create a 2D array to hold the values of rho and delta
M = np.zeros((28,91), dtype = np.int)
# Scan image to find some lines
for x in range(20):
for y in range(20):
if(img[x][y] == 1):
for rho in range(28):
for theta in range(0,91):
if(rho == y*cos(theta*pi/180) + sin(theta*pi/180)):
M[rho][theta] += 1
print(M[7][0])
| 29ad5b07d83286d94d49c3557183a7a475d41fc6 | [
"Python"
] | 1 | Python | dongjaepark/sudoku-solver | 3970ca28c844bcd15fd64e24f8c1598ad5b952a9 | bc15ea666894c503811964d4869c72e9c8b4d6ef |
refs/heads/master | <file_sep>//
// GameScene.swift
// TAction
//
// Created by <NAME> on 14-8-10.
// Copyright (c) 2014年 <EMAIL>. All rights reserved.
//
import SpriteKit
//
enum Decision {
case Collision, Movement, Tackle
}
class GameScene: SKScene, SKPhysicsContactDelegate {
var indicator:SKSpriteNode!
var hero:SKSpriteNode!
var enemy:SKSpriteNode!
var heroShadow:SKSpriteNode!
var defenseArea:SKSpriteNode!
var endPoint:CGPoint!
let MASK_EMPTY:UInt32 = 0x0
let MASK_HERO:UInt32 = 0x1 << 0
let MASK_ENEMY:UInt32 = 0x1 << 1
let MASK_INDICATOR:UInt32 = 0x1 << 2
let MASK_DEFENSE:UInt32 = 0x1 << 3
let ACTION_KEY = "tackle"
var indicatorGreen:SKTexture!
var indicatorYellow:SKTexture!
var indicatorRed:SKTexture!
var indicatorOriginalWidth:CGFloat!
var redCounter = 0
var yellowCounter = 0
var isHeroControl = true
var isEnemyControl = false
var isTackling = false
var isAllowedThrough = true // TODO: will be decided by enemy
var inDefenseArea = false
override func didMoveToView(view: SKView) {
/* Setup your scene here */
self.physicsWorld.gravity = CGVectorMake(0, 0)
self.physicsWorld.contactDelegate = self
self.physicsBody = SKPhysicsBody(edgeLoopFromRect:self.frame)
// init indicator colors
indicatorGreen = SKTexture(imageNamed: "IndicatorGreen")
indicatorYellow = SKTexture(imageNamed: "IndicatorYellow")
indicatorRed = SKTexture(imageNamed: "IndicatorRed")
// add hero
hero = SKSpriteNode(imageNamed: "Hero")
hero.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
hero.zPosition = 10.0
hero.physicsBody = SKPhysicsBody(circleOfRadius: hero.size.width/2)
hero.physicsBody.allowsRotation = false
hero.physicsBody.linearDamping = 0.5
hero.physicsBody.categoryBitMask = MASK_HERO
hero.physicsBody.collisionBitMask = MASK_ENEMY | MASK_HERO
hero.physicsBody.contactTestBitMask = MASK_DEFENSE
addChild(hero)
// add enemy
enemy = SKSpriteNode(imageNamed: "Enemy")
enemy.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame) / 2)
enemy.zPosition = 1.0
enemy.physicsBody = SKPhysicsBody(circleOfRadius: enemy.size.width/2)
enemy.physicsBody.allowsRotation = false
enemy.physicsBody.linearDamping = 0.5
enemy.physicsBody.categoryBitMask = MASK_ENEMY
enemy.physicsBody.collisionBitMask = MASK_ENEMY | MASK_HERO
enemy.physicsBody.contactTestBitMask = MASK_INDICATOR
addChild(enemy)
}
private func createDefenseArea() {
// add defense area
defenseArea = SKSpriteNode(imageNamed: "Enemy")
defenseArea.position = enemy.position
defenseArea.zPosition = enemy.zPosition - 1
defenseArea.xScale = 2.0
defenseArea.yScale = 2.0
defenseArea.alpha = 0.1
defenseArea.physicsBody = SKPhysicsBody(circleOfRadius: defenseArea.size.width / 2)
defenseArea.physicsBody.categoryBitMask = MASK_DEFENSE
defenseArea.physicsBody.collisionBitMask = MASK_EMPTY
defenseArea.physicsBody.contactTestBitMask = MASK_INDICATOR
addChild(defenseArea)
}
private func createIndicator(beginPoint:CGPoint) {
// add indicator
indicator = SKSpriteNode(imageNamed: "IndicatorGreen")
indicatorOriginalWidth = indicator.size.width
indicator.anchorPoint = CGPoint(x:0, y:0.5)
indicator.position = hero.position
var (length, angle) = getScale(beginPoint, endPoint: indicator.position)
indicator.xScale = length / indicatorOriginalWidth
indicator.zRotation = angle
indicator.yScale = hero.size.height / indicator.size.height
indicator.alpha = 0.5
indicator.zPosition = 2.0
indicator.physicsBody = SKPhysicsBody(rectangleOfSize: indicator.size, center: CGPointMake(indicator.size.width / 2, 0))
indicator.physicsBody.categoryBitMask = MASK_INDICATOR
indicator.physicsBody.collisionBitMask = MASK_EMPTY
indicator.physicsBody.contactTestBitMask = MASK_DEFENSE | MASK_ENEMY
addChild(indicator)
// add heroShadow
heroShadow = SKSpriteNode(imageNamed: "Hero")
heroShadow.position = beginPoint
heroShadow.alpha = 0.5
heroShadow.zPosition = 3.0
heroShadow.physicsBody = SKPhysicsBody(circleOfRadius: hero.size.width / 2)
heroShadow.physicsBody.categoryBitMask = MASK_INDICATOR
heroShadow.physicsBody.collisionBitMask = MASK_EMPTY
heroShadow.physicsBody.contactTestBitMask = MASK_DEFENSE | MASK_ENEMY
addChild(heroShadow)
}
private func removeIndicator() {
indicator.removeFromParent()
heroShadow.removeFromParent()
}
private func resetData() {
redCounter = 0
yellowCounter = 0
isTackling = false
// println("0000000 clean counter 000000000")
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
var touch = touches.anyObject() as UITouch
var beginPoint = touch.locationInNode(self)
if isHeroControl {
createIndicator(beginPoint)
createDefenseArea()
}
if isEnemyControl {
// decide tackle
var tackleDecision = makeTackleDecision(beginPoint)
// if tackle, tackle
if tackleDecision {
// println("tackel")
attack(hero.position, startPoint: enemy.position, attacker: enemy)
} else { // else go on move
// println("go on move")
moveHero(endPoint)
}
// remove defense area
defenseArea.removeFromParent()
// clean counter
resetData()
}
}
private func makeTackleDecision(touchPoint:CGPoint) -> Bool {
var (distance, angle) = getScale(touchPoint, endPoint: enemy.position)
return abs(distance) > enemy.size.width / 2 && abs(distance) < defenseArea.size.width / 2
}
private func switchControl() {
if isHeroControl {
println("::: Enemy Control")
isHeroControl = false
isEnemyControl = true
} else {
println("::: Hero Control")
isHeroControl = true
isEnemyControl = false
}
}
override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) {
if isEnemyControl {
return
}
var touch = touches.anyObject() as UITouch
var movePoint:CGPoint = touch.locationInNode(self)
// update indicator
var (length, angle) = getScale(movePoint, endPoint: indicator.position)
indicator.xScale = length / indicatorOriginalWidth
indicator.zRotation = angle
// update heroShadow
heroShadow.position = movePoint
}
private func getScale(startPoint:CGPoint, endPoint:CGPoint) -> (CGFloat, CGFloat) {
let dx = startPoint.x - endPoint.x
let dy = startPoint.y - endPoint.y
return (sqrt(dx * dx + dy * dy), atan2(dy, dx))
}
override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
if isEnemyControl {
// switch control
switchControl()
return
}
var touch = touches.anyObject() as UITouch
endPoint = touch.locationInNode(self)
assert(hero != nil, "########## hero is nil ##########")
// decision
switch makeDecision() {
case .Movement:
println("[Decision]: Movement")
let moveHero = SKAction.moveTo(endPoint, duration: 1.0)
hero.runAction(moveHero)
// remove defenseArea
assert(defenseArea != nil, "########## defense area shouldn't be nil ##########")
defenseArea?.removeFromParent()
// remove indicator
removeIndicator()
case .Collision:
println("[Decision]: Collision")
attack(endPoint, startPoint: hero.position, attacker: hero)
// remove defenseArea
assert(defenseArea != nil, "########## defense area shouldn't be nil ##########")
defenseArea.removeFromParent()
// remove indicator
removeIndicator()
// clean counter
resetData()
case .Tackle:
println("[Decision]: Tackle")
isTackling = true
inDefenseArea = isInDefenseArea()
if isInDefenseArea() {
// println("In Defense Area: Enemy decide")
switchControl()
} else {
moveHero(endPoint)
}
// remove indicator
removeIndicator()
}
}
private func attack(endPoint:CGPoint, startPoint:CGPoint, attacker:SKSpriteNode) {
var (length, angle) = getScale(endPoint, endPoint: startPoint)
var times = 3 * length
attacker.physicsBody.applyForce(CGVectorMake(times * cos(angle), times * sin(angle)))
}
private func moveHero(endPoint:CGPoint) {
let moveHero = SKAction.moveTo(endPoint, duration: 1.0)
hero.runAction(moveHero, withKey:ACTION_KEY)
}
private func isInDefenseArea() -> Bool {
var (distance, angle) = getScale(hero.position, endPoint: enemy.position)
//println("size: \(defenseArea.size.width / 2)")
let nearstDistance = abs(distance) - hero.size.width / 2
// println("nearstDistance: \(abs(nearstDistance))")
// println("enemy size / 2: \(enemy.size.width / 2)")
// assert(nearstDistance >= enemy.size.width / 2, "nearst distance must larger than the half of enemy")
return nearstDistance < defenseArea.size.width / 2
}
private func makeDecision() -> Decision {
//println("++++++++++ makeDecision +++++++")
// println("redCounter: \(redCounter)")
// println("yellowCounter: \(yellowCounter)")
// println("+++++++++++++++++++++++++++")
assert(redCounter >= 0, "########## red counter failed ##########")
assert(yellowCounter >= 0, "########## yellow counter failed ##########")
if redCounter > 0 {
return Decision.Collision
}
if redCounter == 0 && yellowCounter > 0 {
return Decision.Tackle
}
return Decision.Movement
}
override func update(currentTime: CFTimeInterval) {
/*
if hero.physicsBody.velocity.dx == 0 && hero.physicsBody.velocity.dy == 0 {
println("hero stops")
}
*/
/* Called before each frame is rendered */
//println("resting: \(hero.physicsBody.resting)")
/*
if hero.physicsBody.resting && !checkedResting {
println("hero is tired.")
checkedResting = true
}
if !hero.physicsBody.resting && checkedResting {
println("hero is moving")
checkedResting = false
}
*/
}
func didBeginContact(contact: SKPhysicsContact) {
println("------ Contact Begin ------")
debugContact(contact)
if contact.bodyA.categoryBitMask == MASK_HERO && contact.bodyB.categoryBitMask == MASK_DEFENSE {
if isTackling {
// stop move action
hero.removeActionForKey(ACTION_KEY)
// switch control to enemy
switchControl()
return
}
}
if contact.bodyA.categoryBitMask == MASK_ENEMY || contact.bodyB.categoryBitMask == MASK_ENEMY {
redCounter++
}
if contact.bodyA.categoryBitMask == MASK_DEFENSE || contact.bodyB.categoryBitMask == MASK_DEFENSE {
yellowCounter++
}
changeColor()
}
func didEndContact(contact: SKPhysicsContact!) {
println("------ Contact End ------")
debugContact(contact)
if contact.bodyA.categoryBitMask == MASK_ENEMY || contact.bodyB.categoryBitMask == MASK_ENEMY {
redCounter--
}
if contact.bodyA.categoryBitMask == MASK_DEFENSE || contact.bodyB.categoryBitMask == MASK_DEFENSE {
yellowCounter--
}
changeColor()
}
private func changeColor() {
switch makeDecision() {
case .Collision:
indicator.texture = indicatorRed
case .Tackle:
indicator.texture = indicatorYellow
case .Movement:
indicator.texture = indicatorGreen
}
}
private func debugContact(contact: SKPhysicsContact!) {
if contact.bodyA.categoryBitMask == MASK_HERO {
println("hero is body a")
} else if contact.bodyA.categoryBitMask == MASK_ENEMY {
println("enemy is body a")
} else if contact.bodyA.categoryBitMask == MASK_INDICATOR {
println("indicator is body a")
} else if contact.bodyA.categoryBitMask == MASK_DEFENSE {
println("defense is body a")
} else {
println("unknown body a")
}
if contact.bodyB.categoryBitMask == MASK_HERO {
println("hero is body b")
} else if contact.bodyB.categoryBitMask == MASK_ENEMY {
println("enemy is body b")
} else if contact.bodyB.categoryBitMask == MASK_INDICATOR {
println("indicator is body b")
} else if contact.bodyB.categoryBitMask == MASK_DEFENSE {
println("defense is body b")
} else {
println("unknown body b")
}
}
}
| fccaeb3cdf6da81bb066cdb8cd0550329a059348 | [
"Swift"
] | 1 | Swift | chensifeng/TAction | 28b44ccc551f1b3c0ff4891c064999f91e2eaf7f | 05b84f59245ddad4be4809636b1d56ae2ff8483c |
refs/heads/master | <file_sep>### SFPC: Recreating the past - <NAME>
Inspired by <NAME>'s '[Experiments in Motion Graphics](https://archive.org/details/experimentsinmotiongraphics
)' and [Matrix III](https://www.youtube.com/watch?v=ZrKgyY5aDvA). More details on Whitney's work with the IBM 2250 can be found [here](http://blog.animationstudies.org/?p=426
)
Built with openFrameworks.
Requires the [ofxAnimateable](https://github.com/armadillu/ofxAnimatable) addon.



<file_sep>#include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup(){
ofSetVerticalSync(true);
ofSetFrameRate(60);
ofBackground(0);
ofEnableSmoothing();
bckgImg.loadImage("back.png");
triImg.loadImage("tri.png");
eyesImg.loadImage("1f440.png");
ofApp::initControls();
center.set(ofGetWidth()*0.5f, ofGetHeight()*0.5f, 0);
anim[0].reset( 0.0f );
anim[0].setRepeatType(LOOP);
anim[0].setCurve(LINEAR);
anim[0].animateTo( TWO_PI );
anim[1].reset( 0.0f );
anim[1].setRepeatType(LOOP);
anim[1].setCurve(LINEAR);
anim[1].animateTo( TWO_PI );
}
//--------------------------------------------------------------
void ofApp::update(){
this->imgScales[1] = pImgScale[1]* 0.1;
this->imgScales[0] = pImgScale[0]* 0.1;
anim[0].update( 1.0f/pAnimSpeed[0] );
anim[1].update( 1.0f/pAnimSpeed[1] );
}
//--------------------------------------------------------------
void ofApp::draw(){
bckgImg.draw(0, 0);
ofPushMatrix();
ofTranslate(center);
ofSetColor(255);
ofSetLineWidth(1);
if(pShow[0]) {
drawWave();
}
if(pShow[1]) {
drawLissaous();
}
ofPopMatrix();
gui.draw();
}
void ofApp::initControls(){
gui.setup("Parameters");
paramsGroup1.setName("Group 1");
paramsGroup1.add(pShow[0].set( "Show/Hide", true ));
paramsGroup1.add(pAmp[0].set( "Amplitude", 150, 0, 300 ));
paramsGroup1.add(pFreq[0].set( "Frequency", 1, 1, 10 ));
// paramsGroup1.add(pPhase[0].set("Phase", 0,0,TWO_PI));
paramsGroup1.add(pDensity[0].set("Density", 50, 0, 200));
paramsGroup1.add(pAnimSpeed[0].set("Animation Speed", 960, 30, 960));
paramsGroup1.add(pImgScale[0].set("Image scale", 1, 1, 50));
// paramsGroup1.add(pJitterScale[0].set("Jitter scale", true));
paramsGroup2.setName("Group 2");
paramsGroup2.add(pShow[1].set( "Show/Hide", true ));
paramsGroup2.add(pAmp[1].set( "Amplitude", 150, 0, 200 ));
// paramsGroup2.add(pFreq[1].set( "Frequency ", 1, 1, 10 ));
// paramsGroup2.add(pPhase[1].set("Phase", 0,0,TWO_PI));
paramsGroup2.add(pDensity[1].set("Density", 50, 0, 200));
paramsGroup2.add(pAnimSpeed[1].set("Animation Speed", 960, 30, 960));
paramsGroup2.add(plissajouRatio[0].set("Lissajous Radio X", 1, 1, 8));
paramsGroup2.add(plissajouRatio[1].set("Lissajous Radio Y", 3, 1, 8));
paramsGroup2.add(pImgScale[1].set("Image scale", 1, 1, 50));
// paramsGroup2.add(pJitterScale[1].set("Jitter scale", true));
gui.add(paramsGroup1);
gui.add(paramsGroup2);
}
void ofApp::drawWave() {
double y,x,y2;
float t, phase,iconHeight,iconWidth;
phase = anim[0].val();
t = TWO_PI * this->pFreq[0] / this->pDensity[0] ;
for (int i = 0; i < this->pDensity[0] ;i++) {
y = this->pAmp[0] * sin( t * i + phase );
y2 = this->pAmp[0] * sin( t * i + phase + PI);
x = i * ofGetWidth() / this->pDensity[0];
ofCircle( x - ofGetWidth()/2 ,y,1);
ofCircle( x - ofGetWidth()/2 ,y2,1);
iconWidth = triImg.width * this->imgScales[0];
iconHeight = triImg.height * this->imgScales[0];
triImg.draw(x-iconWidth/2-ofGetWidth()/2, y-iconHeight/2, iconWidth, iconHeight);
triImg.draw(x-iconWidth/2-ofGetWidth()/2, y2-iconHeight/2, iconWidth, iconHeight);
}
}
void ofApp::drawLissaous() {
double y,x;
float phase,v,iconHeight,iconWidth;
int scale;
scale = pAmp[1] * 2;
phase = anim[1].val();
v = TWO_PI / this->pDensity[1];
for (int i = 0; i < this->pDensity[1] ; i++) {
x = scale * cos( this->plissajouRatio[0] * v * i + phase);
y = scale * sin( this->plissajouRatio[1] * v * i + phase);
// triImg.draw(x,y,triImg.width * this->imgScales[0], triImg.height * this->imgScales[0]);
iconWidth = eyesImg.width * this->imgScales[1];
iconHeight = eyesImg.height * this->imgScales[1];
eyesImg.draw(x-iconWidth/2, y-iconHeight/2, iconWidth, iconHeight);
ofCircle(x,y,1);
}
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
pparam1 = ofToString(w) + "x" + ofToString(h);
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}<file_sep>#pragma once
#include "ofMain.h"
#include "ofxGui.h"
#include "ofxSvg.h"
#include "ofxAnimatableFloat.h"
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void initControls();
ofPoint calcPoint(float amp, float angle, float phase);
void drawWave();
void drawLissaous();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y);
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
ofParameterGroup paramsGroup1;
ofParameterGroup paramsGroup2;
// Parameters for the two Waves
ofParameter<bool> pShow[2];
ofParameter<float> pAmp[2];
ofParameter<float> pFreq[2];
ofParameter<float> pPhase[2];
ofParameter<int> pDensity[2];
ofParameter<int> pImgScale[2];
//ofParameter<bool> pJitterScale[2];
ofParameter<int> pAnimSpeed[2];
// General Purpose Strings
ofParameter<int> plissajouRatio[2];
ofParameter<string> pparam1;
ofParameter<string> pparam2;
ofParameter<string> pparam3;
// ofxSVG svg;
ofImage bckgImg, triImg, eyesImg;
float imgScales[2];
ofxPanel gui;
ofxAnimatableFloat anim[2];
ofPoint center;
};
| 910f714d5dbf2e87eb4141eca719efe7fe77307b | [
"Markdown",
"C++"
] | 3 | Markdown | streiten/sfpc-rtp-whitney | 23e60638f3990b0df3ab214bef3d1a420bd169c0 | 1d0a2c4729d4c6516f432a84fc6871fc78dc86a8 |
refs/heads/main | <repo_name>dudrms9373/GreenPRJ<file_sep>/src/view/UserMenu.java
package view;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import model.FitnessDao;
public class UserMenu extends JFrame implements ActionListener{
JButton LogoutButton, PTButton, InfoButton, ExtensionButton;
private String id="";
public UserMenu(String id) {
FitnessDao fv = new FitnessDao();
this.setTitle("4. 회원로그인");
this.id = id;
JLabel TitleLabel = new JLabel("<html><body style='text-align:center;'>어서오세요."+fv.getName(id)+"님!<br />오늘도 득근 하세요!!</body></html>",JLabel.CENTER);
TitleLabel.setFont(new Font("굴림", Font.BOLD, 30));
TitleLabel.setBounds(54, 10, 400, 113);
getContentPane().add(TitleLabel);
LogoutButton = new JButton("로그아웃");
LogoutButton.setBounds(463, 24, 97, 36);
getContentPane().add(LogoutButton);
PTButton = new JButton("PT예약");
PTButton.setBounds(54, 149, 105, 230);
getContentPane().add(PTButton);
InfoButton = new JButton("내 정보");
InfoButton.setBounds(240, 149, 97, 230);
getContentPane().add(InfoButton);
ExtensionButton = new JButton("연장하기");
ExtensionButton.setBounds(418, 149, 97, 230);
getContentPane().add(ExtensionButton);
getContentPane().setLayout(null);
this.LogoutButton.addActionListener(this);
this.InfoButton.addActionListener(this);
this.PTButton.addActionListener(this);
this.ExtensionButton.addActionListener(this);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600,500);
this.setResizable(false);
this.setLocationRelativeTo(null);
}
@Override
public void actionPerformed(ActionEvent e) {
switch(e.getActionCommand()) {
case "로그아웃" : new LoginPage(); this.dispose(); break;
case "내 정보" : new MyInfo(id); this.dispose(); break;
case "연장하기" :new PTPrice(id); this.dispose(); break;
case "PT예약" : new PTreserved(id); this.dispose();break;
}
}
}
<file_sep>/src/model/SpecialVo.java
package model;
public class SpecialVo {
//필드
private String wDate; // 특이사항이 추가된 날짜
private String speNote; //특이 사항 내용
private int speMemId; // 특이 사항이 있는 회원의 번호
// 생성자
/// 추가용
public SpecialVo(String speNote, int speMemId) {
this.speNote = speNote;
this.speMemId = speMemId;
}
/// 조회용
public SpecialVo(String wDate, String speNote, int speMemId) {
super();
this.wDate = wDate;
this.speNote = speNote;
this.speMemId = speMemId;
}
// Getter/ Setter
public String getwDate() {
return wDate;
}
public void setwDate(String wDate) {
this.wDate = wDate;
}
public String getSpeNote() {
return speNote;
}
public void setSpeNote(String speNote) {
this.speNote = speNote;
}
public int getSpeMemId() {
return speMemId;
}
public void setSpeMemId(int speMemId) {
this.speMemId = speMemId;
}
// toString()
@Override
public String toString() {
return "SpecialVo [wDate=" + wDate + ", speNote=" + speNote + ", speMemId=" + speMemId + "]";
}
}
<file_sep>/src/view/JoinPage.java
package view;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import model.FitnessDao;
import model.MemberVo;
public class JoinPage extends JFrame implements ActionListener {
JPanel p;
JTextField TextFieldID, TextFieldName, TextFieldBirth, TextFieldPWD, TextFieldTel, TextFieldGender, TextFieldAddres;
JPasswordField PasswordFieldPWD;
JTextArea taIntro;
JButton ButtonJoin, ButtonCancel;
private JTextField textFieldHeight, textFieldWeight;
private boolean check = true;
public JoinPage() {
this.setTitle("회원가입");
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.setSize(380, 610);
this.setResizable(false);
this.setLocationRelativeTo(null);
getContentPane().setLayout(null);
// 라벨
JLabel LabelName = new JLabel("이름");
LabelName.setBounds(25, 30, 77, 26);
getContentPane().add(LabelName);
JLabel LabelBirth = new JLabel("생년월일");
LabelBirth.setBounds(25, 80, 77, 26);
getContentPane().add(LabelBirth);
JLabel LabelID = new JLabel("ID");
LabelID.setBounds(25, 130, 77, 26);
getContentPane().add(LabelID);
JLabel LabelPWD = new JLabel("PWD");
LabelPWD.setBounds(25, 180, 77, 26);
getContentPane().add(LabelPWD);
JLabel LabelTel = new JLabel("전화번호");
LabelTel.setBounds(25, 230, 77, 26);
getContentPane().add(LabelTel);
JLabel LabelGender = new JLabel("성별( M , W )");
LabelGender.setBounds(25, 280, 77, 26);
getContentPane().add(LabelGender);
JLabel LableAddres = new JLabel("주소(~동 까지)");
LableAddres.setBounds(25, 330, 99, 26);
getContentPane().add(LableAddres);
// 텍스트 필드
TextFieldName = new JTextField();
TextFieldName.setBounds(123, 30, 204, 25);
TextFieldName.setFont(new Font("굴림", Font.PLAIN, 13));
getContentPane().add(TextFieldName);
TextFieldName.setColumns(10);
TextFieldBirth = new JTextField();
TextFieldBirth.setBounds(123, 80, 204, 25);
TextFieldBirth.setFont(new Font("굴림", Font.PLAIN, 13));
TextFieldBirth.setColumns(10);
getContentPane().add(TextFieldBirth);
TextFieldID = new JTextField();
TextFieldID.setBounds(123, 130, 204, 25);
TextFieldID.setFont(new Font("굴림", Font.PLAIN, 13));
TextFieldID.setColumns(10);
getContentPane().add(TextFieldID);
TextFieldPWD = new JTextField();
TextFieldPWD.setBounds(123, 180, 204, 25);
TextFieldPWD.setFont(new Font("굴림", Font.PLAIN, 13));
TextFieldPWD.setColumns(10);
getContentPane().add(TextFieldPWD);
TextFieldTel = new JTextField();
TextFieldTel.setBounds(123, 230, 204, 25);
TextFieldTel.setFont(new Font("굴림", Font.PLAIN, 13));
TextFieldTel.setColumns(10);
getContentPane().add(TextFieldTel);
TextFieldGender = new JTextField();
TextFieldGender.setBounds(123, 280, 204, 25);
TextFieldGender.setFont(new Font("굴림", Font.PLAIN, 13));
TextFieldGender.setColumns(10);
getContentPane().add(TextFieldGender);
TextFieldAddres = new JTextField();
TextFieldAddres.setBounds(123, 330, 204, 25);
TextFieldAddres.setFont(new Font("굴림", Font.PLAIN, 13));
TextFieldAddres.setColumns(10);
getContentPane().add(TextFieldAddres);
// 버튼
ButtonJoin = new JButton("가입");
ButtonJoin.setBounds(47, 494, 111, 45);
getContentPane().add(ButtonJoin);
ButtonCancel = new JButton("취소");
ButtonCancel.setBounds(198, 494, 111, 45);
getContentPane().add(ButtonCancel);
JLabel heightLabel = new JLabel("키");
heightLabel.setBounds(25, 380, 99, 26);
getContentPane().add(heightLabel);
JLabel weightLabel = new JLabel("몸무게");
weightLabel.setBounds(25, 430, 99, 26);
getContentPane().add(weightLabel);
textFieldHeight = new JTextField();
textFieldHeight.setFont(new Font("굴림", Font.PLAIN, 13));
textFieldHeight.setColumns(10);
textFieldHeight.setBounds(123, 381, 204, 25);
getContentPane().add(textFieldHeight);
textFieldWeight = new JTextField();
textFieldWeight.setFont(new Font("굴림", Font.PLAIN, 13));
textFieldWeight.setColumns(10);
textFieldWeight.setBounds(123, 431, 204, 25);
getContentPane().add(textFieldWeight);
this.setVisible(true);
// 이벤트
this.ButtonCancel.addActionListener(this);
this.ButtonJoin.addActionListener(this);
}
// public static void main(String[] args) {
// new JoinPage();
// }
@Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "가입":
insertUser();
break;
case "취소":
this.dispose();
new LoginPage();
break;
}
}
private void insertUser() {
FitnessDao fd = new FitnessDao();
int height = Integer.parseInt(textFieldHeight.getText());
int weight = Integer.parseInt(textFieldWeight.getText());
MemberVo fv = new MemberVo(height, weight, TextFieldName.getText(), TextFieldBirth.getText(), TextFieldID.getText(),
TextFieldPWD.getText(), TextFieldTel.getText(), TextFieldGender.getText(), TextFieldAddres.getText()
);
int num = fd.JoinFitness(fv);
System.out.println(num);
// 메세지 상자 출력
if (num == 1) {
JOptionPane.showMessageDialog(null, "회원가입 완료", "완료", JOptionPane.INFORMATION_MESSAGE);
this.dispose();
new LoginPage();
} else {
JOptionPane.showMessageDialog(null, "아이디가 중복되었거나 잘못입력하셨습니다. (다시 한번 확인해주세요)", "중복", JOptionPane.CANCEL_OPTION);
}
}
}
<file_sep>/src/model/ReservationVo.java
package model;
public class ReservationVo {
// Fields
private String resDate; //예약된 시간
private int resMemId; //예약정보 테이블 상의 회원번호
private int resTId; //예약정보 테이블 상의 트레이너번호
// 생성자
public ReservationVo(String resDate, int resMemId, int resTId) {
this.resDate = resDate;
this.resMemId = resMemId;
this.resTId = resTId;
}
// Getter / Setter
public String getResDate() {
return resDate;
}
public void setResDate(String resDate) {
this.resDate = resDate;
}
public int getResMemId() {
return resMemId;
}
public void setResMemId(int resMemId) {
this.resMemId = resMemId;
}
public int getResTId() {
return resTId;
}
public void setResTId(int resTId) {
this.resTId = resTId;
}
//toString()
@Override public String toString(){return "ReservationVo [resDate=" + resDate + ", resMemId=" + resMemId + ", resTId=" + resTId + "]";}
}
<file_sep>/src/view/MainClient.java
package view;
public class MainClient {
public static void main(String[] args) {
new LoginPage();
}
}
<file_sep>/src/model/FitnessDao.java
package model;
import java.awt.Color;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class FitnessDao {
static String n1 = "";
static String i1 = "";
ResultSet rs = null;
// CRUD
// ------------------------------------------------------------------------------------
// 회원 정보 수정
public void updateMem(String id, String name, String pwd, String tel, String addr, String speNote) {
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "UPDATE MEMBER AS M, SPECIAL AS S";
sql += " SET M.MEM_NAME= ?";
sql += " , M.TEL = ?";
sql += " , M.ADDR = ?";
sql += " , S.SPE_NOTE = ?";
sql += " WHERE M.ID= ?" + " AND M.ID = S.ID";
try {
conn = DBConn.getInstance();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, pwd);
pstmt.setString(3, tel);
pstmt.setString(4, addr);
pstmt.setString(5, speNote);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 회원 정보 삭제 ( 점검 완료)
public String removeMem(String id) {
String result="삭제에 실패했습니다";
Connection conn = null;
PreparedStatement pstmt = null;
conn = DBConn.getInstance();
String sql = "DELETE FROM MEMBER ";
sql += " WHERE ID = ?";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
pstmt.executeUpdate();
result=id+"계정이 삭제되었습니다";
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
// 회원조회
public Vector MemberList() {
Vector outV = new Vector();
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "SELECT M.MEM_ID, M.MEM_NAME, M.TEL, M.ADDR, M.GENDER, R.RES_DATE ";
sql += " FROM MEMBER M, RESERVATION R ";
sql += " WHERE M.MEM_ID = R.MEM_ID ";
try {
conn = DBConn.getInstance();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
Vector v = new Vector();
v.add(rs.getString("MEM_ID"));
v.add(rs.getString("MEM_NAME"));
v.add(rs.getString("GENDER"));
v.add(rs.getString("TEL"));
v.add(rs.getString("ADDR"));
v.add(rs.getString("RES_DATE"));
outV.add(v);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
}
}
return outV;
}
//특이사항 가져오기
public String specialMem(String memId) {
Connection conn = null;
PreparedStatement pstmt = null;
String note = "";
String sql = "SELECT SPE_NOTE ";
sql += " FROM SPECIAL S ";
sql += " WHERE S.MEM_ID = ? ";
try {
conn = DBConn.getInstance();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, memId);
rs = pstmt.executeQuery();
if (rs.next()) {
note = rs.getString("SPE_NOTE");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
}
}
return note;
}
// 회원 추가
public int JoinFitness(MemberVo MemberVo) {
Connection conn;
PreparedStatement pstmt = null;
String sql = "";
conn = DBConn.getInstance();
sql = "INSERT INTO MEMBER(MEM_ID, MEM_NAME, MEM_BIRTH,";
sql += " ID, PWD, TEL, GENDER, ADDR, HEIGHT, WEIGHT)";
sql += " VALUES (SEQ_MEM.NEXTVAL, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, MemberVo.getName());
pstmt.setString(2, MemberVo.getBirth());
pstmt.setString(3, MemberVo.getId());
pstmt.setString(4, MemberVo.getPwd());
pstmt.setString(5, MemberVo.getTel());
pstmt.setString(6, MemberVo.getGender());
pstmt.setString(7, MemberVo.getAddress());
pstmt.setInt(8, MemberVo.getHeight());
pstmt.setInt(9, MemberVo.getWeight());
pstmt.executeUpdate();
conn.commit();
} catch (SQLIntegrityConstraintViolationException e) {
System.out.println("아이디가 중복되었거나 빈칸이 있습니다");
return -1;
}
catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return 1;
}
/* 10/15 Prolong 테이블 삭제함 수정 필요 ( 김영근 )
// 남은기간 연장
public void prolong(ProlongVo ProlongVo) {
Connection conn;
PreparedStatement pstmt = null;
String sql = "";
conn = DBConn.getInstance();
sql = "INSERT INTO PROLONG (PROL_ID,STATUS,START_DATE,END_DATE,PROL_DATE,MEM_ID) ";
sql += " VALUES (SEQ_PRO.NEXTVAL,?,?,?,?,?)";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, ProlongVo.getStatus());
pstmt.setString(2, ProlongVo.getStart_date());
pstmt.setString(3, ProlongVo.getEnd_date());
pstmt.setString(4, ProlongVo.getProl_date());
pstmt.setString(5, ProlongVo.getMem_id());
pstmt.executeUpdate();
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
*/
// 로그인
public int loginCheck(String id, String pwd) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
MemberVo vo = new MemberVo();
String sql = "";
conn = DBConn.getInstance();
sql = "SELECT * FROM MEMBER M";
sql += " WHERE M.ID = ? ";
sql += " AND M.PWD = ? ";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
pstmt.setString(2, pwd);
rs = pstmt.executeQuery();
if (rs.next()) {
String name = rs.getString(2);
System.out.println(name + "님 로그인 성공");
return 1;
} else {
JOptionPane.showMessageDialog(null, "로그인 실패");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
}
}
return -1;
}
// 로그인 (이름 가져오기)
public String loginCheck1(String id) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
MemberVo vo = new MemberVo();
String sql = "";
String n = "";
conn = DBConn.getInstance();
sql = "SELECT MEM_NAME FROM MEMBER M";
sql += " WHERE M.ID = ? ";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
String name = rs.getString(1);
return name;
} else {
JOptionPane.showMessageDialog(null, "로그인 실패");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
}
}
return n;
}
// 회원 아이디 찾기(리턴값 = FitnessVo 클래스)
public MemberVo IdSearch(String name, String birth, String tel) {
MemberVo vo = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
MemberVo fv = new MemberVo();
String sql = " ";
conn = DBConn.getInstance();
sql = "SELECT * FROM MEMBER ";
sql += " WHERE MEM_NAME = ? ";
sql += " AND MEM_BIRTH = ? ";
sql += " AND tel = ? ";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, birth);
pstmt.setString(3, tel);
rs = pstmt.executeQuery();
if (rs.next()) {
String name1 = rs.getString(2);
String birth1 = rs.getString(3);
String id = rs.getString(4);
String pwd = rs.getString(5);
String tel1 = rs.getString(6);
String gender = rs.getString(7);
String address = rs.getString(8);
int height = rs.getInt(9);
int weight = rs.getInt(10);
vo = new MemberVo(height, weight,name1, birth1, id, pwd, tel1, gender, address );
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
}
}
return vo;
}
// 비밀번호 찾기
public MemberVo PwdSearch(String name, String birth, String id) {
MemberVo vo = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
MemberVo fv = new MemberVo();
String sql = " ";
conn = DBConn.getInstance();
sql = "SELECT * FROM MEMBER ";
sql += " WHERE MEM_NAME = ? ";
sql += " AND MEM_BIRTH = ? ";
sql += " AND ID = ? ";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, birth);
pstmt.setString(3, id);
rs = pstmt.executeQuery();
if (rs.next()) {
String name1 = rs.getString(2);
String birth1 = rs.getString(3);
String id1 = rs.getString(4);
String pwd = rs.getString(5);
String tel1 = rs.getString(6);
String gender = rs.getString(7);
String address = rs.getString(8);
int height = rs.getInt(9);
int weight = rs.getInt(10);
vo = new MemberVo(height, weight,name1, birth1, id1, pwd, tel1, gender, address );
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
}
}
return vo;
}
//비밀번호 변경
public void newPwd(String pwd,String id) {
Connection conn = null;
PreparedStatement pstmt = null;
String sql ="";
conn = DBConn.getInstance();
sql = " UPDATE MEMBER SET pwd = ?";
sql += " WHERE id = ? ";
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, pwd);
pstmt.setString(2, id);
pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if( pstmt != null ) pstmt.close();
} catch (SQLException e) {
}
}
}
// 예약하기
public Boolean reserve(ReservationVo resVo){
Boolean check =false;
String sql = "INSERT INTO RESERVATION(RES_ID ,RES_DATE, MEM_ID, T_ID)";
sql += " VALUES (SEQ_RES_ID.NEXTVAL, ? , ? , ? )";
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn=DBConn.getInstance();
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, resVo.getResDate());
pstmt.setInt(2, resVo.getResMemId());
pstmt.setInt(3, resVo.getResTId());
pstmt.executeUpdate();
check = true;
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if( pstmt != null ) pstmt.close();
} catch (SQLException e) {
}
return check;
}
}
// 특이사항 추가
public String writeSpe(SpecialVo speVo) {
Connection conn = null;
PreparedStatement pstmt = null;
String result = "특이사항 추가 실패";
String sql = "INSERT INTO SPECIAL(SPE_ID, SPE_NOTE, MEM_ID)";
sql += " VALUES (SEQ_SPE.NEXTVAL, ? , ? )";
try {
conn = DBConn.getInstance();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, speVo.getSpeNote());
pstmt.setInt(2, speVo.getSpeMemId());
pstmt.executeUpdate();
result = "특이사항이 추가되었습니다";
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return result;
}
// PT 내역 추가( sql 에러가 뜨는 걸 보니 괜찮음. 테스트는 reservation에 있는 데이터의 추가가 아니면 안됨)
public String writeExe(ExecutionVo exeVo) {
Connection conn = null;
PreparedStatement pstmt = null;
String result = "PT 내역 추가 실패";
String sql = "INSERT INTO EXECUTION(EXE_ID, EXE_NOTE,";
sql += " HEIGHT, WEIGHT, REMAIN_NUM, RES_ID )";
sql += " VALUES ( SEQ_EXE.NEXTVAL, ? , ? , ? , ? , ? )";
conn = DBConn.getInstance();
try {
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, exeVo.getExeNote());
pstmt.setInt(2, exeVo.getHeight());
pstmt.setInt(3, exeVo.getWeight());
pstmt.setInt(4, exeVo.getRemainNum()); // 새 테이블에 맞춰 수정됨
pstmt.setInt(5, exeVo.getResId());
pstmt.executeUpdate();
result = "PT 내역 추가되었습니다.";
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
}
return result;
}
}
// Id 기준 실행 내역 전체 조회(Vector)
public Vector getExeInfo(String Id, String exeCheck) {
Vector outV = new Vector();
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT E.EXE_ID, E.EXE_NOTE, E.HEIGHT, E.WEIGHT, ";
sql += " E.EXE_CHECK, TO_CHAR(R.RES_DATE, 'YYYY-MM-DD') RES_DATE ";
sql += " FROM EXECUTION E, RESERVATION R, MEMBER M ";
sql += " WHERE R.MEM_ID = M.MEM_ID";
sql += " AND R.RES_ID = E.RES_ID";
sql += " AND M.ID = ? AND E.EXE_CHECK= ?";
try {
conn = DBConn.getInstance();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
Vector v = new Vector();
v.add(rs.getInt("EXE_ID"));
v.add(rs.getString("EXE_NOTE"));
v.add(rs.getInt("HEIGHT"));
v.add(rs.getInt("WEIGHT"));
v.add(rs.getString("EXE_CHECK"));
v.add(rs.getString("RES_DATE"));
outV.add(v);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
}
}
return outV;
}
// 예약 변경 메소드(update set으로 기존 정보만 변경) 필요없어짐
public String updateRes(ReservationVo resVo1 ,ReservationVo resVo2) {
String result="예약 변경에 실패하였습니다";
Connection conn = null;
PreparedStatement pstmt = null;
String sql = "UPDATE RESERVATION";
sql += " SET RES_DATE = ?,";
sql += " T_ID = ? ";
sql += " WHERE RES_DATE = ? ";
try {
conn = DBConn.getInstance();
pstmt= conn.prepareStatement(sql);
pstmt.setString(1, resVo2.getResDate());
pstmt.setInt(2, resVo2.getResTId());
pstmt.setString(3, resVo1.getResDate());
pstmt.executeUpdate();
result=resVo2.getResDate()+"로 예약이 변경되었습니다";
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if( pstmt != null ) pstmt.close();
} catch (SQLException e) {
}
}
return result;
}
//예약 취소하기
public boolean removeRes(String resDate, int memId) {
boolean check = true;
Connection conn = null;
PreparedStatement pstmt =null;
String sql = "DELETE FROM RESERVATION ";
sql += " WHERE RES_DATE = ?";
sql += " AND MEM_ID = ?";
try {
conn= DBConn.getInstance();
pstmt= conn.prepareStatement(sql);
pstmt.setString(1,resDate);
pstmt.setInt(2, memId);
pstmt.executeUpdate();
check = true;
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
}
}
return check;
}
// 회원 개인 정보 조회( 점검 완료 ) -- 내 정보 창에 나오는 정보 위주
public MemberVo getMemInfo(String id) {
MemberVo memVo = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT M.MEM_NAME, M.TEL, M.GENDER, M.ADDR, M.HEIGHT, M.WEIGHT, MEM_BIRTH, E.REMAIN_NUM, R.RES_DATE";
sql += " FROM MEMBER M, RESERVATION R, EXECUTION E";
sql += " WHERE M.MEM_ID = R.MEM_ID AND R.RES_ID = E.RES_ID";
sql += " AND M.ID = ? ";
try {
conn = DBConn.getInstance();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
String name = rs.getString(1);
String tel = rs.getString(2);
String gender = rs.getString(3);
String addr = rs.getString(4);
int height = rs.getInt(5);
int weight = rs.getInt(6);
String birth = rs.getString(7);
int remainNum = rs.getInt(8);
String ptTime = rs.getString(9);
memVo = new MemberVo(height, weight,id, name,birth,
tel, gender, addr,
remainNum, ptTime); // 생성자 새로 생성했음 - 김영근
return memVo;
}
System.out.println(memVo);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return memVo;
}
//회수 연장 메소드
public String addNum(String id, int num){
String result = "회수 연장에 실패했습니다";
Connection conn = null;
PreparedStatement pstmt = null;
int resId = getResId(id);
String sql = "UPDATE EXECUTION";
sql += " SET REMAIN_NUM = REMAIN_NUM +?";
sql += " WHERE RES_ID = ? ";
try {
conn=DBConn.getInstance();
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1, num);
pstmt.setInt(2, resId);
pstmt.executeUpdate();
result= "회수가 "+num+"회 연장되었습니다";
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
private int getResId(String id) {
int resId= 0;
System.out.println("예약 번호 조회");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
int memId=getMemId(id);
String sql = "SELECT E.RES_ID";
sql += " FROM RESERVATION R JOIN EXECUTION E";
sql += " ON R.RES_ID = E.RES_ID ";
sql += " WHERE R.MEM_ID = ? ";
conn=DBConn.getInstance();
try {
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1, memId);
rs = pstmt.executeQuery();
if( rs.next() ){
memId = rs.getInt("E.RES_ID");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return resId;
}
//회원번호로 조회
private int getResId2(int memId) {
int resId= 0;
System.out.println("예약 번호 조회");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT E.RES_ID RS";
sql += " FROM RESERVATION R JOIN EXECUTION E";
sql += " ON R.RES_ID = E.RES_ID ";
sql += " WHERE R.MEM_ID = ? ";
conn=DBConn.getInstance();
try {
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1, memId);
rs = pstmt.executeQuery();
if( rs.next() ){
resId = rs.getInt("RS");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return resId;
}
//id를 받아 회원번호를 가져오는 메소드
public int getMemId(String id) {
int memId = 0;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT MEM_ID";
sql += " FROM MEMBER";
sql += " WHERE ID = ? ";
conn=DBConn.getInstance();
try {
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, id);
rs = pstmt.executeQuery();
if( rs.next() ){
memId = rs.getInt("MEM_ID");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return memId;
}
// 남은 횟수를 조회하는 메소드
public int getRemainNum(String id){
int remainNum = 0;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
int memId = getMemId(id);
String sql = "SELECT REMAIN_NUM ";
sql += " FROM EXECUTION ";
sql += " WHERE MEM_ID = ? ";
conn=DBConn.getInstance();
try {
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1, memId);
rs = pstmt.executeQuery();
if( rs.next() ){
remainNum = rs.getInt("REMAIN_NUM");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return remainNum;
}
//시간 버튼의 상태를 변경(빨강 비활성)
public ArrayList<JButton> getBtn(String date,ArrayList<JButton> btnSet) {
for (JButton jBtn : btnSet) {
String time = jBtn.getText();
String date2=date+" "+time;
boolean check = getResDate(date2); // 조회자료 존재 시 true 반환
if(check){
jBtn.setEnabled(false);
jBtn.setBackground(Color.RED);
}
}
return btnSet;
}
// 해당 날짜의 예약 상황을 조회하여 값이 존재하면 true 를 반환(조회값은 무엇이라도 상관없음)
private boolean getResDate(String date2) {
boolean check = false;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql= "SELECT MEM_ID";
sql += " FROM RESERVATION";
sql += " WHERE RES_DATE= ? ";
try {
conn=DBConn.getInstance();
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, date2);
rs=pstmt.executeQuery();
if( rs.next() ){
check = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return check;
}
//시간 버튼의 상태를 변경(파랑 활성)
public ArrayList<JButton> getMyRes(String date, String tName,String id, ArrayList<JButton> btnSet) {
for (JButton jBtn : btnSet) {
String time = jBtn.getText();
String date2= date+" "+time;
int tId = getTId(tName); //트레이너번호를 가져옴
int memId=getMemId(id); //회원번호 조회 메소드
boolean check = getMemRes(tId,memId,date2); // 조회자료 존재 시 true 반환
if(check){
jBtn.setEnabled(true);
jBtn.setBackground(Color.CYAN);
}
}
return btnSet;
}
//회원번호와 날짜를 인자로 받아 조회값이 존재할 경우 true를 반환
private boolean getMemRes(int tId, int memId, String date2) {
boolean check=false;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql= " SELECT RES_ID ";
sql += " FROM RESERVATION ";
sql += " WHERE MEM_ID = ? ";
sql += " AND RES_DATE = ? ";
sql += " AND T_ID = ? ";
try {
conn=DBConn.getInstance();
pstmt=conn.prepareStatement(sql);
pstmt.setInt(1, memId);
pstmt.setString(2, date2);
pstmt.setInt(3, tId);
rs=pstmt.executeQuery();
if( rs.next() ){
check = true;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return check;
}
//트레이너 이름을 받아 트레이너 번호로 반환하는 메소드
public int getTId(String tName) {
int tId=0; //트레이너 번호
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT T_ID ";
sql += " FROM TRAINER";
sql += " WHERE T_NAME = ? ";
try {
conn=DBConn.getInstance();
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, tName);
rs=pstmt.executeQuery();
if( rs.next() ){
tId = rs.getInt("T_ID");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return tId;
}
//id로 이름 조회
public String getName(String id){
String name=null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT MEM_NAME";
sql += " FROM MEMBER";
sql += " WHERE ID = ? ";
try {
conn=DBConn.getInstance();
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, id);
rs=pstmt.executeQuery();
if( rs.next() ){
name = rs.getString("MEM_NAME");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return name;
}
//이름로 id 조회
public String getId(String name){
String id=null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT ID";
sql += " FROM MEMBER";
sql += " WHERE MEM_NAME = ? ";
try {
conn=DBConn.getInstance();
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, name);
rs=pstmt.executeQuery();
if( rs.next() ){
id = rs.getString("ID");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return id;
}
//id로 이름 조회
public String getTName(String id){
String name=null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = "SELECT T_NAME";
sql += " FROM TRAINER";
sql += " WHERE ID = ? ";
try {
conn=DBConn.getInstance();
pstmt=conn.prepareStatement(sql);
pstmt.setString(1, id);
rs=pstmt.executeQuery();
if( rs.next() ){
name = rs.getString("T_NAME");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(rs!=null)rs.close();
if(pstmt!=null)pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return name;
}
// 로그인
public Boolean loginCheck1(String id, String pwd) {
Boolean check = false;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
MemberVo vo = new MemberVo();
String sql = "";
sql = "SELECT * FROM MEMBER";
sql += " WHERE ID = ? ";
sql += " AND PWD = ? ";
try {
conn = DBConn.getInstance();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
pstmt.setString(2, pwd);
rs = pstmt.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(null, getName(id) + "님 로그인 성공");
check = true;
} else {
JOptionPane.showMessageDialog(null, "아이디나 비밀번호가 일치하지 않습니다");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
}
}
return check;
}
//트레이너 로그인
public boolean trainerlogin(String id, String pwd) {
boolean check=false;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
MemberVo vo = new MemberVo();
String sql = "";
sql = "SELECT T_NAME FROM TRAINER";
sql += " WHERE ID = ? ";
sql += " AND PWD = ? ";
try {
conn = DBConn.getInstance();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, id);
pstmt.setString(2, pwd);
rs = pstmt.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(null, getName(id) + "님 로그인 성공");
check = true;
} else {
JOptionPane.showMessageDialog(null, "아이디나 비밀번호가 일치하지 않습니다");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (rs != null)
rs.close();
if (pstmt != null)
pstmt.close();
} catch (SQLException e) {
}
}
return check;
}
}
<file_sep>/src/view/MyInfo.java
package view;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import model.FitnessDao;
import model.MemberVo;
public class MyInfo extends JFrame implements ActionListener {
JButton JbPreView, Jbfire, JbProlong, btnPTreserved;
JLabel lblMyInfo, lblName, lblTel, lblAddr, lblRemainDay, lblPtTime, lblMyName, lblMyTel, lblMyAddr, lblMyReaminDay,
lblMyPtTime, lblMyWeight, lblMyHeight, lblHeight, lblWeight;
private String id = "";
public MyInfo(String id) {
FitnessDao dao = new FitnessDao();
this.id = id;
this.setTitle("내 정보");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
this.setSize(600, 500);
this.setResizable(false);
this.setLocationRelativeTo(null);
// 이전 버튼
JbPreView = new JButton("<이전");
JbPreView.setBackground(Color.WHITE);
JbPreView.setBounds(12, 10, 85, 23);
// 내 정보 label (맨 위)
lblMyInfo = new JLabel("내 정보");
lblMyInfo.setHorizontalAlignment(SwingConstants.CENTER);
lblMyInfo.setFont(new Font("맑은 고딕", Font.BOLD, 30));
lblMyInfo.setBounds(132, 10, 275, 90);
// 이름 label
lblName = new JLabel("이름");
lblName.setFont(new Font("Dialog", Font.BOLD, 20));
lblName.setHorizontalAlignment(SwingConstants.CENTER);
lblName.setBounds(69, 82, 171, 29);
// 전화번호 label
lblTel = new JLabel("전화번호");
lblTel.setFont(new Font("Dialog", Font.BOLD, 20));
lblTel.setHorizontalAlignment(SwingConstants.CENTER);
lblTel.setBounds(79, 121, 171, 29);
// 주소 label
lblAddr = new JLabel("주소");
lblAddr.setFont(new Font("Dialog", Font.BOLD, 20));
lblAddr.setHorizontalAlignment(SwingConstants.CENTER);
lblAddr.setBounds(69, 159, 171, 29);
// 남은 횟수 label
lblRemainDay = new JLabel("남은횟수");
lblRemainDay.setHorizontalAlignment(SwingConstants.CENTER);
lblRemainDay.setFont(new Font("Dialog", Font.BOLD, 20));
lblRemainDay.setBounds(69, 293, 171, 29);
// 예약시간 label
lblPtTime = new JLabel("PT 예약 시간");
lblPtTime.setHorizontalAlignment(SwingConstants.CENTER);
lblPtTime.setFont(new Font("Dialog", Font.BOLD, 20));
lblPtTime.setBounds(69, 348, 171, 29);
// 회원탈퇴 버튼
Jbfire = new JButton("회원탈퇴");
Jbfire.setForeground(Color.BLACK);
Jbfire.setBackground(Color.DARK_GRAY);
Jbfire.setFont(new Font("굴림", Font.PLAIN, 10));
Jbfire.setBounds(401, 405, 85, 23);
// 연장하기 버튼
JbProlong = new JButton("연장하기");
JbProlong.setBounds(382, 299, 85, 23);
// 데이터넣기이이이잉
MemberVo mv = dao.getMemInfo(id);
//System.out.println(mv);
String tel = mv.getTel();
String addr = mv.getAddress();
int remainNum = mv.getRemainNum();
String ptTime = mv.getPtTime();
int height = mv.getHeight();
int weight = mv.getWeight();
String name = mv.getname();
getLabel(name, tel, addr, remainNum, ptTime, height, weight);
// 나의 남은 횟 수
// lblMyReaminDay = new JLabel("OO일");
lblMyReaminDay.setHorizontalAlignment(SwingConstants.CENTER);
lblMyReaminDay.setFont(new Font("Dialog", Font.PLAIN, 15));
lblMyReaminDay.setBounds(262, 293, 149, 32);
// 내 이름
// lblMyName = new JLabel("OOO");
lblMyName.setHorizontalAlignment(SwingConstants.CENTER);
lblMyName.setFont(new Font("Dialog", Font.PLAIN, 15));
lblMyName.setBounds(279, 87, 149, 32);
// 내 전화번호
// lblMyTel = new JLabel("000-0000-0000");
lblMyTel.setHorizontalAlignment(SwingConstants.CENTER);
lblMyTel.setFont(new Font("Dialog", Font.PLAIN, 15));
lblMyTel.setBounds(289, 121, 149, 32);
// 내 주소
// lblMyAddr = new JLabel("부산광역시");
lblMyAddr.setFont(new Font("Dialog", Font.PLAIN, 15));
lblMyAddr.setHorizontalAlignment(SwingConstants.CENTER);
lblMyAddr.setBounds(279, 159, 149, 32);
// 내 PT 예약시간
// lblMyPtTime = new JLabel("2021-10-20 AM 00:00");
lblMyPtTime.setHorizontalAlignment(SwingConstants.CENTER);
lblMyPtTime.setFont(new Font("Dialog", Font.PLAIN, 15));
lblMyPtTime.setBounds(252, 348, 149, 32);
// 버튼 및 Label 추가
getContentPane().add(JbPreView);
getContentPane().add(JbProlong);
getContentPane().add(Jbfire);
getContentPane().add(lblName);
getContentPane().add(lblTel);
getContentPane().add(lblAddr);
getContentPane().add(lblRemainDay);
getContentPane().add(lblPtTime);
getContentPane().add(lblMyAddr);
getContentPane().add(lblMyInfo);
getContentPane().add(lblMyName);
getContentPane().add(lblMyPtTime);
getContentPane().add(lblMyReaminDay);
getContentPane().add(lblMyTel);
btnPTreserved = new JButton("예약변경");
btnPTreserved.setBounds(401, 354, 85, 23);
getContentPane().add(btnPTreserved);
lblHeight = new JLabel("키");
lblHeight.setFont(new Font("Dialog", Font.BOLD, 20));
lblHeight.setHorizontalAlignment(SwingConstants.CENTER);
lblHeight.setBounds(69, 202, 171, 29);
getContentPane().add(lblHeight);
lblWeight = new JLabel("몸무게");
lblWeight.setFont(new Font("Dialog", Font.BOLD, 20));
lblWeight.setHorizontalAlignment(SwingConstants.CENTER);
lblWeight.setBounds(69, 241, 171, 29);
getContentPane().add(lblWeight);
// lblMyHeight = new JLabel("170");
lblMyHeight.setHorizontalAlignment(SwingConstants.CENTER);
lblMyHeight.setFont(new Font("Dialog", Font.PLAIN, 15));
lblMyHeight.setBounds(279, 202, 149, 32);
getContentPane().add(lblMyHeight);
// lblMyWeight = new JLabel("72");
lblMyWeight.setHorizontalAlignment(SwingConstants.CENTER);
lblMyWeight.setFont(new Font("Dialog", Font.PLAIN, 15));
lblMyWeight.setBounds(279, 241, 149, 32);
getContentPane().add(lblMyWeight);
this.JbPreView.addActionListener(this);
this.JbProlong.addActionListener(this);
this.Jbfire.addActionListener(this);
this.btnPTreserved.addActionListener(this);
this.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case "<이전":
this.dispose();
new UserMenu(id);
break;
case "회원탈퇴":
new UserFire(id);
break;
case "연장하기":
new PTPrice(id);
break;
case "예약변경":
new PTreserved(id);
break;
}
}
public void getLabel(String name, String tel, String addr, int remainNum, String ptTime, int height,
int weight) {
String num = String.valueOf(remainNum);
String height2 = String.valueOf(remainNum);
String weight2 = String.valueOf(remainNum);
lblMyName = new JLabel(name);
lblMyAddr = new JLabel(addr);
lblMyPtTime = new JLabel(ptTime);
lblMyReaminDay = new JLabel(num);
lblMyTel = new JLabel(tel);
lblMyHeight = new JLabel(height2);
lblMyWeight = new JLabel(weight2);
}
public static void main(String[] args) {
new MyInfo("c2864");
}
}
<file_sep>/src/view/PTreserved.java
package view;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import model.FitnessDao;
import model.ReservationVo;
public class PTreserved extends JFrame implements ActionListener {
String id;
String aDate, tName;
int memId, tId;
String[] days;
String[] trainers;
int todayHour;
JLabel lblReserved, lblAM, lblPM;
JComboBox<String> cbDate;
JComboBox<String> cbTrainers;
JButton JBpreview, JB9h, JB10h, JB11h, JB12h, JB13h, JB14h, JB15h, JB16h, JB17h, JB18h, JB19h, JB20h;
FitnessDao fDao;
ArrayList<JButton> btnSet;
ReservationVo resVo;
public PTreserved(String id2) {
fDao = new FitnessDao(); // Dao 생성
this.id = id2; // 계정을 받아 변수에 저장
// Label~
lblReserved = new JLabel("PT 예약");
lblReserved.setFont(new Font("맑은 고딕", Font.BOLD, 30));
lblReserved.setBounds(160, 10, 400, 39); // 좌표 변경
getContentPane().add(lblReserved);
lblAM = new JLabel("오전");
lblAM.setFont(new Font("굴림", Font.BOLD, 40));
lblAM.setHorizontalAlignment(SwingConstants.CENTER);
lblAM.setBounds(27, 58, 95, 120);
getContentPane().add(lblAM);
lblPM = new JLabel("오후");
lblPM.setFont(new Font("굴림", Font.BOLD, 40));
lblPM.setHorizontalAlignment(SwingConstants.CENTER);
lblPM.setBounds(27, 248, 95, 120);
getContentPane().add(lblPM);
// 오늘을 포함한 8일이 포함된 콤보박스 작성
Calendar today = Calendar.getInstance();
int year = today.get(Calendar.YEAR);
int month = today.get(Calendar.MONTH);
int date = today.get(Calendar.DATE);
todayHour = today.get(Calendar.HOUR_OF_DAY);
String fmt = "%4d-%02d-%02d";
days = new String[8];
for (int i = 0; i < days.length; i++) {
String day = String.format(fmt, year, month + 1, date + i);
days[i] = day;
}
cbDate = new JComboBox<>(days);
cbDate.setBounds(400, 50, 150, 20);
getContentPane().add(cbDate);
aDate = (String) cbDate.getSelectedItem();
// 오늘의 예약 일정 표시(default)
lblReserved.setText(aDate + " 예약 일정");
// 트레이너 박스
trainers = new String[3];
trainers[1] = "조성오";
trainers[2] = "유은영";
trainers[3] = "임형준";
cbTrainers = new JComboBox<>(trainers);
cbTrainers.setBounds(200, 50, 150, 20);
getContentPane().add(cbTrainers);
tName = (String) cbTrainers.getSelectedItem();
// 버튼들 9~20시
JBpreview = new JButton("<회원화면");
getContentPane().setLayout(null);
JBpreview.setBounds(12, 10, 100, 30);
getContentPane().add(JBpreview);
JB9h = new JButton("09:00");
JB9h.setBounds(134, 77, 170, 60);
getContentPane().add(JB9h);
JB10h = new JButton("10:00");
JB10h.setBounds(313, 77, 170, 60);
getContentPane().add(JB10h);
JB12h = new JButton("11:00");
JB12h.setBounds(134, 136, 170, 60);
getContentPane().add(JB12h);
JB11h = new JButton("12:00");
JB11h.setBounds(313, 136, 170, 60);
getContentPane().add(JB11h);
JB13h = new JButton("13:00");
getContentPane().add(JB13h);
JB13h.setBounds(134, 209, 170, 60);
JB14h = new JButton("14:00");
getContentPane().add(JB14h);
JB14h.setBounds(313, 209, 170, 60);
JB18h = new JButton("18:00");
getContentPane().add(JB18h);
JB18h.setBounds(313, 327, 170, 60);
JB15h = new JButton("15:00");
getContentPane().add(JB15h);
JB15h.setBounds(134, 268, 170, 60);
JB19h = new JButton("19:00");
getContentPane().add(JB19h);
JB19h.setBounds(134, 386, 170, 60);
JB16h = new JButton("16:00");
getContentPane().add(JB16h);
JB16h.setBounds(313, 268, 170, 60);
JB20h = new JButton("20:00");
getContentPane().add(JB20h);
JB20h.setBounds(313, 386, 170, 60);
JB17h = new JButton("17:00");
getContentPane().add(JB17h);
JB17h.setBounds(134, 327, 170, 60);
// 시간 버튼들을 ArrayList에 담음
btnSet = new ArrayList<JButton>();
btnSet.add(0, JB9h);
btnSet.add(1, JB10h);
btnSet.add(2, JB11h);
btnSet.add(3, JB12h);
btnSet.add(4, JB13h);
btnSet.add(5, JB14h);
btnSet.add(6, JB15h);
btnSet.add(7, JB16h);
btnSet.add(8, JB17h);
btnSet.add(8, JB18h);
btnSet.add(8, JB19h);
btnSet.add(8, JB20h);
// 버튼 상태 조절
refresh();
// ActionListener에 버튼 등록
/// 날짜 콤보 박스
this.cbDate.addActionListener(this);
this.cbTrainers.addActionListener(this);
/// 이전 버튼
this.JBpreview.addActionListener(this);
;
/// 시간 버튼
for (JButton jBtn : btnSet) {
jBtn.addActionListener(this);
}
this.setSize(600, 500);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null); // 중앙에 열리도록 조정
this.setVisible(true);
}
public void refresh() { // 새로 고침
aDate = (String) cbDate.getSelectedItem();
tName = (String) cbTrainers.getSelectedItem();
// default = 모두 예약 가능 상태
for (JButton jBtn : btnSet) {
jBtn.setBackground(Color.GREEN);
jBtn.setEnabled(true);
}
//
// ArrayList를 던져 현재 예약상황에 맞는 버튼 상태로 변경(트레이너 이름을 인자로 넣어 수정할 필요)
btnSet = fDao.getBtn(aDate, btnSet);
// ArrayList를 던져 현재 자신이 예약한 시간 버튼의 상태를 변경
btnSet = fDao.getMyRes(aDate, tName, id, btnSet);
// 현재 시간+2시간 만큼의 시간의 예약을 불가능 하게 함.
if(cbDate.getSelectedItem()==days[0]) {
for (JButton jBtns : btnSet) {
String[] li= jBtns.getText().split(":");
int hour=Integer.parseInt(li[0]);
if(todayHour+2>=hour) {
jBtns.setEnabled(false);
}
}
}
}
// ActionListener
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("<회원화면")) { // 이전 버튼
dispose();
new UserMenu(id);
}
// 시간 버튼 선택시 예약 추가 창 뜨기(미완성)
String time = "";
Color col = null;
for (int num = 9; num <= 20; num++) {
time = String.format("%02d:00", num);
// 해당 시간의 색상 추출 반복문
for (JButton btns : btnSet) {
if (btns.getText().equals(time)) {
col = btns.getBackground();
}
}
if (e.getActionCommand().equals(time)) {
String date = (String) cbDate.getSelectedItem();
String resDate = date + " " + time;
String[] answer = { "예약", "취소" };
String[] cancel = { "예약취소", "닫기" };
memId = fDao.getMemId(id);
tId = fDao.getTId(tName);
if (col == Color.GREEN) { // 예약이 가능한 경우
int ans = JOptionPane.showOptionDialog(null, resDate + "\n예약하시겠습니까?", "PT 예약 확인",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, answer, answer[1]);
if (ans == 0) {
resVo = new ReservationVo(resDate, memId, tId);
boolean check = fDao.reserve(resVo);
if (check) {
JOptionPane.showMessageDialog(null, resDate + "\n 예약되었습니다", "예약 확인", JOptionPane.OK_OPTION);
} else {
JOptionPane.showMessageDialog(null, "예약에 실패했습니다", "오류", JOptionPane.OK_OPTION);
}
}
} else if (col == Color.CYAN) { // 기존 예약을 취소할 경우
int ans2 = JOptionPane.showOptionDialog(null, resDate + "\n예약취소하시겠습니까?", "PT 예약취소 확인",
JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, cancel, cancel[1]);
if (ans2 == 0) {
boolean check = fDao.removeRes(resDate, memId);
if (check) {
JOptionPane.showMessageDialog(null, resDate + "\n 예약이 취소되었습니다", "예약 취소 확인",
JOptionPane.OK_OPTION);
} else {
JOptionPane.showMessageDialog(null, "예약 취소에 실패했습니다", "오류", JOptionPane.OK_OPTION);
}
}
}
}
}
// 콤보 박스의 날짜를 선택할 때마다 레이블의 텍스트 변경
lblReserved.setText((String) cbDate.getSelectedItem() + " 예약 일정");
refresh();
}
// public static void main(String[] args) {
// String id = "guest2";
// new PTreserved(id);
//
// }
}
<file_sep>/src/view/TrainerMenu.java
package view;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import model.FitnessDao;
public class TrainerMenu extends JFrame implements ActionListener, MouseListener {
private JTextField textField;
JPanel leftpanel, rightpanel;
JLabel inName, inGender, inTelLabel, inAddressLabel, inBookLabel, inRemainLabel;
JTable table;
JScrollPane scrollPane;
DefaultTableModel dtm;
Vector v;
Vector column;
JTextArea specTextArea,PtTextArea;
String tid = "";
public TrainerMenu(String id) {
this.setTitle("트레이너 화면");
this.tid = id;
leftpanel = new JPanel();
leftpanel.setBounds(0, 0, 356, 651);
getContentPane().add(leftpanel);
leftpanel.setLayout(null);
// 이름
inName = new JLabel("");
inName.setBounds(121, 22, 207, 29);
leftpanel.add(inName);
// 성별
inGender = new JLabel("");
inGender.setBounds(121, 72, 207, 29);
leftpanel.add(inGender);
// 전화번호
inTelLabel = new JLabel("");
inTelLabel.setBounds(123, 122, 205, 29);
leftpanel.add(inTelLabel);
// 주소
inAddressLabel = new JLabel("");
inAddressLabel.setToolTipText(inAddressLabel.getText());
inAddressLabel.setBounds(123, 172, 205, 29);
leftpanel.add(inAddressLabel);
// 예약시간
inBookLabel = new JLabel("");
inBookLabel.setBounds(123, 222, 205, 29);
leftpanel.add(inBookLabel);
// 남은일수
inRemainLabel = new JLabel("");
inRemainLabel.setBounds(123, 272, 205, 29);
leftpanel.add(inRemainLabel);
JLabel NameLabel = new JLabel("회원 이름 : ");
NameLabel.setBounds(20, 22, 82, 29);
leftpanel.add(NameLabel);
JLabel genderLabel = new JLabel("성별 : ");
genderLabel.setBounds(20, 72, 82, 29);
leftpanel.add(genderLabel);
JLabel telLabel = new JLabel("전화번호 :");
telLabel.setBounds(20, 122, 82, 29);
leftpanel.add(telLabel);
JLabel addressLabel = new JLabel("주소 : ");
addressLabel.setBounds(20, 172, 82, 29);
leftpanel.add(addressLabel);
JLabel bookLabel = new JLabel("예약 시간 : ");
bookLabel.setBounds(20, 222, 82, 29);
leftpanel.add(bookLabel);
JLabel remainLabel = new JLabel("남은 횟수 :");
remainLabel.setBounds(20, 272, 82, 29);
leftpanel.add(remainLabel);
JButton btnNewButton_2 = new JButton("수정");
btnNewButton_2.setBounds(143, 616, 82, 29);
leftpanel.add(btnNewButton_2);
JButton btnNewButton_2_1 = new JButton("삭제");
btnNewButton_2_1.setBounds(246, 616, 82, 29);
leftpanel.add(btnNewButton_2_1);
rightpanel = new JPanel();
rightpanel.setBounds(357, 0, 527, 651);
getContentPane().add(rightpanel);
rightpanel.setLayout(null);
JLabel lblNewLabel_5 = new JLabel("회원관리");
lblNewLabel_5.setFont(new Font("굴림", Font.BOLD, 30));
lblNewLabel_5.setBounds(27, 10, 276, 80);
rightpanel.add(lblNewLabel_5);
JButton btnNewButton = new JButton("로그아웃");
btnNewButton.setBounds(340, 24, 91, 29);
rightpanel.add(btnNewButton);
//JScrollPane
specTextArea= new JTextArea();
PtTextArea = new JTextArea();
JScrollPane spScroll = new JScrollPane(specTextArea);
JScrollPane ptScroll = new JScrollPane(PtTextArea);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
tabbedPane.setBounds(14, 338, 340, 260);
leftpanel.add(tabbedPane);
tabbedPane.addTab("특이사항", spScroll );
tabbedPane.addTab("PT 내역", ptScroll );
dtm = new DefaultTableModel(column, 1);
table = new JTable();
table.setModel(new DefaultTableModel(getDataList(), getColums()) {
public boolean isCellEditable(int row, int column) {
// 각 cell 마다 편집가능 : false - 편집기능 해제
return false;
}
});
scrollPane = new JScrollPane(table);
scrollPane.setBounds(12, 153, 503, 488);
rightpanel.add(scrollPane);
JButton btnNewButton_1 = new JButton("검색");
btnNewButton_1.setBounds(12, 120, 76, 23);
rightpanel.add(btnNewButton_1);
textField = new JTextField();
textField.setBounds(100, 121, 230, 21);
rightpanel.add(textField);
textField.setColumns(10);
this.table.addMouseListener(this);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(900, 700);
this.setLocationRelativeTo(null);
getContentPane().setLayout(null);
this.setVisible(true);
}
// 제목줄
private Vector getColums() {
Vector column = new Vector();
column.add("회원번호");
column.add("회원이름");
column.add("성별");
column.add("전화번호");
column.add("주소");
column.add("예약시간");
return column;
}
// 회원 조회한 데이터 가져오기
private Vector getDataList() {
FitnessDao dao = new FitnessDao();
Vector v = dao.MemberList();
//System.out.println(v);
return v;
}
// 테이블 그리기
private DefaultTableModel initTable() {
// 제목줄 처리 : cols
column = getColums();
// 데이터 처리 : v
v = getDataList();
DefaultTableModel dtm = new DefaultTableModel(v, column);
return dtm;
}
// 회원 정보를 라벨에 넣어서 표시
public void getLabel(String name, String gender, String tel,
String addr, String reserved, int enough) {
// 이름
inName.setText(name);
// 성별
inGender.setText(gender);
// 전화번호
inTelLabel.setText(tel);
// 주소
inAddressLabel.setText(addr);
// 예약시간
inBookLabel.setText(reserved);
// 남은횟수
inRemainLabel.setText(Integer.toString(enough));
}
// 라벨청소
private void clearLabels() {
// 이름
inName.setText("");
// 성별
inGender.setText("");
// 전화번호
inTelLabel.setText("");
// 주소
inAddressLabel.setText("");
// 예약시간
inBookLabel.setText("");
// 남은일수
inRemainLabel.setText("");
//특이사항
specTextArea.setText("");
//PT내역
PtTextArea.setText("");
}
// JTable row 클릭했을 때 회원정보 leftPanel에 나오게
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
FitnessDao dao = new FitnessDao();
int r = table.getSelectedRow();
int c = table.getSelectedColumn();
String memid = (String) table.getValueAt(r, 0);
String name = (String) table.getValueAt(r, 1);
String gender = (String) table.getValueAt(r, 2);
String tel = (String) table.getValueAt(r, 3);
String addr = (String) table.getValueAt(r, 4);
String reserved = (String) table.getValueAt(r, 5);
int enough = dao.getRemainNum(dao.getId(name));
leftpanel.repaint();
getLabel(name, gender, tel, addr, reserved, enough);
//특이사항 메소드 연결
specTextArea.setText(dao.specialMem(memid));
//PT 내역사항 메소드랑 연결해야함!!!! -- 2021.10.17
//PtTextArea.setText();
//System.out.println(name + " " + gender + " " + tel + " " + addr + " " + reserved + " " + enough);
}
// JTable 누를때 라벨 청소
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
if (inName != null)
clearLabels();
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
public static void main(String[] args) {
new TrainerMenu("trainer1");
}
}
| 55e940cd5589918a89b115319ca1b9ebe1ea4639 | [
"Java"
] | 9 | Java | dudrms9373/GreenPRJ | 66122fc8e22f7f33f9b1d9da6c4f751afb4d89ce | f8912cc4fcdeca62fa64694dc672c772828d303e |
refs/heads/master | <repo_name>w49m4t/JavaEquiationSolver<file_sep>/JavaEquiationSolver.java
public class JavaEquiationSolver{
public static void main(String []args){
linEq leq = new linEq();
linEq leq1 = new linEq();
linEq leq2 = new linEq();
linEq leq3 = new linEq();
leq.inpEq("32.1 x + 43 = 1 98");
leq1.inpEq("35x- 43=198");
leq2.inpEq("35+ 43x=198");
leq3.inpEq("35 = 198x - 43");
System.out.println("x = " + leq.result);
System.out.println("x = " + leq1.result);
System.out.println("x = " + leq2.result);
System.out.println("x = " + leq3.result);
}
}
abstract class equiation{
float a;
float b;
float c;
float d;
abstract void inpEq(String eq);
float result;
}
class linEq extends equiation{
void inpEq(String eq){
//defining the patterns that could be a linear equiation
String ptrn = new String("[1-9]+(\\.[1-9]+)?x[+-][1-9]+(\\.[1-9]+)?=[1-9]+(\\.[1-9]+)?");
String ptrn1 = new String("[1-9]+(\\.[1-9]+)?[+-][1-9]+(\\.[1-9]+)?x=[1-9]+(\\.[1-9]+)?");
String ptrn2 = new String("[1-9]+(\\.[1-9]+)?=[1-9]+(\\.[1-9]+)?x[+-][1-9]+(\\.[1-9]+)?");
String ptrn3 = new String("[1-9]+(\\.[1-9]+)?=[1-9]+(\\.[1-9]+)?[+-][1-9]+(\\.[1-9]+)?x");
//removing whitespaces in order to match the patterns
String eqNospace = eq.replaceAll("\\s+","");
//assigning the coeficients with the applicable pattern
String[] tkn = new String[99];
if(eqNospace.matches(ptrn)){
tkn = eqNospace.split("x[+]|x[-]|[=]");
a = Float.parseFloat(tkn[0]);
b = Float.parseFloat(tkn[1]);
c = Float.parseFloat(tkn[2]);
}else if(eqNospace.matches(ptrn1)){
tkn = eqNospace.split("[+]|[-]|x[=]");
a = Float.parseFloat(tkn[1]);
b = Float.parseFloat(tkn[0]);
c = Float.parseFloat(tkn[2]);
}else if(eqNospace.matches(ptrn2)){
tkn = eqNospace.split("x[+]|x[-]|[=]");
a = Float.parseFloat(tkn[1]);
b = Float.parseFloat(tkn[2]);
c = Float.parseFloat(tkn[0]);
}else if(eqNospace.matches(ptrn3)){
tkn = eqNospace.split("x[+]|x[-]|[=]");
a = Float.parseFloat(tkn[2]);
b = Float.parseFloat(tkn[1]);
c = Float.parseFloat(tkn[0]);
}else{
tkn = ("1x+1=1000000000000").split("x|[+-]|[=]");
}
/*
System.out.println(a);
System.out.println(b);
System.out.println(c);
*/
//dealing with the negative coeficients TBD
if(eqNospace.contains("-")){
result = slvLin(a, -b, c);
}else{
result = slvLin(a, b, c);
}
}
private float slvLin(float a, float b, float c){
try{
return (c-b)/a;
}catch(Exception e){
return 999999;
}
}
}
class quadEq extends equiation{
void inpEq(String eq){
//TBD
}
}
<file_sep>/README.md
# JavaEquiationSolver
_An equiation solver coded in java_
## Funcitionalities
The following features are readily available: Linear equiation solver for $ax+b=c$ type equiation. The coeficients could be integers and floats, currently the b could be non-negative.
## Next steps
We plan to achieve in order of the planned actions:
1. handling all negative coeficients
2. extend to ax+b = c+d types
3. handling quadratic equiations
4. creating a user form reader
5. creating an OCR parser
| 4c89c4e256892060b9101cf31562040628f046f4 | [
"Markdown",
"Java"
] | 2 | Java | w49m4t/JavaEquiationSolver | 94a87154058c4b85949b49123916b861236f2456 | e7d79c897958f7067c49f2bf9c29d0b4b11d6896 |
refs/heads/master | <repo_name>ff2248/lazyload-rails<file_sep>/lib/lazyload-rails.rb
require "nokogiri"
require "action_view"
require "lazyload-rails/version"
require 'lazyload-rails/engine' if defined?(Rails::Engine)
ActionView::Helpers::AssetTagHelper.module_eval do
alias :rails_image_tag :image_tag
def image_tag(*attrs)
options, args = extract_options_and_args(*attrs)
image_html = rails_image_tag(*args)
if options[:lazy]
to_lazy_image(image_html)
else
image_html
end
end
private
def to_lazy_image(image_html)
img = Nokogiri::HTML::DocumentFragment.parse(image_html).at_css("img")
img["data-original"] = img["src"]
img["src"] = image_path("lazyload/loading.gif")
img["class"] = img["class"].to_s.split.push(:lazy).join(" ")
img.to_s.html_safe
end
def extract_options_and_args(*attrs)
args = attrs
if args.size > 1
options = attrs.last.dup
args.last.delete(:lazy)
else
options = {}
end
[options, args]
end
end
| 863f8da132dd0230f1ecd0c873ddec0afa5af392 | [
"Ruby"
] | 1 | Ruby | ff2248/lazyload-rails | e0c95d525a224ecc31947c12a0aaffcdab33b009 | 0069403c107b26a1976afaa9c0e785c841e2f941 |
refs/heads/master | <file_sep> InputField is the common type of input and represents the behavior you would expect from a standard HTML `<input />` with the additional framework functionality like labels, hints, formatting and error management build on top.
Note: At this time InputField simply extends the base Field as it requires no additional functionality, however it has been given its
own class to resurvey the name space, and prevent changes to the base API in the future if the functionality was to diverge slightly.
~~~js
<div>
hello world!
<Button onClick={action('clicked')}>Hello Button</Button>
</div>
~~~
format
| Param | Type | Default | Required |
| ------------- |:-------------:| :-------------:| -----:|
| onClick | function | | yes |
| block | bool | false | no |
| disables | bool | false | no |
| loading | bool | false | no |
| size | int | defULT | no |
| type | (primary, secondary) | primary | no |
<file_sep>export {default as PasswordField} from './PasswordField';
<file_sep>export {default as Tag} from './Tag';
export {default as TagGroup} from './TagGroup';<file_sep>export {default as Breadcrumb} from './Breadcrumb';
export {default as BreadcrumbItem} from './BreadcrumbItem';<file_sep>// file: src/stories/index.js
import React from 'react';
import {storiesOf} from '@storybook/react';
import {action} from '@storybook/addon-actions';
import {withNotes} from '@storybook/addon-notes';
import {withKnobs, text, boolean, object} from '@storybook/addon-knobs';
import documentation from './documentation.md';
import SideModal from './SideModal';
const stories = storiesOf('Modal', module);
stories.addDecorator(withKnobs);
stories.add('SideModal', withNotes(documentation)(() => (
<SideModal title="Side Modal" isOpen={true}>
<div style={{backgroundColor: '#f6f7f8', height: '100%'}}>Some content...</div>
</SideModal>
)))<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import {Box} from "elements/box";
import style from './List.scss';
/**
* List is a custom styled DataView which allows Grouping
*/
export default class List extends Box {
static propTypes = {
...Box.propTypes,
/**
* An array of data representing each list item.
*/
records: PropTypes.array
};
static defaultProps = {
...Box.defaultProps,
records: []
};
constructor(props) {
super(props);
// This is an abstract class and cannot be darcey creates
if (this.constructor === List) {
throw new TypeError('Abstract class "List" cannot be instantiated directly.');
}
this.state = {
...this.state,
records: []
}
}
renderItem(record) {
return (
<div>
<b>Default list item</b>
<p>Override the `renderItem(record)` method the provide your own ite.</p>
</div>
);
}
renderList() {
let {records} = this.props;
if (!records) {
return null;
}
const list = records.map((record) => {
return this.renderItem(record);
});
return (
<div className={style.container}>
{list}
</div>
)
}
render() {
const content = this.renderList();
return this.renderBox(content);
}
}<file_sep>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import css from './Grid.scss';
// Report the row and column
export {default as Row} from './Row';
export {default as Col} from './Col';
export default class Grid extends Component {
static propTypes = {
fluid: PropTypes.bool,
style: PropTypes.object,
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
]),
className: PropTypes.string
};
static defaultProps = {
fluid: false
};
render() {
const {children, fluid, style, className} = this.props;
const classes = classNames(css.grid, className, {
[css.gridFluid]: fluid
});
return (
<div style={style} className={classes}>{children}</div>
);
}
}
<file_sep><h2>Description</h2>
A password input field that shown the strength of a password as it is entered.
Note: this Field is still in developement, and the API may change before initial release. If you wish to have a secure password imput, use `<InputField type="password">` for now.
<h2>Usage</h2>
~~~js
import {PasswordField} from 'react-ui-modules';
<PasswordField
name="test-field"
type="email"
value={this.props.value}
error={this.props.error}
placeholder="This is an example placeholder"
label="Example Label"
onChange={(name, value, touched) => {
this.setState({value});
}}
data-test-id="example-test-id"
prepend="$"
append=".00"
/>
~~~
## Props
## Functions
## Events
<file_sep>import React from 'react';
import BreadcrumbItem from './BreadcrumbItem';
import style from './Breadcrumb.scss';
const Breadcrumb = ({children}) => {
return (
<ol className={style.breadcrumb}>
<BreadcrumbItem path="/">
TODO Icon
</BreadcrumbItem>
{children}
</ol>);
};
export default Breadcrumb;<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {Component} from 'elements/base';
import {FieldSet} from 'elements/form/field';
import style from './Field.scss';
/**
* Field is the base class for all form fields. It provides a lot of shared functionality to all field subclasses
* (for example labels, simple validation, clearing and tab index management), but is rarely used directly.
* Instead, it is much more common to use one of the field subclasses.
*
* If you wish to create your own Field subclasses you can extend this class, though it is sometimes more useful
* to extend one of the other base subclasses as they provides additional base functionality.
*/
export default class BaseField extends Component {
static propTypes = {
name: PropTypes.string.isRequired,
disabled: PropTypes.bool,
className: PropTypes.string,
hint: PropTypes.string,
label: PropTypes.string,
placeholder: PropTypes.string,
type: PropTypes.string,
};
static defaultProps = {
...Component.defaultProps,
label: null,
disabled: false,
placeholder: '',
type: 'text'
};
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.onBlur = this.onBlur.bind(this);
this.onFocus = this.onFocus.bind(this);
this.setNode = this.setNode.bind(this);
this.state = {
focus: false
};
}
/**
* Make a change to the components value if the field is not disabled.
* @param value
*/
onChange(value) {
const {name, onChange, disabled} = this.props;
if (!disabled) {
onChange(name, value);
}
}
/**
* Remove focus from this component
*
* Note: this wont remove the dom level focus, only the internal component focus. Dom focus will need to
* be managed outside this component.
*
*/
onBlur() {
this.setState(
{
focus: false
}
)
}
/**
* Set focus on this component.
*
* Note: this wont set the dom level focus, only the internal component focus. Dom focus will need to
* be managed outside this component.
*/
onFocus() {
this.setState(
{
focus: true
}
)
}
/**
* Render the component label
* @returns {XML}
*/
renderLabel() {
const {label, name, error} = this.props;
const {focus} = this.state;
if (!label) {
return;
}
const classes = classNames(style.label, {
[style.labelFocus]: focus,
[style.labelError]: error
});
return <label className={classes} htmlFor={name}>{label}</label>;
}
/**
* Render the components input field. The part of the component that is used to set and display the
* components value
* @returns {XML}
*/
renderInput() {
const {input, name, value, placeholder, type, disabled, autoFocus, testId} = this.props;
return (
<input
data-test-id={'input-' + testId}
name={name}
className={style.input}
autoFocus={autoFocus}
value={(value) ? value : ''}
placeholder={placeholder}
type={type}
onBlur={this.onBlur}
onFocus={this.onFocus}
disabled={disabled}
onChange={(event) => {
const target = event.target;
const value = target.value;
this.onChange(value);
}}
/>
);
}
/**
* Render component hint message
* @returns {*}
*/
renderHint() {
const {hint, testId} = this.props;
return (hint) ? <small data-test-id={"hint-" + testId} className={style.hint}>{hint}</small> : '';
}
/**
* Render the components error states.
* @returns {XML}
*/
renderError() {
const {error, testId} = this.props;
return <span data-test-id={"error-" + testId} className={style.error}>{error}</span>;
}
/**
* Render the component.
*
* Note: it is encouraged that components extending this Field component avoid overriding the render method
* if possible. Instead the extending component should focus on overriding the other render methods like
* `renderInput()` and `renderLabel()`.
*
* If you do end up overriding the render method, you will need to make sure you set the root dom node by
* setting `ref={this.setNode}` on the root dom node element.
*
* @returns {XML}
*/
render() {
const {className, testId} = this.props;
const classes = classNames(style.wrapper, className);
return (
<div data-test-id={'input-' + testId} className={style.wrapper} ref={this.setNode}>
{this.renderInput()}
</div>
);
}
}
<file_sep>export default class Format {
formatString(value){return value;}
}<file_sep><h2>Description</h2>
Specialized SelectorField which only supports two values true or false.
Note: A empty or null value will display as false.
<h2>Usage</h2>
~~~js
import {ToggleField} from 'react-ui-modules';
<ToggleField
type={ToggleField.TYPE.TRUE_FALSE}
name="test-field"
type="email"
value={this.props.value}
error={this.props.error}
placeholder="This is an example placeholder"
label="Example Label"
onChange={(name, value, touched) => {
this.setState({value});
}}
data-test-id="example-test-id"
/>
~~~
## Props
<dl>
<dt><a href="#event_onChange">type</a></dt>
<dd><p>Style type, one of (ToggleField.TYPE.ON_OFF, ToggleField.TYPE.TRUE_FALSE, ToggleField.TYPE.YES_NO, ToggleField.TYPE.GREEN_RED)</p>
</dd>
</dl>
## Functions
## Events
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import {Icon, IconType} from 'elements/icon';
import {Component} from 'elements/base';
import Month from './Month';
import style from './Calendar.scss';
export default class Calendar extends Component {
static propTypes = {
...Calendar.propTypes,
dateFormat: PropTypes.string,
onEventClick: PropTypes.func,
events: PropTypes.arrayOf(
PropTypes.shape(
{
start: PropTypes.string.isRequired,
stop: PropTypes.string.isRequired,
label: PropTypes.string.isRequired
}
)
),
};
static defaultProps = {
...Calendar.defaultProps,
dateFormat: 'YYYY-MM-DD',
};
constructor(props) {
super(props);
this.increaseMonth = this.increaseMonth.bind(this);
this.decreaseMonth = this.decreaseMonth.bind(this);
const today = this.localizeMoment(moment());
const date = (props.value) ? this.stringToDate(props.value) : today;
Object.assign(this.state, super.state, {
today,
date,
});
}
increaseMonth() {
}
decreaseMonth() {
}
/**
* localize into current local
* @param date
* @returns {Duration|string|Moment}
*/
localizeMoment(date) {
return date.clone()
.locale(this.props.locale || moment.locale());
}
stringToDate(date) {
const {dateFormat} = this.props;
return moment(date, dateFormat);
}
renderMonths() {
const {date} = this.state;
const monthDate = date.clone();
return this.renderCurrentMonth(monthDate);
}
renderCurrentMonth(date = this.state.date) {
const {today} = this.state;
const {dateFormat, events, onEventClick} = this.props;
return (<Month date={date} today={today} dateFormat={dateFormat} events={events} onEventClick={onEventClick}/>)
}
render() {
const {date} = this.state;
const year = date.format('YYYY');
const month = date.format('MMMM');
return <div className={style.container}>
<div className={style.header}>
<div className={style.navigation}>
<Icon onClick={this.decreaseMonth} className={style.navigationBack} type={IconType.angleLeft}/>
<Icon onClick={this.increaseMonth} className={style.navigationForward} type={IconType.angleRight}/>
</div>
<div className={style.headerYear}>{year}</div>
<div className={style.headerMonth}>{month}</div>
</div>
<div className={style.calendar}>
<ul className={style.weekdays}>
<li className={style.weekdaysDay}>Sun</li>
<li className={style.weekdaysDay}>Mon</li>
<li className={style.weekdaysDay}>Tue</li>
<li className={style.weekdaysDay}>Wed</li>
<li className={style.weekdaysDay}>Thu</li>
<li className={style.weekdaysDay}>Fri</li>
<li className={style.weekdaysDay}>Sat</li>
</ul>
<div className={style.calendarDays}>
{this.renderMonths()}
</div>
</div>
</div>
}
}
<file_sep>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import moment from 'moment';
import Day from './Day';
import Event from './Event';
import style from './Calendar.scss';
export default class Week extends Component {
static propTypes = {
today: PropTypes.object.isRequired,
date: PropTypes.object.isRequired,
week: PropTypes.object.isRequired,
};
constructor(props){
super(props);
}
renderDays() {
const {today, date, week} = this.props;
const startOfWeek = week.clone();
const days = [];
return days.concat([0, 1, 2, 3, 4, 5, 6].map((offset) => {
const day = startOfWeek.clone()
.add(offset, 'days');
const isToday = (day.isSame(today, 'day'));
const isThisMonth = (day.isSame(date, 'month'));
const key = "weekday-" + offset;
return <Day key={key} day={day} isToday={isToday} isThisMonth={isThisMonth}/>
}));
}
buildEvent(label, color = null, days = 1, offset = 0, isStart = true, isEnd = true) {
const unitSize = (100 / 7);
let width = (unitSize * days) + "%";
let marginLeft = (unitSize * offset) + "%";
const inlineStyle = {
marginLeft,
width,
backgroundColor: color
};
const classes = classNames(style.event, {
[style.eventStart]: isStart,
[style.eventEnd]: isEnd
});
return (
<div style={inlineStyle} className={classes}>
<div className={style.eventLabel}>{(label) ? label : '\u00A0'}</div>
</div>
);
}
/**
* Render the events for the week.
*
* TODO, this needs a major rework, it is very inefficient and some of the functionality should be moved back to the
* Calendar object so that it only needs to be passed once.
*
* @returns {XML}
*/
renderEvents() {
const {dateFormat, events, week, onEventClick} = this.props;
let rows = [
{
offset: 0,
events: []
}
];
let other = [];
if (!events) {
return;
}
// Process the events
let eventsObject = events.map((event) => {
let startDate = moment(event.start, dateFormat);
let stopDate = moment(event.stop, dateFormat);
const length = stopDate.diff(startDate, 'day') + 1;
return {
...event,
startDate,
stopDate,
length
}
});
// Sort by start date
let sortEvents = eventsObject.sort((a, b) => {
return a.startDate.isAfter(b.startDate);
});
const startOfWeek = week.clone()
.startOf('week');
const endOfWeek = week.clone()
.endOf('week');
sortEvents.map((event) => {
const isStart = event.startDate.isSame(week, 'week');
const isEnd = event.stopDate.isSame(week, 'week');
const isBetween = week.isBetween(event.startDate, event.stopDate);
// The total number of days this event runs.
const length = (isStart) ? event.length : event.stopDate.diff(startOfWeek, 'day') + 1;
// The events offset based on the first day of the week.
const offset = (!isStart) ? 0 : event.startDate.diff(startOfWeek, 'day');
// The number of days this event should display in the week.
const days = ((length + offset) > 7) ? 7 - offset : length;
if (isStart || isEnd || isBetween) {
let inRow = rows.some((row) => {
// The new events offset based on the last event in the row.
const diff = (offset - row.offset > 0) ? offset - row.offset : 0;
if (row.offset <= offset && (diff + days) <= 7) {
row.offset = offset + days;
row.events.push(<Event event={event} days={days} offset={diff} isStart={isStart} isEnd={isEnd} onClick={onEventClick}/> );
inRow = true;
return true;
}
});
// If we cant fit this event in an existing row, add a new row.
if (!inRow) {
rows.push(
{
offset: offset + days,
events: [
<Event event={event} days={days} offset={offset} isStart={isStart} isEnd={isEnd} onClick={onEventClick}/>
]
}
);
}
}
});
return rows.map((row) => {
return (
<div className={style.eventRow}>
{row.events}
</div>
);
});
}
render() {
return (
<div className={style.week}>
<div className={style.weekDays}>
{this.renderDays()}
</div>
<div className={style.events}>
{this.renderEvents()}
</div>
</div>
);
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {Component} from 'elements/base';
import style from './ComponentTemplate.scss';
/**
* This component provides a push button with many presentation options.
* There are various styles of Button you can create
*/
export default class ComponentTemplate extends Component {
static propTypes = {
isExample: PropTypes.bool,
};
static defaultProps = {
isExample: false,
};
render() {
return (
<div>...</div>
)
}
}
<file_sep>export {default as Format} from './Format';
export {default as NumberFormat} from './NumberFormat';
<file_sep><h2>Description</h2>
The SelectField represents a html `<select>` control with support for autocomplete.
A SelectField is like a combination of a traditional HTML text `<input>` field and a `<select>` field, and extends on top of the DropdownField.
<h2>Usage</h2>
~~~js
import {SelectField} from 'react-ui-modules';
<SelectField
options={[
{
value: 1,
label: 'QLD'
}, {
value: 2,
label: 'NSW'
}, {
value: 3,
label: 'NSWL'
}, {
value: 4,
label: 'SA'
}, {
value: 5,
label: 'WA'
}, {
value: 6,
label: 'International'
}
]}
name="test-field"
value={this.props.value}
error={this.props.error}
placeholder="This is an example placeholder"
label="Example Label"
onChange={(name, value, touched) => {
this.setState({value});
}}
data-test-id="example-test-id"
prepend="$"
append=".00"
/>
~~~
## Props
## Functions
## Events
<file_sep> A basic button component. Supports a minimal level of customization.
## Example Usage
~~~js
import {Button} from 'react-ui-modules';
<div>
hello world!
<Button onClick={action('clicked')}>Hello Button</Button>
</div>
~~~
| Param | Type | Default | Required |
| ------------- |:-------------:| :-------------:| -----:|
| onClick | function | | yes |
| block | bool | false | no |
| disables | bool | false | no |
| loading | bool | false | no |
| size | int | defULT | no |
| type | (primary, secondary) | primary | no |
<file_sep># Description
A date component provides a simple way to display a date in a different format.
# Example
~~~js
import {DateTime} from 'react-ui-modules'
<DateTime
date={this.state.value}
toFormat="YYYY-MM-DD"
fromFormat="Do MMMM YYYY"
/>
~~~
panelClassNames
inputClassNames
disabled
# Date Format
The DateTime allows the date format to be set for both the 'toFormat' and 'fromFormat'. The following options are supported:
## Year, month, and day tokens
| Input | Example | Description |
|------------|------------------|--------------------------------------------------------|
| `YYYY` | `2014` | 4 or 2 digit year |
| `YY` | `14` | 2 digit year |
| `Y` | `-25` | Year with any number of digits and sign |
| `Q` | `1..4` | Quarter of year. Sets month to first month in quarter. |
| `M MM` | `1..12` | Month number |
| `MMM MMMM` | `Jan..December` | Month name in locale |
| `D DD` | `1..31` | Day of month |
| `Do` | `1st..31st` | Day of month with ordinal |
| `DDD DDDD` | `1..365` | Day of year |
| `X` | `1410715640.579` | Unix timestamp |
| `x` | `1410715640579` | Unix ms timestamp |
## Week year, week, and weekday tokens
| Input | Example | Description |
|------------|----------------|---------------------------------------------|
| `gggg` | `2014` | Locale 4 digit week year |
| `gg` | `14` | Locale 2 digit week year |
| `w ww` | `1..53` | Locale week of year |
| `e` | `0..6` | Locale day of week |
| `ddd dddd` | `Mon...Sunday` | Day name in locale |
| `GGGG` | `2014` | ISO 4 digit week year |
| `GG` | `14` | ISO 2 digit week year |
| `W WW` | `1..53` | ISO week of year |
| `E` | `1..7` | ISO day of week |
## Hour, minute, second, millisecond, and offset tokens
| Input | Example | Description |
|------------|----------|--------------------------------------------------------------------------------|
| `H HH` | `0..23` | Hours (24 hour time) |
| `h hh` | `1..12` | Hours (12 hour time used with `a A`.) |
| `k kk` | `1..24` | Hours (24 hour time from 1 to 24) |
| `a A` | `am pm` | Post or ante meridiem (Note the one character `a p` are also considered valid) |
| `m mm` | `0..59` | Minutes |
| `s ss` | `0..59` | Seconds |
| `S SS SSS` | `0..999` | Fractional seconds |
| `Z ZZ` | `+12:00` | Offset from UTC as `+-HH:mm`, `+-HHmm`, or `Z` |<file_sep>import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import Modal from '../Modal';
import style from '../Modal.scss';
import slide from 'transitions/slide_left.scss';
/**
* This class provides a convenient way to display a "popup" component to interact with
*/
export default class SideModal extends Modal {
static propTypes = {
...SideModal.propTypes,
// A title to place in the modal
title: PropTypes.string,
};
renderWindow() {
const {children, className, role, title} = this.props;
const classes = classNames(style.modal, style.side, className);
return (
<ReactCSSTransitionGroup
transitionName={slide}
transitionEnter={true}
transitionLeave={true}
transitionEnterTimeout={1000}
transitionLeaveTimeout={1000}>
<div onClick={this.modalClick} key="modal" role={role} className={classes}>
<div onClick={this.handleClose} className={style.close}>
<span className={style.closeButton}>+</span>
</div>
<div className={style.content}>
<div className={style.contentHeader}>{(title) ? <h2 className={style.title}>{title}</h2> : ''}</div>
<div className={style.contentBody}>{children}</div>
</div>
</div>
</ReactCSSTransitionGroup>
);
}
}
<file_sep>**Note:** It is not recommended to use this component directly. Instead, it is much more common and recommended to use one of the field subclasses like InputField.
## Description
Field is the base class for all form fields. It provides a lot of shared functionality to all field subclasses (for example labels, simple validation, clearing and tab index management), but is rarely used directly. Instead, it is much more common and recommended to use one of the field subclasses like InputField.
If you wish to create your own Field subclasses you can extend this class, though it is sometimes more useful to extend one of the other base subclasses as they provides additional or better baseline functionality.
Field or one of its subclasses components are normally used within the context of a Form. See the Form component docs for examples on how to put those together.
See `<InputField />` for a application ready input field. It has the same API as Field but has has been setup as a user ready component.
## Usage
~~~js
import {Field} from 'react-ui-modules';
<Field
name="test-field"
type="email"
value={this.props.value}
error={this.props.error}
placeholder="This is an example placeholder"
label="Example Label"
onChange={(name, value, touched) => {
this.setState({value});
}}
data-test-id="example-test-id"
prepend="$"
append=".00"
/>
~~~
## Props
<dl>
<dt><a href="#name">name</a> : <code>String</code></dt>
<dd><p>The name used to represent this field. When used with the Form component the name will be used to sore the fields value, errors, touched and other attributes.</p>
</dd>
<dt><a href="#disabled">disabled</a> : <code>Bool</code></dt>
<dd><p>True to disable the field for input.</p>
</dd>
<dt><a href="#className">className</a> : <code>Object</code></dt>
<dd><p>An additional CSS class to apply to the main element of this component.</p>
</dd>
<dt><a href="#hint">hint</a> : <code>String</code></dt>
<dd><p>An optional hing to display below the field input</p>
</dd>
<dt><a href="#label">label</a> : <code>String</code></dt>
<dd><p>The label of this field</p>
</dd>
<dt><a href="#placeholder">placeholder</a> : <code>String</code></dt>
<dd><p>The short hint is displayed in the Field before the user enters a value. Describes the expected value of an input field.</p>
</dd>
<dt><a href="#type">type</a> : <code>String</code></dt>
<dd><p>The HTML <code><input></code> element type to display</p>
</dd>
<dt><a href="#prepend">prepend</a> : <code>String</code></dt>
<dd><p>Displayed before the field</p>
</dd>
<dt><a href="#append">append</a> : <code>String</code></dt>
<dd><p>Displayed after the field.</p>
</dd>
<dt><a href="#format">format</a> : <code>function</code></dt>
<dd><p>A function that takes the input value as a parameter, and returns a formatted string.</p>
</dd>
<dt><a href="#testId">testId</a> : <code>String</code></dt>
<dd><p>A unique id used to target this field during testing.</p>
</dd>
</dl>
## Functions
<dl>
<dt><a href="#getDisplayString">getDisplayString()</a> ⇒ <code>String</code></dt>
<dd><p>returns a formatted string to be used as the display value of the field. Extending classes may want to override this method to provided formatted results.</p>
<p>Note: this formatting will have no effect on the actual value of the field.</p>
</dd>
<dt><a href="#onBlur">onBlur()</a></dt>
<dd><p>Remove focus from this component</p>
<p>Note: this wont remove the dom level focus, only the internal component focus. Dom focus will need to
be managed outside this component.</p>
</dd>
<dt><a href="#onFocus">onFocus()</a></dt>
<dd><p>Set focus on this component.</p>
<p>Note: this wont set the dom level focus, only the internal component focus. Dom focus will need to
be managed outside this component.</p>
</dd>
<dt><a href="#renderLabel">renderLabel()</a> ⇒ <code>XML</code></dt>
<dd><p>Render the component label</p>
</dd>
<dt><a href="#renderInput">renderInput()</a> ⇒ <code>XML</code></dt>
<dd><p>Render the components input field. The part of the component that is used to set and display the
components value. Extending classes may wish to override this to create new Field functionality.</p>
</dd>
<dt><a href="#renderHint">renderHint()</a> ⇒ <code>XML</code></dt>
<dd><p>Render component hint message.</p>
</dd>
<dt><a href="#renderError">renderError()</a> ⇒ <code>XML</code></dt>
<dd><p>Render the components error message.</p>
</dd>
<dt><a href="#render">render()</a> ⇒ <code>XML</code></dt>
<dd><p>Render the component.</p>
<p>Note: it is encouraged that components extending this component avoid overriding the render method
if possible. Instead the extending component should focus on overriding the other render methods like
<code>renderInput()</code> and <code>renderLabel()</code>.</p>
<p>If you do end up overriding the render method, you will need to make sure you identify the root dom node by
setting <code>ref={this.setNode}</code> on the root dom node element.</p>
</dd>
</dl>
## Events
<dl>
<dt><a href="#event_onChange">"onChange" (value)</a></dt>
<dd><p>Fires when the Fields value changes.</p>
</dd>
</dl>
<file_sep>export {default as Modal} from './Modal';
export {default as WindowModal} from './window/WindowModal';
export {default as SideModal} from './side/SideModal';<file_sep>import React from 'react';
import {storiesOf} from '@storybook/react';
import {action} from '@storybook/addon-actions';
import {withNotes} from '@storybook/addon-notes';
const stories = storiesOf('Welcome', module);
stories.add('About', () => (
<div class="doc">
<h1>Welcome</h1>
<p>React UI Modules is designed to provide a common set of components that can used n almost any app, and can be extended on to build more new and different components.</p>
</div>
))
stories.add('Introduction', () => (
<h1>Introduction</h1>
))
stories.add('Core Concepts', () => (
<h1>Core Concepts</h1>
))<file_sep>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Week from './Week';
export default class Month extends Component {
static propTypes = {
date: PropTypes.object.isRequired,
today: PropTypes.object.isRequired,
onSelect: PropTypes.func.isRequired,
selected: PropTypes.object,
};
isWeekInMonth(startOfWeek) {
const {date} = this.props;
const endOfWeek = startOfWeek.clone().add(6, 'days');
return startOfWeek.isSame(date, 'month') || endOfWeek.isSame(date, 'month');
}
renderWeeks() {
const {onSelect, today, date, selected} = this.props;
const weeks = [];
let currentWeekStart = date.clone().startOf('month').startOf('week');
let i = 0;
let breakAfterNextPush = false;
while (true) {
weeks.push(<Week onSelect={onSelect} today={today} key={i} date={date} week={currentWeekStart} selected={selected}/>);
if (breakAfterNextPush) {
break;
}
i++;
currentWeekStart = currentWeekStart.clone()
.add(1, 'weeks');
// Check to see if the next week is still in the current month, if not exit.
const isWeekInMonth = !this.isWeekInMonth(currentWeekStart);
if (isWeekInMonth) {
if (this.props.peekNextMonth) {
breakAfterNextPush = true
} else {
break
}
}
}
return weeks
}
render() {
return <div>
{this.renderWeeks()}
</div>;
}
}
<file_sep>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import moment from 'moment';
import InputMask from 'inputmask-core'
import {Field} from 'elements/form/field';
import style from './TimeField.scss';
/**
* Field is the base class for all form fields. It provides a lot of shared functionality to all field subclasses
* (for example labels, simple validation, clearing and tab index management), but is rarely used directly.
* Instead, it is much more common to use one of the field subclasses.
*
* If you wish to create your own Field subclasses you can extend this class, though it is sometimes more useful
* to extend one of the other base subclasses as they provides additional base functionality.
*/
export default class TimeField extends Field {
static propTypes = {
...Field.propTypes,
/**
* A Moment.js format string use as the display date format.
*/
displayFormat: PropTypes.string,
/**
* A Moment.js format string use as the display date format.
*/
valueFormat: PropTypes.string,
/**
* Strict mode requires the input to exactly match the specified format, including separators.
*
* Suppose that an API starts by sending dates in 'YYYY-MM-DD' format, and then later changes to 'MM/DD/YYYY' format.
* Setting strict to false will try and fix this issue automatically. Note: setting strict may introduce some additional issues
* as the formatter makes assumptions about the input sting.
*/
strict: PropTypes.bool
};
constructor(props) {
super(props);
//this.onInputKeyPress = this.onInputKeyPress.bind(this);
// const today = this.localizeMoment(moment());
// const selected = (props.value) ? this.getMoment(props.value) : null;
// const date = (props.value) ? selected : today;
this.mask = new InputMask({pattern: '11:11 aa'});
// Object.assign(this.state, super.state, {
// today: today,
// selected: selected,
// date: date,
// inputValue: null
// });
}
componentWillMount() {
// let options = {
// pattern: this.props.mask,
// value: this.props.value,
// formatCharacters: this.props.formatCharacters
// }
// if (this.props.placeholderChar) {
// options.placeholderChar = this.props.placeholderChar
// }
this.mask = new InputMask({pattern: '11:11 aa'})
}
static defaultProps = {
...Field.defaultProps,
displayFormat: 'hh:mm A',
valueFormat: 'hh:mm A',
strict: true
};
getSelection (el) {
console.log('el', el);
let start, end
if (el.selectionStart !== undefined) {
start = el.selectionStart
end = el.selectionEnd
} else {
try {
el.focus()
let rangeEl = el.createTextRange()
let clone = rangeEl.duplicate()
rangeEl.moveToBookmark(document.selection.createRange().getBookmark())
clone.setEndPoint('EndToStart', rangeEl)
start = clone.text.length
end = start + rangeEl.text.length
}
catch (e) { /* not focused or not visible */ }
}
return { start, end }
}
generateTime() {
var times = [];
Array(24).join(',').split(',').forEach(function(_, index) {
var hour = index;
if (hour < 10) {
hour = '0' + hour;
}
times.push({
label: moment(hour + ':00', 'HH:mm').format('hh:mm a'),
value: moment(hour + ':00', 'HH:mm').format('hhmma')
});
times.push({
label: moment(hour + ':30', 'HH:mm').format('hh:mm a'),
value: moment(hour + ':30', 'HH:mm').format('hhmma')
});
});
return times;
}
/**
* returns a formatted string to be used as the display value of the field. Extending classes may want to override this method to provided formatted results.
*
* Note: this formatting will have no effect on the actual value of the field.
* @returns {String} A formatted string
*/
getDisplayString() {
const {value, displayFormat, valueFormat, strict} = this.props;
//return this.generateTime();
// const date = moment(value, valueFormat, strict);
// console.log('date.isValid()', date.isValid());
// if(date.isValid()){
// var formatted = date.format(displayFormat);
// return (formatted) ? formatted : '';
// }
// return value;
console.log('value', value);
if(!value){
return this.mask.emptyValue;
}
this.mask.paste(value)
let maskedValue = this.mask.getValue();
//this.setSelection(this.input, this.mask.selection)
console.log('maskedValue', maskedValue);
return maskedValue;
}
onKeyPress(e) {
// console.log('onKeyPress', JSON.stringify(getSelection(this.input)), e.key, e.target.value)
// Ignore modified key presses
// Ignore enter key to allow form submission
if (e.metaKey || e.altKey || e.ctrlKey || e.key === 'Enter') { return }
e.preventDefault()
//this.setSelection(this.input, this.mask.selection)
this.updateMaskSelection(e)
// if (this.mask.input((e.key || e.data))) {
// e.target.value = this.mask.getValue()
// this._updateInputSelection()
// if (this.props.onChange) {
// this.props.onChange(e)
// }
// }
}
updateMaskSelection(e) {
this.mask.selection = this.getSelection(e)
}
/**
* Transform the value into a display string as specified by the 'displayFormat';
*
* @param date the date to transform.
* @param toMoment should we try turn this into a moment object
*/
getTimeString(date, toMoment = false) {
const {displayFormat, valueFormat} = this.props;
if (toMoment) {
date = this.getMoment(date, valueFormat);
}
return date.format(displayFormat);
}
setSelection(el, selection) {
try {
if (el.selectionStart !== undefined) {
el.focus()
el.setSelectionRange(selection.start, selection.end)
}
else {
el.focus()
let rangeEl = el.createTextRange()
rangeEl.collapse(true)
rangeEl.moveStart('character', selection.start)
rangeEl.moveEnd('character', selection.end - selection.start)
rangeEl.select()
}
}
catch (e) { console.log('Error', e); }
}
/**
* Transform a date object back into a string as defined by the 'valueFormat'
*
* @param date
* @param toMoment should we try turn this into a moment object
*/
getTimeValue(date, toMoment = false) {
const {displayFormat, valueFormat} = this.props;
if (toMoment) {
date = this.getMoment(date, displayFormat);
}
return date.format(valueFormat);
}
renderInputValue() {
const {input, value, name, placeholder, testId} = this.props;
const {inputValue} = this.state;
let ref = r => { this.input = r }
const valueString = (value) ? this.getDateString(value, true) : '';
const inputString = (inputValue) ? inputValue : valueString;
return (
<input
{...input}
ref
data-test-id={"input-" + testId}
name={name}
onBlur={this.onInputBlur}
onFocus={this.handleOpen}
value={this.getDisplayString()}
onKeyDown={this.onKeyPress}
onKeyUp={this.onInputKeyPress}
onChange={this.onInputChange}
placeholder={placeholder}
type="text"
autoComplete="off"
className={dropdownStyle.input}/>
);
}
}
<file_sep>import React, {Component} from "react";
import classNames from 'classnames';
import {Icon, IconType} from 'elements/icon';
import {Tab, TabPanel} from 'elements/tab';
import style from './EmailBuilder.scss';
export default class EmailBuilder extends Component {
static defaultProps = {
active: 0,
speed: 5000
};
state = {
active: this.props.active
};
constructor(props) {
super(props);
}
render() {
return (
<div className={style.container}>
<div className={style.preview}>
...preview
</div>
<Tab className={style.preferences} align={Tab.align.top}>
<TabPanel label="Components">
Components
</TabPanel>
<TabPanel label="Components">
Components
</TabPanel>
<TabPanel label="Body">
Body
</TabPanel>
</Tab>
</div>
);
}
}
<file_sep>export {default as Phone} from './Phone';<file_sep>import React, {Component} from "react";
import PropTypes from 'prop-types';
import moment from 'moment';
export default class DateTime extends Component {
static propTypes = {
date: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
toFormat: PropTypes.string,
fromFormat: PropTypes.string,
};
static defaultProps = {
toFormat: 'MMMM Do YYYY, h:mm:ss a',
fromFormat: null,
};
render() {
const {date, toFormat, fromFormat, className} = this.props;
const momentDate = (date) ? moment(date, fromFormat) : moment();
const formattedDate = momentDate.format(toFormat);
const dateTime = momentDate.format();
return (
<time datetime={dateTime} className={className}>{formattedDate}</time>
);
}
}
<file_sep>import React, {Component} from 'react';
import {Field, FieldSet} from 'elements/form/field';
import style from './InputField.scss';
/**
* InputField is used to create interactive controls in order to accept data simple user data. Is the common type of input and represents the behavior you
* would expect from a standard HTML <input /> with the additional framework functionality like labels and error management build on top.
*
* Note: at this time InputField simply extends the base Field as it requires no additional functionality, however it has been given its
* oen class to resurvey the name space, and prevent changes to the base API in the future if the functionality was to diverge slightly.
*/
export default class InputField extends Field {
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {Icon} from 'elements/icon';
import style from './Title.scss';
const propTypes = {
label: PropTypes.string.isRequired,
className: PropTypes.string,
icon: PropTypes.shape(
{
viewBox: PropTypes.string.isRequired,
path: PropTypes.string.isRequired,
}
)
};
const Title = (props) => {
const {label, icon, className, id} = props;
const classes = classNames(style.title, className);
return (
<h2 {...props} className={classes}>
{(icon) ? <Icon type={icon}/> : ''} {label}
</h2>
);
};
Title.propTypes = propTypes;
export default Title;
<file_sep>import React from 'react';
import style from './Loading.scss';
/**
* Main app container to hold
*/
export const Loading = (color = null) => {
const fillStyle = {
fill: color
};
return (
<svg className={style.loading} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<path className={style.path} opacity=".25" d="M16 0 A16 16 0 0 0 16 32 A16 16 0 0 0 16 0 M16 4 A12 12 0 0 1 16 28 A12 12 0 0 1 16 4"/>
<path style={fillStyle} className={style.path} d="M16 0 A16 16 0 0 1 32 16 L28 16 A12 12 0 0 0 16 4z">
<animateTransform attributeName="transform" type="rotate" from="0 16 16" to="360 16 16" dur=".8s" repeatCount="indefinite" />
</path>
</svg>
);
};
export default Loading;
<file_sep>import React, {Component} from 'react';
import classNames from 'classnames';
import {Field} from 'elements/form/field';
import style from './TextField.scss';
/**
* Field is the base class for all form fields. It provides a lot of shared functionality to all field subclasses
* (for example labels, simple validation, clearing and tab index management), but is rarely used directly.
* Instead, it is much more common to use one of the field subclasses.
*
* If you wish to create your own Field subclasses you can extend this class, though it is sometimes more useful
* to extend one of the other base subclasses as they provides additional base functionality.
*/
export default class TextField extends Field {
renderInput() {
const {input, name, value, placeholder, inputClassName} = this.props;
const classes = classNames(style.input, inputClassName);
return (
<textarea
{...input}
value={ (value) ? value : '' }
name={name}
className={classes}
placeholder={placeholder}
onBlur={this.onBlur}
onFocus={this.onFocus}
onChange={(event) => {
const target = event.target;
const value = target.value;
this.onChange(value);
}}/>
);
}
}
<file_sep>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import style from './Calendar.scss';
export default class Day extends Component {
static propTypes = {
day: PropTypes.object.isRequired,
isToday: PropTypes.bool,
isThisMonth: PropTypes.bool,
};
static defaultProps = {
isToday: false,
isThisMonth: true,
};
constructor(props) {
super(props);
}
render() {
const {day, isToday, isThisMonth} = this.props;
const displayDay = day.format('D');
const key = displayDay;
const classes = classNames(style.weekDay, {
[style.weekDayOther]: !isThisMonth,
[style.weekDayToday]: isToday
});
return (
<div key={key} className={classes}>
{displayDay}
</div>
);
}
}
<file_sep>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import style from './Tooltip.scss';
const propTypes = {
className: PropTypes.string,
isOpen: PropTypes.bool,
disabled: PropTypes.bool,
children: PropTypes.oneOfType(
[
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
]
),
target: PropTypes.oneOfType(
[
PropTypes.string,
PropTypes.object
]
).isRequired,
testId: PropTypes.string,
position: PropTypes.string,
};
const defaultProps = {
isOpen: false,
position: 'RIGHT',
};
class Tooltip extends Component {
static position = {
left: 'LEFT',
right: 'RIGHT'
};
constructor(props) {
super(props);
this.onMouseOverTooltip = this.onMouseOverTooltip.bind(this);
this.onMouseLeaveTooltip = this.onMouseLeaveTooltip.bind(this);
this.show = this.show.bind(this);
this.hide = this.hide.bind(this);
this.getTarget = this.getTarget.bind(this);
this.addTargetEvents = this.addTargetEvents.bind(this);
this.removeTargetEvents = this.removeTargetEvents.bind(this);
this.calculatePosition = this.calculatePosition.bind(this);
this.setHeight = this.setHeight.bind(this);
this.state = {
isOpen: props.isOpen,
top: 0,
left: 0,
height: 0
};
}
componentDidMount() {
this.target = this.getTarget();
this.addTargetEvents();
}
componentWillUnmount() {
this.removeTargetEvents();
}
show() {
this.setState({isOpen: true});
}
hide() {
this.setState({isOpen: false});
this.clearHideTimeout();
}
getTarget() {
const {target} = this.props;
if (typeof target === 'object') {
return target;
}
return document.getElementById(target);
}
onMouseOverTooltip() {
const {isOpen} = this.state;
if (!isOpen) {
this.show();
this.hideTimeout = setTimeout(this.hide, 1500);
}
}
onMouseLeaveTooltip() {
const {isOpen} = this.state;
if (isOpen) {
this.hide();
}
}
calculatePosition(element) {
if (!element) {
return null;
}
const {position} = this.props;
const {height} = this.state;
const positioning = element.getBoundingClientRect();
console.log('positioning', positioning);
// Return when rendering to the left side
if(position === Tooltip.position.left){
return {
top: positioning.top + (positioning.height / 2) - (height / 2),
right: positioning.left
};
}
// Default: Returned when rendering to the right side of the element
return {
top: positioning.top + (positioning.height / 2) - (height / 2),
left: positioning.right
};
}
setHeight(element) {
if (!element) {
return;
}
const position = element.getBoundingClientRect();
this.setState(
{
height: position.height
}
);
}
addTargetEvents() {
this.target.addEventListener('mouseover', this.onMouseOverTooltip, true);
this.target.addEventListener('mouseout', this.onMouseLeaveTooltip, true);
}
removeTargetEvents() {
this.target.removeEventListener('mouseover', this.onMouseOverTooltip, true);
this.target.removeEventListener('mouseout', this.onMouseLeaveTooltip, true);
}
clearShowTimeout() {
clearTimeout(this._showTimeout);
this._showTimeout = undefined;
}
clearHideTimeout() {
clearTimeout(this.hideTimeout);
this.hideTimeout = undefined;
}
render() {
const {className, children, position, testId} = this.props;
const {isOpen} = this.state;
if (!isOpen) {
return null;
}
const positioning = this.calculatePosition(this.target);
const classes = classNames(style.tooltip, className, {
[style.tooltipOpen]: true,
[style.tooltipLeft]: (position === Tooltip.position.left)
});
return (
<div data-test-id={testId} ref={this.setHeight} style={positioning} className={classes}>
<div className={style.content}>
{children}
</div>
</div>
);
}
}
Tooltip.propTypes = propTypes;
Tooltip.defaultProps = defaultProps;
export default Tooltip;
<file_sep>export default class NumberFormat {
constructor(config = {}) {
this.config = Object.assign(
{
numeralPositiveOnly: false,
stripLeadingZeroes: true,
numeralDecimalMark: '.',
delimiter: ',',
numeralIntegerScale: 3,
numeralDecimalScale: 2
},
config);
}
formatString(value) {
const {config} = this;
if (!value) {
return '';
}
value = value.toString();
let partInteger = '';
let partDecimal = '';
let parts = null;
// strip alphabet letters
value = value.replace(/[A-Za-z]/g, '')
// replace the first decimal mark with reserved placeholder
.replace(config.numeralDecimalMark, 'M')
// strip non numeric letters except minus and "M"
// this is to ensure prefix has been stripped
.replace(/[^\dM-]/g, '')
// replace the leading minus with reserved placeholder
.replace(/^\-/, 'N')
// strip the other minus sign (if present)
.replace(/\-/g, '')
// replace the minus sign (if present)
.replace('N', config.numeralPositiveOnly ? '' : '-')
// replace decimal mark
.replace('M', config.numeralDecimalMark)
// strip any leading zeros
if (config.stripLeadingZeroes) {
value = value.replace(/^(-)?0+(?=\d)/, '$1');
}
if (value.indexOf(config.numeralDecimalMark) >= 0) {
parts = value.split(config.numeralDecimalMark);
partInteger = parts[0];
partDecimal = config.numeralDecimalMark + parts[1].slice(0, config.numeralDecimalScale);
} else {
partInteger = value;
}
if (config.numeralIntegerScale > 0) {
const exp = "(\\d)(?=(\\d{" + config.numeralIntegerScale + "})+$)";
partInteger = partInteger.replace(new RegExp(exp, 'g'), '$1' + config.delimiter);
}
return partInteger.toString() + (config.numeralDecimalScale > 0 ? partDecimal.toString() : '');
}
}<file_sep>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {Icon} from 'elements/icon'
import style from './SelectField.scss';
export default class Option extends Component {
static propTypes = {
value: PropTypes.oneOfType(
[
PropTypes.string,
PropTypes.number
]
),
label: PropTypes.oneOfType(
[
PropTypes.string,
PropTypes.number
]
).isRequired,
onClick: PropTypes.func.isRequired,
icon: PropTypes.shape(
{
viewBox: PropTypes.string.isRequired,
path: PropTypes.string.isRequired,
}
),
selected: PropTypes.bool,
disabled: PropTypes.bool
};
static defaultProps = {
selected: false,
disabled: false,
icon: null
};
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
const {disabled, onClick} = this.props;
if (!disabled) {
const {value} = this.props;
onClick(value, event);
}
}
render() {
const {value, label, icon, selected} = this.props;
const classes = classNames(style.option, {
[style.optionSelected]: selected
});
const iconClasses = classNames(style.icon, {
[style.iconSelected]: selected
});
return (
<div key={value} className={classes} id={value} onClick={this.handleClick} role="button" title={label}>
{(icon) ? <Icon className={iconClasses} type={icon}/> : ''}
{label}
</div>
);
}
}
<file_sep>// file: src/stories/index.js
import React from 'react';
import {storiesOf} from '@storybook/react';
import {action} from '@storybook/addon-actions';
import {withNotes} from '@storybook/addon-notes';
import {withKnobs, text, boolean, array} from '@storybook/addon-knobs';
import documentation from './documentation.md';
import Form from '../Form';
import SelectField from './SelectField';
const stories = storiesOf('Form', module);
// Add the `withKnobs` decorator to add knobs support to your stories. You can
// also configure `withKnobs` as a global decorator.
stories.addDecorator(withKnobs);
class StatefulForm extends Form {
render() {
return (<SelectField
options={array('options', [
{
value: 1,
label: 'QLD'
}, {
value: 2,
label: 'NSW'
}, {
value: 3,
label: 'NSWL'
}, {
value: 4,
label: 'SA'
}, {
value: 5,
label: 'WA'
}, {
value: 6,
label: 'International'
}
])}
name={text('name', 'test-field')}
type={text('type', 'email')}
value={this.state.value}
hint={text('hint', 'This is an example hint')}
error={text('error', '')}
placeholder={text('placeholder', 'This is an example placeholder')}
label={text('label', 'Example Label')}
onChange={(name, value, touched) => {
action('onChange');
this.setState({value});
}}
data-test-id={text('data-test-id', 'example-test-id')}
prepend={text('prepend', '$')}
append={text('append', '.00')}
loading={boolean('loading', false)}
disabled={boolean('disabled', false)}/>);
}
}
stories.add('SelectField', withNotes(documentation)(() => (<StatefulForm/>)))<file_sep># Overview
A common set of UI elements that can be reused in any React project.
NOTE: This module is still in early stages of DEVELOPMENT, Its API's are not stable yet, and are subject to change.
# Usage
To add the package to your project run `yarn add react-ui-modules` in the root of you project.
All components are published at the top level of the package, you can include them via the component name like `import {Button, Form, InputField} from 'react-ui-modules'`
The project exposes a number of high level components that can be used delectably as a component `<Button onClick={() =>{}}>`. It also provides a number of base components that can be extended to build mor complex components `CheckDropdown extends DropdownField {}`
For complete documentation of the available components see 'TODO: add link when complete'
# Development
This library aims to provide a reusable components to use in external projects, as such we have provided two options to use when developing:
## Storybook development (Recommended)
We make use of Storybook https://storybook.js.org/ to provide documentation, and allow for testing and development of components. You can start Storybook by running `yarn start:storybook`. This will build and watch a changes and publish them to Storybook. Once the script finishes, it will provide the url to open Storybook.
We are keeping stories inline with the component. Storybook will look for .story.js files in the `src` directory, and automatically build them into a story.
## Linking for development in an external project
First you need to create a symlink of the library locally (If you’d like to learn more about (`npm link`, `yarn link`), check out https://docs.npmjs.com/cli/link.) from the root of the library, run `npm link` or `yarn link` link. You’ll notice this will also run the prepublish script in the console, this will conduct the initial build of the module.
You can now run the `start:dev` command, this will keep an eye on any changes and update the build and symlink whenever anything changes. This allows us to develop in the local module, and see the results in our linked project.
Now we’ll tell our other app that we want to use that symlinked library. From the root of your included app run `yarn link react-ui-modules`.
You can now include the component you wish to work on in your other app `include {Button, Form} from 'react-ui-modules'`. Changes made to the module will be made available to the linked project via the symlink.
Note: You will need keep the `start:dev` job running in the console to continue watching for changes, and updating the linked package.
## GIT
This module makes use of the Gitflow workflow for managing its git versioning and bug fixes. Learn more at https://nvie.com/posts/a-successful-git-branching-model/ or https://danielkummer.github.io/git-flow-cheatsheet/
## Dev Plugins
This tool is build for React projects. This allows us to make use of some of the very useful react development tools.
I recommend installing:
* React Developer Tools - https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en
* Redux DevTools - https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd?hl=en
# Publish
To publish a new version of the module to NPM push all changes to the GIT repo master branch, then use the `yarn publish` command to push the changes. This will run the prepublish script to build the module before pushing up the changes. Make sure to increment the version making use of the NPM semantic versioning or users may not be able to update to the latest version. (Learn more about about NPM semantic versioning at https://docs.npmjs.com/getting-started/semantic-versioning)
To publish the documentation run `yarn publish:storyboard`. Storyboard will do its own build of the Ui packages, so you don't need to build the package before running running the documentation build.
<file_sep>import React, {Component} from "react";
import style from './ListGroup.scss';
export default class ListGroup extends Component {
render() {
const {title} = this.props;
return (
<div data-role="list-group" className={style.container}>
{ title }
</div>
);
}
}
<file_sep>export {default as Form} from './Form';
export {default as Field} from './field';
export {default as FieldSet} from './field';
export {default as InputField} from './input';
export {default as DateField} from './date';
export {default as TextField} from './text';
export {default as Toggle} from './toggle';
export {default as TagField} from './tag';<file_sep>export {default as ViewComponent} from './ViewComponent';
<file_sep>import { configure } from '@storybook/react';
import { setOptions } from '@storybook/addon-options';
import './style.scss';
// automatically import all files ending in *.stories.js
const req = require.context('../src/', true, /\.stories\.js$/)
function loadStories() {
require('./welcome');
req.keys().forEach(filename => req(filename));
}
setOptions({
showDownPanel: false,
name: 'react-ui-modules',
sidebarAnimations: true,
showAddonPanel: true,
showSearchBox: false,
addonPanelInRight: true,
});
configure(loadStories, module);
<file_sep>export {default as Icon} from './Icon';
export {default as IconType} from './IconType';<file_sep>export {default as TagField} from './TagField';
<file_sep>import {Component} from 'elements/base';
/**
* Abstract form class that provides base functionality for any form component.
*
* Form is the building block for components that contain form fields. All form components should interact from
* this class.
*/
export default class Form extends Component {
constructor(props) {
super(props);
this.getValue = this.getValue.bind(this);
this.setValue = this.setValue.bind(this);
this.setErrors = this.setErrors.bind(this);
this.clearErrors = this.clearErrors.bind(this);
this.onKeyPress = this.onKeyPress.bind(this);
this.onSubmit = this.onSubmit.bind(this);
// This is an abstract class and cannot be darcey creates
if (this.constructor === Form) {
throw new TypeError('Abstract class "Form" cannot be instantiated directly.');
}
this.state = {
data: {},
error: {},
touched: {},
hasErrors: false,
loading: false
};
}
/**
* Listen to key press events, and handle any core behaviours.
* @param {the key press event} event
*/
onKeyPress(event) {
if(event.key === 'Enter'){
this.onSubmit();
}
}
/**
* handle submitting of the form.
*
* It will automaticaly be called on enter, but will need to be manualy called on button clicks.
*/
onSubmit() {}
/**
* Set the data state for this form, this will also trigger a reset of the touched fields, and error states.
*
* Note: any attribute that is not set will be defaulted to null.
* @param data the data model.
* @param isLoading is this form still loading.
*/
setData(data, isLoading = false) {
this.setState(
{
data,
error: {},
touched: {},
hasErrors: false,
loading: isLoading
}
);
}
/**
* Bulk set the data object on load or update.
*
* Note: This will murge into the ixusting data object, and only overide values provided. You will need to clear
* the data value before setting if you wish to reset it.
*
* @param {Data to set} newData
*/
setBulk(newData) {
let {data} = this.state;
Object.assign(data, newData);
this.setState({data});
}
/**
* Set or update the value of a form field.
*
* @param name the name of the field to set/update
* @param value the value to set
* @param touch should we update the touched status of this object
*/
setValue(name, value, touch = true) {
const {data, error, touched} = this.state;
const newData = {};
newData[name] = value;
const newTouched = {};
newTouched[name] = true;
const newError = {};
newError[name] = false;
this.setState(
{
data: Object.assign(data, newData),
touched: (touch) ? Object.assign(touched, newTouched) : touched,
error: (touch) ? Object.assign(error, newError) : error,
}
);
this.onChange(data, newData);
}
/**
* Return the value of a form field
*
* @param name
* @returns {*}
*/
getValue(name) {
const {data} = this.state;
return data[name];
}
/**
* Override all error messages, and replace with new error message objects
*
* @param error the error message object to set.
*/
setErrors(error) {
const hasErrors = (error && Object.keys(error).length > 0 );
this.setState(
{
error,
hasErrors
}
);
}
/**
* Reset the error message state for this component.
*/
clearErrors() {
this.setState(
{
error: {},
hasErrors: false,
}
);
}
/**
* Fired when the form data is update.
*
* @param oldData the old state of the data before it changes
* @param newDate newData the new state of the data after it changes
*/
onChange(oldData, newDate) {
} // eslint-disable-line no-unused-vars
}
<file_sep>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import css from './Grid.scss';
export default class Row extends Component {
static propTypes = {
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
]),
style: PropTypes.object
};
render() {
let {children, style} = this.props;
return (
<div style={style} className={css.row}>{children}</div>
);
}
}
<file_sep>import React from 'react';
import classNames from 'classnames';
import style from './Breadcrumb.scss';
const BreadcrumbItem = ({path, children, className}) => {
const classes = classNames(style.item, className);
return (
<li className={classes}>
<Link to={path} className={style.link}>
{children}
</Link>
</li>
);
};
export default BreadcrumbItem;
<file_sep>import React from 'react';
import classNames from 'classnames';
import {Field, FieldSet} from 'elements/form/field';
import style from './ToggleField.scss';
/**
* Specialized SelectorField which only supports two values true or false.
*
* Note: A empty or null value will display as false.
*/
export default class ToggleField extends Field {
/**
* The toggle options presented to the user.
* Note: default to ON_OFF
*
* @type {{ON_OFF: string, TRUE_FALSE: string, YES_NO: string, GREEN_RED: string}}
*/
static TYPE = {
ON_OFF: 'on_off',
TRUE_FALSE: 'true_false',
YES_NO: 'yes_no',
GREEN_RED: 'green_red',
}
renderInput() {
const {input, name, value, type, disabled, testId} = this.props;
const classes = classNames(style.toggle, {
[style.toggleDisabled]: disabled,
[style.toggleChecked]: value
});
const sliderClasses = classNames(style.slider, {
[style.sliderChecked]: value,
[style.trueFalse]: (type == ToggleField.TYPE.TRUE_FALSE),
[style.yesNo]: (type == ToggleField.TYPE.YES_NO),
[style.greenRed]: (type == ToggleField.TYPE.GREEN_RED)
});
return (
<label className={classes}>
<input {...input}
checked={!!(value)}
data-test-id={'input-' + testId}
name={name}
type="checkbox"
onChange={(event) => {
const target = event.target;
const value = target.checked;
this.onChange(value);
}}/>
<span className={sliderClasses}/>
</label>
);
}
}<file_sep>export {default as DateTime} from './DateTime';<file_sep>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import Day from './Day';
import style from './DateField.scss';
export default class Week extends Component {
static propTypes = {
today: PropTypes.object.isRequired,
date: PropTypes.object.isRequired,
week: PropTypes.object.isRequired,
selected: PropTypes.object,
onSelect: PropTypes.func.isRequired
};
renderDays() {
const {onSelect, today, date, week, selected} = this.props;
const startOfWeek = week.clone();
const days = [];
return days.concat([0, 1, 2, 3, 4, 5, 6].map((offset) => {
const day = startOfWeek.clone().add(offset, 'days');
const isSelected = (selected && day.isSame(selected, 'day'));
const isToday = (day.isSame(today, 'day'));
const isThisMonth = (day.isSame(date, 'month'));
const key = "weekday-" + offset;
return <Day key={key} onSelect={onSelect} day={day} isToday={isToday} isThisMonth={isThisMonth} isSelected={isSelected} />
}))
}
render() {
return <div className={style.week}>
{this.renderDays()}
</div>;
}
}
<file_sep>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import Week from './Week';
export default class Month extends Component {
static propTypes = {
date: PropTypes.object.isRequired,
today: PropTypes.object.isRequired,
onEventClick: PropTypes.func,
events: PropTypes.arrayOf(
PropTypes.shape(
{
start: PropTypes.string.isRequired,
stop: PropTypes.string.isRequired,
label: PropTypes.string.isRequired
}
)
),
};
isWeekInMonth(startOfWeek) {
const {date} = this.props;
const endOfWeek = startOfWeek.clone()
.add(6, 'days');
return startOfWeek.isSame(date, 'month') || endOfWeek.isSame(date, 'month');
}
processEvents(){
// const {dateFormat, events} = this.props;
//
// if (!events) {
// return;
// }
//
// let eventsObject = events.map((event) => {
// let startDate = moment(event.start, dateFormat);
// let stopDate = moment(event.stop, dateFormat);
//
// const length = stopDate.diff(startDate, 'day') + 1;
//
// console.log(event.start, event.stop, length);
//
// return {
// ...event,
// startDate,
// stopDate,
// length
// }
// });
//
// let sortEvents = eventsObject.sort((a, b) => {
// // a must be equal to b
// return b.startDate.isAfter(a.startDate);
// });
}
renderWeeks() {
const {today, date, events, dateFormat, onEventClick} = this.props;
const weeks = [];
let currentWeekStart = date.clone()
.startOf('month')
.startOf('week');
let i = 0;
let breakAfterNextPush = false;
while (true) {
weeks.push(<Week today={today} key={i} date={date} week={currentWeekStart} dateFormat={dateFormat} events={events} onEventClick={onEventClick}/>);
if (breakAfterNextPush) {
break;
}
i++;
currentWeekStart = currentWeekStart.clone()
.add(1, 'weeks');
// Check to see if the next week is still in the current month, if not exit.
const isWeekInMonth = !this.isWeekInMonth(currentWeekStart);
if (isWeekInMonth) {
if (this.props.peekNextMonth) {
breakAfterNextPush = true
} else {
break
}
}
}
return weeks
}
//inRange
// processEvents() {
// const {dateFormat, date, events} = this.props;
// const startOfMonth = date.clone().startOf('month');
// const endOfMonth = date.clone().endOf('month');
// const weeksInMonth = endOfMonth.diff(startOfMonth, 'week');
//
// console.log('events', date.format('YYYY-MM-DD'), startOfMonth.format('YYYY-MM-DD'), endOfMonth.format('YYYY-MM-DD'), weeksInMonth);
//
// if (!events) {
// return
// }
//
// let monthEvents = events.filter((event) => {
// let start = moment(event.start, dateFormat);
// let stop = moment(event.stop, dateFormat);
//
// const inMonth = (start.isSame(date, 'month') || stop.isSame(date, 'month'));
//
// if (inMonth) {
// return event;
// }
// });
//
// console.log('events', weeksInMonth, monthEvents);
//
// //1) find all events that sered over multiple weeks
// //2) itterate over all rows and see if outher events will fit in the gape
// //3) max four rows of events.
//
// }
render() {
return <div>
{this.renderWeeks()}
</div>;
}
}
<file_sep>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import style from './Calendar.scss';
export default class Event extends Component {
static propTypes = {
event: PropTypes.arrayOf(
PropTypes.shape(
{
start: PropTypes.string.isRequired,
stop: PropTypes.string.isRequired,
label: PropTypes.string.isRequired
}
)
),
onClick: PropTypes.func,
days: PropTypes.number,
offset: PropTypes.number,
isStart: PropTypes.bool,
isEnd: PropTypes.bool,
};
static defaultProps = {
days: 1,
offset: 0,
isStart: true,
isEnd: true,
};
constructor(props) {
super(props);
this.unitSize = (100 / 7);
this.onClick = this.onClick.bind(this);
}
onClick(e){
const {onClick, event} = this.props;
if(onClick){
onClick(e, event);
}
}
render(){
let {event, days, offset, isStart, isEnd} = this.props;
// Represent the event days with a width
let width = (this.unitSize * days) - 0.2 + "%";
// represent the offset from the last event by left margin
let marginLeft = (this.unitSize * offset) + "%";
const inlineStyle = {
marginLeft,
marginRight: '0.2%',
width,
backgroundColor: event.color
};
const classes = classNames(style.event, {
[style.eventStart]: isStart,
[style.eventEnd]: isEnd
});
return (
<div onClick={this.onClick} style={inlineStyle} className={classes}>
<div className={style.eventLabel}>{(event.label) ? event.label : '\u00A0'}</div>
</div>
);
}
}<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {Component} from 'elements/base';
import {Icon} from 'elements/icon';
import style from './Tab.scss';
/**
* This component provides a push button with many presentation options.
* There are various styles of Button you can create
*/
export default class Tab extends Component {
static align = {
top: 'top',
bottom: 'bottom'
};
static propTypes = {
loading: PropTypes.bool,
align: PropTypes.string,
children: PropTypes.oneOfType(
[
PropTypes.array,
PropTypes.element
]
).isRequired
};
static defaultProps = {
active: 0,
align: Tab.align.top,
loading: false,
className: null,
labelClassName: null
};
state = {
active: this.props.active
};
renderLabels() {
let {children, labelClassName} = this.props;
let {active} = this.state;
if (!children) {
throw new Error('Tabs must contain at least one Tabs.Panel');
}
if (!Array.isArray(children)) {
children = [children];
}
return children.map((child, index) => {
let classes = classNames(style.label, {
[style.labelActive]: (active === index)
},labelClassName);
let icon = child.props.icon;
return (
<li key={index} className={classes} onClick={this.handleClick.bind(this, index)}>
<a className={style.labelLink} href="/">
{(icon)? <Icon className={style.icon} type={icon} /> : null}
{child.props.label}
</a>
</li>
);
});
}
renderTabs() {
let {className, children} = this.props;
let {active} = this.state;
const classes = classNames(style.panel, className);
return (
<div className={classes} key={this.state.active}>
{children[active]}
</div>
);
}
handleClick(index, event) {
event.preventDefault();
this.setState({active: index});
}
render() {
let {children, align, className} = this.props;
const classes = classNames(style.container,
{
[style.containerTop]: (align == Tab.align.top),
},className);
return (
<div className={classes}>
{this.renderTabs()}
<ul className={style.labels}>
{this.renderLabels()}
</ul>
</div>
);
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {Tooltip} from 'elements/tooltip';
import style from './Dropdown.scss';
/**
* This component provides a push button with many presentation options.
* There are various styles of Button you can create
*/
export default class Dropdown extends Tooltip {
static propTypes = {
className: PropTypes.string,
isOpen: PropTypes.bool,
disabled: PropTypes.bool,
children: PropTypes.oneOfType(
[
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
]
),
target: PropTypes.oneOfType(
[
PropTypes.string,
PropTypes.object
]
).isRequired,
};
static defaultProps = {
isOpen: false
};
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.handleDocumentClick = this.handleDocumentClick.bind(this);
}
handleClick(event) {
const {isOpen} = this.state;
event.stopPropagation();
event.preventDefault();
this.setState({isOpen: !isOpen});
}
handleDocumentClick(){
const {isOpen} = this.state;
if(isOpen){
this.hideTimeout = setTimeout(this.hide, 100);
}
}
addTargetEvents() {
this.target.addEventListener('click', this.handleClick, true);
document.addEventListener('click', this.handleDocumentClick, true);
}
removeTargetEvents() {
this.target.removeEventListener('click', this.handleClick, true);
document.addEventListener('click', this.handleDocumentClick, true);
}
show() {
this.clearHideTimeout();
this.setState({isOpen: true});
}
hide() {
this.clearHideTimeout();
this.setState({isOpen: false});
}
getTarget() {
const {target} = this.props;
if (typeof target === 'object') {
return target;
}
return document.getElementById(target);
}
calculatePosition(element) {
if (!element) {
return null;
}
const position = element.getBoundingClientRect();
return {
top: position.bottom + 5,
left: position.right
};
}
render() {
const {className, children, textId} = this.props;
const {isOpen} = this.state;
if (!isOpen) {
return null;
}
const position = this.calculatePosition(this.target);
const classes = classNames(style.container, className, {
[style.containerOpen]: true
});
return (
<div data-test-id={textId} ref={this.setHeight} style={position} className={classes}>
<div className={style.content}>
{children}
</div>
</div>
);
}
}
<file_sep>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import style from './DateField.scss';
export default class Day extends Component {
static propTypes = {
day: PropTypes.object.isRequired,
onSelect: PropTypes.func.isRequired,
isToday: PropTypes.bool,
isThisMonth: PropTypes.bool,
isSelected: PropTypes.bool,
isDisabled: PropTypes.bool,
};
static defaultProps = {
isToday: false,
isThisMonth: true,
isSelected: false,
isDisabled: false
};
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
const {isDisabled, onSelect} = this.props;
if (!isDisabled) {
const {day} = this.props;
onSelect(day, event);
}
}
render() {
const {day, isToday, isThisMonth, isSelected} = this.props;
const displayDay = day.format('D');
const key = displayDay;
const classes = classNames(style.weekDay,{
[style.weekDayOther]: !isThisMonth
});
const activeClass = classNames(style.weekDayStatus, {
[style.weekDayStatusToday]: isToday,
[style.weekDayStatusSelected]: isSelected
});
return (
<div onClick={this.handleClick} key={key} className={classes}>
<div className={activeClass}>
{displayDay}
</div>
</div>
);
}
}
<file_sep>export {default as ListView} from './view/ListView';
export {default as ListItem} from './item/ListItem';
export {default as ListGroup} from './group/ListGroup';
<file_sep>import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Link} from 'react-router';
import './ListItem.scss';
export default class ListItem extends Component {
static propTypes = {
member : PropTypes.object.isRequired,
query: PropTypes.string
};
static defaultProps = {
query: ''
};
render() {
const {member, children, to} = this.props;
return (
<Link to={to} className="list-item"
activeclassNameName="list-item--active">
{children}
</Link>
);
}
}
<file_sep>import React from 'react';
import {Component} from 'elements/base';
export default class ViewComponent extends Component {
}
<file_sep>export {default as SelectField} from './SelectField';
export {default as Options} from './Option';<file_sep><h2>Description</h2>
An abstract class for fields that have a single trigger which opens a "picker" below the field. It provides a base implementation for toggling the picker's visibility when the trigger is tapped.
You would not normally use this class directly, but instead use it as the parent class for a specific picker field implementation. If you are looking for a dropdown select field see `<SelectField>`. It is a implementation of DropdownPicker designd to select a single value.
<h2>Usage</h2>
~~~js
import {DropdownField} from 'react-ui-modules';
class MyDropdownField extends DropdownField {
renderTrigger() {
const {open, testId} = this.state;
return <div data-test-id={'trigger-' + testId} className={style.trigger} onClick={this.handleToggle}>
<Icon type={(open)? IconType.angleUp : IconType.angleDown}/>
</div>;
}
renderPanel() {
return (
<div>Add your own content</div>
);
}
}
~~~
## Props
## Functions
## Events
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import style from './FieldSet.scss';
const propTypes = {
className: PropTypes.string,
children: PropTypes.node.isRequired,
};
const FieldSet = ({className, children,}) => {
const classes = classNames(style.fieldset, className);
return (
<fieldset className={classes}>
{children}
</fieldset>
);
};
FieldSet.propTypes = propTypes;
export default FieldSet;
<file_sep>export {default as Tab} from './Tab';
export {default as TabPanel} from './TabPanel';<file_sep>// file: src/stories/index.js
import React from 'react';
import {storiesOf} from '@storybook/react';
import {action} from '@storybook/addon-actions';
import {withNotes} from '@storybook/addon-notes';
import {withKnobs, text, boolean, select} from '@storybook/addon-knobs';
import documentation from './documentation.md';
import DropdownField from './DropdownField';
const stories = storiesOf('Form', module);
// Add the `withKnobs` decorator to add knobs support to your stories. You can
// also configure `withKnobs` as a global decorator.
stories.addDecorator(withKnobs);
class MyDropdown extends DropdownField {
renderPanel() {
return (
<div>Add your own content</div>
);
}
}
stories.add('DropdownField', withNotes(documentation)(() => (
<MyDropdown />
)))<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import classNames from 'classnames';
import {Icon, IconType} from 'elements/icon';
import {DropdownField} from 'elements/form/dropdown';
import Month from './Month';
import dropdownStyle from '../dropdown/DropdownField.scss';
import style from './DateField.scss';
const ENTER = 'Enter';
/**
* A date picker component which shows a Date Picker dropdown, or allows manual eatery of the date.
*
* The value will be transformed to the displayFormat when rendered in the ui, but the actual value used by the
* component will remain in the valueFormat. Use the 'displayFormat' & 'valueFormat' props to adjust the format.
*
* Note: If an value is provided in a format that doesn't match the 'valueFormat', the component will attempt to
* transform the date using recognized RFC2822 or ISO formats.
*/
export default class DateField extends DropdownField {
static propTypes = {
...DropdownField.propTypes,
/**
* A Moment.js format string use as the display date format.
*/
displayFormat: PropTypes.string,
/**
* A Moment.js format string use as the display date format.
*/
valueFormat: PropTypes.string
};
static defaultProps = {
...DropdownField.defaultProps,
displayFormat: 'YYYY-MM-DD',
valueFormat: 'YYYY-MM-DD',
};
constructor(props) {
super(props);
this.onSelect = this.onSelect.bind(this);
this.increaseMonth = this.increaseMonth.bind(this);
this.decreaseMonth = this.decreaseMonth.bind(this);
this.onInputChange = this.onInputChange.bind(this);
this.onInputBlur = this.onInputBlur.bind(this);
this.onInputKeyPress = this.onInputKeyPress.bind(this);
const today = this.localizeMoment(moment());
const selected = (props.value) ? this.getMoment(props.value) : null;
const date = (props.value) ? selected : today;
Object.assign(this.state, super.state, {
today: today,
selected: selected,
date: date,
inputValue: null
});
}
componentWillReceiveProps(nextProps) {
this.setState(
{
selected: (nextProps.value) ? this.getMoment(nextProps.value) : null,
}
);
}
/**
*
* @param date
* @returns {Duration|string|Moment}
*/
localizeMoment(date) {
return date.clone()
.locale(this.props.locale || moment.locale());
}
/**
* Transform the value into a display string as specified by the 'displayFormat';
*
* @param date the date to transform.
* @param toMoment should we try turn this into a moment object
*/
getDateString(date, toMoment = false) {
const {displayFormat, valueFormat} = this.props;
if (toMoment) {
date = this.getMoment(date, valueFormat);
}
return date.format(displayFormat);
}
/**
* Transform a date object back into a string in defined by the 'valueFormat'
* @param date
* @param toMoment should we try turn this into a moment object
*/
getDateValue(date, toMoment = false) {
const {displayFormat, valueFormat} = this.props;
if (toMoment) {
date = this.getMoment(date, displayFormat);
}
return date.format(valueFormat);
}
getMoment(date) {
const {valueFormat} = this.props;
return moment(date, valueFormat);
}
/**
* increment the current display month by one
*/
increaseMonth() {
const {date} = this.state;
this.setState(
{
date: date.clone()
.add(1, 'month')
}
);
}
/**
* decrement the current display month by one.
*/
decreaseMonth() {
const {date} = this.state;
this.setState(
{
date: date.clone()
.subtract(1, 'month')
}
);
}
onSelect(day, event) {
const {onChange, name} = this.props;
event.preventDefault();
const value = this.getDateValue(day);
onChange(name, value, true);
this.handleClose();
}
onInputBlur(event) {
const {displayFormat} = this.props;
const target = event.target;
const value = target.value;
const day = this.getMoment(value, displayFormat, 'en', true);
if (day.isValid()) {
this.onSelect(day, event);
this.setState(
{
selected: day,
inputValue: null,
date: day
}
);
}// Todo: set any error message.
this.handleClose();
}
onInputChange(event) {
const {displayFormat} = this.props;
const target = event.target;
const value = target.value;
const today = this.localizeMoment(moment());
const day = this.getMoment(value);
this.setState(
{
selected: (day.isValid())? day : null,
inputValue: value,
date: (day.isValid())? day : today
}
);
}
onInputKeyPress(event) {
const value = event.target.value;
const key = event.key;
switch (key) {
case ENTER:
this.onInputBlur(event);
break;
default:
}
}
renderInputValue() {
const {input, value, typeahead, name, placeholder, testId} = this.props;
const {inputValue} = this.state;
const valueString = (value) ? this.getDateString(value, true) : '';
const inputString = (inputValue) ? inputValue : valueString;
if (typeahead) {
return (
<input
{...input}
data-test-id={"input-" + testId}
name={name}
onBlur={this.onInputBlur}
onFocus={this.handleOpen}
value={inputString}
onKeyUp={this.onInputKeyPress}
onChange={this.onInputChange}
placeholder={placeholder}
type="text"
autoComplete="off"
className={dropdownStyle.input}/>
);
}
// Should we use a placeholder text or just a space
const placeholderText = (placeholder)? <span className={style.placeholder}>{placeholder}</span> : '\u00A0';
return (
<div data-test-id={"input-" + testId} className={dropdownStyle.input} tabIndex="1" onClick={this.handleToggle}>
{ (value) ? this.getDateString(value, true) : placeholderText }
</div>
);
}
renderTrigger() {
const {testId} = this.props;
const classes = classNames(style.trigger, dropdownStyle.trigger);
return <div data-test-id={"trigger-" + testId} className={classes} onClick={this.handleToggle}>
<Icon type={IconType.calendar} />
</div>;
}
renderMonths() {
const {date} = this.state;
const monthDate = date.clone();
return this.renderCurrentMonth(monthDate);
}
renderCurrentMonth(date = this.state.date) {
const {today, selected} = this.state;
return (<Month onSelect={this.onSelect} date={date} today={today} selected={selected}/>)
}
renderPanel() {
const {date} = this.state;
const year = date.format('YYYY');
const month = date.format('MMMM');
return <div className={style.panel}>
<div className={style.header}>
<div className={style.navigation}>
<Icon onClick={this.decreaseMonth} className={style.navigationBack} type={IconType.angleLeft} />
<Icon onClick={this.increaseMonth} className={style.navigationForward} type={IconType.angleRight} />
</div>
<div className={style.year}>{year}</div>
<div className={style.month}>{month}</div>
</div>
<div className={style.calendar}>
<ul className={style.weekdays}>
<li className={style.weekdaysDay}>Sun</li>
<li className={style.weekdaysDay}>Mon</li>
<li className={style.weekdaysDay}>Tue</li>
<li className={style.weekdaysDay}>Wed</li>
<li className={style.weekdaysDay}>Thu</li>
<li className={style.weekdaysDay}>Fri</li>
<li className={style.weekdaysDay}>Sat</li>
</ul>
<div className={style.calendarDays}>
{this.renderMonths()}
</div>
</div>
</div>
}
}
<file_sep><h2>Description</h2>
Formatters are a function that takes in the value of a field string, and returns a formatted version for display. The framework provides a number of formatters out of the box, however you are free to add your own by providing in a function callback.
<h2>Usage</h2>
~~~js
import {InputField, NumberFormat} from 'react-ui-modules';
<InputField
name="test-field"
format={new NumberFormat()}
value={this.props.value}
error={this.props.error}
placeholder="This is an example placeholder"
label="Example Label"
onChange={(name, value, touched) => {
this.setState({value});
}}
data-test-id="example-test-id"
prepend="$"
append=".00"
/>
~~~
## Props
## Functions
## Events
<file_sep><h2>Description</h2>
Allow the input of multiple tags.
<h2>Usage</h2>
~~~js
import {TagField} from 'react-ui-modules';
<TagField
name="test-field"
type="email"
value={this.props.value}
error={this.props.error}
placeholder="This is an example placeholder"
label="Example Label"
onChange={(name, value, touched) => {
this.setState({value});
}}
data-test-id="example-test-id"
/>
~~~
## Props
## Functions
## Events
<file_sep>import React from 'react';
import {storiesOf} from '@storybook/react';
import {action} from '@storybook/addon-actions';
import {withNotes} from '@storybook/addon-notes';
import {withKnobs, text, boolean, object} from '@storybook/addon-knobs';
import documentation from './documentation.md';
import DateTime from './DateTime';
const stories = storiesOf('Date', module);
stories.addDecorator(withKnobs);
stories.add('Date', withNotes(documentation)(() => (
<DateTime date={text('date', '2013-01-02')} fromFormat={text('fromFormat', 'YYYY-MM-DD')} toFormat={text('toFormat', 'Do MMMM YYYY')} />
)))<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {Component} from 'elements/base';
import {FieldSet} from 'elements/form/field';
import Format from 'elements/form/format/Format';
import style from './Field.scss';
/**
* Field is the base class for all form fields. It provides a lot of shared functionality to all field subclasses
* (for example labels, simple validation, clearing and tab index management), but is rarely used directly.
* Instead, it is much more common to use one of the field subclasses.
*
* If you wish to create your own Field subclasses you can extend this class, though it is sometimes more useful
* to extend one of the other base subclasses as they provides additional base functionality.
*/
export default class Field extends Component {
/**
* Enum for tri-state values.
* @readonly
* @enum {number}
*/
static propTypes = {
/**
* The name used to represent this field. When used with the Form component the name will be used to sore the fields value, errors, touched and other attributes.
* @member {String}
*/
name: PropTypes.string.isRequired,
/**
* True to disable the field for input.
* @member {Bool}
*/
disabled: PropTypes.bool,
/**
* An additional CSS class to apply to the main element of this component.
* @member {Object}
*/
className: PropTypes.string,
/**
* An optional hing to display below the field input
* @member {String}
*/
hint: PropTypes.string,
/**
* The label of this field
* @member {String}
*/
label: PropTypes.string,
/**
* The short hint is displayed in the Field before the user enters a value. Describes the expected value of an input field.
* @member {String}
*/
placeholder: PropTypes.string,
/**
* The HTML `<input>` element type to display
* @member {String}
*/
type: PropTypes.string,
/**
* Displayed before the field
* @member {String}
*/
prepend: PropTypes.string,
/**
* Displayed after the field.
* @member {String}
*/
append: PropTypes.string,
/**
* A function that takes the input value as a parameter, and returns a formatted string.
* @member {Function}
*/
format: PropTypes.object,
/**
* A unique id used to target this field during testing.
* @member {String}
*/
testId: PropTypes.string
};
static defaultProps = {
...Component.defaultProps,
label: null,
disabled: false,
placeholder: '',
type: 'text',
prepend: null,
append: null,
format: null
};
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.onBlur = this.onBlur.bind(this);
this.onFocus = this.onFocus.bind(this);
this.setNode = this.setNode.bind(this);
this.state = {
focus: false
};
}
/**
* Fires when the Fields value changes.
* @event
* @param value the new Field value
*/
onChange(value) {
const {name, onChange, disabled} = this.props;
if (!disabled) {
onChange(name, value);
}
}
/**
* returns a formatted string to be used as the display value of the field. Extending classes may want to override this method to provided formatted results.
*
* Note: this formatting will have no effect on the actual value of the field.
* @returns {String} A formatted string
*/
getDisplayString() {
const {value, format} = this.props;
if (!format || typeof format.formatString !== "function") {
return (value) ? value : '';
}
const formatValue = format.formatString(value);
return (formatValue) ? formatValue : '';
}
/**
* Remove focus from this component
*
* Note: this wont remove the dom level focus, only the internal component focus. Dom focus will need to
* be managed outside this component.
*
*/
onBlur() {
this.setState(
{
focus: false
}
)
}
/**
* Set focus on this component.
*
* Note: this wont set the dom level focus, only the internal component focus. Dom focus will need to
* be managed outside this component.
*/
onFocus() {
this.setState(
{
focus: true
}
)
}
/**
* Render the component label
* @returns {JSX}
*/
renderLabel() {
const {label, name, error, testId} = this.props;
const {focus} = this.state;
if (!label) {
return;
}
const classes = classNames(style.label, {
[style.labelFocus]: focus,
[style.labelError]: error
});
return <label data-test-id={"label-" + testId} className={classes} htmlFor={name}>{label}</label>;
}
/**
* Render the components input field. The part of the component that is used to set and display the
* components value. Extending classes may wish to override this to create new Field functionality.
*
* @returns {JSX}
*/
renderInput() {
const {error, input, name, value, placeholder, type, disabled, autoFocus, inputClassName, testId, append, prepend, format} = this.props;
const {focus} = this.state;
const classes = classNames(style.input, inputClassName, {
[style.inputFocus]: focus,
[style.inputDisabled]: disabled,
});
return (
<div className={classes}>
{(prepend) ? <div className={style.inputPrepend}>{prepend}</div> : ''}
<input
data-test-id={"input-" + testId}
name={name}
className={style.inputField}
autoFocus={autoFocus}
value={this.getDisplayString()}
placeholder={placeholder}
type={type}
onBlur={this.onBlur}
onFocus={this.onFocus}
disabled={disabled}
onChange={(event) => {
const target = event.target;
const value = target.value;
this.onChange(value);
}}
/>
{(append) ? <div className={style.inputAppend}>{append}</div> : ''}
</div>
);
}
/**
* Render component hint message.
* @returns {JSX}
*/
renderHint() {
const {hint, testId} = this.props;
return (hint) ? <small data-test-id={"hint-" + testId} className={style.hint}>{hint}</small> : '';
}
/**
* Render the components error message.
* @returns {JSX}
*/
renderError() {
const {error, testId} = this.props;
return <span data-test-id={"error-" + testId} className={style.error}>{error}</span>;
}
/**
* Render the component.
*
* Note: it is encouraged that components extending this component avoid overriding the render method
* if possible. Instead the extending component should focus on overriding the other render methods like
* `renderInput()` and `renderLabel()`.
*
* If you do end up overriding the render method, you will need to make sure you identify the root dom node by
* setting `ref={this.setNode}` on the root dom node element.
*
* @returns {JSX}
*/
render() {
const {error, className, testId} = this.props;
const classes = classNames(style.wrapper, className);
return (
<div className={classes} ref={this.setNode} data-test-id={testId}>
{this.renderLabel()}
{this.renderInput()}
{(error && this.renderError())}
{(!error && this.renderHint())}
</div>
);
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {Component} from 'elements/base';
import {Icon, IconType} from 'elements/icon';
import accepts from 'attr-accept';
import style from './Dropzone.scss';
/**
* Field is the base class for all form fields. It provides a lot of shared functionality to all field subclasses
* (for example labels, simple validation, clearing and tab index management), but is rarely used directly.
* Instead, it is much more common to use one of the field subclasses.
*
* If you wish to create your own Field subclasses you can extend this class, though it is sometimes more useful
* to extend one of the other base subclasses as they provides additional base functionality.
*/
export default class Dropzone extends Component {
static propTypes = {
...Component.propTypes,
onClick: PropTypes.func,
onDrop: PropTypes.func,
onDropAccepted: PropTypes.func,
onDropRejected: PropTypes.func,
onDragStart: PropTypes.func,
onDragEnter: PropTypes.func,
onDragOver: PropTypes.func,
onDragLeave: PropTypes.func,
inputProps: PropTypes.object, // Pass additional attributes to the <input type="file"/> tag
accept: PropTypes.string, // Allow specific types of files. See https://github.com/okonet/attr-accept for more information
name: PropTypes.string // name attribute for the input tag
};
static defaultProps = {
...Component.defaultProps,
disablePreview: false,
disableClick: false,
multiple: false,
maxSize: Infinity,
minSize: 0
};
constructor(props, context) {
super(props, context);
this.onClick = this.onClick.bind(this);
this.onDragStart = this.onDragStart.bind(this);
this.onDragEnter = this.onDragEnter.bind(this);
this.onDragLeave = this.onDragLeave.bind(this);
this.onDragOver = this.onDragOver.bind(this);
this.onDrop = this.onDrop.bind(this);
this.onFileDialogCancel = this.onFileDialogCancel.bind(this);
this.fileAccepted = this.fileAccepted.bind(this);
this.isFileDialogActive = false;
this.state = {
isDragActive: false
};
}
static renderChildren(children, isDragActive, isDragReject) {
if (typeof children === 'function') {
return children({isDragActive, isDragReject});
}
return children;
}
static getDataTransferItems(event, isMultipleAllowed = true) {
let dataTransferItemsList = [];
if (event.dataTransfer) {
const dt = event.dataTransfer;
if (dt.files && dt.files.length) {
dataTransferItemsList = dt.files;
} else if (dt.items && dt.items.length) {
// During the drag even the dataTransfer.files is null
// but Chrome implements some drag store, which is accesible via dataTransfer.items
dataTransferItemsList = dt.items;
}
} else if (event.target && event.target.files) {
dataTransferItemsList = event.target.files;
}
if (dataTransferItemsList.length > 0) {
dataTransferItemsList = isMultipleAllowed ? dataTransferItemsList : [dataTransferItemsList[0]];
}
// Convert from DataTransferItemsList to the native Array
return Array.prototype.slice.call(dataTransferItemsList);
}
componentDidMount() {
this.enterCounter = 0;
// Tried implementing addEventListener, but didn't work out
document.body.onfocus = this.onFileDialogCancel;
}
static componentWillUnmount() {
// Can be replaced with removeEventListener, if addEventListener works
document.body.onfocus = null;
}
onDragStart(e) {
if (this.props.onDragStart) {
this.props.onDragStart.call(this, e);
}
}
onDragEnter(e) {
e.preventDefault();
// Count the dropzone and any children that are entered.
++this.enterCounter;
const allFilesAccepted = this.allFilesAccepted(Dropzone.getDataTransferItems(e, this.props.multiple));
this.setState(
{
isDragActive: allFilesAccepted,
isDragReject: !allFilesAccepted
}
);
if (this.props.onDragEnter) {
this.props.onDragEnter.call(this, e);
}
}
onDragOver(e) {
e.preventDefault();
e.stopPropagation();
try {
e.dataTransfer.dropEffect = 'copy'; // eslint-disable-line no-param-reassign
} catch (err) {
// continue regardless of error
}
if (this.props.onDragOver) {
this.props.onDragOver.call(this, e);
}
return false;
}
onDragLeave(e) {
e.preventDefault();
// Only deactivate once the dropzone and all children was left.
if (--this.enterCounter > 0) {
return;
}
this.setState(
{
isDragActive: false,
isDragReject: false
}
);
if (this.props.onDragLeave) {
this.props.onDragLeave.call(this, e);
}
}
onDrop(e) {
const {onDrop, onDropAccepted, onDropRejected, multiple, disablePreview} = this.props;
const fileList = Dropzone.getDataTransferItems(e, multiple);
const acceptedFiles = [];
const rejectedFiles = [];
// Stop default browser behavior
e.preventDefault();
// Reset the counter along with the drag on a drop.
this.enterCounter = 0;
this.isFileDialogActive = false;
fileList.forEach((file) => {
if (!disablePreview) {
file.preview = window.URL.createObjectURL(file);
}
if (this.fileAccepted(file) && this.fileMatchSize(file)) {
acceptedFiles.push(file);
} else {
rejectedFiles.push(file);
}
});
if (onDrop) {
onDrop.call(this, acceptedFiles, rejectedFiles, e);
}
if (rejectedFiles.length > 0 && onDropRejected) {
onDropRejected.call(this, rejectedFiles, e);
}
if (acceptedFiles.length > 0 && onDropAccepted) {
onDropAccepted.call(this, acceptedFiles, e);
}
// Reset drag state
this.setState(
{
isDragActive: false,
isDragReject: false
}
);
}
onClick(e) {
const {onClick, disableClick} = this.props;
if (!disableClick) {
e.stopPropagation();
this.open();
if (onClick) {
onClick.call(this, e);
}
}
}
onFileDialogCancel() {
// timeout will not recognize context of this method
const {onFileDialogCancel} = this.props;
const {fileInputEl} = this;
let {isFileDialogActive} = this;
// execute the timeout only if the onFileDialogCancel is defined and FileDialog
// is opened in the browser
if (onFileDialogCancel && isFileDialogActive) {
setTimeout(() => {
// Returns an object as FileList
const FileList = fileInputEl.files;
if (!FileList.length) {
isFileDialogActive = false;
onFileDialogCancel();
}
}, 300);
}
}
fileAccepted(file) {
return accepts(file, this.props.accept);
}
fileMatchSize(file) {
return file.size <= this.props.maxSize && file.size >= this.props.minSize;
}
allFilesAccepted(files) {
return files.every(this.fileAccepted);
}
open() {
this.isFileDialogActive = true;
this.fileInputEl.value = null;
this.fileInputEl.click();
}
render() {
const {testId, className, accept, inputProps, name, children, ...rest} = this.props;
let {...props} = rest;
const {isDragActive, isDragReject} = this.state;
const classes = classNames(style.container, {
[style.active]: (isDragActive),
[style.reject]: (isDragReject),
}, className);
const inputAttributes = {
accept,
type: 'file',
style: {display: 'none'},
ref: el => this.fileInputEl = el, // eslint-disable-line
onChange: this.onDrop
};
if (name && name.length) {
inputAttributes.name = name;
}
// Remove custom properties before passing them to the wrapper div element
const customProps = [
'acceptedFiles',
'disablePreview',
'disableClick',
'onDropAccepted',
'onDropRejected',
'onFileDialogCancel',
'maxSize',
'minSize'
];
const divProps = {};
customProps.forEach(prop => delete divProps[prop]);
return (
<div
className={classes}
data-test-id={testId}
{...divProps}
onClick={this.onClick}
onDragStart={this.onDragStart}
onDragEnter={this.onDragEnter}
onDragOver={this.onDragOver}
onDragLeave={this.onDragLeave}
onDrop={this.onDrop}
>
{Dropzone.renderChildren(children, isDragActive, isDragReject)}
<input
{...inputProps}
{...inputAttributes}
/>
<div className={style.overlay}>
<div>
<Icon className={style.icon} type={IconType.upload} />
<p className={style.title}>Drop file or click to upload</p>
<p className={style.message}>JPG, GIF or PND greater than 400 x 400 pixels</p>
</div>
</div>
</div>
);
}
}
<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {Component} from 'elements/base';
import ModalOverlay from './ModalOverlay';
import style from './Modal.scss';
import bounce from 'transitions/bounce.scss';
/**
* This class provides a convenient way to display a "popup" component to interact with
*/
export default class Modal extends Component {
static propTypes = {
// Boolean describing if the modal should be shown or not.
isOpen: PropTypes.bool,
// Function that will be run after the modal has opened.
onAfterOpen: PropTypes.func,
// Function that will be run when the modal is requested to be closed, prior to actually closing.
onClose: PropTypes.func,
// On modal click
onModalClick: PropTypes.func,
label: PropTypes.string,
role: PropTypes.string
};
static defaultProps = {
isOpen: false,
role: "dialog"
};
constructor(props) {
super(props);
this.handleClose = this.handleClose.bind(this);
this.modalClick = this.modalClick.bind(this);
}
handleClose(e) {
let {onClose} = this.props;
if (typeof onClose === "function") {
onClose(e, this);
}
}
modalClick(e) {
let {onModalClick} = this.props;
if (typeof onModalClick === "function") {
onModalClick(e, this);
}
}
renderWindow() {
const {children, className, role} = this.props;
const classes = classNames(style.modal, className);
return (
<div className={style.container}>
<div onClick={this.modalClick} key="modal" role={role} className={classes}>
{children}
</div>
</div>
);
}
render() {
const {isOpen} = this.props;
if(!isOpen){return null;}
return (
<div className={style.wrapper}>
<ModalOverlay isOpen={isOpen} onClick={this.handleClose}/>
{(isOpen) ? this.renderWindow() : ''}
</div>
)
}
}
<file_sep>export {default as Title} from './title/Title';
export {default as Alert} from './alert/Alert';<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import {shallow} from 'enzyme';
import Tooltip from './Tooltip';
// it('Check Render', () => {
// const div = document.createElement('div');
// ReactDOM.render(<Field />, div);
// });
//
// test('CheckboxWithLabel changes the text after click', () => {
//
// // Render a checkbox with label in the document
// const checkbox = shallow(
// <Field labelOn="On" labelOff="Off" />
// );
//
// expect(checkbox.text()).toEqual('Off');
//
// checkbox.find('input').simulate('change');
//
// expect(checkbox.text()).toEqual('On');
// });
describe('Standard Tooltip <Tooltip /> component', () => {
const message = 'this is a sample tooltip';
const target = <div id="placement">...</div>;
const tooltip = <div><Tooltip target="placement">{message}</Tooltip>{target}</div>;
// it('Check Render', () => {
// const div = document.createElement('div');
// ReactDOM.render(tooltip, div);
// });
it('Check Render', () => {
const wrapper = shallow(tooltip);
expect(wrapper.contains(target)).toEqual(true);
});
// it('Check hover', () => {
// const wrapper = shallow(tooltip);
// wrapper.find(target).simulate('hover');
// expect(wrapper.contains('tooltip__content')).toEqual(true);
// });
// it('Render Component', () => {
// const menu = shallow(<Menu />);
// const icon = <i className="icon icon--segment" aria-hidden="true"/>;
// expect(menu.contains(icon)).toEqual(true);
// });
// it('renders button click message', () => {
// const wrapper = shallow(<App />);
// const nineSign = <p className="App-intro">Nine: 9</p>;
// wrapper.find('button.elf').simulate('click');
// expect(wrapper.contains(nineSign)).toEqual(true);
// });
});
<file_sep># Description
A date picker component which shows a calender dropdown, or allows manual eatery of the date with some auto formatting.
The value will be transformed to the displayFormat when rendered in the ui, but the actual value used by the component will remain in the valueFormat. Use the 'displayFormat' & 'valueFormat' props to adjust the format.
Note: If an value is provided in a format that doesn't match the 'valueFormat', the component will attempt to transform the date using recognized RFC2822 or ISO formats.
# Example
~~~js
import {WindowModal} from 'react-ui-modules'
<WindowModal title="Segment Title" isOpen={true} onClose={() => {console.log('Do Close');}}>
Some content...
</WindowModal>
~~~<file_sep>import React from 'react';
import PropTypes from 'prop-types';
import {Field} from 'elements/form/field';
import classNames from 'classnames';
import {Icon, IconType} from 'elements/icon';
import style from './DropdownField.scss';
/**
* An abstract class for fields that have a single trigger which opens a "picker" below the field. It provides a
* base implementation for toggling the picker's visibility when the trigger is tapped.
*
* You would not normally use this class directly, but instead use it as the parent class for a specific picker
* field implementation.
*
* TODO: Change to picker
*/
export default class DropdownField extends Field {
static propTypes = {
...Field.propTypes,
typeahead: PropTypes.bool,
panelClassNames: PropTypes.string,
inputClassNames: PropTypes.string
};
static defaultProps = {
...Field.defaultProps,
typeahead: false,
panelClassNames: '',
inputClassNames: ''
};
constructor(props) {
super(props);
this.handleToggle = this.handleToggle.bind(this);
this.handleOpen = this.handleOpen.bind(this);
this.handleClose = this.handleClose.bind(this);
this.handleDocumentClick = this.handleDocumentClick.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
this.onInputBlur = this.onInputBlur.bind(this);
this.onInputChange = this.onInputChange.bind(this);
this.state = {
...super.state,
left: 0,
top: 0,
width: 100,
open: false,
search: '',
};
}
componentDidMount() {
this.manageDocumentClickEvent();
}
componentWillUnmount() {
this.removeDocumentEvents();
}
componentDidUpdate(prevProps) {
const {open} = this.state;
if (open !== prevProps.open) {
this.manageDocumentClickEvent();
}
}
/**
* Decide weather or not to add or remove the click event from the document.
*/
manageDocumentClickEvent() {
const {open} = this.state;
if (open) {
this.addDocumentEvents();
} else {
this.removeDocumentEvents();
}
}
/**
* Add the document click event to the dom
*/
addDocumentEvents() {
document.addEventListener('click', this.handleDocumentClick, true);
}
/**
* Remove the document click event from the dom.
*/
removeDocumentEvents() {
document.removeEventListener('click', this.handleDocumentClick, true);
}
/**
* Handle clicks on the document outside the component.
*
* This event is only added to the document when the state is open.
* @param event
*/
handleDocumentClick(event) {
// If clicked inside the component we will ignore it as we want to be able to hand internal clicks events.
if (this.node && this.node.contains(event.target)) {
return;
}
this.handleClose();
}
getDisplayString() {
return this.props.value;
}
/**
* Fires whenever the typehead input looses focus
* @param event
*/
onInputBlur(event) {
}
/**
* Fires whenever the typeahead input changes
*/
onInputChange(event) {
}
/**
* Toggle the panel state of the component.
*/
handleToggle() {
const {open} = this.state;
const {disabled} = this.props;
this.setState(
{
open: !open,
focus: !open
}
);
}
/**
* Toggle the panel to open
*/
handleOpen() {
this.setState(
{
open: true,
focus: true
}
);
}
/**
* Toggle the panel to closed
*/
handleClose() {
this.setState(
{
filter: null,
open: false,
focus: false
}
);
}
/**
* Handle key press events.
* @param event
*/
handleKeyPress(event) {
}
/**
* Render icons
*/
renderIcon(){}
/**
* Render the content of the drop down panel used to select the field value.
* @returns {null}
*/
renderPanel() {
return null;
}
/**
* Render the dropdown trigger.
* @returns {XML}
*/
renderTrigger() {
const {open, testId} = this.state;
return <div data-test-id={'trigger-' + testId} className={style.trigger} onClick={this.handleToggle}>
<Icon type={(open)? IconType.angleUp : IconType.angleDown}/>
</div>;
}
/**
* Render the display value for this component.
*
* Note: topically when building field components we override the `renderInput()`to change hoe the actual input
* part of the component looks. As dropdown fields have more complexity in regards to how the input functions
* with the dropdown panle, it is recommended that you override this method as opposed to the `renderInput()`
* when trying to change the input appearance.
*
* @returns {XML}
*/
renderInputValue() {
const {input, typeahead, name, placeholder, testId} = this.props;
const value = this.getDisplayString();
if (typeahead) {
return (
<input
{...input}
name={name}
data-test-id={'input-' + testId}
onBlur={this.onInputBlur}
onFocus={this.handleOpen}
value={value}
onKeyUp={this.handleKeyPress}
onChange={this.onInputChange}
placeholder={placeholder}
type="text"
autoComplete="off"
className={style.input}/>
);
}
// Should we use a placeholder text or just a space
const placeholderText = (placeholder)? <span className={style.placeholder}>{placeholder}</span> : '\u00A0';
return (
<div data-test-id={'input-' + testId} className={style.input} tabIndex="1" onClick={this.handleToggle} onKeyUp={this.handleKeyPress}>
{ (value) ? value : placeholderText }
</div>
);
}
renderInput() {
const {disabled, inputClassName} = this.props;
const {open, focus, loading, testId} = this.state;
const inputClasses = classNames(style.wrapper, inputClassName, {
[style.wrapperFocus]: (focus && !disabled),
[style.wrapperDisabled]: disabled,
});
const panelClasses = classNames(style.panel, {
[style.panelFocus]: focus
});
return (
<div data-test-id={testId} className={style.dropdown}>
<div className={inputClasses}>
{this.renderInputValue()}
{this.renderTrigger()}
</div>
{(open && !disabled) ? <div className={panelClasses} data-test-id={'panel-' + testId}>{this.renderPanel()}</div> : ''}
</div>
);
}
}
<file_sep>import React, {Component} from 'react'
import ReactDom from 'react-dom';
import classNames from 'classnames';
import style from './ListView.scss';
export default class ListView extends Component {
constructor() {
super();
this.handleScroll = this.handleScroll.bind(this);
this.initialize = this.initialize.bind(this)
}
componentDidMount() {
this.initialize();
window.addEventListener('resize', this.initialize)
}
componentDidUpdate() {
this.initialize()
}
componentWillUnmount() {
window.removeEventListener('resize', this.initialize);
}
initialize() {
this.scroll_container = ReactDom.findDOMNode(this);
this.findAllGroupHeaders();
this.findCursor();
this.updateActiveHeader()
}
/**
* Find all the group header elements on the page.
*/
findAllGroupHeaders() {
const node = this.scroll_container;
this.group_headings = node.querySelectorAll('[data-role="list-group"]');
}
/**
* Update the cursor that controles what group heading is currently the
* active group.
*/
findCursor() {
const node = this.scroll_container;
const group_headings = this.group_headings;
if (group_headings.length === 0) {
return;
}
//find the current group_header and next sticky elements
if (group_headings[0].offsetTop > node.scrollTop) {
this.group_heading_cursor = -1
} else {
let i = 0;
while (true) {
let next = group_headings[i + 1];
if (next.offsetTop > node.scrollTop) {
this.group_heading_cursor = i;
break;
} else {
i++;
if (i + 1 === group_headings.length) {
break
}
}
}
}
this.setNodes()
}
/**
* Set the group header nodes used for calculation what node to desplay
*/
setNodes() {
this.current_heading = this.group_headings[this.group_heading_cursor];
this.next_heading = this.group_headings[this.group_heading_cursor + 1] || null
}
/**
* Update the active header depending upon the current scroll position
* of the component.
*/
updateActiveHeader() {
//remove last group_header and placeholder
this.unset();
this.setNodes();
if (this.current_heading) {
//insert placeholder
this.insertPlaceholder(this.current_heading);
this.makeActiveGroupHeader(this.current_heading);
}
}
unset() {
if (this.current_heading) {
this.current_heading.style.position = 'inherit';
this.current_heading.style.top = null;
this.current_heading.classList.remove('group_header');
if (this.placeholder) {
this.placeholder.parentNode.removeChild(this.placeholder);
}
this.placeholder = null;
this.current_heading = null;
}
this.next_heading = null;
}
/**
* Create a placeholder for the new active group header.
*/
insertPlaceholder(group_header) {
this.placeholder = document.createElement("div")
this.placeholder.style.width = group_header.clientWidth + 'px'
this.placeholder.style.height = group_header.offsetHeight + 'px'
group_header.parentNode.insertBefore(this.placeholder, group_header)
}
/**
* Set the active group group header
*/
makeActiveGroupHeader(group_header) {
let bounds = this.scroll_container.getBoundingClientRect();
group_header.style.width = bounds.width + 'px';
group_header.style.height = group_header.offsetHeight + 'px';
group_header.style.top = this.scroll_container.offsetTop + 'px';
group_header.style.position = 'fixed';
group_header.style.clip = "rect(0px," + bounds.width + "px," + bounds.height + "px,0px)";
}
handleRefresh(resolve, reject) {
// do some async code here
if (true) {
resolve();
} else {
reject();
}
}
/**
* This handler does as little work as possible, checking if
* a) the scrollTop has hit our up or down boundaries -> Change cursor and update sticky state
* b) if nothing is "set" and we are scrolling down -> Update boundaries
*/
handleScroll() {
let node = this.scroll_container;
let down_boundary = this.next_heading && this.next_heading.offsetTop;
let up_boundary = this.placeholder && this.placeholder.offsetTop;
let set = (this.group_heading_cursor === -1 || up_boundary)
? true
: false;
let real_scroll_top = node.offsetTop + node.scrollTop;
//If we are not set, reset cursor on next downward scroll.
//This will get called once to set this new up/down boundaries
if (!set && this.last_scroll_top < real_scroll_top) {
this.findCursor();
//If we have crossed our downward boundary, make sticky
if (down_boundary && down_boundary < node.scrollTop) {
;
}
this.updateActiveHeader();
return;
}
this.last_scroll_top = real_scroll_top;
//Check if we have hit our boundaries and change the cursor and group_header state accordingly
if (down_boundary && real_scroll_top >= down_boundary) {
this.findCursor();
this.group_heading_cursor++;
this.updateActiveHeader();
return
}
if (up_boundary && real_scroll_top <= up_boundary) {
this.group_heading_cursor--;
this.unset();
this.updateActiveHeader();
return
}
//Check for Sticky collision and adjust top position accordingly
//TODO: Need to workout how to hide group under parent when scrolling,
// if (set && this.current_heading && real_scroll_top >= down_boundary - this.current_heading.offsetHeight) {
// // For now we will simplet swap headdings whenever the new title is at the top.
// var top = Math.min(node.offsetTop, this.next_heading.offsetTop - node.scrollTop - this.current_heading.offsetHeight)
// this.current_heading.style.top = top + 'px'
// return
// }
//If none of the above conditions triggered, check if we are out of bounds, and if so reset cursor
if (real_scroll_top > down_boundary || real_scroll_top < up_boundary) {
this.findCursor();
return
}
}
/**
* Get List
* Generate the list of members. This can be done in two ways depending on
* the state of the search. If the customer is currently searching, then the
* list will return a list of search results. If the state has no search, then
* the complete list of global state contacts is returned.
*/
getList() {
return null
}
/**
* Render the core list element. If you wish to extend this component and wrap it in additional functionality, make
* sure to call this method from the render method.
*
* @returns {XML}
*/
renderList() {
const {className} = this.props;
const classes = classNames(style.container, className);
return (
<div onScroll={this.handleScroll} className={classes}>
{this.getList()}
</div>
)
}
/**
* Render the list, if you override make sure to call renderList()
* @returns {XML}
*/
render() {
return this.renderList();
}
}
<file_sep>import React, {Component} from "react";
import PropTypes from 'prop-types';
import classNames from 'classnames';
import style from './Alert.scss';
export default class Alert extends Component {
static propTypes = {
title: PropTypes.string,
testId: PropTypes.string
};
static defaultProps = {
title: '',
};
static modifier = {
success: style.alertSuccess,
warning: style.alertWarning,
error: style.alertError,
};
constructor(props) {
super(props);
this.handleClose = this.handleClose.bind(this);
}
/**
* Handle the close click
*/
handleClose() {
let {onClose} = this.props;
if (typeof onClose === "function") {
onClose();
}
}
render() {
const {title, children, modifier, className, testId} = this.props;
const classes = classNames(style.container, modifier, className);
return (
<aside data-test-id={testId} className={classes}>
<div data-test-id={'close-' + testId} onClick={this.handleClose} className={style.close} />
{ title ? <h3 className={style.title}>{ title }</h3> : null }
{ children ? <div className={style.body}>{ children }</div> : null }
</aside>
);
}
}
| 3f7a9714e900a4a06957e7674a3c0ca83cfda39e | [
"Markdown",
"JavaScript"
] | 76 | Markdown | levi-putna/react-ui-modules | f6db5745903cd48bfeb82ef5fd60b676b853abb4 | 283929359f954282a8bb0eebab4ba8a34033973a |
refs/heads/master | <repo_name>atharvapatil/tripod<file_sep>/arduino/pulseSensor_BPM/pulseSensor_BPM.ino
// Hardware used Arduino mkr 1010
#include <ArduinoBLE.h>
const int ledPin = LED_BUILTIN; // set ledPin to on-board LED
const int buttonPin = 4; // set buttonPin to digital pin 4
BLEService ledService("4cc4513b-1b63-4c93-a419-dddaeae3fdc7"); // create service
// create switch characteristic and allow remote device to read and write
BLEByteCharacteristic ledCharacteristic("ef9534b9-2c24-4ddc-b9b2-fc690ecf4cb4", BLERead | BLEWrite);
// create button characteristic and allow remote device to get notifications
BLEByteCharacteristic buttonCharacteristic("db07a43f-07e3-4857-bccc-f01abfb8845c", BLERead | BLENotify);
void setup() {
Serial.begin(9600);
while (!Serial);
pinMode(ledPin, OUTPUT); // use the LED as an output
pinMode(buttonPin, INPUT); // use button pin as an input
// begin initialization
if (!BLE.begin()) {
Serial.println("starting BLE failed!");
while (1);
}
// set the local name peripheral advertises
BLE.setLocalName("ButtonLED");
// set the UUID for the service this peripheral advertises:
BLE.setAdvertisedService(ledService);
// add the characteristics to the service
ledService.addCharacteristic(ledCharacteristic);
ledService.addCharacteristic(buttonCharacteristic);
// add the service
BLE.addService(ledService);
//
// ledCharacteristic.writeValue(0);
// buttonCharacteristic.writeValue(0);
// start advertising
BLE.advertise();
Serial.println("Bluetooth device active, waiting for connections...");
}
void loop() {
// poll for BLE events
BLE.poll();
// read the current button pin state
int buttonValue = digitalRead(buttonPin);
// has the value changed since the last read
boolean buttonChanged = (buttonCharacteristic.value() != buttonValue);
if (buttonChanged) {
// button state changed, update characteristics
ledCharacteristic.writeValue(buttonValue);
buttonCharacteristic.writeValue(buttonValue);
}
if (ledCharacteristic.written() || buttonChanged) {
// update LED, either central has written to characteristic or button state has changed
if (ledCharacteristic.value()) {
Serial.println("LED on");
digitalWrite(ledPin, HIGH);
} else {
Serial.println("LED off");
digitalWrite(ledPin, LOW);
}
}
}
<file_sep>/tripod bluetooth input/tripod bluetooth input/ViewController.swift
//
// ViewController.swift
// tripod bluetooth input
//
// Created by <NAME> on 25/04/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
import CoreBluetooth
import Foundation
// UUID to identify the arduino device which in this case is the same as the service
let SERVICE_LED_UUID = "4cc4513b-1b63-4c93-a419-dddaeae3fdc7"
// UUID's to identify the charecteristics of the sensors
let LED_CHARACTERISTIC_UUID = "ef9534b9-2c24-4ddc-b9b2-fc690ecf4cb4"
let BUTTON_CHARACTERISTIC_UUID = "db07a43f-07e3-4857-bccc-f01abfb8845c"
class ViewController: UIViewController {
// DECLARING BLUETOOTH VARIABLES: BEGINS HERE
// Initialising the Bluetooth manager object
var centralManager: CBCentralManager?
// Initialising Peripheral object which is responsible for discovering a nerby Accessory
var arduinoPeripheral: CBPeripheral?
// Variables to identify different sensors on the arduino as individual services which have chareteristics attached to them
var ledService: CBService?
// Variables to communicate the state of a charecteristic to and from the arduino
var charOne: CBCharacteristic?
var charTwo: CBCharacteristic?
// DECLARING BLUETOOTH VARIABLES: ENDS HERE
// label to appened states & the data incoming from the periphral
@IBOutlet weak var buttonValue: UILabel!
@IBOutlet weak var otherButton: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Initiating bluetooth
centralManager = CBCentralManager(delegate: self, queue: nil)
// Text values at different states.
// When the view loads the device starts connecting to Arduino
buttonValue.text = "Connecting to Arduino"
// TO-DO: Write and alert check here to see if Bluetooth is on or not. If Bluetooth is off through a alert with message.
}
}
extension ViewController: CBCentralManagerDelegate{
// Scanning for a Peripherial with a Unique accessory UUID. This id the arduino UUID
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
// The commented statement below searches for all discoverable peripherals, turn on for testing
// central.scanForPeripherals(withServices: nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey: false])
// Scanning for a specific UUID peripheral
central.scanForPeripherals(withServices: [CBUUID(string: SERVICE_LED_UUID)], options: nil)
// Logging to see of Bluetooth is scanning for the defined UUID peripheral
print("Scanning for peripheral with UUID: ", SERVICE_LED_UUID)
}
}
// This function handles the cases when the Bluetooth device we are looking for is discovered
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
// If the peripheral is discovered log the details
print("Discovered peripheral", peripheral)
// Reference it
arduinoPeripheral = peripheral
// Connect to the Arduino peripheral
centralManager?.connect(arduinoPeripheral!, options: nil)
// print out the connection attempt
print("Connecting to: ", arduinoPeripheral!)
}
// This function hadles the cases when the connection is successful
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
// Check if we are connected to the same peripheral
guard let peripheral = arduinoPeripheral else {
return
}
// Delegating
peripheral.delegate = self
// the connected peripheral's properties
print("Connected to: ", arduinoPeripheral!)
// Also the same feeback on the screen
buttonValue.text = "Connection Successful"
// Now that the device is connected start loooking for services attached to it.
peripheral.discoverServices([CBUUID(string: SERVICE_LED_UUID)])
// Test statement to discover all the services attached to the peripheral
// peripheral.discoverServices(nil)
}
}
// Now that is the a periphral discovered and referenced to start looking for properties attached to it.
extension ViewController: CBPeripheralDelegate{
// This function handles the cases when there are services discovered for the peripheral
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?){
// Logging the discovered services
print("Discovered services:", peripheral.services!)
// Feedback on screen
buttonValue.text = "Services Discovered"
// iterating through the services to retrive the one we are looking for
guard let LEDService = peripheral.services?.first(where: { service -> Bool in
service.uuid == CBUUID(string: SERVICE_LED_UUID)
}) else {
return
}
// Referencing it
ledService = LEDService
// & Logging it's UUID to make sure it's the right one
print("LED Service UUID", ledService!.uuid)
// Now that the service is discovered and referenced to. Search for the charecteristics attached to it.
peripheral.discoverCharacteristics([CBUUID(string: LED_CHARACTERISTIC_UUID)], for: LEDService)
peripheral.discoverCharacteristics([CBUUID(string: BUTTON_CHARACTERISTIC_UUID)], for: LEDService)
}
// This function handles the cases when charecteristics are discovered(the ones we are looking for just above)
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
// Log all the charecteristics for test
// print("Charecteristics Discovered", service.characteristics!)
// Look for a specific charecteristic
guard let ledCharecteristic = service.characteristics?.first(where: { characteristic -> Bool in
characteristic.uuid == CBUUID(string: LED_CHARACTERISTIC_UUID)
}) else {
return
}
// If discovered, reference it
charOne = ledCharecteristic
// Log the properties of the charecteristic
print("LED Charecteristic info ", ledCharecteristic)
// Look for a specific charecteristic
guard let buttonCharecteristic = service.characteristics?.first(where: { characteristic -> Bool in
characteristic.uuid == CBUUID(string: BUTTON_CHARACTERISTIC_UUID)
}) else {
return
}
// If discovered, reference it
charTwo = buttonCharecteristic
// Log the properties of the charecteristic
print("Button Charecteristic info ", buttonCharecteristic)
// If the propter can send/notify (BLENotify on arduino) then we need to reference a listener for it
// This is the listenter event for that
peripheral.setNotifyValue(true, for: buttonCharecteristic)
peripheral.setNotifyValue(true, for: ledCharecteristic)
// Now that the charectertistic is discovered it's time to press the button
buttonValue.text = "Place hand on button"
}
// This function handles the cases when the sensor is sending some data
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
// SB Notes:
// Return if there's an error
if let error = error {
print("Error receiving characteristic value:", error.localizedDescription)
return
}
// As a best practice, you should grab the characteristic
// that is passed here and do a check that it is the characteristic that you expect
guard let updatedData = characteristic.value else {
// It's also a good idea to print before returning so you can debug
print("Unable to get data from characeristic:", characteristic)
return
}
// Look into received bytes
let byteArray = [UInt8](updatedData)
print("Received:", byteArray)
// print(byteArray, String(bytes: byteArray, encoding: .utf8)!)
// Extract data from the charecteristic
guard let data = charTwo!.value else {
return
}
// Convert it to a human readable value
let integerValue = data.int8Value()
// Log that value
// print("Button integer value", integerValue)
if integerValue == 0{
buttonValue.text = "First Button Pressed"
} else {
buttonValue.text = "First Button Released"
}
guard let dataTwo = charOne!.value else {
return
}
let buttonTwoValue = dataTwo.int8Value()
// let buttonTwoValue = [UInt8](dataTwo)
otherButton.text = "Potentiometer input: " + "\(buttonTwoValue)"
}
}
// Functions to convert raw data to other formats
extension Data {
func int8Value() -> Int8 {
return Int8(bitPattern: self[0])
}
}
<file_sep>/README.md
# Tripod
Repository has the files to communicate between an Arduino & iOS device via Bluetooth. First application is using a pulse monitor sensor and displaying the BPM on the iOS device screen.
## Progress
### Overall Status
* Two way communication between Arduino & iPad. [See video here](https://photos.app.goo.gl/URevDbxGt3uTu4478)
### Doubts
Hi Nien & Sebastian, some doubts/questions I have.
* On line 203 of ViewController.swift I am getting the data from the button for now but unable to parse it as a string. Looked up some references online but couln't figure it out. The found the method in Data extension to convert the value into integer to print it.
* What is the best way to handle error events in the functions.
### Immediate To-Do's
* Design the user experience(interface, affordances, states, etc)
* Arduino side code and wiring to broadcast the BPM data to serial monitor
<file_sep>/arduino/bell/bell.ino
// Hardware used Arduino mkr 1010
#include <ArduinoBLE.h>
//const int ledPin = 0; // set ledPin to on-board LED
int ledPin = A6; // set ledPin to on-board LED
const int buttonPin = 1; // set buttonPin to digital pin 1
int potValue = 0;
BLEService ledService("4cc4513b-1b63-4c93-a419-dddaeae3fdc7"); // create service
// create switch characteristic and allow remote device to read and write
BLEByteCharacteristic ledCharacteristic("ef9534b9-2c24-4ddc-b9b2-fc690ecf4cb4", BLERead | BLENotify);
// create button characteristic and allow remote device to get notifications
BLEByteCharacteristic buttonCharacteristic("db07a43f-07e3-4857-bccc-f01abfb8845c", BLERead | BLENotify);
void setup() {
Serial.begin(9600);
while (!Serial);
pinMode(ledPin, INPUT); // use the LED as an output
pinMode(buttonPin, INPUT); // use button pin as an input
// begin initialization
if (!BLE.begin()) {
Serial.println("starting BLE failed!");
while (1);
}
// set the local name peripheral advertises
BLE.setLocalName("ButtonLED");
// set the UUID for the service this peripheral advertises:
BLE.setAdvertisedService(ledService);
// add the characteristics to the service
ledService.addCharacteristic(ledCharacteristic);
ledService.addCharacteristic(buttonCharacteristic);
// add the service
BLE.addService(ledService);
ledCharacteristic.writeValue(0);
buttonCharacteristic.writeValue(0);
// start advertising
BLE.advertise();
Serial.println("Bluetooth device active, waiting for connections...");
}
void loop() {
// poll for BLE events
BLE.poll();
// read the current button pin state
char buttonValue = digitalRead(buttonPin);
// has the value changed since the last read
boolean buttonChanged = (buttonCharacteristic.value() != buttonValue);
// boolean buttonChanged = (buttonCharacteristic.value() == 1);
if (buttonChanged) {
// button state changed, update characteristics
// ledCharacteristic.writeValue(buttonValue);
buttonCharacteristic.writeValue(buttonValue);
Serial.println("Button One interaction");
}
// if (buttonValue == LOW) {
// Serial.println("LED on");
// digitalWrite(ledPin, HIGH);
// } else {
// Serial.println("LED off");
// digitalWrite(ledPin, LOW);
// }
// char buttonTwoValue = digitalRead(ledPin);
int potValue = analogRead(ledPin);
int mappedButtonTwoValue = map(potValue, 0, 1024, 0, 255);
Serial.println(mappedButtonTwoValue);
boolean buttonTwoChanged = (ledCharacteristic.value() != mappedButtonTwoValue);
if (buttonTwoChanged) {
// button state changed, update characteristics
ledCharacteristic.writeValue(mappedButtonTwoValue);
// buttonCharacteristic.writeValue(buttonValue);
//Serial.println(mappedButtonTwoValue);
}
// if (ledCharacteristic.written() || buttonChanged) {
// // update LED, either central has written to characteristic or button state has changed
// if (ledCharacteristic.value()) {
// Serial.println("LED on");
// digitalWrite(ledPin, HIGH);
// } else {
// Serial.println("LED off");
// digitalWrite(ledPin, LOW);
// }
// }
}
| aefea146eb7fd5c568a253ca38dfd43db413d6f5 | [
"Swift",
"C++",
"Markdown"
] | 4 | C++ | atharvapatil/tripod | 564a6b49345e8a1936e043c929003658dcde20da | a6ea2a573600352ed64c6834da5c56cdca25ebd2 |
refs/heads/master | <file_sep>package com.dimatechs.ecard;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import com.dimatechs.ecard.Interface.ItemClickListner;
import com.dimatechs.ecard.Model.AdminOrders;
import com.dimatechs.ecard.Model.Products;
import com.dimatechs.ecard.ViewHolder.ProductViewHolder;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.squareup.picasso.Picasso;
public class AdminNewOrdersActivity extends AppCompatActivity {
private RecyclerView ordersList;
private DatabaseReference ordersRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_new_orders);
ordersRef = FirebaseDatabase.getInstance().getReference().child("Orders");
ordersList=findViewById(R.id.orders_list);
ordersList.setLayoutManager(new LinearLayoutManager(this));
}
@Override
protected void onStart() {
super.onStart();
Log.d("aaaa", "onstart");
FirebaseRecyclerOptions<AdminOrders> options=
new FirebaseRecyclerOptions.Builder<AdminOrders>()
.setQuery(ordersRef,AdminOrders.class)
.build();
Log.d("aaaa","op");
FirebaseRecyclerAdapter<AdminOrders, AdminOrdersViewHolder> adapter=
new FirebaseRecyclerAdapter<AdminOrders, AdminOrdersViewHolder>(options) {
@Override
protected void onBindViewHolder(@NonNull AdminOrdersViewHolder holder, final int position, @NonNull final AdminOrders model)
{
Log.d("aaaa","holder");
holder.userName.setText(model.getName());
holder.userPhoneNumber.setText(model.getPhone());
holder.userTotalPrice.setText(" מחיר : " +model.getTotalAmount() + " ש\"ח ");
holder.userDateTime.setText(model.getDate()+" "+model.getTime());
holder.userAdress.setText("חיפה");
holder.showOrdersBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
String uID = getRef(position).getKey();
Intent intent = new Intent(AdminNewOrdersActivity.this,AdminUserProductsActivity.class);
intent.putExtra("uid",uID);
startActivity(intent);
}
});
}
@NonNull
@Override
public AdminOrdersViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
Log.d("aaaa","onCreateViewHolder");
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.orders_layout,parent,false);
AdminOrdersViewHolder holder = new AdminOrdersViewHolder(view);
return holder;
}
};
ordersList.setAdapter(adapter);
adapter.startListening();
}
public static class AdminOrdersViewHolder extends RecyclerView.ViewHolder
{
public TextView userName,userPhoneNumber,userTotalPrice,userDateTime,userAdress;
public Button showOrdersBtn;
public AdminOrdersViewHolder(View itemView) {
super(itemView);
userName = (TextView) itemView.findViewById(R.id.order_user_name);
userPhoneNumber = (TextView) itemView.findViewById(R.id.order_phone_number);
userTotalPrice = (TextView) itemView.findViewById(R.id.order_total_price);
userDateTime = (TextView) itemView.findViewById(R.id.order_date_time);
userAdress = (TextView) itemView.findViewById(R.id.order_address_city);
showOrdersBtn = (Button) itemView.findViewById(R.id.show_all_products_btn);
}
}
}
<file_sep>package com.dimatechs.ecard;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.EventLogTags;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
public class NewProductActivity extends AppCompatActivity {
private Button AddNewProductBtn;
private EditText EDProductName,EDProuctDescription,EdProductPrice;
private ImageView ProductImage;
private static final int GalleryPick=1;
private Uri ImageUri;
private String ProductName ,ProuctDescription,ProductPrice,saveCurrentDate,saveCurrentTime;
private String productRandomKey,downloadImageURL;
private StorageReference ProductImagesRef;
private DatabaseReference ProductsRef;
private ProgressDialog loadingBar;
// teast
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_product);
ProductImagesRef= FirebaseStorage.getInstance().getReference().child("Product Images");
ProductsRef=FirebaseDatabase.getInstance().getReference().child("Products");
loadingBar=new ProgressDialog(this);
AddNewProductBtn=(Button)findViewById(R.id.Btn_new_product);
EDProductName=(EditText) findViewById(R.id.Ed_Product_name);
EDProuctDescription=(EditText) findViewById(R.id.Ed_Product_Description);
EdProductPrice=(EditText) findViewById(R.id.Ed_Product_Price);
ProductImage=(ImageView) findViewById(R.id.product_image);
ProductImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
OpenGallery();
}
});
AddNewProductBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
ValidateProductData();
}
});
}
private void OpenGallery() {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent,GalleryPick);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==GalleryPick && resultCode==RESULT_OK && data!=null)
{
ImageUri=data.getData();
ProductImage.setImageURI(ImageUri);
}
}
private void ValidateProductData() {
ProductName=EDProductName.getText().toString();
ProuctDescription=EDProuctDescription.getText().toString();
ProductPrice=EdProductPrice.getText().toString();
if(ImageUri==null)
{
Toast.makeText(this, "חסר תמונה למוצר", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(ProductName))
{
Toast.makeText(this, "חסר שם מוצר . . .", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(ProuctDescription))
{
Toast.makeText(this, "חסר תאור למוצר . . .", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(ProductPrice))
{
Toast.makeText(this, "חסר מחיר למוצר . . .", Toast.LENGTH_SHORT).show();
}
else
{
StoreProductInformation();
}
}
private void StoreProductInformation()
{
loadingBar.setTitle("הוספת מוצר חדש");
loadingBar.setMessage("המתן בבקשה");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Calendar calendar=Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate=currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a");
saveCurrentTime=currentTime.format(calendar.getTime());
productRandomKey=saveCurrentDate+saveCurrentTime;
final StorageReference filePath=ProductImagesRef.child(ImageUri.getLastPathSegment() + productRandomKey +".jpg");
final UploadTask uploadTask = filePath.putFile(ImageUri);
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e)
{
String message=e.toString();
Toast.makeText(NewProductActivity.this, "Error:"+message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
Toast.makeText(NewProductActivity.this, "תמונה הועלאה בהצלחה", Toast.LENGTH_SHORT).show();
Task<Uri> uriTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
@Override
public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception
{
if(!task.isSuccessful())
{
throw task.getException();
}
downloadImageURL=filePath.getDownloadUrl().toString();
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task)
{
if(task.isSuccessful())
{
downloadImageURL=task.getResult().toString();
Toast.makeText(NewProductActivity.this, "תמונה נשמרה בהצלחה", Toast.LENGTH_SHORT).show();
SaveProductInfoToDatabase();
}
}
});
}
});
}
private void SaveProductInfoToDatabase()
{
HashMap<String,Object> productMap = new HashMap<>();
productMap.put("pid",productRandomKey);
productMap.put("date",saveCurrentDate);
productMap.put("time",saveCurrentTime);
productMap.put("name",ProductName);
productMap.put("description",ProuctDescription);
productMap.put("price",ProductPrice);
productMap.put("image",downloadImageURL);
ProductsRef.child(productRandomKey).updateChildren(productMap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Intent intent=new Intent(NewProductActivity.this,HomeActivity.class);
startActivity(intent);
loadingBar.dismiss();
Toast.makeText(NewProductActivity.this, "מוצר הוסף בהצלחה", Toast.LENGTH_SHORT).show();
}
else
{
loadingBar.dismiss();
String message=task.getException().toString();
Toast.makeText(NewProductActivity.this, "Error:"+message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
<file_sep>package com.dimatechs.ecard;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.dimatechs.ecard.Prevalent.Prevalent;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
public class ConfirmFinalOrderActivity extends AppCompatActivity {
private Button confirmOrderBtn;
private String totalAmount="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirm_final_order);
totalAmount=getIntent().getStringExtra("Total Price");
confirmOrderBtn=(Button)findViewById(R.id.confirm_final_order_btn);
confirmOrderBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
ConfirmOrder();
}
});
}
private void ConfirmOrder()
{
final String saveCurrentTime, saveCurrentDate;
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("MMM dd, yyyy");
saveCurrentDate=currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss a");
saveCurrentTime=currentTime.format(calendar.getTime());
final DatabaseReference ordersRef= FirebaseDatabase.getInstance().getReference()
.child("Orders")
.child(Prevalent.currentOnlineUser.getPhone());
final HashMap<String,Object> ordersMap = new HashMap<>();
ordersMap.put("totalAmount",totalAmount);
ordersMap.put("date",saveCurrentDate);
ordersMap.put("time",saveCurrentTime);
ordersMap.put("state","not shipped");
ordersRef.updateChildren(ordersMap).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task)
{
if(task.isSuccessful())
{
FirebaseDatabase.getInstance().getReference()
.child("Cart List")
.child("User View")
.child(Prevalent.currentOnlineUser.getPhone())
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(ConfirmFinalOrderActivity.this, "ההזמנה נשלחה בהצלחה", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ConfirmFinalOrderActivity.this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
}
});
}
}
});
}
}
| e626fb7e2b9cb32011c2bd096d0f6b593e433e35 | [
"Java"
] | 3 | Java | hanimanaa/Ecard | 38bbe54582b57fce433428bb72643a74726471fa | 11e6e13de9b7f8378e27e3cc9568535134058db5 |
refs/heads/master | <repo_name>ghsantos/Notes<file_sep>/app/src/components/Item.js
/* @flow */
import React, { Component } from 'react';
import {
Text,
StyleSheet,
TouchableOpacity,
View,
} from 'react-native';
import Swipeable from 'react-native-swipeable';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
export default class Item extends Component {
render() {
const rightButton = ([
<View style={{ flex: 1, justifyContent: 'center' }}>
<TouchableOpacity style={styles.deleteButton} onPress={this.props.onPressDelete}>
<Text style={{ color: '#fff' }}>
Apagar
</Text>
</TouchableOpacity>
</View>
]);
return (
<Swipeable
rightButtons={rightButton}
style={[styles.container, { backgroundColor: this.props.color }]}
>
<TouchableOpacity
style={{ flex: 1, flexDirection: 'row' }}
onPress={this.props.onPress}
>
<View style={{ flex: 1, justifyContent: 'center' }}>
{!!this.props.title &&
<Text numberOfLines={1} style={styles.title}>{this.props.title}</Text>
}
{!this.props.locked &&
<Text numberOfLines={this.props.title ? 1 : 2} style={styles.nota}>
{this.props.note}
</Text>
}
</View>
{!!this.props.locked &&
<View style={{ justifyContent: 'center', }}>
<Icon
name='lock'
size={28}
color='#0000009A'
style={styles.icon}
/>
</View>
}
</TouchableOpacity>
</Swipeable>
);
}
}
const styles = StyleSheet.create({
container: {
height: 58,
borderRadius: 4,
paddingHorizontal: 10,
marginBottom: 5,
marginHorizontal: 5,
elevation: 2,
backgroundColor: 'white',
},
title: {
fontSize: 18,
fontWeight: 'bold',
color: '#333',
},
nota: {
fontSize: 14,
},
deleteButton: {
backgroundColor: '#F44336',
width: 68,
height: '65%',
justifyContent: 'center',
alignItems: 'center',
marginLeft: 12,
borderRadius: 2,
},
});
<file_sep>/app/src/components/Line.js
/* @flow weak */
import React from 'react';
import {
View,
StyleSheet,
} from 'react-native';
const Line = () => (
<View style={styles.container} />
);
export default Line;
const styles = StyleSheet.create({
container: {
height: 1,
width: '100%',
marginVertical: 4,
backgroundColor: '#0000004A',
},
});
<file_sep>/app/src/components/AddItem.js
/* @flow */
import React, { Component } from 'react';
import {
Text,
TouchableOpacity,
StyleSheet,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
export default class AddItem extends Component {
render() {
return (
<TouchableOpacity style={styles.container} onPress={this.props.onPress}>
<Icon name='add' color='#555' size={33} />
<Text style={styles.text}>Adicionar</Text>
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create({
container: {
elevation: 3,
padding: 6,
flexDirection: 'row',
backgroundColor: 'white',
justifyContent: 'center',
alignItems: 'center',
},
text: {
fontSize: 25,
marginLeft: 8,
},
});
<file_sep>/app/src/components/DrawerItem.js
/* @flow weak */
import React from 'react';
import {
TouchableOpacity,
Text,
StyleSheet,
} from 'react-native';
const DrawerItem = (props) => (
<TouchableOpacity
style={[
styles.drawerItem,
props.active ? styles.drawerItemSelect : {}
]}
onPress={() => props.onPress()}
>
{props.icon}
<Text style={styles.text}>
{props.text}
</Text>
</TouchableOpacity>
);
export default DrawerItem;
const styles = StyleSheet.create({
drawerItem: {
height: 50,
width: '100%',
flexDirection: 'row',
alignItems: 'center',
paddingLeft: 12,
},
drawerItemSelect: {
backgroundColor: '#E5E5E5'
},
text: {
fontSize: 16,
fontWeight: 'bold',
paddingLeft: 12,
},
});
<file_sep>/app/src/navigators/AppNavigator.js
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
addNavigationHelpers,
StackNavigator,
DrawerNavigator,
} from 'react-navigation';
import { Animated, Easing } from 'react-native';
import HomeScreen from '../containers/HomeScreen';
import ArchiveScreen from '../containers/ArchiveScreen';
import TrashScreen from '../containers/TrashScreen';
import Edict from '../containers/Edict';
import MarkerEdict from '../containers/MarkerEdict';
import CustomDrawer from '../components/CustomDrawer';
import { addListener } from '../utils/redux';
const transitionConfig = () => ({
transitionSpec: {
duration: 350,
easing: Easing.out(Easing.poly(4)),
timing: Animated.timing,
useNativeDriver: true,
},
screenInterpolator: sceneProps => {
const { position, layout, scene, index, scenes } = sceneProps;
const toIndex = index;
const thisSceneIndex = scene.index;
const width = layout.initWidth;
const translateX = position.interpolate({
inputRange: [thisSceneIndex - 1, thisSceneIndex, thisSceneIndex + 1],
outputRange: [width, 0, 0],
});
const slideFromRight = { transform: [{ translateX }] };
const lastSceneIndex = scenes[scenes.length - 1].index;
if (lastSceneIndex - toIndex > 1) {
if (scene.index === toIndex) return;
if (scene.index !== lastSceneIndex) return { opacity: 0 };
}
return slideFromRight;
},
});
const Home = StackNavigator({
main: { screen: HomeScreen, params: { type: 'note' } },
edict: { screen: Edict },
},
{
transitionConfig,
});
const Archive = StackNavigator({
main: { screen: ArchiveScreen },
edict: { screen: Edict },
},
{
transitionConfig,
});
const Trash = StackNavigator({
main: { screen: TrashScreen },
edict: { screen: Edict },
},
{
transitionConfig,
});
const MainNavigator = DrawerNavigator({
Home: { screen: Home },
Archive: { screen: Archive },
Trash: { screen: Trash },
},
{
contentComponent: (props) => <CustomDrawer {...props} />,
});
export const AppNavigator = StackNavigator({
main: { screen: MainNavigator },
marker: { screen: MarkerEdict },
},
{
headerMode: 'none',
});
class AppWithNavigationState extends React.Component {
static propTypes = {
dispatch: PropTypes.func.isRequired,
nav: PropTypes.object.isRequired,
};
render() {
const { dispatch, nav } = this.props;
return (
<AppNavigator
navigation={addNavigationHelpers({
dispatch,
state: nav,
addListener,
})}
/>
);
}
}
const mapStateToProps = state => ({
nav: state.nav,
});
export default connect(mapStateToProps)(AppWithNavigationState);
<file_sep>/README.md
# Notes
## Instalação do app
```
$ cd app/
$ npm install
$
$ # react-native-vector-icons issue (Error: While resolving module `react-native-vector-icons/...)
$ # https://github.com/oblador/react-native-vector-icons/issues/626
$ rm ./node_modules/react-native/local-cli/core/__fixtures__/files/package.json
$
$ react-native run-android # ou react-native run-ios
```
<file_sep>/app/App.js
/** @flow */
import React from 'react';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import AppReducer from './src/reducers';
import AppWithNavigationState from './src/navigators/AppNavigator';
const store = createStore(
AppReducer,
compose(applyMiddleware(thunk)),
);
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<AppWithNavigationState />
</Provider>
);
}
}
<file_sep>/app/src/components/AlertConfirmPass.js
/* @flow */
import React, { Component } from 'react';
import {
Text,
TextInput,
StyleSheet,
} from 'react-native';
import CustomAlert from './CustomAlert';
export default class AlertConfirmPass extends Component {
state = {
pass: '',
}
onPressConfirm() {
this.props.onPressConfirm(this.state.pass);
this.setState({ pass: '' });
}
onPressCancel() {
this.props.onPressCancel();
this.setState({ pass: '' });
}
render() {
return (
<CustomAlert
visible={this.props.visible}
title='Confirme sua senha'
buttons={[
{
text: 'CANCELAR',
onPress: () => this.onPressCancel(),
key: 1,
},
{
text: 'OK',
onPress: () => this.onPressConfirm(),
key: 2,
},
]}
>
{
!this.props.correct &&
<Text style={styles.textIncorrect}>
Senha incorreta, tente novamente.
</Text>
}
<TextInput
autoFocus
secureTextEntry
autoCapitalize='none'
value={this.state.pass}
onChangeText={text => this.setState({ pass: text })}
/>
</CustomAlert>
);
}
}
const styles = StyleSheet.create({
textIncorrect: {
color: '#F44336',
},
});
<file_sep>/app/src/containers/MarkerEdict.js
/* @flow */
import React, { Component } from 'react';
import {
BackHandler,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View,
} from 'react-native';
import CommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import SortableListView from 'react-native-sortable-listview';
import { connect } from 'react-redux';
import { getMarkers, updateMarkers } from '../actions';
import AddItem from '../components/AddItem';
import Header from '../components/Header';
import CustomAlert from '../components/CustomAlert';
import MarkerRow from '../components/MarkerRow';
class MarkerEdict extends Component {
state = {
markers: [],
marker: '',
markerKey: '',
addVisible: false,
}
componentDidMount() {
this.props.getMarkers();
this.backButtonListener = BackHandler.addEventListener('hardwareBackPress', () => {
if (this.props.navigation.state.routeName === 'marker') {
this.goBack();
return true;
}
return false;
});
}
componentWillReceiveProps(nextProps) {
if (nextProps.markers) {
this.setState({ markers: nextProps.markers });
}
}
componentWillUnmount() {
this.backButtonListener.remove();
}
goBack() {
this.props.updateMarkers([...this.state.markers]);
this.props.navigation.goBack(null);
}
generateKey() {
return new Date().getTime().toString();
}
addMarker() {
const key = this.generateKey();
this.setState(prevState => ({
markers: [...prevState.markers, { text: prevState.marker, key }],
marker: '',
}));
}
deleteMarker(markerToRemove) {
this.setState(prevState => ({
markers: prevState.markers.filter(marker => marker.key !== markerToRemove.key)
}));
}
editMarker() {
this.setState(prevState => ({
markers: prevState.markers.map(marker => {
if (marker.key === prevState.markerKey) {
return { key: prevState.markerKey, text: prevState.marker };
}
return marker;
}),
marker: '',
markerKey: '',
}));
}
onPressEdit(markerToEdit) {
this.setState({ marker: markerToEdit.text, markerKey: markerToEdit.key, addVisible: true });
}
onPressOk() {
if (this.state.marker.length > 1) {
if (this.state.markerKey.length > 1) {
this.editMarker();
} else {
this.addMarker();
}
this.setState({ addVisible: false });
}
}
_renderRow = (data) => (
<MarkerRow
marker={data}
onPressDelete={() => this.deleteMarker(data)}
onPressEdit={() => this.onPressEdit(data)}
/>
);
alertAddMarker() {
return (
<CustomAlert
visible={this.state.addVisible}
title='Nome do marcador'
buttons={[
{
text: 'CANCELAR',
onPress: () => this.setState({ addVisible: false, marker: '' }),
key: 1,
},
{
text: 'OK',
onPress: () => this.onPressOk(),
key: 2,
},
]}
>
<TextInput
value={this.state.marker}
onChangeText={text => this.setState({ marker: text })}
autoFocus={this.state.addVisible}
onSubmitEditing={() => this.onPressOk()}
placeholder='Nome do marcador'
/>
</CustomAlert>
);
}
render() {
return (
<View style={styles.container}>
<Header
style={{ backgroundColor: '#7325A1' }}
headerLeft={
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<TouchableOpacity onPress={() => this.goBack()} style={{ paddingHorizontal: 8 }}>
<CommunityIcons
name='arrow-left'
size={30}
color='#FFFFFF'
style={styles.icon}
/>
</TouchableOpacity>
<Text
style={{ color: '#fff', paddingLeft: 20, fontSize: 22, fontWeight: 'bold' }}
>
Marcadores
</Text>
</View>
}
/>
{this.alertAddMarker()}
<SortableListView
style={{ flex: 1 }}
data={this.state.markers}
order={Object.keys(this.state.markers)}
onRowMoved={e => {
this.state.markers.splice(e.to, 0, this.state.markers.splice(e.from, 1)[0]);
this.forceUpdate();
}}
renderRow={this._renderRow}
activeOpacity={0.95}
/>
<AddItem onPress={() => this.setState({ addVisible: true })} />
</View>
);
}
}
function mapStateToProps(state) {
return {
markers: state.markersReducer.markers,
};
}
export default connect(mapStateToProps, { getMarkers, updateMarkers })(MarkerEdict);
const styles = StyleSheet.create({
container: {
flex: 1,
},
list: {
flex: 1,
},
});
<file_sep>/app/src/styles/colors.js
export default [
'#FFFFFF',
'#FF8A80',
'#FFD080',
'#FEFE8B',
'#CDFF90',
'#A7FEEB',
'#80D8FE',
'#B388FE',
'#D3B8AF',
'#F9BBD0',
];
<file_sep>/app/src/components/CustomAlert.js
/* @flow */
import React, { Component } from 'react';
import {
Modal,
ScrollView,
StatusBar,
StyleSheet,
Text,
TouchableOpacity,
View,
} from 'react-native';
export default class CustomAlert extends Component {
render() {
return (
<Modal
animationType="fade"
transparent
visible={this.props.visible}
onRequestClose={() => {}}
>
<View style={styles.container}>
<StatusBar backgroundColor='#333' animated />
<View style={styles.alert}>
<Text style={styles.title}>{this.props.title}</Text>
<ScrollView>
{this.props.children}
</ScrollView>
<View style={styles.buttonContainer}>
{this.props.buttons.map(
button => <TouchableOpacity
onPress={() => button.onPress()}
key={button.key}
style={styles.button}
>
<Text style={styles.textButton}>{button.text}</Text>
</TouchableOpacity>
)}
</View>
</View>
</View>
</Modal>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#1119',
paddingVertical: 50,
},
alert: {
backgroundColor: '#fff',
borderRadius: 3,
width: '85%',
paddingVertical: 18,
paddingHorizontal: 25,
},
title: {
fontSize: 16,
fontWeight: 'bold',
color: '#333',
marginBottom: 10,
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'flex-end',
},
button: {
marginHorizontal: 5,
paddingHorizontal: 5,
marginTop: 10,
},
textButton: {
fontSize: 15,
fontWeight: 'bold',
color: '#009688',
},
});
<file_sep>/app/src/containers/ArchiveScreen.js
/* @flow */
import React, { Component } from 'react';
import {
Alert,
View,
ScrollView,
StyleSheet,
StatusBar,
Text,
} from 'react-native';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { connect } from 'react-redux';
import { getNotes, deleteNote, addNote } from '../actions';
import { NAV_EDIT_NOTE } from '../actions/types';
import Item from '../components/Item';
import AlertConfirmPass from '../components/AlertConfirmPass';
import { confirmPass } from '../utils';
class HomeScreen extends Component {
static navigationOptions = ({ navigation }) => ({
headerStyle: { backgroundColor: '#7325A1' },
title: 'Arquivo',
headerTintColor: 'white',
gesturesEnabled: false,
headerLeft: <MaterialIcons
name='menu'
size={30}
color='white'
style={{ marginLeft: 12 }}
onPress={() => {
navigation.navigate('DrawerOpen');
}}
/>
})
state = {
confirmPassVisible: false,
passCorrect: true,
note: null,
}
componentDidMount() {
console.log(this.props);
this.props.getNotes('archive');
}
onPressDelete(note) {
this.setState({ note });
if (note.locked) {
this.setState({ confirmPassVisible: true });
} else {
this.confirmDelete();
}
}
confirmDelete() {
Alert.alert('', 'Mover nota para a lixeira?',
[
{ text: 'CANCELAR', onPress: () => {} },
{ text: 'MOVER',
onPress: () => {
this.props.deleteNote(this.state.note);
this.props.addNote({ ...this.state.note, typeAnnotation: 'trash' });
this.setState({ note: null });
},
}
]
);
}
async confirmPass(pass) {
const passValid = await confirmPass(pass);
this.setState({ passCorrect: false });
if (passValid) {
this.setState({ confirmPassVisible: false, passCorrect: true });
this.confirmDelete();
}
}
emptyState() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<MaterialIcons name='archive' size={70} color='#CFCFCF' />
<Text style={{ fontWeight: 'bold', fontSize: 16 }}>
Suas notas arquivadas aparecem aqui
</Text>
</View>
);
}
alertConfirmPass() {
return (
<AlertConfirmPass
visible={this.state.confirmPassVisible}
correct={this.state.passCorrect}
onPressCancel={() => this.setState({
confirmPassVisible: false, passCorrect: true
})}
onPressConfirm={(pass) => this.confirmPass(pass)}
/>
);
}
render() {
return (
<View style={styles.container}>
<StatusBar backgroundColor='#7325A1' animated />
{this.alertConfirmPass()}
{this.props.notes.length ?
<ScrollView>
<View style={{ paddingVertical: 5 }}>
{this.props.notes.map(note =>
<Item
title={note.title}
note={note.note}
color={note.color}
key={note.key}
locked={note.locked}
onPress={() =>
this.props.navigation.dispatch({ type: NAV_EDIT_NOTE, note })
}
onPressDelete={() => this.onPressDelete(note)}
/>
)}
</View>
</ScrollView>
: this.emptyState() }
</View>
);
}
}
function mapStateToProps(state, props) {
return {
notes: state.archiveReducer.notes
};
}
export default connect(mapStateToProps, { getNotes, deleteNote, addNote })(HomeScreen);
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
<file_sep>/app/src/components/MarkerRow.js
/* @flow */
import React, { Component } from 'react';
import {
Animated,
Easing,
StyleSheet,
Text,
TouchableOpacity,
View,
} from 'react-native';
import CommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
export default class MarkerRow extends Component {
constructor(props) {
super(props);
this._active = new Animated.Value(0);
this._style = {
transform: [{
scale: this._active.interpolate({
inputRange: [0, 1],
outputRange: [1, 1.04],
}),
}],
elevation: this._active.interpolate({
inputRange: [0, 1],
outputRange: [1, 2],
}),
};
}
componentWillReceiveProps(nextProps) {
if (this.props.active !== nextProps.isActive) {
Animated.timing(this._active, {
duration: 300,
easing: Easing.bounce,
toValue: Number(nextProps.isActive),
}).start();
}
}
render() {
return (
<TouchableOpacity
{...this.props.sortHandlers}
>
<Animated.View style={[styles.container, this._style]}>
<View style={styles.icon}>
<CommunityIcons
name='tag'
size={35}
color='#0000009A'
/>
</View>
<View style={styles.textContainer}>
<Text style={styles.text}>{this.props.marker.text}</Text>
</View>
<TouchableOpacity style={styles.icon} onPress={() => this.props.onPressEdit()}>
<MaterialIcons
name='edit'
size={35}
color='#0000009A'
/>
</TouchableOpacity>
<TouchableOpacity style={styles.icon} onPress={() => this.props.onPressDelete()}>
<CommunityIcons
name='delete'
size={35}
color='#0000009A'
/>
</TouchableOpacity>
</Animated.View>
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create({
container: {
height: 55,
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 10,
backgroundColor: '#fff',
elevation: 0,
},
icon: {
paddingHorizontal: 4,
},
textContainer: {
flex: 1,
paddingHorizontal: 4,
},
text: {
fontSize: 16,
},
});
<file_sep>/app/src/utils/index.js
import { AsyncStorage } from 'react-native';
import CryptoJS from 'crypto-js';
export async function confirmPass(pass) {
const cryptoPass = await getCryptoPass();
if (CryptoJS.SHA256(pass).toString(CryptoJS.enc.Hex) === cryptoPass) {
return true;
}
return false;
}
async function getCryptoPass() {
try {
let password;
await AsyncStorage.getItem('password', (err, pass) => {
password = pass;
});
return password;
} catch (e) {
return null;
}
}
export async function hasCryptoPass() {
const pass = await getCryptoPass();
return !!pass;
}
export function savePass(pass) {
const cryptoPass = CryptoJS.SHA256(pass).toString(CryptoJS.enc.Hex);
AsyncStorage.setItem('password', cryptoPass);
}
<file_sep>/app/src/components/AlertSetPass.js
/* @flow */
import React, { Component } from 'react';
import {
Text,
TextInput,
StyleSheet,
} from 'react-native';
import CustomAlert from './CustomAlert';
export default class AlertConfirmPass extends Component {
state = {
pass: '',
check: '',
correct: true,
}
onPressConfirm() {
this.props.onPressConfirm(this.state.pass, this.state.check);
this.setState({ pass: '', check: '', correct: false });
}
onPressCancel() {
this.setState({ pass: '', check: '', correct: true });
this.props.onPressCancel();
}
render() {
return (
<CustomAlert
visible={this.props.visible}
title='Insira uma senha para bloquear a mensagem'
buttons={[
{
text: 'CANCELAR',
onPress: () => this.onPressCancel(),
key: 1,
},
{
text: 'OK',
onPress: () =>
this.onPressConfirm(),
key: 2,
},
]}
>
{
!this.state.correct &&
<Text style={styles.textIncorrect}>
Senhas não coincidem, tente novamente.
</Text>
}
<Text>Senha</Text>
<TextInput
autoFocus
secureTextEntry
autoCapitalize='none'
value={this.state.pass}
onChangeText={text => this.setState({ pass: text })}
onSubmitEditing={() => this.refs.check.focus()}
/>
<Text>Confirme sua senha</Text>
<TextInput
ref='check'
secureTextEntry
autoCapitalize='none'
value={this.state.check}
onChangeText={text => this.setState({ check: text })}
/>
</CustomAlert>
);
}
}
const styles = StyleSheet.create({
textIncorrect: {
color: '#F44336',
},
});
<file_sep>/app/src/containers/Edict.js
/* @flow */
import React, { Component } from 'react';
import {
Alert,
View,
TextInput,
StatusBar,
StyleSheet,
BackHandler,
Platform,
TouchableOpacity,
} from 'react-native';
import { connect } from 'react-redux';
import CommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import CheckBox from 'react-native-checkbox-heaven';
import CryptoJS from 'crypto-js';
import { addNote, updateNote, deleteNote } from '../actions';
import colors from '../styles/colors';
import Header from '../components/Header';
import AlertConfirmPass from '../components/AlertConfirmPass';
import AlertSetPass from '../components/AlertSetPass';
import CustomAlert from '../components/CustomAlert';
import { hasCryptoPass, savePass, confirmPass } from '../utils';
class Edict extends Component {
static navigationOptions = { header: null, drawerLockMode: 'locked-closed' };
constructor(props) {
super(props);
this.backButtonListener = null;
}
state = {
type: 'ADD',
key: '',
title: '',
note: '',
typeAnnotation: 'note',
color: '#FFFFFF',
locked: false,
markersKey: [],
confirmPassVisible: false, // CustomAlert confirm pass
setPassVisible: false, // CustomAlert set pass
setMarkersVisible: false,
passChecked: '',
passCorrect: true,
noteIsCrypto: false,
}
componentWillMount() {
if (this.props.navigation.state.params) {
const {
key,
title,
color,
locked,
typeAnnotation,
markersKey,
} = this.props.navigation.state.params.note;
this.setState({
type: 'UPDATE',
key,
title,
color,
locked,
typeAnnotation,
markersKey: [...markersKey],
});
if (locked) {
this.setState({ confirmPassVisible: true, noteIsCrypto: true });
} else {
const note = this.props.navigation.state.params.note.note;
this.setState({ note });
}
} else {
const key = this.generateKey();
this.setState({ key });
}
}
componentDidMount() {
this.backButtonListener = BackHandler.addEventListener('hardwareBackPress', () => {
if (this.props.navigation.state.routeName === 'edict') {
this.goBack();
return true;
}
return false;
});
}
componentWillUnmount() {
this.backButtonListener.remove();
}
actionGoBack() {
this.props.navigation.goBack(null);
}
generateKey() {
return new Date().getTime().toString();
}
noteIsValid() {
return this.state.title !== '' || this.state.note !== '';
}
getNoteToSave() {
let noteToSave;
if (this.state.locked) {
noteToSave = CryptoJS.AES.encrypt(this.state.note, this.state.passChecked).toString();
} else {
noteToSave = this.state.note;
}
const note = {
key: this.state.key,
title: this.state.title,
note: noteToSave,
color: this.state.color,
typeAnnotation: this.state.typeAnnotation,
locked: this.state.locked,
markersKey: [...this.state.markersKey],
};
return note;
}
goBack() {
this.saveNote();
this.actionGoBack();
}
archive() {
if (this.noteIsValid()) {
const note = this.getNoteToSave();
this.props.deleteNote(note);
this.props.addNote({ ...note, typeAnnotation: 'archive' });
this.actionGoBack();
}
}
unarchive() {
const note = this.getNoteToSave();
this.props.deleteNote(note);
this.props.addNote({ ...note, typeAnnotation: 'note' });
this.actionGoBack();
}
delete() {
if (this.noteIsValid()) {
if (this.state.typeAnnotation === 'trash') {
Alert.alert('', 'Apagar nota definitivamente?',
[
{ text: 'CANCELAR', onPress: () => {} },
{ text: 'APAGAR', onPress: () => this.onDeleteNote() }
]
);
} else {
Alert.alert('', 'Mover nota para a lixeira?',
[
{ text: 'CANCELAR', onPress: () => {} },
{ text: 'MOVER', onPress: () => this.onDeleteNote() }
]
);
}
}
}
restore() {
const note = this.getNoteToSave();
this.props.deleteNote(note);
this.props.addNote({ ...note, typeAnnotation: 'note' });
this.actionGoBack();
}
onDeleteNote() {
const note = this.getNoteToSave();
if (this.state.type === 'UPDATE') {
this.props.deleteNote(note);
}
if (note.typeAnnotation !== 'trash') {
this.props.addNote({ ...note, typeAnnotation: 'trash' });
}
this.actionGoBack();
}
saveNote() {
if (this.noteIsValid()) {
const note = this.getNoteToSave();
if (this.state.type === 'ADD') {
this.props.addNote(note);
} else {
this.props.updateNote(note);
}
}
}
async onPressLock() {
const hasPass = await hasCryptoPass();
if (this.state.locked) {
this.setState({ locked: false });
} else if (!this.state.passChecked) {
if (hasPass) {
this.setState({ confirmPassVisible: true });
} else {
this.setState({ setPassVisible: true });
}
} else {
this.setState({ locked: true });
}
}
checkPass(pass, passCheck) {
if (pass !== '' && pass === passCheck) {
this.setState({ setPassVisible: false, passChecked: pass, locked: true });
savePass(pass);
}
}
async confirmPass(pass) {
const passValid = await confirmPass(pass);
this.setState({ passCorrect: false });
if (passValid) {
if (this.state.noteIsCrypto) {
const cryptoNote = this.props.navigation.state.params.note.note;
const note = CryptoJS.AES.decrypt(cryptoNote, pass).toString(CryptoJS.enc.Utf8);
this.setState({ noteIsCrypto: false, note });
}
this.setState({
passChecked: pass,
confirmPassVisible: false,
locked: true,
passCorrect: true,
});
}
}
cancelConfirmationPass() {
this.setState({ confirmPassVisible: false, passCorrect: true });
if (this.state.noteIsCrypto) {
this.actionGoBack();
}
}
markerChecked(key) {
for (const markerKey in this.props.markersKey) {
if (key === markerKey) {
return true;
}
}
return false;
}
headerButton() {
if (this.state.typeAnnotation === 'note') {
return (
<TouchableOpacity onPress={() => this.archive()}>
<MaterialIcons
name='archive'
size={30}
color='#0000009A'
style={styles.icon}
/>
</TouchableOpacity>
);
} else if (this.state.typeAnnotation === 'archive') {
return (
<TouchableOpacity onPress={() => this.unarchive()}>
<MaterialIcons
name='unarchive'
size={30}
color='#0000009A'
style={styles.icon}
/>
</TouchableOpacity>
);
}
return (
<TouchableOpacity onPress={() => this.restore()}>
<CommunityIcons
name='delete-restore'
size={30}
color='#0000009A'
style={styles.icon}
/>
</TouchableOpacity>
);
}
header() {
return (
<Header
style={{ backgroundColor: this.state.color }}
headerLeft={
<TouchableOpacity onPress={() => this.goBack()}>
<CommunityIcons
name='arrow-left'
size={30}
color='#0000009A'
style={styles.icon}
/>
</TouchableOpacity>
}
headerRight={
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
{
this.state.typeAnnotation !== 'trash' &&
<TouchableOpacity onPress={() => this.setState({ setMarkersVisible: true })}>
<CommunityIcons
name='tag'
size={28}
color='#0000009A'
style={styles.icon}
/>
</TouchableOpacity>
}
{
this.state.typeAnnotation !== 'trash' &&
<TouchableOpacity onPress={() => this.onPressLock()}>
<CommunityIcons
name={this.state.locked ? 'lock' : 'lock-open'}
size={28}
color='#0000009A'
style={styles.icon}
/>
</TouchableOpacity>
}
{this.headerButton()}
<TouchableOpacity onPress={() => this.delete()}>
<CommunityIcons
name='delete'
size={30}
color='#0000009A'
style={styles.icon}
/>
</TouchableOpacity>
</View>
}
/>
);
}
alertConfirmPass() {
return (
<AlertConfirmPass
visible={this.state.confirmPassVisible}
correct={this.state.passCorrect}
onPressCancel={() => this.cancelConfirmationPass()}
onPressConfirm={(pass) => this.confirmPass(pass)}
/>
);
}
alertSetPass() {
return (
<AlertSetPass
visible={this.state.setPassVisible}
onPressCancel={() => this.setState({ setPassVisible: false })}
onPressConfirm={(pass, check) => this.checkPass(pass, check)}
/>
);
}
alertMarkers() {
return (
<CustomAlert
visible={this.state.setMarkersVisible}
title='Selecione os marcadores para esta nota'
buttons={[
{
text: 'OK',
onPress: () => this.setState({ setMarkersVisible: false }),
key: 1,
},
]}
>
{
this.props.markers.map(marker => (
<CheckBox
key={marker.key}
label={marker.text}
labelStyle={styles.labelStyle}
iconSize={28}
iconName='matMix'
checked={this.state.markersKey.indexOf(marker.key) !== -1}
checkedColor='#7325A1'
uncheckedColor='#0000009A'
onChange={
(val) => {
if (val) {
this.setState(prevState => ({
markersKey: [...prevState.markersKey, marker.key]
}));
} else {
this.setState(prevState => ({
markersKey: prevState.markersKey.filter(markerKey => markerKey !== marker.key)
}));
}
}
}
/>
))
}
</CustomAlert>
);
}
render() {
return (
<View style={[styles.container, { backgroundColor: this.state.color }]}>
{
Platform.Version >= 23 &&
<StatusBar backgroundColor={this.state.color} barStyle='dark-content' />
}
{this.header()}
{this.alertConfirmPass()}
{this.alertSetPass()}
{this.alertMarkers()}
<View style={{ flex: 1, padding: 8 }}>
<TextInput
value={this.state.title}
onChangeText={text => this.setState({ title: text })}
autoFocus={!this.props.navigation.state.params}
editable={this.state.typeAnnotation === 'note'}
placeholder='Título'
underlineColorAndroid='transparent'
style={{ fontSize: 18, fontWeight: 'bold', color: '#111' }}
onSubmitEditing={() => this.refs.nota.focus()}
/>
<View style={{ flex: 1 }}>
<TextInput
ref='nota'
value={this.state.note}
onChangeText={text => this.setState({ note: text })}
editable={this.state.typeAnnotation === 'note'}
placeholder='Nota'
underlineColorAndroid='transparent'
multiline
style={{ flex: 1, textAlignVertical: 'top', color: '#333' }}
/>
</View>
{
this.state.typeAnnotation !== 'trash' &&
<View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
{colors.map(color => <TouchableOpacity
key={color}
style={[styles.colorBox, { backgroundColor: color }]}
onPress={() => this.setState({ color })}
/>)}
</View>
}
</View>
</View>
);
}
}
function mapStateToProps(state) {
return {
markers: state.markersReducer.markers,
};
}
export default connect(mapStateToProps, { addNote, updateNote, deleteNote })(Edict);
const styles = StyleSheet.create({
container: {
flex: 1,
},
colorBox: {
height: 30,
width: 30,
borderRadius: 2,
elevation: 2,
},
icon: {
marginHorizontal: 7,
},
});
| b507aaa2dbaae58f71122ea4b9412c8c8a1e2df2 | [
"JavaScript",
"Markdown"
] | 16 | JavaScript | ghsantos/Notes | e35dc1bc676738f3c54b2b99e3cbe570dcfe877b | 89d383a290c5f7027a66513868ab05b47587f962 |
refs/heads/master | <file_sep><?php
require_once 'database.php';
require_once 'operations.php';
$system_obj = new login_registration();
// Redirect after login
if ($system_obj->get_session()) {
header('Location : index.php');
exit();
}
// Catch value for registration
if (basename($_SERVER['PHP_SELF'])=='registration.php'):
#check page because we are doing multi form in one page
if ($_SERVER['REQUEST_METHOD']=='POST' && isset($_POST['register']))
{
$username = $_POST['username'];
$password = md5($_POST['password']);
$name = $_POST['name'];
$email = $_POST['email'];
$website = $_POST['website'];
if ( empty($username) or empty($password) or empty($name) or empty($email) or empty($website) )
{
echo "<span class=\"error\">ERROR.. Must Fill all Field</span>";
}else
{
$register = $system_obj->registration($username, $password, $name, $email, $website);
if ($register)
{
header('Location : index.php');
}else
{
echo "<center class=\"error\">ERROR.. Username and Password already taken!</center>";
}
}
}
endif; #end Check page
// Login
if (basename($_SERVER['PHP_SELF'])=='login.php'):
#check page because we are doing multi form in one page
if (isset($_POST['login']) && $_SERVER['REQUEST_METHOD']=='POST')
{
$email = $_POST['email'];
$password = $_POST['<PASSWORD>'];
if (empty($email) || empty($password))
{
echo "<center class=\"error\">ERROR.. Must fill all field!!</center>";
}else
{
$password = md5($password);
$login = $system_obj->login($email, $password);
if (!$login)
{
header('Location: index.php');
}else
{
echo "<center class=\"error\">ERROR.. Username and Password not match!</center>";
}
}
}
endif;# end check page
// View Profile
if (basename($_SERVER['PHP_SELF'])=='index.php'):
#check page because we are doing multi form in one page
endif;# end check page <file_sep><?php
include_once 'functions.php';
session_start();
$uid = $_SESSION['uid'];
$uname = $_SESSION['uname'];
if (!$system_obj->get_session()) {
header('Location: login.php');
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login || Registration System</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="body">
<section class="header">
<h2>Login || Registration System</h2>
</section>
<section class="menu">
<ul>
<?php if ($system_obj->get_session()) { ?>
<li><a href="index.php">Home</a></li>
<li>Show Profile</li>
<li>Update Profile</li>
<li>Logout</li>
<?php } else{?>
<li><a href="login.php">Login</a></li>
<li><a href="registration.php">Registration</a></li>
<?php } ?>
</ul>
</section>
<section class="user">
<div class="uname">
<h3>Welcome
<?php
if (isset($uname)) {
echo $uname;
}else{
echo "GUST";
} ?>
</h3>
</div>
</section><file_sep><?php include_once 'header.php';
include_once 'functions.php';
?>
<section class="users">
<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>View Details</th>
</tr>
<?php
$allusers = $system_obj->getAllUser();
foreach ( $allusers as $user) {
?>
<tr>
<td><?php echo $user['id']; ?></td>
<td><?php echo $user['name']; ?></td>
<td><?php echo $user['email']; ?></td>
<td><a href="profile.php?id=<?php echo $user['id']; ?>">View Details</a></td>
</tr>
<?php } ?>
</table>
</section>
<?php include 'footer.php';
<file_sep><?php
require 'config.php';
/**
* Database Connection
*/
class DB_Connection
{
public function __construct()
{
global $pdo;
try {
$pdo = new PDO('mysql:host='.DB_HOST.'; dbname='.DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e) {
exit('Database error!!');
}
}
}
<file_sep><?php include 'header.php';
include 'functions.php';
?>
<section class="registration">
<form name="reg" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<table>
<tr>
<td>Username</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="<PASSWORD>" name="password"></td>
</tr>
<tr>
<td>Full Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="email" name="email"></td>
</tr>
<tr>
<td>Website</td>
<td><input type="text" name="website"></td>
</tr>
<tr>
<td></td>
<td>
<input type="reset" name="reset" value="Reset">
<input type="submit" name="register" value="Submit">
</td>
</tr>
</table>
</from>
</section>
<?php include 'footer.php';
<file_sep><?php
require_once 'functions.php';
/**
* All Operation will Go Here
*/
class login_registration
{
public $table = DB_TABLE;
function __construct()
{
$database = new DB_Connection();
}
// Registration
public function registration($username, $password, $name, $email, $website)
{
global $pdo; # Object of DB Connection
$query = $pdo->prepare("SELECT id FROM $this->table WHERE username = ? AND password = ?");
$query->execute(array($username, $password));
$num = $query->rowCount();
if ($num == 0) {
$sql = $pdo->prepare("INSERT INTO $this->table(username, password, name, email, website) VALUES(?, ?, ?, ?, ?)");
$sql->execute(array($username, $password, $name, $email, $website));
return true;
}else{
echo "<span class=\"error\">ERROR.. Username and Password already taken!</span>";
}
$query->close();
$pdo ->close();
}
// Login
public function login($email, $password)
{
global $pdo;
$query = $pdo->prepare("SELECT id, username FROM $this->table WHERE email =? AND password =?");
$query->execute(array($email, $password));
$user_data = $query->fetch();
$num = $query->rowCount();
if ($num == 1) {
session_start();
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['id'];
$_SESSION['uname'] = $user_data['username'];
$_SESSION['login_meg'] = 'Login Successful..';
return true;
}else
{
return false;
}
}
// Show all user
public function getAllUser(){
global $pdo;
$sql = $pdo->prepare("SELECT * FROM $this->table ORDER BY id ASC");
$sql->execute();
return $sql->fetchAll(PDO::FETCH_ASSOC);
}
// Login session
public function get_session(){
return @$_SESSION['login'];
}
} | b241d0280e8afa6c0e507f70d73cab0f3befb16c | [
"PHP"
] | 6 | PHP | shapon-pal/PHP-MySQL-login-system | 74b4354f8073c825d940652d9513b100a8bae10d | 630eeb4fbfacc40103622cba156c91713da58b4c |
refs/heads/master | <file_sep>export function onShare(res, nickName, gender, fromId) {
let genderTxt = 'Ta';
if(gender == 1) genderTxt = '他';
if(gender == 2) genderTxt = '她';
return {
title: nickName+"邀请您参观"+genderTxt+"的Home",
path: "/pages/share/main?from=" + encodeURIComponent(fromId),
success: function(res) {
console.log(JSON.stringify(res) + "转发成功")
},
fail: function(res) {
console.log(JSON.stringify(res) + "转发失败")
}
}
}
| cbedfd2589a31d431657aa6237adb0aa47d19828 | [
"JavaScript"
] | 1 | JavaScript | GEEK-SHARK/geek-shark | 46c39ba7c8778eb55ae0ca51d2904caae98b6837 | b70cca7fcbeeabfc72960851dcad1f24c2da01c3 |
refs/heads/master | <repo_name>westernknight/CamPath<file_sep>/Assets/CamPath/FunnyCamera.cs
#region 模块信息
/*----------------------------------------------------------------
// Copyright (C) 2015 广州,蓝弧
//
// 模块名:FTD
// 创建者:张嘉俊
// 修改者列表:
// 创建日期:2/18/2016
// 模块描述:
//----------------------------------------------------------------*/
#endregion
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(TouchScript))]
public class FunnyCamera : MonoBehaviour
{
public static FunnyCamera instance;
public enum CameraProperty
{
Freedom,//全局
FollowObject,//焦点跟随物体
AttachObject,//摄像机位置方向跟随物体
}
#region Public Variable Region
public GameObject cameraPropertyObject;
/// <summary>
/// 是否锁上camera不能由玩家操控
/// </summary>
public bool isLockInput = false;
public CameraProperty cameraProperty = CameraProperty.Freedom;
[Range(0, 1)]
public float rollParam = 1;
/// <summary>
/// 缩放最大位移,鼠标滚轮每次增加0.1左右
/// </summary>
public float accumulateZoomMax = 0.5f;
/// <summary>
/// 玩家是否在控制镜头,如果是,不对游戏角色进行操控
/// </summary>
public bool isPlayerCharging = false;
public float boundingSphereRadius = 0.5f;
public LayerMask collisionMask = -1;
#endregion
#region Private Variable Region
/// <summary>
/// 焦点对象,默认是CamPathManager.instance.charactorName
/// </summary>
GameObject focusObject;
/// <summary>
/// 记录鼠标上次的位置
/// </summary>
Vector3 lastMousePosition;
/// <summary>
/// 摄像机到焦点的距离
/// </summary>
[HideInInspector]
float distance = 3;
/// <summary>
/// 为了使用transform的函数算法,摄像机底下增加了一个calculationParam的对象用于算法使用
/// </summary>
GameObject calculationParam;
/// <summary>
/// 没有缩放的实际up camera Pos
/// </summary>
Vector3 upCameraPosition;
/// <summary>
/// 缩放累计值
/// </summary>
float accumulateZoom = 0.1f;
/// <summary>
/// 初始化Pos
/// </summary>
Vector3 maxPos;
/// <summary>
/// 初始化Pos
/// </summary>
Vector3 minPos;
/// <summary>
/// 初始化Pos
/// </summary>
Quaternion maxRot;
/// <summary>
/// 初始化Pos
/// </summary>
Quaternion minRot;
/// <summary>
/// 没有缩放的实际 Pos
/// </summary>
Vector3 actuallyPos;
/// <summary>
/// 屏幕width/2转为世界坐标的宽度
/// </summary>
float cameraWorldWidth;
/// <summary>
/// 屏幕height/2转为世界坐标的宽度
/// </summary>
float cameraWorldHeight;
/// <summary>
/// 初始化顶视角camera的位置,是通过fullMax camera与焦点计算出来的
/// </summary>
Vector3 initUpCameraPosition;
bool isLerpTarget = false;
Vector3 targetPosition;
Quaternion targetRotation;
//fov
float hfovRad;
float wfovRad;
float hfovAngle;
float wfovAngle;
//最大摄像机绕焦点旋转的角度
float mapAngle;
#endregion
#region System Callback Function Region
void Awake()
{
instance = this;
}
void Start()
{
maxPos = GameObject.Find(CamPathManager.instance.fullMapCameraMaxName).transform.position;
minPos = GameObject.Find(CamPathManager.instance.fullMapCameraMinName).transform.position;
maxRot = GameObject.Find(CamPathManager.instance.fullMapCameraMaxName).transform.rotation;
minRot = GameObject.Find(CamPathManager.instance.fullMapCameraMinName).transform.rotation;
transform.position = actuallyPos = maxPos;
transform.rotation = maxRot;
isLerpTarget = false;
TargetToPositionAndRotation(transform.position, transform.rotation);
focusObject = GameObject.Find(CamPathManager.instance.charactorName);
if (focusObject)
{
distance = Vector3.Distance(transform.position, focusObject.transform.position);
//现在的方向 摄像机-焦点
Vector3 currentDirect = maxPos - focusObject.transform.position;
//计算现在的方向投影到xz平面上
Vector3 currentDirectToXZPlaneVec = currentDirect;
currentDirectToXZPlaneVec.y = 0;
//最终保存角度
mapAngle = Vector3.Angle(currentDirectToXZPlaneVec, Vector3.right);//x轴对着镜头,所以是以Vector3.right轴取角度
}
accumulateZoom = accumulateZoomMax;
calculationParam = new GameObject("calc");
calculationParam.transform.parent = transform;
calculationParam.transform.localRotation = Quaternion.identity;
if (focusObject)
{
initUpCameraPosition = upCameraPosition = distance * focusObject.transform.up + focusObject.transform.position;
}
hfovRad = Camera.main.fieldOfView / 2 * Mathf.Deg2Rad;
wfovRad = Mathf.Atan((float)Screen.width / (float)Screen.height * Mathf.Tan(hfovRad));
hfovAngle = Camera.main.fieldOfView / 2;
wfovAngle = wfovRad * Mathf.Rad2Deg;
cameraWorldWidth = Mathf.Tan(wfovRad) * distance;
cameraWorldHeight = Mathf.Tan(hfovRad) * distance;
}
void OnDrawGizmos()
{
if (Application.isPlaying)
{
Gizmos.color = Color.white;
Vector3 focusPoint = transform.forward * distance + transform.position;
Gizmos.DrawWireSphere(focusPoint, 0.5f);
Gizmos.DrawWireSphere(upCameraPosition, 0.5f);
Gizmos.DrawWireSphere(transform.position, boundingSphereRadius);
//画出摄像机四边到平面的4个点
//Vector3 tmp = upCameraPosition;
//tmp.y = 0;
//Gizmos.DrawWireSphere(tmp - point1, 0.5f);
//Gizmos.DrawWireSphere(tmp - point2, 0.5f);
//Gizmos.DrawWireSphere(tmp - point3, 0.5f);
//Gizmos.DrawWireSphere(tmp - point4, 0.5f);
}
}
/// <summary>
/// 摄像机移动补帧
/// </summary>
/// <param name="targetVector"></param>
/// <param name="targetQuaternion"></param>
void TargetToPositionAndRotation(Vector3 targetVector, Quaternion targetQuaternion)
{
if (isLerpTarget)
{
targetPosition = targetVector;
targetRotation = targetQuaternion;
}
else
{
targetPosition = targetVector;
targetRotation = targetQuaternion;
transform.position = targetVector;
transform.rotation = targetQuaternion;
}
}
bool trigger = false;
Vector3 lastColPos;
void OnTriggerEnter(Collider col)
{
trigger = true;
}
void OnTriggerExit(Collider col)
{
trigger = false;
}
void Update()
{
///是否用缓动
transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * 10);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 10);
if (isLockInput)
{
return;
}
if (cameraProperty == CameraProperty.AttachObject)
{
if (cameraPropertyObject != null)
{
isLerpTarget = false;
TargetToPositionAndRotation(cameraPropertyObject.transform.position, cameraPropertyObject.transform.rotation);
}
return;
}
else if (cameraProperty == CameraProperty.FollowObject)
{
if (cameraPropertyObject != null)
{
isLerpTarget = true;
Vector3 tmp = upCameraPosition;
tmp = cameraPropertyObject.transform.position;
tmp.y = upCameraPosition.y;
ReCalculateCameraPosition(tmp);
}
}
else if (cameraProperty == CameraProperty.Freedom)
{
isLerpTarget = false;
}
if (TouchScript.Instance.IsZooming())
{
isPlayerCharging = true;
accumulateZoom += -TouchScript.Instance.zoom;
if (accumulateZoom > accumulateZoomMax)
{
accumulateZoom = accumulateZoomMax;
}
else if (accumulateZoom < 0)
{
accumulateZoom = 0;
}
float tmpRoll = rollParam;
float tmpDistance = distance;
rollParam = accumulateZoom / accumulateZoomMax;
lastMousePosition = Vector3.zero;
if (focusObject)
{
distance = Vector3.Distance(focusObject.transform.position, Vector3.Lerp(minPos, maxPos, rollParam));
}
bool success = ReCalculateCameraPosition(upCameraPosition);
if (!success)
{
rollParam = tmpRoll;
distance = tmpDistance;
}
}
else if (TouchScript.Instance.IsSliding() && cameraProperty == CameraProperty.Freedom)
{
isPlayerCharging = true;
if (lastMousePosition == Vector3.zero)
{
lastMousePosition = Input.mousePosition;
}
else
{
Vector3 newMousePos = Input.mousePosition;
Vector3 delta = TouchScript.Instance.slide;
float hfovy = Camera.main.fieldOfView / 2;
float z = Screen.height / 2 / Mathf.Tan(hfovy * Mathf.Deg2Rad);
Vector3 brelpos = new Vector3();
brelpos.x = delta.y / z * distance;//原来是brelpos.y = -delta.y / z * distance ;转平面,但会产生夹角
brelpos.z = -delta.x / z * distance;
//控制摄像机范围
Vector3 direct = Quaternion.AngleAxis(mapAngle, Vector3.up) * (-brelpos);
ReCalculateCameraPosition(upCameraPosition + direct);
lastMousePosition = newMousePos;
}
}
else
{
isPlayerCharging = false;
lastMousePosition = Vector3.zero;
}
}
/// <summary>
///
/// </summary>
/// <param name="targetPos"></param>
/// <returns>计算后是否改变了Camera,没有改变说明Camera碰撞了</returns>
bool ReCalculateCameraPosition(Vector3 targetPos)
{
//计算roll之后的local pos
calculationParam.transform.position = initUpCameraPosition;
Vector3 lerpCameraLocalPos = calculationParam.transform.InverseTransformPoint(Vector3.Lerp(minPos, maxPos, rollParam));
Vector3 tmp = upCameraPosition;
upCameraPosition = targetPos;
//4-3
//| |
//1-2
//ray cast to floor
calculationParam.transform.position = upCameraPosition;
//local pos转为世界坐标就是实际坐标actuallyPos
actuallyPos = calculationParam.transform.TransformPoint(lerpCameraLocalPos);
RaycastHit hitInfo;
if (!Physics.SphereCast(transform.position, 0.5f, actuallyPos - transform.position, out hitInfo, (actuallyPos - transform.position).magnitude, collisionMask))
{
TargetToPositionAndRotation(actuallyPos, Quaternion.Lerp(minRot, maxRot, rollParam));
return true;
}
else
{
upCameraPosition = tmp;
return false;
}
}
#endregion
#region Private Custom Function Region
#if false
private void CentrePositionTrace()
{
centrePositionRay.origin = transform.position;
centrePositionRay.direction = transform.forward;
if (Physics.Raycast(centrePositionRay, out rayInfo))
{
//其实这里是做击中判断操作
centrePosition = rayInfo.point;
}
}
private void MapLitmitCalculate()
{
real_width = distance * Screen.width * Mathf.Tan(Camera.main.fieldOfView / 2 * Mathf.Deg2Rad) / Screen.height;
real_height = distance * Mathf.Tan(Camera.main.fieldOfView / 2 * Mathf.Deg2Rad);
centrePositionRay = new Ray(transform.position, transform.forward);
}
private void MapLitmitJudge(ref Vector3 Pos)
{
return;
if (centrePosition.z + Mathf.Abs(Pos.z) + real_width > litmit_maxZ)
{
Pos.z -= centrePosition.z + Mathf.Abs(Pos.z) + real_width - litmit_maxZ;
//Pos.z = litmit_maxZ - real_width;
}
if (centrePosition.z - Mathf.Abs(Pos.z) - real_width < litmit_minZ)
{
Pos.z += litmit_minZ - (centrePosition.z - Mathf.Abs(Pos.z) - real_width);
}
if (centrePosition.x + Mathf.Abs(Pos.x) + real_height > litmit_maxX)
{
Pos.x -= centrePosition.x + Mathf.Abs(Pos.x) + real_height - litmit_maxX;
}
if (centrePosition.x - Mathf.Abs(Pos.x) - real_height < litmit_minX)
{
Pos.x += litmit_minX - (centrePosition.x - Mathf.Abs(Pos.x) - real_height);
}
}
#endif
#endregion
}
<file_sep>/Assets/CamPath/CamPathCharactorPosition.cs
#region 模块信息
/*----------------------------------------------------------------
// Copyright (C) 2015 广州,蓝弧
//
// 模块名:FTD
// 创建者:张嘉俊
// 修改者列表:
// 创建日期:2/22/2016
// 模块描述:
//----------------------------------------------------------------*/
#endregion
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CamPathCharactorPosition : MonoBehaviour {
[HideInInspector]
public Vector3 position;
void Start () {
}
void Update () {
}
}
<file_sep>/Assets/CamPath/Editor/CamPathCharactorPositionEditor.cs
#region 模块信息
/*----------------------------------------------------------------
// Copyright (C) 2015 广州,蓝弧
//
// 模块名:FTD
// 创建者:张嘉俊
// 修改者列表:
// 创建日期:2/22/2016
// 模块描述:
//----------------------------------------------------------------*/
#endregion
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
[CustomEditor(typeof(CamPathCharactorPosition))]
public class CamPathCharactorPositionEditor : Editor
{
CamPathCharactorPosition script;
GUIStyle style = new GUIStyle();
void OnEnable()
{
style.fontStyle = FontStyle.Bold;
style.normal.textColor = Color.white;
script = (CamPathCharactorPosition)target;
if (script.gameObject.name == "Position Start")
{
script.transform.localPosition = Vector3.zero;
}
CameraFullMapMaxPreview();
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
}
public void CameraFullMapMaxPreview()
{
Vector3 offset = GameObject.Find("CamPathManager").transform.position - script.transform.position;
GameObject go = new GameObject("tmp");
go.transform.position = GameObject.Find("Camera Full Map Max").transform.position - offset;
go.transform.rotation = GameObject.Find("Camera Full Map Max").transform.rotation;
if (SceneView.currentDrawingSceneView)
{
SceneView.currentDrawingSceneView.AlignViewToObject(go.transform);
}
GameObject.DestroyImmediate(go);
}
public static SceneView GetSceneView()
{
SceneView view = SceneView.currentDrawingSceneView;
if (view == null)
view = EditorWindow.GetWindow<SceneView>();
return view;
}
public void OnSceneGUI()
{
script.position = script.transform.position;
for (int i = 0; i < script.transform.parent.childCount; i++)
{
CamPathCharactorPosition obj = script.transform.parent.GetChild(i).GetComponent<CamPathCharactorPosition>();
if (obj)
{
//Handles.PositionHandle(obj.transform.position, obj.transform.rotation);
Handles.SphereCap(0, obj.transform.position, Quaternion.identity, 1);
Handles.Label(obj.transform.position, obj.gameObject.name, style);
}
else
{
//monster
}
}
//Handles.Label(script.transform.position, script.gameObject.name, style);
//Handles.SphereCap(0, script.transform.position, Quaternion.identity, 1);
}
}
<file_sep>/Assets/CamPath/Editor/ExtensionMethodsEditor.cs
#region 模块信息
/*----------------------------------------------------------------
// Copyright (C) 2015 广州,蓝弧
//
// 模块名:FTD
// 创建者:张嘉俊
// 修改者列表:
// 创建日期:2/22/2016
// 模块描述:
//----------------------------------------------------------------*/
#endregion
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using System.IO;
public static class ExtensionMethodsEditor
{
public static void SaveChildObjectPropertyToJsonFile(GameObject gameObject)
{
SaveChildObjectPropertyToJsonFile(gameObject, gameObject.name, "");
}
public static void SaveChildObjectPropertyToJsonFile(GameObject gameObject,string jsonFileName,string folder)
{
if (string.IsNullOrEmpty(folder))
{
}
else if (!folder.Contains("/"))
{
folder += "/";
}
string path = Application.streamingAssetsPath + "/Config/" +folder+ jsonFileName + ".json";
string dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
LitJson.JsonData allData = new LitJson.JsonData();
allData.SetJsonType(LitJson.JsonType.Array);
{
LitJson.JsonData property = new LitJson.JsonData();
property.SetJsonType(LitJson.JsonType.Array);
Transform t = gameObject.transform;
LitJson.JsonData name = new LitJson.JsonData();
name = t.name;
LitJson.JsonData pos = new LitJson.JsonData();
pos.SetJsonType(LitJson.JsonType.Array);
pos.Add(t.position.x);
pos.Add(t.position.y);
pos.Add(t.position.z);
LitJson.JsonData rot = new LitJson.JsonData();
rot.SetJsonType(LitJson.JsonType.Array);
rot.Add(t.rotation.x);
rot.Add(t.rotation.y);
rot.Add(t.rotation.z);
rot.Add(t.rotation.w);
property.Add(name);
property.Add(pos);
property.Add(rot);
allData.Add(property);
}
for (int i = 0; i < gameObject.transform.childCount; i++)
{
LitJson.JsonData property = new LitJson.JsonData();
property.SetJsonType(LitJson.JsonType.Array);
Transform t = gameObject.transform.GetChild(i);
LitJson.JsonData name = new LitJson.JsonData();
name = t.name;
LitJson.JsonData pos = new LitJson.JsonData();
pos.SetJsonType(LitJson.JsonType.Array);
pos.Add(t.position.x);
pos.Add(t.position.y);
pos.Add(t.position.z);
LitJson.JsonData rot = new LitJson.JsonData();
rot.SetJsonType(LitJson.JsonType.Array);
rot.Add(t.rotation.x);
rot.Add(t.rotation.y);
rot.Add(t.rotation.z);
rot.Add(t.rotation.w);
property.Add(name);
property.Add(pos);
property.Add(rot);
allData.Add(property);
}
FileInfo fi = new FileInfo(path);
StreamWriter sw = new StreamWriter(fi.Create());
sw.Write(LitJson.JsonMapper.ToJson(allData));
sw.Close();
Debug.Log("save ok: " + path);
}
public static void ReadJsonFileDataToChildObjectProperty(GameObject gameObject)
{
ReadJsonFileDataToChildObjectProperty(gameObject, gameObject.name,"");
}
public static void ReadJsonFileDataToChildObjectProperty(GameObject gameObject, string jsonFileName, string folder)
{
if (string.IsNullOrEmpty(folder))
{
}
else if (!folder.Contains("/"))
{
folder += "/";
}
string path = Application.streamingAssetsPath + "/Config/" + gameObject.name + ".json";
FileInfo fi = new FileInfo(path);
if (fi != null)
{
if (fi.Exists)
{
while (gameObject.transform.childCount!=0)
{
GameObject.DestroyImmediate(gameObject.transform.GetChild(0).gameObject);
}
StreamReader sr = new StreamReader(fi.OpenRead());
string json = sr.ReadToEnd();
sr.Close();
LitJson.JsonData allData = LitJson.JsonMapper.ToObject(json);
if (allData.IsArray)
{
{
LitJson.JsonData property = allData[0];
LitJson.JsonData nameProperty = property[0];
gameObject.name = (string)nameProperty;
LitJson.JsonData posProperty = property[1];
Vector3 pos = new Vector3((float)(double)posProperty[0], (float)(double)posProperty[1], (float)(double)posProperty[2]);
LitJson.JsonData rotProperty = property[2];
Quaternion rot = new Quaternion((float)(double)rotProperty[0], (float)(double)rotProperty[1], (float)(double)rotProperty[2], (float)(double)rotProperty[3]);
gameObject.transform.position = pos;
gameObject.transform.rotation = rot;
}
for (int i = 1; i < allData.Count; i++)
{
GameObject go = new GameObject();
go.transform.parent = gameObject.transform;
LitJson.JsonData property = allData[i];
LitJson.JsonData nameProperty = property[0];
go.name = (string)nameProperty;
LitJson.JsonData posProperty = property[1];
Vector3 pos = new Vector3((float)(double)posProperty[0], (float)(double)posProperty[1], (float)(double)posProperty[2]);
LitJson.JsonData rotProperty = property[2];
Quaternion rot = new Quaternion((float)(double)rotProperty[0], (float)(double)rotProperty[1], (float)(double)rotProperty[2], (float)(double)rotProperty[3]);
go.transform.position = pos;
go.transform.rotation = rot;
}
}
Debug.Log("load ok: " + path);
}
}
}
}
<file_sep>/Assets/CamPath/CamPathObject.cs
#region 模块信息
/*----------------------------------------------------------------
// Copyright (C) 2015 广州,蓝弧
//
// 模块名:FTD
// 创建者:张嘉俊
// 修改者列表:
// 创建日期:2/17/2016
// 模块描述:
//----------------------------------------------------------------*/
#endregion
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CamPathObject : MonoBehaviour {
void Start () {
}
void Update () {
}
}
<file_sep>/Assets/CamPath/Editor/CamPathPreViewEditor.cs
#region 模块信息
/*----------------------------------------------------------------
// Copyright (C) 2015 广州,蓝弧
//
// 模块名:FTD
// 创建者:张嘉俊
// 修改者列表:
// 创建日期:2/18/2016
// 模块描述:
//----------------------------------------------------------------*/
#endregion
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
[CustomEditor(typeof(CamPathPreView))]
public class CamPathPreViewEditor : Editor
{
private CamPathPreView script;
Vector3 lastPos;
Vector3 lastRot;
CamPathManager manager;
void OnEnable()
{
style.fontStyle = FontStyle.Bold;
style.normal.textColor = Color.white;
script = (CamPathPreView)target;
///首先要计算好parent(camera)的坐标
///
// script.transform.parent.parent.GetComponent<CamPathManager>().PositionToFocusObject();
manager = GameObject.FindObjectOfType<CamPathManager>();
GameObject charactor = GameObject.Find(manager.charactorName);
if (charactor)
{
manager.transform.position = charactor.transform.position;
}
//现在的方向 摄像机-焦点
Vector3 currentDirect = script.transform.parent.position - manager.transform.position;
//计算现在的方向投影到xz平面上
Vector3 currentDirectToXZPlaneVec = currentDirect;
currentDirectToXZPlaneVec.y = 0;
if (SceneView.currentDrawingSceneView)
{
SceneView.currentDrawingSceneView.AlignViewToObject(script.transform.parent);
}
if (script.init == false)
{
//最终保存角度
script.savedMapAngle = Vector3.Angle(currentDirectToXZPlaneVec, Vector3.right);//x轴对着镜头,所以是以Vector3.right轴取角度
script.savedPos = script.transform.parent.position;
script.init = true;
}
}
GUIStyle style = new GUIStyle();
public void OnSceneGUI()
{
// Handles.SphereCap(0, currentDirectToXZPlaneVecCap+manager.transform.position, Quaternion.identity, 1);
// Handles.SphereCap(0, manager.transform.position, Quaternion.identity, 1);
// Handles.SphereCap(0, kk, Quaternion.identity, 1);
// Handles.PositionHandle(abc, Quaternion.identity);
// Handles.ConeCap(0, inp, Quaternion.identity, 1);
}
public override void OnInspectorGUI()
{
GUILayout.Label("up");
GUILayout.BeginHorizontal();
script.moveUp = GUILayout.HorizontalSlider(script.moveUp, -20, 20);
script.moveUp = EditorGUILayout.FloatField(script.moveUp, GUILayout.Width(50));
GUILayout.EndHorizontal();
GUILayout.Label("forward");
GUILayout.BeginHorizontal();
script.moveForward = GUILayout.HorizontalSlider(script.moveForward, 50, -50);
script.moveForward = EditorGUILayout.FloatField(script.moveForward, GUILayout.Width(50));
GUILayout.EndHorizontal();
Vector3 inputPos = script.savedPos + script.transform.parent.forward * script.moveForward + script.transform.parent.up * script.moveUp;
GUILayout.Label("yaw");
GUILayout.BeginHorizontal();
script.yaw = GUILayout.HorizontalSlider(script.yaw, 170, -170);
script.yaw = EditorGUILayout.FloatField(script.yaw, GUILayout.Width(50));
GUILayout.EndHorizontal();
float mapAngle = script.savedMapAngle + script.yaw;
//当前摄像机对于focus的方向
Vector3 currentDirect = inputPos - manager.transform.position;
//计算现在的方向投影到xz平面上
Vector3 currentDirectToXZPlaneVec = currentDirect;
currentDirectToXZPlaneVec.y = 0;
//读取编辑器叠加的角度
//Vector3.right旋转角度后变为targetDirect
Vector3 targetDirect = Quaternion.AngleAxis(mapAngle, Vector3.up) * Vector3.right ;
//targetDirect转为投影xz平面上的长度
targetDirect = targetDirect * currentDirectToXZPlaneVec.magnitude;
//y方向还原,targetDirect就是最终的方向
targetDirect.y = currentDirect.y;
//方向与焦点相加就是摄像机的位置
script.transform.parent.position = targetDirect + manager.transform.position;
script.transform.parent.LookAt(manager.transform);
if (lastPos != script.transform.parent.position)
{
lastPos = script.transform.parent.position;
if (SceneView.currentDrawingSceneView)
{
SceneView.currentDrawingSceneView.AlignViewToObject(script.transform.parent);
}
}
if (lastRot != script.transform.parent.rotation.eulerAngles)
{
lastRot = script.transform.parent.rotation.eulerAngles;
if (SceneView.currentDrawingSceneView)
{
SceneView.currentDrawingSceneView.AlignViewToObject(script.transform.parent);
}
}
}
}
<file_sep>/Assets/CamPath/CamPathCharactor.cs
#region 模块信息
/*----------------------------------------------------------------
// Copyright (C) 2015 广州,蓝弧
//
// 模块名:FTD
// 创建者:张嘉俊
// 修改者列表:
// 创建日期:2/22/2016
// 模块描述:
//----------------------------------------------------------------*/
#endregion
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CamPathCharactor : MonoBehaviour
{
//读取数据后,要缓存位置
public void TempAllChildPosInEditor()
{
for (int i = 0; i < transform.childCount; i++)
{
CamPathCharactorPosition campath = transform.GetChild(i).GetComponent<CamPathCharactorPosition>();
if (campath==null)
{
campath = transform.GetChild(i).gameObject.AddComponent<CamPathCharactorPosition>();
}
campath.position = transform.GetChild(i).position;
}
}
public void ResetAllChildPosInEditor()
{
for (int i = 0; i < transform.childCount; i++)
{
if (transform.GetChild(i).position!=transform.GetChild(i).GetComponent<CamPathCharactorPosition>().position)
{
transform.GetChild(i).position = transform.GetChild(i).GetComponent<CamPathCharactorPosition>().position;
}
}
}
public void CreateStartPosition()
{
GameObject camGO = new GameObject("Position " + "Start");
camGO.transform.parent = transform;
camGO.transform.position = transform.position;
camGO.transform.rotation = transform.rotation;
camGO.transform.localScale = Vector3.one;
camGO.AddComponent<CamPathCharactorPosition>().position = camGO.transform.position;
}
}
<file_sep>/Assets/CamPath/Editor/CamPathObjectEditor.cs
#region 模块信息
/*----------------------------------------------------------------
// Copyright (C) 2015 广州,蓝弧
//
// 模块名:FTD
// 创建者:张嘉俊
// 修改者列表:
// 创建日期:2/17/2016
// 模块描述:
//----------------------------------------------------------------*/
#endregion
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
[CustomEditor(typeof(CamPathObject))]
public class CamPathObjectEditor : Editor
{
private CamPathObject script;
void OnEnable()
{
script = (CamPathObject)target;
if (SceneView.currentDrawingSceneView)
{
//SceneView.currentDrawingSceneView.AlignViewToObject(script.transform);
}
}
public override void OnInspectorGUI()
{
if (GUILayout.Button("Set Current Camera Position"))
{
script.transform.position = SceneView.currentDrawingSceneView.camera.transform.position;
script.transform.rotation = SceneView.currentDrawingSceneView.camera.transform.rotation;
GameObject.DestroyImmediate(script.transform.GetChild(0).gameObject);
GameObject preView = new GameObject("PreView");
preView.transform.parent = script.transform;
preView.transform.localPosition = Vector3.zero;
preView.transform.localRotation = Quaternion.identity;
preView.transform.localScale = Vector3.one;
preView.AddComponent<CamPathPreView>();
}
}
}
<file_sep>/Assets/CamPath/CamPathPreView.cs
#region 模块信息
/*----------------------------------------------------------------
// Copyright (C) 2015 广州,蓝弧
//
// 模块名:FTD
// 创建者:张嘉俊
// 修改者列表:
// 创建日期:2/18/2016
// 模块描述:
//----------------------------------------------------------------*/
#endregion
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class CamPathPreView : MonoBehaviour {
[HideInInspector]
public bool init = false;
[HideInInspector]
public float moveForward;
[HideInInspector]
public float moveUp;
[HideInInspector]
public float yaw;
[HideInInspector]
public Vector3 savedPos;
[HideInInspector]
public float savedMapAngle;
}
<file_sep>/Assets/CamPath/Editor/CamPathCharactorEditor.cs
#region 模块信息
/*----------------------------------------------------------------
// Copyright (C) 2015 广州,蓝弧
//
// 模块名:FTD
// 创建者:张嘉俊
// 修改者列表:
// 创建日期:2/22/2016
// 模块描述:
//----------------------------------------------------------------*/
#endregion
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
[CustomEditor(typeof(CamPathCharactor))]
public class CamPathCharactorEditor : Editor
{
CamPathCharactor script;
GUIStyle style = new GUIStyle();
public void OnEnable()
{
style.fontStyle = FontStyle.Bold;
style.normal.textColor = Color.white;
script = (CamPathCharactor)target;
bool hasPositionStart = false;
for (int i = 0; i < script.transform.childCount; i++)
{
if (script.transform.GetChild(i).name == "Position " + "Start")
{
hasPositionStart = true;
}
}
if (hasPositionStart == false)
{
GameObject camGO = new GameObject("Position " + "Start");
camGO.transform.parent = script.transform;
camGO.transform.position = script.transform.position;
camGO.transform.rotation = script.transform.rotation;
camGO.transform.localScale = Vector3.one;
camGO.AddComponent<CamPathCharactorPosition>().position = camGO.transform.position;
}
else
{
GameObject start = GameObject.Find("Position Start");
start.transform.localPosition = Vector3.zero;
start.GetComponent<CamPathCharactorPosition>().position = start.transform.position;
}
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
if (GUILayout.Button("Create Position"))
{
CreateNewPosition();
GetSceneView().Focus();
}
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Save", GUILayout.Width(100f)))
{
ExtensionMethodsEditor.SaveChildObjectPropertyToJsonFile(script.gameObject);
//SaveConfig();
}
if (GUILayout.Button("Load", GUILayout.Width(100f)))
{
ExtensionMethodsEditor.ReadJsonFileDataToChildObjectProperty(script.gameObject);
script.TempAllChildPosInEditor();
//ReadConfig();
}
EditorGUILayout.EndHorizontal();
}
public void OnSceneGUI()
{
for (int i = 0; i < script.transform.childCount; i++)
{
CamPathCharactorPosition obj = script.transform.GetChild(i).GetComponent<CamPathCharactorPosition>();
if (obj)
{
//Handles.PositionHandle(obj.transform.position, obj.transform.rotation);
Handles.SphereCap(0, obj.transform.position, Quaternion.identity, 1);
Handles.Label(obj.transform.position, obj.gameObject.name, style);
}
else
{
//monster
}
}
script.ResetAllChildPosInEditor();
}
public static SceneView GetSceneView()
{
SceneView view = SceneView.currentDrawingSceneView;
if (view == null)
view = EditorWindow.GetWindow<SceneView>();
return view;
}
public void CreateNewPosition()
{
GameObject camGO = new GameObject("Position " + (script.transform.childCount == 0 ? "Start" : script.transform.childCount.ToString()) );
camGO.transform.parent = script.transform;
camGO.transform.position = script.transform.position;
camGO.transform.rotation = script.transform.rotation;
camGO.transform.localScale = Vector3.one;
camGO.AddComponent<CamPathCharactorPosition>().position = camGO.transform.position;
// GameObject preView = new GameObject("PreView");
// preView.transform.parent = camGO.transform;
// preView.transform.localPosition = Vector3.zero;
// preView.transform.localRotation = Quaternion.identity;
// preView.transform.localScale = Vector3.one;
// preView.AddComponent<CamPathCharactorPositionPreView>();
Undo.RegisterCreatedObjectUndo(camGO, "Created Position");
Selection.activeGameObject = camGO;
}
}
<file_sep>/Assets/CamPath/CamPathManager.cs
#region 模块信息
/*----------------------------------------------------------------
// Copyright (C) 2015 广州,蓝弧
//
// 模块名:FTD
// 创建者:张嘉俊
// 修改者列表:
// 创建日期:2/17/2016
// 模块描述:
//----------------------------------------------------------------*/
#endregion
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
// 模块描述:CamPathManager的坐标在游戏当中是不会动的
//默认只有一个机位Camera Full Map Max
//Camera Full Map Min是控制缩放的最小值不算一个机位
public class CamPathManager : MonoBehaviour
{
/// <summary>
/// 缩放镜头最大值对象名字
/// </summary>
[HideInInspector]
public string fullMapCameraMaxName = "Camera Full Map Max";
/// <summary>
/// 缩放镜头最小值对象名字
/// </summary>
[HideInInspector]
public string fullMapCameraMinName = "Camera Full Map Min";
/// <summary>
/// 焦点对象名字
/// </summary>
[HideInInspector]
public string charactorName = "CamPathCharactor";
/// <summary>
/// 对齐对象动画处理时私有变量
/// </summary>
[HideInInspector]
bool isAlignToObject = false;
Vector3 alignPosition;
Quaternion alignRotation;
/// <summary>
/// 对齐对象动画处理时动画百分比
/// </summary>
float alignPercent = 0;
bool isFollowToObject = false;
GameObject followToObject;
public static CamPathManager instance;
string currentCameraAlignObjectName;
public enum AlignMethod
{
Instantaneous,
AlignTo,
}
public AlignMethod alignMethod = AlignMethod.AlignTo;
void Awake()
{
instance = this;
alignMethod = AlignMethod.AlignTo;
//默认第一个机位是"Camera Full Map Max"
currentCameraAlignObjectName = fullMapCameraMaxName;
}
/// <summary>
/// 游戏镜头使用设计好的机位
/// </summary>
/// <param name="cameraName"></param>
public void AlignViewToCameraName(string cameraName)
{
AlignViewToCameraObject(GameObject.Find(cameraName));
}
public void AlignViewToCameraObject(GameObject obj)
{
alignPosition = obj.transform.position;
alignRotation = obj.transform.rotation;
if (alignMethod == AlignMethod.Instantaneous)
{
Camera.main.transform.position = alignPosition;
Camera.main.transform.rotation = alignRotation;
}
else if (alignMethod == AlignMethod.AlignTo)
{
if (isAlignToObject)
{
LeanTween.cancel(gameObject);
isAlignToObject = false;
}
if (isAlignToObject == false)
{
isAlignToObject = true;
LeanTween.value(gameObject, 0, 1, 0.8f).setOnUpdate((float f) => { alignPercent = f; }).setOnComplete(() => { isAlignToObject = false; alignPercent = 0; });
}
}
}
/// <summary>
/// 让游戏镜头的焦点设为某个位置
/// </summary>
/// <param name="positionName"></param>
public void FocusTo(string positionName)
{
FocusTo(GameObject.Find(positionName));
}
public void FocusTo(GameObject obj)
{
Vector3 offset = transform.position - obj.transform.position;
alignPosition = GameObject.Find(currentCameraAlignObjectName).transform.position - offset;
alignRotation = GameObject.Find(currentCameraAlignObjectName).transform.rotation;
if (alignMethod == AlignMethod.Instantaneous)
{
Camera.main.transform.position = alignPosition;
Camera.main.transform.rotation = alignRotation;
}
else if (alignMethod == AlignMethod.AlignTo)
{
if (isAlignToObject)
{
LeanTween.cancel(gameObject);
isAlignToObject = false;
}
if (isAlignToObject == false)
{
isAlignToObject = true;
LeanTween.value(gameObject, 0, 1, 0.8f).setOnUpdate((float f) => { alignPercent = f; }).setOnComplete(() => { isAlignToObject = false; alignPercent = 0; });
}
}
}
void Start()
{
}
void Update()
{
if (isAlignToObject && alignMethod == AlignMethod.AlignTo)
{
Camera.main.transform.position = Vector3.Lerp(Camera.main.transform.position, alignPosition, alignPercent);
Camera.main.transform.rotation = Quaternion.Slerp(Camera.main.transform.rotation, alignRotation, alignPercent);
}
}
}
<file_sep>/Assets/CamPath/TouchScript.cs
using UnityEngine;
using System.Collections;
using System;
public class TouchScript : MonoBehaviour
{
#region Public Variable Region
/// <summary>
/// 单例
/// </summary>
public static TouchScript Instance
{
get { return _instance; }
set { _instance = value; }
}
/// <summary>
/// 触摸操作
/// </summary>
public enum ETouchOperation
{
Nothing,
Sliding,
Zooming
}
/// <summary>
/// PC上的偏移值
/// </summary>
public float pcDeviation = 10;
/// <summary>
/// 安卓手机缩放偏移值
/// </summary>
public float androidZoomingDeviation = 1000;
/// <summary>
/// 安卓手机滑动偏移值
/// </summary>
public float androidSlidingDeviation = 10;
/// <summary>
/// 安卓手机上的误差极限值
/// </summary>
public float mobileThreshold = 20.0f;
/// <summary>
/// 滑动值
/// </summary>
public Vector3 slide;
/// <summary>
/// 缩放值
/// </summary>
public float zoom;
/// <summary>
/// 是否允许手势操作
/// </summary>
public bool isTouchAllow;
/// <summary>
/// 操作识别
/// </summary>
public ETouchOperation touchOperation;
#endregion
#region Private Variable Region
private static TouchScript _instance;
private float zoom_init_distance;
private Vector3 slide_init_vector;
#endregion
#region System Callback Function Region
private void Awake()
{
Initialize();
}
private void Update()
{
if (isTouchAllow)
{
#if UNITY_STANDALONE || UNITY_EDITOR
GetSlideInPC();
#elif UNITY_ANDROID || UNITY_IPHONE
GetSlideInMobile();
#endif
}
}
#endregion
#region Public Custom Function Region
/// <summary>
/// 判断是否在滑动
/// </summary>
/// <returns>是否在滑动</returns>
public bool IsSliding()
{
return touchOperation == ETouchOperation.Sliding;
}
public bool IsZooming()
{
return touchOperation == ETouchOperation.Zooming;
}
#endregion
#region Protected Custom Function Region
#endregion
#region Private Custom Function Region
private void Initialize()
{
Instance = this;
zoom_init_distance = 0;
slide_init_vector = Vector3.zero;
slide = Vector3.zero;
zoom = 0;
SetTouchOperation(ETouchOperation.Nothing);
isTouchAllow = true;
}
private void GetSlideInPC()
{
if (!Input.GetMouseButton(0) && Input.GetAxis("Mouse ScrollWheel") == 0)
{
slide = Vector3.zero;
zoom = 0;
slide_init_vector = Vector3.zero;
SetTouchOperation(ETouchOperation.Nothing);
}
else if (Input.GetMouseButton(0))
{
if (slide_init_vector == Vector3.zero)
{
slide_init_vector = Input.mousePosition;
}
else
{
if ((slide_init_vector - Input.mousePosition).sqrMagnitude>1 || touchOperation == ETouchOperation.Sliding)
{
slide = slide_init_vector - Input.mousePosition;
slide_init_vector = Input.mousePosition;
SetTouchOperation(ETouchOperation.Sliding);
}
else
{
slide = Vector3.zero;
slide_init_vector = Input.mousePosition;
}
}
}
else if (Input.GetAxis("Mouse ScrollWheel") != 0)
{
zoom = Input.GetAxis("Mouse ScrollWheel") / pcDeviation;
SetTouchOperation(ETouchOperation.Zooming);
}
}
private void GetSlideInMobile()
{
if (Input.touchCount == 0)
{
zoom_init_distance = 0;
slide_init_vector = Vector3.zero;
zoom = zoom_init_distance;
slide = slide_init_vector;
SetTouchOperation(ETouchOperation.Nothing);
}
else if (Input.touchCount == 1)
{ //Slide
if (zoom_init_distance != 0)
zoom_init_distance = 0;
if (slide_init_vector == Vector3.zero)
{
slide_init_vector = Input.GetTouch(0).position;
}
else
{
if ((slide_init_vector - (Vector3)Input.GetTouch(0).position).sqrMagnitude > 1 || touchOperation == ETouchOperation.Sliding)
{
slide = slide_init_vector - (Vector3)Input.GetTouch(0).position;
slide_init_vector = Input.GetTouch(0).position;
SetTouchOperation(ETouchOperation.Sliding);
}
else
{
slide = Vector3.zero;
slide_init_vector = Input.mousePosition;
}
}
}
else
{ //Zoom
if (slide_init_vector != Vector3.zero)
slide_init_vector = Vector3.zero;
if (zoom_init_distance == 0)
{
zoom_init_distance = (Input.GetTouch(0).position - Input.GetTouch(1).position).magnitude;
}
else
{
var new_distance = (Input.GetTouch(0).position - Input.GetTouch(1).position).magnitude;
if (Math.Abs(new_distance - zoom_init_distance) > mobileThreshold)
{
zoom = (new_distance - zoom_init_distance) / androidZoomingDeviation;
zoom_init_distance = new_distance;
SetTouchOperation(ETouchOperation.Zooming);
}
else
{
zoom = 0;
SetTouchOperation(ETouchOperation.Nothing);
}
}
}
}
private void SetTouchOperation(ETouchOperation to)
{
if (to != touchOperation)
{
touchOperation = to;
}
}
#endregion
}
<file_sep>/Assets/CamPath/Editor/CamPathManagerEditor.cs
#region 模块信息
/*----------------------------------------------------------------
// Copyright (C) 2015 广州,蓝弧
//
// 模块名:FTD
// 创建者:张嘉俊
// 修改者列表:
// 创建日期:2/17/2016
// 模块描述:
//----------------------------------------------------------------*/
#endregion
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using System.IO;
/// <summary>
/// 镜头根据CamPathManager的Camera Charactor来移动
/// </summary>
[CustomEditor(typeof(CamPathManager))]
public class CamPathManagerEditor : Editor
{
private CamPathManager script;
GUIStyle style = new GUIStyle();
void OnEnable()
{
style.fontStyle = FontStyle.Bold;
style.normal.textColor = Color.white;
script = (CamPathManager)target;
CreateChar();
GameObject charactor = GameObject.Find(script.charactorName);
if (charactor)
{
script. transform.position = charactor.transform.position;
}
CreateFullMapCamera();
CreateFunnyCamera();
}
void CreateFunnyCamera()
{
if (Camera.main == null)
{
GameObject tmp = new GameObject("Camera", typeof(Camera), typeof(AudioListener));
tmp.tag = "MainCamera";
GameObject obj = GameObject.Find(script.fullMapCameraMaxName);
Camera.main.transform.position = obj.transform.position;
Camera.main.transform.rotation = obj.transform.rotation;
}
{
FunnyCamera cam = Camera.main.GetComponent<FunnyCamera>();
if (cam == null)
{
Camera.main.gameObject.AddComponent<FunnyCamera>();
}
}
}
/// <summary>
/// 创建2个基本的摄像头
/// </summary>
void CreateFullMapCamera()
{
//search for a manager object within current scene
GameObject camera = GameObject.Find(script.fullMapCameraMaxName);
//if no manager object was found
if (camera == null)
{
//create a new gameobject with that name
if (SceneView.currentDrawingSceneView)
{
camera = new GameObject(script.fullMapCameraMaxName);
camera.transform.parent = script.transform;
GameObject charactor = GameObject.Find(script.charactorName);
//camera.transform.position = SceneView.currentDrawingSceneView.camera.transform.position;
//camera.transform.rotation = SceneView.currentDrawingSceneView.camera.transform.rotation;
camera.transform.position = (charactor.transform.up + charactor.transform.right).normalized * 15 + charactor.transform.position;
camera.transform.LookAt(charactor.transform);
camera.transform.localScale = Vector3.one;
camera.AddComponent<CamPathObject>();
GameObject preView = new GameObject("PreView");
preView.transform.parent = camera.transform;
preView.transform.localPosition = Vector3.zero;
preView.transform.localRotation = Quaternion.identity;
preView.transform.localScale = Vector3.one;
preView.AddComponent<CamPathPreView>();
camera = new GameObject(script.fullMapCameraMinName);
camera.transform.parent = script.transform;
//camera.transform.position = SceneView.currentDrawingSceneView.camera.transform.position;
//camera.transform.rotation = SceneView.currentDrawingSceneView.camera.transform.rotation;
camera.transform.position = (charactor.transform.up + charactor.transform.right).normalized * 14 + charactor.transform.position;
camera.transform.LookAt(charactor.transform);
camera.transform.localScale = Vector3.one;
camera.AddComponent<CamPathObject>();
preView = new GameObject("PreView");
preView.transform.parent = camera.transform;
preView.transform.localPosition = Vector3.zero;
preView.transform.localRotation = Quaternion.identity;
preView.transform.localScale = Vector3.one;
preView.AddComponent<CamPathPreView>();
//如果有,就读取配置
//ReadConfig();
}
}
}
public override void OnInspectorGUI()
{
DrawDefaultInspector();
GUILayout.Label("Camera Editor");
if (GUILayout.Button("New Camera", GUILayout.Width(100f)))
{
CreateNewCamera();
GetSceneView().Focus();
}
GUILayout.Label("Camera Full Map Config");
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Save", GUILayout.Width(100f)))
{
ExtensionMethodsEditor.SaveChildObjectPropertyToJsonFile(script.gameObject);
//SaveConfig();
}
if (GUILayout.Button("Load", GUILayout.Width(100f)))
{
ExtensionMethodsEditor.ReadJsonFileDataToChildObjectProperty(script.gameObject);
for (int i = 0; i < script.transform.childCount; i++)
{
script.transform.GetChild(i).gameObject.AddComponent<CamPathObject>();
GameObject preView = new GameObject("PreView");
preView.transform.parent = script.transform.GetChild(i).gameObject.transform;
preView.transform.localPosition = Vector3.zero;
preView.transform.localRotation = Quaternion.identity;
preView.transform.localScale = Vector3.one;
preView.AddComponent<CamPathPreView>();
}
GameObject charactor = GameObject.Find(script.charactorName);
if (charactor)
{
script.transform.position = charactor.transform.position;
}
//ReadConfig();
}
EditorGUILayout.EndHorizontal();
GUILayout.Label("\nTest");
for (int i = 0; i < script.transform.childCount; i++)
{
CamPathObject obj = script.transform.GetChild(i).GetComponent<CamPathObject>();
if (obj)
{
if (GUILayout.Button(obj.name))
{
if (Application.isPlaying)
{
script.AlignViewToCameraObject(obj.gameObject);
}
else
{
Camera.main.transform.position = obj.transform.position;
Camera.main.transform.rotation = obj.transform.rotation;
}
}
}
}
}
void SaveConfig()
{
GameObject cameraMax = GameObject.Find(script.fullMapCameraMaxName);
GameObject cameraMin = GameObject.Find(script.fullMapCameraMinName);
//if no manager object was found
if (cameraMax != null && cameraMin != null)
{
GameObject charactor = GameObject.Find(script.charactorName);
if (charactor != null)
{
LitJson.JsonData allData = new LitJson.JsonData();
allData.SetJsonType(LitJson.JsonType.Array);
allData.Add(charactor.transform.InverseTransformPoint(cameraMax.transform.position).x);
allData.Add(charactor.transform.InverseTransformPoint(cameraMax.transform.position).y);
allData.Add(charactor.transform.InverseTransformPoint(cameraMax.transform.position).z);
allData.Add(cameraMax.transform.rotation.x);
allData.Add(cameraMax.transform.rotation.y);
allData.Add(cameraMax.transform.rotation.z);
allData.Add(cameraMax.transform.rotation.w);
allData.Add(charactor.transform.InverseTransformPoint(cameraMin.transform.position).x);
allData.Add(charactor.transform.InverseTransformPoint(cameraMin.transform.position).y);
allData.Add(charactor.transform.InverseTransformPoint(cameraMin.transform.position).z);
allData.Add(cameraMin.transform.rotation.x);
allData.Add(cameraMin.transform.rotation.y);
allData.Add(cameraMin.transform.rotation.z);
allData.Add(cameraMin.transform.rotation.w);
string path = Application.streamingAssetsPath + "/Config/Camera.json";
string dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
FileInfo fi = new FileInfo(path);
StreamWriter sw = new StreamWriter(fi.Create());
sw.Write(LitJson.JsonMapper.ToJson(allData));
sw.Close();
Debug.Log("save ok: " + path);
}
}
else
{
Debug.Log("save faile: camera==null");
}
}
void ReadConfig()
{
GameObject camera = GameObject.Find(script.fullMapCameraMaxName);
//if no manager object was found
if (camera != null)
{
string path = Application.streamingAssetsPath + "/Config/Camera.json";
FileInfo fi = new FileInfo(path);
if (fi != null)
{
if (fi.Exists)
{
StreamReader sr = new StreamReader(fi.OpenRead());
string json = sr.ReadToEnd();
sr.Close();
LitJson.JsonData allData = LitJson.JsonMapper.ToObject(json);
if (allData.IsArray)
{
Vector3 pos = new Vector3((float)(double)allData[0], (float)(double)allData[1], (float)(double)allData[2]);
Quaternion rot = new Quaternion((float)(double)allData[3], (float)(double)allData[4], (float)(double)allData[5], (float)(double)allData[6]);
GameObject charactor = GameObject.Find(script.charactorName);
if (charactor != null)
{
camera.transform.position = charactor.transform.TransformPoint(pos);
camera.transform.rotation = rot;
}
}
}
}
}
else
{
Debug.Log("load faile: camera==null");
}
camera = GameObject.Find(script.fullMapCameraMinName);
//if no manager object was found
if (camera != null)
{
string path = Application.streamingAssetsPath + "/Config/Camera.json";
FileInfo fi = new FileInfo(path);
if (fi != null)
{
if (fi.Exists)
{
StreamReader sr = new StreamReader(fi.OpenRead());
string json = sr.ReadToEnd();
sr.Close();
LitJson.JsonData allData = LitJson.JsonMapper.ToObject(json);
if (allData.IsArray)
{
Vector3 pos = new Vector3((float)(double)allData[7], (float)(double)allData[8], (float)(double)allData[9]);
Quaternion rot = new Quaternion((float)(double)allData[10], (float)(double)allData[11], (float)(double)allData[12], (float)(double)allData[13]);
GameObject charactor = GameObject.Find(script.charactorName);
if (charactor != null)
{
camera.transform.position = charactor.transform.TransformPoint(pos);
camera.transform.rotation = rot;
}
}
}
}
}
else
{
Debug.Log("load faile: camera==null");
}
}
public void OnSceneGUI()
{
for (int i = 0; i < script.transform.childCount; i++)
{
CamPathObject obj = script.transform.GetChild(i).GetComponent<CamPathObject>();
if (obj)
{
Handles.Label(obj.transform.position, obj.gameObject.name, style);
Handles.PositionHandle(obj.transform.position, obj.transform.rotation);
}
else
{
//monster
}
}
}
void CreateChar()
{
//search for a manager object within current scene
GameObject charactor = GameObject.Find(script.charactorName);
//if no manager object was found
if (charactor == null)
{
//create a new gameobject with that name
if (SceneView.currentDrawingSceneView)
{
Vector3 pos = SceneView.currentDrawingSceneView.camera.transform.TransformVector(0, 0, 5);
charactor = GameObject.CreatePrimitive(PrimitiveType.Cube);
charactor.GetComponent<BoxCollider>().enabled = false;
charactor.GetComponent<MeshRenderer>().enabled = false;
charactor.name = script.charactorName;
charactor.transform.position = pos + SceneView.currentDrawingSceneView.camera.transform.position;
charactor.AddComponent<CamPathCharactor>().CreateStartPosition() ;
Selection.activeGameObject = charactor;
}
}
}
public void CreateNewCamera()
{
GameObject camGO = new GameObject("Camera " + script.transform.childCount);
camGO.transform.parent = script.transform;
camGO.transform.position = SceneView.currentDrawingSceneView.camera.transform.position;
camGO.transform.rotation = SceneView.currentDrawingSceneView.camera.transform.rotation;
camGO.transform.localScale = Vector3.one;
camGO.AddComponent<CamPathObject>();
GameObject preView = new GameObject("PreView");
preView.transform.parent = camGO.transform;
preView.transform.localPosition = Vector3.zero;
preView.transform.localRotation = Quaternion.identity;
preView.transform.localScale = Vector3.one;
preView.AddComponent<CamPathPreView>();
Undo.RegisterCreatedObjectUndo(camGO, "Created Camera");
Selection.activeGameObject = camGO;
}
public static SceneView GetSceneView()
{
SceneView view = SceneView.currentDrawingSceneView;
if (view == null)
view = EditorWindow.GetWindow<SceneView>();
return view;
}
}
public class CreateCamPathManager : EditorWindow
{
[MenuItem("Window/地图管理器/CamPath Manager")]
//initialize method
static void Init()
{
string managerName = "CamPathManager";
//search for a manager object within current scene
GameObject manager = GameObject.Find(managerName);
//if no manager object was found
if (manager == null)
{
//create a new gameobject with that name
manager = new GameObject(managerName);
manager.AddComponent<CamPathManager>();
Undo.RegisterCreatedObjectUndo(manager, "Created Manager");
}
else if (manager.GetComponent<CamPathManager>() == null)
{
manager.AddComponent<CamPathManager>();
}
//in both cases, select the gameobject
Selection.activeGameObject = manager;
}
} | 2613a5ffcb5b7b35faf5328b5bcd114e8f1b0b69 | [
"C#"
] | 13 | C# | westernknight/CamPath | ff0b2950199d2a2da1bf838c3b972983b803bf80 | 709710c398bb2bcd5cbeb157887ff5cf685cd3db |
refs/heads/master | <file_sep>// js for main app's appearance and styling
// Form Validation
const validateTextField = () => {
const textField = document.getElementById("user-post");
const textFieldContent = document.getElementById("user-post").value;
const charCountSpan = document.getElementById("char-count");
if (textFieldContent.length > 255) {
textField.style.borderColor = "#ff00ff";
charCountSpan.style.color = "#ff00ff";
document.getElementById("submit-button").disabled = true;
}
else if (textFieldContent.length === 0) {
document.getElementById("submit-button").disabled = true;
} else {
textField.style.borderColor = "#ffffff";
charCountSpan.style.color = "#cccccc";
document.getElementById("submit-button").disabled = false;
}
}
<file_sep>// Code for view
const renderRandomPostResponse = xhttp => {
document.getElementById("response-text").textContent = JSON.parse(xhttp.responseText)[0];
document.getElementById("response-date").textContent = JSON.parse(xhttp.responseText)[1];
}
const renderCurrentCharCount = () => {
const charCountSpan = document.getElementById("char-count");
const currentCharCount = document.getElementById("user-post").value.length;
charCountSpan.textContent = `${currentCharCount}`;
}
<file_sep>// Controller stuff? kana...
const ajaxRequest = (url, cFunction) => {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) cFunction(this);
};
xhttp.open("POST", url, true);
xhttp.send();
}
// index.html set-up on load
window.addEventListener("load", function () {
if (document.body.id !== "index") return;
validateForm();
})
// listen.html set-up on load
window.addEventListener("load", function () {
if (document.body.id !== "listen") return;
ajaxRequest("http://localhost/listen-bot/php/get_rand_post.php", renderRandomPostResponse);
});
// validate text field in form
const validateForm = () => {
if (document.body.id !== "index") return;
validateTextField();
renderCurrentCharCount();
}
document.getElementById("user-post").addEventListener("keydown", validateForm);
document.getElementById("user-post").addEventListener("keyup", validateForm);
document.getElementById("user-post").addEventListener("cut", validateForm);
document.getElementById("user-post").addEventListener("paste", validateForm);<file_sep><?php
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
// Global Variables
$servername = "localhost";
$username = "root";
$password = "";
$db_name = "listen-bot";
function main() {
if (!isset($_POST["user-post"])) return;
try {
if (is_post_text_valid($_POST["user-post"])) insert_post_text($_POST["user-post"]);
header("Location: http://localhost/listen-bot/success.html");
exit;
}
catch (Exception $err) {
error_log($err, 3, "error_log.txt");
header("Location: http://localhost/listen-bot/error.html");
exit;
}
}
/****************************** Insert Post *****************************
* @param $post_text string
*/
function insert_post_text($post_text) {
global $servername, $username, $password, $db_name;
$conn = new mysqli($servername, $username, $password, $db_name);
if ($conn->connect_error) exit("Connection failed: " . $conn->connect_error);
$statement = $conn->prepare("INSERT INTO posts (post_text) VALUES (?);");
$statement->bind_param("s", $post_text);
$statement->execute();
$conn->close();
}
/****************************** Validate Post *****************************
* @param $post_text string
* @return boolean
* @throws Exception
*/
function is_post_text_valid($post_text) {
if ($post_text == null) throw new Exception("Post text is null.");
$post_length = strlen($post_text);
if ($post_length == 0 || $post_length > 255 || $post_length < 0) return false;
else return true;
}
main();
<file_sep><?php
// Global Variables
$servername = "localhost";
$username = "root";
$password = "";
$db_name = "listen-bot";
/****************************** Create Posts Table ******************************/
function create_posts_table() {
global $servername, $username, $password, $db_name;
$conn = new mysqli($servername, $username, $password, $db_name);
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
$sql = "CREATE TABLE posts(
post_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
post_text VARCHAR(255),
post_date DATETIME DEFAULT CURRENT_TIMESTAMP
);";
echo (!$conn->query($sql)) ? "err {create_posts_table}: " . $conn->error : "posts table created.";
$conn->close();
}
create_posts_table();
<file_sep><?php
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
// Global Variables
$servername = "localhost";
$username = "root";
$password = "";
$db_name = "listen-bot";
/****************************** Get Random Post ******************************/
function get_random_post_text() {
global $servername, $username, $password, $db_name;
$conn = new mysqli($servername, $username, $password, $db_name);
if ($conn->connect_error) exit("Connection failed: " . $conn->connect_error);
$statement = $conn->prepare("SELECT post_text, post_date FROM posts ORDER BY RAND() LIMIT 1;");
$statement->execute();
$result = $statement->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode([htmlspecialchars($data[0]["post_text"]), htmlspecialchars($data[0]["post_date"])]);
$conn->close();
}
get_random_post_text(); | 56310cb39165cbb681ac495d6ee2099e5323f6c1 | [
"JavaScript",
"PHP"
] | 6 | JavaScript | jodyanna/listen-bot | d0035257c152d4561ca30f3368f877e28ef7125c | e9df22a3a1e9b593115e5a12ad5bb5a931667467 |
refs/heads/master | <file_sep>'use strict';
class Hero {
constructor(name, initialLocation) {
this.name = name;
this.location = initialLocation;
this.inventory = {};
}
getName() {
return this.name;
}
getLocation() {
return this.location;
}
withInventory(fn) {
Object.entries(this.inventory).forEach(([name, item]) => fn(name, item));
}
go(direction) {
let newLocation = this.location.go(direction);
if (newLocation) {
this.location = newLocation;
}
return newLocation;
}
drop(item) {
if (this.holds(item)) {
delete this.inventory[item.getName()];
this.location.place(item);
}
}
take(item) {
if (this.location.contains(item)) {
this.location.remove(item);
this.inventory[item.getName()] = item;
}
}
holds(item) {
return !!this.inventory[item.getName()];
}
itemNamed(itemName) {
return this.inventory[itemName];
}
numberOfItemsCarried() {
return Object.getOwnPropertyNames(this.inventory).length;
}
}
module.exports = Hero;
<file_sep>'use strict';
const textUtil = require('../util/textUtil');
class Location {
constructor(name, description) {
this.name = name;
this.description = description;
this.exits = {};
this.items = {};
}
getName() {
return this.name;
}
getDescription() {
return this.description;
}
withItems(fn) {
Object.values(this.items).forEach(fn);
}
withExits(fn) {
Object.entries(this.exits).forEach(([direction, exit]) => fn(direction, exit))
}
addExit(direction, kind, location) {
this.exits[direction] = {
location: location,
kind: kind
};
}
place(item) {
this.items[item.getName()] = item;
}
remove(item) {
delete this.items[item.getName()];
}
contains(item) {
return !!this.items[item.getName()];
}
itemNamed(itemName) {
return this.items[itemName];
}
go(direction) {
let exit = this.exits[direction];
return exit ? exit.location : null;
}
}
module.exports = Location;
<file_sep>'use strict';
const assert = require('assert');
const Hero = require('../src/model/hero.js');
const Location = require('../src/model/location.js');
const Item = require('../src/model/item.js');
function shouldHaveNoInventoryWhenCreated() {
let hero = new Hero('adventurer', null);
assert.equal(hero.numberOfItemsCarried(), 0);
}
function shouldCarryAnItemWhenPickedUp() {
let location = new Location('test','a test location');
let item = new Item('test', 'a test item');
let hero = new Hero('adventurer', location);
location.place(item);
assert(location.contains(item));
hero.take(item);
assert.equal(hero.numberOfItemsCarried(), 1);
assert.ok(hero.holds(item));
assert(!location.contains(item));
}
function shouldLoseAnItemWhenDropped() {
let location = new Location('test','a test location');
let item = new Item('test', 'a test item');
let hero = new Hero('adventurer', location);
location.place(item);
hero.take(item);
assert.equal(hero.numberOfItemsCarried(), 1);
assert(hero.holds(item));
assert(!location.contains(item));
hero.drop(item);
assert.equal(hero.numberOfItemsCarried(), 0);
assert(!hero.holds(item));
assert(location.contains(item));
}
function shouldTakeAllAtALocation() {
let location = new Location('test','a test location');
let hero = new Hero('adventurer', location);
let item1 = new Item('test1', 'a test item');
let item2 = new Item('test2', 'another test item');
location.place(item1);
location.place(item2);
// === TASK 3 ===
// You will need to write this method in hero.js
hero.takeAll();
assert.equal(hero.numberOfItemsCarried(), 2, 'hero has taken two items');
assert(hero.holds(item1), 'hero has first item');
assert(hero.holds(item2), 'hero has second item');
assert(!location.contains(item1), 'first item is missing from the location');
assert(!location.contains(item2), 'second item is missing from the location');
}
function shouldDropAllAtALocation() {
// === TASK 4 ===
// your code here
}
function main() {
shouldHaveNoInventoryWhenCreated();
shouldCarryAnItemWhenPickedUp();
shouldLoseAnItemWhenDropped();
// === TASK 3 ===
// uncomment this test, and make the tests pass
// shouldTakeAllAtALocation();
// === TASK 4 ===
// uncomment this test
// shouldDropAllAtALocation();
console.log(__filename, 'all OK');
}
main();
<file_sep>require('./heroTests');
require('./locationTests');<file_sep># adventure
Adventure game skeleton for LCCM open day workshop
*NB* to run this exercise you will need Node.js (use the latest version, currently 7.5.0) installed on your computer. Download this from https://nodejs.org/en/
At the open day workshop we'll be running this in a cloud-based development environment called Cloud9.
When working with software, more often than not we don't start from scratch. We work with code that already exists — either code someone else has written, or code we wrote yesterday, last week, last month. This short workshop presents a number of tasks around a simple text adventure game written in Javascript.
Work in pairs. You will find it helpful if one of you knows at least a bit of JavaScript, but even if not, providing you have some level of programming experience you should be able to work out what's going on and complete the tasks.
We'll talk and review between the tasks, and show each other/discuss the solutions so far.
We only have 30 minutes for this open day workshop, so don't worry if you don't get to finish everything! If you want to download the code and play with it some more, it's available on GitHub at https://github.com/davethehat/adventure
The game source is in a folder `adventure`. In Cloud9 you should see a window named 'bash' in the tabs beneath the editing window, so click in the tab and type
```
$ npm start <your name here>
```
(If you're running this at home, open a terminal window, and change directory into the `adventure` directory in the directory into which you downloaded the adventre codebase.)
This will bring you to a prompt:
```
$ npm start David
> adventure@1.0.0 start /Users/david.harvey/dev/adventure
> node ./src/main.js "David"
================================
Welcome, David
================================
...
You are in a clearing.
You see a path to the east.
What now?
```
You can type simple commands:
'north', 'south', 'east', 'west' to move
'look' for a more detailed description of where you are
'take <item>' to pick something up
'drop <item>' to drop something you're carrying
'inventory' to see what you're carrying
'quit' to leave the adventure
Spend a couple of minutes exploring the tiny world.
Now look at the source code. This will be open in an IDE on your desktop.
Firstly take a look at src/main.js, which holds the game's main logic. Don't worry too much about most of what's going on here: look at main() and initialiseMap().
##TASK 1
Using the existing code as an example:
1. Add a location to the game.
2. Add an item to the game.
Now we're going to dive a bit deeper into the code. Take a look at the function in main.js called processVerbObjectCommand. As the name suggests, this is the code that's run when our little game engine deals with a command like take sword. You'll see these call methods on our hero, so take a look at hero.js. If you've worked with languages that let you create classes and objects this should be quite familiar: we'll have a 2-minute overview in the group to clarify/explain.
We're going to expand the repertoire of actions with the ability to take all and drop all. We're going to do this by writing some tests first, that execute these actions against the code that represents our hero.
The tests in this project live in a folder called test. We can run these tests using the following command (from the adventure folder)
```
$ npm test
```
##TASK 2
Take a look at the test code in test/heroTests.js in the IDE. What's common in the way these tests set things up, do something and then check the results?
Break a test by changing an assertion, then run the tests again and see what happens. Undo your change so the test passes again.
##TASK 3
Uncomment the call to shouldTakeAllAtALocation and run the tests. The tests should fail spectacularly.
* add a method takeAll to the Hero class, but leave it empty for now, and run the tests again. What happens?
* make the tests pass by writing the code for takeAll in the Hero class. (Hint — look for some existing code that does something with all the items in a location. Can you use the same pattern?)
* update the code in main.js processVerbObjectCommand to recognise the command "take all" and call this method on the hero.
##TASK 4
Complete the method should DropAllAtALocation to test/heroTest.js, implement the appropriate method on the Hero class so that the tests pass, and add it to the commands that the game understands.
##TASK 5 (homework)
Take a look at the original Colossal Cave Adventure by Crowther and Woods (the Wikipedia page on the game has links to numerous online and downloadable versions). Can you think of how you'd add some of the features of the original adventure to our little JavaScript game? For example
* You can only open a door if you have a key
* Magic words which if used at particular places introduce items, open passages, teleport the hero
* Scoring
* Saving the game
##TASK 6 (homework — advanced)
If you are more familiar with JavaScript and coding in general: the game engine in main.js is quite obvious, but not as it stands particularly easy to extend with new commands and capabilities. How might you make it easier to add the functionality you've explored in Task 5.
<file_sep>'use strict';
const Location = require('./model/location');
const Hero = require('./model/hero');
const Item = require('./model/item');
const { runGame } = require('./engine');
main();
// ===============================
function main() {
const heroName = process.argv[2] || 'adventurer';
const initialLocation = initialiseMap();
const hero = new Hero(heroName, initialLocation);
runGame(hero);
}
// ===============================
function initialiseMap() {
const clearing = new Location('clearing', 'A clearing in a wood.');
const garden = new Location('garden', 'A pretty garden. Birds are singing.');
const hut = new Location('dark hut', 'It smells musty in here.');
const sword = new Item('sword', 'A sharp, shining sword.');
const candle = new Item('candle', 'An old wax candle.');
const eagle = new Item('eagle', 'A proud eagle. It shuffles warily on its perch.');
clearing.addExit('east', 'path', garden);
garden.addExit('west', 'path', clearing);
garden.addExit('north', 'hut', hut);
garden.place(sword);
hut.addExit('south', 'door', garden);
hut.place(candle);
hut.place(eagle);
return clearing;
}
<file_sep>'use strict';
class Item {
constructor(name, description) {
this.name = name;
this.description = description;
}
getName() {
return this.name;
}
getDescription() {
return this.description;
}
}
module.exports = Item;
| 05f19fd0611b829735971a3d3b471cb7cbb997c5 | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | davethehat/adventure | bafef27dbd0ef743daee6a6538b53d8b2b36ea4f | bdada43fac6686152a3a2c2d208895aa033330e9 |
refs/heads/master | <repo_name>aiden0206/Do-main<file_sep>/EOG_HMM.py
from math import log
import numpy as np
import numpy.linalg as lin
import math
def _normalize_prob(prob, item_set):
result = {}
if prob is None:
number = len(item_set)
for item in item_set:
result[item] = 1.0 / number
else:
prob_sum = 0.0
for item in item_set:
prob_sum += prob.get(item, 0)
if prob_sum > 0:
for item in item_set:
result[item] = prob.get(item, 0) / prob_sum
else:
for item in item_set:
result[item] = 0
return result
def _normalize_prob_two_dim(prob, item_set1, item_set2):
result = {}
if prob is None:
for item in item_set1:
result[item] = _normalize_prob(None, item_set2)
else:
for item in item_set1:
result[item] = _normalize_prob(prob.get(item), item_set2)
return result
def _count(item, count):
if item not in count:
count[item] = 0
count[item] += 1
def _count_two_dim(item1, item2, count):
if item1 not in count:
count[item1] = {}
_count(item2, count[item1])
def gaussian(x, mean, cov, correction = False):
x = np.array(x)
D = x.shape[0]
coeff = 1 / ((2 * math.pi) ** (D / 2) * lin.det(cov) ** 0.5)
_exp = math.exp(-0.5 * (x - mean).T @ lin.inv(cov) @ (x - mean))
if correction == False:
return coeff * _exp
elif correction == True:
n = coeff * _exp
m = abs(int(math.log10(n)))
return n * 10 ** m
# HMM model with multivariate gaussian emission distribution
class Model(object):
# emission_prob: {state1: (mu1, cov1), ...}
def __init__(self, states, start_prob=None, tran_prob=None, emit_prob=None):
self._states = set(states)
self._start_prob = _normalize_prob(start_prob, self._states)
self._trans_prob = _normalize_prob_two_dim(tran_prob, self._states, self._states)
# multivariate gaussian distribution
self._emit_prob = emit_prob
def _forward(self, sequence):
sequence_length = len(sequence)
if sequence_length == 0:
return []
alpha = [{}]
for state in self._states:
element = self._emit_prob[state]
gauss = gaussian(x=sequence[0], mean=element[0], cov=element[1])
alpha[0][state] = self._start_prob[state] * gauss
for index in range(1, sequence_length):
alpha.append({})
for state_to in self._states:
prob = 0
for state_from in self._states:
prob += alpha[index - 1][state_from] * \
self._trans_prob[state_from][state_to]
element = self._emit_prob[state_to]
gauss = gaussian(x=sequence[index], mean=element[0], cov=element[1])
alpha[index][state_to] = prob * gauss
return alpha
def _backward(self, sequence):
sequence_length = len(sequence)
if sequence_length == 0:
return []
beta = [{}]
for state in self._states:
beta[0][state] = 1
for index in range(sequence_length - 1, 0, -1):
beta.insert(0, {})
for state_from in self._states:
prob = 0
for state_to in self._states:
element = self._emit_prob[state_to]
gauss = gaussian(x=sequence[index], mean=element[0], cov=element[1])
prob += beta[1][state_to] * \
self._trans_prob[state_from][state_to] * gauss
beta[0][state_from] = prob
return beta
def evaluate(self, sequence):
length = len(sequence)
if length == 0:
return 0
prob = 0
alpha = self._forward(sequence)
for state in alpha[length - 1]:
prob += alpha[length - 1][state]
return prob
def viterbi(self, sequence):
sequence_length = len(sequence)
if sequence_length == 0:
return []
delta = {}
#print('index:', 0)
for state in self._states:
element = self._emit_prob[state]
gauss = gaussian(x=sequence[0], mean=element[0], cov=element[1])
delta[state] = self._start_prob[state] * gauss
#print('gauss:', gauss, 'start_prob:', self._start_prob[state])
#print('delta:', delta)
pre = []
for index in range(1, sequence_length):
#print('index:', index)
delta_bar = {}
pre_state = {}
for state_to in self._states:
max_prob = 0
max_state = None
for state_from in self._states:
prob = delta[state_from] * self._trans_prob[state_from][state_to]
if prob > max_prob:
max_prob = prob
max_state = state_from
element = self._emit_prob[state_to]
gauss = gaussian(x=sequence[index], mean=element[0], cov=element[1])
#print('gauss:', gauss)
delta_bar[state_to] = max_prob * gauss
pre_state[state_to] = max_state
delta = delta_bar
#print('delta:', delta)
pre.append(pre_state)
max_state = None
max_prob = 0
for state in self._states:
if delta[state] > max_prob:
max_prob = delta[state]
max_state = state
if max_state is None:
raise Exception('delta 값이 너무 작아서 0으로 간주되었습니다.')
# 상태 역순 추적
result = [max_state]
for index in range(sequence_length - 1, 0, -1):
max_state = pre[index - 1][max_state]
result.insert(0, max_state)
return result
def baumwelch(self, sequence, smoothing=0):
length = len(sequence)
alpha = self._forward(sequence)
beta = self._backward(sequence)
gamma = []
for index in range(length):
prob_sum = 0
gamma.append({})
for state in self._states:
prob = alpha[index][state] * beta[index][state]
gamma[index][state] = prob
prob_sum += prob
if prob_sum == 0:
continue
for state in self._states:
gamma[index][state] /= prob_sum
xi = []
for index in range(length - 1):
prob_sum = 0
xi.append({})
for state_from in self._states:
xi[index][state_from] = {}
for state_to in self._states:
element = self._emit_prob[state_to]
gauss = gaussian(x=sequence[index+1], mean=element[0], cov=element[1])
prob = alpha[index][state_from] * beta[index + 1][state_to] * \
self._trans_prob[state_from][state_to] * gauss
xi[index][state_from][state_to] = prob
prob_sum += prob
if prob_sum == 0:
continue
for state_from in self._states:
for state_to in self._states:
xi[index][state_from][state_to] /= prob_sum
states_number = len(self._states)
for state in self._states:
# update start probability
self._start_prob[state] = \
(smoothing + gamma[0][state]) / (1 + states_number * smoothing)
# update transition probability
gamma_sum = 0
for index in range(length - 1):
gamma_sum += gamma[index][state]
if gamma_sum > 0:
denominator = gamma_sum + states_number * smoothing
for state_to in self._states:
xi_sum = 0
for index in range(length - 1):
xi_sum += xi[index][state][state_to]
self._trans_prob[state][state_to] = (smoothing + xi_sum) / denominator
else:
for state_to in self._states:
self._trans_prob[state][state_to] = 0
# update emission probability
gamma_sum += gamma[length - 1][state]
emit_gamma_sum = {}
mean_upper = 0
cov_upper = 0
for index in range(length):
mean_upper += gamma[index][state] * sequence[index]
new_mean = mean_upper / gamma_sum
for index in range(length):
dev = sequence[index] - new_mean
cov_upper += gamma[index][state] * np.array([dev]).T @ np.array([dev])
new_cov = cov_upper / gamma_sum
if gamma_sum > 0:
self._emit_prob[state] = (new_mean, new_cov)
else:
raise Exception('gamma_sum의 값이 0입니다.')<file_sep>/README.md
이 활동은 스타트업 domain에서 제작한 하드웨어로부터 수집된 EOG(electrooculography)에서 안구 운동 상태를 추정하는 것입니다.
EOG_HMM.py: 주 알고리즘으로 은닉 마르코프 모델을 사용하였습니다. https://github.com/jason2506/PythonHMM의 hmm.py 코드를 기반으로 했으나 활동 용도에 맞게 혼합 가우시안 방출 분포를 갖도록 확장했습니다.
preprocess.py: HMM 모델의 성능을 높이기 위해 제작한 뇌파 전처리 코드입니다. 기본적인 정규화와 함께 성능 저하의 주 원인인 베이스라인 드리프트를 수정하는 메소드가 있습니다.
test.py: 성능 테스트에 사용된 코드입니다. 아래 사진과 같은 결과를 얻습니다. m은 해당 시점에서 안구가 중앙에 위치함, u는 위, d는 아래에 위치함을 뜻합니다.
train.py 모델 학습에 사용된 코드입니다.
<img width="981" alt="result" src="https://user-images.githubusercontent.com/62476546/99537335-e112e800-29ee-11eb-93ea-dd6592cbfc8c.png"><file_sep>/preprocess.py
import numpy as np
class preprocess:
def __init__(self, file_path, num_channels):
self._file = file_path
self._channels = num_channels
# collected from ADS 1299
def file_load(self):
self.data = {}
for i in range(self._channels):
file = open(self._file)
_list = []
while True:
line = file.readline()
if not line: break
_list.append(float(line.split('\t')[i]))
self.data['channel'+str(i)] = _list
file.close()
#print('self.data 변수에 dictionary 형식으로 저장.')
return
# base_range: [start, end]의 list. 0점으로 맞출 데이터의 범위이며 해당 구간 데이터의 평균을 0점으로 간주.
def normalize(self, base_range):
self.norm = {}
for i in range(self._channels):
file = open(self._file)
_list = []
while True:
line = file.readline()
if not line: break
_list.append(float(line.split('\t')[i]))
self.norm['channel'+str(i)] = _list
file.close()
for i in range(self._channels):
_sum = 0
start, end = base_range[0], base_range[1]
key = 'channel' + str(i)
for j in self.norm[key][start:end]:
_sum += j
avg = _sum / (end - start)
norm = []
for j in self.norm[key]:
norm.append(j - avg)
_max = np.array(norm).max()
_min = -np.array(norm).min()
if _max > _min:
self.norm[key] = norm / _max
else:
self.norm[key] = norm / _min
#print('self.norm 변수에 dictionary 형식으로 저장.')
return
# data: 1D array
def linear_baseline(self, data, start_range=[5, 60], end_range=[950, 980]):
start, end = start_range[0], start_range[1]
mid = (end + start) / 2
_sum = 0
for i in range(start, end):
_sum += data[i]
avg = _sum / (end - start)
start, end = end_range[0], end_range[1]
mid1 = (end + start) / 2
_sum = 0
for i in range(start, end):
_sum += data[i]
avg1 = _sum / (end - start)
a = (avg1 - avg) / (mid1 - mid)
data_correction = []
for i in range(len(data)):
data_correction.append(data[i] - a * (i - mid))
return data_correction<file_sep>/train.py
from EOG_HMM import Model
from math import log
def train(states, initial_start, initial_tran, initial_emit, sequences, delta=0.0001, smoothing=0):
model = Model(states=states, start_prob=initial_start, tran_prob=initial_tran, emit_prob=initial_emit)
old_likelihood = 0
old_likelihood += log(model.evaluate(sequences))
while True:
new_likelihood = 0
model.baumwelch(sequences)
new_likelihood += log(model.evaluate(sequences))
if abs(new_likelihood - old_likelihood) < delta:
break
old_likelihood = new_likelihood
return model<file_sep>/test.py
from EOG_HMM import Model
import numpy as np
from preprocess import preprocess
a1 = preprocess('/Users/aiden0206/Desktop/Domain/EOG/EOG 데이터셋/ud/mudududm1.txt', 2)
a1.normalize([5, 70])
ch1 = a1.linear_baseline(a1.norm['channel0'])
ch2 = a1.linear_baseline(a1.norm['channel1'])
seq = np.array([ch1, ch2]).T
states = ('up', 'down', 'middle')
start_prob = {'up': 0.333, 'down': 0.333, 'middle': 0.333}
transition_prob = {'up': {'up': 0.5, 'middle': 0.5}, 'down': {'down': 0.5, 'middle': 0.5}}
mu1 = [0, 0]
mu2 = [-0.3, -0.4]
mu3 = [0.6, 0.4]
cov1 = [[0.5, 0.0], [0.0, 0.5]]
cov2 = [[0.5, 0.0], [0.0, 0.5]]
cov3 = [[0.5, 0.0], [0.0, 0.5]]
emitting_prob = {'middle': (mu1, cov1), 'up': (mu2, cov2), 'down': (mu3, cov3)}
ud_test = Model(states, start_prob, transition_prob, emitting_prob)
sep_data = []
for window in range(1000 // 2):
sep_data.append(ud_test.viterbi(sequence = seq[window*2 : (window + 1)*2]))
# plot
figs = plt.figure(figsize=(20, 15))
ax1 = figs.add_subplot(311)
ax2 = figs.add_subplot(312)
ax3 = figs.add_subplot(313)
for i in range(1000 // 10):
location = 0.04 * i
text = sep_data[i*(5)][1]
if text == 'middle':
ax1.annotate('m', xy=(location, 1), xytext=(location, 1.5), arrowprops = dict(facecolor='black'))
elif text == 'up':
ax1.annotate('u', xy=(location, 1), xytext=(location, 1.5), arrowprops = dict(facecolor='red'))
elif text == 'down':
ax1.annotate('d', xy=(location, 1), xytext=(location, 1.5), arrowprops = dict(facecolor='blue'))
x = np.linspace(0, 4, 1000)
ax1.plot(x, x)
ax2.plot(x, ch1)
ax3.plot(x, ch2)
plt.show() | 2e6ebb8a6e51512a263425704dd98836e3d29924 | [
"Markdown",
"Python"
] | 5 | Python | aiden0206/Do-main | be6d04256787e8b6c3bc137d183a8153987b3c37 | f890d1577266c644d87a7dc00af4c19bcfa43e10 |
refs/heads/master | <repo_name>GBAleksandrGB/Tomilov_Aleksandr_dz_6<file_sep>/task_6_1.py
def log_gen():
with open('nginx_logs.txt', 'r', encoding='utf-8') as f:
for new_line in f:
new_line = f.readline().replace('"', '').split()
yield new_line[0], new_line[5], new_line[6]
print(*list(log_gen())[:50], sep='\n')
<file_sep>/task_6_3.py
def length_check(list1, list2):
while True:
if len(list1) > len(list2):
list2.append('None\n')
return list1, list2
elif len(list1) < len(list2):
return 1
def open_users():
with open('users.csv', 'r', encoding='utf-8') as f:
full_name_list = f.readlines()
for i, full_name in enumerate(full_name_list):
full_name_list[i] = full_name.replace(',', ' ').replace('\n', '')
return full_name_list
def open_hobby():
with open('hobby.csv', 'r', encoding='utf-8') as f:
user_hobby_list = f.readlines()
for i, user_hobby in enumerate(user_hobby_list):
user_hobby_list[i] = user_hobby.replace(',', ', ')
return user_hobby_list
def write_users():
with open('users_hobby.txt', 'a', encoding='utf-8') as f:
full_name_list, user_hobby_list = length_check(open_users(), open_hobby())
users_hobby = dict(zip(full_name_list, user_hobby_list))
for key, val in users_hobby.items():
f.write(f'{key}: {val}')
write_users()
<file_sep>/task_6_6_add_sale.py
def add_sale(argv):
argv = argv[1:]
argv.append('\n')
with open('bakery.csv', 'a', encoding='utf-8') as f:
f.writelines(argv)
return 0
if __name__ == '__main__':
import sys
exit(add_sale(sys.argv))
<file_sep>/task_6_6_show_sales.py
# смог вывести только общий список
def show_sales(argv):
program, *args = argv
with open('bakery.csv', 'r', encoding='utf-8') as f:
sale_list = f.readlines()
for i, el in enumerate(sale_list):
sale_list[i] = el.replace('\n', '')
if not args:
print(sale_list[i])
return 0
if __name__ == '__main__':
import sys
exit(show_sales(sys.argv))
<file_sep>/task_6_2.py
ip_numbers = {}
with open('nginx_logs.txt', 'r', encoding='utf-8') as f:
file_lines = f.readlines()
f.seek(0)
for line in f:
new_line = f.readline()
ip = new_line.split()[0]
if ip not in ip_numbers:
# через фильтр вычисляет спамера за 50 сек
log_filter = list(filter(lambda el: el.split()[0] == ip, file_lines))
ip_numbers[ip] = len(log_filter)
else:
continue
key_val = ip_numbers.items()
key_val_list = list(key_val)
max_ip_number = max(key_val_list, key=lambda x: x[1])
print(f'Спамер - {max_ip_number[0]} с числом запросов - {max_ip_number[1]}')
| 4a7a33c3da739d48a14c1d0dcd04afa64e1ca2c0 | [
"Python"
] | 5 | Python | GBAleksandrGB/Tomilov_Aleksandr_dz_6 | 712ba59f7f20152424f4f37e67e8c246b0f5753d | 0d1355df554402321d893e9d52c2a5aa59c2b232 |
refs/heads/master | <file_sep>package com.myapp.sshah.instr.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.myapp.sshah.instr.R;
import com.myapp.sshah.instr.models.InstagramPhoto;
import com.squareup.picasso.Picasso;
import java.util.List;
/**
* Created by sshah1 on 10/11/15.
*/
public class InstagramPhotosAdapter extends ArrayAdapter<InstagramPhoto> {
public InstagramPhotosAdapter(Context context, List<InstagramPhoto> objects) {
super(context, android.R.layout.simple_list_item_1, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
InstagramPhoto photo = getItem(position);
if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.photo_feed_item, parent, false);
}
TextView tvUsername = (TextView)convertView.findViewById(R.id.tvUsername);
TextView tvCaption = (TextView) convertView.findViewById(R.id.tvCaption);
ImageView ivPhoto = (ImageView) convertView.findViewById(R.id.ivPhoto);
ImageView ivProfilePhoto = (ImageView) convertView.findViewById(R.id.ivProfileImage);
TextView tvTimeAgo = (TextView)convertView.findViewById(R.id.tvTimeAgo);
TextView tvLikes = (TextView) convertView.findViewById(R.id.tvLikes);
TextView tvComment = (TextView) convertView.findViewById(R.id.tvComment1);
tvUsername.setText(photo.user.username);
tvCaption.setText(photo.caption);
tvTimeAgo.setText(photo.relativeTime);
tvLikes.setText(photo.likeCount + " Likes");
if(!photo.comments.isEmpty()){
tvComment.setText(photo.comments.get(0).comment);
}else{
tvComment.setText("");
}
ivPhoto.setImageResource(0);
ivProfilePhoto.setImageResource(0);
Picasso.with(getContext()).load(photo.imageUrl).into(ivPhoto);
Picasso.with(getContext()).load(photo.user.profileImageUrl).into(ivProfilePhoto);
return convertView;
}
}
<file_sep>package com.myapp.sshah.instr.models;
/**
* Created by sshah1 on 10/13/15.
*/
public class Comment {
public User user;
public String comment;
}
<file_sep>package com.myapp.sshah.instr.models;
/**
* Created by sshah1 on 10/13/15.
*/
public class User {
public String username;
public String profileImageUrl;
}
| 4dfb594f456378b300b0a2b56ad789d5dbcf3d45 | [
"Java"
] | 3 | Java | saurabhshah510/codepath-android-instagram | 12332b3896b98202c8d0da95f9fabf20a2c89a04 | 977812102cb8d187a1fdf0f4afc16ef1d45d5eb7 |
refs/heads/master | <repo_name>braverun/menu-project<file_sep>/scripts/main.js
(function(){
var MenuItem = Backbone.Model.extend({
defaults: {
image: '',
name: '',
brewery: '',
description: '',
price: '',
type: '',
}
});
var MenuCollection = Backbone.Collection.extend({
url: 'https://api.parse.com/1/classes/menuItems',
model: MenuItem,
parse: function(response){
console.log(response);
return response.results;
}
});
var MenuView = Backbone.View.extend({
template: _.template($('[data-template-name=beers]').text()),
render: function(){
$('.js-lagers').html(this.template(this.model.toJSON()));
}
});
var AppRouter = Backbone.Router.extend({
routes: {
'': 'index'
},
initialize: function(){
this.menuCollection = new MenuCollection();
this.menu = new MenuView({collection: this.menuCollection});
},
index: function(){
var self = this;
this.menuCollection.fetch().done(function(){
self.menu.render();
});
},
});
$.ajaxSetup({
headers: {
"X-Parse-Application-Id": "En0HvlSzhghm8rQbbxEudy4jff7J84lvC7C2tWKh",
"X-Parse-REST-API-Key": "<KEY>"
}
});
$(document).ready(function(){
$(".js-sticky-containers").sticky({topSpacing:100});
window.router = new AppRouter();
Backbone.history.start();
console.log('ninja boots');
});
})();
| 7cb184f8c7f53ab40d51afaa563d170f21fe9750 | [
"JavaScript"
] | 1 | JavaScript | braverun/menu-project | 366152c52d33c01c4e3d74333e2b12d49b0a9b4a | 37ce7f3e7ccde35db4378f476e2494bb6c13dd2d |
refs/heads/master | <file_sep># this code gets and clean the aimed dataset
library(reshape2)
# merge the dataset of train and test
Xtrain <- read.table("UCI HAR Dataset/train/X_train.txt")
ytrain <- read.table("UCI HAR Dataset/train/y_train.txt")
trainSubject <- read.table("UCI HAR Dataset/train/subject_train.txt")
train <- cbind(trainSubject, Xtrain, ytrain)
Xtest <- read.table("UCI HAR Dataset/test/X_test.txt")
ytest <- read.table("UCI HAR Dataset/test/y_test.txt")
testSubject <- read.table("UCI HAR Dataset/test/subject_test.txt")
test <- cbind(testSubject, Xtest, ytest)
# extract only the data on mean and standard deviation
features <- read.table("UCI HAR Dataset/features.txt")
features[,2] <- as.character(features[,2])
features_select <- grep(".*mean.*|.*std.*", features[,2])
Xtrain_want <- Xtrain[,features_select]
Xtest_want <- Xtest[,features_select]
train_want <- cbind(trainSubject, ytrain, Xtrain_want)
test_want <- cbind(testSubject, ytest, Xtest_want)
# use descriptive activity names to name the activities in the data set
activity_label <- read.table("UCI HAR Dataset/activity_labels.txt")
# create an intermediate data set and label the data set with descriptive activity names
data_want <- rbind(train_want, test_want)
colnames(data_want) <- c("subject", "activity",features[features_select,2])
# create the final dataset
data_want_melt <- melt(data_want, id=c("subject","activity"))
data_want_mean <- dcast(data_want_melt, subject+activity ~ variable, mean)
# output the data set
write.table(data_want_mean, "Final_tidy_data.txt", row.names=F, quote=F)
| 8fa7a5cce3c92c78a35d44b7479eaba695de508c | [
"R"
] | 1 | R | MaxMCao/Getting-and-Cleaning-Data-Course-Project | 684d039150a01f3be66f4f289bb7a1b01f3291a0 | f27386e68772a273d59c556321c7495f202f02d6 |
refs/heads/master | <repo_name>abstractthis/gowedding<file_sep>/models/models.go
package models
import (
"log"
"os"
"time"
"github.com/abstractthis/gowedding/config"
_ "github.com/mattn/go-sqlite3"
"github.com/jinzhu/gorm"
)
var Logger = log.New(os.Stdout, " ", log.Ldate|log.Ltime|log.Lshortfile)
var db gorm.DB
var err error
func Initialize() error {
Logger.Printf("Initializing DB....%s\n", config.Conf.DBPath)
db, err = gorm.Open("sqlite3", config.Conf.DBPath)
if err != nil {
Logger.Println(err)
return err
}
db.LogMode(config.Conf.IsDev)
db.SetLogger(Logger)
// If the file doesn't exist create it and build out DB
if _, err := os.Stat(config.Conf.DBPath); os.IsNotExist(err) {
Logger.Printf("Database not found... creating db at %s\n", config.Conf.DBPath)
db.CreateTable(&Invite{})
db.CreateTable(&Guest{})
db.CreateTable(&Nonce{})
db.CreateTable(&Email{})
err = seedTables()
Logger.Println("...database created successfully.")
if config.Conf.SendOops {
Logger.Println("Creating pending oops emails...")
createOopsEmails()
Logger.Println("emails created.")
}
if err != nil {
Logger.Printf("Model initalization failed --> %v\n", err)
return err
}
}
Logger.Println("Database initialized.")
return nil
}
func createOopsEmails() error {
err := db.Exec("insert into 'emails' ('invite_id','address','type','sent') values (1001,'<EMAIL>','oops',0);").Error
err = db.Exec("insert into 'emails' ('invite_id','address','type','sent') values (1002,'<EMAIL>','oops',0);").Error
err = db.Exec("insert into 'emails' ('invite_id','address','type','sent') values (1003,'<EMAIL>','oops',0);").Error
return err
}
func seedTables() error {
Logger.Print("Building out tables...")
stamp := time.Now()
i := &Invite{
ID: 2323,
Guests: []Guest{
{First: "david", Last: "smith", IsAttending: false,},
{First: "duong", Last: "nguyen", IsAttending: false,},
},
UpdatedAt: stamp,
}
err := db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 1,
Guests: []Guest{
{First: "kirstine", Last: "wolfe", IsAttending: false,},
{First: "cheryl", Last: "herrara", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 2,
Guests: []Guest{
{First: "daniel", Last: "livesay", IsAttending: false,},
{First: "amanda", Last: "livesay", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 3,
Guests: []Guest{
{First: "farid", Last: "ansari", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 4,
Guests: []Guest{
{First: "carolyn", Last: "apostolides", IsAttending: false,},
{First: "john", Last: "apostolides", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 5,
Guests: []Guest{
{First: "rob", Last: "linton", IsAttending: false,},
{First: "diana", Last: "linton", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 6,
Guests: []Guest{
{First: "onelia", Last: "estudillo", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 7,
Guests: []Guest{
{First: "linh", Last: "forse", IsAttending: false,},
{First: "jason", Last: "forse", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 8,
Guests: []Guest{
{First: "dorothy", Last: "bednar", IsAttending: false,},
{First: "jeremy", Last: "bednar", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 9,
Guests: []Guest{
{First: "julie", Last: "jeanes", IsAttending: false,},
{First: "nathan", Last: "jeanes", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 10,
Guests: []Guest{
{First: "patrick", Last: "schleck", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 11,
Guests: []Guest{
{First: "katie", Last: "picone", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 12,
Guests: []Guest{
{First: "shih-yi", Last: "kim", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 13,
Guests: []Guest{
{First: "maricel", Last: "fong", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 14,
Guests: []Guest{
{First: "esther", Last: "jeong", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 15,
Guests: []Guest{
{First: "jeana", Last: "yi", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 16,
Guests: []Guest{
{First: "billie", Last: "wilson", IsAttending: false,},
{First: "jon", Last: "wilson", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 17,
Guests: []Guest{
{First: "leslie", Last: "yeung", IsAttending: false,},
{First: "karl", Last: "thoennessen", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 18,
Guests: []Guest{
{First: "suprat", Last: "wilson", IsAttending: false,},
{First: "scott", Last: "wilson", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 19,
Guests: []Guest{
{First: "chris", Last: "falkiewicz", IsAttending: false,},
{First: "kari", Last: "falkiewicz", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 20,
Guests: []Guest{
{First: "chad", Last: "richardson", IsAttending: false,},
{First: "janice", Last: "richardson", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 21,
Guests: []Guest{
{First: "bob", Last: "schuck", IsAttending: false,},
{First: "brittany", Last: "wright", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 22,
Guests: []Guest{
{First: "sabrina", Last: "meyers", IsAttending: false,},
{First: "stacey", Last: "meyers", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 23,
Guests: []Guest{
{First: "lynn", Last: "meyers", IsAttending: false,},
{First: "sandy", Last: "meyers", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 24,
Guests: []Guest{
{First: "christine", Last: "young", IsAttending: false,},
{First: "danny", Last: "young", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 25,
Guests: []Guest{
{First: "tiffany", Last: "cereghino", IsAttending: false,},
{First: "chris", Last: "cereghino", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 26,
Guests: []Guest{
{First: "scott", Last: "caston", IsAttending: false,},
{First: "lauren", Last: "caston", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 27,
Guests: []Guest{
{First: "megan", Last: "thomas", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 28,
Guests: []Guest{
{First: "ha", Last: "nguyen", IsAttending: false,},
{First: "joe", Last: "nguyen", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 29,
Guests: []Guest{
{First: "wendy", Last: "lau", IsAttending: false,},
{First: "ben", Last: "lau", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 30,
Guests: []Guest{
{First: "peter", Last: "cho", IsAttending: false,},
{First: "young", Last: "cho", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 31,
Guests: []Guest{
{First: "donnie", Last: "demuth", IsAttending: false,},
{First: "suprina", Last: "dorai", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 32,
Guests: []Guest{
{First: "jorgina", Last: "hall", IsAttending: false,},
{First: "michael", Last: "hall", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 33,
Guests: []Guest{
{First: "marella", Last: "bigcas", IsAttending: false,},
{First: "jo-lawrence", Last: "bigcas", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 34,
Guests: []Guest{
{First: "jenny", Last: "mun", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 35,
Guests: []Guest{
{First: "mary", Last: "an", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 36,
Guests: []Guest{
{First: "anna", Last: "brown", IsAttending: false,},
{First: "jason", Last: "brown", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 37,
Guests: []Guest{
{First: "brianna", Last: "graber", IsAttending: false,},
{First: "chris", Last: "graber", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 38,
Guests: []Guest{
{First: "becky", Last: "malcolm", IsAttending: false,},
{First: "mike", Last: "malcolm", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 39,
Guests: []Guest{
{First: "erica", Last: "shalenberg", IsAttending: false,},
{First: "eli", Last: "shalenberg", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 40,
Guests: []Guest{
{First: "luis", Last: "ocegueda", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 41,
Guests: []Guest{
{First: "keith", Last: "smith", IsAttending: false,},
{First: "katherine", Last: "hartvickson", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 42,
Guests: []Guest{
{First: "gail", Last: "henry", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 43,
Guests: []Guest{
{First: "michael", Last: "smith", IsAttending: false,},
{First: "liz", Last: "cornelissen", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 44,
Guests: []Guest{
{First: "kevin", Last: "smith", IsAttending: false,},
{First: "luz", Last: "montesclaros", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 45,
Guests: []Guest{
{First: "kc", Last: "smith", IsAttending: false,},
{First: "jake", Last: "dewitt", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 46,
Guests: []Guest{
{First: "daniel", Last: "lieras", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 47,
Guests: []Guest{
{First: "david", Last: "henry", IsAttending: false,},
{First: "darryl", Last: "henry", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 48,
Guests: []Guest{
{First: "dave", Last: "henry", IsAttending: false,},
{First: "alora", Last: "henry", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 49,
Guests: []Guest{
{First: "kevin", Last: "tran", IsAttending: false,},
{First: "alyssa", Last: "fumar", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 50,
Guests: []Guest{
{First: "heather", Last: "brown", IsAttending: false,},
{First: "richard", Last: "brown", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 51,
Guests: []Guest{
{First: "lee", Last: "hartvickson", IsAttending: false,},
{First: "cameryn", Last: "hartvickson", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 52,
Guests: []Guest{
{First: "mandie", Last: "nguyen", IsAttending: false,},
{First: "minh", Last: "nguyen", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 53,
Guests: []Guest{
{First: "diem", Last: "nguyen", IsAttending: false,},
{First: "binh", Last: "nguyen", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 101,
Guests: []Guest{
{First: "hang", Last: "nguyen", IsAttending: false,},
{First: "hai", Last: "nguyen", IsAttending: false,},
{IsAttending: false,},
{IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 102,
Guests: []Guest{
{First: "elizabeth", Last: "nguyen", IsAttending: false,},
{IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 103,
Guests: []Guest{
{First: "kim", Last: "nguyen", IsAttending: false,},
{First: "ken", Last: "luu", IsAttending: false,},
{IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 104,
Guests: []Guest{
{First: "duyen", Last: "nguyen", IsAttending: false,},
{First: "hoang", Last: "tran", IsAttending: false,},
{First: "audrey", Last: "tran", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 105,
Guests: []Guest{
{First: "trang", Last: "nguyen", IsAttending: false,},
{First: "eli", Last: "wheeler", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 106,
Guests: []Guest{
{First: "huy", Last: "nguyen", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 107,
Guests: []Guest{
{First: "anh", Last: "dinh", IsAttending: false,},
{First: "kaylee", Last: "luong", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 108,
Guests: []Guest{
{First: "kinh", Last: "nguyen", IsAttending: false,},
{IsAttending: false,},
{IsAttending: false,},
{IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 109,
Guests: []Guest{
{First: "hung", Last: "nguyen", IsAttending: false,},
{First: "judy", Last: "tang", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 110,
Guests: []Guest{
{First: "dziem", Last: "nguyen", IsAttending: false,},
{First: "duong", Last: "hoang", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 111,
Guests: []Guest{
{First: "huynh", Last: "nguyen", IsAttending: false,},
{First: "tan", Last: "nguyen", IsAttending: false,},
{First: "thang", Last: "nguyen", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 112,
Guests: []Guest{
{First: "kathy", Last: "nguyen", IsAttending: false,},
{First: "rob", Last: "petterson", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 113,
Guests: []Guest{
{First: "thao", Last: "tran", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 114,
Guests: []Guest{
{First: "quyen", Last: "le", IsAttending: false,},
{IsAttending: false,},
{IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 115,
Guests: []Guest{
{First: "cuong", Last: "tran", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 116,
Guests: []Guest{
{First: "toan", Last: "nguyen", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 117,
Guests: []Guest{
{First: "ha", Last: "nguyen", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 118,
Guests: []Guest{
{First: "nang", Last: "nguyen", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 119,
Guests: []Guest{
{First: "lien", Last: "thach", IsAttending: false,},
{First: "thuong", Last: "thach", IsAttending: false,},
{First: "teena", Last: "thach", IsAttending: false,},
{First: "james", Last: "thach", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 120,
Guests: []Guest{
{First: "hung", Last: "tran", IsAttending: false,},
{IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 121,
Guests: []Guest{
{First: "mylinh", Last: "nguyen", IsAttending: false,},
{First: "tony", Last: "tran", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 122,
Guests: []Guest{
{First: "jessica", Last: "nguyen", IsAttending: false,},
{First: "joe", Last: "tran", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 123,
Guests: []Guest{
{First: "huy", Last: "tran", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 124,
Guests: []Guest{
{First: "trung", Last: "vu", IsAttending: false,},
{First: "katrina", Last: "vu", IsAttending: false,},
{First: "john", Last: "vu", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 125,
Guests: []Guest{
{First: "thanh", Last: "nguyen", IsAttending: false,},
{IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 126,
Guests: []Guest{
{First: "hun", Last: "nguyen", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 127,
Guests: []Guest{
{First: "huong", Last: "nguyen", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 129,
Guests: []Guest{
{First: "ngoc", Last: "tran", IsAttending: false,},
{IsAttending: false,},
{IsAttending: false,},
{IsAttending: false,},
{IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 132,
Guests: []Guest{
{First: "rosemary", Last: "nguyen", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 133,
Guests: []Guest{
{First: "alyssa", Last: "nguyen", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 135,
Guests: []Guest{
{First: "thai", Last: "la", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 139,
Guests: []Guest{
{First: "lam", Last: "le", IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
i = &Invite{
ID: 301,
Guests: []Guest{
{First: "trinh", Last: "nguyen", IsAttending: false,},
{IsAttending: false,},
},
UpdatedAt: stamp,
}
err = db.Create(&i).Error
if err != nil {
return err
}
Logger.Printf("*~~ Invite %d inserted ~~*\n", i.ID)
return err
}
<file_sep>/controllers/utils.go
package controllers
import (
"os"
"log"
"fmt"
"net/http"
"encoding/json"
"unicode"
"html/template"
"strings"
)
var Logger = log.New(os.Stdout, " ", log.Ldate|log.Ltime|log.Lshortfile)
func JSONResponse(w http.ResponseWriter, d interface{}, c int) {
dj, err := json.MarshalIndent(d, "", " ")
if err != nil {
http.Error(w, "Error creating JSON response", http.StatusInternalServerError)
Logger.Println(err)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(c)
fmt.Fprintf(w, "%s", dj)
}
func CreateResponse(w http.ResponseWriter, locURL string) {
headers := w.Header()
headers.Set("Content-Length", "0")
headers.Set("Content-Type", "text/plain; charset=utf-8")
headers.Set("Location", locURL)
w.WriteHeader(http.StatusCreated)
fmt.Fprint(w, "")
}
func CodeResponse(w http.ResponseWriter, c int) {
headers := w.Header()
headers.Set("Content-Length", "0")
headers.Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(c)
fmt.Fprint(w, "")
}
func ErrorResponse(w http.ResponseWriter, msg string) {
Logger.Println(msg)
http.Error(w, msg, http.StatusInternalServerError)
}
func ErrorResponseWithPayload(w http.ResponseWriter, c int) {
var tName string
if c == http.StatusNotFound {
tName = "templates/404.html"
} else {
tName = "templates/doh.html"
}
t, err := template.ParseFiles(tName)
if err != nil {
ErrorResponse(w, "Template Parse failure: " + tName)
return
}
w.WriteHeader(c)
t.Execute(w, nil)
}
func FirstLetterUpper(str string) string {
for i, v := range str {
return string(unicode.ToUpper(v)) + str[i+1:]
}
return ""
}
func CapIt(s string) string {
// Deal with hyphenated names first
hyphenChop := strings.Split(s, "-")
if len(hyphenChop) > 1 {
name := make([]string, len(hyphenChop))
for i, partial := range hyphenChop {
name[i] = FirstLetterUpper(partial)
}
return strings.Join(name, "-")
} else {
return FirstLetterUpper(s)
}
}
func FullName(first string, last string) string {
if first == "" && last == "" {
return ""
}
first = CapIt(first)
last = CapIt(last)
return first + " " + last
}
/*
* Used in the template for rendering Guest pagination values.
*/
func Sum(x, y int) int {
return x + y
}
<file_sep>/stats/cruncher.go
package stats
import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
"time"
"encoding/json"
"io/ioutil"
"github.com/abstractthis/gowedding/models"
"github.com/abstractthis/gowedding/config"
)
var Logger = log.New(os.Stdout, " ", log.Ldate|log.Ltime|log.Lshortfile)
var processInterval time.Duration
var statsDir string
var statFileCount int
type Cruncher struct {
shutdown chan bool
crunch func()
isRunning bool
}
type MIA struct {
InviteID int32
First string
Last string
}
type Stats struct {
Total int32
Attending int32
NotAttending int32
AllDinner int32
Beef int32
Fish int32
Veggie int32
Kid int32
NoResponse int32
Outstanding []MIA
}
func init() {
statsDir = "." + string(filepath.Separator) + "stats-data"
// Check to see if the stats directory exists if not create it
info, err := os.Stat(statsDir)
if err != nil {
err = os.Mkdir(statsDir,0777)
if err != nil {
Logger.Println("Unable to create stats directory!!")
panic(err)
}
info, err = os.Stat(statsDir)
} else {
if !info.IsDir() {
Logger.Println("stats exists but is not a directory!!")
panic(nil)
}
}
// See what versioning we're on file wise (count files in directory)
files, err := ioutil.ReadDir(statsDir)
if err != nil {
Logger.Println("Failed to read stats directory!!")
panic(err)
}
statFileCount = len(files)
if config.Conf.IsDev {
processInterval = 15 * time.Second
} else {
processInterval = 24 * time.Hour
}
}
func New() *Cruncher {
return &Cruncher{
crunch: generateStats,
isRunning: false,
}
}
func (c *Cruncher) Start() {
if c.isRunning {
Logger.Println("Cruncher is running. Stop Cruncher before starting it.")
return
}
Logger.Println("Spinning up Cruncher...")
c.shutdown = make(chan bool)
go func() {
c.isRunning = true
for {
select {
case <-time.After(processInterval):
// Drop out of select so emails can be processed
// after each interval amount passes.
case <-c.shutdown:
// stop processing emails and exit gofunction
return
}
c.crunch()
}
}()
Logger.Printf("Stats crunched every %v \n", processInterval)
}
func (c *Cruncher) Stop() {
Logger.Print("Stopping Cruncher...")
if c.isRunning {
c.shutdown <- true
c.isRunning = false
Logger.Println("stat crunching stopped.")
} else {
Logger.Println("Cruncher wasn't crunching.")
}
}
func generateStats() {
stats := new(Stats)
calcTotal(stats)
calcAttendance(stats)
calcDinnerSelections(stats)
calcMIA(stats)
if err := persist(stats); err == nil {
email()
}
}
func calcTotal(s *Stats) {
totalGuests := models.TotalGuests()
s.Total = totalGuests
}
func calcAttendance(s *Stats) {
guestsAttending := models.AttendingGuests()
s.Attending = guestsAttending
s.NotAttending = s.Total - guestsAttending
}
func calcDinnerSelections(s *Stats) {
beefCount := models.BeefDinners()
fishCount := models.FishDinners()
veggieCount := models.VeggieDinners()
kidCount := models.KidDinners()
s.Beef = beefCount
s.Fish = fishCount
s.Veggie = veggieCount
s.Kid = kidCount
s.AllDinner = beefCount + fishCount + veggieCount + kidCount
}
func calcMIA(s *Stats) {
miaGuests := models.MIAGuests()
s.Outstanding = make([]MIA, len(miaGuests))
for i, g := range miaGuests {
s.Outstanding[i] = MIA{
InviteID: int32(g.InviteID),
First: g.First,
Last: g.Last,
}
}
}
func persist(s *Stats) error {
j, jerr := json.MarshalIndent(s, "", " ")
if jerr != nil {
Logger.Printf("Failed to marshal stats-%d! --> %v\n", statFileCount, jerr)
return jerr
}
fileName := strings.Join([]string{statsDir, fmt.Sprintf("stats-%d.json", statFileCount)}, string(filepath.Separator))
err := ioutil.WriteFile(fileName, j, 0666)
if err != nil {
Logger.Printf("Failed to write stats-%d! --> %v\n", statFileCount, err)
return err
}
statFileCount += 1
return nil
}
func email() {
id := int32(5000 + statFileCount)
// decrement the file counter because it's incremented when
// the stats are written to disk and this happens after that.
emailType := fmt.Sprintf("stats-%d", statFileCount - 1)
err := models.AddStatEmail(id, emailType)
if err != nil {
Logger.Printf("Failed to queue %s email! --> %v\n", emailType, err)
}
}
func EmailContent(name string) (Stats,error) {
fileName := statsDir + string(filepath.Separator) + name + ".json"
stats := &Stats{}
hardJson, err := ioutil.ReadFile(fileName)
if err != nil {
Logger.Printf("Failed to read stats file[%s]! --> %v\n", fileName, err)
return *stats, err
}
err = json.Unmarshal(hardJson, stats)
if err != nil {
Logger.Printf("Failed to marshal stats file[%s]! --> %v\n", fileName, err)
return *stats, err
}
return *stats, nil
}
<file_sep>/emailer/emailer.go
package emailer
import (
"bytes"
"log"
"math/rand"
"net/smtp"
"os"
"text/template"
"time"
"errors"
"strings"
"github.com/abstractthis/gowedding/models"
"github.com/abstractthis/gowedding/config"
"github.com/abstractthis/gowedding/stats"
"github.com/jordan-wright/email"
)
var Logger = log.New(os.Stdout, " ", log.Ldate|log.Ltime|log.Lshortfile)
var processInterval time.Duration
var delayFloorSec int64
var delayCeilingSec int64
var batchCount int
var fullHostAddr string
var auth smtp.Auth
var ErrUnknownEmailType = errors.New("Unknown Email Type")
type Emailer struct {
shutdown chan bool
send func()
isRunning bool
}
func init() {
// Seed the PRNG
rand.Seed(time.Now().UTC().UnixNano())
// Setup the SMTP auth info
if config.Conf.SMTP.User != "" && config.Conf.SMTP.Pass != "" {
auth = smtp.PlainAuth("", config.Conf.SMTP.User, config.Conf.SMTP.Pass, config.Conf.SMTP.Host)
} else {
auth = nil
}
fullHostAddr = config.Conf.SMTP.Host + ":" + config.Conf.SMTP.Port
if config.Conf.IsDev {
processInterval = 10 * time.Second
delayFloorSec = 0
delayCeilingSec = 5
batchCount = 2
} else {
processInterval = 3 * time.Minute
delayFloorSec = 45
delayCeilingSec = 120
batchCount = 10
}
}
func New() *Emailer {
return &Emailer{
send: discoverEmails,
isRunning: false,
}
}
func (e *Emailer) Start() {
if e.isRunning {
Logger.Println("Emailer is running. Stop Emailer before starting it.")
return
}
Logger.Print("Spinning up Emailer...")
e.shutdown = make(chan bool)
go func() {
e.isRunning = true
for {
select {
case <-time.After(processInterval):
// Drop out of select so emails can be processed
// after each interval amount passes.
case <-e.shutdown:
// stop processing emails and exit gofunction
return
}
e.send()
}
}()
Logger.Printf("Emails processed every %v and will be sent to %s\n", processInterval, fullHostAddr)
}
func (e *Emailer) Stop() {
Logger.Print("Stopping Emailer...")
if e.isRunning {
e.shutdown <- true
e.isRunning = false
Logger.Println("emailer stopped.")
} else {
Logger.Println("emailer wasn't running.")
}
}
func discoverEmails() {
emails, err := models.GetEmailsNotSent(batchCount)
if err != nil {
Logger.Println("Failed to discover emails!")
return
}
sendEmails(emails)
}
func sendEmails(emails []models.Email) {
emailCount := len(emails)
if emailCount > 0 {
var err error
for i, email := range emails {
if email.Type == "confirm" {
err = sendConfirmEmail(&email)
if err == nil {
Logger.Println("Sent confirmation email.")
}
} else if email.Type == "oops" {
err = sendOopsEmail(&email)
if err == nil {
Logger.Println("Sent oops email.")
}
} else if strings.HasPrefix(email.Type, "stats") {
err = sendStatsEmail(&email)
if err == nil {
Logger.Println("Sent stats email.")
}
} else {
err = ErrUnknownEmailType
Logger.Println("Unknown email type found.")
}
if err == nil {
email.Sent = true
models.UpdateEmail(&email)
}
// Don't delay if there's no more emails to send
if i < emailCount - 1 {
// Rest for some random amount between delayFloor and delayCeiling
// so as to not slam the smtp server
delay := time.Duration(delayFloorSec + rand.Int63n(delayCeilingSec - delayFloorSec))
time.Sleep(delay * time.Second)
}
}
} else {
Logger.Println("No pending emails to send.")
}
}
func sendConfirmEmail(em *models.Email) error {
i, err := models.GetInviteByID(em.InviteID)
if err != nil {
return err
}
i.FormatForEmail()
t, err := template.ParseFiles("templates/email/confirmation")
if err != nil {
Logger.Println("Template Parse failure: email/confirmation")
return err
}
var textBuff bytes.Buffer
err = t.Execute(&textBuff, &i)
if err != nil {
Logger.Printf("Failed to execute template: email/confirmation --> %v\n", err)
return err
}
e := email.Email{
Subject: "D&D Wedding RSVP Confirmation",
From: "<EMAIL>",
To: []string{em.Address},
Cc: []string{"<EMAIL>"},
}
e.Text = textBuff.Bytes()
err = e.Send(fullHostAddr, auth)
if err != nil {
Logger.Printf("Failed to send confirm email! --> %v\n", err)
}
return err
}
func sendStatsEmail(em *models.Email) error {
stats, err := stats.EmailContent(em.Type)
if err != nil {
Logger.Printf("Failed to obtain Stats! --> %v\n", err)
return err
}
t, err := template.ParseFiles("templates/email/stats")
if err != nil {
Logger.Println("Template Parse failure: email/stats")
return err
}
var textBuff bytes.Buffer
err = t.Execute(&textBuff, &stats)
if err != nil {
Logger.Printf("Failed to execute template: email/stats --> %v\n", err)
return err
}
e := email.Email{
Subject: "D&D Wedding Statistics",
From: "<EMAIL>",
To: []string{em.Address},
Cc: []string{"<EMAIL>"},
}
e.Text = textBuff.Bytes()
err = e.Send(fullHostAddr, auth)
if err != nil {
Logger.Printf("Failed to send stats email! --> %v\n", err)
}
return err
}
func sendOopsEmail(em *models.Email) error {
t, err := template.ParseFiles("templates/email/oops.html")
if err != nil {
Logger.Printf("Template Parse failure: email/oops.html --> %v\n", err)
return err
}
var textBuff bytes.Buffer
err = t.Execute(&textBuff, nil)
if err != nil {
Logger.Printf("Failed to execute template: email/oops.html --> %v\n", err)
return err
}
e := email.Email{
Subject: "Please RSVP Again for Duong and <NAME>",
From: "<EMAIL>",
To: []string{em.Address},
Cc: []string{"<EMAIL>"},
}
e.HTML = textBuff.Bytes()
err = e.Send(fullHostAddr, auth)
if err != nil {
Logger.Printf("Failed to send oops email! --> %v\n", err)
}
return err
}
<file_sep>/routes/wedding.go
package routes
import (
"log"
"os"
"net/http"
"github.com/gorilla/mux"
"github.com/abstractthis/gowedding/controllers"
//"github.com/justinas/nosurf"
)
var Logger = log.New(os.Stdout, " ", log.Ldate|log.Ltime|log.Lshortfile)
func CreateWeddingRouter(serveStatic bool) http.Handler {
Logger.Println("Creating Wedding Router...")
router := mux.NewRouter()
router.StrictSlash(true)
router.HandleFunc("/rsvp/{id:[0-9]+}/{first:[a-z-]+}/{last:[a-z-]+}/{nonce:[a-z0-9]{40}}/{stamp:[0-9]+}/", controllers.Respondez).Methods("GET")
router.HandleFunc("/rsvp/", controllers.Respondez).Methods("POST")
router.HandleFunc("/rsvp/reply/", controllers.RSVP_Reply).Methods("POST")
// Setup static handlers if need be
if serveStatic {
router.HandleFunc("/wedding", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "static/html/index.html")
})
fs := http.FileServer(http.Dir("./static/"))
router.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))
}
return router
// Setup Cross-site Request Forgery protection
// csrfProtectedHandler := nosurf.New(router)
// csrfProtectedHandler.ExemptRegexp("/rsvp/[a-z]+/[a-z]+/[a-z0-9]{40}")
// return csrfProtectedHandler
}<file_sep>/models/email.go
package models
type Email struct {
ID int
InviteID int
Address string `sql:"type:varchar(100);not null"`
Type string `sql:"type:varchar(16)"`
Sent bool
}
func GetEmailsNotSent(limit int) ([]Email, error) {
var emails []Email
if err := db.Limit(limit).Where("sent=0").Find(&emails).Error; err != nil {
Logger.Printf("Failed to get pending emails! ---> %v\n", err)
}
return emails, err
}
func UpdateEmail(e *Email) error {
err := db.Save(e).Error
if err != nil {
Logger.Printf("Failed to update email! ---> %v\n", err)
}
return err
}
func AddStatEmail(id int32, eType string) error {
e := &Email{
InviteID: int(id),
Address: "<EMAIL>",
Type: eType,
Sent: false,
}
err := db.Create(e).Error
if err != nil {
Logger.Printf("Failed to create %s email! ---> %v\n", eType, err)
}
return err
}<file_sep>/controllers/rsvp.go
package controllers
import (
"net/http"
"strings"
"strconv"
"html/template"
"github.com/abstractthis/gowedding/models"
"github.com/gorilla/mux"
"github.com/gorilla/schema"
)
type RSVP struct {
Invitation models.Invite
HMAC models.Nonce
}
var formDecoder = schema.NewDecoder()
func Respondez(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "GET":
pathVars := mux.Vars(r)
id := pathVars["id"]
firstName := pathVars["first"]
lastName := pathVars["last"]
nonce := pathVars["nonce"]
stamp := pathVars["stamp"]
// Check for a valid nonce
n, err := models.GetNonceByPath(id, firstName, lastName, nonce, stamp)
if err != nil {
ErrorResponseWithPayload(w, http.StatusBadRequest)
return
}
// Get the invite
inviteId, _ := strconv.Atoi(id)
invite, err := models.GetInviteByID(inviteId)
if err != nil {
ErrorResponseWithPayload(w, http.StatusNotFound)
return
}
rsvp := &RSVP{
Invitation: invite,
HMAC: n,
}
t := template.Must(template.New("rsvp.html").Funcs(template.FuncMap{"sum" : Sum, "fullName" : FullName}).ParseFiles("templates/rsvp.html"))
t.Execute(w, rsvp)
case r.Method == "POST":
// Parse the form data
err := r.ParseForm()
if err != nil {
Logger.Println("Failed to parse Respondez POST form!")
ErrorResponseWithPayload(w, http.StatusBadRequest)
return
}
// marshal the form data into the struct
guest := new(models.Guest)
err = formDecoder.Decode(guest, r.PostForm)
if err != nil {
Logger.Println("Failed to marshal Respondez POST form!")
ErrorResponseWithPayload(w, http.StatusBadRequest)
return
}
// Verify that the user exists
err = models.VerifyInviteByGuest(guest)
if err != nil {
ErrorResponseWithPayload(w, http.StatusNotFound)
return
}
// Create HMAC
nonce, err := models.CreateNonce(guest)
if err != nil {
ErrorResponseWithPayload(w, http.StatusBadRequest)
return
}
inviteId := strconv.Itoa(guest.InviteID)
stampStr := strconv.FormatInt(nonce.Stamp, 10)
queryPath := []string{"/rsvp", inviteId, guest.First, guest.Last, nonce.Hash, stampStr}
CreateResponse(w, strings.ToLower(strings.Join(queryPath, "/")))
}
}
func RSVP_Reply(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == "POST":
// Parse the form data
err := r.ParseForm()
if err != nil {
Logger.Printf("Failed to parse RSVP Reply POST form! --> %v\n", err)
ErrorResponseWithPayload(w, http.StatusBadRequest)
return
}
// marshal the form data into the struct
rsvp := new(RSVP)
err = formDecoder.Decode(rsvp, r.PostForm)
if err != nil {
Logger.Printf("Failed to marshal RSVP Reply POST form! --> %v\n", err)
ErrorResponseWithPayload(w, http.StatusBadRequest)
return
}
// Handle the guests
for i, _ := range rsvp.Invitation.Guests {
rsvp.Invitation.Guests[i].NormalizeName()
rsvp.Invitation.Guests[i].InviteID = rsvp.Invitation.ID
}
// Handle the email
rsvp.Invitation.ProcessEmail()
// Verify that the POST is legal
err = models.GetNonce(&rsvp.Invitation, &rsvp.HMAC)
if err != nil {
ErrorResponseWithPayload(w, http.StatusBadRequest)
return
}
// Store the rsvp reply
err = models.UpdateInvite(&rsvp.Invitation, &rsvp.HMAC)
if err != nil {
ErrorResponseWithPayload(w, http.StatusInternalServerError)
return
}
CodeResponse(w, http.StatusOK)
}
}
<file_sep>/models/nonce.go
package models
import (
"time"
"strconv"
"strings"
"crypto/sha1"
"encoding/hex"
"errors"
)
const (
Expiration = 60 * 10 // 10 minutes
)
type Nonce struct {
ID int
Hash string `sql:"type:varchar(64);not null;index:idx_nonce"`
Stamp int64 `sql:"not null;index:idx_nonce"`
}
var action = "RSVP to duong and dave wedding"
var ErrNonceExpired = errors.New("Expired Nonce")
var ErrNonceMismatch = errors.New("Nonce Mismatch")
func GetNonce(i *Invite, hmac *Nonce) error {
err := db.Where("hash=? and stamp=?", hmac.Hash, hmac.Stamp).Find(hmac).Error
if err != nil {
Logger.Printf("404 HMAC --> %v\n", err)
return err
}
// Check that the nonce hasn't expired
ts := time.Now().Unix()
if ts - hmac.Stamp > Expiration {
Logger.Println("HMAC has expired!")
return ErrNonceExpired
}
// Build out hash with information and verify they're the same
for _, g := range i.Guests {
hash := calcNonceHash(i.ID, g.First, g.Last, hmac.Stamp)
if hash == hmac.Hash {
return nil
}
}
Logger.Println("HMAC != HMAC!")
return ErrNonceMismatch
}
func GetNonceByPath(idStr string, first string, last string, hash string, stamp string) (Nonce, error) {
n := Nonce{}
id, err := strconv.Atoi(idStr)
if err != nil {
Logger.Println("Failed to convert invite id!")
return n, err
}
i := Invite{
ID: id,
Guests: []Guest{{InviteID: id, First: first, Last: last},},
}
ts, err := strconv.ParseInt(stamp, 10, 64)
if err != nil {
Logger.Println("Failed to parse nonce timestamp!")
return n, err
}
n.Hash = hash
n.Stamp = ts
err = GetNonce(&i, &n)
if err != nil {
Logger.Printf("HMAC 404 for [%s,%s,%s,%s,%s]\n", idStr, first, last, hash, stamp)
return n, err
}
return n, nil
}
func CreateNonce(g *Guest) (Nonce, error) {
// Get the timestamp (only sec resolution)
ts := time.Now().Unix()
hash := calcNonceHash(g.InviteID, g.First, g.Last, ts)
n := Nonce{
Hash: hash,
Stamp: ts,
}
err := db.Create(&n).Error
if err != nil {
Logger.Printf("Failed to create HMAC for Guest! %v\n", err)
}
return n, err
}
func DeleteNonce(n *Nonce) error {
err := db.Delete(n).Error
if err != nil {
Logger.Println(err)
return err
}
return nil
}
func calcNonceHash(id int, first string, last string, stamp int64) string {
idStr := strconv.Itoa(id)
stampStr := strconv.FormatInt(stamp, 10)
return genNonceHash(idStr, first, last, stampStr)
}
func genNonceHash(id string, first string, last string, stamp string) string {
values := []string{id, first, last, stamp, action}
target := strings.Join(values, "")
hash := sha1.New()
hash.Write([]byte(target))
hashStr := hex.EncodeToString(hash.Sum(nil))
return hashStr
}<file_sep>/models/guest.go
package models
import "strings"
type Guest struct {
ID int
InviteID int `sql:"index"`
First string `sql:"type:varchar(64)"`
Last string `sql:"type:varchar(64)"`
Food string `sql:"type:varchar(8)"`
IsAttending bool
}
func (g *Guest) NormalizeName() {
split := strings.Fields(g.First)
g.First = strings.ToLower(split[0])
g.Last = strings.ToLower(split[1])
}
func VerifyInviteByGuest(g *Guest) error {
err := db.Where("invite_id=? and first=? and last=?", g.InviteID, g.First, g.Last).Find(g).Error
if err != nil {
Logger.Printf("Failed to verify Guest{InviteID: %d, First: %s, Last: %s}\n", g.InviteID, g.First, g.Last)
}
return err
}
func SetGuestIDs(invite *Invite) error {
var dbGuests []Guest
err := db.Where("invite_id=?", invite.ID).Select("id", "first").Find(&dbGuests).Error
if err != nil {
Logger.Printf("Failed to set guests IDs for invite #%d!\n", invite.ID)
return err
}
for i, _ := range invite.Guests {
// Go through looking for matching first name
for _, dbGuest := range dbGuests {
if invite.Guests[i].First == dbGuest.First {
invite.Guests[i].ID = dbGuest.ID
break
}
}
// Cycle again if ID is 0 for an empty db guest (anonymous guest)
if invite.Guests[i].ID == 0 {
for j, dbGuest := range dbGuests {
if dbGuest.First == "" {
// Use the ID for this anonymous guest
invite.Guests[j].ID = dbGuest.ID
// Set the first name of the db guest so its ID isn't used again.
dbGuests[j].First = invite.Guests[j].First
break
}
}
}
}
return nil
}
func TotalGuests() int32 {
var totalGuests int64
err := db.Model(&Guest{}).Where("invite_id<>?", 2323).Count(&totalGuests).Error
if err != nil {
totalGuests = -1
}
return int32(totalGuests)
}
func MIAGuests() []Guest {
var mias []Guest
err := db.Where("invite_id<>? and food='' and first<>''", 2323).Find(&mias).Error
if err != nil {
return make([]Guest, 0)
}
return mias
}
func AttendingGuests() int32 {
var guestsAttending int64
err := db.Model(&Guest{}).Where("invite_id<>? and is_attending=1", 2323).Count(&guestsAttending).Error
if err != nil {
guestsAttending = -1
}
return int32(guestsAttending)
}
func BeefDinners() int32 {
var beef int64
err := db.Model(&Guest{}).Where("invite_id<>? and food='beef'", 2323).Count(&beef).Error
if err != nil {
beef = -1
}
return int32(beef)
}
func FishDinners() int32 {
var fish int64
err := db.Model(&Guest{}).Where("invite_id<>? and food='fish'", 2323).Count(&fish).Error
if err != nil {
fish = -1
}
return int32(fish)
}
func VeggieDinners() int32 {
var veggie int64
err := db.Model(&Guest{}).Where("invite_id<>? and food='veggie'", 2323).Count(&veggie).Error
if err != nil {
veggie = -1
}
return int32(veggie)
}
func KidDinners() int32 {
var kids int64
err := db.Model(&Guest{}).Where("invite_id<>? and food='kid'", 2323).Count(&kids).Error
if err != nil {
kids = -1
}
return int32(kids)
}
<file_sep>/models/invite.go
package models
import (
"time"
"unicode"
"strings"
)
type Invite struct {
ID int `gorm:"primary_key" sql:"index"`
ConfirmAddr Email
Guests []Guest
UpdatedAt time.Time
}
func (i *Invite) ProcessEmail() {
if i.ConfirmAddr.Address == "" {
i.ConfirmAddr = Email{}
} else {
i.ConfirmAddr.Type = "confirm"
}
}
func (i *Invite) FormatForEmail() {
for j, g := range i.Guests {
i.Guests[j].First = capIt(g.First)
i.Guests[j].Last = capIt(g.Last)
if g.IsAttending {
i.Guests[j].Food = firstLetterUpper(g.Food)
}
}
}
func firstLetterUpper(str string) string {
for i, v := range str {
return string(unicode.ToUpper(v)) + str[i+1:]
}
return ""
}
func capIt(s string) string {
// Deal with hyphenated names first
hyphenChop := strings.Split(s, "-")
if len(hyphenChop) > 1 {
name := make([]string, len(hyphenChop))
for i, partial := range hyphenChop {
name[i] = firstLetterUpper(partial)
}
return strings.Join(name, "-")
} else {
return firstLetterUpper(s)
}
}
func GetInviteByID(id int) (Invite, error) {
i := Invite{}
err := db.Where("id=?",id).Find(&i).Error
if err == nil {
err = db.Where("invite_id=?", id).Find(&i.Guests).Error
if err == nil && len(i.Guests) == 0 {
i.Guests = make([]Guest, 0)
} else if err != nil {
Logger.Printf("Failed to get guests for invite %d : %v\n", id, err)
}
} else {
Logger.Printf("Failed to get invite %d!", err)
}
return i, err
}
func UpdateInvite(i *Invite, n *Nonce) error {
err := DeleteNonce(n)
if err != nil {
Logger.Printf("Failed to delete invite hmac! --> %v\n", err)
return err
}
err = SetGuestIDs(i)
if err != nil {
return err
}
i.UpdatedAt = time.Now()
err = db.Debug().Save(i).Error
if err != nil {
Logger.Printf("Failed to update invite! --> %v\n", err)
}
return err
}<file_sep>/config/config.go
package config
import (
"log"
"os"
"encoding/json"
"io/ioutil"
)
// SMTPServer represents the SMTP configuration details
type SMTPServer struct {
Host string `json:"host"`
Port string `json:"port"`
User string `json:"user"`
Pass string `json:"pass"`
}
// Config represents the configuration information.
type Config struct {
ApiURL string `json:"api_url"`
SMTP SMTPServer `json:"smtp"`
DBPath string `json:"dbpath"`
IsDev bool `json:"is_dev"`
SendOops bool `json:"send_oops"`
}
var Conf Config
var Logger = log.New(os.Stdout, " ", log.Ldate|log.Ltime|log.Lshortfile)
func init() {
// Get the config file
config_file, err := ioutil.ReadFile("./config.json")
if err != nil {
Logger.Printf("Config file 404: %v\n", err)
}
json.Unmarshal(config_file, &Conf)
// Change email configuration if in dev
if Conf.IsDev {
Conf.SMTP.Host = "localhost"
Conf.SMTP.Port = "1025"
Conf.SMTP.User = ""
Conf.SMTP.Pass = ""
}
}<file_sep>/gowedding.go
package main
import (
"log"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/gorilla/handlers"
"github.com/abstractthis/gowedding/config"
"github.com/abstractthis/gowedding/routes"
"github.com/abstractthis/gowedding/models"
"github.com/abstractthis/gowedding/emailer"
"github.com/abstractthis/gowedding/stats"
)
var Logger = log.New(os.Stdout, " ", log.Ldate|log.Ltime|log.Lshortfile)
var emailSender *emailer.Emailer
var statsCruncher *stats.Cruncher
func main() {
// Launch the emailer
emailSender = emailer.New()
emailSender.Start()
// Launch stats cruncher
statsCruncher = stats.New()
statsCruncher.Start()
// Spin up goroutine to listen and deal with Ctrl-C
// Actually listens for SIGINT, SIGKILL and SIGTERM
sigChan := make(chan os.Signal, 2)
stopSig := make(chan bool)
go func() {
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
select {
case <-sigChan:
Logger.Printf("Program interrupt received! Cleanup...")
statsCruncher.Stop()
emailSender.Stop()
Logger.Println("cleanup complete.")
os.Exit(1)
case <-stopSig:
return
}
}()
// Initialize the database and its globals
err := models.Initialize()
if err != nil {
Logger.Printf("Model Initialization failed: %v\n", err)
os.Exit(1)
}
// Fire up the api server
Logger.Printf("Launching gowedding api server at http://%s\n", config.Conf.ApiURL)
http.ListenAndServe(config.Conf.ApiURL,
handlers.CombinedLoggingHandler(os.Stdout, routes.CreateWeddingRouter(config.Conf.IsDev)))
// Cleanup on normal exit
statsCruncher.Stop()
emailSender.Stop()
// Stop the goroutine listening for interrupt signals
stopSig <- true
}<file_sep>/static/javascripts/main.js
(function($){
"use strict";
$(document).ready(function(){
if (!String.prototype.startsWith) {
Object.defineProperty(String.prototype, 'startsWith', {
enumerable: false,
configurable: false,
writable: false,
value: function(searchString, position) {
position = position || 0;
return this.lastIndexOf(searchString, position) === position;
}
});
}
$(".error").hide();
jQuery('#countdown_dashboard').countDown({
targetDate: {
'day': 23, // Put the date here
'month': 5, // Month
'year': 2015, // Year
'hour': 0,
'min': 0,
'sec': 0
} //,omitWeeks: true
});
$(".party-container").on("click", "a", function(e) {
$("#party-popup").modal();
var modalHeight = $(window).height() * .6; // Set the height to 60% of the screen size
$(".modal-body").css("height", modalHeight);
e.preventDefault();
e.stopPropagation();
});
var validate = false;
var intRegex = /^\d+$/;
var validateRSVPLookup = function() {
var valid = true;
// Make sure that RSVP ID provided and a number
var id = $.trim($("#rsvpId").val());
if (!!id && intRegex.test(id)) {
$("#rsvpId-error").hide();
$("#rsvpId").val(id);
}
else {
$("#rsvpId-error").show();
valid = false;
}
// Make sure first name provided
var firstName = $.trim($("#first1").val());
if (!!firstName) {
$("#first1-error").hide();
$("#first1").val(firstName);
}
else {
$("#first1-error").show();
valid = false;
}
// Make sure last name provided
var lastName = $.trim($("#last1").val());
if (!!lastName) {
$("#last1-error").hide();
$("#last1").val(lastName);
}
else {
$("#last1-error").show();
valid = false;
}
return valid;
};
var validateGuest = function(guestIndex) {
var valid = true;
var firstName = $.trim($("#gFirst" + guestIndex).val());
var attending = $("#gAttending" + guestIndex).val();
// If no name and the default 'In Spirit' attendence is selected
// assume that there isn't a guest provided for the allotted slot.
if (firstName === "" && attending === "-1") return valid;
// Make sure first name provided
if (!!firstName) {
$("#error-gFirst" + guestIndex).hide();
$("#gFirst" + guestIndex).val(firstName);
}
else {
$("#error-gFirst" + guestIndex).show();
valid = false;
}
// Make sure attendence has been specified
if (attending !== "-1") {
$("#error-attending" + guestIndex).hide();
}
else {
$("#error-attending" + guestIndex).show();
valid = false;
}
if (attending == "1") {
// Check that dinner selection has been made for the guest
if ($("#gFood" + guestIndex).val() !== "-1") {
$("#error-food" + guestIndex).hide();
}
else {
$("#error-food" + guestIndex).show();
valid = false;
}
}
return valid;
};
var validateRSVPReply = function() {
var valid = true;
$("#rsvpwrap li").each(function(i, elem) {
var jElem = $(elem);
var anchor = jElem.children("a");
var guestBoxId = anchor.attr("href");
var guestIndex = guestBoxId.charAt(guestBoxId.length - 1);
valid = validateGuest(guestIndex);
if (valid) {
anchor.removeClass("guestError");
}
else {
anchor.addClass("guestError");
}
});
return valid;
};
var getRSVPForm = function(rsvpURL) {
$.ajax({
url: rsvpURL,
type: "GET",
cache: false,
timeout: 5000
}).done(function(data, textStatus, jqXHR) {
var errHeader = $("#rsvpwrap h3");
if (errHeader.length) {
errHeader.remove();
}
if (!!jqXHR.responseText) {
$("#rsvp-reply-form").replaceWith(data);
$(".error").hide();
}
else {
$("#rsvp-reply-form").replaceWith("<h3>Doh! It seems the gremlins have done something. The server has vanished. Please come back later and try again. Worst-case snail mail wins.</h3>");
}
}).fail(function(jqXHR, textStatus, errorThrown) {
var errHeader = $("#rsvpwrap h3");
if (errHeader.length) {
errHeader.remove();
}
if (!!jqXHR.responseText) {
$("#rsvp-reply-form").replaceWith(jqXHR.responseText);
$(".error").hide();
}
else {
$("#rsvp-reply-form").replaceWith("<h3>Doh! It seems the gremlins have done something. The server has vanished. Please come back later and try again. Worst-case snail mail wins.</h3>");
}
});
};
$("#rsvpwrap").on("change", "select", function(e) {
var selectBox = $(e.target);
var selectWidget = selectBox.attr("id");
var selectValue = selectBox.val();
var selectIndex = selectWidget.charAt(selectWidget.length - 1);
if (selectWidget.startsWith("gAttending")) {
if (selectValue === "1") {
$("#foodBox" + selectIndex).slideDown();
$("#error-attending" + selectIndex).hide();
}
else if (selectValue === "0") {
$("#foodBox" + selectIndex).slideUp();
$("#gFood" + selectIndex).val("-1");
$("#error-attending" + selectIndex).hide();
}
}
else if (selectWidget.startsWith("gFood")) {
if (selectValue !== "-1") {
$("#error-food" + selectIndex).hide();
}
}
if (validate) validateRSVPReply();
});
$("#rsvpwrap").on("focus", ".text-input, select", function () {
$(this).css({border:"2px solid #de675f"});
$(this).css({background:"#fff"});
});
$("#rsvpwrap").on("blur", ".text-input, select", function () {
$(this).css({border:"2px solid #fff"});
$(this).css({background:"transparent"});
});
// Pagination controls
$("#rsvpwrap").on("click", "a", function(e) {
e.preventDefault();
var newActive = $(e.target);
var newGuest = $("#" + newActive.attr("href"));
var oldActive = $("#rsvpwrap li.active");
var oldGuest = $("#" + oldActive.children("a").attr("href"));
oldActive.removeClass("active");
newActive.parent().addClass("active");
oldGuest.slideUp().fadeOut();
newGuest.slideDown().fadeIn();
});
/* Form submission capture */
$("#rsvpwrap").on("submit", "#start-rsvp", function(e) {
e.preventDefault();
var validForm = validateRSVPLookup();
if (!validForm) return;
$("#start-rsvp-btn").prop("disabled", true);
// Submit the form and process response
var form = $(this);
var postData = form.serialize().toLowerCase();
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
cache: false,
data: postData,
timeout: 5000
}).done(function(data, textStatus, jqXHR) {
var rsvpFormURL = jqXHR.getResponseHeader("Location");
if (!!rsvpFormURL) {
getRSVPForm(rsvpFormURL);
}
else {
$("#rsvp-reply-form").replaceWith("<h3>Doh! It seems the gremlins have done something. The server has vanished. Please come back later and try again. Worst-case snail mail wins.</h3>");
}
}).fail(function(jqXHR, textStatus, errorThrown) {
var errHeader = $("#rsvpwrap h3");
if (errHeader.length) {
errHeader.remove();
}
if (!!jqXHR.responseText) {
$("#rsvp-reply-form").replaceWith(jqXHR.responseText);
$(".error").hide();
}
else {
$("#rsvp-reply-form").replaceWith("<h3>Doh! It seems the gremlins have done something. The server has vanished. Please come back later and try again. Worst-case snail mail wins.</h3>");
}
});
});
var getRSVPPostData = function(form) {
var allData = form.serializeArray();
var completedData = [];
// Need to keep the hidden values and the email so grab them first
for (var i = 0; i < allData.length; i++) {
var lowerName = (allData[i].name).toLowerCase();
if (lowerName === "invitation.id" || lowerName === "hmac.hash" ||
lowerName === "hmac.stamp" || lowerName === "invitation.confirmaddr.address") {
completedData.push(allData[i]);
}
}
// Grab guest values for those guest that info was provided
$(".guestInfo").each(function(i) {
var guestName = $.trim($("#gFirst" + i).val());
if (guestName !== "") {
var guestValues = allData.filter(function(elem) {
var lowerName = (elem.name).toLowerCase();
return lowerName.startsWith("invitation.guests." + i);
});
Array.prototype.push.apply(completedData, guestValues);
}
});
return ($.param(completedData)).toLowerCase();
};
$("#rsvpwrap").on("submit", "#rsvp-reply", function(e) {
e.preventDefault();
var validForm = validateRSVPReply();
validate = !validForm;
if (!validForm) return;
$("#reply-submit-btn").prop("disabled", true);
var form = $(this);
var postData = getRSVPPostData(form);
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
cache: false,
data: postData,
timeout: 5000
}).done(function(data, textStatus, jqXHR) {
var errHeader = $("#rsvpwrap h3");
if (errHeader.length) {
errHeader.remove();
}
if (jqXHR.status === 200) {
$("#rsvp-reply-form").replaceWith("<h1>Thank you for taking the time to RSVP!</h1>");
$("a[href='#rsvp']").trigger("click");
}
else {
$("#rsvp-reply-form").replaceWith("<h3>Doh! It seems the gremlins have done something. Please come back later and try again. Worst-case snail mail wins.</h3>");
}
}).fail(function(jqXHR, textStatus, errorThrown) {
var errHeader = $("#rsvpwrap h3");
if (errHeader.length) {
errHeader.remove();
}
if (!!jqXHR.responseText) {
$("#rsvp-reply-form").replaceWith(jqXHR.responseText);
$(".error").hide();
}
else {
$("#rsvp-reply-form").replaceWith("<h3>Doh! It seems the gremlins have done something. The server has vanished. Please come back later and try again. Worst-case snail mail wins.</h3>");
}
});
});
/* Hero height
================================================== */
var windowHeight = $(window).height();
$('.hero').height( windowHeight );
$(window).resize(function() {
var windowHeight = $(window).height();
$('.hero').height( windowHeight );
});
// Menu settings
$('#menuToggle, .menu-close').on('click', function(){
$('#menuToggle').toggleClass('active');
$('body').toggleClass('body-push-toleft');
$('#theMenu').toggleClass('menu-open');
});
/* Gallery
================================================== */
new Photostack( document.getElementById( 'photostack' ), {
callback : function( item ) {
//console.log(item)
}
} );
/* Gallery popup
=================================================== */
var photos = [
"after-the-proposal",
"anna-jason-wedding",
"apple-picking-us",
"audreys-party",
"billies-wedding",
"brewery",
"charger-game-nj",
"chophouse",
"coti-1",
"cp-1",
"cp-2",
"cp-3",
"cp-4",
"cp-5",
"cp-6",
"cruise-dinner",
"dinner1",
"du-27th-1",
"du-27th-2",
"du-grad",
"engage-1",
"engage-2",
"engage-3",
"engage-4",
"engage-5",
"engage-6",
"erica-eli-wedding",
"first-date-kinda-2",
"first-date-kinda",
"flat-iron",
"hall-of-fame",
"magic-mountain",
"maine-1",
"maine-2",
"mi-tailgate",
"navy-pier",
"new-years-2008",
"no-clue-1",
"nyc-skating",
"paris-1",
"paris-2",
"proposal",
"rushmore",
"sd-1",
"seattle",
"shake-shack",
"sig-kappa-us",
"snowboarding",
"the-beginning",
"tx-fishing",
"vegas1",
"vegas2",
"yankee-game",
"du-30th",
"magic-mountain-2"
];
// Select the images to show in this gallery
var selectedPhotos = []
while(selectedPhotos.length != 12) {
var random = Math.floor(Math.random() * photos.length);
// Only use the photo once
if(selectedPhotos.indexOf(photos[random]) === -1) {
selectedPhotos.push(photos[random]);
}
}
// Grab all of the anchors in the gallery and set their href attribute
$('#photostack a').each(function(index) {
$(this).attr('href', '/static/images/placeholders/600x500/' + selectedPhotos[index] + '.jpg');
});
// Grab all of the img tags and set their source and alt attributes
$('#photostack img').each(function(index) {
$(this).attr('src', '/static/images/placeholders/240x240/' + selectedPhotos[index] + '.jpg');
$(this).attr('alt', selectedPhotos[index]);
});
$('.photostack').magnificPopup({
delegate: 'a',
type: 'image',
tLoading: 'Loading image #%curr%...',
mainClass: 'mfp-img-mobile',
gallery: {
enabled: true,
navigateByImgClick: true,
preload: [0,1] // Will preload 0 - before current, and 1 after the current image
},
image: {
tError: '<a href="%url%">The image #%curr%</a> could not be loaded.',
titleSrc: function(item) {
return item.el.attr('title');
}
}
/* zoom: {
enabled: true,
duration: 300 // don't foget to change the duration also in CSS
} */
});
//Home Background slider
jQuery.supersized({
slide_interval : 3000, // Length between transitions
transition : 1, // 0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
transition_speed : 700, // Speed of transition
slide_links : 'blank', // Individual links for each slide (Options: false, 'num', 'name', 'blank')
slides : [ // Slideshow Images
{image : '/static/images/placeholders/slider-0.jpg'},
{image : '/static/images/placeholders/slider-1.jpg'},
{image : '/static/images/placeholders/slider-2.jpg'},
{image : '/static/images/placeholders/slider-3.jpg'},
{image : '/static/images/placeholders/slider-4.jpg'},
{image : '/static/images/placeholders/slider-5.jpg'}
]
});
});
})(jQuery); | 467bd7ba45956371aa54ecff9cf5ec1596a6e550 | [
"JavaScript",
"Go"
] | 13 | Go | abstractthis/gowedding | 564ac152b9e20a0ed5d20cdba37dbb1ab4686fb6 | b2d2753e3a39cbf84ea28a23c062ec4fa3abb98d |
refs/heads/master | <repo_name>alejandroave/metodos<file_sep>/bass.sh
REPE=10 ##maximo de repeticiones
cosa=canal.dat
tiocosa=mugre.dat
tiolucas=desviacion.dat
##para ver si existen los archivos
##si es asi los borra
##agradecimiento a pedrito por
##esta parte
if [ -e $cosa ]; then
rm canal.dat
fi
if [ -e $tiocosa ]; then
rm mugre.dat
fi
if [ -e $tiolucas ]; then
rm desviacion.dat
fi
touch canal.dat
touch desviacion.dat
for POTENCIA in 0 1 2 3 4 5 6 7 8
do
for PCERO in 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 ##porcentajes de aparicion
do
for PECERO in 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 ##posibilidades de exito cero y uno
do
for CONTADOR in 1 2 3 4 5 ##cuantas palabras de un mismo tamaño se aran para sacar el promedio luego
do
touch mugre.dat
res=`python canal.py $PCERO $POTENCIA $PECERO $PECERO $REPE`
echo $res >> mugre.dat
done
res=`awk -f cosa.awk mugre.dat`
echo valor de res $res
rm mugre.dat
echo $POTENCIA $PCERO $PECERO $res >> canal.dat
echo $res >> desviacion.dat
done
done
echo '' >> canal.dat
echo $POTENCIA
done
python desviacion.py
gnuplot grafica.plot
<file_sep>/README.md
metodos
=======
metodos y mas<file_sep>/canal.py
import random
import sys
import numpy
from numpy import*
def palabra(frecuencia,tama):
tamano = int(tama)
vec = zeros(tamano)
for i in range(tama):
proba = random.random()
if proba <= frecuencia:
vec[i] = 0
else:
vec[i] = 1
return vec
def transmisor(cpalabra,probc,probou):
tamp = len(cpalabra)
vec = zeros(tamp)
for i in range(tamp):
pre = random.random()
if cpalabra[i] == 0:
if pre <= probc:
vec[i] = 0
else:
vec[i] = 1
else:
if pre <= probou:
vec[i] = 1
else:
vec[i] = 0
if list(cpalabra) == list(vec):
return 1
else:
return 0
def simulacion(cpalabra,probc,probou,repeticion):
cont = 0
for i in range(repeticion):
corrc = transmisor(cpalabra,probc,probou)
if corrc == 1:
cont = cont + 1
probabilidad = float(cont)/float(repeticion)
return probabilidad
#def main():
frec = float(sys.argv[1]) ##frecuencia que aparesca cero
tama = 2**int(sys.argv[2]) ##tamao de la letra
probc = float(sys.argv[3]) ##probabilidad de que pase cero
probou = float(sys.argv[4]) ##probabilidad de que pase uno
repe = int(sys.argv[5]) ##repeticiones
word = palabra(frec,tama) ##para obtener la palabra
prob = simulacion(word,probc,probou,repe) ##optener la probabilidad
print prob ##imprimir la respuestao
#main()
<file_sep>/desviacion.py
import math ##para la raiz
archivo=open("desviacion.dat","r") ##abrimos archivo
res = [] ##una lista para valores mas adelante
lineas=archivo.readlines() ##cuantas lineas tiene
suma = 0 ##para promedios
contador = 0 ##para promedios
for x in lineas:
suma = suma + float(x) ##sumamos todos los valores
contador = contador + 1
promedio = suma/contador ##sacamos el promedio de los valores
print "Media aritmetica: ",promedio
res = 0
sumad = 0
for x in lineas:
#res.append(float(x) - promedio)
cuadrado = (float(x) - promedio)**2 ##para la desviacion es
##la diferencia de todos los numeros con el
##promedio al cuadrado mas sus sumas nos da
##la varianza
## y la raiz de esta es el desviacion
sumad = sumad + cuadrado
promediod = sumad/contador
print "Varianza: ",promediod
raiz = math.sqrt(promediod)
print "Desviacion estandar: ",raiz
archivo.close
| ead24e9d7072ba113f7da2760bdcdc8a1a4a6f03 | [
"Markdown",
"Python",
"Shell"
] | 4 | Shell | alejandroave/metodos | 7bab82945dc2efb514d0eb01a9f41e923679acf5 | fa5d7c6cfe4807b16341c5fc83b1981237ca4f6d |
refs/heads/master | <repo_name>rashishpaul/sidekiq<file_sep>/Words_of_Wisdom/app/mailers/cat_facts_mailer.rb
class CatfactsMailer < ApplicationMailer
default from: '<EMAIL>'
def catfacts_welcome(user)
@user = user
mail(to: @user, subject:"Welcome to Catfacts!")
end
end
<file_sep>/Words_of_Wisdom/app/controllers/users_controller.rb
class UsersController < ApplicationController
def index
@users = User.all
end
def destroy
User.destroy(params['id'])
redirect_to(:back)
end
def create
user = params['user']
User.create(name: user['name'], email: user['email'])
CatfactsMailer.catfacts_welcome(user['email']).deliver
redirect_to(:back)
end
end
<file_sep>/Words_of_Wisdom/README.rdoc
# Sidekiq
### What is Sidekiq?
Sidekiq is a framework that may be installed with a a simple addition to your Rails Gemfile:
```
gem 'sidekiq'
```
It allows you to perform jobs asynchronously. In summary it performs jobs in the background of an app without interrupting the flow of the app. It is possible to coordinate an automated task at a specific time. Include the following:
```
class NecessaryTask
include Sidekiq::Worker
def perform(name, count)
# action
end
end
```
From the above method you can see that the method takes two arguements. With the following line of code you can postpone a a job execution:
```
NecessaryTask.perform_in(5.minutes, 'text', 3)
```
It is expected that 'text' will display 3x five minutes from the current time.
### Requirements
Sidekiq requires Redis, a Client, and a Server
### References
> https://github.com/mperham/sidekiq/wiki/Getting-Started
> https://www.youtube.com/watch?v=VS9g4wB6wZk
> https://www.codefellows.org/blog/how-to-set-up-a-rails-4-2-mailer-with-sidekiq
| fc340fadb38544c9bd0a9433b9496582252fb0a6 | [
"RDoc",
"Ruby"
] | 3 | Ruby | rashishpaul/sidekiq | fe7259f24e85c35b2f6e01523425a7729228ddcd | df81760d8ec17e437d6552cd4b397a687ac7adc5 |
refs/heads/master | <file_sep>InfoBat
=======
InfoBat es un monitor de información sobre el estado de la batería de dispositivos Android. Además dispone de un widget que muestra el nivel de batería.
## Versiones ##
### Versión 1.1.1 - 12/08/2013 ###
* Supresión de la ventana de información.
* Optimización del código del widget.
* Corregido problema de dimensiones de widget en Android 4.x.
* Reducción de tamaño del ejecutable de un 31%.
* Reducción de uso de memoria en un 29%.
### Versión 1.1 – 08/05/2013 ###
* Ajustes en valores límite de nivel de batería.
* Se ha mejorado el aspecto del widget.
* Se ha optimizado el código del widget y de la actividad.
* Inclusión de pequeñas mejoras.
### Versión 1.0 – 19/04/2013 ###
* Rediseño de la actividad principal.
* Se ha optimizado el refresco de la actividad principal consumiendo menos recursos.
* Inclusión de un widget para visualizar el porcentaje de batería.
### Versión 0.2 – 03/01/2012 ###
* Cambio de AsyncTask de verificación de estado de batería por BroadcastReceiver, lo que mejora el rendimiento de la aplicación.
* Inclusión de un menú principal.
* Actualización de las vistas con información sólo cuando hay cambios en el estado de la batería.
* Mejoras de código y rendimiento.
### Versión 0.1 – 27/12/2011 ###
* Versión inicial que muestra información del estado de la batería del dispositivo en tiempo real.<file_sep>package es.jafs.infobat.widget;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
/**
* Controlador de widget de batería.
* @author <NAME>
* @version 1.0
* @date 2013
*/
public class WidgetBateria extends AppWidgetProvider {
/**
* Desactiva el servicio de actualización del widget.
* @param objContexto Contexto de la aplicación.
*/
@Override
public void onDisabled(final Context objContexto) {
objContexto.stopService(new Intent(objContexto, ServicioBateria.class));
}
/**
* Activa el servicio de actualización del widget.
* @param objContexto Contexto de la aplicación.
* @param objWidgetManager Administrador de widgets.
* @param ariWidgetIds Identificadores de widgets activos.
*/
@Override
public void onUpdate(final Context objContexto, final AppWidgetManager objWidgetManager,
final int[] ariWidgetIds) {
objContexto.startService(new Intent(objContexto, ServicioBateria.class));
}
}
| a178c7ca1eabf807b3507f1bc761437ff4f98072 | [
"Markdown",
"Java"
] | 2 | Markdown | jafs/infobat | 81dbcc52551bc7681a2ae07aff7b24d854aed1b5 | 23f58b1c2d5c3b19624424acde946852350f2489 |
refs/heads/master | <file_sep>package com.android.zoom.Movie;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.android.zoom.Movie.DTO.DailyBoxOfficeList;
import com.android.zoom.R;
import java.util.List;
/**
* 리사이릌 뷰 어댑터 기본 구조
* */
public class MovieAdapter extends RecyclerView.Adapter<MovieAdapter.ViewHolder>{
/**
기본 형태
1. onCreateViewHolder : 뷰홀더를 생성(레이아웃 생성)
2. onBindViewHolder : 뷰홀더가 재활용될 때 실행되는 메서드
3. getItemCount : 아이템 개수를 조회
* */
private List<DailyBoxOfficeList> items;
// this -> 멤버변수 = 인수 변수
public MovieAdapter(List<DailyBoxOfficeList> items){
this.items = items;
}
@NonNull
@Override
public MovieAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(
parent.getContext()).inflate(R.layout.movie_item_list , parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
DailyBoxOfficeList item = items.get(position);
holder.setItem(item);
}
@Override
public int getItemCount() {
return items.size();
}
/**
* 리사이클러뷰 어댑터는 개별 데이터에 대응하는 뷰홀더 클래스를 사용
* 뷰홀더도 기본 기능이 이미 만들어져 있는 ViewHolder 클래스를 상속받아서 만듬
* ViewHolder 는 현재 화면에 보이는 아이템 레이아웃 개수만큼 생성되고
* 새롭게 그려 저야 할 아이템 레이아웃이 있다면(스크롤 동작) 가장 위의 ViewHolder를 재사용해서 데이터만 바꾼다.
* 즉, 몇 천 개의 데이터가 있다고 했을 때 몇 천 개의 아이템 레이아웃을 생성하면 자원 낭비가 있으므로 ViewHolder 재사용성은 이를 방지하여 앱의 효율을 향상시킴
* */
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView rank, movieNm, openDt;
public ViewHolder(View itemView) {
super(itemView);
rank = itemView.findViewById(R.id.rank);
movieNm = itemView.findViewById(R.id.movieNM);
openDt = itemView.findViewById(R.id.openDt);
}
public void setItem(DailyBoxOfficeList item){
rank.setText(item.getRank());
movieNm.setText(item.getMovieNm());
openDt.setText(item.getOpenDt());
}
}
}
<file_sep>package com.android.zoom;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.zoom.Common.Manager.PreferenceManager;
import com.android.zoom.Common.Manager.ToastManager;
import com.android.zoom.Common.Retrofit.RetrofitBuilder;
import com.android.zoom.Common.Retrofit.RetrofitService;
import com.android.zoom.Movie.DTO.BoxOfficeResult;
import com.android.zoom.Movie.DTO.MovieResult;
import com.android.zoom.Movie.MovieAdapter;
import com.android.zoom.User.LoginActivity;
import org.w3c.dom.Text;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
View drawerView;
private RecyclerView recyclerView;
private RecyclerView.Adapter mAdapter;
private RetrofitService retrofitInterface;
public Context mCon;
ProgressDialog progressDialog;
TextView login_user;
TextView log_date;
TextView btn_logout;
Button getMovieData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String msg_login_user = getString(R.string.hello_msg_name);
String msg_log_date = getString(R.string.login_date);
mCon = this;
login_user = findViewById(R.id.login_user);
log_date = findViewById(R.id.log_date);
getMovieData = findViewById(R.id.getMovieData);
btn_logout = findViewById(R.id.btn_logout);
if(PreferenceManager.getString(mCon,"user_name").equals("")) {
ToastManager.showToastMsg(mCon,"로그인이 되어있지않음!!");
Intent intent = new Intent(mCon,LoginActivity.class);
startActivity(intent);
} else {
login_user.setText(String.format(msg_login_user, PreferenceManager.getString(mCon, "user_name")));
log_date.setText(String.format(msg_log_date, PreferenceManager.getString(mCon, "log_date")));
}
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerView = (View) findViewById(R.id.drawerView);
drawerLayout.setDrawerListener(listener);
getMovieData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
progressDialog = new ProgressDialog(mCon);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setTitle("알림");
progressDialog.setMessage("데이터를 불러오는 중...");
progressDialog.show();
recyclerView = findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(mCon, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
// 인스턴스 생성
RetrofitBuilder retrofitClient = RetrofitBuilder.getInstance("http://kobis.or.kr/kobisopenapi/webservice/rest/boxoffice/");
retrofitInterface = retrofitClient.getRetrofitService();
Call<MovieResult> call = retrofitInterface.getBoxOffice(getString(R.string.api_key), "20201222");
call.enqueue(new Callback<MovieResult>() {
@Override
public void onResponse(Call<MovieResult> call, Response<MovieResult> response) {
if(response.isSuccessful()) {
Log.d("msg","연결 성공");
MovieResult movieResult = response.body();
BoxOfficeResult boxOfficeResult = movieResult.getBoxOfficeResult();
mAdapter = new MovieAdapter(boxOfficeResult.getDailyBoxOfficeList());
recyclerView.setAdapter(mAdapter);
progressDialog.dismiss();
}
}
@Override
public void onFailure(Call<MovieResult> call, Throwable t) {
Log.d("retrofit", t.getMessage());
}
});
}
});
}
DrawerLayout.DrawerListener listener = new DrawerLayout.DrawerListener() {
@Override
public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
}
@Override
public void onDrawerOpened(@NonNull View drawerView) {
}
@Override
public void onDrawerClosed(@NonNull View drawerView) {
}
@Override
public void onDrawerStateChanged(int newState) {
}
};
}<file_sep>package com.android.zoom.User.DTO;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
@Data
public class UserResult {
@SerializedName("")
@Expose
private UserData userData;
}
<file_sep>package com.android.zoom.Movie.DTO;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import lombok.Data;
@Data
public class BoxOfficeResult {
@SerializedName("boxofficeType")
@Expose
private String boxofficeType;
@SerializedName("showRange")
@Expose
private String showRange;
@SerializedName("dailyBoxOfficeList")
@Expose
private List<DailyBoxOfficeList> dailyBoxOfficeList = null;
}
<file_sep>package com.android.zoom.Common.Manager;
import android.content.Context;
import android.widget.Toast;
public class ToastManager {
public static void showToastMsg(Context context, String msg) {
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
}
}
| fab046713883e5e4ce1ef68754309562a3e29b6a | [
"Java"
] | 5 | Java | w8230/android_edu | a88ef7ef2d6360190ed0e2e90c16446b1973468f | 4240bc0b98cbb490e5ea2c1abad526205efbcf01 |
refs/heads/master | <file_sep># postprocessing_cdi
script to correct for averaging several reconstructions, correcting for refraction/absorption (not yet for energy scans), removing phase offset/ramp,
interpolating the BCDI data in laboratory frame.
For axes, the Nexus convention is used: z downstream, y vertical, x outboard
For q, the following convention is used: qx downstream, qz vertical, qy outboard
# parameters
simu_flag = 1 # set to 1 if it is simulation, in that case it will add pi to the phase and will not invert it to get the displacement
scan = 281 # spec scan number
datadir = "C:/Users/carnis/Work Folders/Documents/data/IHR_11112018/S"+str(scan)+"/pynxraw/" path to the reconstruction
sdd = 1.25873 # sample to detector distance in m
pixel_size = 55e-6 # detector pixel size in m
reflection = np.array([1, 1, 1]) # measured reflection, use for estimating the temperature
reference_spacing = None # for calibrating the thermal expansion, if None it is fixed to platinum: 3.9236/norm(reflection)
reference_temperature = None # used to calibrate the thermal expansion, if None it is fixed to 293.15K (RT)
sort_by = 'variance/mean' # 'mean_amplitude' or 'variance' or 'variance/mean' or 'volume', metric for finding the best reconstruction to be used as the reference for averaging several reconstructions
correlation_threshold = 0.95 # only reconstructions with a correlation larger than this value will contribute to the average.
original_size = [256, 420, 270] # size of the FFT array used for phasing, when the result has been croped, leave it to [] otherwise
correct_refraction = 0 # 1 for correcting the phase shift due to refraction, 0 otherwise
correct_absorption = 0 # 1 for correcting the amplitude for absorption, 0 otherwise
dispersion = 4.1184E-05 # delta
absorption = 2.3486E-06 # beta
threshold_refraction = 0.20 # threshold used to calculate the optical path
isosurface_strain = 0.25 # threshold use for removing the outer layer (strain is undefined at the exact surface voxel)
threshold_plot = 0.25 # support threshold for plots (max amplitude of 1)
strain_range = 0.001 # for plots
phase_range = np.pi # for plots
keep_size = 0 # 1 to keep the initial array size for orthogonalization (slower)
plot_width = [50, 20, 20] # [z, y, x] margin outside the support in each direction, can be negative. Useful to avoid cutting the object during the orthogonalization
setup = "ID01" # 'SIXS' or '34ID' or 'ID01' or 'P10'
rocking_angle = "outofplane" # "outofplane" or "inplane", does not matter for energy scan. "inplane" e.g. phi @ ID01, mu @ SIXS / "outofplane" e.g. eta @ ID01
en = 8992 # x-ray energy in eV of the Bragg peak
outofplane_angle = 34.5287 # 34.5146 # detector delta ID01, delta SIXS, gamma 34ID
inplane_angle = 0.4536 # 0.4555 # detector nu ID01, gamma SIXS, tth 34ID
grazing_angle = 0 # in degrees, incident angle for in-plane rocking curves (eta ID01, th 34ID, beta SIXS)
tilt_angle = 0.005 # angular step size for rocking angle, eta ID01, mu SIXS, does not matter for energy scan
invert_phase = 1 # should be 1 for the displacement to have the right sign (FT convention), 0 only for simulations
hwidth = 3 # (width-1)/2 of the averaging window for the phase, 0 means no averaging
xrayutils_ortho = 1 # 1 if the data is already orthogonalized
save_raw = 0 # 1 to save the amp-phase.vti before orthogonalization
save_support = 0 # 1 to save the non-orthogonal support for later phase retrieval
save = 1 # 1 to save amp.npz, phase.npz, strain.npz and vtk files
comment = "_iso" + str(isosurface_strain) # should start with _
debug = 0 # to show all plots for debugging
centering = 2 # 0 Max only, 1 COM only, 2 Max then COM
tick_spacing = 25 # for plots, in nm
fix_voxel = 0 # in nm, put 0 to use the default voxel size (mean of the voxel sizes in 3 directions)
output_size = [150, 150, 150] # [z, y, x] Fix the size of the output array, leave it as [] otherwise
align_crystal = 1 # if 1 rotates the crystal to align it along q, 0 otherwise
ref_axis_outplane = "y" # "x", "y" or "z" # q will be aligned along that axis
align_inplane = 0 # if 1 rotates afterwards the crystal inplane to align it along z for easier slicing, 0 otherwise
ref_axis_inplane = "x" # "x", "y" or "z" # will align inplane_normal to that axis
inplane_normal = np.array([1, 0, -0.05]) # facet normal to align with ref_axis_inplane (y should be 0)
<file_sep># -*- coding: utf-8 -*-
"""
strain.py: calculate the strain component from experimental geometry
Input: complex amplitude array from a phasing program
Output: data on orthogonal frame (laboratory or crystal frame), amp_disp_strain array
disp array should be divided by q to get the displacement (disp = -1*phase here)
Laboratory frame: z downstream, y vertical, x outboard
Crystal reciprocal frame: qx downstream, qz vertical, qy outboard
Detector convention: when out_of_plane angle=0 Y=-y , when in_plane angle=0 X=x
In arrays, when plotting the first parameter is the row (vertical axis) and the second the column (horizontal axis)
Therefore the data structure is data[qx, qz, qy] for reciprocal space or data[z, y, x] for real space
Author: <NAME>
Last modification: August 3rd, 2018
"""
import numpy as np
from numpy.fft import fftn, fftshift, ifftn, ifftshift
from matplotlib import pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from scipy.ndimage.measurements import center_of_mass
from scipy.interpolate import RegularGridInterpolator
from scipy.signal import convolve
from scipy.stats import pearsonr
import vtk
from vtk.util import numpy_support
import os
import tkinter as tk
from tkinter import filedialog
import matplotlib.ticker as ticker
import logging
import h5py
import gc
import sys
sys.path.append('C:/Users/carnis/Work Folders/Documents/myscripts/postprocessing_cdi/')
import image_registration as reg
scan = 2191 # spec scan number
datadir = "C:/Users/carnis/Work Folders/Documents/data/CH4760_Pt/S"+str(scan)+"/pynxraw/no_apodization/" # no_apodization" # apodize_during_phasing # apodize_postprocessing
get_temperature = False
reflection = np.array([1, 1, 1]) # measured reflection, use for estimating the temperature
reference_spacing = None # for calibrating the thermal expansion, if None it is fixed to 3.9236/norm(reflection)
reference_temperature = None # used to calibrate the thermal expansion, if None it is fixed to 293.15K (RT)
sort_by = 'variance/mean' # 'mean_amplitude' or 'variance' or 'variance/mean' or 'volume', metric for averaging
correlation_threshold = 0.90
original_size = [270, 432, 400] # size of the FFT array used for phasing, when the result has been croped (.cxi)
# leave it to [] otherwise
output_size = [200, 200, 200] # original_size # [z, y, x] Fix the size of the output array, leave it as [] otherwise
keep_size = 0 # 1 to keep the initial array size for orthogonalization (slower)
fix_voxel = 3.0 # in nm, put 0 to use the default voxel size (mean of the voxel sizes in 3 directions)
hwidth = 0 # (width-1)/2 of the averaging window for the phase, 0 means no averaging
isosurface_strain = 0.5 # threshold use for removing the outer layer (strain is undefined at the exact surface voxel)
comment = "_iso_" + str(isosurface_strain) # "_5e+06_pad800_crop500_noPC" # should start with _
threshold_plot = isosurface_strain # suppor4t threshold for plots (max amplitude of 1)
strain_range = 0.005 # for plots
phase_range = np.pi # for plots
phase_offset = 0 # np.pi # manual offset to add to the phase, should be 0 normally
plot_width = [40, 20, 20] # [55, 0, -10] # [z, y, x] margin outside the support in each direction, can be negative
# useful to avoid cutting the object during the orthogonalization
# define setup below
setup = "ID01" # 'SIXS' or '34ID' or 'ID01' or 'P10' or 'CRISTAL'
rocking_angle = "outofplane" # "outofplane" or "inplane", does not matter for energy scan
# "inplane" e.g. phi @ ID01, mu @ SIXS "outofplane" e.g. eta @ ID01
sdd = 0.50678 # sample to detector distance in m
pixel_size = 55e-6 # detector pixel size in m
en = 8994 # x-ray energy in eV, 6eV offset at ID01
outofplane_angle = 35.3440 # detector delta ID01, delta SIXS, gamma 34ID
inplane_angle = -0.9265 # detector nu ID01, gamma SIXS, tth 34ID
grazing_angle = 0 # in degrees, incident angle for in-plane rocking curves (eta ID01, th 34ID, beta SIXS)
tilt_angle = 0.01015 # angular step size for rocking angle, eta ID01, mu SIXS, does not matter for energy scan
correct_refraction = 1 # 1 for correcting the phase shift due to refraction, 0 otherwise
correct_absorption = 1 # 1 for correcting the amplitude for absorption, 0 otherwise
dispersion = 4.1184E-05 # delta
# Pt: 3.2880E-05 @ 9994eV, 4.1184E-05 @ 8994keV, 5.2647E-05 @ 7994keV, 4.6353E-05 @ 8500eV / Ge 1.4718E-05 @ 8keV
absorption = 3.4298E-06 # beta
# Pt: 2.3486E-06 @ 9994eV, 3.4298E-06 @ 8994keV, 5.2245E-06 @ 7994keV, 4.1969E-06 @ 8500eV
threshold_refraction = 0.1 # threshold used to calculate the optical path
#########################
simu_flag = 0 # set to 1 if it is simulation, the parameter invert_phase will be set to 0 and pi added to the phase
invert_phase = 1 # should be 1 for the displacement to have the right sign (FFT convention), 0 only for simulations
phase_ramp_removal = 'gradient' # 'gradient' or 'upsampling'
xrayutils_ortho = 0 # 1 if the data is already orthogonalized
save_raw = False # True to save the amp-phase.vti before orthogonalization
save_support = False # True to save the non-orthogonal support for later phase retrieval
save_labframe = False # True to save the data in the laboratory frame (before rotations), used for PRTF calculation
save = True # True to save amp.npz, phase.npz, strain.npz and vtk files
apodize_flag = False # True to multiply the diffraction pattern by a 3D gaussian
debug = 0 # 1 to show all plots for debugging
tick_spacing = 50 # for plots, in nm
tick_direction = 'inout' # 'out', 'in', 'inout'
tick_length = 3 # 10 # in plots
tick_width = 1 # 2 # in plots
figure_size = (13, 9) # in inches
centering = 2 # 0 Max only, 1 COM only, 2 Max then COM
align_crystal = 1 # if 1 rotates the crystal to align it along q, 0 otherwise
ref_axis_outplane = "y" # "y" # "z" # q will be aligned along that axis
# TODO: where is q for energy scans? Should we just rotate the reconstruction to have q along one axis, instead of using sample offsets?
align_inplane = 0 # if 1 rotates afterwards the crystal inplane to align it along z for easier slicing, 0 otherwise
ref_axis_inplane = "x" # "x" # will align inplane_normal to that axis
inplane_normal = np.array([1, 0, -0.05]) # facet normal to align with ref_axis_inplane (y should be 0)
#########################################################
if simu_flag == 1:
invert_phase = 0
correct_absorption = 0
correct_refraction = 0
if invert_phase == 1:
phase_fieldname = 'disp'
else:
phase_fieldname = 'phase'
#########################################################
def mean_filter(myamp, myphase, half_width, mythreshold=0.5, debugging=0):
"""
mean_filter: function to apply a mean filter to the phase
:param myamp: corresponding amplitude
:param myphase: phase to be averaged
:param half_width: half_width of the cubic averaging window, 0 means no averaging, 1 is one pixel away...
:param mythreshold: threshold for support determination
:param debugging: set to 1 for plotting
:return: averaged phase
"""
global xrange, yrange, zrange
if half_width != 0:
nbz, nby, nbx = myamp.shape
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(myphase[:, :, nbx // 2], vmin=-phase_range, vmax=phase_range, cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("Phase in middle slice in YZ before averaging")
plt.subplot(2, 2, 2)
plt.imshow(myphase[:, nby // 2, :], vmin=-phase_range, vmax=phase_range, cmap=my_cmap)
plt.colorbar()
plt.title("Phase in middle slice in XZ before averaging")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(myphase[nbz // 2, :, :], vmin=-phase_range, vmax=phase_range, cmap=my_cmap)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Phase in middle slice in XY before averaging")
plt.axis('scaled')
plt.pause(0.1)
mysupport = np.zeros((nbz, nby, nbx))
mysupport[myamp > mythreshold * abs(myamp).max()] = 1
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(mysupport[:, :, nbx // 2], vmin=0, vmax=1, cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("support for phase average in middle slice in YZ")
plt.subplot(2, 2, 2)
plt.imshow(mysupport[:, nby // 2, :], vmin=0, vmax=1, cmap=my_cmap)
plt.colorbar()
plt.title("support for phase average in XZ")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(mysupport[nbz // 2, :, :], vmin=0, vmax=1, cmap=my_cmap)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("support for phase average in XY")
plt.axis('scaled')
plt.pause(0.1)
nonzero_pixels = np.argwhere(mysupport != 0)
new_values = np.zeros((nonzero_pixels.shape[0], 1), dtype=myphase.dtype)
counter = 0
for indx in range(nonzero_pixels.shape[0]):
piz = nonzero_pixels[indx, 0]
piy = nonzero_pixels[indx, 1]
pix = nonzero_pixels[indx, 2]
tempo_support = mysupport[piz-half_width:piz+half_width+1, piy-half_width:piy+half_width+1,
pix-half_width:pix+half_width+1]
nb_points = tempo_support.sum()
temp_phase = myphase[piz-half_width:piz+half_width+1, piy-half_width:piy+half_width+1,
pix-half_width:pix+half_width+1]
if temp_phase.size != 0:
value = temp_phase[np.nonzero(tempo_support)].sum()/nb_points
new_values[indx] = value
else:
counter = counter + 1
for indx in range(nonzero_pixels.shape[0]):
phase[nonzero_pixels[indx, 0], nonzero_pixels[indx, 1], nonzero_pixels[indx, 2]] = new_values[indx]
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(myphase[:, :, nbx // 2], vmin=-phase_range, vmax=phase_range, cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("Phase in middle slice in YZ after averaging")
plt.subplot(2, 2, 2)
plt.imshow(myphase[:, nby // 2, :], vmin=-phase_range, vmax=phase_range, cmap=my_cmap)
plt.colorbar()
plt.title("Phase in middle slice in XZ after averaging")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(myphase[nbz // 2, :, :], vmin=-phase_range, vmax=phase_range, cmap=my_cmap)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Phase in middle slice in XY after averaging")
plt.axis('scaled')
plt.pause(0.1)
print("There were", counter, "voxels for which phase could not be averaged")
return myphase
def refraction_corr(myamp, direction, threshold, xrayutils_orthogonal, k=np.zeros(3), debugging=0):
"""
correct the phase for the effect of refraction in the crystal
:param myamp: amplitude
:param direction: "in" or "out" , incident or diffracted wave
:param threshold: used for defining the support
:param xrayutils_orthogonal: 1 if the data was already orthogonalized before phasing, 0 otherwise
:param k: vector for the incident or diffracted wave depending on direction (xrayutilities case)
:param debugging: 1 to show plots
:return: correction phase
"""
global xrange, yrange, zrange
nbz, nby, nbx = myamp.shape
path = np.zeros((nbz, nby, nbx))
mysupport = np.zeros((nbz, nby, nbx))
mysupport[myamp > threshold * abs(myamp).max()] = 1
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(mysupport.sum(axis=2), cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("Sum(mysupport) in YZ (corr_refraction)")
plt.subplot(2, 2, 2)
plt.imshow(mysupport.sum(axis=1), cmap=my_cmap)
plt.colorbar()
plt.title("Sum(mysupport) in XZ (corr_refraction)")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(mysupport.sum(axis=0), cmap=my_cmap)
plt.colorbar()
plt.title("Sum(mysupport) in XY (corr_refraction)")
plt.axis('scaled')
plt.pause(0.1)
# find limits of the centered crystal
myz, _, _ = np.meshgrid(np.arange(0, nbz, 1), np.arange(0, nby, 1), np.arange(0, nbx, 1),
indexing='ij')
myz = myz * mysupport
min_myz = int(np.min(myz[np.nonzero(myz)]))
max_myz = int(np.max(myz[np.nonzero(myz)])+1) # include last index
del myz
print("Refraction correction (start_z, stop_z):(", min_myz, ',', max_myz, ')')
if direction == "in":
if xrayutils_orthogonal == 0:
for idz in range(min_myz, max_myz, 1):
path[idz, :, :] = mysupport[0:idz, :, :].sum(axis=0)
if xrayutils_orthogonal == 1: # case when data was already orthogonalized in crystal frame before phasing
k_norm = k / np.linalg.norm(k)
pass
# TODO: implement the same as direction out to calculate the path_in
if direction == "out":
if xrayutils_orthogonal == 0:
for idz in range(min_myz, max_myz, 1):
path[idz, :, :] = mysupport[idz:numz, :, :].sum(axis=0)
if xrayutils_orthogonal == 1: # case when data was already orthogonalized in crystal frame before phasing
# TODO: check this, probably wrong, object is in crystal frame after xrayutilities
k_norm = k / np.linalg.norm(k)
for idz in range(min_myz, max_myz, 1):
myy, myx = np.meshgrid(np.arange(0, nby, 1), np.arange(0, nbx, 1), indexing='ij')
myy = myy * mysupport[idz, :, :]
try:
min_myy = int(np.min(myy[np.nonzero(myy)]))
max_myy = int(np.max(myy[np.nonzero(myy)]) + 1)
except BaseException as e:
logger.error(str(e))
continue
del myy
myx = myx * mysupport[idz, :, :]
try:
min_myx = int(np.min(myx[np.nonzero(myx)]))
max_myx = int(np.max(myx[np.nonzero(myx)]) + 1)
except BaseException as e:
logger.error(str(e))
continue
del myx
for idy in range(min_myy, max_myy, 1):
for idx in range(min_myx, max_myx, 1):
stop_flag = 0
counter = 1
new_pixel = np.array([idz, idy, idx])
while stop_flag == 0:
new_pixel = new_pixel + counter * k_norm
coords = np.rint(new_pixel)
stop_flag = 1
if (coords[0] in range(nbz)) and (coords[1] in range(nby)) and (coords[2] in range(nbx)):
path[idz, idy, idx] = path[idz, idy, idx] + \
mysupport[int(coords[0]), int(coords[1]), int(coords[2])]
counter = counter + 1
stop_flag = 0
path = path * mysupport
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(path[nbz // 2 - zrange:nbz // 2 + zrange, nby // 2 - yrange:nby // 2 + yrange, nbx // 2])
plt.colorbar()
plt.axis('scaled')
plt.title("Optical path " + direction + " in pixels at middle frame in YZ")
plt.subplot(2, 2, 2)
plt.imshow(path[nbz // 2 - zrange:nbz // 2 + zrange, nby // 2, nbx // 2 - xrange:nbx // 2 + xrange])
plt.colorbar()
plt.title("Optical path " + direction + " in pixels at middle frame in XZ")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(path[nbz // 2, nby // 2 - yrange:nby // 2 + yrange, nbx // 2 - xrange:nbx // 2 + xrange])
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Optical path " + direction + " in pixels at middle frame in XY")
plt.axis('scaled')
plt.pause(0.1)
return path
def apodize(myamp, myphase, sigma=np.array([0.3, 0.3, 0.3]), mu=np.array([0.0, 0.0, 0.0]), debugging=0):
"""
:param myamp: amplitude before apodization
:param myphase: phase before apodization
:param sigma: sigma of the gaussian
:param mu: mu of the gaussian
:param debugging: to show plots
:return: normalized amplitude, phase of the same shape as myamp
"""
from scipy.stats import multivariate_normal
global xrange, yrange, zrange, original_size # original fft window size
nb_z, nb_y, nb_x = myamp.shape
nbz, nby, nbx = original_size # original size of the FFT window during phasing
myobj = crop_pad(myamp * np.exp(1j * myphase), (nbz, nby, nbx))
del myamp, myphase
gc.collect()
if debugging:
plt.figure()
plt.imshow(abs(myobj[nbz // 2, :, :]))
plt.pause(0.1)
my_fft = fftshift(fftn(myobj))
del myobj
gc.collect()
fftmax = abs(my_fft).max()
print('Max FFT=', fftmax)
if debugging:
plt.figure()
plt.imshow(np.log10(abs(my_fft[nbz // 2, :, :])))
plt.pause(0.1)
grid_z, grid_y, grid_x = np.meshgrid(np.linspace(-1, 1, nbz), np.linspace(-1, 1, nby), np.linspace(-1, 1, nbx),
indexing='ij')
covariance = np.diag(sigma ** 2)
window = multivariate_normal.pdf(np.column_stack([grid_z.flat, grid_y.flat, grid_x.flat]), mean=mu, cov=covariance)
del grid_z, grid_y, grid_x
gc.collect()
window = window.reshape((nbz, nby, nbx))
my_fft = np.multiply(my_fft, window)
del window
gc.collect()
my_fft = my_fft * fftmax / abs(my_fft).max()
print('Max apodized FFT after normalization =', abs(my_fft).max())
if debugging:
plt.figure()
plt.imshow(np.log10(abs(my_fft[nbz // 2, :, :])))
plt.pause(0.1)
myobj = ifftn(ifftshift(my_fft))
del my_fft
gc.collect()
if debugging:
plt.figure()
plt.imshow(abs(myobj[nbz // 2, :, :]))
plt.pause(0.1)
myobj = crop_pad(myobj, (nb_z, nb_y, nb_x)) # return to the initial shape of myamp
return abs(myobj), np.angle(myobj)
def remove_ramp(myamp, myphase, threshold=0.25, gradient_threshold=1, method='gradient', ups_factor=2, debugging=0):
"""
remove_ramp: remove the linear trend in the ramp using its gradient and a threshold
:param myamp: amplitude of the object
:param myphase: phase of the object, to be detrended
:param threshold: threshold used to define the support of the object
:param gradient_threshold: higher threshold used to select valid voxels in the gradient array
:param method: 'gradient' or 'upsampling'
:param ups_factor: upsampling factor (the original shape will be multiplied by this value)
:param debugging: 1 to show plots
:return: normalized amplitude, detrended phase of the same shape as myamp
"""
global xrange, yrange, zrange, original_size # original fft window size
if method == 'upsampling':
nbz, nby, nbx = [mysize*ups_factor for mysize in original_size]
nb_z, nb_y, nb_x = myamp.shape
myobj = crop_pad(myamp * np.exp(1j * myphase), (nbz, nby, nbx))
if debugging:
plt.figure()
plt.imshow(np.log10(abs(myobj).sum(axis=0)))
plt.title('abs(my_fft).sum(axis=0)')
plt.pause(0.1)
my_fft = fftshift(fftn(ifftshift(myobj)))
del myobj, myamp, myphase
gc.collect()
if debugging:
plt.figure()
# plt.imshow(np.log10(abs(my_fft[nbz//2, :, :])))
plt.imshow(np.log10(abs(my_fft).sum(axis=0)))
plt.title('abs(my_fft).sum(axis=0)')
plt.pause(0.1)
zcom, ycom, xcom = center_of_mass(abs(my_fft)**4)
print('FFT shape for subpixel shift:', nbz, nby, nbx)
print('COM before subpixel shift', zcom, ',', ycom, ',', xcom)
shiftz = zcom - (nbz / 2)
shifty = ycom - (nby / 2)
shiftx = xcom - (nbx / 2)
# phase shift in real space
buf2ft = fftn(my_fft) # in real space
del my_fft
gc.collect()
if debugging:
plt.figure()
plt.imshow(abs(buf2ft).sum(axis=0))
plt.title('abs(buf2ft).sum(axis=0)')
plt.pause(0.1)
z_axis = ifftshift(np.arange(-np.fix(nbz/2), np.ceil(nbz/2), 1))
y_axis = ifftshift(np.arange(-np.fix(nby/2), np.ceil(nby/2), 1))
x_axis = ifftshift(np.arange(-np.fix(nbx/2), np.ceil(nbx/2), 1))
z_axis, y_axis, x_axis = np.meshgrid(z_axis, y_axis, x_axis, indexing='ij')
greg = buf2ft * np.exp(1j * 2 * np.pi * (shiftz * z_axis / nbz + shifty * y_axis / nby + shiftx * x_axis / nbx))
del buf2ft, z_axis, y_axis, x_axis
gc.collect()
if debugging:
plt.figure()
plt.imshow(abs(greg).sum(axis=0))
plt.title('abs(greg).sum(axis=0)')
plt.pause(0.1)
my_fft = ifftn(greg)
del greg
gc.collect()
# end of phase shift in real space
if debugging:
plt.figure()
plt.imshow(np.log10(abs(my_fft).sum(axis=0)))
plt.title('centered abs(my_fft).sum(axis=0)')
plt.pause(0.1)
print('COM after subpixel shift', center_of_mass(abs(my_fft) ** 4))
myobj = fftshift(ifftn(ifftshift(my_fft)))
del my_fft
gc.collect()
if debugging:
plt.figure()
plt.imshow(abs(myobj).sum(axis=0))
plt.title('centered abs(myobj).sum(axis=0)')
plt.pause(0.1)
myobj = crop_pad(myobj, (nb_z, nb_y, nb_x)) # return to the initial shape of myamp
print('Upsampling: shift_z, shift_y, shift_x: (', str('{:.3f}'.format(shiftz)),
str('{:.3f}'.format(shifty)), str('{:.3f}'.format(shiftx)), ') pixels')
return abs(myobj)/abs(myobj).max(), np.angle(myobj)
else:
grad_threshold = gradient_threshold
nbz, nby, nbx = myamp.shape
mysupport = np.zeros((nbz, nby, nbx))
mysupport[myamp > threshold*abs(myamp).max()] = 1
mygradz, mygrady, mygradx = np.gradient(myphase, 1)
mysupportz = np.zeros((nbz, nby, nbx))
mysupportz[abs(mygradz) < grad_threshold] = 1
mysupportz = mysupportz * mysupport
myrampz = mygradz[mysupportz == 1].mean()
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(mygradz[nbz // 2 - zrange:nbz // 2 + zrange, nby // 2 - yrange:nby // 2 + yrange, nbx // 2],
vmin=-0.2, vmax=0.2)
plt.colorbar()
plt.axis('scaled')
plt.title("mygradz")
plt.subplot(2, 2, 2)
plt.imshow(mygradz[nbz // 2 - zrange:nbz // 2 + zrange, nby // 2, nbx // 2 - xrange:nbx // 2 + xrange],
vmin=-0.2, vmax=0.2)
plt.colorbar()
plt.title("mygradz")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(mygradz[nbz // 2, nby // 2 - yrange:nby // 2 + yrange, nbx // 2 - xrange:nbx // 2 + xrange],
vmin=-0.2, vmax=0.2)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("mygradz")
plt.axis('scaled')
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(mysupportz[nbz // 2 - zrange:nbz // 2 + zrange, nby // 2 - yrange:nby // 2 + yrange, nbx // 2],
vmin=0, vmax=1)
plt.colorbar()
plt.axis('scaled')
plt.title("mysupportz")
plt.subplot(2, 2, 2)
plt.imshow(mysupportz[nbz // 2 - zrange:nbz // 2 + zrange, nby // 2, nbx // 2 - xrange:nbx // 2 + xrange],
vmin=0, vmax=1)
plt.colorbar()
plt.title("mysupportz")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(mysupportz[nbz // 2, nby // 2 - yrange:nby // 2 + yrange, nbx // 2 - xrange:nbx // 2 + xrange],
vmin=0, vmax=1)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("mysupportz")
plt.axis('scaled')
plt.pause(0.1)
del mysupportz, mygradz
mysupporty = np.zeros((nbz, nby, nbx))
mysupporty[abs(mygrady) < grad_threshold] = 1
mysupporty = mysupporty * mysupport
myrampy = mygrady[mysupporty == 1].mean()
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(mygrady[nbz // 2 - zrange:nbz // 2 + zrange, nby // 2 - yrange:nby // 2 + yrange, nbx // 2],
vmin=-0.2, vmax=0.2)
plt.colorbar()
plt.axis('scaled')
plt.title("mygrady")
plt.subplot(2, 2, 2)
plt.imshow(mygrady[nbz // 2 - zrange:nbz // 2 + zrange, nby // 2, nbx // 2 - xrange:nbx // 2 + xrange],
vmin=-0.2, vmax=0.2)
plt.colorbar()
plt.title("mygrady")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(mygrady[nbz // 2, nby // 2 - yrange:nby // 2 + yrange, nbx // 2 - xrange:nbx // 2 + xrange],
vmin=-0.2, vmax=0.2)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("mygrady")
plt.axis('scaled')
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(mysupporty[nbz // 2 - zrange:nbz // 2 + zrange, nby // 2 - yrange:nby // 2 + yrange, nbx // 2],
vmin=0, vmax=1)
plt.colorbar()
plt.axis('scaled')
plt.title("mysupporty")
plt.subplot(2, 2, 2)
plt.imshow(mysupporty[nbz // 2 - zrange:nbz // 2 + zrange, nby // 2, nbx // 2 - xrange:nbx // 2 + xrange],
vmin=0, vmax=1)
plt.colorbar()
plt.title("mysupporty")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(mysupporty[nbz // 2, nby // 2 - yrange:nby // 2 + yrange, nbx // 2 - xrange:nbx // 2 + xrange],
vmin=0, vmax=1)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("mysupporty")
plt.axis('scaled')
plt.pause(0.1)
del mysupporty, mygrady
mysupportx = np.zeros((nbz, nby, nbx))
mysupportx[abs(mygradx) < grad_threshold] = 1
mysupportx = mysupportx * mysupport
myrampx = mygradx[mysupportx == 1].mean()
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(mygradx[nbz // 2 - zrange:nbz // 2 + zrange, nby // 2 - yrange:nby // 2 + yrange, nbx // 2],
vmin=-0.2, vmax=0.2)
plt.colorbar()
plt.axis('scaled')
plt.title("mygradx")
plt.subplot(2, 2, 2)
plt.imshow(mygradx[nbz // 2 - zrange:nbz // 2 + zrange, nby // 2, nbx // 2 - xrange:nbx // 2 + xrange],
vmin=-0.2, vmax=0.2)
plt.colorbar()
plt.title("mygradx")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(mygradx[nbz // 2, nby // 2 - yrange:nby // 2 + yrange, nbx // 2 - xrange:nbx // 2 + xrange],
vmin=-0.2, vmax=0.2)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("mygradx")
plt.axis('scaled')
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(mysupportx[nbz // 2 - zrange:nbz // 2 + zrange, nby // 2 - yrange:nby // 2 + yrange, nbx // 2],
vmin=0, vmax=1)
plt.colorbar()
plt.axis('scaled')
plt.title("mysupportx")
plt.subplot(2, 2, 2)
plt.imshow(mysupportx[nbz // 2 - zrange:nbz // 2 + zrange, nby // 2, nbx // 2 - xrange:nbx // 2 + xrange],
vmin=0, vmax=1)
plt.colorbar()
plt.title("mysupportx")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(mysupportx[nbz // 2, nby // 2 - yrange:nby // 2 + yrange, nbx // 2 - xrange:nbx // 2 + xrange],
vmin=0, vmax=1)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("mysupportx")
plt.axis('scaled')
plt.pause(0.1)
del mysupportx, mygradx, mysupport
myz, myy, myx = np.meshgrid(np.arange(0, nbz, 1), np.arange(0, nby, 1), np.arange(0, nbx, 1),
indexing='ij')
print('Gradient: Phase_ramp_z, Phase_ramp_y, Phase_ramp_x: (', str('{:.3f}'.format(myrampz)),
str('{:.3f}'.format(myrampy)), str('{:.3f}'.format(myrampx)), ') rad')
myphase = myphase - myz * myrampz - myy * myrampy - myx * myrampx
return myamp, myphase
def orthogonalize(myobj, energy, outofplane, inplane, tilt, myrocking_angle, mygrazing_angle, distance, pixel_x,
pixel_y, myvoxel_size, geometry, debugging=0):
"""
interpolate myobj on the orthogonal reference frame
:param myobj: real space object, in a non-orthogonal frame (output of phasing program)
:param energy: in eV
:param outofplane: in degrees
:param inplane: in degrees (also called inplane_angle depending on the diffractometer)
:param tilt: angular step during the rocking curve, in degrees (ID01 geometry: eta)
:param myrocking_angle: name of the angle which is tilted during the rocking curve
:param mygrazing_angle: in degrees, incident angle for in-plane rocking curves (eta ID01, th 34ID, beta SIXS)
:param distance: sample to detector distance, in meters
:param pixel_x: horizontal pixel size, in meters
:param pixel_y: vertical pixel size, in meters
:param myvoxel_size: user-defined voxel size, in nm
:param geometry: name of the setup 'ID01'or 'SIXS' or '34ID' or 'P10' or 'CRISTAL'
:param debugging: 1 to show plots
:return: object interpolated on an orthogonal grid
"""
global nx, ny, nz, original_size # original fft window size
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(abs(myobj).sum(axis=2), cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title('Sum(non_ortho_obj) in YZ')
plt.subplot(2, 2, 2)
plt.imshow(abs(myobj).sum(axis=1), cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title('Sum(non_ortho_obj) in XZ')
plt.subplot(2, 2, 3)
plt.imshow(abs(myobj).sum(axis=0), cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title('Sum(non_ortho_obj) in XY')
plt.pause(0.1)
tilt_sign = np.sign(tilt)
wavelength = 12.398 * 1e-7 / energy # in m
if len(original_size) != 0:
dz_realspace = wavelength / (original_size[0] * abs(tilt) * np.pi / 180) * 1e9 # in nm
dy_realspace = wavelength * distance / (original_size[1] * pixel_y) * 1e9 # in nm
dx_realspace = wavelength * distance / (original_size[2] * pixel_x) * 1e9 # in nm
else:
dz_realspace = wavelength / (nz * abs(tilt) * np.pi / 180) * 1e9 # in nm
dy_realspace = wavelength * distance / (ny * pixel_y) * 1e9 # in nm
dx_realspace = wavelength * distance / (nx * pixel_x) * 1e9 # in nm
print('Original real space pixel size (z, y, x): (', str('{:.2f}'.format(dz_realspace)), 'nm,',
str('{:.2f}'.format(dy_realspace)), 'nm,', str('{:.2f}'.format(dx_realspace)), 'nm )')
nbz, nby, nbx = myobj.shape # could be smaller if the object was cropped around the support
if nbz != nz or nby != ny or nbx != nx:
pixel_x = wavelength * distance / (nbx * dx_realspace) * 1e9 # in m
pixel_y = wavelength * distance / (nby * dy_realspace) * 1e9 # in m
newtilt = tilt_sign * wavelength / (nbz * dz_realspace * np.pi / 180) * 1e9 # in m
print('New tilt, pixel_y, pixel_x: (', str('{:.4f}'.format(newtilt)), 'deg,',
str('{:.2f}'.format(pixel_y*1e6)), 'um,', str('{:.2f}'.format(pixel_x*1e6)), 'um)')
dz_realspace = wavelength / (nbz * abs(newtilt) * np.pi / 180) * 1e9 # in nm
dy_realspace = wavelength * distance / (nby * pixel_y) * 1e9 # in nm
dx_realspace = wavelength * distance / (nbx * pixel_x) * 1e9 # in nm
print('New real space pixel size (z, y, x): (', str('{:.2f}'.format(dz_realspace)), ' nm,',
str('{:.2f}'.format(dy_realspace)), 'nm,', str('{:.2f}'.format(dx_realspace)), 'nm )')
else:
newtilt = tilt
if myvoxel_size != 0:
voxel = myvoxel_size
else:
voxel = np.mean([dz_realspace, dy_realspace, dx_realspace]) # in nm
myz, myy, myx = np.meshgrid(np.arange(0, nbz, 1), np.arange(0, nby, 1), np.arange(0, nbx, 1),
indexing='ij')
old_z, old_y, old_x, ortho_matrix = update_coords(mygrid=(myz, myy, myx), wavelength=wavelength,
outofplane=outofplane, inplane=inplane, tilt=newtilt,
myrocking_angle=myrocking_angle, mygrazing_angle=mygrazing_angle,
distance=distance, pixel_x=pixel_x, pixel_y=pixel_y,
geometry=geometry)
del myz, myy, myx
# old_z = old_z - old_z.mean() # center array (crystal is centered)
# old_y = old_y - old_y.mean() # center array (crystal is centered)
# old_x = old_x - old_x.mean() # center array (crystal is centered)
# # old_coords is a tuple of 3 X 3D non-orthogonal coordinates arrays in the new frame
# z0, z1 = old_z.min(), old_z.max()
# y0, y1 = old_y.min(), old_y.max()
# x0, x1 = old_x.min(), old_x.max()
del old_x, old_y, old_z
############################
# Vincent's method using inverse transformation
############################
# z, y, x = np.meshgrid(np.linspace(z0, z1, numz), np.linspace(y0, y1, numy), np.linspace(x0, x1, numx),
# indexing='ij')
myz, myy, myx = np.meshgrid(np.arange(-nbz//2, nbz//2, 1)*voxel, np.arange(-nby//2, nby//2, 1)*voxel,
np.arange(-nbx//2, nbx//2, 1)*voxel, indexing='ij')
ortho_imatrix = np.linalg.inv(ortho_matrix)
new_x = ortho_imatrix[0, 0] * myx + ortho_imatrix[0, 1] * myy + ortho_imatrix[0, 2] * myz
new_y = ortho_imatrix[1, 0] * myx + ortho_imatrix[1, 1] * myy + ortho_imatrix[1, 2] * myz
new_z = ortho_imatrix[2, 0] * myx + ortho_imatrix[2, 1] * myy + ortho_imatrix[2, 2] * myz
del myx, myy, myz
# myobj = np.ones((nbz, nby, nbx))
rgi = RegularGridInterpolator((np.arange(-nbz//2, nbz//2), np.arange(-nby//2, nby//2),
np.arange(-nbx//2, nbx//2)), myobj, method='linear',
bounds_error=False, fill_value=0)
ortho_obj = rgi(np.concatenate((new_z.reshape((1, new_z.size)), new_y.reshape((1, new_z.size)),
new_x.reshape((1, new_z.size)))).transpose())
ortho_obj = ortho_obj.reshape((nbz, nby, nbx)).astype(myobj.dtype)
########################
# Slower using griddata
# ######################
# #
# new_z, new_y, new_x = np.meshgrid(np.linspace(z0, z1, numz), np.linspace(y0, y1, numy), np.linspace(x0, x1, numx),
# indexing='ij')
# # tuple of 3 X 3D orthogonal coordinates arrays in the new frame
# ortho_obj = griddata(np.array([np.ndarray.flatten(old_z),
# np.ndarray.flatten(old_y), np.ndarray.flatten(old_x)]).T,
# np.ndarray.flatten(myobj), (new_z, new_y, new_x), method='linear', fill_value=0)
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(abs(ortho_obj).sum(axis=2), cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title('Sum(ortho_obj) in YZ')
plt.subplot(2, 2, 2)
plt.imshow(abs(ortho_obj).sum(axis=1), cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title('Sum(ortho_obj) in XZ')
plt.subplot(2, 2, 3)
plt.imshow(abs(ortho_obj).sum(axis=0), cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title('Sum(ortho_obj) in XY')
plt.pause(0.1)
# myz, myy, myx = np.meshgrid(np.arange(-nbz//2, nbz//2, 1), np.arange(-nby//2, nby//2, 1),
# np.arange(-nbx//2, nbx//2, 1), indexing='ij')
#
# new_x = ortho_matrix[0, 0] * myx + ortho_matrix[0, 1] * myy + ortho_matrix[0, 2] * myz
# new_y = ortho_matrix[1, 0] * myx + ortho_matrix[1, 1] * myy + ortho_matrix[1, 2] * myz
# new_z = ortho_matrix[2, 0] * myx + ortho_matrix[2, 1] * myy + ortho_matrix[2, 2] * myz
# del myx, myy, myz
#
# rgi = RegularGridInterpolator((np.arange(-nbz//2, nbz//2)*voxel, np.arange(-nby//2, nby//2)*voxel,
# np.arange(-nbx//2, nbx//2)*voxel), ortho_obj, method='linear',
# bounds_error=False, fill_value=0)
# detector_obj = rgi(np.concatenate((new_z.reshape((1, new_z.size)), new_y.reshape((1, new_z.size)),
# new_x.reshape((1, new_z.size)))).transpose())
# detector_obj = detector_obj.reshape((nbz, nby, nbx)).astype(ortho_obj.dtype)
#
# if debugging == 1:
# plt.figure(figsize=(18, 15))
# plt.subplot(2, 2, 1)
# plt.imshow(abs(detector_obj).sum(axis=2), cmap=my_cmap)
# plt.colorbar()
# plt.axis('scaled')
# plt.title('Sum(non_ortho_obj) in YZ')
# plt.subplot(2, 2, 2)
# plt.imshow(abs(detector_obj).sum(axis=1), cmap=my_cmap)
# plt.colorbar()
# plt.axis('scaled')
# plt.title('Sum(non_ortho_obj) in XZ')
# plt.subplot(2, 2, 3)
# plt.imshow(abs(detector_obj).sum(axis=0), cmap=my_cmap)
# plt.colorbar()
# plt.axis('scaled')
# plt.title('Sum(non_ortho_obj) in XY')
# plt.pause(0.1)
return ortho_obj, voxel
def update_coords(mygrid, wavelength, outofplane, inplane, tilt, myrocking_angle, mygrazing_angle, distance,
pixel_x, pixel_y, geometry):
"""
calculate the pixel non-orthogonal coordinates in the orthogonal reference frame
:param mygrid: grid corresponding to the real object size
:param wavelength: in m
:param outofplane: in degrees
:param inplane: in degrees (also called inplane_angle depending on the diffractometer)
:param tilt: angular step during the rocking curve, in degrees
:param myrocking_angle: name of the motor which is tilted during the rocking curve
:param mygrazing_angle: in degrees, incident angle for in-plane rocking curves (eta ID01, th 34ID, beta SIXS)
:param distance: sample to detector distance, in meters
:param pixel_x: horizontal pixel size, in meters
:param pixel_y: vertical pixel size, in meters
:param geometry: name of the setup 'ID01'or 'SIXS' or '34ID' or 'P10' or 'CRISTAL'
:return: coordinates of the non-orthogonal grid in the orthogonal reference grid
"""
wavelength = wavelength * 1e9 # convert to nm
distance = distance * 1e9 # convert to nm
lambdaz = wavelength * distance
pixel_x = pixel_x * 1e9 # convert to nm
pixel_y = pixel_y * 1e9 # convert to nm
mymatrix = np.zeros((3, 3))
outofplane = np.radians(outofplane)
inplane = np.radians(inplane)
tilt = np.radians(tilt)
mygrazing_angle = np.radians(mygrazing_angle)
nbz, nby, nbx = mygrid[0].shape
if geometry == 'ID01':
print('using ESRF ID01 PSIC geometry')
if myrocking_angle == "outofplane":
print('rocking angle is eta')
# rocking eta angle clockwise around x (phi does not matter, above eta)
mymatrix[:, 0] = 2*np.pi*nbx / lambdaz * np.array([pixel_x*np.cos(inplane),
0,
pixel_x*np.sin(inplane)])
mymatrix[:, 1] = 2*np.pi*nby / lambdaz * np.array([-pixel_y*np.sin(inplane)*np.sin(outofplane),
-pixel_y*np.cos(outofplane),
pixel_y*np.cos(inplane)*np.sin(outofplane)])
mymatrix[:, 2] = 2*np.pi*nbz / lambdaz * np.array([0,
tilt*distance*(1-np.cos(inplane)*np.cos(outofplane)),
tilt*distance*np.sin(outofplane)])
elif myrocking_angle == "inplane" and mygrazing_angle == 0:
print('rocking angle is phi, eta=0')
# rocking phi angle clockwise around y, assuming incident angle eta is zero (eta below phi)
mymatrix[:, 0] = 2*np.pi*nbx / lambdaz * np.array([pixel_x*np.cos(inplane),
0,
pixel_x*np.sin(inplane)])
mymatrix[:, 1] = 2*np.pi*nby / lambdaz * np.array([-pixel_y*np.sin(inplane)*np.sin(outofplane),
-pixel_y*np.cos(outofplane),
pixel_y*np.cos(inplane)*np.sin(outofplane)])
mymatrix[:, 2] = 2*np.pi*nbz / lambdaz * np.array([-tilt*distance*(1-np.cos(inplane)*np.cos(outofplane)),
0,
tilt*distance*np.sin(inplane)*np.cos(outofplane)])
elif myrocking_angle == "inplane" and mygrazing_angle != 0:
print('rocking angle is phi, with eta non zero')
# rocking phi angle clockwise around y, incident angle eta is non zero (eta below phi)
mymatrix[:, 0] = 2*np.pi*nbx / lambdaz * np.array([pixel_x*np.cos(inplane),
0,
pixel_x*np.sin(inplane)])
mymatrix[:, 1] = 2*np.pi*nby / lambdaz * np.array([-pixel_y*np.sin(inplane)*np.sin(outofplane),
-pixel_y*np.cos(outofplane),
pixel_y*np.cos(inplane)*np.sin(outofplane)])
mymatrix[:, 2] = 2*np.pi*nbz / lambdaz * tilt * distance * \
np.array([(np.sin(mygrazing_angle)*np.sin(outofplane)+
np.cos(mygrazing_angle)*(np.cos(inplane)*np.cos(outofplane)-1)),
np.sin(mygrazing_angle)*np.sin(inplane)*np.sin(outofplane),
np.cos(mygrazing_angle)*np.sin(inplane)*np.cos(outofplane)])
if geometry == 'P10':
print('using PETRAIII P10 geometry')
if myrocking_angle == "outofplane":
print('rocking angle is omega')
# rocking omega angle clockwise around x at mu=0 (phi does not matter, above eta)
mymatrix[:, 0] = 2*np.pi*nbx / lambdaz * np.array([pixel_x*np.cos(inplane),
0,
-pixel_x*np.sin(inplane)])
mymatrix[:, 1] = 2*np.pi*nby / lambdaz * np.array([pixel_y*np.sin(inplane)*np.sin(outofplane),
-pixel_y*np.cos(outofplane),
pixel_y*np.cos(inplane)*np.sin(outofplane)])
mymatrix[:, 2] = 2*np.pi*nbz / lambdaz * np.array([0,
tilt*distance*(1-np.cos(inplane)*np.cos(outofplane)),
tilt*distance*np.sin(outofplane)])
elif myrocking_angle == "inplane" and mygrazing_angle == 0:
print('rocking angle is mu')
# rocking mu angle anti-clockwise around y, mu below all other sample rotations
mymatrix[:, 0] = 2*np.pi*nbx / lambdaz * np.array([pixel_x*np.cos(inplane),
0,
-pixel_x*np.sin(inplane)])
mymatrix[:, 1] = 2*np.pi*nby / lambdaz * np.array([pixel_y*np.sin(inplane)*np.sin(outofplane),
-pixel_y*np.cos(outofplane),
pixel_y*np.cos(inplane)*np.sin(outofplane)])
mymatrix[:, 2] = 2*np.pi*nbz / lambdaz * np.array([tilt*distance*(1-np.cos(inplane)*np.cos(outofplane)),
0,
tilt*distance*np.sin(inplane)*np.cos(outofplane)])
else:
print('inplane rocking for phi not yet implemented for P10')
sys.exit()
if geometry == '34ID':
print('using APS 34ID geometry')
if myrocking_angle == "outofplane":
print('rocking angle is tilt')
# rocking tilt angle anti-clockwise around x (th does not matter, above tilt)
mymatrix[:, 0] = 2*np.pi*nbx / lambdaz * np.array([pixel_x*np.cos(inplane),
0,
-pixel_x*np.sin(inplane)])
mymatrix[:, 1] = 2*np.pi*nby / lambdaz * np.array([pixel_y*np.sin(inplane)*np.sin(outofplane),
-pixel_y*np.cos(outofplane),
pixel_y*np.cos(inplane)*np.sin(outofplane)])
mymatrix[:, 2] = 2*np.pi*nbz / lambdaz * np.array([0,
-tilt*distance*(1-np.cos(inplane)*np.cos(outofplane)),
-tilt*distance*np.sin(outofplane)])
elif myrocking_angle == "inplane" and mygrazing_angle != 0:
print('rocking angle is th, with tilt non zero')
# rocking th angle anti-clockwise around y, incident angle is non zero
mymatrix[:, 0] = 2*np.pi*nbx / lambdaz * np.array([pixel_x*np.cos(inplane),
0,
-pixel_x*np.sin(inplane)])
mymatrix[:, 1] = 2*np.pi*nby / lambdaz * np.array([pixel_y*np.sin(inplane)*np.sin(outofplane),
-pixel_y*np.cos(outofplane),
pixel_y*np.cos(inplane)*np.sin(outofplane)])
mymatrix[:, 2] = 2*np.pi*nbz / lambdaz * tilt * distance * \
np.array([(np.sin(mygrazing_angle)*np.sin(outofplane)+
np.cos(mygrazing_angle)*(1-np.cos(inplane)*np.cos(outofplane))),
-np.sin(mygrazing_angle)*np.sin(inplane)*np.sin(outofplane),
np.cos(mygrazing_angle)*np.sin(inplane)*np.cos(outofplane)])
elif myrocking_angle == "inplane" and mygrazing_angle == 0:
print('rocking angle is th, tilt=0')
# rocking th angle anti-clockwise around y, assuming incident angle is zero (th above tilt)
mymatrix[:, 0] = 2*np.pi*nbx / lambdaz * np.array([pixel_x*np.cos(inplane),
0,
-pixel_x*np.sin(inplane)])
mymatrix[:, 1] = 2*np.pi*nby / lambdaz * np.array([pixel_y*np.sin(inplane)*np.sin(outofplane),
-pixel_y*np.cos(outofplane),
pixel_y*np.cos(inplane)*np.sin(outofplane)])
mymatrix[:, 2] = 2*np.pi*nbz / lambdaz * np.array([tilt*distance*(1-np.cos(inplane)*np.cos(outofplane)),
0,
tilt*distance*np.sin(inplane)*np.cos(outofplane)])
if geometry == 'SIXS':
print('using SIXS geometry')
if rocking_angle == "inplane" and mygrazing_angle != 0:
print('rocking angle is mu, with beta non zero')
# rocking mu angle anti-clockwise around y
mymatrix[:, 0] = 2 * np.pi * nbx / lambdaz * pixel_x * np.array([np.cos(inplane),
-np.sin(mygrazing_angle)*np.sin(inplane),
-np.cos(mygrazing_angle)*np.sin(inplane)])
mymatrix[:, 1] = 2 * np.pi * nby /\
lambdaz*pixel_y*np.array([np.sin(inplane)*np.sin(outofplane),
(np.sin(mygrazing_angle)*np.cos(inplane)*np.sin(outofplane)
- np.cos(mygrazing_angle)*np.cos(outofplane)),
(np.cos(mygrazing_angle)*np.cos(inplane)*np.sin(outofplane)
+ np.sin(mygrazing_angle)*np.cos(outofplane))])
mymatrix[:, 2] = 2*np.pi*nbz / lambdaz * tilt * distance\
* np.array([np.cos(mygrazing_angle)-np.cos(inplane)*np.cos(outofplane),
np.sin(mygrazing_angle)*np.sin(inplane)*np.cos(outofplane),
np.cos(mygrazing_angle)*np.sin(inplane)*np.cos(outofplane)])
elif myrocking_angle == "inplane" and mygrazing_angle == 0:
print('rocking angle is mu, beta=0')
# rocking th angle anti-clockwise around y, assuming incident angle is zero (th above tilt)
mymatrix[:, 0] = 2*np.pi*nbx / lambdaz * np.array([pixel_x*np.cos(inplane),
0,
-pixel_x*np.sin(inplane)])
mymatrix[:, 1] = 2*np.pi*nby / lambdaz * np.array([pixel_y*np.sin(inplane)*np.sin(outofplane),
-pixel_y*np.cos(outofplane),
pixel_y*np.cos(inplane)*np.sin(outofplane)])
mymatrix[:, 2] = 2*np.pi*nbz / lambdaz * np.array([tilt*distance*(1-np.cos(inplane)*np.cos(outofplane)),
0,
tilt*distance*np.sin(inplane)*np.cos(outofplane)])
if geometry == 'CRISTAL':
print('using CRISTAL geometry')
if myrocking_angle == "outofplane":
print('rocking angle is komega')
# rocking tilt angle clockwise around x
mymatrix[:, 0] = 2*np.pi*nbx / lambdaz * np.array([pixel_x*np.cos(inplane),
0,
-pixel_x*np.sin(inplane)])
mymatrix[:, 1] = 2*np.pi*nby / lambdaz * np.array([pixel_y*np.sin(inplane)*np.sin(outofplane),
-pixel_y*np.cos(outofplane),
pixel_y*np.cos(inplane)*np.sin(outofplane)])
mymatrix[:, 2] = 2*np.pi*nbz / lambdaz * np.array([0,
tilt*distance*(1-np.cos(inplane)*np.cos(outofplane)),
tilt*distance*np.sin(outofplane)])
transfer_matrix = 2*np.pi * np.linalg.inv(mymatrix).transpose() # same as Matlab checked JCR
out_x = transfer_matrix[0, 0] * mygrid[2] + transfer_matrix[0, 1] * mygrid[1] + transfer_matrix[0, 2] * mygrid[0]
out_y = transfer_matrix[1, 0] * mygrid[2] + transfer_matrix[1, 1] * mygrid[1] + transfer_matrix[1, 2] * mygrid[0]
out_z = transfer_matrix[2, 0] * mygrid[2] + transfer_matrix[2, 1] * mygrid[1] + transfer_matrix[2, 2] * mygrid[0]
return out_z, out_y, out_x, transfer_matrix
def rotate_crystal(myobj, axis_to_align, reference_axis, debugging=0):
"""
rotate myobj to align axis_to_align onto reference_axis
:param myobj: 3d real array to be rotated
:param axis_to_align: the axis of myobj (vector q) x y z
:param reference_axis: will align axis_to_align onto this x y z
:param debugging: to plot myobj before and after rotation
:return: rotated myobj
"""
nbz, nby, nbx = myobj.shape
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(myobj[:, :, nbx // 2], vmin=0)
plt.colorbar()
plt.axis('scaled')
plt.title("Middle slice in YZ before rotating")
plt.subplot(2, 2, 2)
plt.imshow(myobj[:, nby // 2, :], vmin=0)
plt.colorbar()
plt.title("Middle slice in XZ before rotating")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(myobj[nbz // 2, :, :], vmin=0)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Middle slice in XY before rotating")
plt.axis('scaled')
plt.pause(0.1)
v = np.cross(axis_to_align, reference_axis)
skew_sym_matrix = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]])
my_rotation_matrix = np.identity(3) + skew_sym_matrix + np.dot(skew_sym_matrix, skew_sym_matrix) /\
(1+np.dot(axis_to_align, reference_axis))
transfer_matrix = my_rotation_matrix.transpose()
old_z = np.arange(-nbz // 2, nbz // 2, 1)
old_y = np.arange(-nby // 2, nby // 2, 1)
old_x = np.arange(-nbx // 2, nbx // 2, 1)
myz, myy, myx = np.meshgrid(old_z, old_y, old_x, indexing='ij')
# new_x = transfer_matrix[0, 0] * myx + transfer_matrix[0, 1] * myy + transfer_matrix[0, 2] * myz
# new_y = transfer_matrix[1, 0] * myx + transfer_matrix[1, 1] * myy + transfer_matrix[1, 2] * myz
# new_z = transfer_matrix[2, 0] * myx + transfer_matrix[2, 1] * myy + transfer_matrix[2, 2] * myz
new_x = transfer_matrix[0, 0] * myx + transfer_matrix[0, 1] * myy + transfer_matrix[0, 2] * myz
new_y = transfer_matrix[1, 0] * myx + transfer_matrix[1, 1] * myy + transfer_matrix[1, 2] * myz
new_z = transfer_matrix[2, 0] * myx + transfer_matrix[2, 1] * myy + transfer_matrix[2, 2] * myz
del myx, myy, myz
rgi = RegularGridInterpolator((old_z, old_y, old_x), myobj, method='linear', bounds_error=False, fill_value=0)
myobj = rgi(np.concatenate((new_z.reshape((1, new_z.size)), new_y.reshape((1, new_z.size)),
new_x.reshape((1, new_z.size)))).transpose())
myobj = myobj.reshape((nbz, nby, nbx)).astype(myobj.dtype)
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(myobj[:, :, nbx // 2], vmin=0)
plt.colorbar()
plt.axis('scaled')
plt.title("Middle slice in YZ after rotating")
plt.subplot(2, 2, 2)
plt.imshow(myobj[:, nby // 2, :], vmin=0)
plt.colorbar()
plt.title("Middle slice in XZ after rotating")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(myobj[nbz // 2, :, :], vmin=0)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Middle slice in XY after rotating")
plt.axis('scaled')
plt.pause(0.1)
return myobj
def crop_pad(myobj, myshape, debugging=0):
"""
will crop or pad my obj depending on myshape
:param myobj: 3d complex array to be padded
:param myshape: list of desired output shape [z, y, x]
:param debugging: to plot myobj before and after rotation
:return: myobj padded with zeros
"""
nbz, nby, nbx = myobj.shape
newz, newy, newx = myshape
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(abs(myobj)[:, :, nbx // 2], vmin=0, vmax=1)
plt.colorbar()
plt.axis('scaled')
plt.title("Middle slice in YZ before padding")
plt.subplot(2, 2, 2)
plt.imshow(abs(myobj)[:, nby // 2, :], vmin=0, vmax=1)
plt.colorbar()
plt.title("Middle slice in XZ before padding")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(abs(myobj)[nbz // 2, :, :], vmin=0, vmax=1)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Middle slice in XY before padding")
plt.axis('scaled')
plt.pause(0.1)
# z
if newz >= nbz: # pad
temp_z = np.zeros((myshape[0], nby, nbx), dtype=myobj.dtype)
temp_z[(newz - nbz) // 2:(newz + nbz) // 2, :, :] = myobj
else: # crop
temp_z = myobj[(nbz - newz) // 2:(newz + nbz) // 2, :, :]
# y
if newy >= nby: # pad
temp_y = np.zeros((newz, newy, nbx), dtype=myobj.dtype)
temp_y[:, (newy - nby) // 2:(newy + nby) // 2, :] = temp_z
else: # crop
temp_y = temp_z[:, (nby - newy) // 2:(newy + nby) // 2, :]
# x
if newx >= nbx: # pad
newobj = np.zeros((newz, newy, newx), dtype=myobj.dtype)
newobj[:, :, (newx - nbx) // 2:(newx + nbx) // 2] = temp_y
else: # crop
newobj = temp_y[:, :, (nbx - newx) // 2:(newx + nbx) // 2]
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(abs(newobj)[:, :, newx // 2], vmin=0, vmax=1)
plt.colorbar()
plt.axis('scaled')
plt.title("Middle slice in YZ after padding")
plt.subplot(2, 2, 2)
plt.imshow(abs(newobj)[:, newy // 2, :], vmin=0, vmax=1)
plt.colorbar()
plt.title("Middle slice in XZ after padding")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(abs(newobj)[newz // 2, :, :], vmin=0, vmax=1)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Middle slice in XY after padding")
plt.axis('scaled')
plt.pause(0.1)
return newobj
def center_max(myarray, debugging=0):
""""
:param myarray: array to be centered based on the max value
:param debugging: 1 to show plots
:return centered array
"""
global xrange, yrange, zrange
nbz, nby, nbx = myarray.shape
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(abs(myarray).sum(axis=2)[nbz // 2 - zrange:nbz // 2 + zrange,
nby // 2 - yrange:nby // 2 + yrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in YZ before Max centering")
plt.subplot(2, 2, 2)
plt.imshow(abs(myarray).sum(axis=1)[nbz // 2 - zrange:nbz // 2 + zrange,
nbx // 2 - xrange:nbx // 2 + xrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XZ before Max centering")
plt.subplot(2, 2, 3)
plt.imshow(abs(myarray).sum(axis=0)[nby // 2 - yrange:nby // 2 + yrange,
nbx // 2 - xrange:nbx // 2 + xrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XY before Max centering")
plt.pause(0.1)
piz, piy, pix = np.unravel_index(abs(myarray).argmax(), myarray.shape)
print("Max at (z, y, x): (", piz, ',', piy, ',', pix, ')')
offset_z = int(np.rint(nbz / 2.0 - piz))
offset_y = int(np.rint(nby / 2.0 - piy))
offset_x = int(np.rint(nbx / 2.0 - pix))
print("Max offset: (", offset_z, ',', offset_y, ',', offset_x, ') pixels')
myarray = np.roll(myarray, (offset_z, offset_y, offset_x), axis=(0, 1, 2))
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(abs(myarray).sum(axis=2)[nbz // 2 - zrange:nbz // 2 + zrange,
nby // 2 - yrange:nby // 2 + yrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in YZ after Max centering")
plt.subplot(2, 2, 2)
plt.imshow(abs(myarray).sum(axis=1)[nbz // 2 - zrange:nbz // 2 + zrange,
nbx // 2 - xrange:nbx // 2 + xrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XZ after Max centering")
plt.subplot(2, 2, 3)
plt.imshow(abs(myarray).sum(axis=0)[nby // 2 - yrange:nby // 2 + yrange,
nbx // 2 - xrange:nbx // 2 + xrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XY after Max centering")
plt.pause(0.1)
return myarray
def center_com(myarray, debugging=0):
""""
:param myarray: array to be centered based on the center of mass value
:param debugging: 1 to show plots
:return centered array
"""
global xrange, yrange, zrange
nbz, nby, nbx = myarray.shape
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(abs(myarray).sum(axis=2)[nbz // 2 - zrange:nbz // 2 + zrange,
nby // 2 - yrange:nby // 2 + yrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in YZ before COM centering")
plt.subplot(2, 2, 2)
plt.imshow(abs(myarray).sum(axis=1)[nbz // 2 - zrange:nbz // 2 + zrange,
nbx // 2 - xrange:nbx // 2 + xrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XZ before COM centering")
plt.subplot(2, 2, 3)
plt.imshow(abs(myarray).sum(axis=0)[nby // 2 - yrange:nby // 2 + yrange,
nbx // 2 - xrange:nbx // 2 + xrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XY before COM centering")
plt.pause(0.1)
piz, piy, pix = center_of_mass(abs(myarray))
print("center of mass at (z, y, x): (", str('{:.2f}'.format(piz)), ',',
str('{:.2f}'.format(piy)), ',', str('{:.2f}'.format(pix)), ')')
offset_z = int(np.rint(nbz / 2.0 - piz))
offset_y = int(np.rint(nby / 2.0 - piy))
offset_x = int(np.rint(nbx / 2.0 - pix))
print("center of mass offset: (", offset_z, ',', offset_y, ',', offset_x, ') pixels')
myarray = np.roll(myarray, (offset_z, offset_y, offset_x), axis=(0, 1, 2))
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(abs(myarray).sum(axis=2)[nbz // 2 - zrange:nbz // 2 + zrange,
nby // 2 - yrange:nby // 2 + yrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in YZ after COM centering")
plt.subplot(2, 2, 2)
plt.imshow(abs(myarray).sum(axis=1)[nbz // 2 - zrange:nbz // 2 + zrange,
nbx // 2 - xrange:nbx // 2 + xrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XZ after COM centering")
plt.subplot(2, 2, 3)
plt.imshow(abs(myarray).sum(axis=0)[nby // 2 - yrange:nby // 2 + yrange,
nbx // 2 - xrange:nbx // 2 + xrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XY after COM centering")
plt.pause(0.1)
return myarray
def align_obj(myavg_obj, myref_obj, myobj, threshold, debugging=0, aligning_option='dft'):
"""
align_obj: align two reconstructions by interpolating it based on COM offset, if their cross-correlation is > 0.95
:param myavg_obj: average complex density
:param myref_obj: reference object
:param myobj: complex density to average with
:param threshold: for support definition, typically 0.25
:param debugging: 1 to show plots
:param aligning_option: 'com' for center of mass, 'dft' for dft registration and subpixel shift
:return: the average complex density
"""
global xrange, yrange, zrange
nbz, nby, nbx = myobj.shape
avg_flag = 0
# myref_obj[abs(myref_obj) < abs(myref_obj).max() / 10] = 0
# myobj[abs(myobj) < abs(myobj).max() / 10] = 0
if myavg_obj.sum() == 0:
myavg_obj = myref_obj
if debugging == 0:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(abs(myavg_obj).sum(axis=2)[nbz // 2 - zrange:nbz // 2 + zrange,
nby
// 2 - yrange:nby // 2 + yrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in YZ of reference object")
plt.subplot(2, 2, 2)
plt.imshow(abs(myavg_obj).sum(axis=1)[nbz // 2 - zrange:nbz // 2 + zrange,
nbx // 2 - xrange:nbx // 2 + xrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XZ of reference object")
plt.subplot(2, 2, 3)
plt.imshow(abs(myavg_obj).sum(axis=0)[nby // 2 - yrange:nby // 2 + yrange,
nbx // 2 - xrange:nbx // 2 + xrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XY of reference object")
plt.pause(0.2)
else:
myref_support = np.zeros((nbz, nby, nbx))
myref_support[abs(myavg_obj) > threshold*abs(myavg_obj).max()] = 1
my_support = np.zeros((nbz, nby, nbx))
my_support[abs(myobj) > threshold * abs(myobj).max()] = 1
avg_piz, avg_piy, avg_pix = center_of_mass(abs(myref_support))
piz, piy, pix = center_of_mass(abs(my_support))
offset_z = avg_piz - piz
offset_y = avg_piy - piy
offset_x = avg_pix - pix
print("center of mass offset with reference object: (", str('{:.2f}'.format(offset_z)), ',',
str('{:.2f}'.format(offset_y)), ',', str('{:.2f}'.format(offset_x)), ') pixels')
if aligning_option is 'com':
# re-sample data on a new grid based on COM shift of support
old_z = np.arange(-nbz // 2, nbz // 2)
old_y = np.arange(-nby // 2, nby // 2)
old_x = np.arange(-nbx // 2, nbx // 2)
myz, myy, myx = np.meshgrid(old_z, old_y, old_x, indexing='ij')
new_z = myz + offset_z
new_y = myy + offset_y
new_x = myx + offset_x
del myx, myy, myz
rgi = RegularGridInterpolator((old_z, old_y, old_x), myobj, method='linear', bounds_error=False,
fill_value=0)
new_obj = rgi(np.concatenate((new_z.reshape((1, new_z.size)), new_y.reshape((1, new_z.size)),
new_x.reshape((1, new_z.size)))).transpose())
new_obj = new_obj.reshape((nbz, nby, nbx)).astype(myobj.dtype)
else:
# dft registration and subpixel shift (see Matlab code)
shiftz, shifty, shiftx = reg.getimageregistration(abs(myref_obj), abs(myobj), precision=1000)
new_obj = reg.subpixel_shift(myobj, shiftz, shifty, shiftx) # keep the complex output here
print("Shift calculated from dft registration: (", str('{:.2f}'.format(shiftz)), ',',
str('{:.2f}'.format(shifty)), ',', str('{:.2f}'.format(shiftx)), ') pixels')
new_obj = new_obj / abs(new_obj).max() # renormalize
correlation = pearsonr(np.ndarray.flatten(abs(myref_obj[np.nonzero(myref_support)])),
np.ndarray.flatten(abs(new_obj[np.nonzero(myref_support)])))[0]
# np_corr = np.correlate(np.ndarray.flatten(abs(myref_obj)), np.ndarray.flatten(abs(new_obj))) /\
# np.correlate(np.ndarray.flatten(abs(myref_obj)), np.ndarray.flatten(abs(myref_obj)))
# print('numpy cross-correlation=', np_corr[0])
if correlation < correlation_threshold:
print('pearson cross-correlation=', correlation, 'too low, skip this reconstruction')
else:
print('pearson-correlation=', correlation, ', average with this reconstruction')
if debugging == 0:
myfig = plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(abs(new_obj).sum(axis=2)[nbz // 2 - zrange:nbz // 2 + zrange,
nby // 2 - yrange:nby // 2 + yrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in YZ of aligned candidate")
plt.subplot(2, 2, 2)
plt.imshow(abs(new_obj).sum(axis=1)[nbz // 2 - zrange:nbz // 2 + zrange,
nbx // 2 - xrange:nbx // 2 + xrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XZ of aligned candidate")
plt.subplot(2, 2, 3)
plt.imshow(abs(new_obj).sum(axis=0)[nby // 2 - yrange:nby // 2 + yrange,
nbx // 2 - xrange:nbx // 2 + xrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XY of aligned candidate")
myfig.text(0.60, 0.30, "pearson-correlation = " + str('{:.4f}'.format(correlation)), size=20)
plt.pause(0.2)
myavg_obj = myavg_obj + new_obj
avg_flag = 1
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(abs(myavg_obj).sum(axis=2)[nbz // 2 - zrange:nbz // 2 + zrange,
nby // 2 - yrange:nby // 2 + yrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in YZ after averaging")
plt.subplot(2, 2, 2)
plt.imshow(abs(myavg_obj).sum(axis=1)[nbz // 2 - zrange:nbz // 2 + zrange,
nbx // 2 - xrange:nbx // 2 + xrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XZ after averaging")
plt.subplot(2, 2, 3)
plt.imshow(abs(myavg_obj).sum(axis=0)[nby // 2 - yrange:nby // 2 + yrange,
nbx // 2 - xrange:nbx // 2 + xrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XY after averaging")
plt.pause(0.1)
return myavg_obj, avg_flag
def plane_angle(ref_plane, plane):
"""
Calculate the angle between two crystallographic planes in cubic materials
:param ref_plane: measured reflection
:param plane: plane for which angle should be calculated
:return: the angle in degrees
"""
if np.array_equal(ref_plane, plane):
my_angle = 0.0
else:
my_angle = 180/np.pi*np.arccos(sum(np.multiply(ref_plane, plane)) /
(np.linalg.norm(ref_plane)*np.linalg.norm(plane)))
return my_angle
def wrap(myphase):
"""
wrap the phase in [-pi pi] interval
:param myphase:
:return:
"""
myphase = (myphase + np.pi) % (2 * np.pi) - np.pi
return myphase
def bragg_temperature(spacing, my_reflection, spacing_ref=None, temperature_ref=None, use_q=0, material=None):
"""
Calculate the temperature from Bragg peak position
:param spacing: q or planar distance, in inverse angstroms or angstroms
:param my_reflection: measured reflection, e.g. np.array([1, 1, 1])
:param spacing_ref: reference spacing at known temperature (include substrate-induced strain)
:param temperature_ref: in K, known temperature for the reference spacing
:param use_q: use q (set to 1) or planar distance (set to 0)
:param material: at the moment only 'Pt'
:return: calculated temprature
"""
if material == 'Pt':
# reference values for Pt: temperature in K, thermal expansion x 10^6 in 1/K, lattice parameter in angstroms
expansion_data = np.array([[100, 6.77, 3.9173], [110, 7.10, 3.9176], [120, 7.37, 3.9179], [130, 7.59, 3.9182],
[140, 7.78, 3.9185], [150, 7.93, 3.9188], [160, 8.07, 3.9191], [180, 8.29, 3.9198],
[200, 8.46, 3.9204], [220, 8.59, 3.9211], [240, 8.70, 3.9218], [260, 8.80, 3.9224],
[280, 8.89, 3.9231], [293.15, 8.93, 3.9236], [300, 8.95, 3.9238], [400, 9.25, 3.9274],
[500, 9.48, 3.9311], [600, 9.71, 3.9349], [700, 9.94, 3.9387], [800, 10.19, 3.9427],
[900, 10.47, 3.9468], [1000, 10.77, 3.9510], [1100, 11.10, 3.9553],
[1200, 11.43, 3.9597]])
if spacing_ref is None:
print('Using the reference spacing of Platinum')
spacing_ref = 3.9236 / np.linalg.norm(my_reflection) # angstroms
if temperature_ref is None:
temperature_ref = 293.15 # K
else:
return 0
if use_q == 1:
spacing = 2 * np.pi / spacing # go back to distance
spacing_ref = 2 * np.pi / spacing_ref # go back to distance
spacing = spacing * np.linalg.norm(my_reflection) # go back to lattice constant
spacing_ref = spacing_ref * np.linalg.norm(my_reflection) # go back to lattice constant
print('Reference spacing at', temperature_ref, 'K =', str('{:.4f}'.format(spacing_ref)), 'angstroms')
print('Spacing =', str('{:.4f}'.format(spacing)), 'angstroms using reflection', my_reflection)
# fit the experimental spacing with non corrected platinum curve
myfit = np.poly1d(np.polyfit(expansion_data[:, 2], expansion_data[:, 0], 3))
print('Temperature without offset correction=', int(myfit(spacing) - 273.15), 'C')
# find offset for platinum reference curve
myfit = np.poly1d(np.polyfit(expansion_data[:, 0], expansion_data[:, 2], 3))
spacing_offset = myfit(temperature_ref) - spacing_ref # T in K, spacing in angstroms
print('Spacing offset =', str('{:.4f}'.format(spacing_offset)), 'angstroms')
# correct the platinum reference curve for the offset
platinum_offset = np.copy(expansion_data)
platinum_offset[:, 2] = platinum_offset[:, 2] - spacing_offset
myfit = np.poly1d(np.polyfit(platinum_offset[:, 2], platinum_offset[:, 0], 3))
mytemp = int(myfit(spacing) - 273.15)
print('Temperature with offset correction=', mytemp, 'C')
return mytemp
def calc_coordination(mysupport, mykernel=np.ones((3, 3, 3)), debugging=0):
"""
calculate the coordination number of voxels in a support
:param mysupport:
:param mykernel: kernel used for convolution with the support
:param debugging: 1 to plot
:return:
"""
nbz, nby, nbx = mysupport.shape
mycoord = np.rint(convolve(mysupport, mykernel, mode='same'))
mycoord = mycoord.astype(int)
if debugging == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(mycoord[:, :, nbx // 2])
plt.colorbar()
plt.axis('scaled')
plt.title("Coordination matrix in middle slice in YZ")
plt.subplot(2, 2, 2)
plt.imshow(mycoord[:, nby // 2, :])
plt.colorbar()
plt.title("Coordination matrix in middle slice in XZ")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(mycoord[nbz // 2, :, :])
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Coordination matrix in middle slice in XY")
plt.axis('scaled')
plt.pause(0.1)
return mycoord
def regrid(myobj, voxel_zyx, voxel):
"""
Fonction to interpolate real space data on a grid with same voxel size
:param myobj:
:param voxel_zyx: tuple of voxel sizes in z, y, and x (nexus convention)
:param voxel: voxel size used for the interpolation
:return: myobj interpolated oa a grid with cubic voxels
"""
nbz, nby, nbx = myobj.shape
dz_realspace, dy_realspace, dx_realspace = voxel_zyx
old_z = np.arange(-nbz // 2, nbz // 2, 1) * dz_realspace
old_y = np.arange(-nby // 2, nby // 2, 1) * dy_realspace
old_x = np.arange(-nbx // 2, nbx // 2, 1) * dx_realspace
new_z, new_y, new_x = np.meshgrid(old_z * voxel / dz_realspace,
old_y * voxel / dy_realspace,
old_x * voxel / dx_realspace,
indexing='ij')
rgi = RegularGridInterpolator((old_z, old_y, old_x), myobj, method='linear', bounds_error=False, fill_value=0)
myobj = rgi(np.concatenate((new_z.reshape((1, new_z.size)), new_y.reshape((1, new_y.size)),
new_x.reshape((1, new_x.size)))).transpose())
myobj = myobj.reshape((nbz, nby, nbx)).astype(myobj.dtype)
return myobj
# define a colormap
cdict = {'red': ((0.0, 1.0, 1.0),
(0.11, 0.0, 0.0),
(0.36, 0.0, 0.0),
(0.62, 1.0, 1.0),
(0.87, 1.0, 1.0),
(1.0, 0.0, 0.0)),
'green': ((0.0, 1.0, 1.0),
(0.11, 0.0, 0.0),
(0.36, 1.0, 1.0),
(0.62, 1.0, 1.0),
(0.87, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 1.0, 1.0),
(0.11, 1.0, 1.0),
(0.36, 1.0, 1.0),
(0.62, 0.0, 0.0),
(0.87, 0.0, 0.0),
(1.0, 0.0, 0.0))}
my_cmap = LinearSegmentedColormap('my_colormap', cdict, 256)
logger = logging.getLogger()
################################################
# preload data
################################################
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilenames(initialdir=datadir,
filetypes=[("NPZ", "*.npz"),
("NPY", "*.npy"), ("CXI", "*.cxi"), ("HDF5", "*.h5")])
nbfiles = len(file_path)
plt.ion()
if file_path[0].lower().endswith('.npz'):
ext = '.npz'
npzfile = np.load(file_path[0])
obj = npzfile['obj']
elif file_path[0].lower().endswith('.npy'):
ext = '.npy'
obj = np.load(file_path[0])
elif file_path[0].lower().endswith('.cxi'):
ext = '.cxi'
h5file = h5py.File(file_path[0], 'r')
group_key = list(h5file.keys())[1]
subgroup_key = list(h5file[group_key])
obj = h5file['/' + group_key + '/' + subgroup_key[0] + '/data'].value
elif file_path[0].lower().endswith('.h5'):
ext = '.h5'
h5file = h5py.File(file_path[0], 'r')
group_key = list(h5file.keys())[0]
subgroup_key = list(h5file[group_key])
obj = h5file['/' + group_key + '/' + subgroup_key[0] + '/data'].value[0]
comment = comment + "_1stmode"
else:
sys.exit('wrong file format')
if len(original_size) != 0:
print("Original FFT window size: ", original_size)
print("Padding back to original FFT size")
obj = crop_pad(myobj=obj, myshape=original_size, debugging=0)
else:
original_size = obj.shape
nz, ny, nx = obj.shape
print("Initial data size: (", nz, ',', ny, ',', nx, ')')
################################################
# define range for orthogonalization and plotting - speed up calculations
################################################
support = np.zeros((nz, ny, nx))
support[abs(obj) > 0.15 * abs(obj).max()] = 1
del obj
z, y, x = np.meshgrid(np.arange(0, nz, 1), np.arange(0, ny, 1), np.arange(0, nx, 1),
indexing='ij')
z = z * support
# min_z = int(np.min(z[np.nonzero(z)]))
min_z = min(int(np.min(z[np.nonzero(z)])), nz-int(np.max(z[np.nonzero(z)])))
del z
y = y * support
# min_y = int(np.min(y[np.nonzero(y)]))
min_y = min(int(np.min(y[np.nonzero(y)])), ny-int(np.max(y[np.nonzero(y)])))
del y
x = x * support
# min_x = int(np.min(x[np.nonzero(x)]))
min_x = min(int(np.min(x[np.nonzero(x)])), nx-int(np.max(x[np.nonzero(x)])))
del x
zrange = (nz // 2 - min_z) + plot_width[0]
yrange = (ny // 2 - min_y) + plot_width[1]
xrange = (nx // 2 - min_x) + plot_width[2]
flag_pad_z = 0
flag_pad_y = 0
flag_pad_x = 0
if zrange * 2 > nz:
zrange = nz // 2
flag_pad_z = 1
if yrange * 2 > ny:
yrange = ny // 2
flag_pad_y = 1
if xrange * 2 > nx:
xrange = nx // 2
flag_pad_x = 1
if keep_size == 1:
zrange = nz // 2
yrange = ny // 2
xrange = nx // 2
numz = zrange * 2
numy = yrange * 2
numx = xrange * 2
print("Data size after crop: (", numz, ',', numy, ',', numx, ')')
################################################
# find the best reconstruction from the list, based on mean amplitude and variance
################################################
if nbfiles > 1:
print('Trying to find the best reconstruction')
quality_array = np.ones((nbfiles, 4)) # 1/mean_amp, variance(amp), variance(amp)/mean_amp, 1/volume
for ii in range(nbfiles):
if ext == '.npz':
npzfile = np.load(file_path[ii])
obj = npzfile['obj']
elif ext == '.npy':
obj = np.load(file_path[ii])
elif ext == '.cxi':
h5file = h5py.File(file_path[ii], 'r')
group_key = list(h5file.keys())[1]
subgroup_key = list(h5file[group_key])
obj = h5file['/' + group_key + '/' + subgroup_key[0] + '/data'].value
elif file_path[0].lower().endswith('.h5'): # modes.h5
ext = '.h5'
h5file = h5py.File(file_path[0], 'r')
group_key = list(h5file.keys())[0]
subgroup_key = list(h5file[group_key])
obj = h5file['/' + group_key + '/' + subgroup_key[0] + '/data'].value[0]
else:
sys.exit('Wrong file format')
print('Opening ', file_path[ii])
if len(original_size) != 0:
obj = crop_pad(myobj=obj, myshape=original_size, debugging=0)
# centering of array
if centering == 0:
obj = center_max(obj)
# shift based on max value, required if it spans across the edge of the array before COM
elif centering == 1:
obj = center_com(obj)
elif centering == 2:
obj = center_max(obj)
obj = center_com(obj)
# use only the range of interest
sz, sy, sx = obj.shape
if sz < numz or sy < numy or sx < numx:
print("Did you forget to fill the input parameter 'original_size'?")
sys.exit("array size not compatible")
obj = obj[sz // 2 - zrange:sz // 2 + zrange, sy // 2 - yrange:sy // 2 + yrange,
sx // 2 - xrange:sx // 2 + xrange]
obj_amp = abs(obj) / abs(obj).max()
temp_support = np.zeros(obj_amp.shape)
temp_support[obj_amp > threshold_plot] = 1 # only for plotting
quality_array[ii, 0] = 1 / obj_amp[obj_amp > threshold_plot].mean() # 1/mean(amp)
quality_array[ii, 1] = np.var(obj_amp[obj_amp > threshold_plot]) # var(amp)
quality_array[ii, 2] = quality_array[ii, 0] * quality_array[ii, 1] # var(amp)/mean(amp) index of dispersion
quality_array[ii, 3] = 1 / temp_support.sum() # 1/volume(support)
# will order reconstructions by minimizing the quality factor
if sort_by is 'mean_amplitude': # sort by quality_array[:, 0] first
sorted_obj = np.lexsort((quality_array[:, 3], quality_array[:, 2], quality_array[:, 1], quality_array[:, 0]))
print('sorting by mean_amplitude')
elif sort_by is 'variance': # sort by quality_array[:, 1] first
sorted_obj = np.lexsort((quality_array[:, 0], quality_array[:, 3], quality_array[:, 2], quality_array[:, 1]))
print('sorting by variance')
elif sort_by is 'variance/mean': # sort by quality_array[:, 2] first
sorted_obj = np.lexsort((quality_array[:, 1], quality_array[:, 0], quality_array[:, 3], quality_array[:, 2]))
print('sorting by index of dispersion')
elif sort_by is 'volume': # sort by quality_array[:, 3] first
sorted_obj = np.lexsort((quality_array[:, 2], quality_array[:, 1], quality_array[:, 0], quality_array[:, 3]))
print('sorting by volume')
else: # default
sorted_obj = np.lexsort((quality_array[:, 3], quality_array[:, 2], quality_array[:, 1], quality_array[:, 0]))
print('sorting by mean_amplitude')
print('\nquality_array')
print(quality_array)
print("sorted list", sorted_obj)
del temp_support
gc.collect()
else:
sorted_obj = [0]
print('\n')
################################################
# load reconstructions and average it
################################################
avg_obj = np.zeros((numz, numy, numx))
ref_obj = np.zeros((numz, numy, numx))
avg_counter = 1
print('Averaging using', nbfiles, 'candidate reconstructions')
for ii in sorted_obj:
if ext == '.npz':
npzfile = np.load(file_path[ii])
obj = npzfile['obj']
elif ext == '.npy':
obj = np.load(file_path[ii])
elif ext == '.cxi':
h5file = h5py.File(file_path[ii], 'r')
group_key = list(h5file.keys())[1]
subgroup_key = list(h5file[group_key])
obj = h5file['/'+group_key+'/'+subgroup_key[0]+'/data'].value
elif file_path[0].lower().endswith('.h5'): # modes.h5
ext = '.h5'
h5file = h5py.File(file_path[0], 'r')
group_key = list(h5file.keys())[0]
subgroup_key = list(h5file[group_key])
obj = h5file['/' + group_key + '/' + subgroup_key[0] + '/data'].value[0]
centering = -1 # do not center, data is cropped just on support
else:
sys.exit('Wrong file format')
print('Opening ', file_path[ii])
if len(original_size) != 0:
obj = crop_pad(myobj=obj, myshape=original_size, debugging=0)
# use only the range of interest
sz, sy, sx = obj.shape
if sz < numz or sy < numy or sx < numx:
print("Did you forget to fill the input parameter 'original_size'?")
sys.exit("array size not compatible")
obj = obj[sz // 2 - zrange:sz // 2 + zrange, sy // 2 - yrange:sy // 2 + yrange, sx // 2 - xrange:sx // 2 + xrange]
# align with average reconstruction
if avg_obj.sum() == 0:
avg_obj = obj
if nbfiles > 1:
avg_obj, flag_avg = align_obj(avg_obj, ref_obj, obj, 0.25)
avg_counter = avg_counter + flag_avg
avg_obj = avg_obj / avg_counter
print('Average performed over ', avg_counter, 'reconstructions\n')
del obj, ref_obj
gc.collect()
##############################################
# check if padding is needed instead of cropping
##############################################
if keep_size == 0:
if flag_pad_z == 1:
zrange = (nz // 2 - min_z)*2 + plot_width[0]
if flag_pad_y == 1:
yrange = (ny // 2 - min_y)*2 + plot_width[1]
if flag_pad_x == 1:
xrange = (nx // 2 - min_x)*2 + plot_width[2]
avg_obj = crop_pad(avg_obj, [2*zrange, 2*yrange, 2*xrange], debugging=0)
numz = zrange * 2
numy = yrange * 2
numx = xrange * 2
print("Data size after pad: (", numz, ',', numy, ',', numx, ')')
############################################################
# phase offset removal (at COM value)
############################################################
amp = abs(avg_obj)
phase = np.angle(avg_obj)
del avg_obj
gc.collect()
if debug == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(phase[numz // 2 - zrange:numz // 2 + zrange, numy // 2 - yrange:numy // 2 + yrange, numx // 2],
cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("Phase at middle frame in YZ before offset removal")
plt.subplot(2, 2, 2)
plt.imshow(phase[numz // 2 - zrange:numz // 2 + zrange, numy // 2, numx // 2 - xrange:numx // 2 + xrange],
cmap=my_cmap)
plt.colorbar()
plt.title("Phase at middle frame in XZ before offset removal")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(phase[numz // 2, numy // 2 - yrange:numy // 2 + yrange, numx // 2 - xrange:numx // 2 + xrange],
cmap=my_cmap)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Phase at middle frame in XY before offset removal")
plt.axis('scaled')
plt.pause(0.1)
support = np.zeros(amp.shape)
support[amp > 0.25*amp.max()] = 1
zz, yy, xx = center_of_mass(support)
print("Mean phase:", phase[support == 1].mean(), "rad")
print("COM at (z, y, x): (", str('{:.2f}'.format(zz)), ',', str('{:.2f}'.format(yy)), ',',
str('{:.2f}'.format(xx)), ')')
print("Phase offset at COM(amp) of:", str('{:.2f}'.format(phase[int(zz), int(yy), int(xx)])), "rad")
phase = phase - phase[int(zz), int(yy), int(xx)]
if simu_flag == 1:
phase = phase + phase_offset
# phase = phase - phase[103, 79, 89] + 2.15
phase = wrap(phase)
if debug == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(phase[numz // 2 - zrange:numz // 2 + zrange, numy // 2 - yrange:numy // 2 + yrange, numx // 2],
cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("Phase at middle frame in YZ after offset removal")
plt.subplot(2, 2, 2)
plt.imshow(phase[numz // 2 - zrange:numz // 2 + zrange, numy // 2, numx // 2 - xrange:numx // 2 + xrange],
cmap=my_cmap)
plt.colorbar()
plt.title("Phase at middle frame in XZ after offset removal")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(phase[numz // 2, numy // 2 - yrange:numy // 2 + yrange, numx // 2 - xrange:numx // 2 + xrange],
cmap=my_cmap)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Phase at middle frame in XY after offset removal")
plt.axis('scaled')
plt.pause(0.1)
phase = phase - phase[support == 1].mean() #
del support
gc.collect()
phase = wrap(phase)
if debug == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(phase[numz // 2 - zrange:numz // 2 + zrange, numy // 2 - yrange:numy // 2 + yrange, numx // 2],
cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("Phase at middle frame in YZ after mean removal")
plt.subplot(2, 2, 2)
plt.imshow(phase[numz // 2 - zrange:numz // 2 + zrange, numy // 2, numx // 2 - xrange:numx // 2 + xrange],
cmap=my_cmap)
plt.colorbar()
plt.title("Phase at middle frame in XZ after mean removal")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(phase[numz // 2, numy // 2 - yrange:numy // 2 + yrange, numx // 2 - xrange:numx // 2 + xrange],
cmap=my_cmap)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Phase at middle frame in XY after mean removal")
plt.axis('scaled')
plt.pause(0.1)
############################################################
# average the phase over a window to reduce noise in strain plots or apodization
############################################################
phase = mean_filter(amp, phase, hwidth, threshold_plot, debugging=1)
comment = comment + "_avg" + str(2*hwidth+1)
if apodize_flag:
amp, phase = apodize(amp, phase, debugging=debug)
comment = comment + '_apodize'
avg_obj = amp * np.exp(1j * phase)
np.savez_compressed(datadir + 'S' + str(scan) + '_avg_obj_prtf' + comment, obj=avg_obj)
del amp, phase
gc.collect()
###########################################################
# centering of array
###########################################################
# centering of array
if centering == 0:
avg_obj = center_max(avg_obj)
# shift based on max value, required if it spans across the edge of the array before COM
elif centering == 1:
avg_obj = center_com(avg_obj)
elif centering == 2:
avg_obj = center_max(avg_obj)
avg_obj = center_com(avg_obj)
##############################################
# plot data and save support
##############################################
amp = abs(avg_obj)
if debug == 0:
# plot amp and phase
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(amp.sum(axis=2)[numz // 2 - zrange:numz // 2 + zrange, numy // 2 - yrange:numy // 2 + yrange],
cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in YZ before orthogonalization")
plt.subplot(2, 2, 2)
plt.imshow(amp.sum(axis=1)[numz // 2 - zrange:numz // 2 + zrange, numx // 2 - xrange:numx // 2 + xrange],
cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XZ before orthogonalization")
plt.subplot(2, 2, 3)
plt.imshow(amp.sum(axis=0)[numy // 2 - yrange:numy // 2 + yrange, numx // 2 - xrange:numx // 2 + xrange],
cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XY before orthogonalization")
phase = np.angle(avg_obj)
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(phase[numz // 2 - zrange:numz // 2 + zrange, numy // 2 - yrange:numy // 2 + yrange, numx // 2],
cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("Phase at middle frame in YZ before orthogonalization")
plt.subplot(2, 2, 2)
plt.imshow(phase[numz // 2 - zrange:numz // 2 + zrange, numy // 2, numx // 2 - xrange:numx // 2 + xrange],
cmap=my_cmap)
plt.colorbar()
plt.title("Phase at middle frame in XZ before orthogonalization")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(phase[numz // 2, numy // 2 - yrange:numy // 2 + yrange, numx // 2 - xrange:numx // 2 + xrange],
cmap=my_cmap)
plt.colorbar()
plt.title("Phase at middle frame in XY before orthogonalization")
plt.axis('scaled')
plt.pause(0.1)
del phase
gc.collect()
if save_support:
support = np.zeros((numz, numy, numx))
support[amp/amp.max() > 0.1] = 1 # use a low threshold because support will be cropped by shrinkwrap during phasing
np.savez_compressed(datadir + 'S' + str(scan) + '_support' + comment, obj=support)
del support
gc.collect()
if save_raw:
amp = abs(avg_obj)
np.savez_compressed(datadir + 'S' + str(scan) + '_raw_amp-phase' + comment, amp=amp, phase=np.angle(avg_obj))
wave = 12.398 * 1e-7 / en # wavelength in m
voxel_z = wave / (original_size[0] * abs(tilt_angle) * np.pi / 180) * 1e9 # in nm
voxel_y = wave * sdd / (original_size[1] * pixel_size) * 1e9 # in nm
voxel_x = wave * sdd / (original_size[2] * pixel_size) * 1e9 # in nm
# save raw amp & phase to VTK
# in VTK, x is downstream, y vertical, z inboard, thus need to flip the last axis
temp_array = np.copy(amp)
temp_array = temp_array / temp_array.max()
temp_array[temp_array < 0.01] = 0 # save disk space
AMP = np.transpose(np.flip(temp_array, 2)).reshape(temp_array.size)
data_array = numpy_support.numpy_to_vtk(AMP)
image_data = vtk.vtkImageData()
image_data.SetOrigin(0, 0, 0)
image_data.SetSpacing(voxel_z, voxel_y, voxel_x)
image_data.SetExtent(0, numz - 1, 0, numy - 1, 0, numx - 1)
pd = image_data.GetPointData()
pd.SetScalars(data_array)
pd.GetArray(0).SetName("amp")
temp_array = np.copy(np.angle(avg_obj))
temp_array[amp < 0.01 * amp.max()] = 0 # save disk space
PH = np.transpose(np.flip(temp_array, 2)).reshape(temp_array.size)
phase_array = numpy_support.numpy_to_vtk(PH)
pd.AddArray(phase_array)
pd.GetArray(1).SetName("phase")
pd.Update()
# export data to file
writer = vtk.vtkXMLImageDataWriter()
writer.SetFileName(os.path.join(datadir, "S" + str(scan) + "_raw_amp-phase" + comment + ".vti"))
writer.SetInputData(image_data)
writer.Write()
del temp_array, pd, writer, data_array, phase_array, PH, AMP, image_data, amp
gc.collect()
##############################################
# orthogonalize data
##############################################
if xrayutils_ortho == 0:
if correct_refraction == 1 or correct_absorption == 1:
path_out = refraction_corr(amp, direction="out", threshold=threshold_refraction,
xrayutils_orthogonal=xrayutils_ortho)
obj_ortho, voxel_size = orthogonalize(myobj=avg_obj, energy=en, outofplane=outofplane_angle, inplane=inplane_angle,
tilt=tilt_angle, myrocking_angle=rocking_angle, mygrazing_angle=grazing_angle,
distance=sdd, pixel_x=pixel_size, pixel_y=pixel_size,
myvoxel_size=fix_voxel, geometry=setup)
if debug == 0:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(abs(obj_ortho).sum(axis=2)[numz // 2 - zrange:numz // 2 + zrange,
numy // 2 - yrange:numy // 2 + yrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in YZ after orthogonalization, before centering")
plt.subplot(2, 2, 2)
plt.imshow(abs(obj_ortho).sum(axis=1)[numz // 2 - zrange:numz // 2 + zrange,
numx // 2 - xrange:numx // 2 + xrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XZ after orthogonalization, before centering")
plt.subplot(2, 2, 3)
plt.imshow(abs(obj_ortho).sum(axis=0)[numy // 2 - yrange:numy // 2 + yrange,
numx // 2 - xrange:numx // 2 + xrange], cmap=my_cmap)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Sum(amp) in XY after orthogonalization, before centering")
print("VTK spacing :", str('{:.2f}'.format(voxel_size)), "nm")
else: # data already orthogonalized using xrayutilities, # TODO: DEBUG THIS PART, never checked it
obj_ortho = avg_obj
try:
print("Select the file containing QxQzQy")
file_path = filedialog.askopenfilename(title="Select the file containing QxQzQy",
initialdir=datadir, filetypes=[("NPZ", "*.npz")])
npzfile = np.load(file_path)
qx = npzfile['qx']
qy = npzfile['qy']
qz = npzfile['qz']
except FileNotFoundError:
print('Voxel size unknown')
sys.exit()
dy_real = 2 * np.pi / abs(qz.max() - qz.min()) / 10 # in nm qz=y in nexus convention
dx_real = 2 * np.pi / abs(qy.max() - qy.min()) / 10 # in nm qy=x in nexus convention
dz_real = 2 * np.pi / abs(qx.max() - qx.min()) / 10 # in nm qx=z in nexus convention
if fix_voxel != 0:
voxel_size = fix_voxel
else:
voxel_size = np.mean([dz_real, dy_real, dx_real]) # in nm
print('real space pixel size: ', str('{:.2f}'.format(voxel_size)), 'nm')
print('Use the same voxel size in each dimensions: interpolating...\n\n')
obj_ortho = regrid(obj_ortho, (dz_real, dy_real, dx_real), voxel_size)
del avg_obj
gc.collect()
# #################################################
# calculate q, kin , kout from angles and energy
# #################################################
wave = 12.398 * 1e-7 / en # wavelength in m
kin = 2*np.pi/wave * np.array([1, 0, 0]) # z downstream, y vertical, x outboard
if setup == 'SIXS':
# gamma is anti-clockwise
kout = 2*np.pi/wave * np.array([np.cos(np.pi*inplane_angle/180)*np.cos(np.pi*outofplane_angle/180), # z
np.sin(np.pi*outofplane_angle/180), # y
np.sin(np.pi*inplane_angle/180)*np.cos(np.pi*outofplane_angle/180)]) # x
elif setup == 'ID01':
# nu is clockwise
kout = 2*np.pi/wave * np.array([np.cos(np.pi*inplane_angle/180)*np.cos(np.pi*outofplane_angle/180), # z
np.sin(np.pi*outofplane_angle/180), # y
-np.sin(np.pi*inplane_angle/180)*np.cos(np.pi*outofplane_angle/180)]) # x
elif setup == '34ID':
# gamma is anti-clockwise
kout = 2*np.pi/wave * np.array([np.cos(np.pi*inplane_angle/180)*np.cos(np.pi*outofplane_angle/180), # z
np.sin(np.pi*outofplane_angle/180), # y
np.sin(np.pi*inplane_angle/180)*np.cos(np.pi*outofplane_angle/180)]) # x
elif setup == 'P10':
# TODO: check motor rotation at P10
# gamma is anti-clockwise
kout = 2*np.pi/wave * np.array([np.cos(np.pi*inplane_angle/180)*np.cos(np.pi*outofplane_angle/180), # z
np.sin(np.pi*outofplane_angle/180), # y
np.sin(np.pi*inplane_angle/180)*np.cos(np.pi*outofplane_angle/180)]) # x
elif setup == 'CRISTAL':
# TODO: check motor rotation at CRISTAL
# gamma is anti-clockwise
kout = 2*np.pi/wave * np.array([np.cos(np.pi*inplane_angle/180)*np.cos(np.pi*outofplane_angle/180), # z
np.sin(np.pi*outofplane_angle/180), # y
np.sin(np.pi*inplane_angle/180)*np.cos(np.pi*outofplane_angle/180)]) # x
else:
print('setup parameter: ', setup, 'not defined')
sys.exit()
q = kout - kin
Qnorm = np.linalg.norm(q)
q = q / Qnorm
Qnorm = Qnorm * 1e-10 # switch to angstroms
planar_dist = 2*np.pi/Qnorm # Qnorm should be in angstroms
print("Wavevector transfer [z, y, x]:", q*Qnorm)
print("Wavevector transfer: (angstroms)", str('{:.4f}'.format(Qnorm)))
print("Atomic plane distance: (angstroms)", str('{:.4f}'.format(planar_dist)), "angstroms")
if get_temperature:
temperature = bragg_temperature(planar_dist, reflection, spacing_ref=reference_spacing,
temperature_ref=reference_temperature, use_q=0, material="Pt")
planar_dist = planar_dist / 10 # switch to nm
if xrayutils_ortho == 1:
if correct_refraction == 1 or correct_absorption == 1:
print('Refraction/absorption correction not yet implemented for orthogonal data')
# TODO: implement this, at the moment is it wrong
# path_in = refraction_corr(amp, "in", threshold_refraction, 1, kin) # data in crystal basis, will be slow
# path_out = refraction_corr(amp, "out", threshold_refraction, 1, kout) # data in crystal basis, will be slow
###########################################################
# centering of array
###########################################################
obj_ortho = center_com(obj_ortho)
###########################################################
# plot amp and phase
###########################################################
amp = abs(obj_ortho)
phase = np.angle(obj_ortho)
# plot amp
pixel_spacing = tick_spacing / voxel_size
if debug == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(abs(obj_ortho).sum(axis=2)[numz // 2 - zrange:numz // 2 + zrange,
numy // 2 - yrange:numy // 2 + yrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in YZ after orthogonalization and centering")
plt.subplot(2, 2, 2)
plt.imshow(abs(obj_ortho).sum(axis=1)[numz // 2 - zrange:numz // 2 + zrange,
numx // 2 - xrange:numx // 2 + xrange], cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) in XZ after orthogonalization and centering")
plt.subplot(2, 2, 3)
plt.imshow(abs(obj_ortho).sum(axis=0)[numy // 2 - yrange:numy // 2 + yrange,
numx // 2 - xrange:numx // 2 + xrange], cmap=my_cmap)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Sum(amp) in XY after orthogonalization and centering")
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(phase[numz // 2 - zrange:numz // 2 + zrange, numy // 2 - yrange:numy // 2 + yrange, numx // 2],
vmin=-phase_range, vmax=phase_range, cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("Phase at middle frame in YZ before refraction correction")
plt.subplot(2, 2, 2)
plt.imshow(phase[numz // 2 - zrange:numz // 2 + zrange, numy // 2, numx // 2 - xrange:numx // 2 + xrange],
vmin=-phase_range, vmax=phase_range, cmap=my_cmap)
plt.colorbar()
plt.title("Phase at middle frame in XZ before refraction correction")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(phase[numz // 2, numy // 2 - yrange:numy // 2 + yrange, numx // 2 - xrange:numx // 2 + xrange],
vmin=-phase_range, vmax=phase_range, cmap=my_cmap)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Phase at middle frame in XY before refraction correction")
plt.axis('scaled')
plt.pause(0.1)
del obj_ortho
gc.collect()
############################################################
# refraction correction
############################################################
if xrayutils_ortho == 0: # otherwise it is already calculated for xrayutilities above
if correct_refraction == 1 or correct_absorption == 1:
path_in = refraction_corr(amp, direction="in", threshold=threshold_refraction,
xrayutils_orthogonal=xrayutils_ortho)
path_out, voxel_size = orthogonalize(myobj=path_out, energy=en, outofplane=outofplane_angle,
inplane=inplane_angle, tilt=tilt_angle, myrocking_angle=rocking_angle,
mygrazing_angle=grazing_angle, distance=sdd, pixel_x=pixel_size,
pixel_y=pixel_size, myvoxel_size=fix_voxel, geometry=setup)
# orthogonalize the path_out calculated in the detector frame
optical_path = voxel_size * (path_in + path_out) # in nm
if debug == 1:
plt.figure(figsize=(14, 14))
plt.subplot(2, 2, 1)
plt.imshow(
path_out[numz // 2 - zrange:numz // 2 + zrange, numy // 2 - yrange:numy // 2 + yrange, numx // 2])
plt.colorbar()
plt.axis('scaled')
plt.title("Optical path_out in pixels at middle frame in YZ")
plt.subplot(2, 2, 2)
plt.imshow(
path_out[numz // 2 - zrange:numz // 2 + zrange, numy // 2, numx // 2 - xrange:numx // 2 + xrange])
plt.colorbar()
plt.title("Optical path_out in pixels at middle frame in XZ")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(
path_out[numz // 2, numy // 2 - yrange:numy // 2 + yrange, numx // 2 - xrange:numx // 2 + xrange])
plt.colorbar()
plt.gca().invert_yaxis()
plt.title("Optical path_out in pixels at middle frame in XY")
plt.axis('scaled')
if correct_refraction == 1:
phase_correction = 2 * np.pi / (1e9 * wave) * dispersion * optical_path
phase = phase + phase_correction
fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(2, 2, figsize=figure_size)
plt0 = ax0.imshow(phase_correction[numz // 2 - zrange:numz // 2 + zrange,
numy // 2 - yrange:numy // 2 + yrange, numx // 2], vmin=0, vmax=1)
plt.colorbar(plt0, ax=ax0)
ax0.set_title("Refraction correction at middle frame in YZ")
ax0.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax0.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax0.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction,
length=tick_length, width=tick_width)
plt1 = ax1.imshow(phase_correction[numz // 2 - zrange:numz // 2 + zrange,
numy // 2, numx // 2 - xrange:numx // 2 + xrange], vmin=0, vmax=1)
plt.colorbar(plt1, ax=ax1)
ax1.set_title("Refraction correction at middle frame in XZ")
ax1.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax1.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax1.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction,
length=tick_length, width=tick_width)
plt2 = ax2.imshow(phase_correction[numz // 2, numy // 2 - yrange:numy // 2 + yrange,
numx // 2 - xrange:numx // 2 + xrange], vmin=0, vmax=1)
ax2.invert_yaxis()
plt.colorbar(plt2, ax=ax2)
ax2.set_title("Refraction correction at middle frame in XY")
ax2.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax2.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax2.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction,
length=tick_length, width=tick_width)
ax3.set_visible(False)
fig.text(0.60, 0.30, "Scan " + str(scan), size=20)
fig.text(0.60, 0.25, "Voxel size=" + str('{:.2f}'.format(voxel_size)) + "nm", size=20)
fig.text(0.60, 0.20, "Ticks spacing=" + str(tick_spacing) + "nm", size=20)
plt.pause(0.1)
if correct_absorption == 1:
amp_correction = np.exp(2 * np.pi / (1e9 * wave) * absorption * optical_path)
amp = amp * amp_correction
# amp = amp / amp.max() # normalize
fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(2, 2, figsize=figure_size)
plt0 = ax0.imshow(amp_correction[numz // 2 - zrange:numz // 2 + zrange,
numy // 2 - yrange:numy // 2 + yrange, numx // 2])
plt.colorbar(plt0, ax=ax0)
ax0.set_title("Absorption correction at middle frame in YZ")
ax0.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax0.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax0.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction,
length=tick_length, width=tick_width)
plt1 = ax1.imshow(amp_correction[numz // 2 - zrange:numz // 2 + zrange,
numy // 2, numx // 2 - xrange:numx // 2 + xrange])
plt.colorbar(plt1, ax=ax1)
ax1.set_title("Absorption correction at middle frame in XZ")
ax1.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax1.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax1.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction,
length=tick_length, width=tick_width)
plt2 = ax2.imshow(amp_correction[numz // 2, numy // 2 - yrange:numy // 2 + yrange,
numx // 2 - xrange:numx // 2 + xrange])
ax2.invert_yaxis()
plt.colorbar(plt2, ax=ax2)
ax2.set_title("Absorption correction at middle frame in XY")
ax2.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax2.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax2.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction,
length=tick_length, width=tick_width)
ax3.set_visible(False)
fig.text(0.60, 0.30, "Scan " + str(scan), size=20)
fig.text(0.60, 0.25, "Voxel size=" + str('{:.2f}'.format(voxel_size)) + "nm", size=20)
fig.text(0.60, 0.20, "Ticks spacing=" + str(tick_spacing) + "nm", size=20)
plt.pause(0.1)
############################################################
# phase ramp removal
############################################################
amp, phase = remove_ramp(amp, phase, method=phase_ramp_removal, ups_factor=2, threshold=threshold_plot,
gradient_threshold=1, debugging=0)
if debug == 0:
tempo_phase = np.copy(phase)
tempo_phase[abs(amp) < threshold_plot * abs(amp).max()] = 0
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(tempo_phase[numz // 2 - zrange:numz // 2 + zrange, numy // 2 - yrange:numy // 2 + yrange, numx // 2],
cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("Phase at middle frame in YZ after phase ramp removal 1")
plt.subplot(2, 2, 2)
plt.imshow(tempo_phase[numz // 2 - zrange:numz // 2 + zrange, numy // 2, numx // 2 - xrange:numx // 2 + xrange],
cmap=my_cmap)
plt.colorbar()
plt.title("Phase at middle frame in XZ after phase ramp removal 1")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(tempo_phase[numz // 2, numy // 2 - yrange:numy // 2 + yrange, numx // 2 - xrange:numx // 2 + xrange],
cmap=my_cmap)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Phase at middle frame in XY after phase ramp removal 1")
plt.axis('scaled')
plt.pause(0.1)
amp, phase = remove_ramp(amp, phase, method='gradient', threshold=threshold_plot, gradient_threshold=1,
debugging=0)
############################################################
# phase offset removal (at COM value)
############################################################
support = np.zeros(amp.shape)
support[amp > 0.25*amp.max()] = 1
zz, yy, xx = center_of_mass(support)
print("Mean phase:", phase[support == 1].mean(), "rad")
print("COM at (z, y, x): (", str('{:.2f}'.format(zz)), ',', str('{:.2f}'.format(yy)), ',',
str('{:.2f}'.format(xx)), ')')
print("Phase offset at COM(amp) of:", str('{:.2f}'.format(phase[int(zz), int(yy), int(xx)])), "rad")
phase = phase - phase[int(zz), int(yy), int(xx)]
phase = wrap(phase)
if debug == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(phase[numz // 2 - zrange:numz // 2 + zrange, numy // 2 - yrange:numy // 2 + yrange, numx // 2],
cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("Phase at middle frame in YZ after offset removal")
plt.subplot(2, 2, 2)
plt.imshow(phase[numz // 2 - zrange:numz // 2 + zrange, numy // 2, numx // 2 - xrange:numx // 2 + xrange],
cmap=my_cmap)
plt.colorbar()
plt.title("Phase at middle frame in XZ after offset removal")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(phase[numz // 2, numy // 2 - yrange:numy // 2 + yrange, numx // 2 - xrange:numx // 2 + xrange],
cmap=my_cmap)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Phase at middle frame in XY after offset removal")
plt.axis('scaled')
plt.pause(0.1)
phase = phase - phase[support == 1].mean() #
del support
gc.collect()
phase = wrap(phase)
if debug == 1:
plt.figure(figsize=figure_size)
plt.subplot(2, 2, 1)
plt.imshow(phase[numz // 2 - zrange:numz // 2 + zrange, numy // 2 - yrange:numy // 2 + yrange, numx // 2],
cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("Phase at middle frame in YZ after mean removal")
plt.subplot(2, 2, 2)
plt.imshow(phase[numz // 2 - zrange:numz // 2 + zrange, numy // 2, numx // 2 - xrange:numx // 2 + xrange],
cmap=my_cmap)
plt.colorbar()
plt.title("Phase at middle frame in XZ after mean removal")
plt.axis('scaled')
plt.subplot(2, 2, 3)
plt.imshow(phase[numz // 2, numy // 2 - yrange:numy // 2 + yrange, numx // 2 - xrange:numx // 2 + xrange],
cmap=my_cmap)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Phase at middle frame in XY after mean removal")
plt.axis('scaled')
plt.pause(0.1)
# ###########################################################
# save to VTK before rotations - npz used for PRTF computation
# ###########################################################
if save_labframe:
if invert_phase == 1:
np.savez_compressed(datadir + 'S' + str(scan) + "_amp" + phase_fieldname + comment + '_LAB',
amp=amp, displacement=phase)
else:
np.savez_compressed(datadir + 'S' + str(scan) + "_amp" + phase_fieldname + comment + '_LAB',
amp=amp, phase=phase)
if debug == 1:
print("VTK spacing :", str('{:.2f}'.format(voxel_size)), "nm")
# save amp & phase to VTK before rotation in crystal frame
# in VTK, x is downstream, y vertical, z inboard, thus need to flip the last axis
temp_array = np.copy(amp)
temp_array = temp_array / temp_array.max()
temp_array[temp_array < 0.01] = 0 # save disk space
AMP = np.transpose(np.flip(temp_array, 2)).reshape(temp_array.size)
data_array = numpy_support.numpy_to_vtk(AMP)
image_data = vtk.vtkImageData()
image_data.SetOrigin(0, 0, 0)
image_data.SetSpacing(voxel_size, voxel_size, voxel_size)
image_data.SetExtent(0, numz - 1, 0, numy - 1, 0, numx - 1)
pd = image_data.GetPointData()
pd.SetScalars(data_array)
pd.GetArray(0).SetName("amp")
temp_array = np.copy(phase)
temp_array[amp < 0.01 * amp.max()] = 0 # save disk space
PH = np.transpose(np.flip(temp_array, 2)).reshape(temp_array.size)
phase_array = numpy_support.numpy_to_vtk(PH)
pd.AddArray(phase_array)
pd.GetArray(1).SetName(phase_fieldname)
pd.Update()
# export data to file
writer = vtk.vtkXMLImageDataWriter()
writer.SetFileName(os.path.join(datadir, "S" + str(scan) + "_amp-" + phase_fieldname + "_LAB" + comment + ".vti"))
writer.SetInputData(image_data)
writer.Write()
del temp_array, pd, writer, data_array, phase_array, PH, AMP, image_data
gc.collect()
###########################################################
# invert phase: -1*phase = displacement * q
###########################################################
if invert_phase == 1:
phase = -1 * phase
###########################################################
# put back the crystal in its frame, by aligning q onto the reference axis
###########################################################
if xrayutils_ortho == 0:
if ref_axis_outplane == "x":
myaxis = np.array([1, 0, 0]) # must be in [x, y, z] order
elif ref_axis_outplane == "y":
myaxis = np.array([0, 1, 0]) # must be in [x, y, z] order
elif ref_axis_outplane == "z":
myaxis = np.array([0, 0, 1]) # must be in [x, y, z] order
else:
ref_axis_outplane = "y"
myaxis = np.array([0, 1, 0]) # must be in [x, y, z] order
print('Aligning Q along ', ref_axis_outplane, ":", myaxis)
angle = plane_angle(np.array([q[2], q[1], q[0]])/np.linalg.norm(q), myaxis)
print("Angle between q and", ref_axis_outplane, "=", angle, "deg")
print("Angle with y in zy plane", np.arctan(q[0]/q[1])*180/np.pi, "deg")
print("Angle with y in xy plane", np.arctan(-q[2]/q[1])*180/np.pi, "deg")
print("Angle with z in xz plane", 180+np.arctan(q[2]/q[0])*180/np.pi, "deg")
amp = rotate_crystal(amp, axis_to_align=np.array([q[2], q[1], q[0]])/np.linalg.norm(q),
reference_axis=myaxis, debugging=1)
phase = rotate_crystal(phase, axis_to_align=np.array([q[2], q[1], q[0]])/np.linalg.norm(q),
reference_axis=myaxis, debugging=0)
############################################################
# calculate the strain depending on which axis q is aligned on
############################################################
if ref_axis_outplane == "x":
_, _, strain = np.gradient(planar_dist / (2 * np.pi) * phase,
voxel_size) # q is along x after rotating the crystal
elif ref_axis_outplane == "y":
_, strain, _ = np.gradient(planar_dist / (2 * np.pi) * phase,
voxel_size) # q is along y after rotating the crystal
elif ref_axis_outplane == "z":
strain, _, _ = np.gradient(planar_dist / (2 * np.pi) * phase,
voxel_size) # q is along y after rotating the crystal
else: # default is ref_axis_outplane = "y"
_, strain, _ = np.gradient(planar_dist / (2 * np.pi) * phase,
voxel_size) # q is along y after rotating the crystal
# old method of A. Ulvestad
# gradz, grady, gradx = np.gradient(planar_dist/(2*np.pi)*phase, voxel_size) # planar_dist, voxel_size in nm
# strain = q[0]*gradz + q[1]*grady + q[2]*gradx # q is normalized
#############################################################
# remove the surface layer of the crystal, where the strain is not defined
#############################################################
# remove the outer layer of support for saving, because strain is undefined there
support = np.ones((numz, numy, numx))
support[abs(amp) < isosurface_strain * abs(amp).max()] = 0
coordination_matrix = calc_coordination(support, mykernel=np.ones((9, 9, 9)), debugging=1)
outer = np.copy(coordination_matrix)
outer[np.nonzero(outer)] = 1
# outer[coordination_matrix > 22] = 0 # remove the bulk, threshold=22 for kernel (3, 3, 3)
outer[coordination_matrix > 428] = 0 # remove the bulk, threshold=428 for kernel (9, 9, 9)
outer[coordination_matrix == 0] = 1 # corresponds to outside of the crystal
bulk = np.ones((numz, numy, numx)) - outer
del coordination_matrix, support
gc.collect()
if debug == 0:
plt.figure(figsize=figure_size)
plt.subplot(2, 3, 1)
plt.imshow(outer[:, :, numx//2])
plt.colorbar()
plt.axis('scaled')
plt.title("Surface matrix in middle slice in YZ")
plt.subplot(2, 3, 2)
plt.imshow(outer[:, numy//2, :])
plt.colorbar()
plt.title("Surface matrix in middle slice in XZ")
plt.axis('scaled')
plt.subplot(2, 3, 3)
plt.imshow(outer[numz//2, :, :])
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Surface matrix in middle slice in XY")
plt.axis('scaled')
outer = np.multiply(outer, strain)
plt.subplot(2, 3, 4)
plt.imshow(outer[:, :, numx//2], vmin=-strain_range, vmax=strain_range, cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("Surface strain in middle slice in YZ")
plt.subplot(2, 3, 5)
plt.imshow(outer[:, numy//2, :], vmin=-strain_range, vmax=strain_range, cmap=my_cmap)
plt.colorbar()
plt.title("Surface strain in middle slice in XZ")
plt.axis('scaled')
plt.subplot(2, 3, 6)
plt.imshow(outer[numz//2, :, :], vmin=-strain_range, vmax=strain_range, cmap=my_cmap)
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Surface strain in middle slice in XY")
plt.axis('scaled')
plt.figure(figsize=figure_size)
plt.subplot(2, 3, 1)
plt.imshow(bulk[:, :, numx//2])
plt.colorbar()
plt.axis('scaled')
plt.title("Bulk matrix in middle slice in YZ")
plt.subplot(2, 3, 2)
plt.imshow(bulk[:, numy//2, :])
plt.colorbar()
plt.title("Bulk matrix in middle slice in XZ")
plt.axis('scaled')
plt.subplot(2, 3, 3)
plt.imshow(bulk[numz//2, :, :])
plt.gca().invert_yaxis()
plt.colorbar()
plt.title("Bulk matrix in middle slice in XY")
plt.axis('scaled')
del outer
gc.collect()
#############################################################
# rotates the crystal inplane for easier slicing of the result
#############################################################
if xrayutils_ortho == 0:
if align_inplane == 1:
align_crystal = 1
if ref_axis_inplane == "x":
myaxis_inplane = np.array([1, 0, 0]) # must be in [x, y, z] order
elif ref_axis_inplane == "z":
myaxis_inplane = np.array([0, 0, 1]) # must be in [x, y, z] order
else:
ref_axis_inplane = "z"
myaxis_inplane = np.array([0, 0, 1]) # must be in [x, y, z] order
amp = rotate_crystal(amp, axis_to_align=inplane_normal/np.linalg.norm(inplane_normal),
reference_axis=myaxis_inplane, debugging=1)
bulk = rotate_crystal(bulk, axis_to_align=inplane_normal/np.linalg.norm(inplane_normal),
reference_axis=myaxis_inplane, debugging=0)
phase = rotate_crystal(phase, axis_to_align=inplane_normal/np.linalg.norm(inplane_normal),
reference_axis=myaxis_inplane, debugging=0)
strain = rotate_crystal(strain, axis_to_align=inplane_normal/np.linalg.norm(inplane_normal),
reference_axis=myaxis_inplane, debugging=0)
bulk[bulk < 0.01] = 0
bulk[np.nonzero(bulk)] = 1
if align_crystal == 1:
comment = comment + '_crystal-frame'
else:
comment = comment + '_lab-frame'
print('Rotating back the crystal in laboratory frame')
amp = rotate_crystal(amp, axis_to_align=myaxis,
reference_axis=np.array([q[2], q[1], q[0]])/np.linalg.norm(q), debugging=1)
bulk = rotate_crystal(bulk, axis_to_align=myaxis,
reference_axis=np.array([q[2], q[1], q[0]])/np.linalg.norm(q), debugging=0)
phase = rotate_crystal(phase, axis_to_align=myaxis,
reference_axis=np.array([q[2], q[1], q[0]])/np.linalg.norm(q), debugging=0)
strain = rotate_crystal(strain, axis_to_align=myaxis,
reference_axis=np.array([q[2], q[1], q[0]])/np.linalg.norm(q), debugging=0)
bulk[bulk < 0.01] = 0
bulk[np.nonzero(bulk)] = 1
print('Voxel size: ', str('{:.2f}'.format(voxel_size)), "nm")
###########################################################
# pad array to fit the output_size parameter
###########################################################
if not output_size: # output_size not defined, default to actual size
pass
else:
numz, numy, numx = amp.shape
amp = crop_pad(amp, output_size, debugging=0)
bulk = crop_pad(bulk, output_size, debugging=0)
phase = crop_pad(phase, output_size, debugging=0)
strain = crop_pad(strain, output_size, debugging=0)
numz, numy, numx = amp.shape
print("Final data shape:", numz, numy, numx)
############################################################
# save result to vtk (result in the laboratory frame or rotated result in the crystal frame)
############################################################
if save:
amp_bulk = np.copy(amp)
amp_bulk[bulk == 0] = 0
if invert_phase == 1:
np.savez_compressed(datadir + 'S' + str(scan) + "_amp" + phase_fieldname + "strain" + comment,
amp=amp, displacement=phase, bulk=amp_bulk, strain=strain)
else:
np.savez_compressed(datadir + 'S' + str(scan) + "_amp" + phase_fieldname + "strain" + comment,
amp=amp, phase=phase, bulk=amp_bulk, strain=strain)
# save amp & phase to VTK
# in VTK, x is downstream, y vertical, z inboard, thus need to flip the last axis
temp_array = np.copy(amp)
temp_array = temp_array / temp_array.max()
temp_array[temp_array < 0.01] = 0 # save disk space
AMP = np.transpose(np.flip(temp_array, 2)).reshape(temp_array.size)
data_array = numpy_support.numpy_to_vtk(AMP)
image_data = vtk.vtkImageData()
image_data.SetOrigin(0, 0, 0)
image_data.SetSpacing(voxel_size, voxel_size, voxel_size)
image_data.SetExtent(0, numz - 1, 0, numy - 1, 0, numx - 1)
pd = image_data.GetPointData()
pd.SetScalars(data_array)
pd.GetArray(0).SetName("amp")
temp_array = np.copy(amp_bulk)
BULK = np.transpose(np.flip(temp_array, 2)).reshape(temp_array.size)
bulk_array = numpy_support.numpy_to_vtk(BULK)
pd.AddArray(bulk_array)
pd.GetArray(1).SetName("amp_bulk")
pd.Update()
temp_array = np.copy(phase)
temp_array[amp < 0.01 * amp.max()] = 0 # save disk space
PH = np.transpose(np.flip(temp_array, 2)).reshape(temp_array.size)
phase_array = numpy_support.numpy_to_vtk(PH)
pd.AddArray(phase_array)
pd.GetArray(2).SetName(phase_fieldname)
pd.Update()
temp_array = np.copy(strain)
STR = np.transpose(np.flip(temp_array, 2)).reshape(temp_array.size)
strain_array = numpy_support.numpy_to_vtk(STR)
pd.AddArray(strain_array)
pd.GetArray(3).SetName("strain")
pd.Update()
# export data to file
writer = vtk.vtkXMLImageDataWriter()
writer.SetFileName(os.path.join(datadir, "S"+str(scan)+"_amp-" + phase_fieldname + "-strain" + comment + ".vti"))
writer.SetInputData(image_data)
writer.Write()
del temp_array, pd, writer, data_array, phase_array, PH, AMP, image_data, amp_bulk
gc.collect()
#############################################
# plot phase & strain
#############################################
amp = amp / amp.max()
# support = np.zeros(amp.shape)
# support[amp > threshold_plot] = 1 # only for plotting
volume = bulk.sum()*voxel_size**3 # in nm3
strain[bulk == 0] = -2*strain_range
phase[bulk == 0] = -2*phase_range
# del bulk
# gc.collect()
fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(2, 2, figsize=figure_size)
plt0 = ax0.imshow(bulk[:, :, numx//2], cmap=my_cmap, vmin=0, vmax=1)
plt.colorbar(plt0, ax=ax0)
ax0.set_title('Orthogonal bulk at middle frame in YZ')
ax0.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax0.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax0.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction, length=tick_length,
width=tick_width)
plt1 = ax1.imshow(bulk[:, numy//2, :], cmap=my_cmap, vmin=0, vmax=1)
plt.colorbar(plt1, ax=ax1)
ax1.set_title('Orthogonal bulk at middle frame in XZ')
ax1.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax1.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax1.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction, length=tick_length,
width=tick_width)
plt2 = ax2.imshow(bulk[numz//2, :, :], cmap=my_cmap, vmin=0, vmax=1)
ax2.invert_yaxis()
plt.colorbar(plt2, ax=ax2)
ax2.set_title('Orthogonal bulk at middle frame in XY')
ax2.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax2.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax2.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction, length=tick_length,
width=tick_width)
ax3.set_visible(False)
fig.text(0.60, 0.45, "Scan " + str(scan), size=20)
fig.text(0.60, 0.40, "Bulk - isosurface=" + str('{:.2f}'.format(threshold_plot)), size=20)
fig.text(0.60, 0.35, "Ticks spacing=" + str(tick_spacing) + "nm", size=20)
plt.pause(0.1)
if save:
plt.savefig(
datadir + 'S' + str(scan) + '_bulk' + comment + '.png')
# del support
# gc.collect()
fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(2, 2, figsize=figure_size)
plt0 = ax0.imshow(amp[:, :, numx//2], cmap=my_cmap, vmin=0, vmax=1)
plt.colorbar(plt0, ax=ax0)
ax0.set_title("Amp at middle frame in YZ \nafter orthogonalization and centering")
ax0.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax0.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax0.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction, length=tick_length,
width=tick_width)
plt1 = ax1.imshow(amp[:, numy//2, :], cmap=my_cmap, vmin=0, vmax=1)
plt.colorbar(plt1, ax=ax1)
ax1.set_title("Amp at middle frame in XZ \nafter orthogonalization and centering")
ax1.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax1.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax1.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction, length=tick_length,
width=tick_width)
plt2 = ax2.imshow(amp[numz//2, :, :], cmap=my_cmap, vmin=0, vmax=1)
ax2.invert_yaxis()
plt.colorbar(plt2, ax=ax2)
ax2.set_title("Amp at middle frame in XY \nafter orthogonalization and centering")
ax2.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax2.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax2.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction, length=tick_length,
width=tick_width)
ax3.set_visible(False)
fig.text(0.60, 0.45, "Scan " + str(scan), size=20)
fig.text(0.60, 0.40, "Voxel size=" + str('{:.2f}'.format(voxel_size)) + "nm", size=20)
fig.text(0.60, 0.35, "Ticks spacing=" + str(tick_spacing) + "nm", size=20)
fig.text(0.60, 0.30, "Volume=" + str(int(volume)) + "nm3", size=20)
fig.text(0.60, 0.25, "Sorted by " + sort_by, size=20)
fig.text(0.60, 0.20, 'correlation threshold=' + str(correlation_threshold), size=20)
fig.text(0.60, 0.15, "Average over " + str(avg_counter) + " reconstruction(s)", size=20)
fig.text(0.60, 0.10, "Planar distance=" + str('{:.5f}'.format(planar_dist)) + "nm", size=20)
if get_temperature:
fig.text(0.60, 0.05, "Estimated T=" + str(temperature) + "C", size=20)
if save:
plt.savefig(datadir + 'amp_S' + str(scan) + comment + '.png')
fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(2, 2, figsize=figure_size)
plt0 = ax0.imshow(phase[:, :, numx//2], vmin=-phase_range, vmax=phase_range, cmap=my_cmap)
plt.colorbar(plt0, ax=ax0)
ax0.set_title("Displacement at middle frame in YZ \nafter ramp and offset removal")
ax0.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax0.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax0.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction, length=tick_length,
width=tick_width)
plt1 = ax1.imshow(phase[:, numy//2, :], vmin=-phase_range, vmax=phase_range, cmap=my_cmap)
plt.colorbar(plt1, ax=ax1)
ax1.set_title("Displacement at middle frame in XZ \nafter ramp and offset removal")
ax1.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax1.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax1.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction, length=tick_length,
width=tick_width)
plt2 = ax2.imshow(phase[numz//2, :, :], vmin=-phase_range, vmax=phase_range, cmap=my_cmap)
ax2.invert_yaxis()
plt.colorbar(plt2, ax=ax2)
ax2.set_title("Displacement at middle frame in XY \nafter ramp and offset removal")
ax2.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax2.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax2.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction, length=tick_length,
width=tick_width)
ax3.set_visible(False)
fig.text(0.60, 0.30, "Scan " + str(scan), size=20)
fig.text(0.60, 0.25, "Voxel size=" + str('{:.2f}'.format(voxel_size)) + "nm", size=20)
fig.text(0.60, 0.20, "Ticks spacing=" + str(tick_spacing) + "nm", size=20)
fig.text(0.60, 0.15, "Average over " + str(avg_counter) + " reconstruction(s)", size=20)
if hwidth > 0:
fig.text(0.60, 0.10, "Averaging over " + str(2*hwidth+1) + " pixels", size=20)
else:
fig.text(0.60, 0.10, "No phase averaging", size=20)
if save:
plt.savefig(datadir + 'displacement_S' + str(scan) + comment + '.png')
fig, ((ax0, ax1), (ax2, ax3)) = plt.subplots(2, 2, figsize=figure_size)
plt0 = ax0.imshow(strain[:, :, numx//2], vmin=-strain_range, vmax=strain_range, cmap=my_cmap)
plt.colorbar(plt0, ax=ax0)
ax0.set_title("Strain at middle frame in YZ")
ax0.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax0.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax0.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction, length=tick_length,
width=tick_width)
plt1 = ax1.imshow(strain[:, numy//2, :], vmin=-strain_range, vmax=strain_range, cmap=my_cmap)
plt.colorbar(plt1, ax=ax1)
ax1.set_title("Strain at middle frame in XZ")
ax1.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax1.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax1.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction, length=tick_length,
width=tick_width)
plt2 = ax2.imshow(strain[numz//2, :, :], vmin=-strain_range, vmax=strain_range, cmap=my_cmap)
ax2.invert_yaxis()
plt.colorbar(plt2, ax=ax2)
ax2.set_title("Strain at middle frame in XY")
ax2.xaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax2.yaxis.set_major_locator(ticker.MultipleLocator(pixel_spacing))
ax2.tick_params(labelbottom='off', labelleft='off', top='on', right='on', direction=tick_direction, length=tick_length,
width=tick_width)
ax3.set_visible(False)
fig.text(0.60, 0.30, "Scan " + str(scan), size=20)
fig.text(0.60, 0.25, "Voxel size=" + str('{:.2f}'.format(voxel_size)) + "nm", size=20)
fig.text(0.60, 0.20, "Ticks spacing=" + str(tick_spacing) + "nm", size=20)
fig.text(0.60, 0.15, "Average over " + str(avg_counter) + " reconstruction(s)", size=20)
if hwidth > 0:
fig.text(0.60, 0.10, "Averaging over " + str(2*hwidth+1) + " pixels", size=20)
else:
fig.text(0.60, 0.10, "No phase averaging", size=20)
if save:
plt.savefig(datadir + 'strain_S' + str(scan) + comment + '.png')
print('End of script')
plt.ioff()
plt.show()
<file_sep># -*- coding: utf-8 -*-
"""
starting from a 2D complex object (output of phasing program), center the object, remove the phase ramp,
the phase offset and wrap the phase
"""
import numpy as np
import h5py
import sys
import tkinter as tk
from tkinter import filedialog
from scipy.ndimage.measurements import center_of_mass
import matplotlib
matplotlib.use("Qt5Agg")
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
datadir = "C:/Users/Jerome/Documents/data/BCDI_isosurface/S2227/simu/Figures/phasing_kin_FFT/"
savedir = datadir
original_size = [512, 512] # size of the FFT window used for phasing
phase_range = np.pi/30 # in radians, for plots
save_colorbar = 1 # to save the colorbar
comment = "_pynx_fft_negative" # should start with _
aGe = 0.5658 # lattice spacing of Ge in nm
d400_Ge = aGe/4
q400_Ge = 2*np.pi/d400_Ge # inverse nm
print('q=', str(q400_Ge), ' inverse nm')
# parameters for plotting
params = {'backend': 'ps',
'axes.labelsize': 20,
'text.fontsize': 20,
'legend.fontsize': 20,
'title.fontsize': 20,
'xtick.labelsize': 20,
'ytick.labelsize': 20,
'text.usetex': False,
'figure.figsize': (11, 9)}
# define a colormap
cdict = {'red': ((0.0, 1.0, 1.0),
(0.11, 0.0, 0.0),
(0.36, 0.0, 0.0),
(0.62, 1.0, 1.0),
(0.87, 1.0, 1.0),
(1.0, 0.0, 0.0)),
'green': ((0.0, 1.0, 1.0),
(0.11, 0.0, 0.0),
(0.36, 1.0, 1.0),
(0.62, 1.0, 1.0),
(0.87, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 1.0, 1.0),
(0.11, 1.0, 1.0),
(0.36, 1.0, 1.0),
(0.62, 0.0, 0.0),
(0.87, 0.0, 0.0),
(1.0, 0.0, 0.0))}
my_cmap = matplotlib.colors.LinearSegmentedColormap('my_colormap', cdict, 256)
def crop_pad_2d(myobj, myshape, debugging=0):
"""
will crop or pad my obj depending on myshape
:param myobj: 2d complex array to be padded
:param myshape: list of desired output shape [y, x]
:param debugging: to plot myobj before and after padding
:return: myobj padded with zeros
"""
nby, nbx = myobj.shape
newy, newx = myshape
if debugging == 1:
plt.figure()
plt.imshow(abs(myobj), vmin=0, vmax=1)
plt.colorbar()
plt.axis('scaled')
plt.title("before crop/pad")
plt.pause(0.1)
# y
if newy >= nby: # pad
temp_y = np.zeros((newy, nbx), dtype=myobj.dtype)
temp_y[(newy - nby) // 2:(newy + nby) // 2, :] = myobj
else: # crop
temp_y = myobj[(nby - newy) // 2:(newy + nby) // 2, :]
# x
if newx >= nbx: # pad
newobj = np.zeros((newy, newx), dtype=myobj.dtype)
newobj[:, (newx - nbx) // 2:(newx + nbx) // 2] = temp_y
else: # crop
newobj = temp_y[:, (nbx - newx) // 2:(newx + nbx) // 2]
if debugging == 1:
plt.figure()
plt.imshow(abs(newobj), vmin=0, vmax=1)
plt.colorbar()
plt.axis('scaled')
plt.title("after crop/pad")
plt.pause(0.1)
return newobj
def center_com_2d(myarray, debugging=0):
""""
:param myarray: array to be centered based on the center of mass value
:param debugging: 1 to show plots
:return centered array
"""
nby, nbx = myarray.shape
if debugging == 1:
plt.figure()
plt.imshow(abs(myarray), cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp)before COM centering")
plt.pause(0.1)
piy, pix = center_of_mass(abs(myarray))
print("center of mass at (y, x): (", str('{:.2f}'.format(piy)), ',', str('{:.2f}'.format(pix)), ')')
offset_y = int(np.rint(nby / 2.0 - piy))
offset_x = int(np.rint(nbx / 2.0 - pix))
print("center of mass offset: (", offset_y, ',', offset_x, ') pixels')
myarray = np.roll(myarray, (offset_y, offset_x), axis=(0, 1))
if debugging == 1:
plt.figure()
plt.imshow(abs(myarray), cmap=my_cmap)
plt.colorbar()
plt.title("Sum(amp) after COM centering")
plt.pause(0.1)
return myarray
def remove_ramp_2d(myamp, myphase, threshold, gradient_threshold, debugging=0):
"""
remove_ramp: remove the linear trend in the ramp using its gradient and a threshold
:param myamp: amplitude of the object
:param myphase: phase of the object, to be detrended
:param threshold: threshold used to define the support of the object
:param gradient_threshold: higher threshold used to select valid voxels in the gradient array
:param debugging: 1 to show plots
:return: the detrended phase
"""
grad_threshold = gradient_threshold
nby, nbx = myamp.shape
mysupport = np.zeros((nby, nbx))
mysupport[myamp > threshold*abs(myamp).max()] = 1
mygrady, mygradx = np.gradient(myphase, 1)
mysupporty = np.zeros((nby, nbx))
mysupporty[abs(mygrady) < grad_threshold] = 1
mysupporty = mysupporty * mysupport
myrampy = mygrady[mysupporty == 1].mean()
if debugging == 1:
plt.figure()
plt.imshow(mygrady, vmin=-0.2, vmax=0.2)
plt.colorbar()
plt.axis('scaled')
plt.title("mygrady")
plt.pause(0.1)
plt.figure()
plt.imshow(mysupporty, vmin=0, vmax=1)
plt.colorbar()
plt.axis('scaled')
plt.title("mysupporty")
plt.pause(0.1)
mysupportx = np.zeros((nby, nbx))
mysupportx[abs(mygradx) < grad_threshold] = 1
mysupportx = mysupportx * mysupport
myrampx = mygradx[mysupportx == 1].mean()
if debugging == 1:
plt.figure()
plt.imshow(mygradx, vmin=-0.2, vmax=0.2)
plt.colorbar()
plt.axis('scaled')
plt.title("mygradx")
plt.pause(0.1)
plt.figure()
plt.imshow(mysupportx, vmin=0, vmax=1)
plt.colorbar()
plt.axis('scaled')
plt.title("mysupportx")
plt.pause(0.1)
myy, myx = np.meshgrid(np.arange(0, nby, 1), np.arange(0, nbx, 1), indexing='ij')
print('Phase_ramp_y, Phase_ramp_x: (', str('{:.3f}'.format(myrampy)), str('{:.3f}'.format(myrampx)), ') rad')
myphase = myphase - myy * myrampy - myx * myrampx
return myphase
def wrap(myphase):
"""
wrap the phase in [-pi pi] interval
:param myphase:
:return:
"""
myphase = (myphase + np.pi) % (2 * np.pi) - np.pi
return myphase
plt.ion()
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename(initialdir=datadir, filetypes=[("NPZ", "*.npz"),
("NPY", "*.npy"), ("CXI", "*.cxi"), ("HDF5", "*.h5")])
if file_path.lower().endswith('.npz'):
ext = '.npz'
npzfile = np.load(file_path)
obj = npzfile['obj']
elif file_path.lower().endswith('.npy'):
ext = '.npy'
obj = np.load(file_path[0])
elif file_path.lower().endswith('.cxi'):
ext = '.cxi'
h5file = h5py.File(file_path, 'r')
group_key = list(h5file.keys())[1]
subgroup_key = list(h5file[group_key])
obj = h5file['/' + group_key + '/' + subgroup_key[0] + '/data'].value
elif file_path.lower().endswith('.h5'):
ext = '.h5'
h5file = h5py.File(file_path, 'r')
group_key = list(h5file.keys())[0]
subgroup_key = list(h5file[group_key])
obj = h5file['/' + group_key + '/' + subgroup_key[0] + '/data'].value[0]
comment = comment + "_1stmode"
else:
sys.exit('wrong file format')
################
# center object
################
obj = center_com_2d(obj, debugging=1)
if len(original_size) != 0:
print("Original FFT window size: ", original_size)
print("Padding back to initial size")
obj = crop_pad_2d(myobj=obj, myshape=original_size, debugging=1)
ny, nx = obj.shape
half_window = int(nx/2)
####################
# remove phase ramp
####################
amp = abs(obj)
amp = amp / amp.max()
plt.figure()
plt.imshow(amp, cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("amplitude")
plt.pause(0.1)
phase = np.angle(obj)
plt.figure()
plt.imshow(phase, cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("phase before ramp removal")
plt.pause(0.1)
# phase = remove_ramp_2d(amp, phase, threshold=0.0005, gradient_threshold=0.01, debugging=1)
plt.figure()
plt.imshow(phase, cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("phase after ramp removal")
plt.pause(0.1)
####################
# remove phase offset
####################
support = np.zeros(amp.shape)
support[amp > 0.05] = 1
plt.figure()
plt.imshow(support, cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("support used for offset removal")
plt.pause(0.1)
ycom, xcom = center_of_mass(support)
print("Mean phase:", phase[support == 1].mean(), "rad")
print("COM at (y, x): (", ',', str('{:.2f}'.format(ycom)), ',',
str('{:.2f}'.format(xcom)), ')')
print("Phase offset at COM(amp) of:", str('{:.2f}'.format(phase[int(ycom), int(xcom)])), "rad")
phase = phase - phase[int(ycom), int(xcom)]
plt.figure()
plt.imshow(phase, cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("phase after offset removal")
plt.pause(0.1)
####################
# wrap phase
####################
phase = wrap(phase)
plt.figure()
plt.imshow(phase, cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("phase after wrapping")
plt.pause(0.1)
####################
# scale back to displacement
####################
phase = phase / q400_Ge
phase[support == 0] = np.nan
plt.figure()
plt.imshow(phase, cmap=my_cmap)
plt.colorbar()
plt.axis('scaled')
plt.title("phase after rescaling to displacement")
plt.pause(0.1)
####################
# plot the phase
####################
fig, ax0 = plt.subplots(1, 1)
plt0 = ax0.imshow(phase[half_window - 100:half_window+100, half_window-100:half_window+100],
cmap=my_cmap, vmin=-phase_range, vmax=phase_range)
ax0.tick_params(labelbottom='off', labelleft='off', bottom='off', left='off', top='off', right='off')
plt.pause(0.5)
plt.savefig(savedir + comment + '.png', bbox_inches="tight")
if save_colorbar == 1:
plt.colorbar(plt0, ax=ax0)
plt.xlabel('X')
plt.ylabel('Y')
plt.pause(0.5)
plt.savefig(savedir + comment + '_colorbar.png', bbox_inches="tight")
plt.ioff()
plt.show()
| 3bca5b8f9780f8ac27c3f57ec2b21a61432ab189 | [
"Markdown",
"Python"
] | 3 | Markdown | Lawryle/postprocessing_cdi | 9016b2b49134eb82fba41c822f0805e09b8c5d81 | 969bad726a856fb70196f5883b6d7af5d1b6e223 |
refs/heads/master | <file_sep>#ifndef pacemaker_h
#define pacemaker_h
#include "globals.h"
class PaceMakerImpl;
class PaceKeeper;
class Pacer;
const USec SAMPLE_PERIOD = 500000;
class PaceMaker {
public:
PaceMaker(PaceKeeper* = nil, USec period = SAMPLE_PERIOD);
virtual ~PaceMaker();
virtual void startall();
virtual void pause();
virtual void resume();
virtual void start(Scheduler*);
virtual void cont(Scheduler*, USec);
virtual void stop(Scheduler*);
virtual void stopall();
virtual void cont_eval(USec period = -1);
virtual void get_origin(Sec&, USec&);
static PaceMaker* instance();
virtual void set_pacekeeper(PaceKeeper*);
virtual PaceKeeper* get_pacekeeper();
protected:
PaceMakerImpl* _impl;
};
#endif
<file_sep>#include "gcollector.h"
#include "pacer.h"
#include <stdio.h>
class TileImpl {
public:
TileImpl();
virtual void play(RunTime&);
virtual void get_grades(Grade& low, Grade& high);
virtual void regrade();
public:
Pacer* _pacer;
Grade _low, _high;
SessionID _id;
Pacer* _target;
Grade _target_x;
};
TileImpl::TileImpl () {
_pacer = nil;
_low = _high = -1;
_id = -1;
_target = nil;
}
void TileImpl::play (RunTime& rtime) {
Grade low, high;
get_grades(low, high);
FadeType f = fadetype(
rtime._cur_grade, rtime._fut_grade, low, high
);
if (f == no_fade) {
return;
}
if (rtime._id != _id) {
/* new session */
_id = rtime._id;
_target = nil;
_target_x = -1;
}
Grade& cur = rtime._cur_grade;
Grade& fut = rtime._fut_grade;
Grade orig_cur = cur;
Grade orig_fut = fut;
if (_target != nil) {
cur -= _target_x;
fut -= _target_x;
_target->get_grades(low, high);
FadeType f = fadetype(cur, fut, low, high);
switch(f) {
case no_fade:
{
_target = nil;
_target_x = -1;
}
break;
case sustain:
{
_target->play(rtime);
cur = orig_cur;
fut = orig_fut;
return;
}
break;
case fadeout_low:
case fadeout_high:
{
_target->play(rtime);
}
break;
case fadein_low:
case fadein_high:
break;
}
cur = orig_cur;
fut = orig_fut;
}
if (_pacer->count() > 0) {
Grade l, h;
_pacer->child(0)->get_grades(l, h);
cur -= l;
fut -= l;
}
for (PacerIndex i = 0; i < _pacer->count(); i++) {
Grade l, h;
Pacer* p = _pacer->child(i);
p->get_grades(l, h);
Grade diff = h - l;
if (cur >= 0 && cur <= diff) {
/* fade out, target already played */
if (_target == nil) {
p->play(rtime);
}
if (cur == fut) {
//printf("target set to %d out of %d\n", i, _pacer->count()-1);
//printf("cur and fut are %d %d\n", orig_cur, orig_fut);
_target = p;
_target_x = orig_cur - cur;
//printf("target_x is %d\n", _target_x);
}
} else if (fut >= 0 && fut <= diff) {
p->play(rtime);
_target = p;
_target_x = orig_fut - fut;
}
cur -= (diff + 1);
fut -= (diff + 1);
if (cur < 0 && fut < 0) {
break;
}
}
cur = orig_cur;
fut = orig_fut;
}
void TileImpl::get_grades (Grade& low, Grade& high) {
if (_low == -1 && _high == -1) {
for (PacerIndex i = 0; i < _pacer->count(); i++) {
Grade l, h;
_pacer->child(i)->get_grades(l, h);
_high += h - l + 1;
}
if (_pacer->count() > 0) {
Grade l, h;
_pacer->child(0)->get_grades(l, h);
_low = l;
_high += l;
}
}
low = _low;
high = _high;
}
void TileImpl::regrade () {
_low = -1;
_high = -1;
for (PacerIndex i = 0; i < _pacer->count(); i++) {
Grade l, h;
_pacer->child(i)->regrade();
_pacer->child(i)->get_grades(l, h);
_high += h - l + 1;
}
if (_pacer->count() > 0) {
Grade l, h;
_pacer->child(0)->get_grades(l, h);
_low = l;
_high += l;
}
}
/***************************************************************************/
class NormalImpl {
public:
NormalImpl();
virtual void play(RunTime&);
virtual void get_grades(Grade& low, Grade& high);
virtual void regrade();
public:
Pacer* _pacer;
Grade _low, _high;
SessionID _id;
};
NormalImpl::NormalImpl () {
_pacer = nil;
_low = _high = -1;
_id = -1;
}
void NormalImpl::play (RunTime& rtime) {
Grade low, high;
get_grades(low, high);
FadeType f = fadetype(
rtime._cur_grade, rtime._fut_grade, low, high
);
if (f == no_fade) {
return;
}
Grade& cur = rtime._cur_grade;
Grade& fut = rtime._fut_grade;
Grade orig_cur = cur;
Grade orig_fut = fut;
Grade diff = _high - _low;
float cur_f, fut_f;
if (diff == 0) {
if (cur == 0 || fut == 0) {
cur_f = cur;
fut_f = fut;
} else {
return;
}
} else {
cur_f = ((float)cur)/((float)diff);
fut_f = ((float)fut)/((float)diff);
}
for (PacerIndex i = 0; i < _pacer->count(); i++) {
Grade l, h;
Pacer* p = _pacer->child(i);
p->get_grades(l, h);
cur = (Grade)(cur_f * (h - l) + l);
fut = (Grade)(fut_f * (h - l) + l);
p->play(rtime);
}
cur = orig_cur;
fut = orig_fut;
}
void NormalImpl::get_grades (Grade& low, Grade& high) {
if (_low == -1 || _high == -1) {
for (PacerIndex i = 0; i < _pacer->count(); i++) {
Grade l, h;
_pacer->child(i)->get_grades(l, h);
if (_high < (h - l)) {
_high = h - l;
}
}
}
low = _low;
high = _high;
}
void NormalImpl::regrade () {
_low = 0;
_high = -1;
for (PacerIndex i = 0; i < _pacer->count(); i++) {
Grade l, h;
_pacer->child(i)->regrade();
_pacer->child(i)->get_grades(l, h);
if (_high < (h - l)) {
_high = h - l;
}
}
}
/***************************************************************************/
class DistribImpl {
public:
DistribImpl();
virtual void play(RunTime&);
virtual void get_grades(Grade& low, Grade& high);
virtual void regrade();
public:
Pacer* _pacer;
Grade _low, _high;
SessionID _id;
};
DistribImpl::DistribImpl () {
_pacer = nil;
_low = _high = -1;
_id = -1;
}
void DistribImpl::regrade () {
_low = -1;
_high = -1;
if (_pacer->count() > 0) {
_pacer->child(0)->regrade();
_pacer->child(0)->get_grades(_low, _high);
}
for (PacerIndex i = 1; i < _pacer->count(); i++) {
Grade l, h;
_pacer->child(i)->regrade();
_pacer->child(i)->get_grades(l, h);
if (h > _high) {
_high = h;
}
if (l < _low) {
_low = l;
}
}
}
void DistribImpl::get_grades (Grade& low, Grade& high) {
if (_low == -1 || _high == -1) {
if (_pacer->count() > 0) {
_pacer->child(0)->get_grades(_low, _high);
}
for (PacerIndex i = 1; i < _pacer->count(); i++) {
Grade l, h;
_pacer->child(i)->get_grades(l, h);
if (h > _high) {
_high = h;
}
if (l < _low) {
_low = l;
}
}
}
low = _low;
high = _high;
}
void DistribImpl::play (RunTime& rtime) {
Grade low, high;
get_grades(low, high);
FadeType f = fadetype(
rtime._cur_grade, rtime._fut_grade, low, high
);
if (f == no_fade) {
return;
}
Grade& cur = rtime._cur_grade;
Grade& fut = rtime._fut_grade;
for (PacerIndex i = 0; i < _pacer->count(); i++) {
Grade l, h;
Pacer* p = _pacer->child(i);
p->get_grades(l, h);
if (cur >= l && cur <= h) {
p->play(rtime);
} else if (fut >= l && fut <= h) {
p->play(rtime);
}
}
}
/***************************************************************************/
GradeCollector::GradeCollector () {}
GradeCollector::~GradeCollector () {}
void GradeCollector::set_pacer (Pacer*) {}
/***************************************************************************/
Tiler::Tiler () {
_impl = new TileImpl;
}
Tiler::~Tiler () { delete _impl; }
void Tiler::play (RunTime& rtime) {
_impl->play(rtime);
}
void Tiler::set_pacer (Pacer* p) {
_impl->_pacer = p;
}
void Tiler::get_grades (Grade& low, Grade& high) {
Grade l, h;
_impl->get_grades(l, h);
low = l; high = h;
}
void Tiler::regrade () {
_impl->regrade();
}
Normalizer::Normalizer () {
_impl = new NormalImpl;
}
Normalizer::~Normalizer () { delete _impl; }
void Normalizer::play (RunTime& rtime) {
_impl->play(rtime);
}
void Normalizer::set_pacer (Pacer* p) {
_impl->_pacer = p;
}
void Normalizer::get_grades (Grade& low, Grade& high) {
Grade l, h;
_impl->get_grades(l, h);
low = l; high = h;
}
void Normalizer::regrade () {
_impl->regrade();
}
Distributor::Distributor () {
_impl = new DistribImpl;
}
Distributor::~Distributor () { delete _impl; }
void Distributor::play (RunTime& rtime) {
_impl->play(rtime);
}
void Distributor::set_pacer (Pacer* p) {
_impl->_pacer = p;
}
void Distributor::get_grades (Grade& low, Grade& high) {
Grade l, h;
_impl->get_grades(l, h);
low = l; high = h;
}
void Distributor::regrade () {
_impl->regrade();
}
<file_sep>/*
* glypheditor - a simple drawing editor-like application for tutorial purposes
*/
#include <InterViews/monoglyph.h>
class Button;
class GlyphViewer;
class TelltaleGroup;
class Window;
class GlyphEditor : public MonoGlyph {
public:
GlyphEditor();
Window* window();
GlyphViewer* viewer();
void new_session();
void quit();
virtual void allocate(Canvas*, const Allocation&, Extension&);
protected:
Button* make_tool(TelltaleGroup*, const char*, unsigned int);
Button* make_policy(TelltaleGroup*, const char*, unsigned int);
protected:
GlyphViewer* _gviewer;
Window* _w;
private:
Glyph* interior();
Glyph* buttons();
Glyph* pacekeepers();
Glyph* menus();
};
inline Window* GlyphEditor::window () { return _w; }
inline GlyphViewer* GlyphEditor::viewer () { return _gviewer; }
<file_sep>class RGBNames {
public:
RGBNames ();
RGBNames (const char *filename);
char *lookupName (int red, int green, int blue);
void lookupTriplet (int *red, int *green, int *blue);
};
<file_sep>#include <Dispatch/iohandler.h>
#include <Dispatch/dispatcher.h>
#include <OS/list.h>
#include <sys/time.h>
#include "pacekeeper.h"
#include "pacer.h"
#include "pacemaker.h"
class PaceHandlerList;
class PaceMakerImpl {
public:
PaceMakerImpl(PaceKeeper*, USec period);
virtual ~PaceMakerImpl();
void set_pacekeeper(PaceKeeper*);
PaceKeeper* get_pacekeeper();
void tick(long sec, long usec);
void startall();
void pause();
void resume();
void play(Scheduler*, Sec, USec);
void start(Scheduler*);
void cont(Scheduler*, USec);
void stop(Scheduler*);
void stopall();
void cont_eval(USec period);
void get_origin(Sec& sec, USec& usec);
public:
PaceHandlerList* _plist;
IOHandler* _ehandler;
PaceKeeper* _pacekeeper;
boolean _running;
boolean _paused;
Sec _o_sec;
USec _o_usec;
Sec _p_sec;
USec _p_usec;
USec _period;
};
class PaceHandler : public IOHandler {
public:
PaceHandler(Scheduler* = nil, PaceMakerImpl* = nil);
virtual ~PaceHandler();
virtual void timerExpired(long, long);
public:
Scheduler* _pacer;
PaceMakerImpl* _impl;
};
PaceHandler::PaceHandler(Scheduler* p, PaceMakerImpl* impl) {
_pacer = p;
_impl = impl;
}
PaceHandler::~PaceHandler () {}
void PaceHandler::timerExpired (long sec, long usec) {
_impl->play(_pacer, sec, usec);
}
declarePtrList(PaceHandlerList, PaceHandler);
implementPtrList(PaceHandlerList, PaceHandler);
class EvalHandler : public IOHandler {
public:
EvalHandler(PaceMakerImpl*);
virtual void timerExpired(long, long);
public:
PaceMakerImpl* _impl;
};
EvalHandler::EvalHandler (PaceMakerImpl* impl) {
_impl = impl;
}
void EvalHandler::timerExpired(long sec, long usec) {
_impl->tick(sec, usec);
}
PaceMakerImpl::PaceMakerImpl (PaceKeeper* pk, USec period) {
_running = false;
_paused = false;
_period = period;
_pacekeeper = pk;
_o_sec = 0;
_o_usec = 0;
_p_sec = 0;
_p_usec = 0;
_plist = new PaceHandlerList(5);
_ehandler = new EvalHandler(this);
}
PaceMakerImpl::~PaceMakerImpl () {
Dispatcher& d = Dispatcher::instance();
for (long i = 0; i < _plist->count(); i++) {
d.stopTimer(_plist->item(i));
delete _plist->item(i);
}
d.stopTimer(_ehandler);
delete _ehandler;
delete _plist;
}
void PaceMakerImpl::set_pacekeeper(PaceKeeper* pacekeeper) {
_pacekeeper = pacekeeper;
}
PaceKeeper* PaceMakerImpl::get_pacekeeper () {
return _pacekeeper;
}
void PaceMakerImpl::tick (long sec, long usec) {
_pacekeeper->eval(sec-_o_sec, usec-_o_sec);
}
void PaceMakerImpl::cont_eval (USec period) {
if (period > 0) {
_period = period;
}
Dispatcher& d = Dispatcher::instance();
d.stopTimer(_ehandler);
d.startTimer(0, _period, _ehandler);
}
void PaceMakerImpl::get_origin(Sec& sec, USec& usec) {
sec = _o_sec;
usec = _o_usec;
}
void PaceMakerImpl::startall () {
_running = true;
timeval curTime;
gettimeofday(&curTime, nil);
_o_sec = curTime.tv_sec;
_o_usec = curTime.tv_usec;
_pacekeeper->startall(0, 0);
Dispatcher& d = Dispatcher::instance();
d.startTimer(0, _period, _ehandler);
}
void PaceMakerImpl::pause () {
if (_running && !_paused) {
_paused = true;
timeval curTime;
gettimeofday(&curTime, nil);
_p_sec = curTime.tv_sec;
_p_usec = curTime.tv_usec;
Dispatcher& d = Dispatcher::instance();
for (long i = 0; i < _plist->count(); i++) {
d.stopTimer(_plist->item(i));
}
d.stopTimer(_ehandler);
}
}
void PaceMakerImpl::resume () {
if (_running && _paused) {
timeval curTime;
gettimeofday(&curTime, nil);
Sec sec = _p_sec - _o_sec;
Sec usec = _p_usec - _o_usec;
for (long i = 0; i < _plist->count(); i++) {
_pacekeeper->play(_plist->item(i)->_pacer, sec, usec);
}
_o_sec += curTime.tv_sec - _p_sec;
_o_usec += curTime.tv_usec - _p_usec;
Dispatcher& d = Dispatcher::instance();
d.startTimer(0, _period, _ehandler);
}
}
void PaceMakerImpl::play (Scheduler* p, Sec sec, USec usec) {
if (_running && !_paused) {
for (long i = 0; i < _plist->count(); i++) {
if (_plist->item(i)->_pacer == p) {
Dispatcher& d = Dispatcher::instance();
d.stopTimer(_plist->item(i));
delete _plist->item(i);
_plist->remove(i);
break;
}
}
_pacekeeper->play(p, sec-_o_sec, usec-_o_usec);
}
}
void PaceMakerImpl::cont (Scheduler* p, USec usec) {
if (_running) {
if (usec > 0) {
PaceHandler* phandler = new PaceHandler(p, this);
_plist->append(phandler);
Dispatcher::instance().startTimer(0, usec, phandler);
} else {
timeval curTime;
gettimeofday(&curTime, nil);
play(p, curTime.tv_sec, curTime.tv_usec);
}
}
}
void PaceMakerImpl::start (Scheduler* p) {
timeval curTime;
gettimeofday(&curTime, nil);
if (!_running) {
_running = true;
_o_sec = curTime.tv_sec;
_o_usec = curTime.tv_usec;
_pacekeeper->start(p, 0, 0);
} else {
_pacekeeper->start(p, curTime.tv_sec-_o_sec, curTime.tv_usec-_o_usec);
}
}
void PaceMakerImpl::stop (Scheduler* p) {
for (long i = 0; i < _plist->count(); i++) {
if (_plist->item(i)->_pacer == p) {
Dispatcher::instance().stopTimer(_plist->item(i));
delete _plist->item(i);
_plist->remove(i);
break;
}
}
timeval curTime;
gettimeofday(&curTime, nil);
_pacekeeper->stop(p, curTime.tv_sec-_o_sec, curTime.tv_usec-_o_usec);
}
void PaceMakerImpl::stopall () {
Dispatcher& d = Dispatcher::instance();
if (_running) {
_running = false;
for (long i = 0; i < _plist->count(); i++) {
d.stopTimer(_plist->item(i));
delete _plist->item(i);
}
}
_plist->remove_all();
d.stopTimer(_ehandler);
if (_pacekeeper != nil) {
timeval curTime;
gettimeofday(&curTime, nil);
_pacekeeper->stopall(curTime.tv_sec-_o_sec, curTime.tv_usec-_o_usec);
}
}
/*************************************************************************/
static PaceMaker* _maker = nil;
PaceMaker::PaceMaker (PaceKeeper* pk, USec period) {
_impl = new PaceMakerImpl(pk, period);
_maker = this;
}
PaceMaker::~PaceMaker () {
delete _impl;
if (_maker == this) {
_maker = nil;
}
}
void PaceMaker::startall () {
_impl->startall();
}
void PaceMaker::pause () {
_impl->pause();
}
void PaceMaker::resume () {
_impl->resume();
}
void PaceMaker::cont (Scheduler* p, USec usec) {
_impl->cont(p, usec);
}
void PaceMaker::start (Scheduler* p) {
_impl->start(p);
}
void PaceMaker::stop (Scheduler* p) {
_impl->stop(p);
}
void PaceMaker::stopall () {
_impl->stopall();
}
PaceMaker* PaceMaker::instance () {
if (_maker == nil) {
_maker = new PaceMaker;
}
return _maker;
}
void PaceMaker::set_pacekeeper(PaceKeeper* pacekeeper) {
_impl->set_pacekeeper(pacekeeper);
}
PaceKeeper* PaceMaker::get_pacekeeper () { return _impl->get_pacekeeper(); }
void PaceMaker::cont_eval(USec period) {
_impl->cont_eval(period);
}
void PaceMaker::get_origin (Sec& sec, USec& usec) {
Sec s;
USec u;
_impl->get_origin(s, u);
sec = s;
usec = u;
}
<file_sep>/*
* GlyphViewer
*/
#ifndef glyphviewer_h
#define glyphviewer_h
#include <InterViews/event.h>
#include <InterViews/monoglyph.h>
#include "figureview.h"
class Canvas;
class Color;
class Cursor;
class GlyphGrabber;
class PaceMaker;
class RootGraphic;
class GlyphViewer : public MonoGlyph {
public:
GlyphViewer(float w = -1.0, float h = -1.0);
virtual ~GlyphViewer();
virtual void request(Requisition&) const;
virtual void allocate(Canvas*, const Allocation&, Extension&);
virtual void draw(Canvas*, const Allocation&) const;
virtual void pick(Canvas*, const Allocation&, int depth, Hit&);
virtual Tool& tool();
void set_policy(unsigned int);
unsigned int get_policy();
RootView* getroot();
void setrootgr(Graphic*);
const Allocation& allocation() const;
Canvas* canvas() const;
protected:
void initshape();
void initgraphic();
protected:
float _width, _height;
Allocation _a;
RootView* _root;
Tool _tool;
GlyphGrabber* _grabber;
Canvas* _canvas;
Graphic* _master;
unsigned int _policy;
const Color* _bg;
};
inline const Allocation& GlyphViewer::allocation () const { return _a; }
inline Canvas* GlyphViewer::canvas () const { return _canvas; }
#endif
<file_sep>#include "figure.h"
#include "pacer.h"
#include "pacemaker.h"
#include "pacekeeper.h"
#include "gcollector.h"
#include <InterViews/action.h>
#include <InterViews/canvas.h>
#include <InterViews/color.h>
#include <InterViews/display.h>
#include <InterViews/brush.h>
#include <InterViews/geometry.h>
#include <InterViews/transformer.h>
#include <InterViews/window.h>
#include <IV-X11/xcanvas.h>
#include <OS/math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static Coord Area(Coord l, Coord b, Coord r, Coord t) {
return (r-l)*(t-b);
}
static boolean damaged (BoxObj& box) {
return !(
box._l == 0 && box._b == 0 && box._r == 0 && box._t == 0
);
}
static void clear (BoxObj& box) {
box._l = 0;
box._b = 0;
box._r = 0;
box._t = 0;
}
static const short UniLevel = 0;
static const long SLACK = 1000;
/**********************************************************/
EventMapper::EventMapper () {}
EventMapper::~EventMapper () {}
/*****************************************************************************/
class DragImpl {
public:
DragImpl (USec, USec, long, long, float);
virtual ~DragImpl();
USec init(Event&);
USec map(Event&);
USec relax();
public:
USec _high;
USec _low;
float _relax;
USec _cur_rate;
long _hspeed;
long _lspeed;
Event _last;
};
DragImpl::DragImpl (USec high, USec low, long l, long h, float relax) {
_high = high;
_low = low;
_cur_rate = _high;
_relax = relax;
_hspeed = h;
_lspeed = l;
_last.window(nil);
}
DragImpl::~DragImpl () {}
USec DragImpl::init (Event& e) {
_last = e;
return _high;
}
USec DragImpl::map (Event& e) {
USec value = _cur_rate;
if (_last.window() != nil) {
Coord distx = e.pointer_x()-_last.pointer_x();
Coord disty = e.pointer_y()-_last.pointer_y();
Coord total_dist = Math::abs(distx)+Math::abs(disty);
unsigned long len = e.time() - _last.time();
long speed;
if (len > 0) {
speed = total_dist*1e6/len;
} else {
speed = _hspeed + 1;
}
if (speed > _hspeed) {
value = _low;
} else if (speed < _lspeed) {
value = _high;
} else {
float factor = ((float)(speed-_lspeed))/(_hspeed-_lspeed);
value = (USec) (_high - factor*(_high-_low));
}
}
_last = e;
if (value > _cur_rate) {
value = _cur_rate;
} else {
_cur_rate = value;
}
return value;
}
USec DragImpl::relax () {
if (_cur_rate < _high) {
_cur_rate *= _relax;
}
if (_cur_rate > _high) {
_cur_rate = _high;
}
return _cur_rate;
}
/*****************************************************************************/
DragMapper::DragMapper (USec high, USec low, long l, long h, float relax) {
_impl = new DragImpl(high, low, l, h, relax);
}
DragMapper::~DragMapper () {
delete _impl;
}
USec DragMapper::init (Event& e) {
return _impl->init(e);
}
USec DragMapper::map (Event& e) {
return _impl->map(e);
}
USec DragMapper::relax () {
return _impl->relax();
}
/*****************************************************************************/
class ContImpl {
public:
ContImpl( USec, USec, Coord, Coord, ContDimension);
virtual ~ContImpl();
USec init(Event&);
USec map(Event&);
USec relax();
void set_dimension(ContDimension);
public:
USec _high;
USec _low;
USec _cur_rate;
Coord _short;
Coord _long;
ContDimension _dimension;
Event _last;
};
ContImpl::ContImpl (USec high, USec low, Coord s, Coord l, ContDimension d) {
_high = high;
_low = low;
_short = s;
_long = l;
_cur_rate = _high;
_dimension = d;
_last.window(nil);
}
ContImpl::~ContImpl () {}
USec ContImpl::init (Event& e) {
_last = e;
return _high;
}
void ContImpl::set_dimension(ContDimension d) {
_dimension = d;
}
USec ContImpl::map (Event& e) {
USec value = _cur_rate;
if (_last.window() != nil) {
Coord distx = e.pointer_x()-_last.pointer_x();
Coord disty = e.pointer_y()-_last.pointer_y();
Coord total_dist;
if (_dimension == Cont_XY) {
total_dist = Math::abs(distx)+Math::abs(disty);
} else if (_dimension == Cont_Y) {
total_dist = Math::abs(disty);
} else {
total_dist = Math::abs(distx);
}
if (total_dist > _long) {
value = _low;
} else if (total_dist < _short) {
value = _high;
} else {
float factor = (total_dist-_short)/(_long-_short);
value = (USec) (_high - factor*(_high-_low));
}
}
_cur_rate = value;
return value;
}
USec ContImpl::relax () {
return _cur_rate;
}
/*****************************************************************************/
ContMapper::ContMapper (
USec high, USec low, Coord s, Coord l, ContDimension dimension
) {
_impl = new ContImpl(high, low, s, l, dimension);
}
ContMapper::~ContMapper () {
delete _impl;
}
USec ContMapper::init (Event& e) {
return _impl->init(e);
}
USec ContMapper::map (Event& e) {
return _impl->map(e);
}
USec ContMapper::relax () {
return _impl->relax();
}
void ContMapper::set_dimension(ContDimension d) {
_impl->set_dimension(d);
}
/*****************************************************************************/
Pacer::Pacer () { _parent = nil; }
Pacer::~Pacer () {}
void Pacer::append (Pacer*) {}
void Pacer::prepend (Pacer*) {}
void Pacer::insert(PacerIndex, Pacer*) {}
void Pacer::remove (PacerIndex) {}
void Pacer::remove_all () {}
void Pacer::delete_all () {}
PacerIndex Pacer::count () const { return 0; }
Pacer* Pacer::child (PacerIndex) const { return nil; }
Pacer* Pacer::get_parent () const { return _parent; }
void Pacer::set_parent (Pacer* p) { _parent = p; }
void Pacer::regrade () {}
void Pacer::pick(SchedulerList&) {}
/**********************************************************/
PolyPacer::PolyPacer () {
_child_list = new PacerList(10);
}
PolyPacer::~PolyPacer () {
for (int i = 0; i < count(); i++) {
Pacer* c = child(i);
delete c;
}
delete _child_list;
}
void PolyPacer::pick(SchedulerList& plist) {
for (PacerIndex i = 0; i < count(); i++) {
Pacer* p = child(i);
p->pick(plist);
}
}
void PolyPacer::regrade () {
for (PacerIndex i = 0; i < count(); i++) {
child(i)->regrade();
}
}
void PolyPacer::append (Pacer* gp) {
if (gp != nil) {
_child_list->append(gp);
gp->set_parent(this);
}
}
void PolyPacer::prepend (Pacer* gp) {
if (gp != nil) {
_child_list->prepend(gp);
gp->set_parent(this);
}
}
void PolyPacer::insert(PacerIndex i, Pacer* gp) {
if (gp != nil) {
_child_list->insert(i, gp);
gp->set_parent(this);
}
}
void PolyPacer::remove (PacerIndex i) {
Pacer* p = child(i);
if (p != nil) {
_child_list->remove(i);
p->set_parent(nil);
}
}
void PolyPacer::remove_all () {
for (PacerIndex i = 0; i < count(); i++) {
Pacer* p = child(i);
p->set_parent(nil);
}
_child_list->remove_all();
}
void PolyPacer::delete_all () {
for (PacerIndex i = 0; i < count(); i++) {
Pacer* p = child(i);
delete p;
}
_child_list->remove_all();
}
PacerIndex PolyPacer::count () const {
return _child_list->count();
}
Pacer* PolyPacer::child (PacerIndex i) const {
return _child_list->item(i);
}
/**********************************************************/
Grader::Grader (GradeCollector* g) {
_collector = g;
if (_collector != nil) {
_collector->set_pacer(this);
}
}
Grader::~Grader () {
delete _collector;
}
GradeCollector* Grader::get_collector () const { return _collector; }
void Grader::set_collector (GradeCollector* g) {
if (g != _collector) {
delete _collector;
_collector = g;
if (_collector != nil) {
_collector->set_pacer(this);
}
}
}
void Grader::play (RunTime& rtime) {
GradeCollector* collector = get_collector();
if (collector != nil) {
collector->play(rtime);
}
}
void Grader::get_grades(Grade& low, Grade& high) {
GradeCollector* collector = get_collector();
if (collector != nil) {
Grade l, h;
collector->get_grades(l, h);
low = l; high = h;
}
}
void Grader::regrade () {
GradeCollector* collector = get_collector();
if (collector != nil) {
collector->regrade();
}
}
/**********************************************************/
UniPacer::UniPacer () { _kid = nil; }
UniPacer::~UniPacer () { delete _kid; }
Pacer* UniPacer::get_kid () const { return _kid; }
void UniPacer::set_kid (Pacer* k) {
if (_kid != k) {
if (_kid != nil) {
_kid->set_parent(nil);
}
_kid = k;
if (_kid != nil) {
_kid->set_parent(this);
}
}
}
void UniPacer::pick(SchedulerList& plist) {
if (_kid != nil) {
_kid->pick(plist);
}
}
void UniPacer::regrade () {
if (_kid != nil) {
_kid->regrade();
}
}
void UniPacer::append (Pacer* p) {
set_kid(p);
}
void UniPacer::prepend (Pacer* p) {
set_kid(p);
}
void UniPacer::insert (PacerIndex i, Pacer* p) {
if (i == 0) {
set_kid(p);
}
}
void UniPacer::remove (PacerIndex i) {
if (i == 0) {
if (_kid != nil) {
_kid->set_parent(nil);
}
_kid = nil;
}
}
void UniPacer::remove_all () {
remove(0);
}
void UniPacer::delete_all () {
delete _kid;
_kid = nil;
}
PacerIndex UniPacer::count () const {
if (_kid == nil) {
return 0;
} else {
return 1;
}
}
Pacer* UniPacer::child (PacerIndex i) const {
if (i == 0) {
return _kid;
} else {
return nil;
}
}
void UniPacer::play (RunTime& rtime) {
if (_kid != nil) {
_kid->play(rtime);
}
}
void UniPacer::get_grades (Grade& low, Grade& high) {
if (_kid != nil) {
Grade l, h;
_kid->get_grades(l, h);
low = l; high = h;
} else {
low = high = 0;
}
}
/**********************************************************/
Scheduler::Scheduler (USec period) {
_period = period;
}
void Scheduler::set_period (USec period) {
if (period != _period) {
_period = period;
PaceMaker* maker = PaceMaker::instance();
maker->get_pacekeeper()->adjust(this);
}
}
USec Scheduler::get_period () { return _period; }
void Scheduler::pick (SchedulerList& plist) {
plist.append(this);
}
void Scheduler::start (Sec, USec) {}
void Scheduler::stop (Sec, USec) {}
void Scheduler::play (RunTime& rtime) {
Grade low, high;
get_grades(low, high);
FadeType f = fadetype(
rtime._cur_grade, rtime._fut_grade, low, high
);
if (f != no_fade) {
//USec slack = SLACK;
PaceMaker::instance()->cont(this, _period);
UniPacer::play(rtime);
//PaceMaker::instance()->cont(this, slack);
}
}
/**********************************************************/
UIScheduler::UIScheduler (
EventMapper* emapper
) : Scheduler(-1) {
_emapper = emapper;
_playing = false;
}
UIScheduler::~UIScheduler () {
delete _emapper;
}
void UIScheduler::start (Sec, USec) {
_playing = true;
}
void UIScheduler::stop (Sec, USec) {
_playing = false;
}
void UIScheduler::play (RunTime& rtime) {
if (_playing) {
Scheduler::play(rtime);
set_period(_emapper->relax());
}
}
void UIScheduler::cur_event (Event& e) {
if (!_playing) {
set_period(_emapper->init(e));
} else {
set_period(_emapper->map(e));
PaceMaker::instance()->cont(this, -1);
}
}
void UIScheduler::set_mapper (EventMapper* emapper) {
delete _emapper;
_emapper = emapper;
}
/**********************************************************/
ActionPacer::ActionPacer (Action* before, Action* after) {
_before = before;
_after = after;
Resource::ref(_before);
Resource::ref(_after);
}
ActionPacer::~ActionPacer () {
Resource::unref(_before);
Resource::unref(_after);
}
void ActionPacer::set_before (Action* before) {
Resource::ref(before);
Resource::unref(_before);
_before = before;
}
void ActionPacer::set_after (Action* after) {
Resource::ref(after);
Resource::unref(_after);
_after = after;
}
void ActionPacer::play (RunTime& rtime) {
if (_before != nil) {
_before->execute();
}
UniPacer::play(rtime);
if (_after != nil) {
_after->execute();
}
}
/**********************************************************/
GraphicPacer::GraphicPacer (Canvas* c, Graphic* gr) {
_gr = gr;
_canvas = c;
Resource::ref(_gr);
_low = _high = UniLevel;
}
GraphicPacer::~GraphicPacer () {
Resource::unref(_gr);
}
BoxObj GraphicPacer::_damage;
BoxObj& GraphicPacer::damaged_area () { return _damage; }
void GraphicPacer::incur (BoxObj& box) {
if (!damaged(_damage)) {
_damage = box;
} else {
_damage = _damage + box;
}
}
void GraphicPacer::clear () {
::clear(_damage);
}
void GraphicPacer::get_grades (Grade& low, Grade& high) {
low = _low;
high = _high;
}
void GraphicPacer::set_grades (Grade low, Grade high) {
_low = low;
_high = high;
}
void GraphicPacer::set_graphic (Graphic* gr) {
Resource::ref(gr);
Resource::unref(_gr);
_gr = gr;
}
void GraphicPacer::play (RunTime& rtime) {
if (_canvas == nil) {
return;
}
Grade& cur = rtime._cur_grade;
Grade& fut = rtime._fut_grade;
FadeType f = fadetype(cur, fut, _low, _high);
boolean to_draw = false;
switch (f) {
case sustain:
{
to_draw = true;
}
break;
case fadein_low:
case fadein_high:
{
//_gr->alpha_stroke(true);
//_gr->alpha_fill(true);
to_draw = true;
}
break;
case fadeout_low:
case fadeout_high:
{
/*
Coord l, b, r, t;
_gr->getbounds(l, b, r, t);
if ((r-l)*(t-b) < 100000.0) {
_gr->alpha_stroke(true);
_gr->alpha_fill(true);
to_draw = true;
}
*/
}
break;
case no_fade:
break;
}
if (to_draw) {
_gr->drawclipped(
_canvas, _damage._l, _damage._b, _damage._r, _damage._t
);
}
_gr->alpha_stroke(false);
_gr->alpha_fill(false);
}
/**********************************************************/
Repairer::Repairer (
Canvas* c, Graphic* gr
) : GraphicPacer(c, gr) {}
void Repairer::incur (BoxObj& box) {
if (!damaged(_total)) {
_total = box;
} else {
_total = _total + box;
}
}
void Repairer::clear () {
::clear(_total);
}
BoxObj& Repairer::damaged_area () { return _total; }
/**********************************************************/
Filler::Filler (
Canvas* c, Graphic* gr, const Color* fill
) : Repairer(c, gr) {
_fill = fill;
Resource::ref(_fill);
}
Filler::~Filler () {
Resource::unref(_fill);
}
void Filler::play (RunTime& rtime) {
if (_canvas == nil) {
return;
}
Grade& cur = rtime._cur_grade;
Grade& fut = rtime._fut_grade;
FadeType f = fadetype(cur, fut, _low, _high);
if (f != no_fade) {
if (damaged(_total)) {
_canvas->fill_rect(
_total._l, _total._b, _total._r, _total._t, _fill
);
::clear(_total);
}
}
}
/**********************************************************/
FCGraphicPacer::FCGraphicPacer (
Canvas* c, Graphic* gr, const Color* fill
) : Filler(c, gr, fill) {}
FCGraphicPacer::~FCGraphicPacer () {}
void FCGraphicPacer::play (RunTime& rtime) {
if (_canvas == nil) {
return;
}
Grade& cur = rtime._cur_grade;
Grade& fut = rtime._fut_grade;
FadeType f = fadetype(cur, fut, _low, _high);
if (f == fadein_low || f == fadein_high || f == sustain) {
if (damaged(_total)) {
CanvasRep* crep = _canvas->rep();
BoxObj box = _clip-_total;
_canvas->damage(box._l, box._b, box._r, box._t);
crep->start_repair();
_canvas->fill_rect(
_total._l, _total._b, _total._r, _total._t, _fill
);
_gr->drawclipped(
_canvas, _total._l, _total._b, _total._r, _total._t
);
_gr->alpha_fill(false);
_gr->alpha_stroke(false);
crep->finish_repair();
_canvas->window()->display()->sync();
::clear(_total);
}
}
}
/**********************************************************/
Fixer::Fixer (Canvas* c, Graphic* gr) : Repairer(c, gr) {}
void Fixer::play (RunTime& rtime) {
Grade& cur = rtime._cur_grade;
Grade& fut = rtime._fut_grade;
FadeType f = fadetype(cur, fut, _low, _high);
if (f != no_fade) {
_gr->drawclipped(
_canvas, _total._l, _total._b, _total._r, _total._t
);
::clear(_total);
}
}
/**********************************************************/
SelectPacer::SelectPacer (Canvas* c, Graphic* gr) {
_canvas = c;
_gr = gr;
Resource::ref(_gr);
}
SelectPacer::~SelectPacer () {
Resource::unref(_gr);
}
void SelectPacer::set_graphic (Graphic* gr) {
Resource::ref(gr);
Resource::unref(_gr);
_gr = gr;
}
void SelectPacer::play (RunTime& rtime) {
if (!damaged(GraphicPacer::damaged_area())) {
return;
}
_gr->alpha_fill(true);
_gr->alpha_stroke(true);
UniPacer::play(rtime);
_gr->alpha_fill(false);
_gr->alpha_stroke(false);
GraphicPacer::clear();
}
/**********************************************************/
Clipper::Clipper (Canvas* c, BoxObj* box) {
_canvas = c;
_box = box;
}
Clipper::~Clipper () {}
void Clipper::play (RunTime& rtime) {
if (damaged(*_box)) {
CanvasRep* crep = _canvas->rep();
BoxObj box = _allot-*_box;
_canvas->damage(box._l, box._b, box._r, box._t);
crep->start_repair();
UniPacer::play(rtime);
crep->finish_repair();
_canvas->window()->display()->sync();
GraphicPacer::clear();
}
}
/**********************************************************/
XorPacer::XorPacer (
Canvas* c, Graphic* g, const Color* color
) : GraphicPacer(c, g) {
_color = new Color(*color, 1.0, Color::Xor);
_color->ref();
_brush = new Brush(0.0);
_brush->ref();
_drawn = false;
_t = nil;
set_graphic(g);
}
XorPacer::~XorPacer () {
Resource::unref(_color);
Resource::unref(_brush);
Resource::unref(_t);
}
void XorPacer::set_graphic (Graphic* g) {
GraphicPacer::set_graphic(g);
if (g != nil) {
Resource::unref(_t);
_t = new Transformer;
_gr->eqv_transformer(*_t);
if (_gr->count_() > 0) {
_gr->getbounds(_box._l, _box._b, _box._r, _box._t);
_t->inverse_transform(_box._l, _box._b);
_t->inverse_transform(_box._r, _box._t);
} else {
_gr->get_max_min(_box._l, _box._b, _box._r, _box._t);
}
}
}
void XorPacer::play (RunTime& rtime) {
Grade& cur = rtime._cur_grade;
Grade& fut = rtime._fut_grade;
FadeType f = fadetype(cur, fut, _low, _high);
if (f == fadeout_low || f == fadeout_high) {
if (_drawn) {
printf("fade out\n");
xor();
}
} else if (f == fadein_low || f == fadein_high) {
if (!_drawn) {
_gr->eqv_transformer(*_t);
xor();
GraphicPacer::clear();
}
} else if (f != no_fade) {
if (_drawn) {
xor();
}
_gr->eqv_transformer(*_t);
xor();
GraphicPacer::clear();
}
}
void XorPacer::xor () {
boolean doit = false;
if (!_drawn) {
if (damaged(_damage)) {
_drawn = true;
doit = true;
}
} else {
doit = true;
_drawn = false;
}
if (doit) {
_canvas->push_clipping();
_canvas->clip_rect(_allot._l, _allot._b, _allot._r, _allot._t);
_canvas->front_buffer();
_canvas->push_transform();
_canvas->transform(*_t);
_canvas->rect(
_box._l, _box._b, _box._r, _box._t, _color, _brush
);
_canvas->pop_transform();
_canvas->pop_clipping();
_canvas->back_buffer();
_canvas->window()->display()->sync();
}
}
<file_sep>#ifndef idraw_h
#define idraw_h
#include <InterViews/enter-scope.h>
#include <OS/enter-scope.h>
class InputFile;
class Graphic;
class IdrawReader {
public:
static Graphic* load(InputFile*);
static Graphic* load(const char*);
};
#endif
<file_sep>/* colorChooser.c:
* a simple interviews application for searching through the red-green-blue
* color space of your workstation or terminal, and learning the name of
* any color that can be displayed on it. if you invoke this program with
* exactly one argument, the name of a file like the standard X
* distribution's "rgb.txt", the program will sometimes be able to tell
* you an English language name for the current color. If the current color
* is not sufficiently near to any of these named colors, the program will
* give you a 6-digit hexadecimal string to name the color. In either case,
* the name can be used to specify X resource colors.
*
* some sample invocations:
* colorChooser
* colorChooser /usr/lib/X11/rgb.txt
* colorChooser /local/X11R5/lib/X11/rgb.txt
* colorChooser $OPENWINHOME/lib/rgb.txt
*
* (the last three try to cover the range of places where the rgb.txt
* might be found on your workstation)
*
* here's what the rgb.txt file actually looks like:
*
* 255 250 240 FloralWhite
* 253 245 230 OldLace
* 250 240 230 linen
* 250 235 215 AntiqueWhite
* 255 239 213 PapayaWhip
*
*
* This program is based upon "cedit" by <NAME> of the MIT
* X Consortium. Many thanks to Dave, for cedit and for his frequent,
* helpful postings to comp.windows.interviews.
*
* This program was developed using InterViews 3.1beta3.
*
* I wrote this program as a learning exercise. I've met with a lot of
* frustration in learning InterViews. There are no books, and
* sample source code is invariably cryptic. I hope that this program
* reads easily; if any one has questions, suggestions or complaints,
* please send them to me, <EMAIL>, and I'll do my best to help.
*
*
* thumbnail sketch
*
* This program demonstrates the interaction between 3 fundamental
* iv classes: Adjustable, Adjuster, and Observer. See Chapter 4 of
* the InterViews manual for a description of these classes. I believe
* that these three classes are analagous to Smalltalk's Model-View-
* Controller: Adjustables (Models) are the data your program is
* concerned with; Adjusters (Controllers) manipulate the data;
* Observers (Views) provide ways to view the data. In this program,
* instances of these three classes are used like this:
*
* Adjusters: 3 vertical scrollbars, one each for the red, green, and
* blue color components.
* Adjustables: 3 "ColorValue" objects, each of which stores the color
* intensity of the color component it represents.
* Observers: - 1 color patch, which watches the ColorValue objects,
* and displays the color described by them
* - 3 "ColorValueReadout" objects, each of which
* watches one of the ColorValues, and displays the intensity
* of its ColorValue as a number between 0 and 255, in a
* little box just above the related scrollbar
* - 1 "DynamicLabel", which watches the ColorValue objects
* and displays a name for the current color in an inset
* box above the color patch.
*
*
* a little more detail
*
* - the 3 "ColorValue" adjustables, one for each of the color
* components, form the heart of the program. they accept
* scrolling messages from the scrollbars. they (implicitly) send
* update messages to all of their attached observers when their
* notify function is called. they don't appear on the screen, but they
* store the current intensitity of the colors, and the rate at which they
* change these values in response to messages from adjusters (the
* scrollbars).
* class ColorValue: public Adjustable
*
* - 3 scrollbars, which subclass Adjuster, and send messages to the
* ColorValue adjustables. they are produced by WidgetKit member
* functions, and are initialized with a single parameter each --
* a pointer to the adjustable they'll adjust.
*
* - each of the observers is attached to the ColorValue adjustables, so
* that they can be notified whenever the adjustables have changed.
* they then query the ColorValue objects to find out what their current
* values are, and update themselves appropriately:
*
* 1. class ColorDisplay: public Patch, public Observer
* 2. class DynamicLabel: public MonoGlyph, public Observer
* 3. class ColorValueReadout: public MonoGlyph, public Observer
*
* note: the ColorDisplay object and the DynamicLabel object are both
* attached to all three of the ColorValue objects: they both need
* the value of all three color components in order to update themselves.
* but the ColorValueReadout objects are each attached to only
* one of the ColorValue objects -- the one which corresponds to the
* color component they're concerned with.
*
* there's one more class in this application, which simply returns
* a color name when it's passed a triplet of red-green-blue values.
* it's declared in rgbNames.h, and defined in rgbNames.c.
*
* class RGBNames {
* public:
* RGBNames ();
* RGBNames (const char *filename);
* char *lookupName (int red, int green, int blue);
* };
*/
/*----------------------------------------------------------------------------*/
static char *SCCSid = "@(#)colorChooser.c 2.2 12/16/92 12:03:28";
/*----------------------------------------------------------------------------*/
#include <IV-look/button.h>
#include <IV-look/dialogs.h>
#include <IV-look/kit.h>
#include <IV-look/menu.h>
#include <IV-look/field.h>
#include <IV-look/telltale.h>
#include <InterViews/adjust.h>
#include <InterViews/background.h>
#include <InterViews/box.h>
#include <InterViews/color.h>
#include <InterViews/display.h>
#include <InterViews/glue.h>
#include <InterViews/label.h>
#include <InterViews/layout.h>
#include <InterViews/patch.h>
#include <InterViews/session.h>
#include <InterViews/style.h>
#include <InterViews/window.h>
#include <OS/string.h>
#include <stdio.h>
#include <string.h>
#include "rgbNames.h"
/*----------------------------------------------------------------------------*/
/* ColorValue is a subclass of Adjustable. Adjustables are broadly defined
* as objects that "handle requests to modify their viewing area."
* objects of the ColorValue class, however, are not seen on the screen.
* each object of this class
* - records the current intensity of one of the three primary colors
* (the application has three ColorValue objects, one each for
* red, green and blue);
* - sets the bounds that the color intensity must stay within
* - is connnected to a scrollbar (an adjuster subclass), from which
* it receives a variety of scrolling messages
* - has observers attached that can be told (via Adjustable::notify)
* that it has changed.
* the values range from 0.0 to 1.0, which is the InterViews color range,
* perhaps inherited from PostScript. I'm more used to thinking of color
* on workstation screens ranging from 0-255, so you'll see below that
* ColorValueReadout objects scale the numbers into that range.
*/
/*----------------------------------------------------------------------------*/
class ColorValue: public Adjustable {
protected:
ColorValue ();
public:
ColorValue (Coord lower, Coord upper);
virtual ~ColorValue ();
virtual void lower_bound (Coord);
virtual void upper_bound (Coord);
virtual void current_value (Coord);
virtual void scroll_incr (Coord);
virtual void page_incr (Coord);
virtual Coord lower (DimensionName) const;
virtual Coord upper (DimensionName) const;
virtual Coord length (DimensionName) const;
virtual Coord cur_lower (DimensionName) const;
virtual Coord cur_upper (DimensionName) const;
virtual Coord cur_length (DimensionName) const;
virtual void scroll_to (DimensionName, Coord position);
virtual void scroll_forward (DimensionName);
virtual void scroll_backward (DimensionName);
virtual void page_forward (DimensionName);
virtual void page_backward (DimensionName);
private:
Coord curvalue_;
Coord lower_;
Coord span_;
Coord scroll_incr_;
Coord page_incr_;
};
/*----------------------------------------------------------------------------*/
ColorValue::ColorValue ()
{
scroll_incr_ = 0.0;
page_incr_ = 0.0;
}
/*----------------------------------------------------------------------------*/
ColorValue::ColorValue (Coord lower, Coord upper)
{
lower_ = lower;
span_ = upper - lower;
scroll_incr_ = span_ * 0.005;
page_incr_ = span_ * 0.1;
curvalue_ = (lower + upper) * 0.5;
}
/*----------------------------------------------------------------------------*/
ColorValue::~ColorValue () {}
void ColorValue::lower_bound (Coord c) {lower_ = c;}
void ColorValue::upper_bound (Coord c) {span_ = c - lower_;}
/*----------------------------------------------------------------------------*/
void ColorValue::current_value (Coord value)
{
curvalue_ = value;
constrain (Dimension_X, curvalue_);
notify (Dimension_X);
notify (Dimension_Y);
}
/*----------------------------------------------------------------------------*/
void ColorValue::scroll_incr (Coord c) {scroll_incr_ = c;}
void ColorValue::page_incr (Coord c) {page_incr_ = c;}
Coord ColorValue::lower (DimensionName) const {return lower_;}
Coord ColorValue::upper (DimensionName) const {return lower_ + span_;}
Coord ColorValue::length (DimensionName) const {return span_;}
Coord ColorValue::cur_lower (DimensionName) const {return curvalue_;}
Coord ColorValue::cur_upper (DimensionName) const {return curvalue_;}
Coord ColorValue::cur_length (DimensionName) const {return 0;}
/*----------------------------------------------------------------------------*/
void ColorValue::scroll_to (DimensionName d, Coord position)
{
Coord p = position;
constrain (d, p);
if (p != curvalue_) {
curvalue_ = p;
notify (Dimension_X);
notify (Dimension_Y);
}
}
/*----------------------------------------------------------------------------*/
void ColorValue::scroll_forward (DimensionName d)
{
scroll_to (d, curvalue_ + scroll_incr_);
}
/*----------------------------------------------------------------------------*/
void ColorValue::scroll_backward (DimensionName d)
{
scroll_to(d, curvalue_ - scroll_incr_);
}
/*----------------------------------------------------------------------------*/
void ColorValue::page_forward(DimensionName d)
{
scroll_to(d, curvalue_ + page_incr_);
}
/*----------------------------------------------------------------------------*/
void ColorValue::page_backward(DimensionName d)
{
scroll_to(d, curvalue_ - page_incr_);
}
/*============================================================================*/
/* ColorValueReadout subclasses Observer, so that these objects
* can be attached to Adjustables (in our case, to ColorValues) and will
* receive the update message from ColorValue::notify. the
* attachment takes place in the ColorValueReadout constructor. when
* the update message is received, the ColorValueReadout asks its
* associated ColorValue for its current value, and then sprintf's that number
* into a string, and passes it to its FieldEditor.
*/
class ColorValueReadout: public MonoGlyph, public Observer {
public:
ColorValueReadout (ColorValue*, Style*);
virtual ~ColorValueReadout ();
virtual InputHandler* focusable () const;
virtual void update (Observable*);
virtual void disconnect (Observable*);
private:
ColorValue* colorValue_;
FieldEditor* editor_;
void accept_editor (FieldEditor*);
void cancel_editor (FieldEditor*);
};
/*----------------------------------------------------------------------------*/
/* These macros allow the user's typed numbers, in the text editor fields, to
* be passed back to theColorValueReadout.
*/
declareFieldEditorCallback(ColorValueReadout)
implementFieldEditorCallback(ColorValueReadout)
/*----------------------------------------------------------------------------*/
ColorValueReadout::ColorValueReadout
(ColorValue* colorValue, Style* style): MonoGlyph (nil)
{
Style* s = new Style (style);
s->alias ("ColorValueReadout");
colorValue_ = colorValue;
colorValue->attach (Dimension_X, this);
editor_ = DialogKit::instance()->field_editor (
"100.00", s,
new FieldEditorCallback(ColorValueReadout)(
this, &ColorValueReadout::accept_editor,
&ColorValueReadout::cancel_editor
)
);
body (editor_);
update (colorValue->observable (Dimension_X));
}
/*----------------------------------------------------------------------------*/
ColorValueReadout::~ColorValueReadout ()
{
if (colorValue_ != nil)
colorValue_->detach(Dimension_X, this);
}
/*----------------------------------------------------------------------------*/
InputHandler* ColorValueReadout::focusable () const
{
return editor_;
}
/*----------------------------------------------------------------------------*/
void ColorValueReadout::update (Observable*)
{
int scaledColorValue = (int) (255 * colorValue_->cur_lower (Dimension_X));
char buf [20];
sprintf (buf, "%2d", scaledColorValue);
editor_->field (buf);
}
/*----------------------------------------------------------------------------*/
void ColorValueReadout::disconnect (Observable*)
{
colorValue_ = nil;
}
/*----------------------------------------------------------------------------*/
void ColorValueReadout::accept_editor (FieldEditor*)
{
Coord v;
const String& value = *editor_->text();
if (value.convert (v))
colorValue_->current_value (v);
}
/*----------------------------------------------------------------------------*/
void ColorValueReadout::cancel_editor(FieldEditor*)
{
update (colorValue_->observable (Dimension_X));
}
/*============================================================================*/
/* ColorDisplay. this class is attached to ColorValue objects, from
* which they receive update objects whenever the ColorValues change.
* they find out the current rgb values
*/
class ColorDisplay: public Patch, public Observer {
public:
ColorDisplay (ColorValue*, ColorValue*, ColorValue*, Style*);
virtual ~ColorDisplay ();
virtual void allocate (Canvas*, const Allocation&, Extension&);
virtual void draw (Canvas*, const Allocation&) const;
virtual void update (Observable*);
virtual void disconnect (ColorValue*);
private:
Adjustable* red_;
Adjustable* green_;
Adjustable* blue_;
Color* color_;
};
/*----------------------------------------------------------------------------*/
ColorDisplay::ColorDisplay (ColorValue* r, ColorValue* g,
ColorValue* b, Style*) : Patch (nil)
{
red_ = r;
red_->attach (Dimension_X, this);
green_ = g;
green_->attach (Dimension_X, this);
blue_ = b;
blue_->attach (Dimension_X, this);
color_ = nil;
}
/*----------------------------------------------------------------------------*/
ColorDisplay::~ColorDisplay()
{
if (red_ != nil)
red_->detach(Dimension_X, this);
if (green_ != nil)
green_->detach(Dimension_X, this);
if (blue_ != nil)
blue_->detach(Dimension_X, this);
}
/*----------------------------------------------------------------------------*/
void ColorDisplay::allocate (Canvas* canvas, const
Allocation& allocation,
Extension& extension)
{
extension.set (canvas, allocation);
Patch::allocate (canvas, allocation, extension);
}
/*----------------------------------------------------------------------------*/
void ColorDisplay::draw (Canvas* canvas,
const Allocation& allocation) const
{
canvas->fill_rect (allocation.left (), allocation.bottom (),
allocation.right (), allocation.top (), color_);
}
/*----------------------------------------------------------------------------*/
void ColorDisplay::update (Observable*)
{
Resource::unref (color_);
color_ = new Color (
float (red_->cur_lower(Dimension_X)),
float (green_->cur_lower(Dimension_X)),
float (blue_->cur_lower(Dimension_X)),1.0);
Resource::ref (color_);
redraw ();
}
/*----------------------------------------------------------------------------*/
void ColorDisplay::disconnect (ColorValue* a)
{
if (a == red_)
red_ = nil;
else if (a == green_)
green_ = nil;
else if (a == blue_)
blue_ = nil;
}
/*============================================================================*/
/* DynamicLabel watches all three of the ColorValues, asks the RGBNames
* class for a new string whenever any of the ColorValues change, and
* then writes that new string to its patch.
*/
class DynamicLabel: public MonoGlyph, public Observer {
public:
DynamicLabel::DynamicLabel (RGBNames*, ColorValue*, ColorValue*,
ColorValue*, Style*);
virtual void update ();
virtual void update (Observable*);
private:
Patch* patch_;
Style* style_;
char text_ [80];
WidgetKit *kit;
RGBNames *rgbLookupTable_;
Adjustable* red_;
Adjustable* green_;
Adjustable* blue_;
};
/*----------------------------------------------------------------------------*/
DynamicLabel::DynamicLabel (RGBNames *lookupTable,
ColorValue *redValue, ColorValue *greenValue,
ColorValue *blueValue, Style* style):
MonoGlyph (nil)
{
style_ = style;
kit = WidgetKit::instance ();
patch_ = new Patch (nil);
body (patch_);
strcpy (text_, "no text yet");
red_ = redValue;
green_ = greenValue;
blue_ = blueValue;
rgbLookupTable_ = lookupTable;
red_->attach (Dimension_X, this);
green_->attach (Dimension_X, this);
blue_->attach (Dimension_X, this);
update ();
}
/*----------------------------------------------------------------------------*/
void DynamicLabel::update ()
{
int scaledRed, scaledGreen, scaledBlue;
scaledRed = (int) (255 * red_->cur_lower (Dimension_X));
scaledGreen = (int) (255 * green_->cur_lower (Dimension_X));
scaledBlue = (int) (255 * blue_->cur_lower (Dimension_X));
sprintf (text_, "%s",
rgbLookupTable_->lookupName (scaledRed, scaledGreen, scaledBlue));
patch_->body (new Label (text_, kit->font (), kit->foreground ()));
patch_->redraw ();
patch_->reallocate ();
patch_->redraw ();
}
/*----------------------------------------------------------------------------*/
void DynamicLabel::update (Observable *)
{
int scaledRed, scaledGreen, scaledBlue;
scaledRed = (int) (255 * red_->cur_lower (Dimension_X));
scaledGreen = (int) (255 * green_->cur_lower (Dimension_X));
scaledBlue = (int) (255 * blue_->cur_lower (Dimension_X));
sprintf (text_, "%s",
rgbLookupTable_->lookupName (scaledRed, scaledGreen, scaledBlue));
patch_->body (new Label (text_, kit->font (), kit->foreground ()));
patch_->redraw ();
patch_->reallocate ();
patch_->redraw ();
}
/*============================================================================*/
int main (int argc, char** argv)
{
Session* session = new Session ("ColorChooser", argc, argv);
Style* style = session->style();
WidgetKit& kit = *WidgetKit::instance();
LayoutKit& layout = *LayoutKit::instance();
ColorValue* redValue = new ColorValue (0.0, 1.0);
ColorValue* greenValue = new ColorValue (0.0, 1.0);
ColorValue* blueValue = new ColorValue (0.0, 1.0);
RGBNames *rgbLookupTable;
Glyph *colorVBox, *scrollersAndReadoutVBox, *mainHBox;
ColorValueReadout *redReadOut, *greenReadOut, *blueReadOut;
/* construct the rgb name table, possibly using a path to a rgb.txt
*/
if (argc == 2)
rgbLookupTable = new RGBNames (argv [1]);
else
rgbLookupTable = new RGBNames ();
DynamicLabel* colorNameDisplay =
new DynamicLabel (rgbLookupTable, redValue, greenValue, blueValue, style);
Glyph *framedColorNameDisplay;
/* InterViews requires us to use styles in order to set X resources
* for glyphs. the user interface has three scrollbars, side-by-side,
* each topped off by a numerical readout. we want the each of the
* three color readouts to use the appropriate foreground color,
* reminding the user which color the scrollbar manimpulates.
* these three styles allow us to set the color of the text in the
* readouts as X resources:
* ColorChooser*redReadOut*foreground: red
* ColorChooser*greenReadOut*foreground: green3
* ColorChooser*blueReadOut*foreground: blue
*/
kit.begin_style ("redReadOut");
redReadOut = new ColorValueReadout (redValue, style);
kit.end_style ();
kit.begin_style ("greenReadOut");
greenReadOut = new ColorValueReadout (greenValue, style);
kit.end_style ();
kit.begin_style ("blueReadOut");
blueReadOut = new ColorValueReadout (blueValue, style);
kit.end_style ();
/* create a bunch of layout glyphs, containing the user interface
* objects, which are later assembled into the ApplicationWindow.
* framedColorNameDisplay: this is an inset frame in which the
* name of the current color is displayed
* colorVBox: an unframed vertical box which contains the
* framedColorNameDisplay, centered above an inset frame holding
* the color patch.
* scrollersAndReadoutVBox: another vertical box, which has the
* three scrollbars topped off by the numerical readout boxes.
* mainHBox: a horizontal box which assembles the colorVBox
* and the scrollersAndReadoutVbox side-by-side
*/
framedColorNameDisplay =
kit.inset_frame (
layout.hbox (
layout.hglue (3,0,0),
layout.h_fixed_span (
colorNameDisplay,
155)
)
);
colorVBox =
layout.vbox (
layout.vglue (30,0,0),
layout.hbox (
layout.hglue (20,0,0),
framedColorNameDisplay
),
layout.vglue (10,0,0),
kit.inset_frame (
layout.fixed_span (
new ColorDisplay (redValue, greenValue, blueValue, style),
200.0, 200.0)
)
);
scrollersAndReadoutVBox =
layout.vbox (
layout.vglue (63,0,0),
layout.hbox (
layout.h_fixed_span (redReadOut, 25),
layout.h_fixed_span (greenReadOut, 25),
layout.h_fixed_span (blueReadOut, 25)),
layout.v_fixed_span (
layout.hbox (
layout.h_fixed_span (kit.vscroll_bar (redValue), 25),
layout.h_fixed_span (kit.vscroll_bar (greenValue), 25),
layout.h_fixed_span (kit.vscroll_bar (blueValue), 25)
),
185.0),
layout.vglue (13,0,0)
);
mainHBox =
layout.hbox (
layout.margin (
colorVBox,
8.0),
layout.margin (
scrollersAndReadoutVBox,
8.0)
);
Window* w = new ApplicationWindow (
new Background (
kit.outset_frame (
layout.hbox (
layout.hglue (),
layout.vbox (
layout.vglue (),
layout.margin (kit.push_button ("Quit", kit.quit()), 5.0),
mainHBox,
layout.vglue()
),
layout.hglue ()
)
),
kit.background ()
) // Background
); // ApplicationWindow
redValue->current_value (0.7);
greenValue->current_value (0.6);
blueValue->current_value (0.8);
colorNameDisplay->update ();
return session->run_window (w);
} // main
/*----------------------------------------------------------------------------*/
<file_sep>#ifndef gcollector_h
#define gcollector_h
#include <OS/list.h>
#include "globals.h"
class Pacer;
class TileImpl;
class NormalImpl;
class DistribImpl;
class GradeCollector {
public:
virtual ~GradeCollector();
virtual void play(RunTime&) = 0;
virtual void get_grades(Grade& low, Grade& high) = 0;
virtual void regrade() = 0;
virtual void set_pacer(Pacer*);
protected:
GradeCollector();
};
class Tiler : public GradeCollector {
public:
Tiler();
virtual ~Tiler();
virtual void play(RunTime&);
virtual void get_grades(Grade& low, Grade& high);
virtual void regrade();
virtual void set_pacer(Pacer*);
private:
TileImpl* _impl;
};
class Normalizer : public GradeCollector {
public:
Normalizer();
virtual ~Normalizer();
virtual void play(RunTime&);
virtual void get_grades(Grade& low, Grade& high);
virtual void regrade();
virtual void set_pacer(Pacer*);
private:
NormalImpl* _impl;
};
class Distributor : public GradeCollector {
public:
Distributor();
virtual ~Distributor();
virtual void play(RunTime&);
virtual void get_grades(Grade& low, Grade& high);
virtual void regrade();
virtual void set_pacer(Pacer*);
private:
DistribImpl* _impl;
};
#endif
<file_sep>/* rgbNames.c: a class that reads and stores the X11 color names
* color names, stored in $OPENWINHOME/lib/rgb.txt, and which will return
* a color name which is a reasonable match for an rgb triplet. for example
*
* 186 85 211 will return MediumOrchid
*
* the numbers are from a scale that runs from 0 to 255.
*
* the RGBNames class is defined in this file, and may be tested here
* as well, by defining EMBEDDED_TEST at compile time. the class
* is designed to be part of a simple Interviews exercise, in which
* the user may interactively choose colors for display. this class
* allows the program to convert the rgb numerical triplet into a name
* meaningful to the xnews server.
*
* the header file, rgbNames.h, declares the public portion of this class,
* and should be included by any application that wants to use the class.
*/
/*----------------------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
/*----------------------------------------------------------------------------*/
int extractRGBValuesAndColorName (char *rawString,
int *red, int *green, int *blue,
char *colorName);
/*----------------------------------------------------------------------------*/
const char *const RGB_FILE = "/usr/openwin/lib/rgb.txt";
const int MAX_COLORS = 800;
const int BIG_STRING_SIZE = 255;
class RGBNames {
public:
RGBNames ();
RGBNames (const char *filename);
char *lookupName (int red, int green, int blue);
private:
struct rgbNameTableType {
int red, green, blue;
char name [40];
};
rgbNameTableType rgbNameTable [MAX_COLORS];
int rgbtxtFileIsBeingUsed;
int tableSize;
int tolerance; /* in matching an incoming rgb against a table entry */
void init (const char *filename);
};
/*----------------------------------------------------------------------------*/
void RGBNames::init (const char *filename)
{
FILE *fp;
char rawString [BIG_STRING_SIZE];
int red, green, blue;
char colorName [40];
int badLines = 0;
int totalLines = 0;
if ((fp = fopen (filename, "r")) == (FILE *) NULL) {
rgbtxtFileIsBeingUsed = 0;
return;
} /* fopen failed */
/* we found the file, so read it into the table.
* todo: check the file for integrity
*/
rgbtxtFileIsBeingUsed = 1;
tableSize = 0;
while (fgets (rawString, BIG_STRING_SIZE - 1, fp) != (char *) NULL) {
totalLines++;
rawString [strlen (rawString) - 1] = 0; /* strip linefeed */
if (extractRGBValuesAndColorName (rawString, &red, &green, &blue,
colorName)) {
rgbNameTable [tableSize].red = red;
rgbNameTable [tableSize].green = green;
rgbNameTable [tableSize].blue = blue;
strcpy (rgbNameTable [tableSize].name, colorName);
tableSize++;
} /* if good extraction -- no spaces in the color name */
else
badLines++;
} /* while not eof */
tolerance = 10;
fclose (fp);
} /* RGBNames::init */
/*----------------------------------------------------------------------------*/
RGBNames::RGBNames ()
{
rgbtxtFileIsBeingUsed = 0;
} /* RGBNames constructor */
/*----------------------------------------------------------------------------*/
RGBNames::RGBNames (const char *filename)
{
init (filename);
} /* RGBNames constructor */
/*----------------------------------------------------------------------------*/
char *RGBNames::lookupName (int red, int green, int blue)
/* return the name of the color with rgb values closest to those supplied
* in the parameter list. "closest" is the table entry with the smallest
* error: abs (redRequested - redInTable [i]) +
* abs (greenRequested - greenInTable [i]) +
* abs (blueRequested - blueInTable [i]) +
* this definition, and its implementation are hasty, brute force
* techniques. lots of improvement is possible...
*/
{
int exactlyMatchingEntry, exactMatch = 0;
int redError, greenError, blueError;
char hexColorName [20];
char temp [20];
if (rgbtxtFileIsBeingUsed) {
for (int i=0; i < tableSize; i++) {
redError = abs (red - rgbNameTable [i].red);
greenError = abs (green - rgbNameTable [i].green);
blueError = abs (blue - rgbNameTable [i].blue);
if (redError + greenError + blueError < tolerance) {
exactMatch = 1;
exactlyMatchingEntry = i;
break;
} /* if exact match */
} /* for i */
if (exactMatch)
return rgbNameTable [exactlyMatchingEntry].name;
} /* if rgbtxtFileIsBeingUsed */
/* either there's no rgb.txt file in use, or no exact match was found.
* so cobble together the hex value of the current rgb triplet:
*/
sprintf (temp, "%02x%02x%02x", red, green, blue);
strcpy (hexColorName, "#");
strcat (hexColorName, temp);
return hexColorName;
} /* RGBNames:: lookupName */
/*----------------------------------------------------------------------------*/
int extractRGBValuesAndColorName (char *rawString,
int *red, int *green, int *blue,
char *colorName)
/* X11 stores colors like this:
* 186 85 211 medium orchid
* 186 85 211 MediumOrchid
* here, we're only interested in the second form, in which the color
* name is one continous word, with now embedded blanks. extract the tokens
* from <rawString>, and figure out if there are blanks in the color name (by
* trying to extract a 5th token). return the values via the function
* arguments, and return the function's value
* 1: color name is only one word
* 0: more than one word
*/
{
static char *separators = " \t"; /* space and tab */
char *newToken;
int colorNameIsOnlyOneWord;
static int timesCalled = 0;
newToken = strtok (rawString, separators);
assert (newToken);
*red = atoi (newToken);
newToken = strtok ((char *) NULL, separators);
assert (newToken);
*green = atoi (newToken);
newToken = strtok ((char *) NULL, separators);
assert (newToken);
*blue = atoi (newToken);
newToken = strtok ((char *) NULL, separators);
assert (newToken);
strcpy (colorName, newToken);
if (strtok ((char *) NULL, separators))
colorNameIsOnlyOneWord = 0;
else
colorNameIsOnlyOneWord = 1;
return colorNameIsOnlyOneWord;
} /* extract rgb values and color names */
/*----------------------------------------------------------------------------*/
#ifdef EMBEDDED_TEST
/*------------------*/
int main (int, char **)
{
int red, green, blue;
char colorName [80];
RGBNames rgbLookupTable ("/usr/openwin/lib/rgb.txt");
while (1) {
printf ("enter rgb value (red green blue)\n");
scanf ("%d %d %d", &red, &green, &blue);
strcpy (colorName, rgbLookupTable.lookupName (red, green, blue));
printf ("best match color name for (%d, %d, %d): %s\n",
red, green, blue, colorName);
} /* while */
return 0;
} /* main */
/*----------------------------------------------------------------------------*/
#endif
<file_sep>/*
* planar figures
*/
#include "figureview.h"
#include "pacemaker.h"
#include "globals.h"
#include "glyphviewer.h"
#include "grabber.bm"
#include "grabberMask.bm"
#include <InterViews/Bitmaps/enlargeHit.bm>
#include <InterViews/Bitmaps/enlargeMask.bm>
#include <InterViews/Bitmaps/reducerHit.bm>
#include <InterViews/Bitmaps/reducerMask.bm>
#include <InterViews/bitmap.h>
#include <InterViews/canvas.h>
#include <InterViews/color.h>
#include <InterViews/cursor.h>
#include <InterViews/display.h>
#include <InterViews/event.h>
#include <InterViews/transformer.h>
#include <InterViews/window.h>
#include <IV-look/kit.h>
#include <IV-X11/xcanvas.h>
#include <OS/math.h>
#include <math.h>
#include <stdio.h>
static Cursor* zoom_in_cursor = nil;
static Cursor* zoom_out_cursor = nil;
static Cursor* grabber_cursor = nil;
static Cursor* window_cursor = nil;
static double zoom_factor = 600.0;
GrTarget::GrTarget(ViewIndex i, Graphic* t) {
_index = i;
_target = t;
}
ViewAction::ViewAction (Graphic* gr) {
_gr = gr;
}
Graphic* ViewAction::target () const {
return _gr;
}
boolean ViewAction::executable () const {
return false;
}
class Translator : public ViewAction {
public:
Translator(Graphic*, Coord, Coord);
virtual void execute();
virtual boolean executable() const;
protected:
Coord _lx, _ly;
};
Translator::Translator (
Graphic* gr, Coord lx, Coord ly
) : ViewAction(gr) {
_lx = lx;
_ly = ly;
}
void Translator::execute () {
_gr->translate(_lx, _ly);
}
boolean Translator::executable () const { return true; }
class Scaler : public ViewAction {
public:
Scaler(Graphic*, Coord, Coord, Coord, Coord);
virtual void execute();
virtual boolean executable() const;
protected:
Coord _cx, _cy, _sx, _sy;
};
Scaler::Scaler (
Graphic* gr, Coord sx, Coord sy, Coord cx, Coord cy
) : ViewAction(gr) {
_sx = sx;
_sy = sy;
_cx = cx;
_cy = cy;
}
void Scaler::execute () {
_gr->scale(_sx, _sy, _cx, _cy);
}
boolean Scaler::executable () const { return true; }
class Rotator : public ViewAction {
public:
Rotator(Graphic*, Coord, Coord, Coord);
virtual void execute();
virtual boolean executable() const;
protected:
Coord _cx, _cy, _angle;
};
Rotator::Rotator (
Graphic* gr, Coord angle, Coord cx, Coord cy
) : ViewAction(gr) {
_angle = angle;
_cx = cx;
_cy = cy;
}
void Rotator::execute () {
_gr->rotate(_angle, _cx, _cy);
}
boolean Rotator::executable () const { return true; }
static void initcursors() {
if (zoom_in_cursor == nil) {
Bitmap* zoom_in = new Bitmap(
enlarger_hit_bits, enlarger_hit_width, enlarger_hit_height,
enlarger_hit_x_hot, enlarger_hit_y_hot
);
Bitmap* zoom_in_mask = new Bitmap(
enlarger_mask_bits, enlarger_mask_width, enlarger_mask_height,
enlarger_mask_x_hot, enlarger_mask_y_hot
);
Bitmap* zoom_out = new Bitmap(
reducer_hit_bits, reducer_hit_width, reducer_hit_height,
reducer_hit_x_hot, reducer_hit_y_hot
);
Bitmap* zoom_out_mask = new Bitmap(
reducer_mask_bits, reducer_mask_width, reducer_mask_height,
reducer_mask_x_hot, reducer_mask_y_hot
);
zoom_in_cursor = new Cursor(zoom_in, zoom_in_mask);
zoom_out_cursor = new Cursor(zoom_out, zoom_out_mask);
Bitmap* grabber = new Bitmap(
grabber_bits, grabber_width, grabber_height,
grabber_x_hot, grabber_y_hot
);
Bitmap* grabber_mask = new Bitmap(
grabberMask_bits, grabberMask_width, grabberMask_height,
grabberMask_x_hot, grabberMask_y_hot
);
grabber_cursor = new Cursor(grabber, grabber_mask);
}
}
static void initviews (GrView* pv) {
Graphic* p = pv->getgraphic();
if (p != nil) {
ViewIndex p_count = p->count_();
for (ViewIndex i = 0; i < p_count; i++) {
Graphic* c = p->child_(i);
if (c->count_() > 0) {
GrView* cv = new PolyView(c);
pv->append(cv);
//initviews(cv);
} else {
GrView* cv = new GrView(c);
pv->append(cv);
}
}
}
}
GrView::GrView (Graphic* gr) {
_gr = gr;
Resource::ref(_gr);
_index = 0;
}
GrView::~GrView () {
Resource::unref(_gr);
}
Graphic* GrView::getgraphic () const {
return _gr;
}
void GrView::setgraphic (Graphic* gr) {
Resource::ref(gr);
Resource::unref(_gr);
_gr = gr;
}
void GrView::setindex (ViewIndex i) {
_index = i;
}
ViewIndex GrView::getindex () const {
return _index;
}
boolean GrView::grasp (const Event& e, Tool& tool, ViewAction*& action) {
action = nil;
ToolState& ts = tool.toolstate();
ts._init = e;
ts._last = e;
Graphic* gr = getgraphic();
gr->getbounds(ts._l, ts._b, ts._r, ts._t);
if (tool.tool() == Tool::scale) {
Coord lx, ly;
Coord cx, cy;
lx = e.pointer_x();
ly = e.pointer_y();
cx = (ts._l + ts._r)/2.0;
cy = (ts._b + ts._t)/2.0;
action = new Scaler(
gr, Math::abs((lx-cx)*2.0/(ts._r-ts._l)),
Math::abs((ly-cy)*2.0/(ts._t-ts._b)),
cx, cy
);
action->ref();
}
return true;
}
boolean GrView::manipulating (
const Event& e, Tool& tool, ViewAction*& action
) {
action = nil;
if (e.type() == Event::up) {
return false;
} else {
unsigned int tool_type = tool.tool();
ToolState& ts = tool.toolstate();
if (tool_type != Tool::nop) {
float pi = 3.14159;
Graphic* gr = getgraphic();
Transformer* tx = ts._gs.transformer();
Coord x, y, lx, ly;
x = ts._last.pointer_x();
y = ts._last.pointer_y();
lx = e.pointer_x();
ly = e.pointer_y();
switch(tool_type) {
case Tool::select:
break;
case Tool::move:
{
if (tx != nil) {
tx->inverse_transform(lx, ly);
tx->inverse_transform(x, y);
}
ts._last = e;
action = new Translator(gr, lx-x, ly-y);
action->ref();
}
break;
case Tool::scale:
{
Coord cx, cy;
cx = (ts._l + ts._r)/2.0;
cy = (ts._b + ts._t)/2.0;
ts._last = e;
action = new Scaler(
gr, (lx-cx)/(x-cx), (ly-cy)/(y-cy), cx, cy
);
action->ref();
}
break;
case Tool::rotate:
{
Coord cx, cy;
cx = (ts._l + ts._r)/2.0;
cy = (ts._b + ts._t)/2.0;
float ldy = ly-cy; float ldx = lx-cx;
float dy = y-cy; float dx = x-cx;
float cur = atan(ldy/ldx)/pi*180.0;
float last = atan(dy/dx)/pi*180.0;
if (ldx < 0.0) {
cur += 180.0;
}
if (dx < 0.0) {
last += 180.0;
}
ts._last = e;
action = new Rotator(gr, cur-last, cx, cy);
action->ref();
}
break;
}
}
}
return true;
}
void GrView::effect (const Event&, Tool&, ViewAction*& action) {
action = nil;
}
void GrView::append(GrView*) {}
void GrView::prepend(GrView*) {}
void GrView::insert(ViewIndex, GrView*) {}
void GrView::remove(ViewIndex) {}
void GrView::remove(GrView*) {}
ViewIndex GrView::count () const { return 0; }
GrView* GrView::child (ViewIndex) const { return nil; }
/************************************************************************/
declarePtrList(GrViewList, GrView);
implementPtrList(GrViewList, GrView);
PolyView::PolyView (Graphic* gr) : GrView (gr) {
_body = new GrViewList;
}
PolyView::~PolyView () {
ViewIndex count = _body->count();
for (ViewIndex i = 0; i < count; i++) {
GrView* grview = _body->item(i);
delete grview;
}
delete _body;
_gr->remove_all_();
}
void PolyView::append (GrView* g) {
_body->append(g);
g->setindex(count()-1);
}
void PolyView::prepend (GrView* g) {
insert(0, g);
}
void PolyView::insert (ViewIndex i, GrView* g) {
_body->insert(i, g);
for (ViewIndex j = i; j < count(); j++) {
child(j)->setindex(j);
}
}
void PolyView::remove (ViewIndex i) {
_body->remove(i);
for (ViewIndex j = i; j < count(); j++) {
child(j)->setindex(j);
}
}
void PolyView::remove (GrView* gr) {
ViewIndex count = _body->count();
for (int i = 0; i < count; i++) {
if (child(i) == gr) {
remove(i);
break;
}
}
}
ViewIndex PolyView::count () const { return _body->count(); }
GrView* PolyView::child (ViewIndex i) const {
return _body->item(i);
}
/**********************************************************************/
implementList(TargetList,GrTarget);
RootView::RootView (
RootGraphic* rootgr, Graphic* gr, const Color* bg, GlyphViewer* gviewer
) : PolyView(gr) {
_gviewer = gviewer;
_targets = new TargetList(5);
_bg = bg;
Resource::ref(_bg);
_rootgr = rootgr;
if (_rootgr == nil) {
_rootgr = new RootGraphic(nil, _bg);
_rootgr->ref();
}
if (gr == nil) {
setgraphic(new PolyGraphic);
}
_lx = _ly = 0.0;
initcursors();
}
RootView::~RootView () {
_rootgr->remove_(getgraphic());
delete _targets;
Resource::unref(_rootgr);
Resource::unref(_bg);
}
void RootView::setgraphic (Graphic* gr) {
if (gr == nil) {
gr = new PolyGraphic;
}
Graphic* orig = getgraphic();
if (gr != orig) {
if (orig != nil) {
_rootgr->remove_(orig);
}
ViewIndex count = _body->count();
for (ViewIndex i = 0; i < count; i++) {
GrView* grview = _body->item(i);
delete grview;
}
_body->remove_all();
PolyView::setgraphic(gr);
initviews(this);
_rootgr->append_(gr);
_rootgr->undraw();
}
}
void RootView::background(const Color* bg) {
if (bg != nil) {
Resource::ref(bg);
}
if (_bg != nil) {
Resource::unref(_bg);
}
_bg = bg;
_rootgr->background(bg);
}
boolean RootView::grasp (const Event& e, Tool& tool, ViewAction*& action) {
action = nil;
Window* w = e.window();
if (window_cursor == nil) {
window_cursor = w->cursor();
}
Graphic* target;
boolean flag = true;
float tol = 2.0;
unsigned int tool_type = tool.tool();
Graphic* gr = getgraphic();
WidgetKit* kit = WidgetKit::instance();
switch (tool_type) {
case Tool::select:
break;
case Tool::rate_scroll:
{
w->cursor(kit->ufast_cursor());
_lx = e.pointer_x();
_ly = e.pointer_y();
GrTarget sel(-1, getgraphic());
_targets->append(sel);
}
break;
case Tool::grab_scroll:
{
w->cursor(kit->hand_cursor());
_lx = e.pointer_x();
_ly = e.pointer_y();
GrTarget sel(-1, getgraphic());
_targets->append(sel);
}
break;
case Tool::rate_zoom:
{
w->cursor(zoom_in_cursor);
_lx = e.pointer_x();
_ly = e.pointer_y();
GrTarget sel(-1, getgraphic());
_targets->append(sel);
}
break;
case Tool::move:
case Tool::scale:
case Tool::rotate:
{
BoxObj ibox(
e.pointer_x()-tol, e.pointer_y()-tol,
e.pointer_x()+tol, e.pointer_y()+tol
);
long index = gr->last_intersecting(ibox, target);
if (target != nil) {
target->alpha_stroke(false); //hack
target->alpha_fill(false); //hack
Window* w = e.window();
Canvas* c = w->canvas();
w->cursor(grabber_cursor);
ToolState& ts = tool.toolstate();
gr->total_gs(ts._gs);
ViewAction* kidact = nil;
flag = child(index)->grasp(e, tool, kidact);
action = kidact;
GrTarget sel(index, target);
_targets->append(sel);
}
}
break;
}
return flag;
}
boolean RootView::manipulating (
const Event& e, Tool& tool, ViewAction*& action
) {
action = nil;
boolean flag = true;
ViewIndex count = _targets->count();
Window* w = e.window();
WidgetKit* kit = WidgetKit::instance();
Graphic* gr = getgraphic();
unsigned int tool_type = tool.tool();
switch (tool_type) {
case Tool::select:
case Tool::narrow:
if (e.type() == Event::up) {
flag = false;
}
break;
case Tool::rate_scroll:
{
if (e.type() == Event::up) {
flag = false;
} else {
Coord dx = _lx - e.pointer_x();
Coord dy = _ly - e.pointer_y();
if (dx != 0.0 && dy != 0.0) {
double angle = atan2(dy, dx)*180/M_PI;
if (angle < -157.5) {
w->cursor(kit->rfast_cursor());
} else if (angle < -112.5) {
w->cursor(kit->rufast_cursor());
} else if (angle < -67.5) {
w->cursor(kit->ufast_cursor());
} else if (angle < -22.5) {
w->cursor(kit->lufast_cursor());
} else if (angle < 22.5) {
w->cursor(kit->lfast_cursor());
} else if (angle < 67.5) {
w->cursor(kit->ldfast_cursor());
} else if (angle < 112.5) {
w->cursor(kit->dfast_cursor());
} else if (angle < 157.5) {
w->cursor(kit->rdfast_cursor());
} else {
w->cursor(kit->rfast_cursor());
}
}
action = new Translator(gr, dx, dy);
action->ref();
}
}
break;
case Tool::grab_scroll:
{
if (e.type() == Event::up) {
flag = false;
} else {
Coord dx = e.pointer_x() - _lx;
Coord dy = e.pointer_y() - _ly;
if (dx != 0.0 || dy != 0.0) {
action = new Translator(gr, dx, dy);
action->ref();
_lx = e.pointer_x();
_ly = e.pointer_y();
}
}
}
break;
case Tool::rate_zoom:
{
if (e.type() == Event::up) {
flag = false;
} else {
Coord dx = 0.0;
Coord dy = _ly - e.pointer_y();
if (dy != 0.0) {
double factor;
if (dy > 0.0) {
w->cursor(zoom_out_cursor);
factor = zoom_factor/(zoom_factor+dy);
} else {
w->cursor(zoom_in_cursor);
factor = (zoom_factor-dy)/zoom_factor;
}
action = new Scaler(gr, factor, factor, _lx, _ly);
action->ref();
}
}
}
break;
default:
{
ViewAction* kidact = nil;
for (ViewIndex i = 0; i < count && flag; i++) {
ViewIndex index = _targets->item_ref(i)._index;
flag = child(index)->manipulating(e, tool, kidact);
}
action = kidact;
}
break;
}
return flag;
}
void RootView::effect (const Event& e, Tool& tool, ViewAction*& action) {
action = nil;
Window* w = e.window();
if (w != nil) {
w->cursor(window_cursor);
Canvas* c = w->canvas();
ViewIndex count = _targets->count();
Graphic* gr = getgraphic();
ViewAction* kidact = nil;
for (ViewIndex i = 0; i < count; i++) {
ViewIndex index = _targets->item_ref(i)._index;
if (index >= 0) {
child(index)->effect(e, tool, kidact);
//gr->child_(index)->flush();
}
}
action = kidact;
_targets->remove_all();
}
}
Tool::Tool (unsigned int cur_tool) {
_cur_tool = cur_tool;
_toolstate = new ToolState;
}
Tool::~Tool () {
delete _toolstate;
}
unsigned int Tool::tool () { return _cur_tool; }
void Tool::tool (unsigned int cur_tool) { _cur_tool = cur_tool; }
void Tool::reset () {
delete _toolstate;
_toolstate = new ToolState;
}
ToolState& Tool::toolstate () { return *_toolstate; }
void Tool::toolstate(ToolState* toolstate) {
delete _toolstate;
_toolstate = toolstate;
}
<file_sep>#include <InterViews/canvas.h>
#include <InterViews/color.h>
#include <InterViews/display.h>
#include <InterViews/event.h>
#include <InterViews/handler.h>
#include <InterViews/hit.h>
#include <InterViews/polyglyph.h>
#include <InterViews/session.h>
#include <InterViews/target.h>
#include <InterViews/transformer.h>
#include <InterViews/window.h>
#include <OS/list.h>
#include <InterViews/brush.h>
#include <IV-X11/xevent.h>
#include <IV-X11/xcanvas.h>
#include <sys/time.h>
#include <math.h>
#include <stdio.h>
#include "figure.h"
#include "figureview.h"
#include "globals.h"
#include "glyphviewer.h"
#include "pacer.h"
#include "pacemaker.h"
#include "pacekeeper.h"
#include "gcollector.h"
static const long LEVELS = 6;
static long count_leaves (Pacer* p) {
long count = 0;
if (p->count() > 0) {
for (long i = 0; i < p->count(); i++) {
Pacer* kid = p->child(i);
count += count_leaves(kid);
}
} else {
count = 1;
}
return count;
}
static long inc;
static long cur_inc;
static long cur_level;
static void RecurAutoGrade(Pacer* p) {
if (p->count() > 0) {
for (long i = 0; i < p->count(); i++) {
Pacer* kid = p->child(i);
RecurAutoGrade(kid);
}
} else {
cur_inc--;
if (cur_inc < 0) {
cur_inc = inc;
if (cur_level > 0) {
cur_level--;
}
}
GraphicPacer* gp = (GraphicPacer*) p;
gp->set_grades(0, cur_level);
}
}
static void AutoGrade (Pacer* p) {
long count = count_leaves(p);
cur_level = LEVELS-1;
inc = count/LEVELS;
cur_inc = count/LEVELS;
RecurAutoGrade(p);
}
static Pacer* CreatePacers(Canvas* c, Graphic* gr) {
Pacer* d;
if (gr->count_() > 0) {
d = new Grader(new Distributor);
for (GlyphIndex i = 0; i < gr->count_(); i++) {
d->append(CreatePacers(c, gr->child_(i)));
}
} else {
d = new GraphicPacer(c, gr);
}
return d;
}
static BoxObj allot;
static void effect (ViewAction* action, BoxObj& box) {
Graphic* gr;
Coord l, b, r, t;
gr = action->target();
gr->getbounds(l, b, r, t);
BoxObj before(l, b, r, t);
action->execute();
gr->getbounds(l, b, r, t);
BoxObj after(l, b, r, t);
box = before+after;
box = allot-box;
// a hack to get around xor dudus
Coord pad = 5.0;
box._l -= pad;
box._b -= pad;
box._r += pad;
box._t += pad;
}
class ClearAction : public Action {
public:
ClearAction();
virtual void execute();
};
ClearAction::ClearAction () {}
void ClearAction::execute () { GraphicPacer::clear(); }
class ContAction : public Action {
public:
ContAction(ViewAction*, Pacer*);
virtual ~ContAction();
virtual void execute();
protected:
ViewAction* _vaction;
Pacer* _pacer;
};
ContAction::ContAction (
ViewAction* vaction, Pacer* pacer
) {
_vaction = vaction;
Resource::ref(_vaction);
_pacer = pacer;
}
ContAction::~ContAction () {
Resource::unref(_vaction);
}
void ContAction::execute () {
BoxObj box;
if (_vaction != nil) {
effect(_vaction, box);
for (long i = 0; i < _pacer->count(); i++) {
FCGraphicPacer* fc = (FCGraphicPacer*) _pacer->child(i);
fc->incur(box);
}
}
}
class FullFixer : public GraphicPacer {
public:
FullFixer(Canvas* c, Graphic* _gr, const Color* fill);
virtual void set_graphic(Graphic*);
void set_clipped (BoxObj&);
virtual void play(RunTime&);
protected:
void xor();
protected:
BoxObj _allot;
const Color* _fill;
Color* _color;
Brush* _brush;
BoxObj _box;
Transformer* _t;
boolean _drawn;
};
inline void FullFixer::set_clipped(BoxObj& allot) { _allot = allot; }
FullFixer::FullFixer (
Canvas* c, Graphic* gr, const Color* fill
) : GraphicPacer (c, gr) {
_fill = fill;
Resource::ref(_fill);
_color = new Color(*fill, 1.0, Color::Xor);
_color->ref();
_brush = new Brush(0.0);
_brush->ref();
_drawn = false;
set_graphic(gr);
}
void FullFixer::set_graphic(Graphic* gr) {
GraphicPacer::set_graphic(gr);
_t = new Transformer;
_gr->eqv_transformer(*_t);
_gr->getbounds(_box._l, _box._b, _box._r, _box._t);
_t->inverse_transform(_box._l, _box._b);
_t->inverse_transform(_box._r, _box._t);
}
void FullFixer::xor () {
boolean doit = false;
if (!_drawn) {
_drawn = true;
doit = true;
} else {
doit = true;
_drawn = false;
}
if (doit) {
_canvas->push_clipping();
_canvas->clip_rect(_allot._l, _allot._b, _allot._r, _allot._t);
_canvas->front_buffer();
_canvas->push_transform();
_canvas->transform(*_t);
_canvas->rect(
_box._l, _box._b, _box._r, _box._t, _color, _brush
);
_canvas->pop_transform();
_canvas->pop_clipping();
_canvas->back_buffer();
}
}
void FullFixer::play (RunTime&) {
/*
CanvasRep* crep = _canvas->rep();
BoxObj box = _allot-_damage;
_canvas->damage(box._l, box._b, box._r, box._t);
crep->start_repair();
//_canvas->fill_rect(_damage._l, _damage._b, _damage._r, _damage._t, _fill);
//_gr->drawclipped(_canvas,_damage._l, _damage._b, _damage._r, _damage._t);
_gr->alpha_fill(true);
_gr->alpha_stroke(true);
_gr->drawclipped(_canvas,_damage._l, _damage._b, _damage._r, _damage._t);
_gr->alpha_fill(false);
_gr->alpha_stroke(false);
*/
if (_drawn) {
xor();
_drawn = false;
}
_gr->eqv_transformer(*_t);
xor();
GraphicPacer::clear();
}
class GlyphGrabber : public Handler {
public:
GlyphGrabber(GlyphViewer*, Graphic* master);
virtual ~GlyphGrabber();
virtual boolean event(Event&);
protected:
boolean _busy;
int _orig_tool;
PaceMaker* _pmaker;
PaceKeeper* _contkeeper;
PaceKeeper* _ekeeper;
PaceKeeper* _dampedkeeper;
PaceKeeper* _pckeeper;
PaceKeeper* _cohkeeper;
GlyphViewer* _gviewer;
Graphic* _master;
UIScheduler* _ui;
ActionPacer* _view0;
Grader* _gp00;
Grader* _view1;
ActionPacer* _action;
Clipper* _clipper10;
Clipper* _clipper11;
Repairer* _fixer;
Repairer* _filler;
SelectPacer* _selector;
Grader* _gp10;
Grader* _gp11;
boolean _continue;
boolean _control_is_down;
XorPacer* _xor;
};
GlyphGrabber::GlyphGrabber (GlyphViewer* gviewer, Graphic* master) {
_gviewer = gviewer;
_busy = false;
_orig_tool = -1;
_master = master;
Resource::ref(_master);
const Color* bg = gviewer->getroot()->background();
Canvas* canvas = gviewer->canvas();
_ui = new UIScheduler(new DragMapper);
_view0 = new ActionPacer;
_gp00 = new Grader(new Tiler);
_view0->set_kid(_gp00);
for (long i = 0; i < _master->count_(); i++) {
_gp00->append(new FCGraphicPacer(canvas, _master->child_(i), bg));
}
_view1 = new Grader(new Tiler);
_fixer = new Fixer(canvas, _master->child_(0));
_filler = new Filler(canvas, _master->child_(0), bg);
_action = new ActionPacer(nil, new ClearAction);
_selector = new SelectPacer(canvas, _master);
_selector->set_damaged(&GraphicPacer::damaged_area());
_clipper10 = new Clipper(canvas, &_fixer->damaged_area());
_clipper11 = new Clipper(canvas, &GraphicPacer::damaged_area());
_gp10 = new Grader(new Normalizer);
_gp11 = new Grader(new Tiler);
_view1->append(_clipper10);
_clipper10->set_kid(_action);
_action->set_kid(_gp10);
_gp10->append(_filler);
_gp10->append(_fixer);
_view1->append(_selector);
_selector->set_kid(_clipper11);
_clipper11->set_kid(_gp11);
_xor = new XorPacer(canvas, nil, bg);
//_view1->append(_xor);
_contkeeper = new Continuator(_ui);
_ekeeper = new EventKeeper(_ui);
_dampedkeeper = new DampedKeeper(_ui);
_pckeeper = new PCKeeper(_ui);
_cohkeeper = new CoherenceKeeper(_ui);
_pmaker = new PaceMaker(_cohkeeper);
}
GlyphGrabber::~GlyphGrabber () {
Resource::unref(_master);
_ui->set_kid(nil);
delete _ui;
delete _contkeeper;
delete _ekeeper;
delete _dampedkeeper;
delete _pckeeper;
delete _cohkeeper;
delete _view0;
delete _view1;
}
class SelGraphic : public PolyGraphic {
public:
SelGraphic();
virtual void append_(Graphic*);
virtual void prepend_(Graphic*);
virtual void insert_(GlyphIndex, Graphic*);
virtual void remove_(GlyphIndex);
virtual void remove_(Graphic*);
virtual void replace_(GlyphIndex, Graphic*);
};
SelGraphic::SelGraphic() {}
void SelGraphic::append_ (Graphic* g) {
_body->append(g);
}
void SelGraphic::prepend_ (Graphic* g) {
_body->prepend(g);
}
void SelGraphic::insert_ (GlyphIndex i, Graphic* g) {
_body->insert(i, g);
}
void SelGraphic::remove_ (GlyphIndex i) {
_body->remove(i);
}
void SelGraphic::remove_ (Graphic* gr) {
PolyGraphic::remove_(gr);
}
void SelGraphic::replace_ (GlyphIndex i, Graphic* g) {
_body->replace(i, g);
}
boolean GlyphGrabber::event (Event& e) {
RootView* rv = _gviewer->getroot();
Canvas* canvas = _gviewer->canvas();
const Allocation& a = _gviewer->allocation();
if (e.type() == Event::down && !_busy) {
_busy = true;
Display* d = e.display();
Canvas* c = e.window()->canvas();
d->grab(e.window(), this);
_orig_tool = -1;
ViewAction* action = nil;
BoxObj box(a.left(), a.bottom(), a.right(), a.top());
Tool& tool = _gviewer->tool();
_control_is_down = e.control_is_down();
if (_control_is_down) {
_ui->set_kid(_view0);
for (long i = 0; i < _gp00->count(); i++) {
FCGraphicPacer* fc = (FCGraphicPacer*) _gp00->child(i);
fc->set_clipped(box);
}
e.poll();
_orig_tool = tool.tool();
if (e.left_is_down()) {
tool.tool(Tool::rate_scroll);
_ui->set_mapper(new ContMapper);
_continue = rv->grasp(e, tool, action);
_view0->set_before(
new ContAction(action, _gp00)
);
} else if (e.middle_is_down()) {
tool.tool(Tool::grab_scroll);
_continue = rv->grasp(e, tool, action);
_ui->set_mapper(new DragMapper);
_view0->set_before(nil);
} else if (e.right_is_down()) {
tool.tool(Tool::rate_zoom);
_continue = rv->grasp(e, tool, action);
ContMapper* mapper = new ContMapper;
mapper->set_dimension(Cont_Y);
_ui->set_mapper(mapper);
_view0->set_before(
new ContAction(action, _gp00)
);
}
} else {
_ui->set_kid(_view1);
_ui->set_mapper(new DragMapper);
_clipper10->set_clipped(box);
_clipper11->set_clipped(box);
_selector->set_clipped(box);
_continue = rv->grasp(e, tool, action);
}
_ui->cur_event(e);
if (_continue && action != nil) {
BoxObj box;
if (action->executable()) {
effect(action, box);
if (_control_is_down) {
for (long i = 0; i < _gp00->count(); i++) {
FCGraphicPacer* fc =
(FCGraphicPacer*) _gp00->child(i);
fc->incur(box);
}
} else {
GraphicPacer::incur(box);
_fixer->incur(box);
_filler->incur(box);
}
}
}
if (!_control_is_down) {
_gp11->delete_all();
const TargetList* t = rv->cur_targets();
long count = t->count();
if (count == 1 && t->item_ref(0)._target == rv->getgraphic()) {
/* not supported */
} else {
if (count == 1) {
for (long i = 0; i < _master->count_(); i++) {
Graphic* sel = _master->child_(i)->child_(
t->item_ref(0)._index
);
_gp11->append(new GraphicPacer(canvas, sel));
}
Graphic* sel = _master->child_(0)->child_(
t->item_ref(0)._index
);
//_xor->set_clipped(box);
//_xor->set_graphic(sel);
} else {
/* not supported */
}
}
}
_ui->regrade();
switch(_gviewer->get_policy()) {
case PaceKeeper::NoPK:
_pmaker->set_pacekeeper(_contkeeper);
break;
case PaceKeeper::EDriven:
_pmaker->set_pacekeeper(_ekeeper);
break;
case PaceKeeper::DampedOsc:
_pmaker->set_pacekeeper(_dampedkeeper);
break;
case PaceKeeper::PC:
_pmaker->set_pacekeeper(_pckeeper);
break;
case PaceKeeper::Coh:
_pmaker->set_pacekeeper(_cohkeeper);
break;
default:
_pmaker->set_pacekeeper(_cohkeeper);
break;
}
_pmaker->startall();
} else if (e.type() == Event::up && _busy) {
_busy = false;
Display* d = e.display();
d->ungrab(this);
Canvas* c = e.window()->canvas();
if (_continue) {
ViewAction* action = nil;
rv->effect(e, _gviewer->tool(), action);
if (action != nil) {
BoxObj box;
if (action->executable()) {
effect(action, box);
if (_control_is_down) {
for (long i = 0; i < _gp00->count(); i++) {
FCGraphicPacer* fc =
(FCGraphicPacer*) _gp00->child(i);
fc->incur(box);
}
} else {
GraphicPacer::incur(box);
_fixer->incur(box);
_filler->incur(box);
//_xor->incur(box);
}
}
action->unref();
}
}
_ui->cur_event(e);
d->ungrab(this);
_pmaker->stopall();
Canvas* canvas = _gviewer->canvas();
canvas->damage_all();
const Allocation& a = _gviewer->allocation();
canvas->fill_rect(
a.left(), a.bottom(), a.right(), a.top(),
_gviewer->getroot()->background()
);
_gviewer->getroot()->getgraphic()->draw(canvas, a);
_fixer->clear();
_filler->clear();
GraphicPacer::clear();
for (long i = 0; i < _gp00->count(); i++) {
FCGraphicPacer* fc = (FCGraphicPacer*) _gp00->child(i);
fc->clear();
}
if (_orig_tool >= 0) {
Tool& tool = _gviewer->tool();
tool.tool(_orig_tool);
_orig_tool = -1;
}
} else if (_busy) {
if (_continue) {
Canvas* c = e.window()->canvas();
ViewAction* action = nil;
_continue = rv->manipulating(e, _gviewer->tool(), action);
if (action != nil) {
if (action->executable()) {
BoxObj box;
effect(action, box);
if (_control_is_down) {
for (long i = 0; i < _gp00->count(); i++) {
FCGraphicPacer* fc =
(FCGraphicPacer*) _gp00->child(i);
fc->incur(box);
}
} else {
GraphicPacer::incur(box);
_fixer->incur(box);
_filler->incur(box);
//_xor->incur(box);
}
}
Tool& tool = _gviewer->tool();
if (_control_is_down && tool.tool() != Tool::grab_scroll) {
_view0->set_before(
new ContAction(action, _gp00)
);
}
action->unref();
}
_ui->cur_event(e);
}
}
return true;
}
GlyphViewer::GlyphViewer(
float w, float h
) : MonoGlyph(nil) {
_canvas = nil;
_root = new RootView;
_root->ref();
_root->viewer(this);
_root->background(new Color(1.0, 1.0, 1.0, 1.0));
_width = w;
_height = h;
_grabber = nil;
body(new Target(_root->getrootgr(),TargetAlwaysHit));
initshape();
initgraphic();
}
GlyphViewer::~GlyphViewer () {
_grabber->unref();
_root->unref();
}
Tool& GlyphViewer::tool () {
return _tool;
}
void GlyphViewer::set_policy (unsigned int policy) {
_policy = policy;
}
unsigned int GlyphViewer::get_policy () {
return _policy;
}
RootView* GlyphViewer::getroot () { return _root; }
void GlyphViewer::setrootgr (Graphic* root) {
if (root != _root->getgraphic()) {
Extension ext;
Allocation a;
_master = root;
if (_master->count_() > 0) {
_root->setgraphic(root->child_(0));
} else {
_root->setgraphic(nil);
}
root = _root->getrootgr();
root->transformer(nil);
body(new Target(root, TargetAlwaysHit));
initgraphic();
Canvas* c = canvas();
if (c != nil) {
Requisition req;
root->request(req);
root->allocate(c, _a, ext);
}
Resource::unref(_grabber);
if (_master->count_() > 0) {
_grabber = new GlyphGrabber(this, _master);
} else {
_grabber = nil;
}
Resource::ref(_grabber);
}
}
void GlyphViewer::initshape () {
if (_width < -0.5 && _height < -0.5) {
Coord l, b, r, t;
_root->getgraphic()->getbounds(l, b, r, t);
_width = r - l;
_height = t - b;
}
Allotment& ax = _a.x_allotment();
Allotment& ay = _a.y_allotment();
ax.span(_width);
ay.span(_height);
}
void GlyphViewer::initgraphic () {
Coord l, b, r, t;
_root->getgraphic()->getbounds(l, b, r, t);
_root->getgraphic()->translate(-l-(r-l)/2.0, -b-(t-b)/2.0);
/*
if (_master->count_() > 0) {
Graphic* ref = _master->child_(0);
for (long i = 1; i < _master->count_(); i++) {
ref->align(Center, _master->child_(i), Center);
}
}
*/
Canvas* c = canvas();
if (c != nil) {
c->damage_all();
}
}
void GlyphViewer::allocate(Canvas* c, const Allocation& a, Extension& ext) {
_canvas = c;
_a = a;
allot._l = _a.left();
allot._b = _a.bottom();
allot._r = _a.right();
allot._t = _a.top();
MonoGlyph::allocate(c, a, ext);
ext.merge(c, a);
}
void GlyphViewer::request(Requisition& req) const {
Requirement& rx = req.x_requirement();
rx.natural(_width);
rx.stretch(fil);
rx.shrink(_width);
rx.alignment(0.0);
Requirement& ry = req.y_requirement();
ry.natural(_height);
ry.stretch(fil);
ry.shrink(0.0);
ry.alignment(0.0);
}
void GlyphViewer::draw(Canvas* c, const Allocation& a) const {
_root->getrootgr()->draw(c, a);
}
void GlyphViewer::pick(Canvas* c, const Allocation& a, int depth, Hit& h) {
const Event* e = h.event();
if (e->type() == Event::down && _grabber != nil) {
h.begin(depth, this, 0, _grabber);
MonoGlyph::pick(c, a, depth, h);
h.end();
}
}
<file_sep>#include "globals.h"
#include <OS/math.h>
implementPtrList(PacerList, Pacer);
implementPtrList(SchedulerList, Scheduler);
FadeType fadetype (Grade cur, Grade fut, Grade low, Grade high) {
if (cur != fut) {
if (cur >= low && fut < low) {
return fadeout_low;
} else if (cur < low && fut >= low) {
return fadein_low;
} else if (cur > high && fut <= high) {
return fadein_high;
} else if (cur <= high && fut > high) {
return fadeout_high;
} else if (cur >= low && cur <= high && fut >= low && fut <= high) {
return sustain;
} else {
return no_fade;
}
} else if (cur >= low && cur <= high) {
return sustain;
} else {
return no_fade;
}
}
/*****************************************************************************/
static const int NUMPOINTS = 200; // must be > 1
static const double SMOOTHNESS = 1.0;
static int mlsize = 0;
static int mlcount = 0;
static Coord* mlx, *mly;
/**********************************************************/
RunTime::RunTime () {
_cur_grade = -1;
_fut_grade = -1;
_sec = -1;
_usec = -1;
_period = -1;
_id = -10000;
}
/**********************************************************/
TimeSlice::TimeSlice (USec nat, USec str, USec shr) {
_nat = nat;
_str = str;
_shr = shr;
}
TimeSlice::TimeSlice (const TimeSlice& s) {
_nat = s._nat;
_str = s._str;
_shr = s._shr;
}
TimeSlice& TimeSlice::operator = (const TimeSlice& s) {
_nat = s._nat;
_str = s._str;
_shr = s._shr;
return *this;
}
boolean TimeSlice::operator == (const TimeSlice& s) {
return (_nat == s._nat && _str == s._str && _shr == s._shr);
}
boolean TimeSlice::operator != (const TimeSlice& s) {
return (_nat != s._nat || _str != s._str || _shr != s._shr);
}
USec TimeSlice::min () { return (_nat-_shr); }
USec TimeSlice::max () { return (_nat+_str); }
/*****************************************************************************/
PointObj::PointObj (Coord x, Coord y) { _x = x; _y = y; }
PointObj::PointObj (PointObj* p) { _x = p->_x; _y = p->_y; }
float PointObj::Distance (PointObj& p) {
return sqrt(float(square(_x - p._x) + square(_y - p._y)));
}
/*****************************************************************************/
LineObj::LineObj (Coord x0, Coord y0, Coord x1, Coord y1) {
_p1._x = x0; _p1._y = y0; _p2._x = x1; _p2._y = y1;
}
LineObj::LineObj (LineObj* l) {
_p1._x = l->_p1._x; _p1._y = l->_p1._y;
_p2._x = l->_p2._x; _p2._y = l->_p2._y;
}
boolean LineObj::Contains (PointObj& p) {
return
(p._x >= min(_p1._x, _p2._x)) && (p._x <= max(_p1._x, _p2._x)) &&
(p._y >= min(_p1._y, _p2._y)) && (p._y <= max(_p1._y, _p2._y)) && (
(p._y - _p1._y)*(_p2._x - _p1._x) -
(_p2._y - _p1._y)*(p._x - _p1._x)
) == 0;
}
inline int signum (int a) {
if (a < 0) {
return -1;
} else if (a > 0) {
return 1;
} else {
return 0;
}
}
int LineObj::Same (PointObj& p1, PointObj& p2) {
Coord dx, dx1, dx2;
Coord dy, dy1, dy2;
dx = _p2._x - _p1._x;
dy = _p2._y - _p1._y;
dx1 = p1._x - _p1._x;
dy1 = p1._y - _p1._y;
dx2 = p2._x - _p2._x;
dy2 = p2._y - _p2._y;
return signum((int)(dx*dy1 - dy*dx1)) * signum((int)(dx*dy2 - dy*dx2));
}
boolean LineObj::Intersects (LineObj& l) { // from Sedgewick, p. 313
BoxObj b1 (_p1._x, _p1._y, _p2._x, _p2._y);
BoxObj b2 (l._p1._x, l._p1._y, l._p2._x, l._p2._y);
return
b1.Intersects(b2) && Same(l._p1, l._p2) <= 0 && l.Same(_p1, _p2) <= 0;
}
/*****************************************************************************/
BoxObj::BoxObj (Coord x0, Coord y0, Coord x1, Coord y1) {
_l = min(x0, x1); _b = min(y0, y1);
_r = max(x0, x1); _t = max(y0, y1);
}
BoxObj::BoxObj (BoxObj* b) {
_l = b->_l; _b = b->_b; _r = b->_r; _t = b->_t;
}
boolean BoxObj::operator== (BoxObj& box) {
float tol = 0.0001;
return (
Math::equal(_l, box._l, tol) &&
Math::equal(_r, box._r, tol) &&
Math::equal(_b, box._b, tol) &&
Math::equal(_t, box._t, tol)
);
}
boolean BoxObj::Contains (PointObj& p) {
return
(p._x >= _l) && (p._x <= _r) &&
(p._y >= _b) && (p._y <= _t);
}
boolean BoxObj::Intersects (BoxObj& b) {
return (
(_l <= b._r) && (b._l <= _r) &&
(_b <= b._t) && (b._b <= _t)
);
}
boolean BoxObj::Intersects (LineObj& l) {
Coord x1 = min(l._p1._x, l._p2._x);
Coord x2 = max(l._p1._x, l._p2._x);
Coord y1 = min(l._p1._y, l._p2._y);
Coord y2 = max(l._p1._y, l._p2._y);
BoxObj lbox(x1, y1, x2, y2);
boolean intersects = false;
if (Intersects(lbox)) {
intersects = Contains(l._p1) || Contains(l._p2);
if (!intersects) {
LineObj l0 (_l, _b, _r, _b);
LineObj l1 (_r, _b, _r, _t);
LineObj l2 (_r, _t, _l, _t);
LineObj l3 (_l, _t, _l, _b);
intersects =
l.Intersects(l0) || l.Intersects(l1) ||
l.Intersects(l2) || l.Intersects(l3);
}
}
return intersects;
}
BoxObj BoxObj::operator- (BoxObj& b) {
BoxObj i;
if (Intersects(b)) {
i._l = max(_l, b._l);
i._b = max(_b, b._b);
i._r = min(_r, b._r);
i._t = min(_t, b._t);
}
return i;
}
BoxObj BoxObj::operator+ (BoxObj& b) {
BoxObj m;
m._l = min(_l, b._l);
m._b = min(_b, b._b);
m._r = max(_r, b._r);
m._t = max(_t, b._t);
return m;
}
boolean BoxObj::Within (BoxObj& b) {
return (
(_l >= b._l) && (_b >= b._b) &&
(_r <= b._r) && (_t <= b._t)
);
}
/*****************************************************************************/
MultiLineObj::MultiLineObj (Coord* x, Coord* y, int count) {
_x = x; _y = y; _count = count;
}
void MultiLineObj::GrowBuf () {
Coord* newx, *newy;
int newsize;
if (mlsize == 0) {
mlsize = NUMPOINTS;
mlx = new Coord[NUMPOINTS];
mly = new Coord[NUMPOINTS];
} else {
newsize = mlsize * 2;
newx = new Coord[newsize];
newy = new Coord[newsize];
Memory::copy(mlx, newx, newsize * sizeof(Coord));
Memory::copy(mly, newy, newsize * sizeof(Coord));
delete mlx;
delete mly;
mlx = newx;
mly = newy;
mlsize = newsize;
}
}
boolean MultiLineObj::CanApproxWithLine (
double x0, double y0, double x2, double y2, double x3, double y3
) {
double triangleArea, sideSquared, dx, dy;
triangleArea = x0*y2 - x2*y0 + x2*y3 - x3*y2 + x3*y0 - x0*y3;
triangleArea *= triangleArea; // actually 4 times the area
dx = x3 - x0;
dy = y3 - y0;
sideSquared = dx*dx + dy*dy;
return triangleArea <= SMOOTHNESS * sideSquared;
}
void MultiLineObj::AddLine (double x0, double y0, double x1, double y1) {
if (mlcount >= mlsize) {
GrowBuf();
}
if (mlcount == 0) {
mlx[mlcount] = round(x0);
mly[mlcount] = round(y0);
++mlcount;
}
mlx[mlcount] = round(x1);
mly[mlcount] = round(y1);
++mlcount;
}
void MultiLineObj::AddBezierArc (
double x0, double y0, double x1, double y1,
double x2, double y2, double x3, double y3
) {
double midx01, midx12, midx23, midlsegx, midrsegx, cx,
midy01, midy12, midy23, midlsegy, midrsegy, cy;
Midpoint(x0, y0, x1, y1, midx01, midy01);
Midpoint(x1, y1, x2, y2, midx12, midy12);
Midpoint(x2, y2, x3, y3, midx23, midy23);
Midpoint(midx01, midy01, midx12, midy12, midlsegx, midlsegy);
Midpoint(midx12, midy12, midx23, midy23, midrsegx, midrsegy);
Midpoint(midlsegx, midlsegy, midrsegx, midrsegy, cx, cy);
if (CanApproxWithLine(x0, y0, midlsegx, midlsegy, cx, cy)) {
AddLine(x0, y0, cx, cy);
} else if (
(midx01 != x1) || (midy01 != y1) || (midlsegx != x2) ||
(midlsegy != y2) || (cx != x3) || (cy != y3)
) {
AddBezierArc(x0, y0, midx01, midy01, midlsegx, midlsegy, cx, cy);
}
if (CanApproxWithLine(cx, cy, midx23, midy23, x3, y3)) {
AddLine(cx, cy, x3, y3);
} else if (
(cx != x0) || (cy != y0) || (midrsegx != x1) || (midrsegy != y1) ||
(midx23 != x2) || (midy23 != y2)
) {
AddBezierArc(cx, cy, midrsegx, midrsegy, midx23, midy23, x3, y3);
}
}
void MultiLineObj::CalcSection (
Coord cminus1x, Coord cminus1y, Coord cx, Coord cy,
Coord cplus1x, Coord cplus1y, Coord cplus2x, Coord cplus2y
) {
double p0x, p1x, p2x, p3x, tempx,
p0y, p1y, p2y, p3y, tempy;
ThirdPoint(
double(cx), double(cy), double(cplus1x), double(cplus1y), p1x, p1y
);
ThirdPoint(
double(cplus1x), double(cplus1y), double(cx), double(cy), p2x, p2y
);
ThirdPoint(
double(cx), double(cy), double(cminus1x), double(cminus1y),
tempx, tempy
);
Midpoint(tempx, tempy, p1x, p1y, p0x, p0y);
ThirdPoint(
double(cplus1x), double(cplus1y), double(cplus2x), double(cplus2y),
tempx, tempy
);
Midpoint(tempx, tempy, p2x, p2y, p3x, p3y);
AddBezierArc(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y);
}
void MultiLineObj::SplineToMultiLine (Coord* cpx, Coord* cpy, int cpcount) {
register int cpi;
if (cpcount < 3) {
_x = cpx;
_y = cpy;
_count = cpcount;
} else {
mlcount = 0;
CalcSection(
cpx[0], cpy[0], cpx[0], cpy[0], cpx[0], cpy[0], cpx[1], cpy[1]
);
CalcSection(
cpx[0], cpy[0], cpx[0], cpy[0], cpx[1], cpy[1], cpx[2], cpy[2]
);
for (cpi = 1; cpi < cpcount - 2; ++cpi) {
CalcSection(
cpx[cpi - 1], cpy[cpi - 1], cpx[cpi], cpy[cpi],
cpx[cpi + 1], cpy[cpi + 1], cpx[cpi + 2], cpy[cpi + 2]
);
}
CalcSection(
cpx[cpi - 1], cpy[cpi - 1], cpx[cpi], cpy[cpi],
cpx[cpi + 1], cpy[cpi + 1], cpx[cpi + 1], cpy[cpi + 1]
);
CalcSection(
cpx[cpi], cpy[cpi], cpx[cpi + 1], cpy[cpi + 1],
cpx[cpi + 1], cpy[cpi + 1], cpx[cpi + 1], cpy[cpi + 1]
);
_x = mlx;
_y = mly;
_count = mlcount;
}
}
void MultiLineObj::ClosedSplineToPolygon (Coord* cpx, Coord* cpy, int cpcount){
register int cpi;
if (cpcount < 3) {
_x = cpx;
_y = cpy;
_count = cpcount;
} else {
mlcount = 0;
CalcSection(
cpx[cpcount - 1], cpy[cpcount - 1], cpx[0], cpy[0],
cpx[1], cpy[1], cpx[2], cpy[2]
);
for (cpi = 1; cpi < cpcount - 2; ++cpi) {
CalcSection(
cpx[cpi - 1], cpy[cpi - 1], cpx[cpi], cpy[cpi],
cpx[cpi + 1], cpy[cpi + 1], cpx[cpi + 2], cpy[cpi + 2]
);
}
CalcSection(
cpx[cpi - 1], cpy[cpi - 1], cpx[cpi], cpy[cpi],
cpx[cpi + 1], cpy[cpi + 1], cpx[0], cpy[0]
);
CalcSection(
cpx[cpi], cpy[cpi], cpx[cpi + 1], cpy[cpi + 1],
cpx[0], cpy[0], cpx[1], cpy[1]
);
_x = mlx;
_y = mly;
_count = mlcount;
}
}
void MultiLineObj::GetBox (BoxObj& b) {
b._l = b._r = _x[0];
b._b = b._t = _y[0];
for (int i = 1; i < _count; ++i) {
b._l = min(b._l, _x[i]);
b._b = min(b._b, _y[i]);
b._r = max(b._r, _x[i]);
b._t = max(b._t, _y[i]);
}
}
boolean MultiLineObj::Contains (PointObj& p) {
register int i;
BoxObj b;
GetBox(b);
if (b.Contains(p)) {
for (i = 1; i < _count; ++i) {
LineObj l (_x[i-1], _y[i-1], _x[i], _y[i]);
if (l.Contains(p)) {
return true;
}
}
}
return false;
}
boolean MultiLineObj::Intersects (LineObj& l) {
register int i;
BoxObj b;
GetBox(b);
if (b.Intersects(l)) {
for (i = 1; i < _count; ++i) {
LineObj test(_x[i-1], _y[i-1], _x[i], _y[i]);
if (l.Intersects(test)) {
return true;
}
}
}
return false;
}
boolean MultiLineObj::Intersects (BoxObj& userb) {
register int i;
BoxObj b;
GetBox(b);
if (b.Intersects(userb)) {
for (i = 1; i < _count; ++i) {
LineObj test(_x[i-1], _y[i-1], _x[i], _y[i]);
if (userb.Intersects(test)) {
return true;
}
}
}
return false;
}
boolean MultiLineObj::Within (BoxObj& userb) {
BoxObj b;
GetBox(b);
return b.Within(userb);
}
/*****************************************************************************/
FillPolygonObj::FillPolygonObj (
Coord* x, Coord* y, int n
) : MultiLineObj(x, y, n) {
_normCount = 0;
_normx = _normy = nil;
}
FillPolygonObj::~FillPolygonObj () {
delete _normx;
delete _normy;
}
static int LowestLeft (Coord* x, Coord* y, int count) {
register int i;
int lowestLeft = 0;
Coord lx = *x;
Coord ly = *y;
for (i = 1; i < count; ++i) {
if (y[i] < ly || (y[i] == ly && x[i] < lx)) {
lowestLeft = i;
lx = x[i];
ly = y[i];
}
}
return lowestLeft;
}
void FillPolygonObj::Normalize () {
if (_count != 0) {
register int i, newcount = 1;
int lowestLeft, limit = _count;
if (*_x == _x[_count - 1] && *_y == _y[_count - 1]) {
--limit;
}
lowestLeft = LowestLeft(_x, _y, limit);
_normCount = limit + 2;
_normx = new Coord[_normCount];
_normy = new Coord[_normCount];
for (i = lowestLeft; i < limit; ++i, ++newcount) {
_normx[newcount] = _x[i];
_normy[newcount] = _y[i];
}
for (i = 0; i < lowestLeft; ++i, ++newcount) {
_normx[newcount] = _x[i];
_normy[newcount] = _y[i];
}
_normx[newcount] = _normx[1];
_normy[newcount] = _normy[1];
--newcount;
_normx[0] = _normx[newcount];
_normy[0] = _normy[newcount];
}
}
boolean FillPolygonObj::Contains (PointObj& p) { // derived from <NAME>,
if (_normCount == 0) { // "An Introduction to
Normalize(); // Ray Tracing", p. 53,
} // courtesy <NAME>
int count = 0;
PointObj p0(0, 0);
boolean cur_y_sign = _normy[0] >= p._y;
for (int i = 0; i < _normCount - 2; ++i) {
LineObj l (
_normx[i] - p._x, _normy[i] - p._y,
_normx[i+1] - p._x, _normy[i+1] - p._y
);
if (l.Contains(p0)) {
return true;
}
boolean next_y_sign = l._p2._y >= 0;
if (next_y_sign != cur_y_sign) {
boolean cur_x_sign = l._p1._x >= 0;
boolean next_x_sign = l._p2._x >= 0;
if (cur_x_sign && next_x_sign) {
++count;
} else if (cur_x_sign || next_x_sign) {
Coord dx = l._p2._x - l._p1._x;
Coord dy = l._p2._y - l._p1._y;
if (dy >= 0) {
if (l._p1._x * dy > l._p1._y * dx) {
++count;
}
} else {
if (l._p1._x * dy < l._p1._y * dx) {
++count;
}
}
}
}
cur_y_sign = next_y_sign;
}
return count % 2 == 1;
}
boolean FillPolygonObj::Intersects (LineObj& l) {
BoxObj b;
boolean intersects = false;
if (_normCount == 0) {
Normalize();
}
GetBox(b);
if (b.Intersects(l)) {
MultiLineObj ml (_normx, _normy, _normCount - 1);
intersects = ml.Intersects(l) || Contains(l._p1) || Contains(l._p2);
}
return intersects;
}
boolean FillPolygonObj::Intersects (BoxObj& ub) {
BoxObj b;
GetBox(b);
if (!b.Intersects(ub)) {
return false;
}
if (b.Within(ub)) {
return true;
}
LineObj bottom(ub._l, ub._b, ub._r, ub._b);
if (Intersects(bottom)) {
return true;
}
LineObj right(ub._r, ub._b, ub._r, ub._t);
if (Intersects(right)) {
return true;
}
LineObj top(ub._r, ub._t, ub._l, ub._t);
if (Intersects(top)) {
return true;
}
LineObj left(ub._l, ub._t, ub._l, ub._b);
return Intersects(left);
}
/*****************************************************************************/
Extent::Extent (float x0, float y0, float x1, float y1, float t) {
_l = x0; _b = y0; _cx = x1; _cy = y1; _tol = t;
}
Extent::Extent (Extent& e) {
_l = e._l; _b = e._b;
_cx = e._cx; _cy = e._cy; _tol = e._tol;
}
boolean Extent::Within (Extent& e) {
float l = _l - _tol, b = _b - _tol;
float el = e._l - _tol, eb = e._b - _tol;
return
l >= el && b >= eb && 2*_cx - l <= 2*e._cx - el &&
2*_cy - b <= 2*e._cy - eb;
}
void Extent::Merge (Extent& e) {
float nl = min(_l, e._l);
float nb = min(_b, e._b);
if (Undefined()) {
_l = e._l; _b = e._b; _cx = e._cx; _cy = e._cy;
} else if (!e.Undefined()) {
_cx = (nl + max(2*_cx - _l, 2*e._cx - e._l)) / 2;
_cy = (nb + max(2*_cy - _b, 2*e._cy - e._b)) / 2;
_l = nl;
_b = nb;
}
_tol = max(_tol, e._tol);
}
<file_sep>/*
* glypheditor implementation
*/
#include <InterViews/action.h>
#include <InterViews/adjust.h>
#include <InterViews/box.h>
#include <InterViews/canvas.h>
#include <InterViews/color.h>
#include <InterViews/debug.h>
#include <InterViews/label.h>
#include <InterViews/layout.h>
#include <InterViews/session.h>
#include <InterViews/style.h>
#include <InterViews/telltale.h>
#include <InterViews/transformer.h>
#include <IV-look/button.h>
#include <IV-look/dialogs.h>
#include <IV-look/field.h>
#include <IV-look/fchooser.h>
#include <IV-look/menu.h>
#include <IV-look/kit.h>
#include <OS/file.h>
#include <OS/string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysent.h>
#include "figure.h"
#include "glypheditor.h"
#include "glyphviewer.h"
#include "pacekeeper.h"
#include "idraw.h"
static const char* tempfile = "/tmp/edraw";
class Displayer : public FieldEditor {
public:
Displayer(
const String& sample, WidgetKit*, Style*, FieldEditorAction* = nil
);
virtual void press(const Event&);
};
Displayer::Displayer(
const String& sample, WidgetKit* w, Style* s, FieldEditorAction* fa
) : FieldEditor(sample, w, s, fa) {}
void Displayer::press (const Event&) {}
class BoundedValue : public Adjustable {
protected:
BoundedValue();
public:
BoundedValue(Coord lower, Coord upper);
virtual ~BoundedValue();
virtual void lower_bound(Coord);
virtual void upper_bound(Coord);
virtual void current_value(Coord);
virtual void scroll_incr(Coord);
virtual void page_incr(Coord);
virtual Coord lower(DimensionName) const;
virtual Coord upper(DimensionName) const;
virtual Coord length(DimensionName) const;
virtual Coord cur_lower(DimensionName) const;
virtual Coord cur_upper(DimensionName) const;
virtual Coord cur_length(DimensionName) const;
virtual void scroll_to(DimensionName, Coord position);
virtual void scroll_forward(DimensionName);
virtual void scroll_backward(DimensionName);
virtual void page_forward(DimensionName);
virtual void page_backward(DimensionName);
private:
Coord curvalue_;
Coord lower_;
Coord span_;
Coord scroll_incr_;
Coord page_incr_;
};
BoundedValue::BoundedValue() {
scroll_incr_ = 0.0;
page_incr_ = 0.0;
}
BoundedValue::BoundedValue(Coord lower, Coord upper) {
lower_ = lower;
span_ = upper - lower;
scroll_incr_ = span_ * 0.04;
page_incr_ = span_ * 0.4;
curvalue_ = (lower + upper) * 0.5;
}
BoundedValue::~BoundedValue() { }
void BoundedValue::lower_bound(Coord c) { lower_ = c; }
void BoundedValue::upper_bound(Coord c) { span_ = c - lower_; }
void BoundedValue::current_value(Coord value) {
curvalue_ = value;
constrain(Dimension_X, curvalue_);
notify(Dimension_X);
notify(Dimension_Y);
}
void BoundedValue::scroll_incr(Coord c) { scroll_incr_ = c; }
void BoundedValue::page_incr(Coord c) { page_incr_ = c; }
Coord BoundedValue::lower(DimensionName) const { return lower_; }
Coord BoundedValue::upper(DimensionName) const { return lower_ + span_; }
Coord BoundedValue::length(DimensionName) const { return span_; }
Coord BoundedValue::cur_lower(DimensionName) const { return curvalue_; }
Coord BoundedValue::cur_upper(DimensionName) const { return curvalue_; }
Coord BoundedValue::cur_length(DimensionName) const { return 0; }
void BoundedValue::scroll_to(DimensionName d, Coord position) {
Coord p = position;
constrain(d, p);
if (p != curvalue_) {
curvalue_ = p;
notify(Dimension_X);
notify(Dimension_Y);
}
}
void BoundedValue::scroll_forward(DimensionName d) {
scroll_to(d, curvalue_ + scroll_incr_);
}
void BoundedValue::scroll_backward(DimensionName d) {
scroll_to(d, curvalue_ - scroll_incr_);
}
void BoundedValue::page_forward(DimensionName d) {
scroll_to(d, curvalue_ + page_incr_);
}
void BoundedValue::page_backward(DimensionName d) {
scroll_to(d, curvalue_ - page_incr_);
}
class Valuator : public MonoGlyph, public Observer {
public:
Valuator(BoundedValue*, Style*);
virtual ~Valuator();
virtual InputHandler* focusable() const;
virtual void update(Observable*);
virtual void disconnect(Observable*);
private:
BoundedValue* bvalue_;
FieldEditor* editor_;
void accept_editor(FieldEditor*);
void cancel_editor(FieldEditor*);
};
declareFieldEditorCallback(Valuator)
implementFieldEditorCallback(Valuator)
Valuator::Valuator(BoundedValue* bv, Style* style) : MonoGlyph(nil) {
Style* s = new Style(style);
s->alias("Valuator");
bvalue_ = bv;
bv->attach(Dimension_X, this);
editor_ = new Displayer(
String("9999"), WidgetKit::instance(), s,
new FieldEditorCallback(Valuator)(
this, &Valuator::accept_editor, &Valuator::cancel_editor
)
);
editor_->field("0.50");
body(editor_);
update(bv->observable(Dimension_X));
}
Valuator::~Valuator() {
if (bvalue_ != nil) {
bvalue_->detach(Dimension_X, this);
}
}
InputHandler* Valuator::focusable() const {
return editor_;
}
float frame_dist;
void Valuator::update(Observable*) {
Coord v = bvalue_->cur_lower(Dimension_X);
char buf[20];
sprintf(buf, "%.2f", v);
editor_->field(buf);
frame_dist = v*300.0 + 2.0;
}
void Valuator::disconnect(Observable*) {
bvalue_ = nil;
}
void Valuator::accept_editor(FieldEditor*) {
Coord v;
const String& value = *editor_->text();
if (value.convert(v)) {
bvalue_->current_value(v);
}
}
void Valuator::cancel_editor(FieldEditor*) {
update(bvalue_->observable(Dimension_X));
}
/******************************************************/
class CatalogButton : public Button {
public:
CatalogButton(Glyph*, Style*, TelltaleState*, Action*);
virtual ~CatalogButton();
virtual void enter();
virtual void leave();
};
CatalogButton::CatalogButton(
Glyph* g, Style* s, TelltaleState* t, Action* a
) : Button(g, s, t, a) {}
CatalogButton::~CatalogButton () {}
void CatalogButton::enter () {}
void CatalogButton::leave () {}
/******************************************************/
class ToolCallback : public Action {
public:
ToolCallback(GlyphViewer*, unsigned int);
virtual void execute();
private:
GlyphViewer* _gv;
unsigned _type;
};
ToolCallback::ToolCallback (
GlyphViewer* gv, unsigned int t
) {
_gv = gv;
_type = t;
}
void ToolCallback::execute () {
_gv->tool().tool(_type);
}
/******************************************************/
class PolicyCallback : public Action {
public:
PolicyCallback(GlyphViewer*, unsigned int);
virtual void execute();
private:
GlyphViewer* _gv;
unsigned int _type;
};
PolicyCallback::PolicyCallback (
GlyphViewer* gv, unsigned int t
) {
_gv = gv;
_type = t;
}
void PolicyCallback::execute () {
_gv->set_policy(_type);
}
/******************************************************/
GlyphEditor::GlyphEditor () {
body(interior());
}
Glyph* GlyphEditor::interior () {
BoundedValue* bv = new BoundedValue(0.0, 1.0);
bv->current_value(0.5);
bv->scroll_incr(0.01);
bv->page_incr(0.1);
LayoutKit* layout = LayoutKit::instance();
WidgetKit* widget = WidgetKit::instance();
Style* s = new Style;
s->attribute("foreground", "black");
s->attribute("font", "-*-times-bold-r-normal-*-14-*-*-*-*-*-*-*");
widget->push_style(s);
Glyph* label1 = widget->label("Policies");
Glyph* label2 = widget->label("Tools");
widget->pop_style();
_gviewer = new GlyphViewer(600, 500);
return widget->inset_frame(
layout->vbox(
menus(),
layout->hbox(
layout->vbox(
widget->inset_frame(
_gviewer
)
),
widget->outset_frame(
layout->vbox(
layout->vglue(5, fil/2.0, 0),
layout->hmargin(
label1,
1.0, fil/10, 0, 1.0, fil/10, 0
),
pacekeepers(),
layout->vglue(10, 0, 0),
layout->hmargin(
label2,
1.0, fil/10, 0, 1.0, fil/10, 0
),
buttons(),
layout->vglue(10, 0, 0),
layout->vglue(20, fil, 0)
)
)
)
)
);
}
class Teller : public TelltaleState {
public:
Teller(const TelltaleFlags, Action*);
virtual void set(const TelltaleFlags, boolean);
protected:
Action* _action;
};
Teller::Teller(const TelltaleFlags f, Action* a) : TelltaleState (f) {
_action = a;
}
void Teller::set (const TelltaleFlags f, boolean flag) {
if (flag && (f == is_active)) {
TelltaleState::set(is_active | is_chosen, flag);
if (_action != nil) {
_action->execute();
}
} else if (!flag && f == is_chosen) {
TelltaleState::set(is_active | is_chosen, flag);
} else if (!flag && f == is_active) {
} else if (flag && f == is_chosen) {
} else {
TelltaleState::set(f, flag);
}
}
Button* GlyphEditor::make_tool (
TelltaleGroup* teller, const char* label, unsigned int tool_id
) {
WidgetKit* widget = WidgetKit::instance();
LayoutKit* layout = LayoutKit::instance();
TelltaleFlags f = TelltaleState::is_enabled | TelltaleState::is_choosable;
widget->begin_style("PushButton", "Button");
Action* a = new ToolCallback(
_gviewer, tool_id
);
TelltaleState* ts = new Teller(f, a);
ts->join(teller);
Button* tool = new CatalogButton(
widget->push_button_look(
layout->hmargin(
widget->label(label), 1.0, fil/10, 0, 1.0, fil/10, 0
), ts
),
widget->style(), ts, nil
);
widget->end_style();
return tool;
}
Button* GlyphEditor::make_policy (
TelltaleGroup* teller, const char* label, unsigned int policy
) {
WidgetKit* widget = WidgetKit::instance();
LayoutKit* layout = LayoutKit::instance();
TelltaleFlags f = TelltaleState::is_enabled | TelltaleState::is_choosable;
widget->begin_style("PushButton", "Button");
Action* a = new PolicyCallback(
_gviewer, policy
);
TelltaleState* ts = new Teller(f, a);
ts->join(teller);
Button* tool = new CatalogButton(
widget->push_button_look(
layout->hmargin(
widget->label(label), 1.0, fil/10, 0, 1.0, fil/10, 0
), ts
),
widget->style(), ts, nil
);
widget->end_style();
return tool;
}
Glyph* GlyphEditor::pacekeepers () {
LayoutKit* layout = LayoutKit::instance();
TelltaleGroup* teller = new TelltaleGroup;
Button* nopk = make_policy(teller, "None", PaceKeeper::NoPK);
Button* edriven = make_policy(teller, "Event Driven", PaceKeeper::EDriven);
Button* damposc = make_policy(teller, "Damped Osc", PaceKeeper::DampedOsc);
Button* pc = make_policy(teller, "Penalty/Credit", PaceKeeper::PC);
Button* coh = make_policy(teller, "Coherence", PaceKeeper::Coh);
coh->state()->set(TelltaleState::is_active, true);
_gviewer->set_policy(PaceKeeper::Coh);
return layout->vbox(
nopk, edriven, damposc, pc, coh
);
}
Glyph* GlyphEditor::buttons () {
LayoutKit* layout = LayoutKit::instance();
TelltaleGroup* teller = new TelltaleGroup;
Button* move = make_tool(teller, "Move", Tool::move);
Button* scale = make_tool(teller, "Scale", Tool::scale);
Button* rotate = make_tool(teller, "Rotate", Tool::rotate);
move->state()->set(TelltaleState::is_active, true);
return layout->vbox(
move, scale, rotate
);
}
void GlyphEditor::new_session () {
_gviewer->setrootgr(new PolyGraphic);
}
void GlyphEditor::allocate (Canvas* c, const Allocation& a, Extension& ext) {
_w = c->window();
MonoGlyph::allocate(c, a, ext);
}
class Importer : public Action {
public:
Importer(GlyphEditor* ed);
virtual void execute();
protected:
GlyphEditor* _ed;
static FileChooser* _chooser;
};
FileChooser* Importer::_chooser;
Importer::Importer (GlyphEditor* ed) { _ed = ed; }
void Importer::execute () {
Style* style;
boolean resetcaption = false;
if (_chooser == nil) {
style = new Style(Session::instance()->style());
_chooser = DialogKit::instance()->file_chooser(".", style);
Resource::ref(_chooser);
char buf[256];
sprintf(buf, "Select an idraw drawing to import:");
style->attribute("caption", "");
style->attribute("subcaption", buf);
} else {
style = _chooser->style();
}
while (_chooser->post_for(_ed->window())) {
const String* s = _chooser->selected();
InputFile* f = InputFile::open(*s);
if (f != nil) {
Graphic* gr = IdrawReader::load(f);
if (gr != nil) {
gr->flush();
_ed->viewer()->setrootgr(gr);
delete f;
break;
} else {
style->attribute("caption", "Import failed!");
resetcaption = true;
delete f;
}
} else {
unlink(tempfile);
char cmd[256];
sprintf(cmd, "ls %s > %s", s->string(), tempfile);
system(cmd);
String fname(tempfile);
f = InputFile::open(fname);
if (f != nil) {
long len = f->length();
if (len == 0) {
delete f;
style->attribute("caption", "Import failed!");
resetcaption = true;
} else {
char* buffer;
int len = f->read(buffer);
PolyGraphic* poly = new PolyGraphic;
char* prev = buffer;
while(true) {
char* ptr = strchr(prev, '\n');
if (ptr == nil || (buffer+len < ptr)) {
break;
}
CopyString str(prev, ptr-prev);
Graphic* gr = IdrawReader::load(str.string());
if (gr != nil) {
poly->append_(gr);
/*
if (gr != poly->child_(0)) {
poly->child_(0)->align(Center, gr, Center);
}
*/
}
prev = ptr+1;
}
if (poly->count_() == 0) {
delete f;
delete poly;
style->attribute("caption", "Import failed!");
resetcaption = true;
} else {
poly->flush();
Transformer* tr = new Transformer;
for (long i = 0; i < poly->count_(); i++) {
Graphic* gr = poly->child_(i);
gr->transformer(tr);
}
tr->unref();
long sel = poly->child_(0)->count_();
for (long j = 0; j < sel; j++) {
tr = new Transformer;
for (i = 0; i < poly->count_(); i++) {
Graphic* gr = poly->child_(i)->child_(j);;
gr->transformer(tr);
}
tr->unref();
}
_ed->viewer()->setrootgr(poly);
delete f;
break;
}
}
} else {
style->attribute("caption", "Import failed!");
resetcaption = true;
}
}
}
if (resetcaption) {
style->attribute("caption", "");
}
}
class QuitAction : public Action {
public:
QuitAction();
virtual void execute();
};
QuitAction::QuitAction () {}
void QuitAction::execute () { WidgetKit::instance()->quit()->execute(); }
class Cleaner : public Action {
public:
Cleaner(GlyphEditor* ed);
virtual void execute();
protected:
GlyphEditor* _ed;
};
Cleaner::Cleaner (GlyphEditor* ed) {
_ed = ed;
}
void Cleaner::execute () {
_ed->new_session();
}
Glyph* GlyphEditor::menus () {
WidgetKit* widget = WidgetKit::instance();
Menu* mb = widget->menubar();
MenuItem* mi = widget->menubar_item("File");
Menu* pulldown = widget->pulldown();
MenuItem* cleaner = widget->menu_item("Purge");
MenuItem* import = widget->menu_item("Import");
MenuItem* quit = widget->menu_item("Quit");
cleaner->action(new Cleaner(this));
import->action(new Importer(this));
quit->action(new QuitAction);
mb->append_item(mi);
mi->menu(pulldown);
pulldown->append_item(import);
pulldown->append_item(cleaner);
pulldown->append_item(widget->menu_item_separator());
pulldown->append_item(quit);
return mb;
}
<file_sep>/*
* planar figureviews
*/
#ifndef figureview_h
#define figureview_h
#include <InterViews/action.h>
#include <InterViews/event.h>
#include <InterViews/resource.h>
#include "figure.h"
#include "globals.h"
class Color;
class GlyphViewer;
class Graphic;
class GrViewList;
class Transformer;
typedef long ViewIndex;
class ViewAction : public Action {
public:
virtual boolean executable() const;
Graphic* target() const;
protected:
ViewAction(Graphic* = nil);
protected:
Graphic* _gr;
};
class ToolState {
public:
Event _init;
Event _last;
Coord _l, _b, _r, _t;
Graphic _gs;
};
class Tool {
public:
enum {
nop, select, move, scale, stretch, rotate, alter, create, narrow,
rate_scroll, grab_scroll, rate_zoom
};
Tool(unsigned int = Tool::nop);
virtual ~Tool();
virtual unsigned int tool();
virtual void tool(unsigned int);
virtual ToolState& toolstate();
virtual void toolstate(ToolState*);
virtual void reset();
protected:
unsigned int _cur_tool;
ToolState* _toolstate;
};
class GrView : public Resource{
public:
GrView(Graphic* gr = nil);
virtual ~GrView ();
virtual Graphic* getgraphic() const;
virtual void setgraphic(Graphic*);
virtual boolean grasp(const Event&, Tool&, ViewAction*&);
virtual boolean manipulating(const Event&, Tool&, ViewAction*&);
virtual void effect(const Event&, Tool&, ViewAction*&);
virtual void append(GrView*);
virtual void prepend(GrView*);
virtual void insert(ViewIndex, GrView*);
virtual void remove(ViewIndex);
virtual void remove(GrView*);
virtual ViewIndex count() const;
virtual GrView* child(ViewIndex) const;
virtual void setindex(ViewIndex);
virtual ViewIndex getindex() const;
protected:
Graphic* _gr;
ViewIndex _index;
};
class PolyView : public GrView {
public:
PolyView(Graphic* = nil) ;
virtual ~PolyView();
virtual void append(GrView*);
virtual void prepend(GrView*);
virtual void insert(ViewIndex, GrView*);
virtual void remove(ViewIndex);
virtual void remove(GrView*);
virtual ViewIndex count() const;
virtual GrView* child(ViewIndex) const;
protected:
GrViewList* _body;
};
class GrTarget {
public:
GrTarget(ViewIndex = 0, Graphic* = nil);
public:
ViewIndex _index;
Graphic* _target;
};
declareList(TargetList,GrTarget);
class RootView : public PolyView {
public:
RootView(
RootGraphic* = nil, Graphic* = nil,
const Color* bg = nil, GlyphViewer* = nil
);
virtual ~RootView();
virtual void setgraphic(Graphic*);
RootGraphic* getrootgr();
void background(const Color*);
const Color* background();
void viewer(GlyphViewer*);
GlyphViewer* viewer();
const TargetList* cur_targets() const;
virtual boolean grasp(const Event&, Tool&, ViewAction*&);
virtual boolean manipulating(const Event&, Tool&, ViewAction*&);
virtual void effect(const Event&, Tool&, ViewAction*&);
protected:
RootGraphic* _rootgr;
TargetList* _targets;
const Color* _bg;
GlyphViewer* _gviewer;
Coord _lx, _ly;
};
inline const Color* RootView::background () { return _bg; }
inline GlyphViewer* RootView::viewer () { return _gviewer; }
inline void RootView::viewer (GlyphViewer* v) { _gviewer = v; }
inline const TargetList* RootView::cur_targets () const{ return _targets; }
inline RootGraphic* RootView::getrootgr () { return _rootgr; }
#endif
<file_sep>#ifndef pacer_h
#define pacer_h
#include <InterViews/event.h>
#include "globals.h"
class Action;
class Brush;
class Canvas;
class Color;
class ContImpl;
class Graphic;
class GradeCollector;
class Transformer;
class DragImpl;
static const long SlowRate = 1e6;
static const long FastRate = 50e3;
static const long RelaxRate = 5e3;
static const long LowSpeed = 10000;
static const long HighSpeed = 1000000;
static const float ShortDist = 10.0;
static const float LongDist = 50.0;
class EventMapper {
public:
virtual ~EventMapper();
virtual USec init(Event&) = 0;
virtual USec map(Event&) = 0;
virtual USec relax() = 0;
protected:
EventMapper();
};
class DragMapper : public EventMapper {
public:
DragMapper(
USec = SlowRate, USec = FastRate, long = LowSpeed, long = HighSpeed,
float _relax_factor = 1.15
);
virtual ~DragMapper();
virtual USec init(Event&);
virtual USec map(Event&);
virtual USec relax();
private:
DragImpl* _impl;
};
typedef unsigned int ContDimension;
enum {
Cont_X = 0, Cont_Y, Cont_XY
};
class ContMapper : public EventMapper {
public:
ContMapper(
USec = SlowRate, USec = FastRate,
Coord = ShortDist, Coord = LongDist, ContDimension = Cont_XY
);
virtual ~ContMapper();
virtual USec init(Event&);
virtual USec map(Event&);
virtual USec relax();
void set_dimension(ContDimension);
private:
ContImpl* _impl;
};
class Pacer {
public:
virtual ~Pacer();
virtual void append(Pacer*);
virtual void prepend(Pacer*);
virtual void insert(PacerIndex, Pacer*);
virtual void remove(PacerIndex);
virtual void remove_all();
virtual void delete_all();
virtual PacerIndex count() const;
virtual Pacer* child(PacerIndex) const;
virtual Pacer* get_parent() const;
virtual void set_parent(Pacer*);
virtual void play(RunTime&) = 0;
virtual void pick(SchedulerList&);
virtual void get_grades(Grade& low, Grade& high) = 0;
virtual void regrade();
protected:
Pacer();
protected:
Pacer* _parent;
};
class PolyPacer : public Pacer {
public:
virtual ~PolyPacer();
virtual void play(RunTime&) = 0;
virtual void get_grades(Grade& low, Grade& high) = 0;
virtual void pick(SchedulerList&);
virtual void regrade();
virtual void append(Pacer*);
virtual void prepend(Pacer*);
virtual void insert(PacerIndex, Pacer*);
virtual void remove(PacerIndex);
virtual void remove_all();
virtual void delete_all();
virtual PacerIndex count() const;
virtual Pacer* child(PacerIndex) const;
protected:
PolyPacer();
protected:
PacerList* _child_list;
};
class Grader : public PolyPacer {
public:
Grader(GradeCollector* = nil);
virtual ~Grader();
GradeCollector* get_collector() const;
void set_collector(GradeCollector*);
virtual void play(RunTime&);
virtual void get_grades(Grade& low, Grade& high);
virtual void regrade();
protected:
GradeCollector* _collector;
};
class UniPacer : public Pacer {
public:
UniPacer();
virtual ~UniPacer();
virtual Pacer* get_kid() const;
virtual void set_kid(Pacer*);
virtual void append(Pacer*);
virtual void prepend(Pacer*);
virtual void insert(PacerIndex, Pacer*);
virtual void remove(PacerIndex);
virtual void remove_all();
virtual void delete_all();
virtual PacerIndex count() const;
virtual Pacer* child(PacerIndex) const;
virtual void play(RunTime&);
virtual void regrade();
virtual void pick(SchedulerList&);
virtual void get_grades(Grade& low, Grade& high);
protected:
Pacer* _kid;
};
class Scheduler : public UniPacer {
public:
Scheduler(USec period);
virtual void set_period(USec period);
virtual USec get_period();
virtual void start(Sec, USec);
virtual void stop(Sec, USec);
virtual void play(RunTime&);
virtual void pick(SchedulerList&);
protected:
USec _period;
};
class UIScheduler : public Scheduler {
public:
UIScheduler(EventMapper*);
virtual ~UIScheduler();
virtual void start(Sec, USec);
virtual void stop(Sec, USec);
virtual void play(RunTime&);
virtual void cur_event(Event&);
void set_mapper(EventMapper*);
protected:
EventMapper* _emapper;
boolean _playing;
USec _event_usec;
Sec _event_sec;
};
class ActionPacer : public UniPacer {
public:
ActionPacer(Action* before = nil, Action* after = nil);
virtual ~ActionPacer();
virtual void play(RunTime&);
void set_before(Action*);
void set_after(Action*);
protected:
Action* _before;
Action* _after;
};
class GraphicPacer : public Pacer {
public:
GraphicPacer(Canvas*, Graphic*);
virtual ~GraphicPacer();
virtual Graphic* get_graphic() const;
virtual void set_graphic(Graphic*);
void set_grades(Grade low, Grade high);
virtual void play(RunTime&);
virtual void get_grades(Grade& low, Grade& high);
static BoxObj& damaged_area();
static void incur(BoxObj&);
static void clear();
protected:
static BoxObj _damage;
protected:
Canvas* _canvas;
Graphic* _gr;
Grade _low, _high;
};
inline Graphic* GraphicPacer::get_graphic () const { return _gr; }
class Repairer : public GraphicPacer {
public:
virtual void incur(BoxObj&);
virtual void clear();
virtual BoxObj& damaged_area();
virtual void play(RunTime&) = 0;
protected:
Repairer(Canvas*, Graphic*);
protected:
BoxObj _total;
};
class Filler : public Repairer {
public:
Filler(Canvas*, Graphic*, const Color* fill);
virtual ~Filler();
virtual void play(RunTime&);
protected:
const Color* _fill;
};
class FCGraphicPacer : public Filler {
public:
FCGraphicPacer(Canvas*, Graphic*, const Color* fill);
virtual ~FCGraphicPacer();
void set_clipped (BoxObj&);
virtual void play(RunTime&);
protected:
BoxObj _clip;
};
inline void FCGraphicPacer::set_clipped(BoxObj& clip) { _clip = clip; }
class Fixer : public Repairer {
public:
Fixer(Canvas*, Graphic*);
virtual void play(RunTime&);
};
class SelectPacer : public UniPacer {
public:
SelectPacer(Canvas*, Graphic*);
virtual ~SelectPacer();
void set_damaged(BoxObj*);
void set_clipped (BoxObj&);
void set_graphic(Graphic*);
virtual void play(RunTime&);
protected:
Canvas* _canvas;
Graphic* _gr;
BoxObj* _box;
BoxObj _allot;
};
inline void SelectPacer::set_damaged(BoxObj* box) { _box = box; }
inline void SelectPacer::set_clipped(BoxObj& allot) { _allot = allot; }
class Clipper : public UniPacer {
public:
Clipper(Canvas*, BoxObj*);
virtual ~Clipper();
void set_damaged(BoxObj*);
void set_clipped (BoxObj&);
virtual void play(RunTime&);
protected:
Canvas* _canvas;
BoxObj* _box;
BoxObj _allot;
};
inline void Clipper::set_damaged(BoxObj* box) { _box = box; }
inline void Clipper::set_clipped(BoxObj& allot) { _allot = allot; }
class XorPacer : public GraphicPacer {
public:
XorPacer(Canvas*, Graphic*, const Color*);
virtual ~XorPacer();
virtual void set_graphic(Graphic*);
void set_clipped (BoxObj&);
virtual void play(RunTime&);
protected:
void xor();
protected:
Color* _color;
Brush* _brush;
BoxObj _box;
BoxObj _allot;
Transformer* _t;
boolean _drawn;
};
inline void XorPacer::set_clipped(BoxObj& allot) { _allot = allot; }
class Player : public PolyPacer {
public:
Player(Pacer*, TimeSlice&);
virtual void play(RunTime&);
protected:
Pacer* _actor;
TimeSlice _schedule;
};
#endif
<file_sep># interviews-3.2a
[InterViews](http://sites.music.columbia.edu/doug/MiXViews/building.mxv.html)(download: ftp://ftp.sgi.com/graphics/interviews/) include some design pattern illustrations referenced in Design Patterns of GOF.
<file_sep>#ifndef pacekeeper_h
#define pacekeeper_h
#include "globals.h"
class Scheduler;
class ContinueImpl;
class CoherenceImpl;
class DampedImpl;
class EventImpl;
class PCImpl;
class PaceKeeper {
public:
enum {
NoPK = 0, EDriven, DampedOsc, PC, Coh
};
virtual ~PaceKeeper();
virtual void startall(Sec, USec) = 0;
virtual void stopall(Sec, USec) = 0;
virtual void start(Scheduler*, Sec, USec) = 0;
virtual void play(Scheduler*, Sec, USec) = 0;
virtual void stop(Scheduler*, Sec, USec) = 0;
virtual void eval(Sec, USec);
virtual void adjust(Scheduler*);
protected:
PaceKeeper();
};
class Continuator : public PaceKeeper {
public:
Continuator(Pacer* root);
virtual ~Continuator();
virtual void startall(Sec, USec);
virtual void stopall(Sec, USec);
virtual void start(Scheduler*, Sec, USec);
virtual void play(Scheduler*, Sec, USec);
virtual void stop(Scheduler*, Sec, USec);
protected:
ContinueImpl* _impl;
};
class EventKeeper : public PaceKeeper {
public:
EventKeeper(Pacer* root);
virtual ~EventKeeper();
virtual void startall(Sec, USec);
virtual void stopall(Sec, USec);
virtual void start(Scheduler*, Sec, USec);
virtual void play(Scheduler*, Sec, USec);
virtual void stop(Scheduler*, Sec, USec);
virtual void adjust(Scheduler*);
virtual void eval(Sec, USec);
protected:
EventImpl* _impl;
};
class DampedKeeper : public PaceKeeper {
public:
DampedKeeper(Pacer* root);
virtual ~DampedKeeper();
virtual void startall(Sec, USec);
virtual void stopall(Sec, USec);
virtual void start(Scheduler*, Sec, USec);
virtual void play(Scheduler*, Sec, USec);
virtual void stop(Scheduler*, Sec, USec);
virtual void adjust(Scheduler*);
virtual void eval(Sec, USec);
protected:
DampedImpl* _impl;
};
class PCKeeper : public PaceKeeper {
public:
PCKeeper(Pacer* root);
virtual ~PCKeeper();
virtual void startall(Sec, USec);
virtual void stopall(Sec, USec);
virtual void start(Scheduler*, Sec, USec);
virtual void play(Scheduler*, Sec, USec);
virtual void stop(Scheduler*, Sec, USec);
virtual void adjust(Scheduler*);
virtual void eval(Sec, USec);
protected:
PCImpl* _impl;
};
class CoherenceKeeper : public PaceKeeper {
public:
CoherenceKeeper(Pacer* root);
virtual ~CoherenceKeeper();
virtual void startall(Sec, USec);
virtual void stopall(Sec, USec);
virtual void start(Scheduler*, Sec, USec);
virtual void play(Scheduler*, Sec, USec);
virtual void stop(Scheduler*, Sec, USec);
virtual void eval(Sec, USec);
virtual void adjust(Scheduler*);
private:
CoherenceImpl* _impl;
};
#endif
<file_sep>#include "pacekeeper.h"
#include "pacemaker.h"
#include "pacer.h"
#include <OS/list.h>
#include <sys/time.h>
#include <stdio.h>
static Sec MaxTransit = 30000;
static SessionID globalID = 0;
typedef unsigned int ImplState;
static const unsigned int TOL = 0;
static const unsigned int MIN_CYCLE = 2;
static const unsigned int MAX_CYCLE = 10;
static const unsigned int USEC_TO_CYCLE = 10000;
static long find_player(Scheduler* s, SchedulerList* plist) {
for (long i = 0; i < plist->count(); i++) {
if (s == plist->item(i)) {
return i;
}
}
return -1;
}
class CCell {
public:
CCell();
public:
float _coherence;
USec _cpf;
USec _tleft;
USec _tdelta;
};
CCell::CCell () {
_coherence = 1.0;
_cpf = 0;
_tleft = 0;
_tdelta = 0;
}
declareList(CCellList, CCell);
implementList(CCellList, CCell);
declarePtrList(PlayList, CCellList);
implementPtrList(PlayList, CCellList);
/********************************************************************/
PaceKeeper::PaceKeeper () {}
PaceKeeper::~PaceKeeper () {}
void PaceKeeper::eval (Sec, USec) {}
void PaceKeeper::adjust (Scheduler*) {}
/********************************************************************/
class ContinueImpl {
public:
ContinueImpl(Pacer* root);
virtual ~ContinueImpl();
virtual void startall(Sec, USec);
virtual void stopall(Sec, USec);
virtual void start(Scheduler*, Sec, USec);
virtual void play(Scheduler*, Sec, USec);
virtual void stop(Scheduler*, Sec, USec);
public:
Pacer* _root;
Grade _low, _high;
SchedulerList* _playerlist;
boolean _running;
};
ContinueImpl::ContinueImpl (Pacer* root) {
_root = root;
_playerlist = nil;
_running = false;
}
ContinueImpl::~ContinueImpl () {
delete _playerlist;
}
void ContinueImpl::startall (Sec sec, USec usec) {
globalID++;
_running = true;
if (_playerlist == nil) {
_playerlist = new SchedulerList(5);
_root->pick(*_playerlist);
_root->get_grades(_low, _high);
}
for (long k = 0; k < _playerlist->count(); k++) {
Scheduler* player = _playerlist->item(k);
player->start(sec, usec);
play(player, sec, usec);
}
}
void ContinueImpl::stopall (Sec sec, USec usec) {
_running = false;
if (_playerlist != nil) {
for (long k = 0; k < _playerlist->count(); k++) {
Scheduler* player = _playerlist->item(k);
player->stop(sec, usec);
}
}
}
void ContinueImpl::start (Scheduler* p, Sec sec, USec usec) {
if (!_running) {
_running = true;
globalID++;
}
p->start(sec, usec);
play(p, sec, usec);
}
void ContinueImpl::stop (Scheduler* p, Sec sec, USec usec) {
p->stop(sec, usec);
}
void ContinueImpl::play (Scheduler* s, Sec sec, USec usec) {
RunTime rtime;
rtime._cur_grade = _low;
rtime._fut_grade = _low;
rtime._id = globalID;
USec period = s->get_period();
rtime._period = period;
rtime._sec = sec;
rtime._usec = usec;
s->play(rtime);
}
/********************************************************************/
Continuator::Continuator (Pacer* root) {
_impl = new ContinueImpl(root);
}
Continuator::~Continuator () {
delete _impl;
}
void Continuator::startall (Sec sec, USec usec) {
_impl->startall(sec, usec);
}
void Continuator::stopall (Sec sec, USec usec) {
_impl->stopall(sec, usec);
}
void Continuator::start (Scheduler* s, Sec sec, USec usec) {
_impl->start(s, sec, usec);
}
void Continuator::play (Scheduler* s, Sec sec, USec usec) {
_impl->play(s, sec, usec);
}
void Continuator::stop (Scheduler* s, Sec sec, USec usec) {
_impl->stop(s, sec, usec);
}
/*******************************************************************/
class EventImpl {
public:
enum {sustain, transit, trial};
EventImpl(Pacer* r);
virtual ~EventImpl();
virtual void startall(Sec, USec);
virtual void stopall(Sec, USec);
virtual void start(Scheduler*, Sec, USec);
virtual void play(Scheduler*, Sec, USec);
virtual void stop(Scheduler*, Sec, USec);
virtual void eval(Sec, USec);
virtual void adjust(Scheduler*);
protected:
Pacer* _root;
SchedulerList* _playerlist;
PlayList* _playlist;
ImplState _fut_state;
ImplState _cur_state;
Grade _cur_grade;
Grade _fut_grade;
Grade _low, _high;
boolean _running;
};
EventImpl::EventImpl (Pacer* r) {
_root = r;
_running = false;
_playerlist = nil;
_playlist = nil;
}
EventImpl::~EventImpl () {
delete _playerlist;
if (_playlist != nil) {
for (long i = 0; i < _playlist->count(); i++) {
delete _playlist->item(i);
}
delete _playlist;
}
}
void EventImpl::stopall (Sec sec, USec usec) {
_running = false;
if (_playerlist != nil) {
for (long k = 0; k < _playerlist->count(); k++) {
Scheduler* player = _playerlist->item(k);
player->stop(sec, usec);
}
}
}
void EventImpl::startall (Sec sec, USec usec) {
_running = true;
globalID++;
if (_playerlist == nil) {
_playerlist = new SchedulerList(5);
_root->get_grades(_low, _high);
_root->pick(*_playerlist);
long grades = _high - _low + 1;
CCell cell;
_playlist = new PlayList(_playerlist->count());
for (long i = 0; i < _playerlist->count(); i++) {
CCellList* clist = new CCellList(grades);
_playlist->append(clist);
for (long j = 0; j < grades; j++) {
clist->append(cell);
}
}
}
_cur_grade = _low;
_fut_grade = _low;
_cur_state = sustain;
_fut_state = sustain;
RunTime rtime;
rtime._cur_grade = _cur_grade;
rtime._fut_grade = _fut_grade;
rtime._id = globalID;
rtime._sec = sec;
rtime._usec = usec;
for (long k = 0; k < _playerlist->count(); k++) {
Scheduler* player = _playerlist->item(k);
player->start(sec, usec);
USec period = player->get_period();
rtime._period = period;
player->play(rtime);
}
}
void EventImpl::play (Scheduler* p, Sec sec, USec usec) {
RunTime rtime;
rtime._cur_grade = _cur_grade;
rtime._fut_grade = _fut_grade;
rtime._id = globalID;
USec period = p->get_period();
rtime._period = period;
rtime._sec = sec;
rtime._usec = usec;
timeval b, a;
gettimeofday(&b, nil);
p->play(rtime);
gettimeofday(&a, nil);
USec len = (a.tv_usec-b.tv_usec)+(a.tv_sec-b.tv_sec)*1e6;
long index = find_player(p, _playerlist);
if (index >= 0) {
CCell& cc = _playlist->item(index)->item_ref(_fut_grade);
USec cpf = len;
boolean to_eval = false;
if (cc._cpf > 0) {
cc._tdelta += cpf - cc._cpf;
} else {
to_eval = true;
}
cc._cpf = cpf;
cc._tleft += rtime._period-len;
if (to_eval && cc._tleft < 0) {
_cur_state = _fut_state;
_fut_state = sustain;
eval(a.tv_sec, a.tv_usec);
}
}
}
void EventImpl::eval (Sec, USec) {
if (!_running) {
return;
}
switch(_fut_state) {
case trial:
{
_cur_state = _fut_state;
/* See if need to downgrade */
if (_fut_grade < _high) {
for (long i = 0; i < _playlist->count(); i++) {
CCell& cc = _playlist->item(i)->item_ref(_fut_grade);
if (cc._tleft < 0) {
for (long j = 0; j < _playlist->count(); j++) {
CCell& cell0 = _playlist->item(j)->item_ref(
_fut_grade
);
cell0._tleft = 0;
cell0._tdelta = 0;
CCell& cell1 = _playlist->item(j)->item_ref(
_fut_grade+1
);
cell1._tleft = 0;
cell1._tdelta = 0;
cell1._cpf = 0;
}
_fut_state = transit;
break;
}
}
}
if (_fut_state != transit) {
_fut_state = sustain;
_cur_grade = _fut_grade;
} else {
_cur_grade = _fut_grade;
_fut_grade += 1;
}
}
break;
case transit:
{
if (_cur_state == sustain) {
_cur_grade = _fut_grade;
_cur_state = _fut_state;
if (_fut_grade > _cur_grade) {
_fut_state = sustain;
} else {
_fut_state = trial;
}
} else {
_cur_grade = _fut_grade;
_cur_state = _fut_state;
_fut_state = sustain;
}
}
break;
case sustain:
{
_cur_state = _fut_state;
_cur_grade = _fut_grade;
/* See if need to downgrade */
if (_fut_grade < _high) {
for (long i = 0; i < _playlist->count(); i++) {
CCell& cc = _playlist->item(i)->item_ref(_cur_grade);
if (cc._tleft < 0) {
for (long j = 0; j < _playlist->count(); j++) {
CCell& cell0 = _playlist->item(j)->item_ref(
_cur_grade
);
cell0._tleft = 0;
cell0._tdelta = 0;
CCell& cell1 = _playlist->item(j)->item_ref(
_cur_grade+1
);
cell1._tleft = 0;
cell1._tdelta = 0;
cell1._cpf = 0;
}
_fut_state = transit;
_fut_grade = _cur_grade+1;
PaceMaker::instance()->cont_eval(
MaxTransit + SAMPLE_PERIOD
);
return;
}
}
}
}
break;
}
if (_fut_state == transit) {
PaceMaker::instance()->cont_eval(MaxTransit + SAMPLE_PERIOD);
} else {
PaceMaker::instance()->cont_eval(SAMPLE_PERIOD);
}
}
void EventImpl::start (Scheduler* p, Sec sec, USec usec) {
if (!_running) {
_running = true;
globalID++;
}
long index = find_player(p, _playerlist);
if (index >= 0) {
CCell cell;
CCellList* clist = _playlist->item(index);
for (long i = 0; i < clist->count(); i++) {
clist->item_ref(i) = cell;
}
}
p->start(sec, usec);
play(p, sec, usec);
}
void EventImpl::stop (Scheduler* p, Sec sec, USec usec) {
long index = find_player(p, _playerlist);
if (index >= 0) {
CCell cell;
CCellList* clist = _playlist->item(index);
for (long i = 0; i < clist->count(); i++) {
clist->item_ref(i) = cell;
}
}
p->stop(sec, usec);
}
void EventImpl::adjust (Scheduler* p) {
if (_playerlist == nil) {
return;
}
USec period = p->get_period();
long index = find_player(p, _playerlist);
if (index < 0) {
return;
}
CCellList* clist = _playlist->item(index);
Grade level = clist->count()-1;
for (long i = 0; i < clist->count(); i++) {
if (clist->item_ref(i)._cpf < period) {
level = i;
break;
}
}
if (level < _fut_grade) {
level = _fut_grade - 1;
//printf("attempted by EventKeeper\n");
}
if (level != _fut_grade) {
_cur_state = _fut_state;
_fut_state = transit;
_cur_grade = _fut_grade;
_fut_grade = level;
for (long j = 0; j < _playlist->count(); j++) {
CCell& cell0 = _playlist->item(j)->item_ref(
_cur_grade
);
cell0._tleft = 0;
cell0._tdelta = 0;
CCell& cell1 = _playlist->item(j)->item_ref(
_fut_grade
);
cell1._tleft = 0;
cell1._tdelta = 0;
if (_fut_grade < _cur_grade) {
cell0._cpf = 0;
cell1._cpf = 0;
} else {
cell1._cpf = 0;
}
}
PaceMaker::instance()->cont_eval(MaxTransit+SAMPLE_PERIOD);
}
}
/*******************************************************************/
EventKeeper::EventKeeper (Pacer* root) {
_impl = new EventImpl(root);
}
EventKeeper::~EventKeeper () {
delete _impl;
}
void EventKeeper::adjust (Scheduler* s) {
_impl->adjust(s);
}
void EventKeeper::eval (Sec sec, USec usec) {
_impl->eval(sec, usec);
}
void EventKeeper::startall (Sec sec, USec usec) {
_impl->startall(sec, usec);
}
void EventKeeper::stopall (Sec sec, USec usec) {
_impl->stopall(sec, usec);
}
void EventKeeper::start (Scheduler* s, Sec sec, USec usec) {
_impl->start(s, sec, usec);
}
void EventKeeper::play (Scheduler* s, Sec sec, USec usec) {
_impl->play(s, sec, usec);
}
void EventKeeper::stop (Scheduler* s, Sec sec, USec usec) {
_impl->stop(s, sec, usec);
}
/*******************************************************************/
class Cycle {
public:
Cycle();
public:
unsigned long _cycle;
unsigned long _cur_cycle;
};
Cycle::Cycle () {
_cycle = MIN_CYCLE;
_cur_cycle = 0;
}
declareList (CycleList, Cycle);
implementList (CycleList, Cycle);
class DampedImpl : public EventImpl {
public:
DampedImpl(Pacer* r);
virtual ~DampedImpl();
virtual void startall(Sec, USec);
virtual void eval(Sec, USec);
virtual void adjust(Scheduler*);
protected:
CycleList* _cyclelist;
};
DampedImpl::DampedImpl (Pacer* r) : EventImpl (r) {
_cyclelist = nil;
}
DampedImpl::~DampedImpl () {
delete _cyclelist;
}
void DampedImpl::startall (Sec sec, USec usec) {
EventImpl::startall(sec, usec);
if (_cyclelist == nil) {
Grade grades = _high-_low+1;
_cyclelist = new CycleList(grades);
Cycle cycle;
for (long i = 0; i < grades; i++) {
_cyclelist->append(cycle);
}
}
}
void DampedImpl::eval (Sec sec, USec usec) {
if (!_running) {
return;
}
switch(_fut_state) {
case trial:
{
_cur_state = _fut_state;
/* See if need to downgrade */
if (_fut_grade < _high) {
for (long i = 0; i < _playlist->count(); i++) {
CCell& cc = _playlist->item(i)->item_ref(_fut_grade);
if (cc._tleft < 0) {
for (long j = 0; j < _playlist->count(); j++) {
CCell& cell0 = _playlist->item(j)->item_ref(
_fut_grade
);
cell0._tleft = 0;
cell0._tdelta = 0;
CCell& cell1 = _playlist->item(j)->item_ref(
_fut_grade+1
);
cell1._tleft = 0;
cell1._tdelta = 0;
cell1._cpf = 0;
}
_fut_state = transit;
break;
}
}
}
if (_fut_state != transit) {
//printf("succeeded\n");
_fut_state = sustain;
_cur_grade = _fut_grade;
Cycle& cycle = _cyclelist->item_ref(_fut_grade);
cycle._cur_cycle = 0;
if (_fut_grade < _high) {
Cycle& past_cycle = _cyclelist->item_ref(_fut_grade+1);
if (past_cycle._cycle > MIN_CYCLE) {
past_cycle._cycle--;
}
past_cycle._cur_cycle = 0;
}
} else {
//printf("failed\n");
_cur_grade = _fut_grade;
_fut_grade += 1;
Cycle& cycle = _cyclelist->item_ref(_fut_grade);
if (cycle._cycle < MAX_CYCLE) {
cycle._cycle++;
}
cycle._cur_cycle = 0;
}
}
break;
case transit:
{
EventImpl::eval(sec, usec);
return;
}
break;
case sustain:
{
EventImpl::eval(sec, usec);
if (_fut_state == sustain) {
/* See if need to upgrade */
if (_cur_grade > _low) {
Cycle& cycle = _cyclelist->item_ref(_fut_grade);
cycle._cur_cycle++;
if (cycle._cur_cycle > cycle._cycle) {
cycle._cur_cycle = 0;
for (long j = 0; j < _playlist->count(); j++) {
CCell& cell0 = _playlist->item(j)->item_ref(
_cur_grade
);
cell0._tleft = 0;
cell0._tdelta = 0;
CCell& cell1 = _playlist->item(j)->item_ref(
_cur_grade-1
);
cell1._tleft = 0;
cell1._tdelta = 0;
}
//printf("attempted by Damped_Osc/PCKeeper\n");
_fut_state = transit;
_fut_grade = _cur_grade-1;
}
}
} else {
return;
}
}
break;
}
if (_fut_state == transit) {
PaceMaker::instance()->cont_eval(MaxTransit + SAMPLE_PERIOD);
} else {
PaceMaker::instance()->cont_eval(SAMPLE_PERIOD);
}
}
void DampedImpl::adjust (Scheduler* p) {
EventImpl::adjust(p);
if (_fut_state == transit) {
Cycle& cycle0 = _cyclelist->item_ref(_cur_grade);
cycle0._cur_cycle = 0;
Cycle& cycle1 = _cyclelist->item_ref(_fut_grade);
cycle1._cur_cycle = 0;
}
}
/*******************************************************************/
DampedKeeper::DampedKeeper (Pacer* root) {
_impl = new DampedImpl(root);
}
DampedKeeper::~DampedKeeper () {
delete _impl;
}
void DampedKeeper::adjust (Scheduler* s) {
_impl->adjust(s);
}
void DampedKeeper::eval (Sec sec, USec usec) {
_impl->eval(sec, usec);
}
void DampedKeeper::startall (Sec sec, USec usec) {
_impl->startall(sec, usec);
}
void DampedKeeper::stopall (Sec sec, USec usec) {
_impl->stopall(sec, usec);
}
void DampedKeeper::start (Scheduler* s, Sec sec, USec usec) {
_impl->start(s, sec, usec);
}
void DampedKeeper::play (Scheduler* s, Sec sec, USec usec) {
_impl->play(s, sec, usec);
}
void DampedKeeper::stop (Scheduler* s, Sec sec, USec usec) {
_impl->stop(s, sec, usec);
}
/*******************************************************************/
class PCImpl : public DampedImpl {
public:
PCImpl(Pacer*);
virtual ~PCImpl();
virtual void eval(Sec, USec);
};
PCImpl::PCImpl (Pacer* p) : DampedImpl (p) {}
PCImpl::~PCImpl () {}
void PCImpl::eval (Sec sec, USec usec) {
if (!_running) {
return;
}
if (_fut_state == trial) {
_cur_state = _fut_state;
USec credit = 0;
USec penalty = 0;
/* See if need to downgrade */
if (_fut_grade < _high) {
for (long i = 0; i < _playlist->count(); i++) {
CCell& cc = _playlist->item(i)->item_ref(_fut_grade);
if (cc._tleft < 0) {
penalty = -cc._tleft;
for (long j = 0; j < _playlist->count(); j++) {
CCell& cell0 = _playlist->item(j)->item_ref(
_fut_grade
);
cell0._tleft = 0;
cell0._tdelta = 0;
CCell& cell1 = _playlist->item(j)->item_ref(
_fut_grade+1
);
cell1._tleft = 0;
cell1._tdelta = 0;
cell1._cpf = 0;
}
_fut_state = transit;
break;
} else {
credit += cc._tleft;
}
}
}
if (_fut_state != transit) {
//printf("succeeded\n");
_fut_state = sustain;
_cur_grade = _fut_grade;
Cycle& cycle = _cyclelist->item_ref(_fut_grade);
cycle._cur_cycle = 0;
if (_fut_grade < _high) {
Cycle& past_cycle = _cyclelist->item_ref(_fut_grade+1);
if (past_cycle._cycle > MIN_CYCLE) {
past_cycle._cycle -= credit/USEC_TO_CYCLE;
}
past_cycle._cur_cycle = 0;
}
PaceMaker::instance()->cont_eval(SAMPLE_PERIOD);
} else {
//printf("failed\n");
_cur_grade = _fut_grade;
_fut_grade += 1;
Cycle& cycle = _cyclelist->item_ref(_fut_grade);
if (cycle._cycle < MAX_CYCLE) {
cycle._cycle += penalty/USEC_TO_CYCLE;
}
cycle._cur_cycle = 0;
PaceMaker::instance()->cont_eval(MaxTransit + SAMPLE_PERIOD);
}
} else {
DampedImpl::eval(sec, usec);
}
}
/*******************************************************************/
PCKeeper::PCKeeper (Pacer* root) {
_impl = new PCImpl(root);
}
PCKeeper::~PCKeeper () {
delete _impl;
}
void PCKeeper::adjust (Scheduler* s) {
_impl->adjust(s);
}
void PCKeeper::eval (Sec sec, USec usec) {
_impl->eval(sec, usec);
}
void PCKeeper::startall (Sec sec, USec usec) {
_impl->startall(sec, usec);
}
void PCKeeper::stopall (Sec sec, USec usec) {
_impl->stopall(sec, usec);
}
void PCKeeper::start (Scheduler* s, Sec sec, USec usec) {
_impl->start(s, sec, usec);
}
void PCKeeper::play (Scheduler* s, Sec sec, USec usec) {
_impl->play(s, sec, usec);
}
void PCKeeper::stop (Scheduler* s, Sec sec, USec usec) {
_impl->stop(s, sec, usec);
}
/*******************************************************************/
class CoherenceImpl : public EventImpl {
public:
CoherenceImpl(Pacer* r);
virtual ~CoherenceImpl();
void eval(Sec, USec);
};
CoherenceImpl::CoherenceImpl (Pacer* r) : EventImpl (r) {}
CoherenceImpl::~CoherenceImpl () {}
void CoherenceImpl::eval (Sec sec, USec usec) {
if (!_running) {
return;
}
switch(_fut_state) {
case trial:
{
_cur_state = _fut_state;
/* See if need to downgrade */
if (_fut_grade < _high) {
for (long i = 0; i < _playlist->count(); i++) {
CCell& cc = _playlist->item(i)->item_ref(_fut_grade);
if (cc._tleft < 0) {
for (long j = 0; j < _playlist->count(); j++) {
CCell& cell0 = _playlist->item(j)->item_ref(
_fut_grade
);
cell0._tleft = 0;
cell0._tdelta = 0;
CCell& cell1 = _playlist->item(j)->item_ref(
_fut_grade+1
);
cell1._tleft = 0;
cell1._tdelta = 0;
cell1._cpf = 0;
}
_fut_state = transit;
CCell& acell = _playlist->item(i)->item_ref(
_fut_grade+1
);
acell._coherence /= 2;
break;
} else {
CCell& acell = _playlist->item(i)->item_ref(
_fut_grade+1
);
acell._coherence *= 1.2;
if (acell._coherence > 1.0) {
acell._coherence = 1.0;
}
}
}
}
if (_fut_state != transit) {
_fut_state = sustain;
_cur_grade = _fut_grade;
//printf("succeeded \n");
} else {
_cur_grade = _fut_grade;
_fut_grade += 1;
//printf("failed \n");
}
}
break;
case transit:
{
EventImpl::eval(sec, usec);
return;
}
break;
case sustain:
{
EventImpl::eval(sec, usec);
if (_fut_state == sustain) {
/* See if need to upgrade */
if (_cur_grade > _low) {
for (long i = 0; i < _playlist->count(); i++) {
USec period = _playerlist->item(i)->get_period();
CCell& b = _playlist->item(i)->item_ref(_cur_grade);
CCell& a = _playlist->item(i)->item_ref(_cur_grade-1);
if (b._tdelta > 0) {
PaceMaker::instance()->cont_eval(SAMPLE_PERIOD);
return;
}
float delta = b._tdelta;
float cpf1 = b._cpf-delta;
float cpf0 = a._cpf-a._tdelta;
USec est = (USec) (cpf0 + cpf0/cpf1*delta*b._coherence);
if (est > (period-TOL)) {
PaceMaker::instance()->cont_eval(SAMPLE_PERIOD);
return;
}
}
//printf("attempted by CohKeeper\n");
for (long j = 0; j < _playlist->count(); j++) {
CCell& cell0 = _playlist->item(j)->item_ref(
_cur_grade
);
cell0._tleft = 0;
cell0._tdelta = 0;
CCell& cell1 = _playlist->item(j)->item_ref(
_cur_grade-1
);
cell1._tleft = 0;
cell1._tdelta = 0;
}
_fut_state = transit;
_fut_grade = _cur_grade-1;
}
} else {
return;
}
}
break;
}
if (_fut_state == transit) {
PaceMaker::instance()->cont_eval(MaxTransit + SAMPLE_PERIOD);
} else {
PaceMaker::instance()->cont_eval(SAMPLE_PERIOD);
}
}
/*******************************************************************/
CoherenceKeeper::CoherenceKeeper (Pacer* r) {
_impl = new CoherenceImpl(r);
}
CoherenceKeeper::~CoherenceKeeper () {
delete _impl;
}
void CoherenceKeeper::startall (Sec sec, USec usec) {
_impl->startall(sec, usec);
}
void CoherenceKeeper::stopall (Sec sec, USec usec) {
_impl->stopall(sec, usec);
}
void CoherenceKeeper::play (Scheduler* p, Sec sec, USec usec) {
_impl->play(p, sec, usec);
}
void CoherenceKeeper::start (Scheduler* p, Sec sec, USec usec) {
_impl->start(p, sec, usec);
}
void CoherenceKeeper::stop (Scheduler* p, Sec sec, USec usec) {
_impl->stop(p, sec, usec);
}
void CoherenceKeeper::eval (Sec sec, USec usec) {
_impl->eval(sec, usec);
}
void CoherenceKeeper::adjust (Scheduler* p) {
_impl->adjust(p);
}
| 30ba3e03452dfe01791a5bb5fb66b1293fa4239c | [
"Markdown",
"C",
"C++"
] | 20 | C++ | binshengliu/interviews-3.2a | df4e990ac7a8beb715abe9fc9f87096896f951ff | 733a9a1d056e312798b0b19849ee62d122d55526 |
refs/heads/master | <file_sep>package com.dudv2.javafx.service;
import com.dudv2.javafx.model.Student;
import org.springframework.stereotype.Service;
@Service
public class AuthService {
private final Student mockData = new Student("dudv2", "123");
public boolean authenticate(String username, String password) {
if (username.equals(mockData.getUsername()) && password.equals(mockData.getPassword())) {
return true;
}
return false;
}
}
<file_sep>package com.dudv2.javafx.ui.login;
import com.dudv2.javafx.SpringBootExampleApplication;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import net.rgielen.fxweaver.core.FxWeaver;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class LoginApp extends Application {
private ConfigurableApplicationContext applicationContext;
@Override
public void init() throws Exception {
String[] args = getParameters().getRaw().toArray(new String[0]);
this.applicationContext = new SpringApplicationBuilder()
.sources(SpringBootExampleApplication.class)
.run(args);
// this.applicationContext = SpringApplication.run(LoginApp.class);
}
@Override
public void start(Stage primaryStage) throws Exception {
FxWeaver fxWeaver = applicationContext.getBean(FxWeaver.class);
Parent root = fxWeaver.loadView(LoginController.class);
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
@Override
public void stop() throws Exception {
this.applicationContext.close();
Platform.exit();
}
}
<file_sep>package com.dudv2.javafx.constant;
public class RegexConstant {
public static final String USERNAME_REGEX = "";
}
| 4e88ff3d8bcbc25095fbd9059e39ed06d8e54dd5 | [
"Java"
] | 3 | Java | duBK1995/javafx-example | a00f5f2a55f5f55f380a6014fb170d0a840bf500 | db12b1966ab4a9116d329143e441143b888a349c |
refs/heads/master | <repo_name>kennethabilar/react-express-starter<file_sep>/README.md
# React Express Starter
### Install dependencies
```sh
$ npm install
```
### Install client dependencies
```sh
$ npm run client-install
```
### Start the server
```sh
$ npm run server
```
### Start the client
```sh
$ npm run client
```
### Start the client and server
```sh
$ npm run dev
```
<file_sep>/client/src/components/Users.js
import React, { Component } from 'react';
import axios from 'axios';
class Users extends Component {
constructor() {
super();
this.state = {
users: []
}
}
componentDidMount() {
axios.get('/api/users')
.then(res => {
this.setState({ users: res.data }, () => {
console.log(this.state.users);
});
})
.catch(err => {
console.log(err);
});
}
render() {
return (
<div className="users">
<ul>
{
this.state.users.map(user => {
return (
<li key={user.id}>{user.first_name} {user.last_name} - {user.email}</li>
);
})
}
</ul>
</div>
);
}
}
export default Users;
| fd30d3aa67b7c604d5893c60ecdd37940df9749f | [
"Markdown",
"JavaScript"
] | 2 | Markdown | kennethabilar/react-express-starter | 29d2f45dd382f8ffa1b22422d84680c4410bcc0b | e2a67666e09079a8b279c75f3d140c8878e2fe7a |
refs/heads/master | <repo_name>amol6022/StockPricePrediction<file_sep>/auto_arima.py
from pyramid.arima import auto_arima
data = df.sort_index(ascending=True, axis=0)
train = data[:987]
valid = data[987:]
training = train['Close']
validation = valid['Close']
model = auto_arima(training, start_p=1, start_q=1,max_p=3, max_q=3, m=12,start_P=0, seasonal=True,d=1, D=1, trace=True,error_action='ignore',suppress_warnings=True)
model.fit(training)
forecast = model.predict(n_periods=248)
forecast = pd.DataFrame(forecast,index = valid.index,columns=['Prediction'])
rms=np.sqrt(np.mean(np.power((np.array(valid['Close'])-np.array(forecast['Prediction'])),2)))
rms
# RMS VALUE IS FOUND TO BE 44.954584993246954
#plot
plt.plot(train['Close'])
plt.plot(valid['Close'])
plt.plot(forecast['Prediction'])
<file_sep>/knn.py
#importing libraries
from sklearn import neighbors
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0, 1))
#scaling data
x_train_scaled = scaler.fit_transform(x_train)
x_train = pd.DataFrame(x_train_scaled)
x_valid_scaled = scaler.fit_transform(x_valid)
x_valid = pd.DataFrame(x_valid_scaled)
#using gridsearch to find the best parameter
params = {'n_neighbors':[2,3,4,5,6,7,8,9]}
knn = neighbors.KNeighborsRegressor()
model = GridSearchCV(knn, params, cv=5)
#fit the model and make predictions
model.fit(x_train,y_train)
preds = model.predict(x_valid)
#rmse
rms=np.sqrt(np.mean(np.power((np.array(y_valid)-np.array(preds)),2)))
rms
# RMS VALUE : 115.17086550026721
#plot
valid['Predictions'] = 0
valid['Predictions'] = preds
plt.plot(valid[['Close', 'Predictions']])
plt.plot(train['Close'])
<file_sep>/linear_regression.py
# importing libraries
import pandas as pd
import numpy as np
# reading the data
df = pd.read_csv('NSE-TATAGLOBAL11.csv')
# looking at the first five rows of the data
print(df.head())
print('\n Shape of the data:')
print(df.shape)
#setting index as date values
df['Date'] = pd.to_datetime(df.Date,format='%Y-%m-%d')
df.index = df['Date']
#sorting
data = df.sort_index(ascending=True, axis=0)
#creating a separate dataset
new_data = pd.DataFrame(index=range(0,len(df)),columns=['Date', 'Close'])
for i in range(0,len(data)):
new_data['Date'][i] = data['Date'][i]
new_data['Close'][i] = data['Close'][i]
#create features
from fastai.structured import add_datepart
add_datepart(new_data, 'Date')
new_data.drop('Elapsed', axis=1, inplace=True) #elapsed will be the time stamp
new_data['mon_fri'] = 0
for i in range(0,len(new_data)):
if (new_data['Dayofweek'][i] == 0 or new_data['Dayofweek'][i] == 4):
new_data['mon_fri'][i] = 1
else:
new_data['mon_fri'][i] = 0
#split into train and validation
train = new_data[:987]
valid = new_data[987:]
x_train = train.drop('Close', axis=1)
y_train = train['Close']
x_valid = valid.drop('Close', axis=1)
y_valid = valid['Close']
#implement linear regression
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(x_train,y_train)
Results
#make predictions and find the rmse
preds = model.predict(x_valid)
rms=np.sqrt(np.mean(np.power((np.array(y_valid)-np.array(preds)),2)))
rms
#plot
valid['Predictions'] = 0
valid['Predictions'] = preds
valid.index = new_data[987:].index
train.index = new_data[:987].index
plt.plot(train['Close'])
plt.plot(valid[['Close', 'Predictions']])
| 55b0774dfd88ef4d254cdf6133da0b2ea5c1aeb8 | [
"Python"
] | 3 | Python | amol6022/StockPricePrediction | 2c3b74b8f14e9ca5d55806ee919fb74c7cde9602 | 264248b0bddd2bbc29152294f1ed2b5ae5622125 |
refs/heads/master | <repo_name>Leoprogramming/chonky-husky<file_sep>/background.js
class Background {
constructor() {}
drawingBackground() {
//width and height are predefined variables from p5, and its the width and height of the canvas
game.backgroundImgs.forEach(function (elem) {
elem.x -= elem.speed;
//image(source, x coordinate, y coordinate, width, height)
image(elem.src, elem.x, 0, width, height);
image(elem.src, elem.x + width, 0, width, height);
if (elem.x <= - width) {
elem.x = 0;
}
});
}
}<file_sep>/player.js
class Player {
constructor() {
this.gravity = 0.1;
this.speed = 0;
this.jumps = 0;
this.x = 50;
// this.jumpSound = loadSound("/assets/jump-sound.mp3", loaded)
}
setupPlayer() {
//here i am setting some variables based on the images height and width
this.y = height - game.playerImg.height;
this.width = game.playerImg.width;
this.height = game.playerImg.height;
}
jump() {
this.jumps += 1;
console.log(this.y);
if (this.y > 640) {
song.play();
}
// check how many times the player before touching the ground
if (this.jumps < 2) {
this.speed = -10;
}
}
moveRight() {
this.x += 20;
}
moveLeft() {
this.x -= 20;
}
drawingThePlayer() {
this.speed += this.gravity;
this.y += this.speed;
// this if statement is to check that gravity doesn't affect the Husky if he is outside of the canvas
if (this.y >= height - game.playerImg.height) {
this.y = height - game.playerImg.height;
//we set the jumps to 0 so we can jump again
this.jumps = 0;
}
image(game.playerImg, this.x, this.y);
}
}<file_sep>/main.js
const game = new Game();
let song;
let points = 0;
let lives = 3;
let bestTime = localStorage.getItem("fastestTime");
let gameStart = false;
let finalImage;
if (!bestTime) {
bestTime = 0;
}
function preload() {
game.preloadGame();
finalImage = loadImage("assets/player/husky-end-message.png");
}
function setup() {
createCanvas(windowWidth, 600);
game.setup();
background = new Background();
song = loadSound("assets/howl2-trim.mp3");
}
function draw() {
if (gameStart === true) {
document.getElementById("scorebox").style.visibility = "visible";
console.log(bestTime);
if (points > bestTime) {
localStorage.setItem("fastestTime", points);
document.querySelector("#best").innerHTML = points;
}
if (lives > 0) {
game.drawingGame();
document.querySelector("#score").innerText = points;
if (points > 0) {
game.playerImg = game.playerImg2;
}
}
}
if (lives <= 0) {
game.drawingGame();
game.playerImg = game.playerImg3;
image(finalImage, 200, 0);
setTimeout(() => noLoop(), 500) ;
document.querySelector(".game-over").style.visibility = "visible";
}
}
function keyPressed() {
if (keyCode == 32) {
game.player.jump();
}
if (keyCode == 37) {
game.player.moveLeft();
}
if (keyCode == 39) {
game.player.moveRight();
}
if (keyCode === 13) {
document.querySelector(".game-start").style.display = "none";
gameStart = true;
}
if (keyCode === 8) {
window.location.reload();
}
}
document.querySelector("#best").innerHTML = bestTime;<file_sep>/README.md
# chonky-husky
Fat Husky Game built with the objective of learning more about JavaScript animations, games, P5.js Library and more.
<file_sep>/obstacles.js
class Obstacles {
constructor(randomY) {
this.x = width;
this.y = randomY;
this.img = game.treatImg;
this.imgBad = game.badTreatImg;
this.width = this.img.width;
this.height = this.img.height;
this.score = 0;
}
checkCollision(player) {
let leftSide = this.x;
let rightSide = this.x + this.width;
let playerLeftSide = player.x;
let playerRightSide = player.x + player.width;
let topSide = this.y;
let bottomSide = this.y + this.height;
let playerTopSide = player.y;
let playerBottomSide = player.y + player.height;
let xCollision =
leftSide > playerLeftSide - 10 &&
leftSide < playerRightSide + 10 &&
rightSide > playerLeftSide - 10 &&
rightSide < playerRightSide + 10;
let yCollision =
topSide > playerTopSide - 10 &&
topSide < playerBottomSide + 10 &&
bottomSide > playerTopSide - 10 &&
bottomSide < playerBottomSide + 10;
if (yCollision && xCollision) {
points += 5;
console.log(this.score);
return true;
} else {
return false;
}
}
drawingObstacles() {
this.x -= 2;
image(this.img, this.x, this.y, this.width, this.height);
}
}<file_sep>/game.js
class Game {
constructor() {
this.background = new Background();
this.player = new Player();
this.obstacles = [];
this.chocolate = [];
}
preloadGame() {
this.backgroundImgs = [
{ src: loadImage("assets/background/background-snow.jpg"), x: 0, speed: 0 },
{ src: loadImage("assets/background/background-snow.jpg"), x: 0, speed: 1 },
{ src: loadImage("assets/background/background-snow.jpg"), x: 0, speed: 2 },
{ src: loadImage("assets/background/background-snow.jpg"), x: 0, speed: 3 },
{ src: loadImage("assets/background/background-snow.jpg"), x: 0, speed: 4 },
];
this.playerImg = loadImage("assets/player/husky-loop.gif");
this.playerImg2 = loadImage("assets/player/husky-fat-small.jpg");
this.playerImg3 = loadImage("assets/player/sick-husky.png");
this.treatImg = loadImage("assets/treats/treat-small.png");
this.badTreatImg = loadImage("assets/treats/bad-treat.png");
}
setup() {
this.player.setupPlayer();
}
drawingGame() {
clear();
// this is the framerate we want our game to run
frameRate(20);
this.background.drawingBackground();
this.player.drawingThePlayer();
// frameCount is a p5 variable that counts all of the loops/frames that the game is doing or having.
if (frameCount % 60 === 0) {
//random function from p5
let randomNumber = random(0, height - 60);
this.obstacles.push(new Obstacles(randomNumber));
}
this.obstacles.forEach((elem) => {
// we draw all of the obstacles
elem.drawingObstacles();
elem.checkCollision(this.player);
});
this.obstacles = this.obstacles.filter((obstacle) => {
if (obstacle.checkCollision(this.player)) {
return false;
} else {
return true;
}
});
if (frameCount % 20 === 0) {
//random function from p5
let randomNumber = random(0, height - 60);
this.chocolate.push(new Chocolate(randomNumber));
}
this.chocolate.forEach((elem) => {
// we draw all of the chocolate
elem.drawingChocolate();
elem.checkCollision(this.player);
});
this.chocolate = this.chocolate.filter((chocolate) => {
if (chocolate.checkCollision(this.player)) {
return false;
} else {
return true;
}
});
}
} | 67d44e19d2aa78f89f923639eb3cdea418e71607 | [
"JavaScript",
"Markdown"
] | 6 | JavaScript | Leoprogramming/chonky-husky | b3d664b1402d4386c18c3dfe6580b4752559f355 | 474c9958ac6adda8de744685225c0c3a8ca6c74b |
refs/heads/master | <file_sep>package com.feng.sauron.client.plugin.httpclient.httpclient4.printlog;
import com.feng.sauron.client.plugin.PrintTraceLog;
import com.feng.sauron.client.plugin.TracerAdapterFactory;
/**
* @author <EMAIL>
* @version 创建时间:2016年10月31日 上午11:45:46
*
*/
public class HttpRequestExecutorPrintLog implements PrintTraceLog {
private HttpRequestExecutorPrintLog() {
}
private static class InnerClass {
private static final HttpRequestExecutorPrintLog Inner_Class = new HttpRequestExecutorPrintLog();
}
public static HttpRequestExecutorPrintLog getInstances() {
return InnerClass.Inner_Class;
}
@Override
public String print(TracerAdapterFactory tracerAdapterFactory) {
return null;
}
}
<file_sep>package com.fengjr.sauron.test.web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.alibaba.rocketmq.client.exception.MQClientException;
import com.alibaba.rocketmq.client.producer.DefaultMQProducer;
import com.alibaba.rocketmq.client.producer.SendResult;
import com.alibaba.rocketmq.common.message.Message;
import com.feng.ipcenter.service.IPDataFileService;
import com.feng.sauron.client.annotations.TraceClass;
import com.feng.sauron.client.annotations.TraceMethod;
/**
* Created by lianbin.wang on 11/2/16.
*/
@TraceClass
public class RocketMQServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
DefaultMQProducer producer = new DefaultMQProducer("fengmq-test-group");
IPDataFileService bean = null;
@TraceMethod
@Override
public void init() throws ServletException {
producer.setNamesrvAddr("10.255.73.156:9876");
// producer.setNamesrvAddr("10.255.52.16:9876");
try {
producer.start();
} catch (MQClientException e) {
e.printStackTrace();
}
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "consumer.xml" });
bean = (IPDataFileService) context.getBean("ipDataFileService");
super.init();
context.start();
}
@Override
@TraceMethod
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Message message = new Message("fengmq-test", "my test content".getBytes());
try {
SendResult result = producer.send(message);
resp.getWriter().write("message send success, msgId:" + result.getMsgId());
} catch (Exception e) {
e.printStackTrace();
resp.getWriter().write("message send fail, " + e.getMessage());
}
String find = bean.find("172.16.17.32");
System.out.println(find);
}
@Override
@TraceMethod
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
<file_sep>package com.feng.sauron.client.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import com.feng.sauron.client.plugin.PreProcessTransformer;
import com.feng.sauron.client.plugin.jvm.JvmTracer;
import com.feng.sauron.client.plugin.jvm.SystemInfoTracer;
import com.feng.sauron.config.SauronConfig;
import com.feng.sauron.config.WatchableConfigClient;
import com.feng.sauron.utils.SauronLogUtils;
/**
* @author <EMAIL>
* @version 2016年11月15日 上午10:18:45
*
*/
@WebListener
public class SauronLoadTimeWeavingListener implements ServletContextListener, Switch {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
if (flag.get()) {
try {//以下每个方法的顺序不要乱动,小心死锁 ,看似不影响,其实很重要
WatchableConfigClient.getInstance().get(SauronConfig.getAPP_NAME(), "jvm-switch", "ON");
SauronInitializer.init();
SauronLogUtils.run();// 必须在最前面
JavaAgentMain.run();
JavaAgentWeaver javaAgentWeaver = new JavaAgentWeaver();
javaAgentWeaver.addTransformer(new PreProcessTransformer());
JvmTracer.run();
SystemInfoTracer.run();
System.err.println("sauron.init.success");
} catch (Exception ex) {
System.err.println("sauron.init.failure");
ex.printStackTrace();
} catch (Throwable e) {
System.err.println("sauron.init.failure");
e.printStackTrace();
}
flag.set(false);
}
// CopyOfRedefineClasse.run();
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
WatchableConfigClient.close();
System.err.println("ConfigClient Closed!");
}
}
<file_sep>package com.feng.sauron.client.agent;
import java.lang.instrument.Instrumentation;
import com.feng.sauron.client.listener.SauronInitializer;
import com.feng.sauron.client.plugin.PreProcessTransformer;
import com.feng.sauron.client.plugin.jvm.JvmTracer;
import com.feng.sauron.client.plugin.jvm.SystemInfoTracer;
import com.feng.sauron.utils.LogBackUtils;
/**
* @author <EMAIL>
* @version 2016年10月28日 下午2:16:10
*/
public class SauronAgent {
private static volatile Instrumentation instrumentation;
public static void premain(String options, Instrumentation inst) {
try {
SauronInitializer.init();
} catch (Exception e) {
} catch (Throwable e) {
}
LogBackUtils.run();
JvmTracer.run();
SystemInfoTracer.run();
instrumentation = inst;
inst.addTransformer(new PreProcessTransformer());
}
public static void agentmain(String options, Instrumentation inst) {
instrumentation = inst;
}
public static Instrumentation getInstrumentation() {
return instrumentation;
}
}
<file_sep>APP="sauron-warning"
#需要启动的Java主程序(main方法类)
APP_MAINCLASS=com.feng.sauron.warning.server.Startup_FengjrSauronWarningCore
LOG_BASE="/export/log"
LOG_DIR="$LOG_BASE/$APP"
APP_HOME="/export/server/$APP"
CONFIGPATH=$APP_HOME/conf
#STDOUT_FILE=$LOG_DIR/stdout.log
GC_FILE=$LOG_DIR/gc.log
export LANG="zh_CN.UTF-8"
export LC_ALL="zh_CN.UTF-8"
export JAVA_HOME=/export/local/jdk1.7
export JAVA_BIN=/export/local/jdk1.7/bin
export PATH=$PATH:$JAVA_BIN
JAVA_OPTS="-server -Xms2048m -Xmx2048m -XX:PermSize=128m -XX:MaxPermSize=128m -XX:+UseConcMarkSweepGC -verbose:gc -Xloggc:"$GC_FILE" -Dfile.encoding=UTF-8"
<file_sep>package com.feng.sauron.client.plugin.local.annotation;
/**
* @author <EMAIL>
* @version 创建时间:2016年10月27日 下午8:29:32
*
*/
public interface AnnotationTracerName {
public final static String TRACERNAME_STRING = "Annotation";
}
<file_sep>zookeeper.servers=bzk1.fengjr.inc:2181,bzk1.fengjr.inc:2181,bzk1.fengjr.inc:2181<file_sep>package com.feng.sauron.client.listener;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Method;
/**
* @author <EMAIL>
* @version 2016年10月11日 上午11:33:06
*
*/
public class JavaAgentWeaver {
private static final String JAVA_CORE_AGENT_CLASS_NAME = "com.feng.sauron.client.agent.SauronAgent";
private static final String JAVA_AGENT_CLASS_NAME = "com.feng.sauron.agent.SauronAgent";
private static Instrumentation inst = null;
public JavaAgentWeaver() {
getInstrumentation();
if (inst == null) {
throw new IllegalStateException("Java Agent is not found!");
}
}
public void addTransformer(ClassFileTransformer transformer) {
if (inst == null) {
throw new IllegalStateException("Java Agent Instrumentation is not ready!");
} else {
inst.addTransformer(transformer, true);
}
}
public Instrumentation getInstrumentation() {
try {
Class<?> agentClass = isInstrumentationAvailable();
// 顺序不能乱,先 agent 后 core_agent
if (agentClass == null) {
agentClass = isInstrumentationAvailable_core();
}
if (agentClass == null) {
System.err.println("Java Agent is required for Instrumentation.");
return null;
}
Method getInstrumentationMethod = agentClass.getMethod("getInstrumentation", new Class[0]);
inst = (Instrumentation) getInstrumentationMethod.invoke(agentClass, new Object[0]);
if (inst == null) {
System.err.println("Instrumentation is not functional!");
}
} catch (Exception e) {
System.err.println("getInstrumentation error ...");
throw new IllegalStateException("getInstrumentation error ...");
}
return inst;
}
public static Class<?> isInstrumentationAvailable() {
Class<?> agentClass = null;
try {
agentClass = Class.forName(JAVA_AGENT_CLASS_NAME, true, ClassLoader.getSystemClassLoader());// 使用系统classloader才能加载到 带有inst 变量的类
} catch (Exception e) {
}
return agentClass;
}
public static Class<?> isInstrumentationAvailable_core() {
Class<?> agentClass = null;
try {
agentClass = Class.forName(JAVA_CORE_AGENT_CLASS_NAME, true, ClassLoader.getSystemClassLoader());// 使用系统classloader才能加载到 带有inst 变量的类
} catch (Exception e) {
}
return agentClass;
}
}
| 35ae73c5d82878eb8f7a821d0a8ae391186752e9 | [
"Java",
"Shell",
"INI"
] | 8 | Java | buptcui/sauron | 1bdf050b5ccbfec478d9d90108fb8dfd39428f53 | aebd50d2ecfaf59074cbcee4c48d3212e98f461f |
refs/heads/master | <repo_name>rohanrocks29/ProgrammingAssignment2<file_sep>/cachematrix.R
# This code is written along the same lines of the example provided by
# coursera. The first function calculates the inverse of the matrix and stores
# it in 'm' in the global environment.
makeCacheMatrix <- function(x = matrix()) {
m <- NULL
set <- function(y) {
x <<- y
m <<- NULL
}
get <- function() x
# Calculate inverse of matrix using 'solve' function
# And store it in m as cached value
setinverse <- function(solve) m <<- solve
getinverse <- function() m
list(set = set, get = get,
setinverse = setinverse,
getinverse = getinverse)
}
## This function checks if a cached matrix exists. If it does then
# it returns the cached value and does not calculate the inverse
cacheSolve <- function(x = matrix(), ...) {
# Check for cached value and return if existing
m <- x$getinverse()
if(!is.null(m)) {
message("getting cached data")
return(m)
}
# If it doesnt exist, calculate inverse and store as cached
data <- x$get()
# Inverse of matrix
m <- solve(data)
x$setinverse(m)
# Return the inverse
m
}
| 1345a50bfa4186c534219b8bbc94d92aeda914c7 | [
"R"
] | 1 | R | rohanrocks29/ProgrammingAssignment2 | d2df596aee6a837d2f6ef6ebb2fe5677503ecd18 | 4e7f08194eee6e61271f40165d52d5bfc6eee538 |
refs/heads/master | <file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { routing } from './app.routing';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { VideoPlayerComponent } from './components/video-player/video-player.component';
import { LoginComponent } from './pages/login/login.component';
import { HomeComponent } from './pages/home/home.component';
import { NavbarComponent } from './components/navbar/navbar.component';
import { HeaderComponent } from './components/header/header.component';
import { MovieGenreRowComponent } from './components/movie-genre-row/movie-genre-row.component';
import { PlayerComponent } from './pages/player/player.component';
import { ModalMovieDetailsComponent } from './components/modal-movie-details/modal-movie-details.component';
import { MovieListService } from './services/movie-list.service';
import { UtilityService } from './services/utility.service';
import { DataService } from './services/data.service';
import { UserService } from './services/user.service';
import { AuthGuard } from './guard/auth.guard';
@NgModule({
declarations: [
AppComponent,
VideoPlayerComponent,
LoginComponent,
HomeComponent,
NavbarComponent,
HeaderComponent,
MovieGenreRowComponent,
PlayerComponent,
ModalMovieDetailsComponent
],
imports: [
BrowserModule,
FormsModule,
routing,
HttpClientModule,
HttpModule
],
providers: [
MovieListService,
DataService,
UtilityService,
UserService,
AuthGuard
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, OnInit, HostListener, Inject } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { DOCUMENT } from '@angular/platform-browser';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.scss']
})
export class NavbarComponent implements OnInit {
navBarScroll: string;
constructor(@Inject(DOCUMENT) private document: Document) { }
ngOnInit() {
}
@HostListener('window:scroll', [])
onWindowScroll() {
const number = this.document.documentElement.scrollTop || this.document.body.scrollTop || 0;
if (number > 100) {
this.navBarScroll = 'black';
} else {
this.navBarScroll = '';
}
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { MovieListService } from '../../services/movie-list.service';
@Component({
selector: 'app-player',
templateUrl: './player.component.html',
styleUrls: ['./player.component.css']
})
export class PlayerComponent implements OnInit {
public movieLink = '';
constructor(
private route: ActivatedRoute,
private movieListService: MovieListService
) {
// tslint:disable-next-line:radix
const id = parseInt(this.route.snapshot.paramMap.get('name'));
this.getVideoDetails(id);
}
ngOnInit() {
}
getVideoDetails(id) {
const body = JSON.stringify({'movie': '' + id, 'password': '<PASSWORD>'});
this.movieListService.getMovieDetails(body).subscribe(
(d) => {
console.log(d);
console.log(d[0]['link']);
this.movieLink = d[0]['link'];
}
);
}
}
<file_sep>SET GLOBAL local_infile = 1;
CREATE TABLE IF NOT EXISTS movies (id INT NOT NULL AUTO_INCREMENT, name VARCHAR(100), image VARCHAR(100), link VARCHAR(1000), PRIMARY KEY `id`(`id`));
<file_sep>#/bin/bash
dockerInstance="moviesDB";
dbUser="admin";
dbPass="<PASSWORD>";
dbInstance="MOVIES_DB";
dbTable="movies";
query="";
Log() {
#Check required parameters:
if [[ -z "$1" || -z "$2" ]]
then
echo "ERROR DURING PARSING LOG DATA. CHECK PARAMETERS";
exit 1;
fi;
#Set variables:
L_type=$1;
L_message=$2;
L_timeStamp=`date "+%Y/%m/%d %H:%M:%S"`;
#Return formatted message:
echo "$L_type | $L_timeStamp | $L_message";
}
doQuery (){
if [[ -z "$1" || -z "$2" || -z "$3" || -z "$4" || -z "$5" || -z "$6" ]]
then
Log "ERROR" "SOME PARAMETER IS NULL OR IVALID. PLEASE, CHECK THEM ALL: QUERY = $1 | DOCKER INSTANCE = $2 | DBUSER = $3 | DBPASS = $4 | DBINSTANCE = $5 | DBTABLE = $6";
exit 1;
fi;
#Set variables:
Q_query=$1;
Q_dockerInstance=$2;
Q_dbUser=$3;
Q_dbPass=$4;
Q_dbInstance=$5;
Q_dbTable=$6;
Q_values="";
#Building Query
docker exec -i $Q_dockerInstance mysql -u$dbUser -p$dbPass --local-infile $Q_dbInstance -e "$Q_query";
}
while getopts 'i:d:sh' OPTION; do
case "$OPTION" in
s)
query="select id, name, image, link from $dbTable";
;;
h)
echo -e "script usage: $(basename $0)\n$0 -i < name of csvfile containing the following format: NAME,IMAGE,MOVIE_LINK (one for each line) > | Insert the movies into DB\n$0 -d < path/name of file containing movies' ID (one for each line) > | Delete all movies with selected IDs from DB\n$0 -s | Return all movies on catalog\n$0 -h | Show this message" >&2
exit 0;
;;
i)
if [[ -z "$OPTARG" ]]
then
Log "ERROR" "-i needs an argument"
exit 1;
fi
CSVFile="$OPTARG";
#check if file exists
if [ ! -f $CSVFile ]
then
Log "Error" "File $parm does not exists";
exit 1;
fi
lastLine=`cat $CSVFile | wc -l`;
currentLine="1";
while read line
do
name=`echo $line | awk -F"," '{ print $1 }'`;
image=`echo $line | awk -F"," '{ print $2 }'`;
link=`echo $line | awk -F"," '{ print $3 }'`;
if [[ -z $name || -z $image || -z $link ]]
then
log "Error" "One or more parameters are null";
exit 1;
fi
if [[ $currentLine -lt $lastLine ]];
then
result="('$name','$image','$link'), ";
Q_values=$Q_values$result;
#echo "DENTRO LOOP: $Q_query";
else
result="('$name','$image','$link')";
Q_values=$Q_values$result;
fi
let "currentLine ++";
done < $CSVFile;
query="INSERT INTO movies (name, image, link) VALUES "$Q_values";";
mv $CSVFile $CSVFile.done;
;;
d)
if [[ -z "$OPTARG" ]]
then
Log "ERROR" "-d needs an argument"
exit 1;
fi
CSVFile="$OPTARG";
#check if file exists
if [ ! -f $CSVFile ]
then
Log "Error" "File $parm does not exists";
exit 1;
fi
lastLine=`cat $CSVFile | wc -l`;
currentLine="1";
while read line
do
if [[ ! -z $line ]]
then
if [[ $currentLine -lt $lastLine ]];
then
result="$line,";
Q_values=$Q_values$result;
else
result="$line";
Q_values=$Q_values$result;
fi
let "currentLine ++";
else
LOG "INFO" "Ignoring line $currentLine. Is it null?";
fi
done < $CSVFile;
query="DELETE FROM movies WHERE id in ($Q_values);";
mv $CSVFile $CSVFile.done;
;;
?)
echo "script usage: $(basename $0) [-i <csvfile with fields terminated by ',' for name, image and link values>] -> Insert movies into DB [-d <list with all ID's values] -> This option will be delete all movies from database [-s] -> get all movies list [h] -> help, show this message]" >&2
exit 1
;;
esac
done
doQuery "$query" $dockerInstance $dbUser $dbPass $dbInstance $dbTable
<file_sep>Flask
flask-restful
mysql-connector-python
<file_sep>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { DataService } from './data.service';
import { UtilityService } from './utility.service';
@Injectable()
export class InstitutionsService {
private apiUrl: string;
constructor(private dataService: DataService,
private utilityService: UtilityService) {
this.apiUrl = this.dataService.requestUrlBuilder(this.utilityService.apiContainer['institutionsAggregate'].url);
}
public getInstitutions(skip: number, take: number) {
return this.dataService.get(this.apiUrl);
}
}
<file_sep>from typing import List, Dict
from flask import Flask, jsonify, request
from flask_cors import CORS, cross_origin
import mysql.connector
import collections
app = Flask(__name__)
CORS(app, support_credentials=True)
def list_login(email, password) -> List[Dict]:
config = {
'user': 'admin',
'password': '<PASSWORD>',
'host': 'db_auth',
'port': '3306',
'database': 'auth'
}
connection = mysql.connector.connect(**config)
cursor = connection.cursor()
cursor.execute("SELECT * FROM users WHERE email='" + email + "' AND password='" + password + "'")
rows = cursor.fetchall()
objects_list = []
for row in rows:
d = collections.OrderedDict()
d['id'] = row[0]
d['firstname'] = row[1]
d['lastname'] = row[2]
d['email'] = row[3]
d['password'] = row[4]
objects_list.append(d)
cursor.close()
connection.close()
if len(objects_list):
result = {'success': 'ok'}
return result
# @app.route('/', methods=['GET'])
# def index() -> str:
# return jsonify(list_login())
# @app.route('/login', methods=['POST'])
# @cross_origin(supports_credentials=True)
# def addOne():
# email = request.json.get('email')
# password = request.json.get('password')
# return jsonify(list_login(email, password))
@app.route('/login', methods=['POST'])
def create_task():
if not request.json:
return jsonify({'error': "Content-type error"})
email = request.json['email']
password = request.json.get('password', "")
return jsonify(list_login(''.join(email), ''.join(password)))
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5001)
<file_sep>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { DataService } from './data.service';
import { IMovie } from '../interface/movieList';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
@Injectable()
export class MovieListService {
private apiUrl = 'http://localhost:5000/movie';
private apiVideoUrl = 'http://localhost:5000/';
// private apiPhpURL = 'http://localhost:6000/movielist.php';
constructor(private dataService: DataService,
private http: HttpClient) {
}
public getData(): Observable<IMovie[]> {
return this.dataService.get<IMovie[]>(this.apiUrl);
}
public getMovieDetails(data) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.post(this.apiVideoUrl, data, httpOptions);
}
// public getMovieListPHP(): Observable<IMovie> {
// return this.dataService.get<IMovie>(this.apiPhpURL);
// }
}
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.8.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: 13-Jan-2019 às 23:25
-- Versão do servidor: 5.7.23
-- versão do PHP: 7.2.10
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `cosnflix`
--
-- --------------------------------------------------------
--
-- Estrutura da tabela `users`
--
DROP TABLE IF EXISTS `users`;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`firstname` varchar(20) NOT NULL,
`lastname` varchar(20) NOT NULL,
`email` varchar(90) NOT NULL,
`password` varchar(90) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;
--
-- Extraindo dados da tabela `users`
--
INSERT INTO `users` (`id`, `firstname`, `lastname`, `email`, `password`) VALUES
(1, 'cosnflix', 'feup', '<EMAIL>', '<PASSWORD>');
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>version: '3.3' # specify docker-compose version
# Define the services/containers to be run
services:
angular: # name of the service
build: angular-client # specify the directory of the Dockerfile
hostname: frontend-client
volumes:
- ./angular-client:/usr/src/app
working_dir: /usr/src/app
ports:
- "4201:4200" # specify port forewarding
depends_on:
- auth-service-python
- movie-service-python
- catalog-service
links:
- auth-service-python
- movie-service-python
- catalog-service
auth-service-python: #name of the service
build: auth-server-python # specify the directory of the Dockerfile
hostname: auth-python
ports:
- "5001:5001" #specify ports forewarding
links:
- db_auth
depends_on:
- db_auth
catalog-service: #name of the service
build: catalog-server # specify the directory of the Dockerfile
hostname: catalog-host
ports:
- "6001:6001" #specify ports forewarding
volumes:
- ./catalog/img:/catalog/img
- ./catalog/movies:/catalog/movies
movie-service-python: #name of the service
build: ./movie-server-python # specify the directory of the Dockerfile
hostname: movie-service-python
ports:
- "5000:5000" #specify ports forewarding
links: #specify communication with another containers
- db_movies
depends_on:
- db_movies
db_movies:
image: mysql:latest
container_name: moviesDB
volumes:
- ./dbMovieData:/var/lib/mysql
- ./create_db_movies:/docker-entrypoint-initdb.d/
restart: always
ports:
- "3308:3306"
hostname: db-movie
environment:
MYSQL_ROOT_PASSWORD: <PASSWORD>
MYSQL_DATABASE: MOVIES_DB
MYSQL_USER: admin
MYSQL_PASSWORD: <PASSWORD>
db_auth:
image: mysql:latest
container_name: authDB
volumes:
- ./dbAuth:/var/lib/mysql
- ./create_db_auth:/docker-entrypoint-initdb.d/
restart: always
ports:
- "3307:3306"
hostname: db-auth
environment:
MYSQL_ROOT_PASSWORD: <PASSWORD>
MYSQL_DATABASE: auth
MYSQL_USER: admin
MYSQL_PASSWORD: <PASSWORD><file_sep>import { Component, OnInit, Input } from '@angular/core';
import { MovieListService } from '../../services/movie-list.service';
import { DataService } from '../../services/data.service';
import { Router } from '@angular/router';
import { IMovie } from '../../interface/movieList';
@Component({
selector: 'app-movie-genre-row',
templateUrl: './movie-genre-row.component.html',
styleUrls: ['./movie-genre-row.component.scss']
})
export class MovieGenreRowComponent implements OnInit {
@Input() message: string;
movieList = [];
constructor(
private movieListService: MovieListService,
private route: Router,
) {}
ngOnInit() {
this.movieListService.getData()
.subscribe((data) => {
this.movieList = data;
});
}
onSelect(movie) {
this.route.navigate(['/watch', movie.id]);
}
}
<file_sep>COSNFLIX
docker-compose up --build
CREATE AND UPDATE CATALOG USE:
mngCatalog.sh -h
<file_sep>from typing import List, Dict
from flask import Flask, jsonify, request
from flask_cors import CORS, cross_origin
import mysql.connector
import collections
app = Flask(__name__)
CORS(app, support_credentials=True)
def list_movies() -> List[Dict]:
config = {
'user': 'admin',
'password': '<PASSWORD>',
'host': 'db_movies',
'port': '3306',
'database': 'MOVIES_DB'
}
connection = mysql.connector.connect(**config)
cursor = connection.cursor()
cursor.execute('SELECT * FROM movies')
rows = cursor.fetchall()
objects_list = []
for row in rows:
d = collections.OrderedDict()
d['id'] = row[0]
d['name'] = row[1]
d['image'] = row[2]
d['link'] = row[3]
objects_list.append(d)
cursor.close()
connection.close()
return objects_list
def selectID(id) -> List[Dict]:
config = {
'user': 'admin',
'password': '<PASSWORD>',
'host': 'db_movies',
'port': '3306',
'database': 'MOVIES_DB'
}
connection = mysql.connector.connect(**config)
cursor = connection.cursor()
cursor.execute('SELECT * FROM movies WHERE id=' + id)
rows = cursor.fetchall()
objects_list = []
for row in rows:
d = collections.OrderedDict()
d['id'] = row[0]
d['name'] = row[1]
d['image'] = row[2]
d['link'] = row[3]
objects_list.append(d)
cursor.close()
connection.close()
return objects_list
@app.route('/movie')
def index() -> str:
return jsonify(list_movies())
@app.route('/', methods=['POST'])
def create_task():
if not request.json:
return jsonify({'error': "Content-type error"})
movie = request.json['movie']
return jsonify(selectID(movie))
if __name__ == '__main__':
app.run(host='0.0.0.0')
<file_sep>import { Component, OnInit, Input, ViewChild, ElementRef } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
import { MovieListService } from '../../services/movie-list.service';
@Component({
selector: 'app-video-player',
templateUrl: './video-player.component.html',
styleUrls: ['./video-player.component.scss']
})
export class VideoPlayerComponent implements OnInit {
@Input() videoDetail: any;
@ViewChild('myVideo') myVideo: ElementRef;
videoSrc = 'http://distribution.bbb3d.renderfarming.net/video/mp4/bbb_sunflower_1080p_30fps_normal.mp4';
constructor(
private sanitizier: DomSanitizer,
private movieListService: MovieListService,
) {
}
ngOnInit() {
setTimeout(
() => {
this.playVideo();
}, 3000);
}
playVideo() {
console.log(this.videoSrc);
console.log(this.videoDetail);
this.myVideo.nativeElement.src = this.videoDetail;
this.myVideo.nativeElement.load();
this.myVideo.nativeElement.play();
}
}
<file_sep>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { DataService } from '../../services/data.service';
import { UserService } from '../../services/user.service';
import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
loginAlert = '';
alertState = false;
private apiUrl = 'http://localhost:5001/login';
// This link get the information of the python service
// however it is not working yet with our read yet
constructor(
private router: Router,
private dataService: DataService,
private userService: UserService,
private http: HttpClient
) { }
ngOnInit() {
}
onClickSubmit(data) {
// data = JSON.stringify({"email": "<EMAIL>", "password": "<PASSWORD>"});
const body = JSON.stringify({'email': '' + data.email, 'password': '' + data.password});
// const body = JSON.stringify(data);
this.confirmUrser(body).subscribe(
(d: any) => {
if (d['success'] === 'ok') {
this.userService.setUserLoggedIn();
this.router.navigate(['/index']);
}
},
(err) => {
this.alertState = true;
this.loginAlert = 'Sorry, we can\'t find an account with this information!';
}
);
}
confirmUrser (data) {
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
return this.http.post(this.apiUrl, data, httpOptions);
}
}
<file_sep>Then, spin up the container once the build is done:
`$ docker run -it \
-v ${PWD}:/usr/src/app \
-v /usr/src/app/node_modules \
-p 4200:4200 \
--rm \
feupflix`
Open your browser to http://localhost:4200 and you should see the app. Try making a change to the AppComponent’s template (src/app/app.component.html) within your code editor. You should see the app hot-reload. Kill the server once done.<file_sep>import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class UtilityService {
public _router: Router;
public apiContainer = {
'movieList': {
url: 'movielist'
}
};
constructor(router: Router) {
this._router = router;
}
public navigate(path: string) {
this._router.navigate([path]);
}
public navigateToSignIn() {
window.location.href = 'Account/Logout';
}
public getItemsByStatus(data: any[], status: string): any {
return data ? data.filter(item => item['status'] === status) : [];
}
public handleResponse(data: any[], insert?: any[], insertMapper?: any[]) {
if (insert && insertMapper) {
insert.forEach(element => {
const position = this.getPosition(insertMapper, element);
data[position]['id'] = element['insert']['id'];
});
}
data.forEach(element => {
element['dirty'] = false;
if (element['status'] !== 'DELETE') {
element['status'] = undefined;
element['isDel'] = undefined;
}
});
}
public getPosition(array: any[], element: any) {
for (const item of array) {
if (item.token === element.token) {
return item.idx;
}
}
return -1;
}
}
<file_sep>FROM node:9.6.1-slim
WORKDIR /catalog
RUN npm install http-server -g
CMD http-server -p 6001
EXPOSE 6001
| 52cea26086086aaded01d3b33f50b39afc1bb4cc | [
"SQL",
"YAML",
"Markdown",
"Python",
"Text",
"TypeScript",
"Dockerfile",
"Shell"
] | 19 | TypeScript | macedojleo/COSNFLIX | af89f2a28efc260606f2dead8f1642b7d8640322 | 722c2e5e7ba210fc7be7eed60e01cef83aa93f16 |
refs/heads/master | <file_sep>import java.io.*;
public class Rotator {
public static void scheduler(String[] teams, FileWriter fw) throws IOException {
int numOfTeams = teams.length;
String[] evenTeams;
int k = 0;
if (numOfTeams % 2 == 0) {
evenTeams = new String[numOfTeams-1];
for(k = 0; k < numOfTeams-1; k++)
evenTeams[k] = teams[k+1];
} else {
evenTeams = new String[numOfTeams];
for(k = 0;k < numOfTeams-1; k++)
evenTeams[k] = teams[k+1];
evenTeams[numOfTeams-1] = "Bye";
}
int teamsSize = evenTeams.length; //it is even number
int total = ((teamsSize+1) - 1); // rounds needed to complete tournament
int halfSize = (teamsSize+1)/ 2;
int count = 0;
for (int week = total-1; week >= 0; week--) {
System.out.println("week " + (++count));
fw.write("\r\nweek " + (count) +"\r\n");
int teamIdx = week % teamsSize;
if(!evenTeams[teamIdx].equals("Bye")) {
System.out.println(teams[0] + " vs. "+ evenTeams[teamIdx] );
fw.write(teams[0] + " vs. "+ evenTeams[teamIdx] +"\r\n");
}
for (int i = 1; i < halfSize; i++) {
int firstTeam = (week + i) % teamsSize;
int secondTeam = (week + teamsSize - i) % teamsSize;
if ( !evenTeams[firstTeam].equals("Bye") && !evenTeams[secondTeam].equals("Bye")) {
System.out.println(evenTeams[firstTeam] + " vs. "+ evenTeams[secondTeam]);
fw.write(evenTeams[firstTeam] + " vs. "+ evenTeams[secondTeam] +"\r\n");
}
}
System.out.println();
}
}
}
<file_sep>
import java.io.*;
import java.util.Scanner;
public class Main {
public static String[] getTeams() throws FileNotFoundException {
File f = new File("input.txt");
Scanner sc1 = new Scanner(f);
int size = 0;
while (sc1.hasNextLine()){
sc1.nextLine();
++size;
}
String[] teams = new String[size];
Scanner sc2= new Scanner(f);
for (int i=0;i<size;++i) {
teams[i] = sc2.nextLine();
}
sc1.close();
sc2.close();
return teams;
}
public static void main(String[] args) throws IOException {
String[] teams= getTeams();
FileWriter fw = new FileWriter("output.txt");
Rotator.scheduler(teams, fw);
fw.close();
}
}
<file_sep># Round Robin Tournament
## Description
There are 10 soccer teams that will play in the league this year are stored in a file called “input.txt”. Read the names of these teams from the file and develop a round-robin schedule so that every team plays every other team over the next 9 weeks. You must put the results of your program (the schedule) into a file called “output.txt”.
## Output
Here is a sample solution:
Soccer Schedule: Number of teams is: 10
```
Week 1
Cosmos plays Attackers
Red Bull plays iPhoners
Manchester United plays Foo Fighters
Liverpool plays Giants
Staples plays Westhill
Week 2
Cosmos plays iPhoners
Attackers plays Foo Fighters
Red Bull plays Giants
Manchester United plays Westhill
Liverpool plays Staples
Week 3
Cosmos plays Foo Fighters
iPhoners plays Giants
Attackers plays Westhill
Red Bull plays Staples
Manchester United plays Liverpool
Week 4
Cosmos plays Giants
Foo Fighters plays Westhill
iPhoners plays Staples
Attackers plays Liverpool
Red Bull plays Manchester United
Week 5
Cosmos plays Westhill
Giants plays Staples
Foo Fighters plays Liverpool
iPhoners plays Manchester United
Attackers plays Red Bull
Week 6
Cosmos plays Staples
Westhill plays Liverpool
Giants plays Manchester United
Foo Fighters plays Red Bull
iPhoners plays Attackers
Week 7
Cosmos plays Liverpool
Staples plays Manchester United
Westhill plays Red Bull
Giants plays Attackers
Foo Fighters plays iPhoners
Week 8
Cosmos plays Manchester United
Liverpool plays Red Bull
Staples plays Attackers
Westhill plays iPhoners
Giants plays Foo Fighters
Week 9
Cosmos plays Red Bull
Manchester United plays Attackers
Liverpool plays iPhoners
Staples plays Foo Fighters
Westhill plays Giants
```
## Algorithm
Scheduling algorithm taken from [Wikipedia](https://en.wikipedia.org/wiki/Round-robin_tournament)
If is the number of competitors, a pure round robin tournament requires games. If is even, then in each of rounds, games can be run in parallel, provided there exist sufficient resources (e.g. courts for a tennis tournament). If is odd, there will be rounds, each with games, and one competitor having no game in that round.
The standard algorithm for round-robins is to assign each competitor a number, and pair them off in the first round …
```
Round 1. (1 plays 14, 2 plays 13, ... )
1 2 3 4 5 6 7
14 13 12 11 10 9 8
```
then fix one competitor (number one in this example) and rotate the others clockwise one position
```
Round 2. (1 plays 13, 14 plays 12, ... )
1 14 2 3 4 5 6
13 12 11 10 9 8 7
```
```
Round 3. (1 plays 12, 13 plays 11, ... )
1 13 14 2 3 4 5
12 11 10 9 8 7 6
```
until you end up almost back at the initial position
```
Round 13. (1 plays 2, 3 plays 14, ... )
1 3 4 5 6 7 8
2 14 13 12 11 10 9
```
If there are an odd number of competitors, a dummy competitor can be added, whose scheduled opponent in a given round does not play and has a bye. The schedule can therefore be computed as though the dummy were an ordinary player, either fixed or rotating. Instead of rotating one position, any number relatively prime to will generate a complete schedule. The upper and lower rows can indicate home/away in sports, white/black in chess, etc.
To ensure fairness, this must alternate between rounds since competitor 1 is always on the first row. If, say, competitors 3 and 8 were unable to fulfil their fixture in the third round, it would need to be rescheduled outside the other rounds, since both competitors would already be facing other opponents in those rounds. More complex scheduling constraints may require more complex algorithms. This schedule is applied in chess and draughts tournaments of rapid games, where players physically move round a table.
| f1cb248a0a64a5b91a482d36e4925d8d383ab219 | [
"Markdown",
"Java"
] | 3 | Java | lavivien-cs-projects/RoundRobinTournament | 9be59104efc9bd9a12694f0546922a088deeb091 | eff5b750022581e27b7a18898c221c3fc3de82e7 |
refs/heads/master | <file_sep>(function() {
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
//// ______ _ _ ////
//// | ___| | | (_) ////
//// | |_ _ _ _ __ ___| |_ _ ___ _ __ ////
//// | _| | | | '_ \ / __| __| |/ _ \| '_ \ ////
//// | | | |_| | | | | (__| |_| | (_) | | | | ////
//// \_| \__,_|_| |_|\___|\__|_|\___/|_| |_| ////
//// ////
//// ////
//// ______ _ _ ////
//// | ___ \ | | (_) ////
//// | |_/ / __ __ _ ___| |_ _ ___ ___ ////
//// | __/ '__/ _` |/ __| __| |/ __/ _ \ ////
//// | | | | | (_| | (__| |_| | (_| __/ ////
//// \_| |_| \__,_|\___|\__|_|\___\___| ////
//// ////
//// ////
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
// Q1
// Write a function called `sum` that takes two
// parameters and returns the sum of those 2 numbers.
var sum = function (a, b) {
return a + b;
};
// Q2
// Write a function named `avg` that takes 3 parameters
// and returns the average of those 3 numbers.
var avg = function (a, b, c) {
return (a + b + c)/ 3;
};
// Q3
// Write a function called `getLength` that takes one
// parameter (a string) and returns the length
var getLength = function (a) {
return a.length;
};
// Q4
// Write a function called `greaterThan` that takes
// two parameters and returns `true` if the second
// parameter is greater than the first. Otherwise
// the function should return `false`.
var greaterThan = function (a, b) {
if (a < b) {
return true;
} else {
return false; }
};
// Q5
// Write a function called `greet` that takes a
// single parameter and returns a string that
// is formated like "Hello, Name!" where *Name*
// is the parameter that was passed in.
var greet = function (name) {
return "Hello, " + name + "!";
};
// Q6
// Write a function called `madlib` that takes
// 4 or more parameters (words). The function
// should insert the words into a pre-defined
// sentence. Finally the function should return
// that sentence.
// Note: When I say words and sentence I mean
// strings. For example:
// words: "quick", "fox", "fence"
// sentence: "quick brown fox jumps over the fence"
var madLib = function (num1, place, num2, erAdj, occupation) {
return "Pro-Tip: every " + num1 + " hour(s), while drinking craft beer from " + place + ", spend " + num2 + " hour(s) playing ping-pong with JD. It will make you a way " + erAdj + " super-ninja-" + occupation + "/developer than 3WSchools ever could!";
};
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
// ---------------------
// Define a function max() that takes two numbers as arguments and returns the largest of them. Use the if-then-else construct available in JavaScript.
// ---------------------
function max(a, b){
if (a > b) {
return a;
} if (a < b) {
return b; }
};
// ---------------------
// Define a function maxOfThree() that takes three numbers as arguments and returns the largest of them.
// ---------------------
function maxOfThree(a, b, c){
var numbers = [a,b,c]
numbers.reduce(function(largest, current) {
if (current > largest) {
largest = current;
}
return largest;
}, Number.MIN_VALUE);
};
console.log(maxOfThree(2,6,4));
// ---------------------
// Write a function that takes a character (i.e. a string of length 1) and returns true if it is a vowel, false otherwise.
// ---------------------
function isVowel(char){
var vowels = 'aeiou';
if (vowels.indexOf(char) !== -1) {
return true;
} else {
return false;
}
}
// ---------------------
// Write a function translate() that will translate a text into "rövarspråket". That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".
// ---------------------
function rovarspraket(phrase){
var chars = phrase.split('');
var finalPhrase = [];
chars.forEach( function(char) {
if (!isVowel(char)) {
finalPhrase.push(char + 'o' + char);
} else {
finalPhrase.push(char);
}
});
return finalPhrase.join('');
}
// ---------------------
// Define a function reverse() that computes the reversal of a string. For example, reverse("jag testar") should return the string "ratset gaj".
// ---------------------
function reverse(string){
return string.split('').reverse().join('');
}
// ---------------------
// Write a function findLongestWord() that takes an array of words and returns the length of the longest one.
// ---------------------
function findLongestWord(words){
var longest = '';
words.forEach(function(word){
if (word.length > longest.length)
longest = word;
});
return winner.length;
}
// ---------------------
// Write a function filterLongWords() that takes an array of words and an integer i and returns the array of words that are longer than i.
// ---------------------
function filterLongWords(words, i){
var x = words.filter( function (word) {
return word.length > i;
});
return x;
}
filterLongWords(['pear', 'banana', 'orange'], 4);
// ---------------------
// Write a function charFreq() that takes a string and builds a frequency listing of the characters contained in it. Represent the frequency listing as a Javascript object. Try it with something like charFreq("abbabcbdbabdbdbabababcbcbab").
// ---------------------
// create blank object
var obj = {};
function charFreq(string){
// declare a variable that splits string into seperate letters and sort them in alphabetical order
var eachLetter = string.split('').sort('');
// map each letter and look for every instance of each letter until there's none left
eachLetter.map(function(letter) {
// looks for letter in object
if (letter in obj) {
// ++ adds an interval for every instance of a letter in the object
obj[letter] ++;
// if no interval, letter count is 1
} else {
obj[letter] = 1;
};
});
return obj;
}
}()); | 24bdb30429da5c5946cbb61108196cfc14b09700 | [
"JavaScript"
] | 1 | JavaScript | hopecrichlow/Function-Practice | aa705fe16dd47da4570df9b6e7b882e9f675c479 | d2402898ba46a04f5d3f294abb5b24000a103eb3 |
refs/heads/master | <repo_name>Klayre/mechantania<file_sep>/mechantania/batch_code/world_builder/build_areas.py
#HEADER
import evennia
import evennia.utils.search
import utils.import_trizbort_map as MapImporter
from utils.builder_utils import remove_all_rooms
# A list of area files you should use when constructing. These will
# be accumulated into the callers "ndb.build_area_list" dictionary.
# The dictionary will contain key="area name",value="start room #dbref"
# There will be a failure if either the area name or start room #dbref
# can't be found.
AREA_FILES = ["world/content/maps/areas/tutorial/tutorial.trizbort",
"world/content/maps/areas/tutorial/tutorial2.trizbort"]
#CODE
# Delete the caller.ndb.builder_area_list
caller.ndb.builder_area_list = {}
# Construct each area in the game.
cntr = 0
for mapFile in AREA_FILES:
caller.msg("Building area %d / %d : '%s'" %(cntr, len(AREA_FILES), mapFile))
# Delete any areas with same name.
xml_tree = MapImporter.parse_file(mapFile)
if (not xml_tree):
caller.msg("ERROR: Can not load map %s." % mapFile)
area_name = MapImporter.get_map_name(xml_tree)
if (not area_name):
caller.msg("ERROR: Can not get map name from %s." % mapFile)
# Remove all rooms
objects_with_zone = evennia.utils.search.search_object_by_tag(area_name,
category="zone")
if len(objects_with_zone) != 0:
caller.msg(" Warning: Zone with name %s already exists. All rooms in this"
"zone will be deleted." % area_name)
remove_all_rooms(tag=area_name, category="zone")
roomRoot = MapImporter.construct_world(xml_tree)
caller.msg("constructed area %s" % area_name)
caller.msg("Starting room: %s |y#%d|n" %(roomRoot.key, roomRoot.id))
caller.ndb.builder_area_list[area_name] = roomRoot.id
cntr += 1
<file_sep>/mechantania/typeclasses/characters.py
"""
Characters
Characters are (by default) Objects setup to be puppeted by Accounts.
They are what you "see" in game. The Character class in this module
is setup to be the "default" character type created by the default
creation commands.
"""
from evennia import DefaultCharacter
from utils.map import Mapper
from evennia import utils
import re
from evennia.utils import lazy_property
from world.handlers.traits import TraitHandler
from world.handlers.equip import EquipHandler
import typeclasses.rooms
# Base statistics that every character gets.
BASE_STATS = {
'hp' : { 'name':'HP', 'type':'gauge', 'base':100, 'max':'base'},
'exp' : { 'name':'EXP', 'type':'gauge', 'base':0, 'max':'100' },
'level' : { 'name':'Level', 'type':'static', 'base':1 }
}
CHARACTER_SLOTS = {
"wield1" : None,
"wield2" : None,
"armor1" : None,
"armor2" : None
}
CHARACTER_LIMBS = (
("right wield", ("wield1",)),
("left wield", ("wield2",)),
("body", ("body",)),
("legs", ("legs",)),
)
class Character(DefaultCharacter):
"""
The Character defaults to reimplementing some of base Object's hook methods with the
following functionality:
at_basetype_setup - always assigns the DefaultCmdSet to this object type
(important!)sets locks so character cannot be picked up
and its commands only be called by itself, not anyone else.
(to change things, use at_object_creation() instead).
at_after_move(source_location) - Launches the "look" command after every move.
at_post_unpuppet(account) - when Account disconnects from the Character, we
store the current location in the pre_logout_location Attribute and
move it to a None-location so the "unpuppeted" character
object does not need to stay on grid. Echoes "Account has disconnected"
to the room.
at_pre_puppet - Just before Account re-connects, retrieves the character's
pre_logout_location Attribute and move it back on the grid.
at_post_puppet - Echoes "AccountName has entered the game" to the room.
"""
def at_object_creation(self):
"This is called when object is first created, only."
# Set up the stats
if (self.stats_base):
# this will clear out all the stats! Is there a better way to do this?
self.stats_base.clear()
for key, kwargs in BASE_STATS.iteritems():
self.stats_base.add(key, **kwargs)
# TODO: Move this to a separate data file.
self.db.map_symbol = u'\u263b'.encode('utf-8')
# For EquipmentHandler to work.
self.db.slots = dict(CHARACTER_SLOTS)
self.db.limbs = tuple(CHARACTER_LIMBS)
return super(Character, self).at_object_creation()
def at_before_move(self, dest):
"""
Preferm pre-move steps.
* Checks the room doesn't have any objects with mIsBlocking property.
If it does, then it will return False so that account can not move
there, unless they are an importal.
"""
isBlocked = False
# Search all objects in room
allObjects = (con for con in dest.contents)
roomBlockingObjects = dest.get_blocking_objects()
# Filter out just things that actually block character
actualBlockingObjects = []
for con in roomBlockingObjects:
if (hasattr(con.db, 'mIsBlocking') and con.db.mIsBlocking):
isImmortal = False
if self.locks.check_lockstring(self, "dummy:perm(Immortals)"):
isImmortal = True
if (not isImmortal):
# Only block non-immortals
actualBlockingObjects.append(con)
self.msg("A %s blocks your path." % con.name)
else:
self.msg("|yWARNING:|n You would have been blocked by a %s, but you are an "
"IMMORTAL!" % con.name)
if (len(actualBlockingObjects) != 0):
return False
# Otherwise just do normal movement.
return super(Character, self).at_before_move(dest)
# Overload "search" to also allow the syntax <exit>.<object>
def search(self, searchdata,
global_search=False,
use_nicks=True, # should this default to off?
typeclass=None,
location=None,
attribute_name=None,
quiet=False,
exact=False,
candidates=None,
nofound_string=None,
multimatch_string=None,
use_dbref=True):
# Check if we have an exit pre-pended to the start of the command
p = re.compile("(.+)\.(.+)")
searchmatch = p.search(searchdata)
if searchmatch:
# We do have an exit pre-pended, let's extract it and then search
# that location for the object we want.
# We do this by
# 1) stripping off the prepended location + "." from the object
# 2) using the prepended location to search the "exits", and if
# found, set the target of the search command there
searchLocationString = None
searchTarg = None
searchLocationString = searchmatch.group(1)
searchTarg = searchmatch.group(2)
for ex in self.location.exits:
if (ex.key == searchLocationString) or (searchLocationString in ex.aliases.all()):
location = ex.destination
searchdata = searchTarg
break
return super(Character, self).search(searchdata, global_search,
use_nicks, typeclass,
location,
attribute_name,
quiet,
exact,
candidates,
nofound_string,
multimatch_string,
use_dbref)
def at_look(self, target):
desc = super(Character, self).at_look(target)
self.msg(type(target))
if (utils.inherits_from(target, typeclasses.rooms.Room)):
# Print out the map
mapper = Mapper()
mapper.generate_map(target)
desc = desc + "\n" + str(mapper)
return desc
# Pretty-print the equipment on this character.
# TODO: Maybe move somewhere else
def pp_equipment(self, looker):
return self.equip.pretty_print(looker)
@lazy_property
def stats_base(self):
return TraitHandler(self, db_attribute='stats_base')
@lazy_property
def equip(self):
"""Handler for equipped items"""
return EquipHandler(self)
class Npc(Character):
def at_char_entered(self, character):
"""
A simple is_agressive check
Can be expanded later
"""
if self.db.is_aggressive:
self.execute_cmd("say Graaah, die %s" % character)
else:
self.execute_cmd("say Greetings, %s" % character)
# TODO: Move to utils
# pretty-print the stats of the character.
<file_sep>/mechantania/batch_code/world_builder/build_world.py
# Builds the entire world.
#TODO If you ever have _connector_ nodes to connect from one map file to
# another, then use this file - after importing ev erything, go through all
# the world and connect the connector nodes.
#HEADER
from typeclasses.rooms import Room
#CODE
caller.msg("Building the world...Please wait...")
# Build test world
#INSERT batch_code.world_builder.build_areas
caller.msg("Areas built, gluing them together...Please wait...")
# Glue the world together
#INSERT batch_code.world_builder.connect_areas
caller.msg("World building DONE.")
<file_sep>/mechantania/commands/items/poison_commands.py
from evennia import Command
from evennia import CmdSet
class CmdDrink(Command):
key = "drink poison"
aliases = ["drink"]
locks = "cmd:all()"
def func(self):
# Pass the caller to the PoisonScript object
self.obj.do_drink(self.caller)
class DefaultCmdSet(CmdSet):
key = "PoisonCmdSet"
def at_cmdset_creation(self):
"Init the cmd set"
self.add(CmdDrink)
<file_sep>/mechantania/typeclasses/mobjects/environment/tree.py
from evennia import CmdSet
from evennia import DefaultObject
"""
A tree object. A tree in a room will block the player from entering the room.
A player can chop the tree down and the tree will drop logs of wood (random)
Create this tree with:
@create/drop mobjects.environment.tree.Tree
"""
class DefaultCmdSet(CmdSet):
key = "Tree"
def at_cmdset_creation(self):
# No commands
pass
# TODO: Objects will have a host of flags on them. BLOCKING is one of them.
# This class should be refactoring with the BLOCKING flag and inherrited from
# an mobject later.
from evennia import DefaultObject
class Tree(DefaultObject):
def at_object_creation(self):
desc = "A large tree."
self.db.desc = desc
# UTF character found on
# http://graphemica.com/characters/tags/trees
# There are actually multiple trees on there!
# The below is just the default.
self.db.map_symbol = u'\U0001F333'.encode('utf-8')
# self.db.map_symbol = unichr(9786).encode('utf-8')
# no commands at this time
#self.cmdset.add_default(treeCmdSet, permanent = True)
#
# Member variables
#
# Whether this tree blocks the room for entry
self.db.mIsBlocking = True
<file_sep>/mechantania/utils/import_trizbort_map.py
# Import a trizbort (http://www.trizbort.com/) map file to create
# a map area. The map is represented by a single room, which is
# represented by the "isStartRoom" element tag (only one room should
# have this set. This room is returned.
# TODO - Make this return a batch script which can be executed in-game.
# TODO: Error check to make sure all roomsnext to each other have a link
import evennia
from typeclasses.rooms import Room
from typeclasses.exits import Exit
import re
import ast
import xml.etree.ElementTree as ET
import evennia.utils.spawner
def parse_file(filename):
return ET.parse(filename)
def get_map_name(xml_tree):
root = xml_tree.getroot()
mapTitle = None
for child in root:
if (child.tag == "info"):
infoRoot = child
for infoChild in infoRoot:
if infoChild.tag == "title":
mapTitle = infoChild.text
return mapTitle
# Main function
def construct_world(xml_tree):
root = xml_tree.getroot()
print(root)
print(root.attrib)
infoRoot = None
mapRoot = None
for child in root:
if (child.tag == "info"):
infoRoot = child
if (child.tag == "map"):
mapRoot = child
# Iterate over all the children in mapRoot.
# Children tags:
# "room" - A roomt
# "line" - A connect between rooms
# Dict of rooms by their unique ID (note ID is
# global amongst everything.
xmlRooms = {}
# Starting room ID
startRoomId = None
# Dict of exits by their unique ID
xmlExits = {}
# Gets the map "title" (will be name of the zone)
mapTitle = None
mapAuthor = None
mapDescription = None
for child in infoRoot:
if child.tag == "title":
mapTitle = child.text
if child.tag == "author":
mapAuthor = child.text
if child.tag == "description":
mapDescription = child.text
if not mapTitle or not mapAuthor or not mapDescription:
raise Exception("Map needs to have title, author , and description.")
for child in mapRoot:
childId = child.attrib["id"]
if (child.tag == "room"):
xmlRooms[childId] = child
if (child.attrib.get("isStartRoom")):
if (child.attrib.get("isStartRoom") == "yes"):
startRoomId = childId
elif (child.tag == "line"):
xmlExits[childId] = child
print (xmlRooms)
print (xmlExits)
print ("Start room: " + startRoomId)
# Now we have all our rooms and exits. Let's start creating.
# Start by creating all the rooms. Keep them in dict by their original
# ID for easy reference.
mechRooms = {}
for roomId, roomNode in xmlRooms.iteritems():
specialAttrib = check_for_special_room(roomNode)
mechRooms[roomId] = create_mech_room_from_xml(roomNode,
zoneName = mapTitle,
zoneAuthor = mapAuthor,
zoneDescription = mapDescription,
specialAttrib=specialAttrib)
print(mechRooms[roomId])
print(mechRooms[roomId].id)
for exitId, exitNode in xmlExits.iteritems():
create_room_exits_from_xml(exitNode, xmlRooms, mechRooms)
# Return the starting room.
return mechRooms[startRoomId]
# Checks for special room, and if so, returns special attribute.
def check_for_special_room(roomNode):
roomName = roomNode.attrib.get("name")
if not roomName:
raise Exception("Invalid room name on special")
return None
m = re.search("special:(.+?)", roomName)
if m:
return m.group(1)
return None
# Returns a dictionary of {zoneDestination="zone destination", connectorID="connectorID"}
def get_special_room_attrib(roomNode):
roomSubtitle = roomNode.attrib.get("subtitle")
if not roomSubtitle:
raise Exception("Invalid room name on subtitle")
return None
searchString = "(.+) *: *(.+)"
m = re.search(searchString, roomSubtitle)
if m:
zoneDestination = m.group(1)
connectorName = m.group(2)
if (zoneDestination and connectorName):
retDict = {"zoneDestination":zoneDestination,
"connectorName":connectorName}
else:
id = int(roomNode.attrib["id"])
raise Exception("special connector room id %d doesn't have proper "
"subtitle." % (id))
retDict = None
return retDict
def get_object_prototype_list(xml_room_node):
retList = []
for ch in xml_room_node:
if ch.tag == "objects":
objects = ch.text
print("objects : " + objects)
if (objects) :
# Strip off whitespace
objects.replace(" ", "")
# Split by "|"
objSubList = objects.split('|')
for o in objSubList:
if (o != ""):
retList.append(o)
print ("retlist:")
print (retList)
# Go through the objects and look for prototypes
return retList
# Spawn all objects in room, except for "special" objects.
# Returns a list of dicts for all objects spawned.
def handle_objects_in_room(object_list, mech_room):
ret_obj_list = []
# Iterate over the object strings
for obj in object_list:
if (len(obj.split(":")) == 1):
# This is just a normal prototype name with no ":"
objDictStr = "{\"prototype\":\"" + obj + "\"}"
else:
objDictStr = obj
print("objDictStr: " + objDictStr)
object_dict = ast.literal_eval(objDictStr)
if not object_dict.get("connectorName"):
# Append all the data that was generated dynamically
# outside of the prototype
object_dict["location"] = mech_room.dbref
mech_object = evennia.utils.spawner.spawn(object_dict)
else:
# These aren't really objects, but a connector
# Handle this as a special room. We tag it with a special
# connector tag/id
mech_room.tags.add("connector_to", category="map_builder")
mech_room.ndb.connector_name = object_dict.get("connectorName")
ret_obj_list.append(object_dict)
return ret_obj_list
def create_mech_room_from_xml(xml_room_node,
zoneName,
zoneAuthor,
zoneDescription,
specialAttrib=None):
# Create our room.
# TODO: Use region for zone
# TODO: TAG AS SPECIAL ROOM
subtitle = xml_room_node.attrib.get("subtitle").encode('utf-8')
name = xml_room_node.attrib.get("name")
desc = xml_room_node.attrib.get("description")
if (subtitle and subtitle != "" and not specialAttrib):
# a prototype was given, spawn from the prototype instead
roomProtoDict = {"prototype":subtitle, "key":name, "desc":desc}
roomObject = evennia.utils.spawner.spawn(roomProtoDict)[0]
else:
# TODO Allow for locks/permissions to be specified
# TODO Allow for aliases to be specified
# TODO Allow for mapsymbol to be specified
roomObject = evennia.create_object(typeclass = "rooms.Room", key=name)
roomObject.db.desc = desc
# Zones
print("zone: %s", zoneName)
roomObject.tags.add(zoneName, category="zone", data=zoneDescription)
# Adds the author tag, but then sets data to the zone name
roomObject.tags.add(zoneAuthor, category="zone_author", data=zoneName)
if specialAttrib:
connectorDict = get_special_room_attrib(xml_room_node)
print("special room found connecting to zone %s , connector name %s" %
(connectorDict["zoneDestination"], connectorDict["connectorName"]))
roomObject.tags.add("connector_from", category="map_builder")
roomObject.db.map_builder_connector_dict = connectorDict
# Spawn object
object_list = get_object_prototype_list(xml_room_node)
handle_objects_in_room(object_list, roomObject)
# Spawn the objects
return roomObject
# Returns a list of primary name as first element, and aliases
# as other elements
def get_cardinal_name_and_aliases_from_dock_node(dock):
portDir = dock.attrib.get("port")
retList = []
if portDir == "s":
retList.append("south")
retList.append("s")
elif portDir == "w":
retList.append("west")
retList.append("w")
elif portDir == "n":
retList.append("north")
retList.append("n")
elif portDir == "e":
retList.append("east")
retList.append("e")
elif portDir == "ne":
retList.append("northeast")
retList.append("ne")
elif portDir == "se":
retList.append("southeast")
retList.append("se")
elif portDir == "sw":
retList.append("southwest")
retList.append("sw")
elif portDir == "nw":
retList.append("northwest")
retList.append("nw")
# Otherwise just return whatever was stored.
# TODO: Add aliases?
retList.append(portDir)
return retList
# Returns a list where first entry is the primary name, other entries are
# aliases (i.e. portal_to_testarea;portal;port creates primary name
# portal_to_testarea as entry 0, and portal as entry 1, and port as
# entry 2
def get_named_exit_aliases_from_line(xml_line_node):
lineName = xml_line_node.attrib.get("name")
#TODO: Aliases.
#TODO: Exit description
print ("name alias %s" % lineName)
name_alias_list = lineName.split(';')
print(name_alias_list)
# strip whitespace, and empty strings
retList = [word.strip() for word in name_alias_list if word.strip()]
return retList
def create_room_exits_from_xml(xml_exit_node, xml_rooms_dict, mechRoomsDict):
# Create the exits
#TODO: ONE-WAY EXITS! This is useful for non-cardinal direction exits which
# might have different discriptions on either side of the exit...
# A list - First 2 entries are source and destination.
roomsSrcDest = []
# Get the ids. Each "dock" has ids in continous order for a single exit,
# so store in a list.
dockNodes = {}
isOneWay = False
if xml_exit_node.attrib.get("flow") == "oneWay":
isOneWay = True
for child in xml_exit_node:
if (child.tag == "dock"):
dockIndex = child.attrib.get("index")
dockNodes[dockIndex] = child
roomId = child.attrib.get("id")
roomsSrcDest.append(mechRoomsDict[roomId])
# Create exits on both rooms.
for dockKey, dock in dockNodes.iteritems():
print dock
dockIndex = int(dock.attrib.get("index"))
if isOneWay:
print "Is one way? " + str(isOneWay)
if dockIndex != 0:
continue
# Check if this is one way, and we are going the correct way.
exitNameList = []
if xml_exit_node.attrib.get("name"):
if (xml_exit_node.attrib.get("name") != ""):
# Names on exits override
exitNameList = get_named_exit_aliases_from_line(xml_exit_node)
print(exitNameList)
if (len(exitNameList) == 0):
exitNameList = get_cardinal_name_and_aliases_from_dock_node(dock)
# TODO Tags?
srcRoom = roomsSrcDest[dockIndex]
dstRoom = roomsSrcDest[(dockIndex + 1) % 2]
for exit in srcRoom.exits:
if exit.name == exitNameList[0]:
msg = "Trying to create an exit {0}:#{1} on room" \
"{2}:#{3} that already has that exit " \
"created!".format(exit.name, exit.id, \
srcRoom.name, srcRoom.id)
print(msg)
raise Exception(msg)
evennia.create_object(typeclass = "exits.Exit",
key=exitNameList[0],
location=srcRoom,
aliases=exitNameList[1:],
destination=dstRoom)
<file_sep>/mechantania/commands/items/equip.py
from evennia import default_cmds
import world.rules.rules as rules
class CmdInventory(default_cmds.MuxCommand):
locks = "cmd:all()"
key = "inventory"
aliases = ["inv"]
def func (self):
caller = self.caller
class CmdWear(default_cmds.MuxCommand):
""" Wear an object """
locks = "cmd:all()"
key = "wear"
aliases = ["equip"]
def func(self):
# Wears an item.
caller = self.caller
args = self.args.strip()
if args:
# Check if caller has this thing.
obj = caller.search(
args,
candidates=caller.contents,
nofound_string="%s not found in inventory!" % args,
multimatch_string="You are carrying more than one %s: " % args)
if not obj:
return
if not obj:
caller.msg("You do not have {}".format(str(obj)))
return
else:
for slot in obj.db.slots:
if slot not in caller.db.slots:
caller.msg("You can't find a suitable limb wear that.".format(slot))
return
if (not caller.equip.add(obj)) :
caller.msg("You can't equip that.")
return
if hasattr(obj, "at_equip"):
obj.at_equip(caller)
caller.msg("You equip the {}".format(str(obj)))
else:
# Display current equip
if hasattr(caller, "equip"):
output = caller.equip.pretty_print(caller)
if not output:
caller.msg("You have nothing equipped")
else:
caller.msg("|YYour equipment:|n\n{}".format(output))
totalStat = 0;
totalAttack = caller.equip.get_total_stat("attack")
effectiveAttack = rules.calc_effective_stat("attack", caller)
caller.msg("Total attack: {} (effective: {})".format(str(totalAttack), str(effectiveAttack)))
totalDefense = caller.equip.get_total_stat("defense")
effectiveDefense = rules.calc_effective_stat("defense", caller)
caller.msg("Total defense: {} (effective: {})".format(str(totalDefense), str(effectiveDefense)))
totalBulkiness = caller.equip.get_total_stat("bulkiness")
effectiveBulkiness = rules.calc_effective_stat("bulkiness", caller)
caller.msg("Total bulkiness: {} (effective: {})".format(str(totalBulkiness), str(effectiveBulkiness)))
totalSpeed = caller.equip.get_total_stat("speed")
effectiveSpeed = rules.calc_effective_stat("speed", caller)
caller.msg("Total speed: {} (effective: {})".format(str(totalSpeed), str(effectiveSpeed)))
else:
caller.msg("Can't display equipment.")
# # Get the currently equipped armor/weapons.
# if hasattr(caller.equip):
# data = []
# s_width = 0;
# for slot, obj in caller.equip:
# wearName = slot
#
# if not obj or not obj.access(caller, "view"):
# continue
#
# if (caller.equip.limbs):
# # For limbs, use the named limb instead.
# for l in caller.equip.limbs:
# if slot in l[1]: # Check if limb attached to slot
# wearName = l[0] # Set wearname to limb name.
#
# s_width = max(len(wearName), s_width)
#
# data.append(
# " |b{slot:>{swidth}.{swidth}}|n: {item:<20.20}".format(
# slot=wearName.capitalize(),
# swidth=s_width,
# item=obj.name,
# )
# )
#
# if len(data) <= 0:
# output = "You have nothing equipped."
# else:
# table = EvTable(header=False, border=None, table=[data])
# output = "|YYour equipment:|n\n{}".format(table)
#
# caller.msg(output)
# else:
# caller.msg("You have no wearable slots.")
<file_sep>/mechantania/utils/map.py
# Creates a map that can be printed.
from typeclasses.rooms import Room
from evennia.utils import evtable
# Map size in W/H
MAP_SIZE_W = 9
# Center of the map from character's POV
MAP_CENTER = (MAP_SIZE_W/2, MAP_SIZE_W/2)
# Default if no symbol can be obtained from room.
NO_ROOM_CHAR = '.'
class Mapper():
"""
A basic dynamic mapper class which will display the map with MAP_SIZE_W in
WxH
"""
def __init__(self):
"""
Initializes the map
"""
self.reset_map()
def reset_map(self):
"""
Clears the map and fills in with default NO_ROOM_CHAR
"""
self.map = [['.' for x in range(MAP_SIZE_W)] for y in \
range(MAP_SIZE_W)]
def print_map(self):
"""
Prints the map to text. Only used for debugging.
"""
print(self.map)
def has_room(self, local_coords):
"""
Checks if the room at local_coords (local) is already in the map
"""
return self.map[local_coords[0]][local_coords[1]] != NO_ROOM_CHAR
def is_valid_coords(self, coords):
if ((coords[0] < 0) or (coords[0] >= MAP_SIZE_W) or
(coords[1] < 0) or (coords[1] >= MAP_SIZE_W)):
return False
return True
def do_cell_recursive(self, room, prevRoom, local_coords, do_recurse=True):
# TODO: If db.map_symbol does not exist, this leads to strange things.
# I think there is a bug in how i'm checking below...
if room.attributes.has('map_symbol'):
if isinstance(room, Room):
self.map[local_coords[0]][local_coords[1]] = \
room.get_map_symbol()
# if (type(room.attributes.get('map_symbol') == str)):
# self.map[local_coords[0]][local_coords[1]] = room.attributes.get('map_symbol')
# else:
# ## Not needed since map is initialized to empty NO_ROOM_CHAR
if (do_recurse):
# Visit the map, use coords in reverse order
for ex in room.exits:
if (ex.key == "north" and ex.destination != prevRoom):
newCoords = (local_coords[0], local_coords[1]-1)
# Make sure have not already visited this room
# on another path...
if (self.is_valid_coords(newCoords) and not self.has_room(newCoords)):
self.do_cell_recursive(ex.destination, room, newCoords)
if (ex.key == "east" and ex.destination != prevRoom):
newCoords = (local_coords[0]+1, local_coords[1])
# Make sure have not already visited this room
# on another path...
if (self.is_valid_coords(newCoords) and not self.has_room(newCoords)):
self.do_cell_recursive(ex.destination, room, newCoords)
if (ex.key == "south" and ex.destination != prevRoom):
newCoords = (local_coords[0], local_coords[1]+1)
# Make sure have not already visited this room
# on another path...
if (self.is_valid_coords(newCoords) and not self.has_room(newCoords)):
self.do_cell_recursive(ex.destination, room, newCoords)
if (ex.key == "west" and ex.destination != prevRoom):
newCoords = (local_coords[0]-1, local_coords[1])
# Make sure have not already visited this room
# on another path...
if (self.is_valid_coords(newCoords) and not self.has_room(newCoords)):
self.do_cell_recursive(ex.destination, room, newCoords)
pass
def generate_map(self, roomCenter):
"""
Main call to generate the map.
This should be called anytime the room that is the center
of the map needs to change. I.e. when a player changes rooms.
"""
self.do_cell_recursive(roomCenter, roomCenter, MAP_CENTER)
# Convert map to unicode
for x in range(MAP_SIZE_W):
for y in range(MAP_SIZE_W):
if isinstance(self.map[x][y], basestring):
self.map[x][y] = self.map[x][y].decode('UTF-8')
pass
def __str__(self):
retStr = ""
# Flips so that the display starts with (0, 0) at the bottom
for y in range(MAP_SIZE_W):
retStr += "\n"
for x in range(MAP_SIZE_W):
# format to 2 char
retStr += '{: <1}'.format(self.map[x][y])
return retStr
<file_sep>/mechantania/batch_code/world_builder/connect_areas.py
#HEADER
import utils.builder_utils
#CODE
#
# Glues together the areas in order to form the whole world.
#
# For each area, gather all the rooms with tags for "special".
#for area, startRoom in caller.ndb.builder_area_list.iteritems():
#
# # First destroy any rooms from this area previously created.
# remove_all_rooms(tag=area, category="zone")
# Look for connectors
utils.builder_utils.connect_all_areas()
<file_sep>/mechantania/world/scripts/poison_script.py
from typeclasses.scripts import Script
class PoisonScript(Script):
def at_script_creation(self):
"""
Called when script object is first created. Sets things up.
We want to have a lid on the button that the user can pull
aside in order to make the button 'pressable'. But after a set
time that lid should auto-close again, making the button safe
from pressing (and deleting this command).
"""
self.key = "poison_script"
self.desc = "Script to control the poison effect on the player"
self.interval = 5
self.persistent = False
self.start_delay = True
#self.repeats = 1
# def is_valid(self):
# pass
#
# def at_start(self):
# pass
def at_stop(self):
self.obj.msg("The poison wears off!")
pass
def at_repeat(self):
# This is meant to be attached to the player with hp
hp = self.obj.db.mech_character_stats_container.get_value("hp_curr")
if (hp != None):
hp -= 20
self.obj.msg("%s Your body trembles as the poison courses through "
"your veins (HP: %s)." % (self.obj.name, hp))
self.obj.location.msg_contents("%s shivers and doesn't look so"
"good." % self.obj.name,
exclude=self.obj)
if (hp <= 0):
hp = 100
self.obj.msg("You DIE. Not.")
self.stop()
self.obj.db.mech_character_stats_container.set_value("hp_curr", hp)
<file_sep>/mechantania/commands/stats.py
# Commands related to stats
from evennia import default_cmds
import world.rules.rules as rules
class CmdStats(default_cmds.MuxCommand):
locks = "cmd:all()"
key = "stats"
aliases = ["stat"]
def func(self):
caller = self.caller
if self.args:
string = "Usage: stats"
self.caller.msg(string)
return
# Show the statistics for the player
stat = rules.calc_effective_stat("attack", caller)
caller.msg("attack stat: {}" .format(stat))
<file_sep>/mechantania/world/rules/rules.py
import random
# We have 3 main combat characteristics calculated from the
# character, character's armor/weapons, class, passive
# abilities, etc.
# 1. nibleness - Speed of attacks, ability to flee, ability to dodge, etc.
# 2. defense - resistance to attacks
# 3. offense - strength of attacks.
# Armor could be:
# There a number of slots on a character that can contain armor.
# Each slot contributes to the nimbleness or defense of a character.
#
# 0. None
# * +++ nimbleness
# * 0 defense
# 1. Light
# * ++ nimbleness
# * + defense
# 2. Medium
# * + nimbleness
# * ++ defense
# 3. Heavy
# * 0 nimbleness
# * +++ defense
# Weapons could be:
# 0. None
# 1. Martial (such as spiky gloves, or spiky feet, etc).
# * ++++ nibleness
# * + attack
# 2. Stab
# * +++ nibleness
# * ++ attack
# 3. Slice
# * ++ nimbleness
# * +++ attack
# 4. Slash
# * + nimbleness
# * ++++ attack
# 5. Smash
# * 0 nimbleness
# * +++++ attack.
def calc_effective_stat(statName, char, obj=None):
# Rule for calculating effective stat for the character from items/weapons.
# If obj==None, then we take the TOTAL over all objects
# TODO : Right now these are just getting total stat. Later though,
# we will have rules which affect how much of each stat actually gets
# added to the character (i.e. object's level vs char's level, etc)
if obj is None:
return char.equip.get_total_stat(statName)
else:
return char.equip.get_stat(statName, obj).actual
# Following functions calculate the stat related to each.
def calc_nimbleness(char):
# Could be affected by armor, weapon's size, etc.
pass
def calc_defense(char):
# Could be affected by armor, weapon's size, etc.
pass
def calc_offense(char):
# Could be affected by weapon's strength
pass
def resolve_combat(combat_handler, actiondict):
"""
This is called by the combat handler
actiondict is a dictionary with a list of two actions
for each character:
{char.id:[(action1, char, target), (action2, char, target)], ...}
"""
flee = {} # track number of flee commands per character
for isub in range(2):
# loop over sub-turns
messages = []
for subturn in (sub[isub] for sub in actiondict.values()):
# for each character, resolve the sub-turn
action, char, target = subturn
if target:
taction, tchar, ttarget = actiondict[target.id][isub]
if action == "hit":
if taction == "parry" and ttarget == char:
msg = "%s tries to hit %s, but %s parries the attack!"
messages.append(msg % (char, tchar, tchar))
elif taction == "defend" and random < 0.5:
msg = "%s defends against the attack by %s."
messages.append(msg % (tchar, char))
elif taction == "flee":
msg = "%s stops %s from disengaging, with a hit!"
flee[tchar] = -2
messages.append(msg % (char, tchar))
else:
msg = "%s hits %s, bypassing their %s!"
messages.append(msg % (char, tchar, taction))
elif action == "parry":
if taction == "hit":
msg = "%s parries the attack by %s."
messages.append(msg % (char, tchar))
elif taction == "feint":
msg = "%s tries to parry, but %s feints and hits!"
messages.append(msg % (char, tchar))
else:
msg = "%s parries to no avail."
messages.append(msg % char)
elif action == "feint":
if taction == "parry":
msg = "%s feints past %s's parry, landing a hit!"
messages.append(msg % (char, tchar))
elif taction == "hit":
msg = "%s feints but is defeated by %s hit!"
messages.append(msg % (char, tchar))
else:
msg = "%s feints to no avail."
messages.append(msg % char)
elif action == "defend":
msg = "%s defends."
messages.append(msg % char)
elif action == "flee":
if char in flee:
flee[char] += 1
else:
flee[char] = 1
msg = "%s tries to disengage (two subsequent turns needed)"
messages.append(msg % char)
# echo results of each subturn
combat_handler.msg_all("\n".join(messages))
# at the end of both sub-turns, test if anyone fled
msg = "%s withdraws from combat."
for (char, fleevalue) in flee.items():
if fleevalue == 2:
combat_handler.msg_all(msg % char)
combat_handler.remove_character(char)
<file_sep>/mechantania/typeclasses/mobjects/environment/wall.py
from evennia import CmdSet
from evennia import DefaultObject
"""
A tree object. A tree in a room will block the player from entering the room.
A player can chop the tree down and the tree will drop logs of wood (random)
Create this tree with:
@create/drop mobjects.environment.tree.Tree
"""
class DefaultWallCmdSet(CmdSet):
key = "Wall"
def at_cmdset_creation(self):
# No commands on this object.
pass
# TODO: Objects will have a host of flags on them. BLOCKING is one of them.
# This class should be refactoring with the BLOCKING flag and inherrited from
# an mobject later.
from evennia import DefaultObject
class Wall(DefaultObject):
def at_object_creation(self):
desc = "A large wall."
self.db.desc = desc
self.db.map_symbol = "#"
#
# Member variables
#
self.db.mIsBlocking = True
# no commands at this time. Also don't want the player to be able
# to "get" the tree.
self.cmdset.add_default(DefaultWallCmdSet, permanent=True)
<file_sep>/mechantania/adminscripts/updateAllObjectsOfType.py
# This is how to update all objects of type.
def updateAllObjectsOfType(objTypeClassPath, objTypeClass):
from objTypeClassPath import objTypeClass
[obj.at_object_creation() for obj in objTypeClass.objects.all()]
<file_sep>/mechantania/world/items.py
import typeclasses.objects as objects
from evennia.utils import lazy_property
from world.handlers.traits import TraitHandler
import world.rules.rules as rules
STATS_NAME = "stats_item"
# Stats common to all items.
STATS_ITEM = {
'rarity' : { 'name':'rarity', 'type':'static', 'base':0 },
}
# Stats common to all equippables
STATS_EQUIPPABLE = {
'attack' : { 'name':'attack', 'type':'static', 'base':0 },
'speed' : { 'name':'speed', 'type':'static', 'base':0 },
'defense' : {'name':'defense', 'type':'static', 'base':0 },
'bulkiness' : {'name':'bulkiness', 'type':'static', 'base':0 },
'durability' : {'name':'durability', 'type':'gauge', 'base':100, 'min':0},
'level' : { 'name':'level', 'type':'static', 'base':0 },
}
def RepresentsInt(s):
try:
int(s)
return True
except ValueError:
return False
# Light, medium, heavy armor/weapons/clothes.
# TODO: Maybe these should be related only to weapons/armor later,
# TODO: Turn this into a wrapper function instead
# not to clothes.
EQUIP_SIZES = ["none", "light", "medium", "heavy"]
class Item(objects.Object):
#for key, kwargs in BASE_STATS.iteritems():
# self.stats_base.add(key, **kwargs)
def at_object_creation(self):
super(Item, self).at_object_creation()
self.locks.add(";".join(("puppet:perm(Wizards)",
"equip:false()",
"get:true()"
)))
# Attach the item stats.
if self.stats:
del self.stats
# Create the stats if they don't already exist.
for key, kwargs in STATS_ITEM.iteritems():
if not self.stats.get(key):
# Only add the stat if it doesn't exist.
self.stats.add(key, **kwargs)
# Check the "ndb" stat names, which might have been set through
# prototypes.
if key in self.nattributes.all():
stat = self.stats.get(key)
if stat is not None:
stat.base = self.nattributes.get(key)
def return_apearance(self, looker):
pass
def get_level(self):
return self.stats.level.actual
def get_rarity(self):
return self.stats.rarity.actual
def get_durability_percentage(self):
return self.stats.durability.actual
def pp_stats(self, looker=None, excludeStats=None):
# Pretty print the stats of the item.
# excludeStats are stats that should be excluded, such as:
# excludeStats = ["level", "rarity"]
# If looker is not None, then this function will display the effective stat
# this item will have on the looker.
data = []
if excludeStats is None:
excludeStats = []
for statKey in self.stats.all:
if not (statKey.lower() in excludeStats):
stat = self.stats.get(statKey)
if stat.actual != 0:
# Only print stats that have an actual value.
if looker is not None:
dataString = "{statValue} (effective: {effectiveValue})".format(
statValue=stat,
effectiveValue=rules.calc_effective_stat(statKey, looker, self))
else:
dataString = "{statValue}".format(
statValue=stat)
data.append(dataString)
# print "data: {}".format(data)
# table = EvTable(header=False, border=None, table=[data])
return "".join(data)
@lazy_property
def stats(self):
return TraitHandler(self, db_attribute=STATS_NAME)
class Equippable(Item):
def at_object_creation(self):
super(Equippable, self).at_object_creation()
self.locks.add("puppet:false();wear:true()")
# Default slot is armor.
self.db.slots = ["body"]
# Attach the item stats.
for key, kwargs in STATS_EQUIPPABLE.iteritems():
if not self.stats.get(key):
# Only add the stat if it doesn't exist.
self.stats.add(key, **kwargs)
def at_equip(self, equipper):
pass
def basetype_posthook_setup(self):
# Check the "db" stat names, which might have been set through
# prototypes.
# This is called from basetype_posthook_setup because all of the attributes
# in a prototype are added BEFORE this call in at_first_save, but after
# at_object_creation (so at_object_creation can't be used)
# Any DB stats with traits of the same name will instead set the state,
# and the corresponding attribute will be removed.
for key in self.stats.all:
attribValue = self.attributes.get(key)
if attribValue is not None:
stat = self.stats.get(key)
stat.base = attribValue
self.attributes.remove(key)
# Init internal attributes
self.__init_prototype_attribs()
print("equip size : {}".format(self.db.equip_size))
#
# Internal functions
#
def __init_prototype_attribs(self):
# Checks that the attributes from prototypes is valid
equip_size = self.attributes.get("equip_size")
# Clean equip size, either by converting to int from string or by cleaning the string.
if equip_size is not None:
equip_size = equip_size.lower()
if equip_size not in EQUIP_SIZES:
raise ValueError("Invalid equip_size param {}".format(equip_size))
self.db.equip_size = equip_size
<file_sep>/mechantania/typeclasses/mobjects/items/poison_object.py
"""
A simple poison object.
This will be [drink]able by the player. If it is [drinked], then
the player's health will diminish by -20 HP every 10 seconds. A message
will be sent to the player that his health is being depleted, and a message
will be sent to the room that the player looks ill.
After the player's health has reached 0 HP, the Player's HP will reset
and a message will be emitted stating the player has fake died.
Create this poison with
@create/drop temp.objects.poison_object.Poison
"""
from typeclasses.objects import Object
from commands.items.poison_commands import DefaultCmdSet as poisonCmdSet
from mscripts.poison_script import PoisonScript
#
# Poison definition
#
class Poison(Object):
def at_object_creation(self):
"""
Called when object is created.
"""
desc = "A bottle of poison."
self.db.desc = desc
# Must define these before adding the scripts
# incase the scripts reference these
self.db.is_full = True
self.cmdset.add_default(poisonCmdSet, permanent=True)
def return_appearance(self, looker):
# Get the description of parent
string = super(Poison, self).return_appearance(looker)
if self.db.is_full:
return string + "\n\nA tiny bottle of |g green |n liquid."
else:
return string + "\n\nThe bottle appears empty"
def do_drink(self, pobject):
if (not self.db.is_full):
pobject.msg("You can't drink from an empty bottle...")
return
if (pobject.db.mech_character_stats_container == None):
pobject.msg("You can't drink this poison, apparently you have no "
"stats... are you even alive?")
return
currHp = pobject.db.mech_character_stats_container.get_value("hp_curr")
if (currHp == None):
pobject.msg("You can't drink this poison, apparently you have no"
"HP... are you even alive?")
# Why is this called on a non-player?
return
# Attach the poison script to the player
pobject.scripts.add(PoisonScript)
pobject.msg("You chug the bottle of poison.")
self.db.is_full = False
<file_sep>/mechantania/typeclasses/mobjects/mech_base_rooms.py
"""
Room
Rooms are simple containers that has no location of their own.
"""
from evennia import DefaultRoom
from evennia import DefaultCharacter
DEFAULT_ROOM_CHAR = '`'
class MechBaseRoom(DefaultRoom):
"""
Rooms are like any Object, except their location is None
(which is default). They also use basetype_setup() to
add locks so they cannot be puppeted or picked up.
(to change that, use at_object_creation instead)
See examples/object.py for a list of
properties and methods available on all Objects.
"""
def at_object_creation(self):
self.db.map_symbol = ","
# Returns if the room is blocked by an object or not.
def get_blocking_objects(self):
# Search the room's objects for any blocking object.
return [obj for obj in self.contents_get() if
hasattr(obj.db, 'mIsBlocking') and obj.db.mIsBlocking]
def return_appearance(self, looker):
desc = super(MechBaseRoom, self).return_appearance(looker)
return desc
def get_map_symbol(self, looker=None):
map_symbol = DEFAULT_ROOM_CHAR
#
# Perform these operations in this order (where successive checks
# override last)
# 1) Room map symbol (should exist always).
# 2) Object map symbol (if multiple objects, then what?)
# 3) Non-player charater map symbol
# 4) player character map symbol
if (type(self.attributes.get('map_symbol') == str)):
map_symbol = self.attributes.get('map_symbol')
# Search for objects in the room with map symbols.
for obj in self.contents_get():
if not isinstance(obj, DefaultCharacter):
if obj.attributes.has('map_symbol'):
map_symbol = obj.attributes.get('map_symbol')
# Search for characters
# TODO: Color these red or green depending on aggr, non-aggr, or npc
for obj in self.contents_get():
if isinstance(obj, DefaultCharacter):
if obj.attributes.has('map_symbol'):
map_symbol = obj.attributes.get('map_symbol')
return map_symbol
<file_sep>/mechantania/utils/builder_utils.py
import evennia.utils.search
from typeclasses.rooms import Room
from typeclasses.characters import Character
from typeclasses.accounts import Account
from typeclasses.exits import Exit
import evennia
def remove_all_rooms(tag=None, category=None):
if tag:
rooms = evennia.utils.search.search_object_by_tag(key=tag, category=category)
else:
# Removes all rooms from the world, except for limbo
rooms = Room.objects.all()
numRooms = len(rooms) - 2 # Don't count Limbo
cntr = 0
for room in rooms:
# Clear exits
room.clear_exits()
if room.name == "Limbo" or room.id == 2:
# Don't delete limbo
continue
print "Deleting room %d / %d" % (cntr, numRooms)
# First delete on non-account, non-character objects in the room if
# their home is set to this zone.
roomObjects = room.contents
for roomObject in roomObjects:
if (not isinstance(roomObject, Character)
and not isinstance(roomObject, Account)):
# roomObject.scripts.clear()
print (" Deleting object '%s'" %roomObject.name)
roomObject.delete()
# Clear scripts
# roomScripts = room.scripts.all()
# for script in roomScripts:
# script.stop()
# Delete the room
room.delete()
cntr += 1
def connect_all_areas():
CARDINAL_DIRS = { "north" : "south",
"south" : "north",
"east" : "west",
"west" : "east",
"northeast" : "southwest",
"southwest" : "northeast",
"southeast" : "northwest",
"northwest" : "southeast"}
EXIT_OPPOSITE = { "north" : "south",
"south" : "north",
"east" : "west",
"west" : "east",
"northeast" : "southwest",
"southwest" : "northeast",
"southeast" : "northwest",
"northwest" : "southeast"}
def is_cardinal_direction(mech_exit):
return mech_exit.name in CARDINAL_DIRS
# Gets the exit of of the opposite direction from destRoom (i.e.
# if mech_exit is North, it will return the Exit object of South
# from destRoom.
# If opposite exit is not found, it will return None.
def get_opposite_exit(mech_exit, destRoom):
for exit in destRoom.exits:
if EXIT_OPPOSITE[exit.name] == mech_exit.name:
return exit
return None
# Get all the rooms that match the <area> tag
connector_from_rooms = evennia.utils.search.search_object_by_tag(key="connector_from",
category="map_builder")
connector_to_rooms = evennia.utils.search.search_object_by_tag(key="connector_to",
category="map_builder")
for from_room in connector_from_rooms:
# get the connector dict
connectorDict = from_room.db.map_builder_connector_dict
if not connectorDict:
raise Exception("No connector dictionary assigned to connector from_room "
"%s/#%d in zone %s" %(from_room.name,
int(from_room.id),
from_room.tags.get(category="zone")))
zoneDest = connectorDict["zoneDestination"]
connectorName = connectorDict["connectorName"]
for rooms in connector_to_rooms:
print "TEST"
print "zoneDest: " + zoneDest
print "connectorname: " + connectorName
print rooms.tags.all(return_key_and_category=True)
print rooms.ndb.connector_name
print "connectorname == rooms.ndb.connector_name" + \
str(str(connectorName) == str(rooms.ndb.connector_name))
# Search the to rooms for the one with a tag with zoneDest as zone
# TROUBLE HERE. connector_name == connectorName doesn't seem to work.
to_room = [to_room for to_room in connector_to_rooms if \
to_room.tags.get(zoneDest, category="zone") and \
(str(to_room.ndb.connector_name) == str(connectorName))]
# Do we have multiple to rooms?
if len(to_room) > 1:
exMsg = "Multiple to_room for connector to zone %s:%s" %(zoneDest, connectorName)
raise Exception(exMsg)
if len(to_room) == 0:
exMsg = "No to_room matching %s:%s" %(zoneDest, connectorName)
raise Exception(exMsg)
if to_room == None:
exMsg = "No to_room for connector to zone %s:%s" %(zoneDest, connectorName)
raise Exception(exMsg)
to_room = to_room[0]
# Gather exits leading into this room.
# Check to make sure to_room doesn't already have these exits.
# Follow the exit to exit's distination, and then set the cardinal
# direction exit to the to_room instead
# Then delete the from_room connector.
#Gather exits
from_room_exits = from_room.exits
to_room_exits = to_room.exits
# Gather exits in "from_room", and move them to "to_room"
for from_exit in from_room_exits:
exit_in_to_room = False
create_exit_name = from_exit.name
if (is_cardinal_direction(from_exit)):
for to_exit in to_room_exits:
if to_exit.name == create_exit_name:
exit_in_to_room = True
if exit_in_to_room:
raise Exception("Can't connect connector room exit. There"
"is already an exit named %s in room #%s"
% (create_exit_name, to_room.id))
# Create the exit in the to_room, same as exit in from_room
evennia.create_object(typeclass = "exits.Exit",
key=create_exit_name,
location=to_room,
destination=from_exit.destination,
aliases=from_exit.aliases.all())
# Now iterate over all the rooms with exits to the "from_room", and
# set their destination to the to room.
for currExit in Exit.objects.all_family():
if currExit.destination == from_room:
currExit.destination = to_room
# TODO: Clean up, remove connector tags, etc
# TODO: ADd locks?
<file_sep>/mechantania/world/scripts/combat/combat_handler.py
import random
from typeclasses.scripts import Script
#TODO: Message actions to room.
class HitType:
UNARMED = 1
def HitTargets(char, targets):
target = None
if (type(targets) == list):
if (len(targets) == 0):
raise ValueError("Targets must not be empty!")
if len(targets) > 1:
char.msg("|rWARNING|n: Can't hit more than one target currently. " \
"Defaulting to first target.")
target = targets[0]
else:
target = targets
# Determine type of hit by checking weapon that char is weilding.
# TODO: Implement this after implementing weapons. For now just
# punch.
# TODO: Move this to its own module.
hitType = HitType.UNARMED
if hitType == HitType.UNARMED:
# Move this to its own module.
charHitMsg = "punch"
targetHitMsg = "punches"
else:
raise ValueError("Invalid hittype")
# TODO: You should pull this from a rule book instead!
rollDamage = random.randint(1, 1000)
char.msg("You {0} {1} for [{2}] damange.".format(charHitMsg, target, rollDamage))
target.msg("{0} {1} you for [{2}] damage.".format(char, targetHitMsg, rollDamage))
# Todo: automatically target when only two characters
class CombatHandler(Script):
"""
This implements the combat handler.
"""
# standard Script hooks
def at_script_creation(self):
"Called when script is first created"
self.key = "combat_handler_%i" % random.randint(1, 1000)
self.desc = "handles combat"
self.interval = 60 * 2 # two minute timeout
self.start_delay = True
self.persistent = True
# store all combatants
# A dict of dbref : character object
self.db.characters = {}
# A dict of dbref : [ targets ]
self.ndb.targets = {}
# Character battle queue. First one in queue gets to go next.
self.db.characterQueue = []
def _init_character(self, character):
"""
This initializes handler back-reference
and combat cmdset on a character
"""
character.ndb.combat_handler = self
character.cmdset.add("commands.combat.combat.CombatCmdSet")
def _cleanup_character(self, character):
"""
Remove character from handler and clean
it of the back-reference and cmdset
"""
dbref = character.id
del self.db.characters[dbref]
del self.ndb.targets[dbref]
# Remove character from queue
if dbref in self.db.characterQueue:
self.db.characterQueue.remove(dbref)
del character.ndb.combat_handler
character.cmdset.delete("commands.combat.combat.CombatCmdSet")
character.msg("|yYour battle is over.|n")
def _update_battle_queue(self):
# Pop off the top, then push onto back
charTurn = self.db.characterQueue.pop(0)
self.db.characterQueue.append(charTurn)
return self.db.characterQueue[0]
def _get_character_object(self, dbref):
return self.db.characters.get(dbref)
def at_start(self):
"""
This is called on first start but also when the script is restarted
after a server reboot. We need to re-assign this combat handler to
all characters as well as re-assign the cmdset.
"""
for character in self.db.characters.values():
self._init_character(character)
# Select a random character for turn
def at_stop(self):
"Called just before the script is stopped/destroyed."
for character in list(self.db.characters.values()):
# note: the list() call above disconnects list from database
self._cleanup_character(character)
def at_repeat(self):
"""
This is called every self.interval seconds (turn timeout) or
when force_repeat is called (because everyone has entered their
commands). We know this by checking the existence of the
`normal_turn_end` NAttribute, set just before calling
force_repeat.
"""
if self.ndb.normal_turn_end:
# we get here because the turn ended normally
# (force_repeat was called) - no msg output
del self.ndb.normal_turn_end
else:
# turn timeout
self.msg_all("Turn timer timed out. Continuing.")
self.end_turn()
# Combat-handler methods
def add_character(self, character):
"Add combatant to handler"
dbref = character.id
self.db.characters[dbref] = character
self.ndb.targets[dbref] = []
self.db.characterQueue.append(character.id)
self._init_character(character)
def remove_character(self, character):
"Remove combatant from handler"
if character.id in self.db.characters:
# Cleanup the character, deleting entries.
self._cleanup_character(character)
if not self.db.characters or len(self.db.characters) < 2:
# if no more characters in battle, kill this handler
self.stop()
def msg_all(self, message):
"Send message to all combatants"
for character in self.db.characters.values():
character.msg(message)
def add_action(self, action, character):
"""
Called by combat commands to perform an action.
If it is not character's turn, this command will do nothing.
If it is character's turn, this function will attempt to
perform the action on the character's selected targets.
action - string identifying the action, like "hit" or "parry"
character - the character performing the action
target - the target character or None
actions are stored in a dictionary keyed to each character, each
of which holds a list of max 2 actions. An action is stored as
a tuple (character, action, target).
"""
dbref = character.id
retMsg = ""
targetId = None
# Check if this character's turn.
if (self.db.characterQueue[0] != character.id):
character.msg( "It's not your turn...")
return False
if len(self.ndb.targets) == 0 or len(self.ndb.targets[character.id]) == 0:
# TODO: Maybe have a function for each action type to pick the
# targets. AOE spells might not require a single target.
# No targets, so pick one at random (excluding the character
# obviously)
potentialTargets = \
[char for char in self.db.characters.values() if char != character]
randTarget = random.choice(potentialTargets)
targetId = randTarget.id
retMsg += "You are not targetting anyone, so targetting {target} " \
"at random.\n".format(target=randTarget)
else:
if character.id in self.ndb.targets:
targetId = self.ndb.targets[character.id][0]
if targetId == None:
character.msg( "|rERROR: |n problems finding a suitable target.")
return False
if targetId not in self.db.characters:
character.msg( "|rERROR: |n Target is not in list of combatants!")
return False
targetChar = self.db.characters[targetId]
if (action == "hit"):
HitTargets(character, targetChar)
self.end_turn()
return True
def end_turn(self):
"""
This resolves all actions by calling the rules module.
It then resets everything and starts the next turn. It
is called by at_repeat().
"""
if len(self.db.characters) < 2:
# less than 2 characters in battle, kill this handler
self.msg_all("Combat has ended")
self.stop()
else:
# reset counters before next turn
for character in self.db.characters.values():
self.db.characters[character.id] = character
# Send messages to everyone indicating who's turn it is.
currChar = self._get_character_object(self.db.characterQueue[0])
nextChar = self._get_character_object(self._update_battle_queue())
currChar.msg("Your turn is over. It is now {char}'s turn.".format(char = \
nextChar))
nextChar.msg("It is now YOUR turn!")
for ch in self.db.characters.values():
if ch.id != currChar.id and ch.id != nextChar.id:
ch.msg("It is now {char}'s turn.".format(char=nextChar))
<file_sep>/mechantania/commands/combat/combat.py
from evennia import Command
from evennia import create_script
from evennia import default_cmds
from evennia.commands.cmdset import CmdSet
from evennia.commands.default import help
# Commands
# Attack commands
# Hit (weapon type slice, slash, etc)
## Physical attack
#
# Misc commands
## Target <enemy 1> <enemy 2>, etc
### Doesn't take a turn
#
## Flee
### Take a chance to flee from combat. Opponents won't be able
### to attack you for 10 seconds.
## Backout
### Debug command to end the fight.
class CmdHit(Command):
"""
hit an enemy
usage:
hit <target>
Strikes the given enemy with your current weapon.
"""
key = "hit"
aliases = ["strike", "slash"]
help_category = "combat"
def func(self):
"Implements the command"
# if not self.args:
# self.caller.msg("Usage: hit <target>")
# return
# target = self.caller.search(self.args)
# if not target:
# return
ok = self.caller.ndb.combat_handler.add_action("hit",
self.caller)
if not ok:
self.caller.msg("You cannot {0}".format(self.key))
# # tell the handler to check if turn is over
# self.caller.ndb.combat_handler.check_end_turn()
#class CmdParry(Command):
# """
# parry an enemy
#
# usage:
# parry <target>
#
# Strikes the given enemy with your current weapon.
# """
# key = "parry"
# help_category = "combat"
#
# def func(self):
# "Implements the command"
# if not self.args:
# self.caller.msg("Usage: parry <target>")
# return
# target = self.caller.search(self.args)
# if not target:
# return
# ok = self.caller.ndb.combat_handler.add_action("parry",
# self.caller,
# target)
#
# if ok:
# self.caller.msg("You add 'parry' to the combat queue")
# else:
# self.caller.msg("You can only queue two actions per turn!")
#
# # tell the handler to check if turn is over
# self.caller.ndb.combat_handler.check_end_turn()
#
#class CmdFeint(Command):
# """
# feint an enemy
#
# usage:
# feint <target>
#
# Strikes the given enemy with your current weapon.
# """
# key = "feint"
# help_category = "combat"
#
# def func(self):
# "Implements the command"
# if not self.args:
# self.caller.msg("Usage: feint <target>")
# return
# target = self.caller.search(self.args)
# if not target:
# return
# ok = self.caller.ndb.combat_handler.add_action("feint",
# self.caller,
# target)
#
# if ok:
# self.caller.msg("You add 'feint' to the combat queue")
# else:
# self.caller.msg("You can only queue two actions per turn!")
#
# # tell the handler to check if turn is over
# self.caller.ndb.combat_handler.check_end_turn()
#
#
#class CmdDefend(Command):
# """
# defend an enemy
#
# usage:
# defend <target>
#
# Strikes the given enemy with your current weapon.
# """
# key = "defend"
# help_category = "combat"
#
# def func(self):
# "Implements the command"
# if not self.args:
# self.caller.msg("Usage: defend <target>")
# return
# target = self.caller.search(self.args)
# if not target:
# return
# ok = self.caller.ndb.combat_handler.add_action("defend",
# self.caller,
# target)
#
# if ok:
# self.caller.msg("You add 'defend' to the combat queue")
# else:
# self.caller.msg("You can only queue two actions per turn!")
#
# # tell the handler to check if turn is over
# self.caller.ndb.combat_handler.check_end_turn()
#
#class CmdDefend(Command):
# """
# defend an enemy
#
# usage:
# defend <target>
#
# Strikes the given enemy with your current weapon.
# """
# key = "defend"
# help_category = "combat"
#
# def func(self):
# "Implements the command"
# if not self.args:
# self.caller.msg("Usage: defend <target>")
# return
# target = self.caller.search(self.args)
# if not target:
# return
# ok = self.caller.ndb.combat_handler.add_action("defend",
# self.caller,
# target)
#
# if ok:
# self.caller.msg("You add 'defend' to the combat queue")
# else:
# self.caller.msg("You can only queue two actions per turn!")
#
# # tell the handler to check if turn is over
# self.caller.ndb.combat_handler.check_end_turn()
#
#class CmdDisengage(Command):
# """
# disengage an enemy
#
# usage:
# disengage <target>
#
# Strikes the given enemy with your current weapon.
# """
# key = "disengage"
# help_category = "combat"
#
# def func(self):
# "Implements the command"
#
# if not self.args:
# self.caller.msg("Usage: disengage <target>")
# return
# target = self.caller.search(self.args)
# if not target:
# return
# ok = self.caller.ndb.combat_handler.add_action("disengage",
# self.caller,
# target)
#
# if ok:
# self.caller.msg("You add 'disengage' to the combat queue")
# else:
# self.caller.msg("You can only queue two actions per turn!")
#
# # tell the handler to check if turn is over
# self.caller.ndb.combat_handler.check_end_turn()
class CmdBackout(Command):
"""
Backs out of combat.
usage:
backout
USED ONLY FOR TESTING.
Will remove the character from the combat handler.
"""
key = "backout"
help_category = "combat"
def func(self):
self.caller.msg("You backout from combat...")
self.caller.ndb.combat_handler.remove_character(self.caller)
class CombatCmdSet(CmdSet):
key = "combat_cmdset"
mergetype = "Replace"
priority = 10
no_exits = True
def at_cmdset_creation(self):
self.add(CmdHit())
# self.add(CmdParry())
# self.add(CmdFeint())
# self.add(CmdDefend())
# self.add(CmdDisengage())
self.add(CmdBackout())
self.add(default_cmds.CmdPose())
self.add(default_cmds.CmdSay())
self.add(default_cmds.CmdHelp())
# The help system
self.add(help.CmdHelp())
self.add(help.CmdSetHelp())
class CmdAttack(Command):
"""
initiates combat
Usage:
attack <target>
This will initiate combat with <target>. If <target is
already in combat, you will join the combat.
"""
key = "attack"
help_category = "General"
def func(self):
"Handle command"
if not self.args:
self.caller.msg("Usage: attack <target>")
return
target = self.caller.search(self.args)
if not target:
return
# set up combat
if target.ndb.combat_handler:
# target is already in combat - join it
target.ndb.combat_handler.add_character(self.caller)
target.ndb.combat_handler.msg_all("%s joins combat!" % self.caller)
else:
# create a new combat handler
# TODO Change path of this..
chandler = create_script("mscripts.combat.combat_handler.CombatHandler")
chandler.add_character(self.caller)
chandler.add_character(target)
self.caller.msg("You attack %s! You are in combat." % target)
target.msg("%s attacks you! You are in combat." % self.caller)
<file_sep>/HINTS.md
To upgrade evennia core:
pip install --upgrade -e evennia
* On Windows, use "evennia.bat" instead in below commands, if running from git bash
To get into pyenv:
source ./pyenv/Scripts/activate
To init evennia:
evennia --init <gamename>
To start evennia:
* I found this doesn't work in git bash, so I run in Windows CMD:
evennia start
evennia stop
etc
| e38cdcefd0f2d1c79864861156a9e7ede04ffcbb | [
"Markdown",
"Python"
] | 21 | Python | Klayre/mechantania | 6ea0a80165707bffcab07d5f4ac46869bfc04635 | e66e0999cc788d89c1b974d04ca5e23d6561267f |
refs/heads/master | <repo_name>BiggaHD/node-mail<file_sep>/app.js
const express = require("express");
const bodyParser = require("body-parser");
const nodemailer = require("nodemailer");
const smtpTransport = require("nodemailer-smtp-transport");
const creds = require("./config/credentials");
const app = express();
// Enable CORS
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.set("view engine", "hbs");
// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Getting the form-data from React
app.post("/form-data", (req, res) => {
let output = `
<p>You have a new contact request</p>
<h3>Contact Details:</h3>
<ul>
<li>Name: ${req.body.formData.name}</li>
<li>Company: ${req.body.formData.company}</li>
<li>Email: ${req.body.formData.email}</li>
<li>Phone: ${req.body.formData.phone}</li>
</ul>
<h3>Message:</h3>
<p>${req.body.formData.message}</p>
`;
let transporter = nodemailer.createTransport(
smtpTransport({
service: "gmail",
host: "smtp.gmail.com",
auth: {
user: creds.user,
pass: <PASSWORD>
},
tls: {
rejectUnauthorized: false // Not safe for production
}
})
);
// Setup email data with unicode symbols
let mailOptions = {
from: `Contact Form - ${req.body.formData.email}`, // sender address
to: creds.user, // list of receivers
subject: "Node Contact Request", // Subject line
text: "", // plain text body
html: output // html body
};
// Send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log("Message sent: %s", info.messageId);
res.status(200).json({ msg: "Email has been sent" });
});
});
app.listen(5050, () => console.log("Server started..."));
| fb1a3291827e4b5adfd8a587436f31f761a882e9 | [
"JavaScript"
] | 1 | JavaScript | BiggaHD/node-mail | 7cca705bbdc56ebb9d1d512de750c943d508a8fd | ac001ddf8ca0dd8ec507a0afa162674c007ece34 |
refs/heads/master | <repo_name>Niharika3128/my_profile<file_sep>/Profile/app_profile/models.py
from django.db import models
class ProfileReg(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
contact_no = models.IntegerField()
email = models.EmailField(max_length=100)
subject = models.TextField(max_length=100)
message = models.TextField(max_length=1000)<file_sep>/Profile/app_profile/views.py
from django.shortcuts import render
from .models import ProfileReg
from django.core.mail import EmailMessage
from Profile import settings as se
def index_profile(request):
return render(request,'index.html')
def profile_Save(request):
if request.method == "POST":
fname = request.POST.get("fname")
lname = request.POST.get("lname")
cno = request.POST.get("pnum")
email = request.POST.get("email")
sub = request.POST.get("subject")
mes = request.POST.get("message")
mess_age = smsACASMSotp(fname,cno)
import json
d1 = json.loads(mess_age)
if d1['return']:
to = email
emails = list(to.split(','))
em = EmailMessage(fname,mes,se.EMAIL_HOST_USER,emails)
em.send(False)
ProfileReg(first_name=fname,last_name=lname,contact_no=cno,email=email,subject=sub,message=mes).save()
return render(request,'index.html',{"MES":"Your Response is Successfully Submitted"})
else:
return render(request,'index.html',{"MES": "Inavild Contact_No"})
def smsACASMSotp(fname,cno):
import requests
url = "https://www.fast2sms.com/dev/bulk"
payload = "sender_id=FSTSMS&message=Hello,Mr./Ms. "+ str(fname)+ ", Thankyou for your attention" +"&language=english&route=p&numbers=" + cno
headers = {
'authorization': "<KEY>",
'Content-Type': "application/x-www-form-urlencoded",
'Cache-Control': "no-cache",
}
response = requests.request("POST", url, data=payload, headers=headers)
print(response.text)
return response.text | aa9c266032899801d3947787b8b2c87e122093d6 | [
"Python"
] | 2 | Python | Niharika3128/my_profile | ce7fa03e7c7a88f57bdd0d67025512440e214edd | 8717ab6fa8303815f6615f383e493ceed46d1025 |
refs/heads/master | <file_sep>include ':app'
rootProject.name='WifiManager'
<file_sep># WifiManager
WiFi controller application.
This provide the wifi feture enable or disable using a button click
<file_sep>package com.bush.wifimanager;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
Button btnWifiOn, btnwifioff;
WifiManager wifiManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnWifiOn = findViewById(R.id.btnTurnOn);
btnwifioff = findViewById(R.id.btnTurnOff);
btnWifiOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifiManager != null) {
wifiManager.setWifiEnabled(true);
Log.d(TAG, "onClick: Wifi enabled");
}
Toast.makeText(MainActivity.this, "Wifi Turn On", Toast.LENGTH_SHORT).show();
}
});
btnwifioff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
if (wifiManager != null) {
wifiManager.setWifiEnabled(false);
Log.d(TAG, "onClick: Wifi disabled");
}
Toast.makeText(MainActivity.this, "Wifi Turn OFF", Toast.LENGTH_SHORT).show();
}
});
}
}
| b15655ee8084332002706f5d54e86754f5a6c12c | [
"Markdown",
"Java",
"Gradle"
] | 3 | Gradle | budhdisharma23/WifiManager | 35b5d9d26b817302d67d95c14c57ae4bb3370c47 | 4505ec5c5ffa46de45e5c504c13e5331516efb9d |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
import datetime
class FangyuanPipeline(object):
def __init__(self):
self.connect = pymysql.connect(
host = "127.0.0.1",
port = 3306,
db = "tongcheng",
user = "root",
passwd = "",
charset = 'utf8',
use_unicode = True
)
self.cursor = self.connect.cursor()
print("连接数据库成功,正在存入数据库...")
def process_item(self, item, spider):
sql = "SELECT phone FROM info1 WHERE phone = %s;"%item['phone']
status = self.cursor.execute(sql)
if status == 0:
self.cursor.execute(
"""insert into info1(create_time,cname, phone, city, post_time)
value (%s,%s, %s, %s, %s)""",
(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
item['name'],
item['phone'],
item["city"],
item['time']
))
self.connect.commit()
else:pass
return item
def close_spider(self,spider):
self.connect.close()
# CREATE TABLE info (
# auto_id INT NOT NULL primary key AUTO_INCREMENT,
# create_time DateTime NOT NULL,
# cname VARCHAR(20),
# phone VARCHAR(20),
# city VARCHAR(20),
# post_time VARCHAR(20));
<file_sep># -*- coding: utf-8 -*-
import scrapy
import re
import jsonpath
from FangYuan.items import FangyuanItem
import time
from FangYuan.cityList import cityList
class ErshoufangSpider(scrapy.Spider):
name = 'fy'
allowed_domains = ['luna.58.com']
# scrapy crawl fy -a city=武汉 接收参数
def __init__(self, city=None,*args, **kwargs):
super(ErshoufangSpider, self).__init__(*args, **kwargs)
self.city = city
def start_requests(self):
city_code = jsonpath.jsonpath(cityList,"$..{}".format(self.city))[0].split("|")[0]
start_urls = ['https://luna.58.com/m/autotemplate?city={}&temname=ershoufang_common'.format(city_code),'https://luna.58.com/m/autotemplate?city={}&temname=zufang_common'.format(city_code)]
for url in start_urls:
yield scrapy.Request(url,dont_filter = True)
def parse(self, response):
text = response.body.decode('utf-8') #将response转为字符串用正则提取linkUrl
linkUrl = re.findall(r'"linkUrl":"(https://luna.58.com/list.shtml\?plat=m.*?)"',text)
city = re.findall(r'href=".*?class="city">(.*?)</a>',text)[0]
for link in linkUrl:
#此处为ajex加载,pn表示页数,大概看了下所有商品不会超过20页
links = [link + "&pn=" +str(pn) for pn in range(1,21)]
for url in links:
yield scrapy.Request(url,callback=self.parse_shop,meta={"city":city})
def parse_shop(self,response):
text = response.body.decode('utf-8')
try:
shouID = re.findall(r'"infoId":"([0-9]*?)"',text)
shouID = list(set(shouID))
for id in shouID:
shopUrl = "https://luna.58.com/info/"+id
yield scrapy.Request(shopUrl,callback=self.parse_info,meta={"shopUrl":shopUrl,"city":response.meta["city"]})
except Exception as e:
print("parse_shop错误:",e)
def parse_info(self,response):
shopUrl = response.meta["shopUrl"]
item = FangyuanItem()
text = response.body.decode('utf-8')
try:
name = re.findall(r'"contactperson":"(.*?)"',text)[0]
phone = re.findall(r'"phone":"([0-9]*?)"',text)[0]
post_time = re.findall(r'"postdate":"([0-9-]*?)"',text)[0]
cmmtype = re.findall(r'"cmmtype":"(\d)"',text)[0] #经纪人还是个人“1”表示个人,“0”表示经纪人
timeArray = time.strptime(post_time, "%Y-%m-%d") #转换成时间数组
timestamp = time.mktime(timeArray) #转换成时间戳
now_time = int(time.time())
if now_time-timestamp > 86400*30 or int(cmmtype)==0:
print("此信息不符合条件,过滤")
else:
# item["shopUrl"] = shopUrl
item["time"] = post_time
item["name"] = name + "(个人)"
item["phone"] = phone
item["city"] = response.meta["city"]
yield item
except Exception as e:
print("parse_info错误:",e)
<file_sep># -*- coding: utf-8 -*-
import os
import sys
citys = sys.argv[1:]
for city in citys:
cmd = "scrapy crawl fy -a city={}".format(city)
os.system(cmd)
| 0b2d49c057093420b03c0494a38aa47771de5b3d | [
"Python"
] | 3 | Python | zwl-Haley/58--scrapy | 442e0a476160449173179333de539ce8f72704e0 | 7a3c7cf2976be5d7c110a1998b3ff63c1e96fbf8 |
refs/heads/main | <repo_name>AkshayReddy57/alore-growth<file_sep>/src/app/main/add-segment/add-segment.component.ts
import {
Component,
Inject,
OnInit
} from '@angular/core';
import {
FormBuilder,
FormGroup
} from '@angular/forms';
import {
MatDialogRef,
MAT_DIALOG_DATA
} from '@angular/material/dialog';
import {
AppComponent
} from 'src/app/app.component';
export interface DialogData {
icon: string;
description: string;
name: string;
}
@Component({
selector: 'app-add-segment',
templateUrl: './add-segment.component.html',
styleUrls: ['./add-segment.component.scss']
})
export class AddSegmentComponent implements OnInit {
addSegmentForm: FormGroup;
public textArea: string = '';
public isEmojiPickerVisible: boolean;
public addEmoji(event) {
this.addSegmentForm.get('icon').setValue(`${this.textArea}${event.emoji.native}`)
this.textArea = `${this.textArea}${event.emoji.native}`;
this.isEmojiPickerVisible = false;
}
constructor(
public dialogRef: MatDialogRef < AppComponent > ,
private formBuilder: FormBuilder,
@Inject(MAT_DIALOG_DATA) public data: DialogData
) {}
ngOnInit(): void {
this.addSegmentForm = this.formBuilder.group({
name: [''],
icon: [''],
description: ['']
})
}
selectIcon(event) {
this.isEmojiPickerVisible = true
}
save() {
this.dialogRef.close(this.addSegmentForm.value);
}
close() {
this.dialogRef.close();
}
}
<file_sep>/src/app/app.component.ts
import {
Component
} from '@angular/core';
import {
MatDialog
} from '@angular/material/dialog';
import {
AddSegmentComponent
} from './main/add-segment/add-segment.component';
import {
EmojiModule
} from '@ctrl/ngx-emoji-mart/ngx-emoji';
import {
AddTableComponent
} from './main/add-table/add-table.component';
import {
TooltipPosition
} from '@angular/material/tooltip';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'alore';
segments = [];
public textArea: string = '';
icon: string;
description: string;
name: string;
dynamicTestList: any;
selectedTestItem: any;
color: string;
showExtraClass = true;
segmentIndex: any = 0
positionOptions: TooltipPosition = 'above';
public isEmojiPickerVisible: boolean;
public addEmoji(event) {
this.textArea = `${this.textArea}${event.emoji.native}`;
this.isEmojiPickerVisible = false;
}
constructor(public dialog: MatDialog) {}
addSegment() {
const dialogRef = this.dialog.open(AddSegmentComponent, {
width: '450px',
data: {
name: this.name,
icon: this.icon,
description: this.description
}
});
dialogRef.afterClosed().subscribe(result => {
if (result.name) {
let obj = {
name: result.name,
icon: result.icon,
description: result.description,
tables: [],
}
this.segments.push(obj)
}
});
}
addNewTable(segment, index) {
const dialogRef = this.dialog.open(AddTableComponent, {
width: '450px',
data: {
name: this.name,
icon: this.icon,
color: this.color
}
});
dialogRef.afterClosed().subscribe(result => {
if (result.name) {
let obj = {
name: result.name,
icon: result.icon,
color: result.color,
}
this.segments = this.segments.map((element, i) => {
if (element.name == segment.name && index == i) {
element.tables.push(obj)
}
return element
})
}
})
}
}
<file_sep>/README.md
# TalenticaUi
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 9.1.13.
## Instructions to run locally
1. Download/Clone the repository
2. Go to Talentica-UI folder
3. `npm install` to install npm modules (which will automatically install bower dependencies)
4. Start the server `ng serve`
5. View in browser at `http://localhost:4200`
| 55e0d14540bae8e1223c61bdc5d72f278fc2c36b | [
"Markdown",
"TypeScript"
] | 3 | TypeScript | AkshayReddy57/alore-growth | ea0d23cdb0e65cc6e0019fce4e8b0b6099a382f5 | 5565c29045550badedc1e31360ff0a1eeda50025 |
refs/heads/master | <file_sep>import './App.css';
import React from 'react';
import Task from './components/Task';
import TaskInput from './components/TaskInput';
class App extends React.Component{
constructor() {
super();
this.state= {
tasks: [
{id:0, title:'Create music', done: false },
{id:1, title:'Create video', done: true },
]
}
}
addTask = task => {
this.setState(state => {
let { tasks } =state;
tasks.push ({
id:tasks.length !==0 ? task.length : 0,
title :task,
done:false
})
return tasks;
});
};
doneTask = id =>{
const index= this.state.tasks.map(task=>task.id).indexOf(id);
this.setState(state => {
let { tasks } = state;
tasks[index].done = true;
return tasks;
})
}
deleteTask = id =>{
const index= this.state.tasks.map(task=>task.id).indexOf(id);
this.setState(state => {
let { tasks } = state;
delete tasks[index];
return tasks;
});
};
render (){
const { tasks } = this.state;
const activeTasks = tasks.filter(task => !task.done)
const doneTasks = tasks.filter(task => task.done)
return (
<div className="App">
<div className="Container">
<header>
<h1>ToDo App</h1>
</header>
<div>
<h1 className="top"> Active tasks: {activeTasks.length} </h1>
</div>
{[...activeTasks, ...doneTasks].map(task => (
<div className="active-tasks">
<Task
doneTask={() => this.doneTask(task.id)}
deleteTask={() => this.deleteTask(task.id)}
task={task} key={task.id}></Task>
</div>
))}
<TaskInput addTask = {this.addTask}></TaskInput>
</div>
</div>
);
}
}
export default App;
<file_sep>import React from "react";
const Task = ({task, ...props}) => {
const ActionBtn = () => (
<div>{!task.done
? <p onClick={props.doneTask}>✅</p>
: <p onClick={props.deleteTask}>❌</p>}
</div>
);
return(
<div className = "task">
<p> {task.title} </p>
<ActionBtn></ActionBtn>
</div>
)
}
export default Task; | 905e259f42b007d17e058234d9df7ff496461a89 | [
"JavaScript"
] | 2 | JavaScript | CreatoR750/ToDo-App | 2652982b24c1edc691d4bc2c7fd7e381562c588e | f397a61c809ccd33a42a2e5d2eeadfd250801c50 |
refs/heads/master | <repo_name>MarwanELAdawy/Admin-Panel<file_sep>/app.js
require('dotenv').config();
const express = require('express');
const bodyparser = require('body-parser');
const mongoose = require('mongoose');
const usersRouter = require('./routers/users.router');
const placesRouter = require('./routers/places.router');
const adminRouter = require('./routers/admin.router');
const mongourl = process.env.MONGO_URL || 'mongodb://localhost:27017/test';
const port = process.env.PORT || 3000;
const app = express();
app.use(bodyparser.json());
app.use('/users', usersRouter);
app.use('/users/:userId/places', placesRouter);
app.use('/admin', adminRouter);
app.get('/', (req, res) => res.send('Hello World!'));
const run = async () => {
await mongoose.connect(mongourl, {
useNewUrlParser: true
})
await app.listen(port, () => {
console.log(`app listening on port ${port}!`);
})
}
run()
| 8ff2f02c5f53ebeb01b9914805525189de34430c | [
"JavaScript"
] | 1 | JavaScript | MarwanELAdawy/Admin-Panel | 6ea6797608f1abf50259b2fdb14755d826cbd691 | e5199aefa8df09972f67ded6bc72ecd3db7f8e5e |
refs/heads/master | <file_sep>///
/// @file intrinsics.hpp
/// @brief Wrappers for compiler intrinsics.
///
/// Copyright (C) 2022 <NAME>, <<EMAIL>>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef INTRINSICS_HPP
#define INTRINSICS_HPP
#include <stdint.h>
#include <cassert>
#if !defined(__has_builtin)
#define __has_builtin(x) 0
#endif
#if !defined(__has_include)
#define __has_include(x) 0
#endif
// GCC & Clang
#if defined(__GNUC__) || \
__has_builtin(__builtin_popcountl)
namespace {
inline int popcnt64(uint64_t x)
{
#if __cplusplus >= 201703L
if constexpr(sizeof(int) >= sizeof(uint64_t))
return __builtin_popcount(x);
else if constexpr(sizeof(long) >= sizeof(uint64_t))
return __builtin_popcountl(x);
else if constexpr(sizeof(long long) >= sizeof(uint64_t))
return __builtin_popcountll(x);
#else
return __builtin_popcountll(x);
#endif
}
} // namespace
#elif __cplusplus >= 202002L && \
__has_include(<bit>)
#include <bit>
#define popcnt64(x) std::popcount(x)
#else
namespace {
/// This uses fewer arithmetic operations than any other known
/// implementation on machines with fast multiplication.
/// It uses 12 arithmetic operations, one of which is a multiply.
/// https://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation
///
inline int popcnt64(uint64_t x)
{
uint64_t m1 = 0x5555555555555555ull;
uint64_t m2 = 0x3333333333333333ull;
uint64_t m4 = 0x0F0F0F0F0F0F0F0Full;
uint64_t h01 = 0x0101010101010101ull;
x -= (x >> 1) & m1;
x = (x & m2) + ((x >> 2) & m2);
x = (x + (x >> 4)) & m4;
return (int) ((x * h01) >> 56);
}
} // namespace
#endif
#if (defined(__GNUC__) || \
defined(__clang__)) && \
defined(__x86_64__) && \
(defined(__BMI__) || (defined(_MSC_VER) && defined(__AVX2__)))
#define HAS_CTZ64
#define CTZ64_SUPPORTS_ZERO
namespace {
inline uint64_t ctz64(uint64_t x)
{
// No undefined behavior, tzcnt(0) = 64
__asm__("tzcnt %1, %0" : "=r"(x) : "r"(x));
return x;
}
} // namespace
#elif (defined(__GNUC__) || \
defined(__clang__)) && \
defined(__x86_64__) && \
!defined(__BMI__)
#define HAS_CTZ64
#define CTZ64_SUPPORTS_ZERO
namespace {
inline uint64_t ctz64(uint64_t x)
{
// REP BSF uses the TZCNT instruction on x64 CPUs with the BMI1
// instruction set (>= 2013) and the BSF instruction on older x64
// CPUs. BSF(0) is undefined behavior, it leaves the destination
// register unmodified. Fortunately, it is possible to avoid this
// undefined behavior by always setting the destination register
// to the same value before executing BSF(0). This works on all
// AMD & Intel CPUs since the i586 (from 1993), the Linux kernel
// also relies on this behavior, see this Linux commit:
// https://github.com/torvalds/linux/commit/ca3d30cc02f780f68771087040ce935add6ba2b7
//
// The constraint "0" for input operand 1 says that it must occupy
// the same location as output operand 0. Hence the assembly below
// uses the same input & output register. This ensures that
// BSF(0) = 0, hence there is no undefined behavior. However, you
// cannot rely on ctz64(0) = 0 since TZCNT(0) = 64.
__asm__("rep bsf %1, %0" : "=r"(x) : "0"(x));
assert(x <= 64);
return x;
}
} // namespace
#elif defined(_MSC_VER) && \
defined(_M_X64) && \
defined(__AVX2__) && \
__has_include(<immintrin.h>)
#define HAS_CTZ64
#define CTZ64_SUPPORTS_ZERO
// No undefined behavior, _tzcnt_u64(0) = 64
#define ctz64(x) _tzcnt_u64(x)
#elif (defined(__GNUC__) || \
defined(__clang__)) && \
defined(__aarch64__)
#define HAS_CTZ64
#define CTZ64_SUPPORTS_ZERO
namespace {
inline uint64_t ctz64(uint64_t x)
{
// No undefined behavior, clz(0) = 64.
// ARM64 has no CTZ instruction, we have to emulate it.
__asm__("rbit %0, %1 \n\t"
"clz %0, %0 \n\t"
: "=r" (x)
: "r" (x));
return x;
}
} // namespace
// In 2022 std::countr_zero() causes performance issues in many
// cases, especially on x64 CPUs. Therefore we try to use alternative
// compiler intrinsics or inline assembly whenever possible.
#elif __cplusplus >= 202002L && \
__has_include(<bit>) && \
!(defined(_MSC_VER) && defined(_M_X64))
#include <bit>
#define HAS_CTZ64
#define CTZ64_SUPPORTS_ZERO
// No undefined behavior, std::countr_zero(0) = 64
#define ctz64(x) std::countr_zero(x)
#elif defined(__GNUC__) || \
__has_builtin(__builtin_ctzl)
#define HAS_CTZ64
namespace {
inline int ctz64(uint64_t x)
{
// __builtin_ctz(0) is undefined behavior,
// we don't define CTZ64_SUPPORTS_ZERO.
assert(x != 0);
#if __cplusplus >= 201703L
if constexpr(sizeof(int) >= sizeof(uint64_t))
return __builtin_ctz(x);
else if constexpr(sizeof(long) >= sizeof(uint64_t))
return __builtin_ctzl(x);
else if constexpr(sizeof(long long) >= sizeof(uint64_t))
return __builtin_ctzll(x);
#else
return __builtin_ctzll(x);
#endif
}
} // namespace
#endif
#endif // INTRINSICS_HPP
<file_sep>///
/// @file resizeUninitialized.hpp
/// @brief std::vector.resize() default initializes memory.
/// This is a workaround to avoid default initialization
/// in order to avoid unnecessary overhead.
///
/// Copyright (C) 2022 <NAME>, <<EMAIL>>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef RESIZEUNINITIALIZED_HPP
#define RESIZEUNINITIALIZED_HPP
#include <stdint.h>
#include <cstddef>
#include <vector>
namespace {
void resizeUninitialized(std::vector<uint64_t>& vect,
std::size_t size)
{
struct NoInitType
{
NoInitType() { };
uint64_t val;
};
using noInitVector = std::vector<NoInitType>;
auto noInitVect = (noInitVector*) &vect;
noInitVect->resize(size);
}
} // namespace
#endif
<file_sep>///
/// @file resizeUninitialized.cpp
/// @brief Test resizeUninitialized() which resizes a std::vector
/// without default initialization.
///
/// Copyright (C) 2022 <NAME>, <<EMAIL>>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primesieve/resizeUninitialized.hpp>
#include <stdint.h>
#include <iostream>
#include <vector>
#include <cstdlib>
void check(bool OK)
{
std::cout << " " << (OK ? "OK" : "ERROR") << "\n";
if (!OK)
std::exit(1);
}
int main()
{
std::size_t size = 100000;
uint64_t val = (1ull << 60) - 3;
{
std::vector<uint64_t> vect;
vect.resize(size, val);
// After resizeUninitialized() the old vector
// content must still be the same.
vect.clear();
resizeUninitialized(vect, size);
std::cout << "vect.size() = " << vect.size();
check(vect.size() == size);
std::cout << "vect.capacity() = " << vect.capacity();
check(vect.capacity() == size);
for (std::size_t i = 0; i < size; i += 37)
{
std::cout << "vect[" << i << "] = " << vect[i];
check(vect[i] == val);
}
// After resizeUninitialized() to a smaller size
// there must be no reallocation. The capacity
// must still be the same as before.
std::size_t newSize = size / 67;
resizeUninitialized(vect, newSize);
std::cout << "vect.size() = " << vect.size();
check(vect.size() == newSize);
std::cout << "vect.capacity() = " << vect.capacity();
check(vect.capacity() == size);
for (std::size_t i = 0; i < newSize; i += 37)
{
std::cout << "vect[" << i << "] = " << vect[i];
check(vect[i] == val);
}
// Test that reallocation works correctly.
// First print the current vector address.
uintptr_t address1 = (uintptr_t) vect.data();
std::cout << "1st vector allocation: " << address1 << std::endl;
// There must be no reallocation here.
vect.clear();
resizeUninitialized(vect, size);
uintptr_t address2 = (uintptr_t) vect.data();
std::cout << "1st vector allocation: " << address2 << std::endl;
if (address1 != address2)
{
std::cout << "address2 = " << address2;
check(address2 == address1);
std::exit(1);
}
// This causes a reallocation, the old vector
// content must be copied into the new vector.
resizeUninitialized(vect, size * 50);
uintptr_t address3 = (uintptr_t) vect.data();
std::cout << "2nd vector allocation: " << address3 << std::endl;
std::cout << "vect.size() = " << vect.size();
check(vect.size() == size * 50);
std::cout << "vect.capacity() = " << vect.capacity();
check(vect.capacity() == size * 50);
for (std::size_t i = 0; i < size; i++)
{
if (vect[i] != val)
{
std::cout << "vect[" << i << "] = " << vect[i];
check(vect[i] == val);
std::exit(1);
}
}
}
std::cout << std::endl;
std::cout << "All tests passed successfully!" << std::endl;
return 0;
}
| d77a1992cd589b905eb8a1e803940d48d622d486 | [
"C++"
] | 3 | C++ | Tiza59/primesieve | 79798932ce53062f050067355e71db917e1894af | 238d05783eb1a7b37ec13ef394c7d0e36060489c |
refs/heads/master | <file_sep>/*
* native requires.
*/
var express = require('express');
var http = require('http');
/*
* package.json requires.
*/
/*
* local requires.
*/
var routes = require('./routes/index');
var app = module.exports = express();
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('SECRET'));
app.use(express.session());
app.use(require('stylus').middleware({ src: __dirname + '/public' }));
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function() {
app.use(express.errorHandler());
});
app.get('/announce', routes.announce);
app.get('/scrape', routes.scrape);
app.get('/', routes.index);
http.createServer(app).listen(6969);
console.log('Tracker online listening on port: 6969');<file_sep>Node-Tracker
============
Moved to: https://github.com/Dokifansubs/anidex_tracker<file_sep>// Native requires
// package.json requires
var bencode = require('bencode');
var _ = require('lodash');
// Local requires
var common = require('./../tools/common');
var Database = require('./../tracker/database');
var Peer = require('./../tools/peer');
var Response = require('./../tools/response');
var database = new Database();
exports.index = function(req, res) {
res.render('index', {title: 'AniDex Tracker', torrents: [], peers: []});
};
exports.announce = function(req, res) {
var info_hash = common.descramble(req.param('info_hash'));
var peer_id = common.descramble(req.param('peer_id'));
var ip = req.param('ip') || req.connection.remoteAddress;
var port = parseInt(req.param('port'));
var compact = parseInt(req.param('compact')) || 1;
var no_peer_id = parseInt(req.param('no_peer_id')) || 0;
var numwant = parseInt(req.param('numwant')) || 50;
var uploaded = req.param('uploaded') || 0;
var downloaded = req.param('downloaded') || 0;
var left = req.param('left');
res.header('Content-Type', 'text/plain');
if (info_hash === '') {
res.end(common.bencodeFailure(101, 'info_hash is required'), 'binary');
return;
}
if (peer_id === '') {
res.end(common.bencodeFailure(102, 'peer_id is required'), 'binary');
return;
}
if (port === NaN) {
res.end(common.bencodeFailure(103, 'port is required'), 'binary');
return;
}
if (info_hash.length != 40) {
console.log(info_hash);
res.end(common.bencodeFailure(150, 'info_hash is not the correct lenght'), 'binary');
return;
}
if (peer_id.length != 40) {
console.log(peer_id);
res.end(common.bencodeFailure(151, 'peer_id is not the correct length'), 'binary');
return;
}
if (numwant > 200) {
numwant = 200;
}
var peer = new Peer(peer_id, info_hash, numwant, compact, ip, port, uploaded, downloaded, left);
switch (req.param('event')) {
case 'completed':
// Peer is now a seeder.
console.log('Leecher: ' + peer.peer_id + ' completed download of: ' + peer.info_hash);
database.completePeer(peer, function(err, response) {
if (err) {
throw err;
} else {
res.end(response, 'binary');
}
});
break;
case 'stopped':
// No longer seeding or leeching.
if (peer._left == 0) {
console.log('Peer: ' + peer.peer_id + ' left swarm as seeder for torrent: ' + peer.info_hash);
} else {
console.log('Peer: ' + peer.peer_id + ' left swarm as leecher for torrent: ' + peer.info_hash);
}
database.removePeer(peer, function(err, response) {
if (err) {
throw err;
} else {
res.end(response, 'binary');
}
});
break;
case 'started':
// New seeder or leecher entered swarm.
if (peer._left == 0) {
console.log('Peer: ' + peer.peer_id + ' entered swarm as seeder for torrent: ' + peer.info_hash);
} else {
console.log('Peer: ' + peer.peer_id + ' entered swarm as leecher for torrent: ' + peer.info_hash);
}
console.log('Peer information: ');
console.log(peer);
database.addPeer(peer, function(err, response) {
if (err) {
throw err;
} else {
res.end(response, 'binary');
}
});
break;
default:
// Update event.
console.log('Peer: ' + peer.peer_id + ' update event for: ' + peer.info_hash);
database.updatePeer(peer, function(err, response) {
if (err) {
throw err;
} else {
console.log(bencode.decode(response));
res.end(response, 'binary');
}
});
break;
}
};
exports.scrape = function(req, res) {
var info_hash = {};
if (Array.isArray(req.param('info_hash'))) {
info_hash = _.map(req.param('info_hash'), function(item) {
return common.descramble(item);
});
} else {
info_hash = common.descramble(req.param('info_hash'));
}
res.header('Content-Type', 'text/plain');
database.scrape(info_hash, function(err, response) {
if (err) {
throw err;
} else {
res.end(response.bencodeScrape(), 'binary');
}
});
};<file_sep>// Native requires.
var fs = require('fs');
// package.json requires.
var mysql = require('mysql');
var _ = require('lodash');
// Local requires.
var Response = require('./../tools/response');
var common = require('./../tools/common');
var mysqlconf = require('./../conf/mysql.json');
// Removes peers from database whose last update is more than 1 hour.
Database.prototype.flushPeers = function() {
console.log('Flushing peers');
// Delete all peers whose last update is more than 1 hour ago.
this.connection.query('SELECT `id`, `peer_id`, `info_hash`, `left` '
+ 'FROM `nodetracker`.`peers` '
+ 'WHERE `last_update` < DATE_SUB(NOW(), INTERVAL 1 HOUR)'
, function(err, rows, fields) {
rows.forEach(function(item) {
var field = '';
// If peer had 0 bytes left to download, it was a seeder.
if (item.left == 0) {
field = '`complete`' ;
} else {
field = '`incomplete`';
}
this.connection.query('UPDATE `nodetracker`.`torrent` '
+ 'SET ' + field + ' = ' + field + ' - 1 '
+ 'WHERE `info_hash` = ' + this.connection.escape(item.info_hash) + ' '
+ 'AND ' + field + ' > 0'
, function(err, result) {
console.log('Decremented ' + field + ' on ' + item.info_hash);
});
this.connection.query('DELETE FROM `nodetracker`.`peers` '
+ 'WHERE `id` = ' + this.connection.escape(item.id)
, function(err, result) {
console.log('Removed peer ' + item.peer_id + ' for torrent: ' + item.info_hash);
});
}.bind(this));
}.bind(this));
};
Database.prototype.checkTorrent = function(peer, callback) {
this.connection.query('SELECT * FROM `nodetracker`.`torrent` '
+ 'WHERE `info_hash` = ' + this.connection.escape(peer.info_hash)
, function(err, rows, fields) {
if (err) {
callback(err);
} else if (rows.length == 0) {
callback(new Error('Torrent not found'));
} else {
callback(undefined);
}
}.bind(this));
};
// Adds peer to database or returns error if the torrent is not tracked.
// NOTE: failure codes are optional, but included anyway. Can be removed
// for bandwidth saving.
Database.prototype.addPeer = function(peer, callback) {
this.checkTorrent(peer, function(err) {
if (err) {
callback(undefined, common.bencodeFailure(200, 'Torrent not in database.'));
} else {
this.transaction(peer, callback);
}
}.bind(this));
};
// Transaction to add a peer.
Database.prototype.transaction = function(peer, callback) {
this.connection.beginTransaction(function(err) {
this.connection.query('REPLACE '
+ 'INTO `nodetracker`.`peers` (`id`, `peer_id`, `info_hash`, `ip`, `port`, `uploaded`, `downloaded`, `left`) '
+ 'VALUES (' + peer.toAddPeerString() + ')'
, function(err, result) {
if (err) {
this.connection.rollback(function() {
callback(err, undefined);
});
} else {
// TODO: lol fix that it doesn't update every cycle.
var field = '';
if (peer._left == 0) {
field = '`complete`';
} else {
field = '`incomplete`';
}
this.connection.query('UPDATE `nodetracker`.`torrent` '
+ 'SET ' + field + ' = ' + field + ' + 1 '
+ 'WHERE `info_hash` = ' + this.connection.escape(peer.info_hash)
, function(err, result) {
if (err) {
this.connection.rollback(function() {
callback(err, undefined);
});
} else {
this.connection.commit(function(err) {
if (err) {
this.connection.rollback(function() {
callback(err, undefined);
})
} else {
this.getPeers(peer, callback);
}
}.bind(this));
}
}.bind(this));
}
}.bind(this));
}.bind(this));
};
// Removes peer from database.
Database.prototype.removePeer = function(peer, callback) {
this.connection.query('SELECT `id`, `peer_id`, `info_hash`, `left` '
+ 'FROM `nodetracker`.`peers` '
+ 'WHERE `id` = ' + this.connection.escape(peer.peer_id + peer.info_hash)
, function(err, rows, fields) {
if (err) {
callback(err, undefined);
} else {
// TODO: Convert this to a function. (Also used by flushPeers)
rows.forEach(function(item) {
var field = '';
if (item.left == 0) {
field = '`complete`' ;
} else {
field = '`incomplete`';
}
this.connection.query('UPDATE `nodetracker`.`torrent` '
+ 'SET ' + field + ' = ' + field + ' - 1 '
+ 'WHERE `info_hash` = ' + this.connection.escape(item.info_hash) + ' '
+ 'AND ' + field + ' > 0'
, function(err, result) {
console.log('Decremented ' + field + ' on ' + item.info_hash);
});
this.connection.query('DELETE FROM `nodetracker`.`peers` '
+ 'WHERE `id` = ' + this.connection.escape(item.id)
, function(err, result) {
console.log('Removed peer ' + item.peer_id + ' for torrent: ' + item.info_hash);
});
this.getPeers(peer, callback);
}.bind(this));
}
}.bind(this));
};
// Increments the completed count for torrent.
// TODO: Clients can spam complete count and it will keep increasing,
// should add check to prevent clients with left=0 from sending complete
// (or just add completed boolean)
Database.prototype.completePeer = function(peer, callback) {
this.connection.query('UPDATE `nodetracker`.`torrent` '
+ 'SET `downloaded` = `downloaded` + 1, '
+ '`incomplete` = `incomplete` - 1, '
+ '`complete` = `complete` + 1 '
+ 'WHERE `info_hash` = ' + this.connection.escape(peer.info_hash)
, function(err, result) {
if (err) {
callback(err, undefined);
} else {
this.updatePeer(peer, callback);
}
}.bind(this));
};
// Updates the peer in the database.
// TODO: uTorrent doesn't send "started" when it resumes from paused/stopped state
// only when it restarts. Peer could have been deleted from database when it resumes.
Database.prototype.updatePeer = function(peer, callback) {
this.connection.query('UPDATE `nodetracker`.`peers` '
+ 'SET `uploaded` = ' + this.connection.escape(peer.uploaded) + ', '
+ '`downloaded` = ' + this.connection.escape(peer.downloaded) + ', '
+ '`left` = ' + this.connection.escape(peer._left) + ' '
+ 'WHERE `id` = ' + this.connection.escape(peer.peer_id + peer.info_hash)
, function(err, result) {
if (err) {
callback(err, undefined);
} else {
this.getPeers(peer, callback);
}
}.bind(this));
};
// Returns a randomly ordered set of peers to the client.
// NOTE: Tracker supports compact and non-compact, however non-compact
// requires more bandwidth.
Database.prototype.getPeers = function(peer, callback) {
var colums = '`ip`, `port` ';
if (peer._compact === 0) {
colums = '`peer_id`, ' + colums;
}
// TODO: Maybe create a smarter algorithm?
// Return a certain high download : low download distribution.
this.connection.query('SELECT ' + colums
+ 'FROM `nodetracker`.`peers` '
+ 'WHERE `info_hash` = ' + this.connection.escape(peer.info_hash) + ' '
+ 'AND `peer_id` != ' + this.connection.escape(peer.peer_id) + ' '
+ 'ORDER BY RAND() '
+ 'LIMIT ' + this.connection.escape(peer.numwant)
, function(err, rows, result) {
if (err) {
callback(err, undefined);
return;
}
this.scrape(peer.info_hash, function(err, response) {
if (err) {
callback(err, undefined);
} else {
// Add all peers to response!
rows.forEach(function(item) {
response.addPeer(item);
});
// Return hex IPv4 if client requested compact.
if (peer._compact) {
callback(undefined, response.bencodePeersIPv4Compact());
} else {
callback(undefined, response.bencodePeersIPv4());
}
}
}.bind(this));
}.bind(this));
};
Database.prototype.scrape = function(info_hash, callback) {
if (Array.isArray(info_hash)) {
info_hash = _.map(info_hash, function(item) {
return this.connection.escape(item);
}.bind(this))
info_hash = info_hash.join(',');
} else {
info_hash = this.connection.escape(info_hash);
}
this.connection.query('SELECT `info_hash`, `complete`, `incomplete`, `downloaded` '
+ 'FROM `nodetracker`.`torrent` '
+ 'WHERE `info_hash` IN (' + info_hash + ')'
, function(err, rows, fields) {
if (err) {
callback(err, undefined);
return;
}
var response = new Response();
rows.forEach(function(item) {
response.addScrape(item);
});
callback(undefined, response);
});
};
function Database() {
this.connection = mysql.createConnection(mysqlconf);
this.connection.connect();
// Clear out expired peers.
this.flushPeers();
// Set interval to clear expired peers.
setInterval(this.flushPeers.bind(this), 1000 * 60 * 4);
}
module.exports = Database;<file_sep>var common = require('./../tools/common');
var bencode = require('bencode');
var ip = common.hexEncodeIPv4('127.0.0.1', 57895);
console.log(ip);
console.log(bencode.encode(new Buffer(ip, 'binary'))); | ce8218839735a95d7bba2fd57110f96bba18ef3a | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | Orillion360/Node-Tracker | 79383f725f57ff4f677e38e09bfa1747ce2b1679 | 53695f29ed8a9744c20e982605f8213351473d14 |
refs/heads/master | <repo_name>singhsterabhi/js-intl-kitchen-sink<file_sep>/src/pages/RelativeTimeFormat/index.js
import React from 'react';
import {
Row,
Col,
Card,
PageHeader,
Form,
Select,
Statistic,
Typography,
InputNumber,
} from 'antd';
const { Option } = Select;
const { Title, Text } = Typography;
const RelativeTimeFormat = () => {
return (
<div>
<PageHeader
title="Intl.RelativeTimeFormat"
subTitle="Enables language-sensitive relative time formatting."
/>
<Row gutter={16}>
<Col span={6}>
<p>Days</p>
<InputNumber onChange={() => {}} />
</Col>
<Col span={12}>
<Card bordered={false}>
<Row gutter={16}>
<Col span={24}>
<Statistic title="Result" value="TODO" />
</Col>
</Row>
</Card>
</Col>
<Col span={6}>
<p>Unit</p>
<Select placeholder="Select Unit" onChange={() => {}}>
<Option key="clear" value={undefined}>
undefined (clear)
</Option>
</Select>
</Col>
</Row>
<br />
<Row gutter={16}>
<Col span={16}>
<Card title="Parameters" bordered={false}>
<Form labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}>
<Row gutter={16}>
<Title level={4}>
locales<Text code>Optional</Text>
</Title>
<Col span={12}>
<Form.Item label="locale">
<Select placeholder="Select a locale" onChange={() => {}}>
<Option key="clear" value={undefined}>
undefined (clear)
</Option>
</Select>
</Form.Item>
</Col>
<Col span={12}>
<p>
When requesting a language that may not be supported, such
as Balinese, include a fallback language.
</p>
</Col>
<Col span={24}>
<Title level={4}>
options<Text code>Optional</Text>
</Title>
<Col span={12}>
<Form.Item label="localeMatcher">
<Select
placeholder="Select a localeMatcher"
onChange={() => {}}
>
<Option key="clear" value={undefined}>
undefined (clear)
</Option>
</Select>
</Form.Item>
<Form.Item label="numeric">
<Select
placeholder="Select a numeric"
onChange={() => {}}
>
<Option key="clear" value={undefined}>
undefined (clear)
</Option>
</Select>
</Form.Item>
<Form.Item label="style">
<Select placeholder="Select a style" onChange={() => {}}>
<Option key="clear" value={undefined}>
undefined (clear)
</Option>
</Select>
</Form.Item>
</Col>
</Col>
</Row>
</Form>
</Card>
</Col>
<Col span={8}>
<Card title="Useful Links" bordered={false}></Card>
</Col>
</Row>
</div>
);
};
export default RelativeTimeFormat;
<file_sep>/src/components/Sidebar/index.js
import React from 'react';
import { Layout } from 'antd';
import styles from './styles.module.css';
import MainMenu from '../MainMenu';
import Ads from '../ads';
const { Sider: SiderAntd } = Layout;
const Sidebar = () => {
return (
<SiderAntd className={styles.sider}>
<div className={styles.logo}>
<img
src="http://www.xgeeks.io/assets/xgeeks_logo_white.svg"
alt="logo"
/>
<p>Open Source</p>
</div>
<MainMenu />
<Ads />
</SiderAntd>
);
};
export default Sidebar;
| de4b020719324e5f2df6ee8db582d2c1a9a129ce | [
"JavaScript"
] | 2 | JavaScript | singhsterabhi/js-intl-kitchen-sink | 81f645bed5ab230f5a3921d175a67f7666578bf9 | abd4c2e2de5f786206b4bac6cde7268fb654fce1 |
refs/heads/master | <file_sep>package com.example.rapinderatest;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.beloo.widget.chipslayoutmanager.SpacingItemDecoration;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import static com.pchmn.materialchips.util.ViewUtil.dpToPx;
public class MainActivity extends AppCompatActivity {
public static String TAG = MainActivity.class.getName();
private ProgressDialog pd;
ImageGridAdapter adapter;
ArrayList<ImageList> subListArrayList = new ArrayList<ImageList>();
ImageList subList;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initToolbar();
recyclerView = findViewById(R.id.recycler_view);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(MainActivity.this, 2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new SpacingItemDecoration(10, dpToPx(5)));
// recyclerView.addItemDecoration(new SpacingItemDecoration(2,dpToPx( 3), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setNestedScrollingEnabled(true);
loadimagelist();
}
private void initToolbar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Image");
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.favorites_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.favorites:
Fragment myFragment = new FavoritesFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, myFragment)
.addToBackStack("FavoritesFragment").commit();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void loadimagelist() {
//creating a string request to send request to the url
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://jsonplaceholder.typicode.com/photos",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
progressBar.setVisibility(View.INVISIBLE);
//hiding the progressbar after completion
try {
JSONArray imageArray = new JSONArray(response);
//now looping through all the elements of the json array
for (int i = 0; i < imageArray.length(); i++) {
subList=new ImageList();
//getting the json object of the particular index inside the array
JSONObject imageObject = imageArray.getJSONObject(i);
//creating a image object and giving them the values from json object
ImageList image = new ImageList();
image.setAlbumid(imageObject.getString("albumId"));
image.setId(imageObject.getString("id"));
image.setTitle(imageObject.getString("title"));
image.setThumbnailurl(imageObject.getString("url"));
image.setUrl(imageObject.getString("thumbnailUrl"));
//adding the image to imagelist
subListArrayList.add(image);
adapter = new ImageGridAdapter(MainActivity.this, subListArrayList);
recyclerView.setAdapter(adapter);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progressBar.setVisibility(View.INVISIBLE);
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
//creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//adding the string request to request queue
requestQueue.add(stringRequest);
}
}
<file_sep>package com.example.rapinderatest;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
import java.util.List;
public class ImageInfoAdapter extends RecyclerView.Adapter<ImageInfoAdapter.MyView> {
private Context mContext;
private List<ImageList> subList;
private ArrayList<ImageList> arraylist;
public class MyView extends RecyclerView.ViewHolder {
public ImageView image;
TextView title;
public MyView(View view) {
super(view);
image = (ImageView) view.findViewById(R.id.img);
title=(TextView)view.findViewById(R.id.title);
}
}
public ImageInfoAdapter(Context mContext, ArrayList<ImageList> albumList) {
this.mContext = mContext;
this.subList = albumList;
this.arraylist = new ArrayList<ImageList>();
this.arraylist.addAll(albumList);
}
@Override
public ImageInfoAdapter.MyView onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.image_info, parent, false);
return new ImageInfoAdapter.MyView(itemView);
}
@Override
public void onBindViewHolder(final ImageInfoAdapter.MyView holder, int position) {
final ImageList enq = subList.get(position);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.no);
requestOptions.error(R.drawable.no);
Glide.with(mContext).setDefaultRequestOptions(requestOptions).load(enq.getThumbnailurl()).into(holder.image);
holder.title.setText(enq.getTitle());
}
@Override
public int getItemCount() {
return subList.size();
}
}
<file_sep>package com.example.rapinderatest;
import android.app.ProgressDialog;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.beloo.widget.chipslayoutmanager.SpacingItemDecoration;
import java.util.ArrayList;
import static com.pchmn.materialchips.util.ViewUtil.dpToPx;
/**
* A simple {@link Fragment} subclass.
*/
public class FavoritesFragment extends Fragment {
public static String TAG = FavoritesFragment.class.getName();
private ProgressDialog pd;
ImageInfoAdapter adapter;
ArrayList<ImageList> subListArrayList = new ArrayList<ImageList>();
ImageList subList;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
DatabaseHelper db;
public FavoritesFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root= inflater.inflate(R.layout.fragment_favorites, container, false);
recyclerView =root. findViewById(R.id.recycler_view);
db=new DatabaseHelper(getContext());
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(getContext(), 1);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.addItemDecoration(new SpacingItemDecoration(10, dpToPx(5)));
// recyclerView.addItemDecoration(new SpacingItemDecoration(2,dpToPx( 3), true));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setNestedScrollingEnabled(true);
subListArrayList=db.getAllFavorites();
if (subListArrayList.size()>0) {
adapter = new ImageInfoAdapter(getContext(), subListArrayList);
recyclerView.setAdapter(adapter);
}
return root;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.image_info, menu);
MenuItem item = menu.findItem(R.id.favorites);
item.setVisible(false);
MenuItem addf = menu.findItem(R.id.addfavorites);
addf.setVisible(false);
MenuItem info = menu.findItem(R.id.info);
info.setVisible(false);
MenuItem dowload = menu.findItem(R.id.download);
dowload.setVisible(false);
super.onCreateOptionsMenu(menu, inflater);
}
}
<file_sep>rootProject.name='RapinderaTest'
include ':app'
<file_sep>package com.example.rapinderatest;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "image_db";
public static final String TABLE_NAME = "favorite_images";
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ "fav_img_id" + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "album_id" + " INTEGER,"
+ "id" + " INTEGER,"
+ "title" + " TEXT,"
+ "url" + " TEXT,"
+ "thumbnailurl" + " TEXT"
+ ")";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
// Create tables again
onCreate(db);
}
public long insertFavImage(String albumid,String id,String title,String url,String thumbnailurl) {
// get writable database as we want to write data
String sql="SELECT * FROM "+TABLE_NAME+" WHERE `id`='" +id+"'";
SQLiteDatabase sQLiteDatabase2 = getReadableDatabase();
Cursor cursor = sQLiteDatabase2.rawQuery(sql, null);
cursor.moveToFirst();
Log.d("Cursor Count", String.valueOf(cursor.getCount()));
if (cursor.getCount() == 0) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("album_id", albumid);
values.put("id", id);
values.put("title", title);
values.put("url", url);
values.put("thumbnailurl", thumbnailurl);
// insert row
long id1 = db.insert(TABLE_NAME, null, values);
// close db connection
db.close();
// return newly inserted row id
return id1;
} return 0;
}
public ArrayList<ImageList> getAllFavorites() {
ArrayList<ImageList> favorites = new ArrayList<>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_NAME ;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
ImageList note = new ImageList();
note.setAlbumid(String.valueOf(cursor.getInt(cursor.getColumnIndex("album_id"))));
note.setId(cursor.getString(cursor.getColumnIndex("id")));
note.setTitle(cursor.getString(cursor.getColumnIndex("title")));
note.setUrl(cursor.getString(cursor.getColumnIndex("url")));
note.setThumbnailurl(cursor.getString(cursor.getColumnIndex("thumbnailurl")));
favorites.add(note);
} while (cursor.moveToNext());
}
// close db connection
db.close();
// return favorites list
return favorites;
}
}
| 27fea7fe79ecf91e115f28eb9772c41836690962 | [
"Java",
"Gradle"
] | 5 | Java | supriya9792/RapinderaTest | 31b52b4b3a50e00c4be91327ca9fd1c9851a15f3 | bf29e61465aea111303e75156f59635f81937045 |
refs/heads/main | <repo_name>mhmddzidane/Shopping-list-ReactJS<file_sep>/src/components/info/index.js
import PropTypes from 'prop-types'
import styles from './info.module.css'
const Info = ({todosLength, totalCounts, onDelete}) => {
return(
<div className={styles.info}>
<div className={styles.infoTotal}>
<p>{`Total List: ${todosLength}`}</p>
</div>
<div className={styles.infoTotal}>
<p>{`Total Counts: ${totalCounts}`}</p>
</div>
<button className={styles.deleteAllButton} onClick={onDelete}>
Delete all
</button>
</div>
)
}
Info.propTypes = {
todosLength: PropTypes.number,
totalCounts: PropTypes.func,
onDelete: PropTypes.func
}
export default Info | 7d7f3d2f6cdb89dc578c1c3d4130bca9fd016b9c | [
"JavaScript"
] | 1 | JavaScript | mhmddzidane/Shopping-list-ReactJS | fac3661630e8eda9937828ae6011e9afef4c02f6 | 323244ee5a56b7768a217686d962b93d41d9c92a |
refs/heads/master | <file_sep>package main.mainFrame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* @Author : fancici
* @Date : Create in 2018 03 2018/3/26 6:46
* @Description : 实现版本说功能
* @Paramter :
**/
public class AboutListener extends JDialog implements ActionListener {
protected JPanel secondPanel; // 第二层面板
protected JScrollPane aboutScrollPanel; //存放借阅信息的面板
protected Container container;
public void AboutListener(){
container = this.getContentPane();
secondPanel = new JPanel();
secondPanel.setLayout( new BorderLayout());
JLabel aboutcontent = new JLabel("<html><body>系统版本 1.0<br />由梵陨星负责开发维护,如有任何疑问,请联系" +
"<br />微信 梵陨星</body></html> ",
SwingConstants.CENTER );
container.add( aboutcontent );
setSize(600,450);
this.show(true);
}
public void actionPerformed(ActionEvent e){
this.AboutListener();
}
}
<file_sep># 图书馆管理系统
developing enverionment changes. secondly create repository
- 新增用户注册、登陆、注销模块
- 实现系统数据库连接
<file_sep>package main.mainFrame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
/**
* @Author : fancici
* @Date : Create in 2018 03 2018/3/23 17:05
* @Description : 借书还书--我的借阅 功能实现 能够查阅 当前借阅 和 历史借阅两个记录, 使用的是JRadioButton类;
* 成员变量单独空出来
* @Paramter :
**/
public class MyBookInfoListener extends JFrame implements ActionListener {
protected JPanel secondPanel; // 第二层面板
protected JScrollPane bookLibScrollPanel; //存放借阅信息的面板
//JTable 测试内容。
protected JTable borrowInfoTable; //显示借阅信息的表格
Vector allBorrowInfoVector = new Vector(); //存放所有的行的内容向量
private Container container;
public void MyBookInfoListener() {
//JTable 测试内容,可以删除
Vector rowVector_1 = new Vector(); //存放第一行内容的向量
container = this.getContentPane(); //主窗口
secondPanel = new JPanel();
secondPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
//JTable 测试内容,可以删除
rowVector_1.add("Java程序设计");
rowVector_1.add("耿祥义");
rowVector_1.add("清华大学出版社");
//存在bug 下面一栏会使系统崩溃
//rowVector_1.add("09-09-08");
//rowVector_1.add("09-12-08");
rowVector_1.add("");
rowVector_1.add("0");
rowVector_1.add("0");
allBorrowInfoVector.add(rowVector_1);
rowVector_1 = new Vector();
rowVector_1.add("C++从入门到放弃");
rowVector_1.add("梵陨星");
rowVector_1.add("华南理工大学出版社");
//rowVector_1.add("18-07-08");
//rowVector_1.add("18-10-08");
rowVector_1.add("");
rowVector_1.add("0");
rowVector_1.add("0");
allBorrowInfoVector.add(rowVector_1);
Vector borrowHead = new Vector();
borrowHead.add("书名");
borrowHead.add("作者");
borrowHead.add("出版");
borrowHead.add("借阅日期");
borrowHead.add("应还日期");
borrowHead.add("归还日期");
borrowHead.add("超期天数");
borrowHead.add("罚款金额");
//生成具有内容和表头的表格
borrowInfoTable = new JTable( allBorrowInfoVector, borrowHead ); //以数组数据生成表格
borrowInfoTable.setEnabled(false); //设置表格是不可编辑的,只显示信息
borrowInfoTable.setPreferredScrollableViewportSize( new Dimension(0,20));
bookLibScrollPanel = new JScrollPane();
bookLibScrollPanel.setViewportView(borrowInfoTable); //放到滚动面板上
//设置提醒信息
bookLibScrollPanel.setBorder(BorderFactory.createTitledBorder("借阅信息"));
add(BorderLayout.CENTER,bookLibScrollPanel);
validate();
//设置文本框提示信息
secondPanel.setBorder(BorderFactory.createTitledBorder("借阅查询选项"));
JRadioButton currBorrowButton = new JRadioButton("当前借阅");
JRadioButton historyBorrowButton = new JRadioButton("历史借阅");
secondPanel.add(currBorrowButton);
secondPanel.add(historyBorrowButton);
//注册事件监听程序,对ActionListener做出处理
currBorrowButton.addActionListener(new currBorrowInfoListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("当前借阅需要补充数据");
}
});
historyBorrowButton.addActionListener(new historyBorrowInfoListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("历史借阅需要补充数据");
}
});
ButtonGroup buttonGroup_1 = new ButtonGroup();
buttonGroup_1.add(currBorrowButton);
buttonGroup_1.add(historyBorrowButton);
this.add(BorderLayout.NORTH, secondPanel);
this.setTitle("我的借阅");
this.setSize(600, 450);
this.setVisible(true);
//创建我的查询列表
}
//菜单项窗口
public void actionPerformed(ActionEvent e) {
this.MyBookInfoListener();
}
class currBorrowInfoListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("当前借阅需要补充数据");
}
}
class historyBorrowInfoListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("历史借阅需要补充数据");
}
}
}
<file_sep>package main.mainFrame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
/**
* @Author : fancici
* @Date : Create in 2018 03 2018/3/25 7:48
* @Description : 馆藏检索——图书检索 功能界面
* @Paramter :
**/
public class BookRetrievalListener extends JFrame implements ActionListener {
protected JLabel selectionLabel;
protected JComboBox fieldComboBox;
protected JPanel secondPanel;
protected JButton retrievalButton;
protected JTextField keywordText;
private Container container;
protected String fieldSelected;
public void BookRetrievalListener() {
container = this.getContentPane();
selectionLabel = new JLabel("检索方式");
String[] list ={"11","22","33","44","55"};
fieldComboBox = new JComboBox(list); //分类检索下拉列表
//注册事件监听者FieldSelectedListener为内部类
fieldComboBox.addItemListener(new FieldSelectedListener());
keywordText = new JTextField("java", 20); //显示关键字文本框
retrievalButton = new JButton("检索"); //提交命令按钮
secondPanel = new JPanel();
secondPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
keywordText.setSize(secondPanel.getWidth() / 2, secondPanel.getWidth());
secondPanel.add(selectionLabel);
secondPanel.add(fieldComboBox);
secondPanel.add(keywordText);
secondPanel.add(retrievalButton);
this.add(secondPanel);
// 添加后面的JList显示检索内容
this.setTitle("书目检索");
this.setSize(600, 450);
this.setVisible(true);
}
class FieldSelectedListener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
fieldSelected = (String) fieldComboBox.getSelectedItem();
}
}
}
public void actionPerformed(ActionEvent event) {
BookRetrievalListener bookRetrievalListener = new BookRetrievalListener();
bookRetrievalListener.BookRetrievalListener();
}
}<file_sep>package main.mainFrame;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* @Author : fancici
* @Date : Create in 2018 03 2018/3/25 14:48
* @Description :
* @Paramter :
**/
public class LoginInListener extends JDialog implements ActionListener{
protected JPanel selectionLabel; // 第二层面板
JDialog dialog = new JDialog();
Container container;
public void LoginInListener(){
container = this.getContentPane();
container.setLayout( new GridLayout(2,3));
JPanel selectionLabel = new JPanel();
JLabel readerIdLabel = new JLabel("账号",JLabel.RIGHT);
selectionLabel.add(readerIdLabel);
JTextField readerFieldText = new JTextField(10);
selectionLabel.add(readerFieldText);
selectionLabel.add( new JLabel());
selectionLabel.add( new JLabel("密码",JLabel.RIGHT));
JPasswordField pswdText = new JPasswordField(10);
selectionLabel.add(pswdText);
JButton okButton = new JButton("确定");
//为okbutton注册事件
okButton.addActionListener( new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
new AboutListener().setVisible(true);
}
});
selectionLabel.add(okButton);
this.add(selectionLabel);
this.setTitle("我的借阅");
this.setSize(600, 450);
this.setVisible(true);
}
public void actionPerformed( ActionEvent Event ){
this.LoginInListener();
}
} | b63ba7e68ef2559941b4ef734411446390404864 | [
"Markdown",
"Java"
] | 5 | Java | fanyunxing/libmanagesytm | 583182c305f272b55ff9caa6afddb51067161555 | 43089099dfecc8b09f7de1d185baba57c84a7a92 |
refs/heads/master | <file_sep>CarNew1201
==========
sasdasdasdasdsds<file_sep>source 'https://github.com/CocoaPods/Specs.git'
pod 'JSONKit', '~> 1.5pre'
pod 'AFNetworking', '~> 2.3.1'
pod 'SDWebImage', '~> 3.7.1'
pod 'MMDrawerController', '~> 0.5.6'
pod 'UMeng', '~> 2.2.1'
pod 'UMengFeedback', '~> 1.4.1'
pod 'WeChatSDK', '~> 0.0.1'
pod 'MBProgressHUD', '~> 0.8'
pod 'Reachability', '~> 3.1.1'
pod 'Baidu-Maps-iOS-SDK', '~> 2.6.0'
pod 'RongCloudIMKit', '~> 1.3.3'
| ad16e3e57912765ba21753914869000cec4a2d87 | [
"Markdown",
"Ruby"
] | 2 | Markdown | TeamOfFBAuto/CarNew1201 | a0063a52e95b06e40efea3fb07288e1f7293cd0b | 29e566e2e74efc72cb5c5d554f92512ee630f25a |
refs/heads/master | <file_sep>def game_hash
game_hash = {
home: {
team_name: "<NAME>",
colors: ["Black", "White"],
players: {
player_name: ["<NAME>", "<NAME>", "<NAME>",
"<NAME>", "<NAME>"],
number: [0, 30, 11, 1, 31],
shoe: [16, 14, 17, 19, 15],
points: [22, 12, 17, 26, 19],
rebounds: [12, 12, 19, 12, 2],
assists: [12, 12, 10, 6, 2],
steals: [3, 12, 3, 3, 4],
blocks: [1, 12, 1, 8, 11],
slam_dunks: [1, 7, 15, 5, 1]
}
},
away: {
team_name: "<NAME>",
colors: ["Turquoise", "Purple"],
players: {
player_name: ["<NAME>", "<NAME>",
"<NAME>", "<NAME>", "<NAME>"],
number: [4, 0, 2, 8, 33],
shoe: [18, 16, 14, 15, 15],
points: [10, 12, 24, 33, 6],
rebounds: [1, 4, 12, 3, 12],
assists: [1, 7, 12, 2, 12],
steals: [2, 7, 4, 1, 22],
blocks: [7, 15, 5, 1, 5],
slam_dunks: [2, 10, 5, 0, 12],
}
}
}
end
def num_points_scored(player)
hash = game_hash
if hash[:home][:players][:player_name].include?(player)
hash[:home][:players][:points][(hash[:home][:players][:player_name].index(player))]
elsif hash[:away][:players][:player_name].include?(player)
hash[:away][:players][:points][(hash[:away][:players][:player_name].index(player))]
end
end
def shoe_size(player)
hash = game_hash
if hash[:home][:players][:player_name].include?(player)
hash[:home][:players][:shoe][(hash[:home][:players][:player_name].index(player))]
elsif hash[:away][:players][:player_name].include?(player)
hash[:away][:players][:shoe][(hash[:away][:players][:player_name].index(player))]
end
end
def team_colors(team)
hash = game_hash
if hash[:home][:team_name] == team
hash[:home][:colors].map {|i| i.capitalize}
elsif hash[:away][:team_name] == team
hash[:away][:colors].map {|i| i.capitalize}
end
end
def team_names
teams = [game_hash[:home][:team_name], game_hash[:home][:team_name]]
end
def player_numbers(team)
if game_hash[:home][:team_name] == team
game_hash[:home][:players][:number]
elsif game_hash[:away][:team_name] == team
game_hash[:away][:players][:number]
end
end
def player_stats(player)
stat_hash = {}
idx = 0
if game_hash[:home][:players][:player_name].include?(player)
idx = (game_hash[:home][:players][:player_name].index(player))
stat_hash[:number] = game_hash[:home][:players][:number][idx]
stat_hash[:shoe] = game_hash[:home][:players][:shoe][idx]
stat_hash[:points] = game_hash[:home][:players][:points][idx]
stat_hash[:rebounds] = game_hash[:home][:players][:rebounds][idx]
stat_hash[:assists] = game_hash[:home][:players][:assists][idx]
stat_hash[:steals] = game_hash[:home][:players][:steals][idx]
stat_hash[:blocks] = game_hash[:home][:players][:blocks][idx]
stat_hash[:slam_dunks] = game_hash[:home][:players][:slam_dunks][idx]
elsif game_hash[:away][:players][:player_name].include?(player)
idx = (game_hash[:away][:players][:player_name].index(player))
stat_hash[:number] = game_hash[:away][:players][:number][idx]
stat_hash[:shoe] = game_hash[:away][:players][:shoe][idx]
stat_hash[:points] = game_hash[:away][:players][:points][idx]
stat_hash[:rebounds] = game_hash[:away][:players][:rebounds][idx]
stat_hash[:assists] = game_hash[:away][:players][:assists][idx]
stat_hash[:steals] = game_hash[:away][:players][:steals][idx]
stat_hash[:blocks] = game_hash[:away][:players][:blocks][idx]
stat_hash[:slam_dunks] = game_hash[:away][:players][:slam_dunks][idx]
end
stat_hash
end
def big_shoe_rebounds
home_shoes = game_hash[:home][:players][:shoe]
away_shoes = game_hash[:away][:players][:shoe]
if home_shoes.max > away_shoes.max
game_hash[:home][:players][:rebounds][home_shoes.index(home_shoes.max)]
else
game_hash[:away][:players][:rebounds][away_shoes.index(away_shoes.max)]
end
end
| ff5939ec848db224bf2f660c2f662c7eced80541 | [
"Ruby"
] | 1 | Ruby | Franco84/advanced-hashes-hashketball-web-1116 | d2fb4767f33d23bf3a5f5087ba95d94b1a0fb523 | e18fe7ce7e46346165e877882007c3e33b705eeb |
refs/heads/master | <repo_name>Cheezily/PaperTracker<file_sep>/admin/adminUsers.php
<?php
?>
<div class="mainWrapperWithNav">
Users
</div><file_sep>/static/header.php
<?php
//session_start();
?>
<link rel="stylesheet" href="css/main.css">
<script type='text/javascript' src='bower_components/jquery/dist/jquery.min.js'></script>
<header>
<?php
if (isset($_SESSION['firstname'])) {
echo "<form class='logoutForm' method='post' action='index.php'>";
echo "<input type='submit' class='logoutButton' name='logout' value='Logout' id='logout'>";
echo "</form>";
echo "<span class='greeting'>Hello, ".$_SESSION['firstname']."</span>";
} elseif (isset($_GET['q']) && $_GET['q'] == 'recovery') {
echo "<div class=loginButtons>";
echo "Password Recovery";
echo "</div>";
} else {
echo "<div class='loginButtons'>";
echo "<form method='post' action='index.php' class='headerFrom'>";
echo "<input type='submit' class='loginButton' id='newUser' name='newUserRequest' value='New User'>";
echo "</form>";
echo " or ";
echo "<form method='post' action='index.php' class='headerFrom'>";
echo "<input type='submit' class='loginButton' id='login' name='loginRequest' value='Login'>";
echo "</form>";
echo "</div>";
}
?>
</header>
<file_sep>/model/adminDB.php
<?php
function getAllMessages() {
global $db;
$query = "SELECT * FROM messages ORDER BY whenSent DESC";
$statement = $db->prepare($query);
$statement->execute();
$results = $statement->fetchAll();
return $results;
}
function getAllPapers() {
global $db;
$query = "SELECT * FROM papers";
$statement=$db->prepare($query);
$statement->execute();
$results = $statement->fetchAll();
return $results;
}
function getAllUsers() {
global $db;
$query = "SELECT * FROM users";
$statement=$db->prepare($query);
$statement->execute();
$results = $statement->fetchAll();
return $results;
}
function getRealName($username) {
global $db;
$query = "SELECT first_name, last_name, affiliation FROM users WHERE username=:username";
$statement=$db->prepare($query);
$statement->bindValue('username', $username);
$statement->execute();
$results = $statement->fetch();
return $results;
}
function getAllReviewers() {
global $db;
$query = "SELECT * FROM users WHERE role='reviewer'";
$statement=$db->prepare($query);
$statement->execute();
$results = $statement->fetchAll();
//var_dump($results);
return $results;
}
function assignReviewer($paperID, $reviewer) {
global $db;
$query = "UPDATE papers SET reviewername=:reviewer, status='awaiting_review', whenAssigned=:assigned WHERE paperID=:paperID";
$statement=$db->prepare($query);
$statement->bindValue('reviewer', $reviewer);
$statement->bindValue('paperID', $paperID);
$statement->bindValue('assigned', date("Y-m-d H:i:s"));
return $statement->execute();
}
function addEditorNotes($paperID, $noteText) {
global $db;
$query = "UPDATE papers SET editorNotes=:editorNotes, whenEditorNotes=:whenEditorNotes WHERE paperID=:paperID";
$statement=$db->prepare($query);
$statement->bindValue('editorNotes', $noteText);
$statement->bindValue('whenEditorNotes', date("Y-m-d H:i:s"));
$statement->bindValue('paperID', $paperID);
return $statement->execute();
}
function deleteEditorNotes($paperID) {
//only the editor can delete notes
if ($_SESSION['username'] === 'admin') {
global $db;
$query = "UPDATE papers SET editorNotes=NULL, whenEditorNotes=NULL WHERE paperID=:paperID";
$statement=$db->prepare($query);
$statement->bindValue('paperID', $paperID);
return $statement->execute();
}
}
function deletePaperDB($paperID) {
//only the editor can delete anything
if ($_SESSION['username'] === 'admin') {
global $db;
$query = "SELECT * FROM papers WHERE paperID=:paperID";
$statement = $db->prepare($query);
$statement->bindValue('paperID', $paperID);
$statement->execute();
$paper = $statement->fetch();
if (!empty($paper['draftFilename'])) {
$doc_dir = getcwd().'/uploads/drafts/';
unlink($doc_dir.$paper['draftFilename']);
}
if (!empty($paper['firstReviewFilename'])) {
$doc_dir = getcwd().'/uploads/firstReview/';
unlink($doc_dir.$paper['firstReviewFilename']);
}
if (!empty($paper['revisedFilename'])) {
$doc_dir = getcwd().'/uploads/revisions/';
unlink($doc_dir.$paper['revisedFilename']);
}
if (!empty($paper['finalReviewFilename'])) {
$doc_dir = getcwd().'/uploads/finalReview/';
unlink($doc_dir.$paper['finalReviewFilename']);
}
$query = "DELETE FROM papers WHERE paperID=:paperID";
$statement = $db->prepare($query);
$statement->bindValue('paperID', $paperID);
return $statement->execute();
}
}
function updateStatus($paperID, $status) {
$possibilities = array('awaiting_assignment','awaiting_review',
'awaiting_revisions','revisions_submitted','accepted','rejected');
//only the editor can change the status of a paper
if ($_SESSION['username'] === 'admin' &&
in_array($status, $possibilities)) {
global $db;
$query = 'UPDATE papers SET status=:status, whenEditorInitialDecision=:when WHERE paperID=:paperID';
$statement = $db->prepare($query);
$statement->bindValue('status', $status);
$statement->bindValue('when', date("Y-m-d H:i:s"));
$statement->bindValue('paperID', $paperID);
return $statement->execute();
}
}
?>
<file_sep>/index.php
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
date_default_timezone_set ("America/Chicago");
//CSS transitions are not supported in IE 8 or 9
if(preg_match('/(?i)msie [5-9]/',$_SERVER['HTTP_USER_AGENT'])) {
echo "<h1>Please upgrade to a modern browser like Chrome,".
" Firefox, Edge, or Internet Explorer version 10+</h1>";
die();
}
require_once 'controller/messages.php';
require_once 'controller/login.php';
require_once 'controller/newUser.php';
require_once 'controller/userUploads.php';
//Handle routing if the session is set
if ($_SESSION['role'] == 'author') {
//header("Location: authorDashboard.php");
$role = "author";
}
if ($_SESSION['role'] == 'reviewer') {
//header("Location: reviewerDashboard.php");
$role = "reviewer";
}
if ($_SESSION['role'] == 'admin') {
//header("Location: adminDashboard.php");
$role = "admin";
}
//***********************************
//-------------ROUTING---------------
//***********************************
if (empty($role)) {
include "greeting.php";
}
if ($_SESSION['role'] == 'author') {
include "authorDashboard.php";
}
if ($_SESSION['role'] == 'reviewer') {
include "reviewerDashboard.php";
}
if ($_SESSION['role'] == 'admin') {
include "admin/adminDashboard.php";
}
?><file_sep>/model/messagesDB.php
<?php
require_once 'database.php';
function getMessages($fromUsername) {
global $db;
$query = "SELECT * FROM messages WHERE fromUsername=:fromUsername ORDER BY whenSent DESC";
$statement = $db->prepare($query);
$statement->bindValue(":fromUsername", $fromUsername);
$statement->execute();
$results = $statement->fetchAll();
return $results;
}
function sendMessage($fromUsername, $message, $messageTitle) {
$whenSent = date("Y-m-d H:i:s");
global $db;
$query = "INSERT INTO messages(fromUsername, whenSent, message, title) VALUES (:fromUsername, :whenSent, :message, :title)";
$statement = $db->prepare($query);
$statement->bindValue(":fromUsername", $fromUsername);
$statement->bindValue(":whenSent", $whenSent);
$statement->bindValue(":message", $message);
$statement->bindValue(":title", $messageTitle);
$results = $statement->execute();
if ($results) {
return "Message sent";
} else {
return;
}
}
function replyToMessage($messageID, $reply) {
//echo "id ".$messageID." reply: ".$reply;
$whenReplied = date("Y-m-d H:i:s");
global $db;
$query = "UPDATE messages SET whenReplied=:whenReplied, reply=:reply WHERE messageID=:messageID";
$statement = $db->prepare($query);
$statement->bindValue("whenReplied", $whenReplied);
$statement->bindValue("reply", $reply);
$statement->bindValue("messageID", $messageID);
$result = $statement->execute();
return $result;
}
?><file_sep>/admin/adminSummary.php
<?php
$messageCount = getMessageCounts();
$newMessages = $messageCount[0];
$oldMessages = $messageCount[1];
$papersCount = getPaperCounts();
$newPapers = $papersCount[0];
$oldPapers = $papersCount[1];
$usersCount = getUserCounts();
$newUsers = $usersCount[0];
$oldUsers = $usersCount[1];
?>
<div class="mainWrapperWithNav">
<h2>Messages:</h2>
<h3>New Messages to You Since Last Login: <?php echo $newMessages; ?></h3>
<p>(Total messages to the Editor: <?php echo $newMessages + $oldMessages; ?>)</p>
<br><br>
<h2>Papers:</h2>
<h3>New Papers Submitted Since Last Login: <?php echo $newPapers; ?></h3>
<p>(Total papers submitted: <?php echo $newPapers + $oldPapers; ?>)</p>
<br><br>
<h2>Users:</h2>
<h3>New Registered Users Since Last Login: <?php echo $newUsers; ?></h3>
<p>(Total users registered: <?php echo $newUsers + $oldUsers; ?>)</p>
<br>
</div><file_sep>/admin/adminDashboard.php
<?php
include 'static/header.php';
include 'controller/adminFunctions.php';
include 'adminNavigation.php';
include $adminPage;
?>
<file_sep>/model/papersDB.php
<?php
require_once 'database.php';
function getPaperInfo($paperID) {
global $db;
$query = "SELECT * FROM papers WHERE paperID=:paperID";
$statement=$db->prepare($query);
$statement->bindValue('paperID', $paperID);
$statement->execute();
$results = $statement->fetch();
return $results;
}
//AUTHOR FUNCTIONS
function checkPapers($username) {
global $db;
$query = 'SELECT * FROM papers WHERE username=:username ORDER BY whenSubmitted DESC';
$statement = $db->prepare($query);
$statement->bindValue(":username", $username);
$statement->execute();
$results = $statement->fetchAll();
if ($results) {
return $results;
} else {
return FALSE;
}
}
function uploadDraft($username, $filename, $title) {
global $db;
$query = 'INSERT INTO papers (username, draftFilename, whenSubmitted, title, recentlyUpdated) '
. 'VALUES (:username, :filename, :whenSubmitted, :title, :recentlyUpdated)';
$statement = $db->prepare($query);
$statement->bindValue(":username", $username);
$statement->bindValue(":whenSubmitted", date("Y-m-d H:i:s"));
$statement->bindValue(":filename", $filename);
$statement->bindValue(":title", $title);
$statement->bindValue(":recentlyUpdated", "1");
$statement->execute();
}
function checkForRevision($paperID) {
global $db;
$query = 'SELECT * FROM papers WHERE paperID=:paperID';
$statement = $db->prepare($query);
$statement->bindValue(":paperID", $paperID);
$statement->execute();
$results = $statement->fetch();
return $results['revisedFilename'];
}
function uploadRevision($paperID, $filename) {
global $db;
echo "info: ".$paperID. " ". $filename;
$query = 'UPDATE papers SET revisedFilename=:filename, whenRevised=:whenRevised, status=:status WHERE paperID=:paperID';
$statement = $db->prepare($query);
$statement->bindValue(":filename", $filename);
$statement->bindValue(":status", "revisions_submitted");
$statement->bindValue(":whenRevised", date("Y-m-d H:i:s"));
$statement->bindValue(":paperID", $paperID);
$statement->execute();
}
////////////////////
//REVIEWER FUNCTIONS
////////////////////
function checkPapersForReviewer($reviewername) {
//echo $reviewername;
global $db;
$query = 'SELECT * FROM papers WHERE reviewername=:reviewername ORDER BY whenSubmitted DESC';
$statement = $db->prepare($query);
$statement->bindValue(":reviewername", $reviewername);
$statement->execute();
$results = $statement->fetchAll();
//var_dump($results);
if ($results) {
return $results;
} else {
return FALSE;
}
}
function checkForFirstReview($paperID) {
global $db;
$query = 'SELECT * FROM papers WHERE paperID=:paperID';
$statement = $db->prepare($query);
$statement->bindValue(":paperID", $paperID);
$statement->execute();
$results = $statement->fetch();
return $results['firstReviewFilename'];
}
function checkForFinalReview($paperID) {
global $db;
$query = 'SELECT * FROM papers WHERE paperID=:paperID';
$statement = $db->prepare($query);
$statement->bindValue(":paperID", $paperID);
$statement->execute();
$results = $statement->fetch();
return $results['finalReviewFilename'];
}
function uploadFirstReview($paperID, $filename, $recommendation) {
global $db;
$query = 'UPDATE papers SET firstReviewFilename=:filename, whenFirstReply=:whenFirstReply,'
. ' firstRecommendation=:recommendation, recentlyUpdated="1" WHERE paperID=:paperID';
$statement = $db->prepare($query);
$statement->bindValue(":filename", $filename);
$statement->bindValue(":recommendation", $recommendation);
$statement->bindValue(":whenFirstReply", date("Y-m-d H:i:s"));
$statement->bindValue(":paperID", $paperID);
$statement->execute();
}
function uploadFinalReview($paperID, $filename, $recommendation) {
global $db;
$query = 'UPDATE papers SET finalReviewFilename=:filename, whenFinalReply=:whenFinalReply,'
. ' recommendation=:recommendation, recentlyUpdated="1" WHERE paperID=:paperID';
$statement = $db->prepare($query);
$statement->bindValue(":filename", $filename);
$statement->bindValue(":recommendation", $recommendation);
$statement->bindValue(":whenFinalReply", date("Y-m-d H:i:s"));
$statement->bindValue(":paperID", $paperID);
$statement->execute();
}
?><file_sep>/registration.php
<?php
require_once 'model/usersDB.php';
//this should be refactored at some point to not have to feed
//index.php any get parameters. That will require a seperate
//registrationSuccess.php or something else to forward to upon success
$role = trim(filter_input(INPUT_POST, 'role', FILTER_SANITIZE_STRIPPED));
$firstName = trim(filter_input(INPUT_POST, 'firstName', FILTER_SANITIZE_STRIPPED));
$lastName = trim(filter_input(INPUT_POST, 'lastName', FILTER_SANITIZE_STRIPPED));
$affiliation = trim(filter_input(INPUT_POST, 'affiliation', FILTER_SANITIZE_STRIPPED));
$email = trim(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL));
$username = trim(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRIPPED));
$password = trim(filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRIPPED));
$passwordConfirm = trim(filter_input(INPUT_POST, 'passwordConfirm', FILTER_SANITIZE_STRIPPED));
//Get the role and store it as $r for GET params back to index.php if needed
if ($role == 'Author') {
$r = 'a';
} elseif ($role == 'Reviewer') {
$r = 'r';
} else {
$r='ERROR. Refresh page';
}
//Check to see if any of the fields are blank or if the passwords are too short
$errorList = '';
$errorTrigger = FALSE;
if (!$firstName) {
$errorList .= "&f=true";
$errorTrigger = TRUE;
} else {
$errorList .= "&firstname=".ucfirst($firstName);
}
if (!$lastName) {
$errorList .= "&l=true";
$errorTrigger = TRUE;
} else {
$errorList .= "&lastname=".ucfirst($lastName);
}
if (!$affiliation) {
$errorList .= "&a=true";
$errorTrigger = TRUE;
} else {
$errorList .= "&affiliation=".$affiliation;
}
if (strlen($_POST['email']) == 0) {
$errorList .= "&e=true";
$errorTrigger = TRUE;
} elseif (strlen($_POST['email']) > 0 && $email == FALSE) {
//check to see if there was an email submitted and that it's invalid
$errorList .= "&ei=true";
} else {
$errorList .= "&email=".$email;
}
if (!$username) {
$errorList .= "&u=true";
$errorTrigger = TRUE;
} else {
$errorList .= "&username=".$username;
}
if (!$password) {
$errorList .= "&pw=true";
$errorTrigger = TRUE;
}
if (!$passwordConfirm && $password && strlen($password) >= 8) {
$errorList .= "&pw2=true";
$errorTrigger = TRUE;
}
//Check to see if the password is too short
if ($password && strlen($password) < 8) {
$errorList .= "&pws=true";
$errorTrigger = TRUE;
}
//Check to see if the username is taken. Function in model/registrationDB.php
if (checkUsername($username)) {
header('Location: index.php?err=u'.$errorList.'&r='.$r);
die();
}
if ($errorTrigger) {
header("Location: index.php?err=b".$errorList."&r=".$r);
die();
}
//Check if the passwords submitted match
if ($password != $passwordConfirm) {
header('Location: index.php?err=pwm&r='.$r);
die();
}
//If all of the above checks have passed, we add the user to the database
//and display a success page
$user = array(
'username' => $username,
'firstName' => ucfirst($firstName),
'lastName' => ucfirst($lastName),
'affiliation' => $affiliation,
'email' => $email,
'password' => $<PASSWORD>,
'role' => $role
);
addUser($user);
$loginInfo = login($user['username'], $user['password']);
if (!empty($loginInfo)) {
session_start();
$_SESSION['username'] = $loginInfo[0]['username'];
$_SESSION['firstname'] = $loginInfo[0]['first_name'];
$_SESSION['lastname'] = $loginInfo[0]['last_name'];
$_SESSION['email'] = $loginInfo[0]['email'];
$_SESSION['role'] = $loginInfo[0]['role'];
$_SESSION['userID'] = $loginInfo[0]['userID'];
$_SESSION['username'] = $loginInfo[0]['username'];
$_SESSION['lastLogin'] = $loginInfo[1];
$_SESSION['firstLogin'] = TRUE;
header("Location: index.php");
}
?><file_sep>/reviewerDashboard.php
<?php
session_start();
if (!isset($_SESSION['username'])) {
header("Location: index.php");
}
require_once 'model/papersDB.php';
require_once 'controller/messages.php';
$yourPapers = checkPapersForReviewer($_SESSION['username']);
$hideAlert = FALSE;
if (isset($_POST['getStarted'])) {
$hideAlert = TRUE;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>
Submission Tracker
</title>
<script type='text/javascript' src='bower_components/jquery/dist/jquery.min.js'></script>
</head>
<body>
<?php include 'static/header.php';?>
<?php
if ($_SESSION['firstLogin']) {
?>
<?php if($hideAlert == FALSE) {?>
<div class='newAuthorAlert'>
<?php
} else {
?>
<div class='hideAuthorAlert'>
<?php
}
?>
<h2>Hi there!</h2>
<p>Welcome to your dashboard. As an author, there won't be
much here to look at -- just the status of the papers you've submitted
and a button to submit a new one.</p>
<p>The possible states your paper could be in are:</p>
<ul id='statusListAlert'>
<li>Awaiting Assignment (to a reviewer)</li>
<li>Awaiting Review</li>
<li>Awaiting Revisions (from you)</li>
<li>Rejected</li>
<li>Accepted (you're done!)</li>
</ul>
<br>
<p>Press the button below to get started and submit a paper for review.</p>
<form method='post' action='index.php'>
<input type='submit' name='getStarted' class='getStartedButton' value='Get Started'>
</form>
</div>
<?php
}
?>
<div class='statusList'>
</div>
<?php if ((!isset($newPaperError) && isset($newPaper) &&
(!isset($newPaperCancel) && !isset($newPaperSubmitted)))
|| ($_SESSION['firstLogin'] && !$hideAlert)) {?>
<div class='mainWrapper fadeOut'>
<?php
} elseif (($_SESSION['firstLogin'] && $hideAlert) || isset($newPaperCancel) ||
isset($newPaperSubmitted)) {
$hideAlert = FALSE;
$_SESSION['firstLogin'] = FALSE;
?>
<div class='mainWrapper fadeIn'>
<?php } else { ?>
<div class='mainWrapper'>
<?php } ?>
<h2>Your Review Queue:</h2>
<div class='paperList'>
<?php
//from papersDB.php
if (!empty($yourPapers)) {
//var_dump($yourPapers);
forEach ($yourPapers as $paper) { ?>
<div class='paperWrapper'>
<!--Display the paper title-->
<div class='paperAttribute'>
<?php echo "<span class='attributeLabel'>Title:</span> ".htmlspecialchars($paper['title']); ?>
</div>
<!--Display a link to the draft file submitted by the author-->
<div class='paperAttribute'>
<?php echo "<span class='attributeLabel'>Draft File:</span> ".
"<a target='_blank' href='uploads/drafts/".$paper['draftFilename'].
"'>".htmlspecialchars($paper['draftFilename'])."</a>"; ?>
</div>
<!--Display the box for the reviewer to submit the initial review
or display the comment file the reviewer already submitted-->
<?php if (!$paper['firstRecommendation']) { ?>
<p class='instructions'>Please review the draft file. Select your
recommendation and submit a MS Word file with your comments whenever you're ready</p>
<?php if ($reviewError) {
echo "<span class='miniWarning'>".$reviewError."</span>";
} ?>
<div class='paperAttribute'>
<span class='attributeLabel'>Recommendation:</span>
<form method='post' action='index.php' enctype="multipart/form-data">
<select name='recommendation' required>
<option value='' selected></option>
<option value='accept' >Accept As Is</option>
<option value='minor' >Minor Revisions Needed</option>
<option value='major' >Major Revisions Needed</option>
<option value='reject' >Reject This Paper</option>
</select>
<input type='hidden' name='paperID' value='<?php
echo $paper['paperID']; ?>'>
<input type='file' name='reviewFile' required>
<input type='submit' class='reviewSubmit'
name='firstReviewSubmit' value='Submit'>
</form>
</div>
<?php } ?>
<!--Let the reviewer know what's going on after they upload the
initial review-->
<?php if ($paper['firstReviewFilename']) { ?>
<div class='paperAttribute'>
<?php echo "<span class='attributeLabel'>Initial Feedback File:</span> ".
"<a target='_blank' href='uploads/firstReview/".$paper['firstReviewFilename'].
"'>".htmlspecialchars($paper['firstReviewFilename'])."</a></div>";
$iRecommendation = '';
switch ($paper['firstRecommendation']) {
case "accept":
$initialRecommendation = "Accept As-Is -- made ".
date("M j, Y, g:i a", strtotime($paper['whenFirstReply']));
break;
case "reject":
$initialRecommendation = "Reject Draft -- made ".
date("M j, Y, g:i a", strtotime($paper['whenFirstReply']));
break;
case "minor":
$initialRecommendation = "Minor Revisions Needed -- made ".
date("M j, Y, g:i a", strtotime($paper['whenFirstReply']));
break;
case "major":
$initialRecommendation = "Major Revisions Needed -- made ".
date("M j, Y, g:i a", strtotime($paper['whenFirstReply']));
break;
default:
$initialRecommendation = "Error: No Recommendation Made. Please contact the reviewer.";
}
echo "<div class='paperAttribute'><span class='attributeLabel'>Your Initial Recommendation:</span> ".
$initialRecommendation."</div>";
?>
<?php if ($paper['recentlyUpdated'] == "1" &&
!$paper['finalReviewFilename'] &&
!$paper['revisedFilename']) {
echo "<p class='instructions'>Thanks! Based on your
feedback, if a decision for a revise & resubmit is made by the Editor,
this box will allow you to submit a final review to the Editor
once the revised copy has been submitted by the author. You will be notified by email
when the Editor reviews your recommendation.</p>";
} elseif ($paper['status'] != 'revisions_submitted') {
echo "<p class='instructions'>The Editor is currently"
. " reviewing your recommendation.</p>";
} ?>
<?php } ?>
<!--Display a link to the revised file submitted by the author
if one exists-->
<?php if ($paper['revisedFilename']) { ?>
<div class='paperAttribute'>
<?php echo "<span class='attributeLabel'>Author's Revised File:</span> ".
"<a target='_blank' href='uploads/drafts/".$paper['revisedFilename'].
"'>".htmlspecialchars($paper['revisedFilename'])."</a>"; ?>
</div>
<?php } ?>
<!--Display the box for the reviewer to submit the final review-->
<?php if ($paper['status'] == 'revisions_submitted' &&
!$paper['finalReviewFilename']) { ?>
<p class='instructions'>Please select your final
recommendation and submit a MS Word file with your comments whenever you're ready</p>
<?php if ($reviewError) {
echo "<span class='miniWarning'>".$reviewError."</span>";
} ?>
<div class='paperAttribute'>
<span class='attributeLabel'>Final Recommendation:</span>
<form method='post' action='index.php' enctype="multipart/form-data">
<select name='recommendation' required>
<option value='' selected></option>
<option value='accept' >Accept</option>
<option value='reject' >Reject</option>
</select>
<input type='hidden' name='paperID' value='<?php
echo $paper['paperID']; ?>'>
<input type='file' name='reviewFile' required>
<input type='submit' class='reviewSubmit'
name='finalReviewSubmit' value='Submit'>
</form>
</div>
<?php } ?>
<!--Let the reviewer know what's going on after they upload the
final review-->
<?php if ($paper['finalReviewFilename'] &&
$paper['status'] != 'accepted' &&
$paper['status'] != 'rejected') { ?>
<div class='paperAttribute'>
<?php echo "<span class='attributeLabel'>Final Feedback File:</span> ".
"<a target='_blank' href='uploads/firstReview/".$paper['finalReviewFilename'].
"'>".htmlspecialchars($paper['finalReviewFilename'])."</a>"; ?>
</div>
<?php if ($paper['recentlyUpdated'] == "1") {
echo "<p class='instructions'>Thanks! You will be notified by email
when the Editor makes a final decision on this paper.</p>";
} else {
echo "<p class='instructions'>The Editor is currently "
. "reviewing your recommendation.</p>";
} ?>
<?php }
echo readEditorNote($paper);
?>
</div>
<?php
}
} else { ?>
<h2>You have no papers waiting for your review. The administrator will
assign one shortly or you can message them using the form below.</h2>
<?php } ?>
</div>
<br>
<br>
<?php include "userMessages.php"; ?>
</div>
<script type="text/javascript" src="js/readNotes.js"></script>
</body>
</html>
<file_sep>/controller/login.php
<?php
//Login request flag
if ($_POST['loginRequest'] && !isset($_SESSION['username'])) {
$newLoginRequest = TRUE;
}
//handles logout requests
if ($_POST['logout'] == 'Logout') {
$_SESSION = array();
session_destroy();
//header("Location: index.php");
}
//error handling from the login form on this page
if ($_POST['from_login_form'] && !$_POST['forgot_PW']) {
$name = filter_input(INPUT_POST, 'username');
$userPW = filter_input(INPUT_POST, 'password');
if (!$name && !$userPW) {
$loginError = "Please enter a username and password.";
} elseif ($name && !$userPW) {
$loginError = "Please enter a password.";
} elseif (!$name && $userPW) {
$loginError = "No username entered.";
} else {
//checks to see if the username and password matches.
require_once 'model/usersDB.php';
$result = login($name, $userPW);
if (!empty($result)) {
//var_dump($result);
$_SESSION['username'] = $result[0]['username'];
$_SESSION['firstname'] = $result[0]['first_name'];
$_SESSION['lastname'] = $result[0]['last_name'];
$_SESSION['email'] = $result[0]['email'];
$_SESSION['role'] = $result[0]['role'];
$_SESSION['userID'] = $result[0]['userID'];
$_SESSION['username'] = $result[0]['username'];
$_SESSION['lastLogin'] = $result[0]['last_login'];
$_SESSION['previousLogin'] = $result[1][0];
$_SESSION['firstLogin'] = TRUE;
} else {
$loginError = "Invalid username or password";
}
}
} elseif ($_POST['from_login_form'] && $_POST['forgot_PW']) {
//header("Location: forgotPW.php?q=recovery");
$forgotPW = TRUE;
} else {
$loginError = NULL;
}
?><file_sep>/admin/adminMessages.php
<?php
$messages = getMessageLists();
$needsReply = $messages[0];
$alreadyReplied = $messages[1];
?>
<div class="mainWrapperWithNav">
<h2>Messages Awaiting Reply:</h2>
<div class='adminMessageList'>
<?php
if ($needsReply > 0) {
forEach ($needsReply as $message) { ?>
<div class="adminMessage">
<p class="messageLineHeader">
<?php echo "From: ".$message['fromUsername']." on ".
date("F j, Y, g:i a", strtotime($message['whenSent']))
?>
</p>
<p class="messageLineHeader">
<?php echo "Re: ".$message['title']; ?>
</p>
<p class="messageLine">
<?php echo "Message: ".$message['message']; ?>
</p>
<hr>
<form method='post' action='index.php'>
<input type='hidden' name='messageID' placeholder="Your Reply..."
value=<?php echo $message['messageID']; ?>>
<textarea class='replyText' name='reply'></textarea>
<input class='replySubmit' type='submit' name='replyToMessage' value='Submit'>
</form>
</div>
<?php }
} else {
echo "<p>No messages currently waiting for a reply</p>";
}
?>
</div>
<hr>
<br>
<h2>Messages Already Replied To:</h2>
<div class='adminMessageList'>
<?php
if ($alreadyReplied > 0) {
forEach ($alreadyReplied as $message) { ?>
<div class="adminMessageOld">
<p class="messageLineHeader">
<?php echo "From: ".$message['fromUsername']." on ".
$message['whenSent'];
?>
</p>
<p class="messageLineHeader">
<?php echo "Re: ".$message['title']; ?>
</p>
<p class="messageLine">
<?php echo "Message: ".$message['message']; ?>
</p>
<hr>
<p class="messageLineHeader">
<?php echo "Reply Sent On: ".$message['whenReplied']; ?>
</p>
<p class="messageLine">
<?php echo "Reply: ".$message['reply']; ?>
</p>
</div>
<?php }
} else {
echo "<p>No messages Replied To</p>";
}
?>
</div>
</div>
<file_sep>/controller/messages.php
<?php
require_once 'model/messagesDB.php';
//Message sent alert needs to be cleared on each reload
$messageStatus = NULL;
//Handle when a message is sent
if (isset($_POST['sendMessage'])) {
if ($_SESSION['messageSent'] != $_POST['message']) {
$message = filter_input(INPUT_POST, 'message');
$fromUsername = filter_input(INPUT_POST, 'fromUsername');
$messageTitle = filter_input(INPUT_POST, 'messageTitle');
//this is run through the session var so it doesn't resend the message
//each time the user refreshes the page
$_SESSION['messageSent'] = $message;
$messageStatus = sendMessage($fromUsername, $message, $messageTitle);
}
}
if (isset($_POST['replyToMessage'])) {
require_once 'model/messagesDB.php';
$reply = filter_input(INPUT_POST, 'reply');
$messageID = filter_input(INPUT_POST, 'messageID', FILTER_VALIDATE_INT);
$adminPage = "adminMessages.php";
replyToMessage($messageID, $reply);
}
function getMessageList($fromUsername) {
$messages = getMessages($fromUsername);
$repliedMessages = array();
$noRepliesYet = array();
forEach($messages as $message) {
if (!empty($message['reply'])) {
array_push($repliedMessages, $message);
} else {
array_push($noRepliesYet, $message);
}
}
return array($repliedMessages, $noRepliesYet);
}
function readEditorNote($paper) {
$noteButton = '';
if ($paper['editorNotes']) {
$noteDate = date('M j, Y, g:i a', strtotime($paper['whenEditorNotes']));
$buttonTitle = "Editor Note Submitted on ".$noteDate." -- Click to View";
$noteButton = "<div class='noteButtonWrapper'>".
"<button class='viewNoteButton' paperID=".$paper['paperID'].">".$buttonTitle.
"</button>".
"</div>";
} else {
$noteButton = "<div class='attributeLabel paperAttribute'>There are no notes from the Editor yet for this paper.</div>";
/*$noteButton = "<div class='noteButtonWrapper'>".
"<button class='adminNoteButton adminNoteButton1' paperID=".$paper['paperID'].">".
$buttonTitle.
"</button>".
"</div>";*/
}
$output = $noteButton."<div class='adminPaperNote' id='makeNoteFor".$paper['paperID']."'>".
"<div class='adminNoteHeading'>Note for <b>".$paper['title']."</b> by the Editor".
"</div><hr>".
"<div class='paperNote' id='textFor".$paper['paperID']."'>".
($paper['editorNotes']).
"</div><hr>".
"<button type='button' class='closeNoteButton' paperID=".$paper['paperID'].">Close</button>".
"</div>";
return $output;
}
?><file_sep>/admin/adminNavigation.php
<?php
if (!isset($adminPage)) {
switch ($_POST['adminPage']) {
case "users":
$adminPage = "adminUsers.php";
break;
case "settings":
$adminPage = "adminSettings.php";
break;
case "papers":
$adminPage = "adminPapers.php";
break;
case "messages":
$adminPage = "adminMessages.php";
break;
default:
$adminPage = "adminSummary.php";
}
}
?>
<nav class="adminNav">
<form
<?php if ($adminPage === "adminSummary.php") {
echo " class='activePage' ";
} ?>
method="post" action="index.php">
<input type="hidden" name="adminPage" value="summary">
<input class='navButton' type="submit" value="Summary">
</form>
<form
<?php if ($adminPage === "adminPapers.php") {
echo " class='activePage' ";
} ?>
method="post" action="index.php">
<input type="hidden" name="adminPage" value="papers">
<input class='navButton' type="submit" value="Papers">
</form>
<form
<?php if ($adminPage === "adminUsers.php") {
echo " class='activePage' ";
} ?>
method="post" action="index.php">
<input type="hidden" name="adminPage" value="users">
<input class='navButton' type="submit" value="Users">
</form>
<form
<?php if ($adminPage === "adminMessages.php") {
echo " class='activePage' ";
} ?>
method="post" action="index.php">
<input type="hidden" name="adminPage" value="messages">
<input class='navButton' type="submit" value="Messages">
</form>
<form
<?php if ($adminPage === "adminSettings.php") {
echo " class='activePage' ";
} ?>
method="post" action="index.php">
<input type="hidden" name="adminPage" value="settings">
<input class='navButton' type="submit" value="Settings">
</form>
</nav>
<file_sep>/authorDashboard.php
<?php
session_start();
if (!isset($_SESSION['username'])) {
header("Location: index.php");
}
require_once 'model/papersDB.php';
require_once 'controller/messages.php';
$yourPapers = checkPapers($_SESSION['username']);
$hideAlert = FALSE;
if (isset($_POST['getStarted'])) {
$hideAlert = TRUE;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>
Submission Tracker
</title>
<script type='text/javascript' src='bower_components/jquery/dist/jquery.min.js'></script>
</head>
<body>
<?php include 'static/header.php';?>
<?php
if ($_SESSION['firstLogin']) {
?>
<?php if($hideAlert == FALSE) {?>
<div class='newAuthorAlert'>
<?php
} else {
?>
<div class='hideAuthorAlert'>
<?php
}
?>
<h2>Hi there!</h2>
<p>Welcome to your dashboard. As an author, there won't be
much here to look at -- just the status of the papers you've submitted
and a button to submit a new one.</p>
<p>The possible states your paper could be in are:</p>
<ul id='statusListAlert'>
<li>Awaiting Assignment (to a reviewer)</li>
<li>Awaiting Review</li>
<li>Awaiting Revisions (from you)</li>
<li>Rejected</li>
<li>Accepted (you're done!)</li>
</ul>
<br>
<p>Press the button below to get started and submit a paper for review.</p>
<form method='post' action='index.php'>
<input type='submit' name='getStarted' class='getStartedButton' value='Get Started'>
</form>
</div>
<?php
}
?>
<div class='statusList'>
</div>
<?php if ((!isset($newPaperError) && isset($newPaper) &&
(!isset($newPaperCancel) && !isset($newPaperSubmitted)))
|| ($_SESSION['firstLogin'] && !$hideAlert)) {?>
<div class='mainWrapper fadeOut'>
<?php
} elseif (($_SESSION['firstLogin'] && $hideAlert) || isset($newPaperCancel) ||
isset($newPaperSubmitted)) {
$hideAlert = FALSE;
$_SESSION['firstLogin'] = FALSE;
?>
<div class='mainWrapper fadeIn'>
<?php } elseif (isset($newPaperError) || isset($newPaperSubmitted) || isset($newPaperCancel)) { ?>
<div class='mainWrapper dimmed'>
<?php } else { ?>
<div class='mainWrapper'>
<?php } ?>
<h2>Submission List:</h2>
<div class='paperList'>
<?php if (!empty($yourPapers)) {
forEach ($yourPapers as $paper) { ?>
<?php switch ($paper['status']) {
case "awaiting_assignment":
echo "<div class='paperWrapper awaitingAssignment'>";
break;
case "awaiting_review":
echo "<div class='paperWrapper awaitingReview'>";
break;
case "awaiting_revisions":
echo "<div class='paperWrapper awaitingRevisions'>";
break;
case "revisions_submitted":
echo "<div class='paperWrapper awaitingFinal'>";
break;
case "accepted":
echo "<div class='paperWrapper accepted'>";
break;
case "rejected":
echo "<div class='paperWrapper rejected'>";
break;
default:
echo "<div class='paperWrapper'>";
} ?>
<div class='paperAttribute'>
<?php echo "<span class='attributeLabel'>Title:</span> ".htmlspecialchars($paper['title']); ?>
</div>
<div class='paperAttribute'>
<?php switch ($paper['status']) {
case "awaiting_assignment":
echo "<span class='attributeLabel'>Status:</span> Awaiting Assignment to Reviewer";
break;
case "awaiting_review":
echo "<span class='attributeLabel'>Status:</span> Assigned to Reviewer. Under review";
break;
case "awaiting_revisions":
echo "<span class='attributeLabel'>Status:</span> Initial Review Complete. Awaiting your revisions";
break;
case "revisions_submitted":
echo "<span class='attributeLabel'>Status:</span> Revision submitted. Awaiting final review";
break;
case "accepted":
echo "<span class='attributeLabel'>Status:</span> Complete. Accepted!";
break;
case "rejected":
echo "<span class='attributeLabel'>Status:</span> Rejected";
break;
default:
echo "Status not available. Please contact the administrator";
} ?>
</div>
<div class='paperAttribute'>
<?php echo "<span class='attributeLabel'>Draft Filename:</span> ".
"<a target='_blank' href='uploads/drafts/".$paper['draftFilename'].
"'>".htmlspecialchars($paper['draftFilename'])."</a>"; ?>
</div>
<!--display the link to the revised paper if there is one-->
<?php if ($paper['revisedFilename']) { ?>
<div class='paperAttribute'>
<span class='attributeLabel'>Your Revised Paper:</span>
<?php echo "<a href='".$paper['revisedFilename'].
"'>".$paper['revisedFilename']."</a>"; ?>
</div>
<?php } ?>
<!--display the links to the feedback docs if they're there
and the editor has updated the status-->
<div class='paperAttribute'>
<?php if ($paper['firstReviewFilename'] && !$paper['finalReviewFilename'] &&
$paper['status'] == "awaiting_revisions") {
$firstReviewFilename = htmlspecialchars($paper['firstReviewFilename']);
echo "<span class='attributeLabel'>Initial Reviewer Feedback:</span> ".
"<a target='_blank' href='uploads/firstReview/".$firstReviewFilename.
"'>".$firstReviewFilename."</a>";
} elseif ($paper['finalReviewFilename'] &&
($paper[status] == "accepted" ||
$paper['status'] == "rejected")) {
$finalReviewFilename = htmlspecialchars($paper['finalReviewFilename']);
echo "<span class='attributeLabel'>Final Review:</span> ".
"<a target='_blank' href='uploads/finalReview/".$finalReviewFilename.
"'>".$finalReviewFilename."</a>";
} else {
echo "<span class='attributeLabel'>Initial Reviewer Feedback:</span> N/A";
}
?>
</div>
<!--display option to submit a revised paper if only the
first feedback file exists and the status has been updated
by the editor-->
<?php if ($paper['firstReviewFilename'] &&
!$paper['finalReviewFilename'] &&
!$paper['revisedFilename'] &&
$paper['status'] == "awaiting_revisions") { ?>
<div class='paperAttribute'>
<span class='attributeLabel'>Your Revised Paper:</span>
<form method='post' action='index.php' enctype="multipart/form-data">
<input class='revisionSubmit' type='submit' name='revisionSubmit' value='Submit'>
<input type='file' class='revisionUpload' name='revisionFile' required>
<input type='hidden' name='paperID' value='<?php
echo $paper['paperID']; ?>'>
</form>
</div>
<?php if ($revisionError) {
echo "<div class='paperAttribute'><span class='miniWarning'>".$revisionError."</span></div>";
} ?>
<?php } echo readEditorNote($paper);?>
</div>
<?php
}
} else { ?>
<h2>You have no papers waiting for review. Click the button below
to submit a new document for review.</h2>
<?php } ?>
</div>
<form method='post' action='index.php'>
<button class='submitButton' type='submit' name="newPaper">Submit New Draft</button>
</form>
<br>
<br>
<?php include "userMessages.php"; ?>
</div>
<?php if (isset($newPaper) || isset($newPaperError)) {
include 'newPaper.php';
} ?>
<script type="text/javascript" src="js/readNotes.js"></script>
</body>
</html>
<?php
?><file_sep>/PaperTracker.sql
-- phpMyAdmin SQL Dump
-- version 4.5.2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Sep 26, 2016 at 08:25 PM
-- Server version: 10.1.10-MariaDB
-- PHP Version: 5.6.19
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
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: `PaperTracker`
--
-- --------------------------------------------------------
--
-- Table structure for table `messages`
--
CREATE TABLE `messages` (
`messageID` int(12) NOT NULL,
`fromUsername` varchar(30) NOT NULL,
`toUsername` varchar(30) NOT NULL,
`whenSent` datetime NOT NULL,
`whenReplied` datetime DEFAULT NULL,
`message` text NOT NULL,
`reply` text,
`title` varchar(255) NOT NULL,
`newMessage` tinyint(4) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `messages`
--
INSERT INTO `messages` (`messageID`, `fromUsername`, `toUsername`, `whenSent`, `whenReplied`, `message`, `reply`, `title`, `newMessage`) VALUES
(105, 'admin', 'user', '2016-08-25 10:14:06', NULL, 'message', NULL, 'General Question', 1),
(106, 'user', 'admin', '2016-09-05 11:22:19', NULL, 'This is a test!!!', NULL, 'General Question', 1),
(107, 'user', 'admin', '2016-09-04 11:30:50', NULL, 'What?? Another message????', NULL, 'General Question', 1),
(108, 'user', 'admin', '2016-09-05 12:31:02', NULL, 'New message time!', NULL, 'General Question', 1),
(109, 'user', 'admin', '2016-09-05 12:31:35', '2016-09-09 10:06:32', 'Test message', 'this is the reply', 'General Question', 1);
-- --------------------------------------------------------
--
-- Table structure for table `papers`
--
CREATE TABLE `papers` (
`paperID` int(10) NOT NULL,
`username` varchar(30) NOT NULL,
`reviewername` varchar(30) DEFAULT NULL,
`firstRecommendation` enum('accept','minor','major','reject') DEFAULT NULL,
`finalRecommendation` enum('accept','minor','major','reject') DEFAULT NULL,
`draftFilename` varchar(50) NOT NULL,
`firstReviewFilename` varchar(50) DEFAULT NULL,
`revisedFilename` varchar(50) DEFAULT NULL,
`finalReviewFilename` varchar(50) DEFAULT NULL,
`status` enum('awaiting_assignment','awaiting_review','awaiting_revisions','revisions_submitted','accepted','rejected') NOT NULL DEFAULT 'awaiting_assignment',
`finalDecision` enum('accepted','rejected') DEFAULT NULL,
`whenSubmitted` datetime NOT NULL,
`whenAssigned` datetime DEFAULT NULL,
`whenFirstReply` datetime DEFAULT NULL,
`whenEditorInitialDecision` datetime DEFAULT NULL,
`whenRevised` datetime DEFAULT NULL,
`whenFinalReply` datetime DEFAULT NULL,
`whenCompleted` datetime DEFAULT NULL,
`title` varchar(255) NOT NULL,
`recentlyUpdated` tinyint(1) NOT NULL DEFAULT '0',
`editorNotes` text,
`whenEditorNotes` datetime DEFAULT NULL,
`finalNotes` text,
`whenFinalNotes` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`userID` int(11) NOT NULL,
`username` varchar(30) NOT NULL,
`account_created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`last_login` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`first_name` varchar(40) NOT NULL,
`last_name` varchar(40) NOT NULL,
`affiliation` varchar(255) DEFAULT NULL,
`email` varchar(40) NOT NULL,
`passwordHash` varchar(60) NOT NULL,
`role` enum('author','reviewer','admin') NOT NULL DEFAULT 'author'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`userID`, `username`, `account_created`, `last_login`, `first_name`, `last_name`, `affiliation`, `email`, `passwordHash`, `role`) VALUES
(1, 'admin', '2016-08-19 00:00:00', '2016-09-24 19:23:13', 'Firstname', 'Lastname', NULL, '<EMAIL>', <PASSWORD>', 'admin'),
(3, 'reviewer', '2016-08-20 04:31:38', '2016-09-05 10:52:52', 'firstname', 'lastname', 'Illinois State University', '<EMAIL>', <PASSWORD>', 'reviewer'),
(5, 'user', '2016-08-21 04:34:55', '2016-09-25 11:51:03', 'first', 'last', 'ISU', '<EMAIL>', <PASSWORD>$11$fSL8mjGwt/SSWhJKfFMIwuPOAiIqx4Wo6Hi8mTqyfFoZ2MA3vtD/y', 'author'),
(6, 'newuser', '2016-08-31 01:11:11', '2016-08-30 19:32:22', 'first', 'last', NULL, '<EMAIL>', '$2y$11$tIcWiltjNU5Xi.SUVcN06.DaFytYq7e/LRMhgU3GoMxnfsNKJd9mO', 'author'),
(7, 'reviewer2', '2016-09-21 22:13:40', '2016-09-26 07:13:51', 'Jane', 'Doe', 'USF', '<EMAIL>', '$2y$11$JMhXDihXBRd.zqEgfEz8aOyN3OJgBVx8aG3Zb1wZpz3dq6GRkz7za', 'reviewer');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `messages`
--
ALTER TABLE `messages`
ADD PRIMARY KEY (`messageID`);
--
-- Indexes for table `papers`
--
ALTER TABLE `papers`
ADD PRIMARY KEY (`paperID`),
ADD UNIQUE KEY `filename` (`draftFilename`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`userID`),
ADD UNIQUE KEY `username` (`username`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `messages`
--
ALTER TABLE `messages`
MODIFY `messageID` int(12) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=110;
--
-- AUTO_INCREMENT for table `papers`
--
ALTER TABLE `papers`
MODIFY `paperID` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `userID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
/*!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>/greeting.php
<!DOCTYPE html>
<html>
<head>
<title>
Submission Tracker
</title>
</head>
<body>
<?php include 'static/header.php';?>
<?php if ($loginError || $newUserError || $newUserRequested || $newAuthorRequested || $newReviewerRequested) {
echo "<div class='mainWrapper' style='opacity: .3'>";
} elseif ($newLoginRequest) {echo "<div class='mainWrapper fadeOutMainWrapper'>";
} else {echo "<div class='mainWrapper'>";}?>
<h1>Hi there!</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut
enim ad minim veniam, quis nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.</p>
</div>
<!--The login form will be displayed if there are any /registration
errors or if the form was requested by clicking the login
button in the header-->
<?php if ($loginError || $newUserError || $newLoginRequest) { ?>
<?php if ($newLoginRequest) {echo "<div class='loginForm loginFormAppear' id='loginWindow'>";}
elseif (!$newLoginRequest && ($loginError || $newUserError)) {echo "<div class='loginForm' id='loginWindow'>";} ?>
<div <?php
if ($newUserError) {
echo "style='display: none'";
}
?>>
<form method='post' action='index.php'>
<label for='login_username'>Username
<span class='warning' id='loginWarning'>
<?php echo $loginError; ?>
</span>
</label>
<input type='text' id='login_username' name='username' placeholder='Username'><br>
<label for='login_password'>Password</label>
<input type='<PASSWORD>' id='login_password' name='password'><br><br>
<input type='hidden' name='from_login_form' value='1'>
<input type='submit' id='login_submit' name='submit' value='Log In'>
</form>
<form method='post' action='index.php'>
<input type='hidden' name='from_login_form' value='0'>
<input type='submit' id='loginCancelButton' name='submit' value='Cancel'>
</form>
<form method='post' action='index.php'>
<input type='hidden' name='from_login_form' value='1'>
<input type='hidden' name='forgot_PW' value='1'>
<input type='submit' id='forgotPWbutton' id='login_submit' name='submit'
value='Click here if you forgot your password'>
</form>
</div>
</div>
<?php } ?>
<!--Registration forms. Starts hidden-->
<?php if ($newUserRequested || $newAuthorRequested || $newReviewerRequested) { ?>
<?php if ($newAuthorRequested || $newReviewerRequested) { ?>
<div class="loginForm loginFormDisappear" id="registrationDialog">
<?php } else { ?>
<div class="loginForm loginFormAppear" id="registrationDialog">
<?php } ?>
<p id='roleTitle'>
<?php if ($newUserError) {
echo $newUserErrorRole;
} else {
echo 'Please select your role:';
}
?>
</p>
<div class='roleSelection'>
<form method="post" action='index.php'>
<input type="submit" class='registrationButton' name="newAuthorRegister" value="Author - You'll be submitting papers"><br>
</form>
<form method="post" action='index.php'>
<input type="submit" class='registrationButton' name="newReviewerRegister" value="Reviewer - You'll be reviewing papers"><br>
</form>
<form method='post' action='index.php'>
<input type='hidden' name='from_login_form' value='0'>
<input type='submit' id='roleCancelButton' name='submit' value='Cancel'>
</form>
</div>
</div>
<?php } ?>
<?php if ($newUserError || $newAuthorRequested || $newReviewerRequested) {
if ($newUserError && !$newAuthorRequested && !$newReviewerRequested) {
echo "<div class='loginForm newUserForm'>";
} else {
echo "<div class='loginForm newUserForm newUserFormAppear'>";} ?>
<form class='newUserRegisterForm' method='post' action='registration.php'>
<?php if ($newAuthorRequested || ($errRole === 'Author')) {echo "<h4>New Author Registration:</h4>";}?>
<?php if ($newReviewerRequested || ($errRole === 'Reviewer')) {echo "<h4>New Reviewer Registration:</h4>";}?>
<label for='authorUsername'>Username
<span class='miniWarning'>
<?php if ($nameError) {
echo " ".$newUserError;
}
if ($nameBlank) {
echo "Required";
}
?>
</span>
</label>
<input type='text' id='username' name='username'
<?php
if ($nameFilled && !$nameError) {
echo " value='".$nameFilled."' ";
}
?>
placeholder="Username">
<span class='warning'><?php //echo $taken_username; ?></span>
<label for='firstName'>First Name
<span class='miniWarning'>
<?php if ($firstNameBlank) {
echo "Required";
}
?>
</span>
</label>
<input type='text' id='firstName' name='firstName'
<?php
if ($firstNameFilled) {
echo " value='".$firstNameFilled."' ";
}
?>
placeholder="First Name"><br>
<label for='lastName'>Last Name
<span class='miniWarning'>
<?php if ($lastNameBlank) {
echo "Required";
}
?>
</span>
</label>
<input type='text' id='lastName' name='lastName'
<?php
if ($lastNameFilled) {
echo " value='".$lastNameFilled."' ";
}
?>
placeholder="Last Name"><br>
<label for='affiliation'>Affiliation (university, publication, etc...)
<span class='miniWarning'>
<?php if ($affiliationBlank) {
echo "Required";
}
?>
</span>
</label>
<input type='text' id='affiliation' name='affiliation'
<?php
if ($affiliationFilled) {
echo " value='".$affiliationFilled."' ";
}
?>
placeholder="Affiliation"><br>
<label for='authorEmail'>Email
<span class='miniWarning'>
<?php if ($emailBlank && !$emailInvalid) {
echo "Required";
}
if (!$emailBlank && $emailInvalid) {
echo "Not a valid email format";
}
?>
</span>
</label>
<input type='text' id='email' name='email'
<?php
if ($emailFilled) {
echo " value='".$emailFilled."' ";
}
?>
placeholder="Email"><br>
<label for='password'>Password (min 8 characters)
<span class='miniWarning'>
<?php if ($userPWError) {
echo " ".$newUserError;
}
if ($userPWBlank) {
echo "Required";
}
if ($userPWTooShort) {
echo "Password too short";
}
?>
</span>
</label>
<input type='password' id='password' name='password'><br>
<label for='password2'>Confirm Password
<span class='miniWarning'>
<?php if ($userPWError) {
echo " ".$newUserError;
}
if ($userPW2Blank) {
echo "Please confirm password entered";
}
?>
</span>
</label>
<input type='password' id='password' name='passwordConfirm'><br><br>
<input type='hidden' name='role'
<?php
if ($errRole) {
echo "value=".$errRole;
}
if ($newAuthorRequested) {
echo "value='Author'";
}
if ($newReviewerRequested) {
echo "value='Reviewer'";
}
?>
>
<input id='createAccount' type='submit' value='Create Account'>
</form>
<form method='post' action='index.php'>
<input type='hidden' name='from_login_form' value='0'>
<input class='secondaryButton' type='submit' id='createAccountCancel' name='submit' value='Cancel'>
</form>
</div>
<?php } ?>
</body>
</html><file_sep>/admin/adminPapers.php
<?php
$papers = getAllPapers();
$paperList = getPapersByStatus($papers);
$needsAssignment = $paperList["needsAssignment"];
$awaitingInitialReview = $paperList["awaitingInitialReview"];
$needsPostReviewStatus = $paperList["needsPostReviewStatus"];
$awaitingRevisions = $paperList["awaitingRevisions"];
$awaitingFinalReview = $paperList["awaitingFinalReview"];
$finalReviewDone = $paperList["finalReviewDone"];
$accepted = $paperList["accepted"];
$rejected = $paperList["rejected"];
$recentlyUpdated = $paperList["recentlyUpdated"];
$reviewerOptions = reviewerOptionList();
function paperTitle($paper) {
echo "<div class='paperAttribute'>".
"<span class='attributeLabel'>Paper Title: </span>".htmlspecialchars($paper['title']).
"</div>";
}
function submittedBy($paper) {
$author = getRealName($paper['username']);
echo "<div class='paperAttribute'>".
"<span class='attributeLabel'>Submitted By: </span>".
'<b>'.$author[0].' '.$author[1].'</b> from <b>'.$author[2].'</b> on '.
date("M j, Y, g:i a (e)", strtotime($paper['whenSubmitted'])).
"<br>".
"</div>";
}
function getReviewer($paper) {
$reviewer = getRealName($paper['reviewername']);
echo "<div class='paperAttribute paperAttributeAlt'>".
"<span class='attributeLabel attributeLabelAlt'>Reviewer: </span>".
'<b>'.$reviewer[0].' '.$reviewer[1].'</b> from <b>'.$reviewer[2].
'</b> assigned on '.date("M j, Y, g:i a", strtotime($paper['whenAssigned'])).
"<br>".
"</div>";
}
function reviewerInitialRecommendation($paper) {
$recommendaton = '';
switch ($paper['firstRecommendation']) {
case "accept":
$recommendaton = "Accept As-Is as of ".
date("M j, Y, g:i a", strtotime($paper['whenFirstReply']));
break;
case "reject":
$recommendaton = "Reject Draft as of ".
date("M j, Y, g:i a", strtotime($paper['whenFirstReply']));
break;
case "minor":
$recommendaton = "Minor Revisions Needed as of ".
date("M j, Y, g:i a", strtotime($paper['whenFirstReply']));
break;
case "major":
$recommendaton = "Major Revisions Needed as of ".
date("M j, Y, g:i a", strtotime($paper['whenFirstReply']));
break;
default:
$recommendaton = "Error: No Recommendation Made. Please contact the reviewer.";
}
echo "<div class='paperAttribute paperAttributeAlt'>".
"<span class='attributeLabel attributeLabelAlt'>Reviewer Initial Recommendation: </span>".
$recommendaton."<br>".
"</div>";
}
function getEditorInitialDecision($paper) {
$decision = '';
switch($paper['status']) {
case ("awaiting_revisions" || "revisions_submitted"):
$decision = "Revise & Resubmit";
break;
case "accepted":
$decision = "Complete. Paper Accepted.";
break;
case "rejected":
$decision = "Complete. Paper Rejected";
break;
default:
$decision = "Please update the paper status";
}
echo "<div class='paperAttribute paperAttributeAlt'>".
"<span class='attributeLabel attributeLabelAlt'>Editor Initial Decision: </span>".
"<b>".$decision.".</b> Decision made <b>".
date("M j, Y, g:i a", strtotime($paper['whenEditorInitialDecision'])).
"</b>".
"<br>".
"</div>";
}
function getDraftFilename($paper) {
echo "<div class='paperAttribute'>".
"<span class='attributeLabel'>Draft File: </span>".
"<a target='_blank' href='uploads/drafts/".$paper['draftFilename']."'>".
htmlspecialchars($paper['draftFilename']).
"</a>".
"<br>".
"</div>";
}
function firstReviewFilename($paper) {
echo "<div class='paperAttribute paperAttributeAlt'>".
"<span class='attributeLabel attributeLabelAlt'>Initial Reviewer Notes: </span>".
"<a class='attributeLinkAlt' target='_blank' href='uploads/firstReview/".
$paper['firstReviewFilename']."'>".
htmlspecialchars($paper['firstReviewFilename']).
"</a>".
"<br>".
"</div>";
}
function getRevisedFilename($paper) {
if ($paper['revisedFilename']) {
echo "<div class='paperAttribute paperAttributeAlt'>".
"<span class='attributeLabel attributeLabelAlt'>Author's Revised File: </span>".
"<a class='attributeLinkAlt' target='_blank' href='uploads/revisions/".
$paper['revisedFilename']."'>".
htmlspecialchars($paper['revisedFilename']).
"</a>".
"<span class='attributeLabel attributeLabelAlt'> on </span>".
date("M j, Y, g:i a", strtotime($paper['whenRevised'])).
"</div>";
} else {
echo "<div class='paperAttribute paperAttributeAlt'>".
"<span class='attributeLabel attributeLabelAlt'>Author's Revised File: N/A</span>".
"</div>";
}
}
function finalReviewFilename($paper) {
if ($paper['finalReviewFilename']) {
echo "<div class='paperAttribute paperAttributeAlt'>".
"<span class='attributeLabel attributeLabelAlt'>Final Reviewer Notes: </span>".
"<a class='attributeLinkAlt' target='_blank' href='uploads/firstReview/".
$paper['firstReviewFilename']."'>".
htmlspecialchars($paper['finalReviewFilename']).
"</a>".
"<br>".
"</div>";
} else {
echo "<div class='paperAttribute paperAttributeAlt'>".
"<span class='attributeLabel attributeLabelAlt'>Final Reviewer Notes: N/A</span>".
"</div>";
}
}
function paperNote($paper) {
$noteButton = '';
$authorName = getRealName($paper['username']);
if ($paper['editorNotes']) {
$noteDate = date('M j, Y, g:i a', strtotime($paper['whenEditorNotes']));
$buttonTitle = "Editor Note Submitted on ".$noteDate." -- Click to View/Edit";
$noteButton = "<div class='noteButtonWrapper'>".
"<button class='adminNoteButton' paperID=".$paper['paperID'].">".$buttonTitle.
"</button>".
"</div>";
} else {
$buttonTitle = "Click here to add note to the Author";
$noteButton = "<div class='noteButtonWrapper'>".
"<button class='adminNoteButton adminNoteButton1' paperID=".$paper['paperID'].">".
$buttonTitle.
"</button>".
"</div>";
}
$output = $noteButton."<div class='adminPaperNote' id='makeNoteFor".$paper['paperID']."'>".
"<div class='adminNoteHeading'>Note for <b>".$paper['title']."</b> by ".
'<b>'.$authorName[0].' '.$authorName[1].'</b> at <b>'.$authorName[2].'</b>'.
"</div><hr>".
"<form class='noteForm' method='post' action=''>".
"<input type='hidden' name='paperID' value='".$paper['paperID']."'>".
"<textarea class='paperNote' name='noteText' id='textAreaFor".$paper['paperID']."'>".
"</textarea><hr>".
"<input class='submitNoteButton' type='submit' name='adminNote' value='Submit'>".
"<input class='deleteNoteButton' type='submit' name='deleteNote' value='Delete This Note'>".
"<button type='button' class='cancelNoteButton' paperID=".$paper['paperID'].">Cancel</button>".
"</form>".
"<div id='textFor".$paper['paperID']."' style='display: none;'>".
($paper['editorNotes']).
"</div>".
"</div>";
return $output;
}
function deletePaper($paper) {
$output = "<div class='deletePaperButtonWrapper'>".
"<button class='deletePaperButton' paperID=".$paper['paperID']." id='delete".$paper['paperID']."'>".
"Delete This Paper".
"</button>".
"<form class='deleteConfirm' id='confirm".$paper['paperID']."' method='post' action=''>".
"<input type='hidden' name='paperID' value=".$paper['paperID'].">".
"<input type='submit' name='deletePaper' value='Click to confirm that you really wish to delete this paper!'>".
"</form>".
"</div>";
return $output;
}
?>
<div class="mainWrapperWithNav">
<?php if(empty($papers)) { ?>
<p>There are no papers in the database at the moment.</p>
<?php } else { ?>
<h3 class='explanation'>Papers displayed on this page are grouped by each step in the review process
as different actions need to be performed at each step.</h3>
<div class='paperStatus'>
<h3><span class='paperStep'>Step 1: </span>New Papers Awaiting Reviewer Assignment:
<?php echo count($needsAssignment); ?>
</h3>
<?php if(empty($needsAssignment)) { ?>
<!--<p>There are no papers that need to be assigned at this time.</p>-->
<?php } else { ?>
<hr>
<?php forEach ($needsAssignment as $paper) { ?>
<div class="adminPaper">
<?php echo paperTitle($paper);?>
<?php echo submittedBy($paper);?>
<?php echo getDraftfilename($paper);?>
<div class='paperAttribute paperAttributeAlt'>
<span class='attributeLabel attributeLabelAlt'>Please Assign Reviewer: </span>
<form method="post" action="index.php">
<select name="reviewer">
<?php echo $reviewerOptions;
echo $adminPage;?>
</select>
<input type='hidden' name='paperID' value='<?php echo $paper['paperID'];?>'>
<input type='hidden' name='adminPage' value='papers'>
<input type='submit' class='paperOptionSubmit' name='changeReviewer' value='Assign Reviewer'>
</form>
</div>
<?php echo paperNote($paper); ?>
<?php echo deletePaper($paper); ?>
</div>
<?php }
} //ends needsAssignment loop ?>
</div>
<div class='paperBridge'>⇩</div>
<div class='paperStatus'>
<h3><span class='paperStep'>Step 2: </span>Papers Awaiting Initial Review:
<?php echo count($awaitingInitialReview); ?>
</h3>
<!--The editor needs to add an author note once they make a decision.
Any papers with r&r, accepted, or rejected with no note will still
appear here with a notice-->
<?php if(empty($awaitingInitialReview)) { ?>
<!--<p>There are no papers awaiting initial review at this time.</p>-->
<?php } else { ?>
<hr>
<?php forEach ($awaitingInitialReview as $paper) { ?>
<div class='adminPaper'>
<?php echo paperTitle($paper);?>
<?php echo submittedBy($paper);?>
<?php echo getDraftfilename($paper);?>
<?php echo getReviewer($paper);?>
<div class='paperAttribute paperAttributeAlt'>
<span class='attributeLabel attributeLabelAlt'>Change Reviewer: </span>
<form method="post" action="index.php">
<select name="reviewer">
<?php echo $reviewerOptions;
echo $adminPage;?>
</select>
<input type='hidden' name='paperID' value='<?php echo $paper['paperID'];?>'>
<input type='hidden' name='adminPage' value='papers'>
<input type='submit' name='changeReviewer' value='Assign Reviewer'>
</form>
<br>
</div>
<?php echo paperNote($paper); ?>
<?php echo deletePaper($paper); ?>
</div>
<?php }
} //ends awaitingInitialReview loop ?>
</div>
<div class='paperBridge paperBridge1'>⇩</div>
<div class='paperStatus'>
<h3><span class='paperStep'>Step 3: </span>Papers with Initial Review Completed and Awaiting Your Input:
<?php echo count($needsPostReviewStatus); ?>
</h3>
<?php if(empty($needsPostReviewStatus)) { ?>
<!--<p>There are no papers awaiting an initial decision at this time.</p>-->
<?php } else { ?>
<hr>
<?php forEach ($needsPostReviewStatus as $paper) { ?>
<div class='adminPaper'>
<?php echo paperTitle($paper);?>
<?php echo submittedBy($paper);?>
<?php echo getDraftfilename($paper);?>
<?php echo getReviewer($paper);?>
<?php echo reviewerInitialRecommendation($paper); ?>
<?php echo firstReviewFilename($paper); ?>
<div class='paperAttribute paperAttributeAlt1'>
<span class='attributeLabel attributeLabelAlt1'>Editor's initial Decision: </span>
<form paperID='<?php echo $paper['paperID']; ?>'
class='paperOptionList' method="post" action="index.php">
<select class='paperOptionList' name="editorStatus">
<option value='none'></option>
<option value='awaiting_revisions'>Request Revisions</option>
<option value='accepted'>Accept As-Is</option>
<option value='rejected'>Reject</option>
</select>
<input type='hidden' name='paperID' value='<?php echo $paper['paperID'];?>'>
<input type='hidden' name='adminPage' value='papers'>
<input type='submit' class='paperOptionSubmit' name='changePaperStatus'
value='Submit'>
<span class='attributeLabel attributeLabelAlt1'>
Be sure to add a note to the author first!
</span>
</form>
<br>
</div>
<div id='needsNote<?php echo $paper['paperID']; ?>' class='noteWarning'>
This paper needs a note to the author with your feedback before the status can
be updated! Please click on the link directly below this message to add your
feedback and try again.
</div>
<?php echo paperNote($paper); ?>
<?php echo deletePaper($paper); ?>
</div>
<?php }
} //ends needsPostReviewStatus loop ?>
</div>
<div class='paperBridge paperBridge2'>⇩</div>
<div class='paperStatus'>
<h3><span class='paperStep'>Step 4: </span>Papers Awaiting Revisions form the Author:
<?php echo count($awaitingRevisions); ?>
</h3>
<?php if(empty($awaitingRevisions)) { ?>
<!--<p>There are no papers awaiting revisions at this time.</p>-->
<?php } else { ?>
<hr>
<?php forEach ($awaitingRevisions as $paper) { ?>
<div class='adminPaper'>
<?php echo paperTitle($paper);?>
<?php echo submittedBy($paper);?>
<?php echo getDraftfilename($paper);?>
<?php echo getReviewer($paper);?>
<?php echo reviewerInitialRecommendation($paper); ?>
<?php echo firstReviewFilename($paper); ?>
<?php echo getEditorInitialDecision($paper); ?>
<?php echo paperNote($paper); ?>
<?php echo deletePaper($paper); ?>
</div>
<?php }
} //ends awaitingRevisions loop ?>
</div>
<div class='paperBridge paperBridge3'>⇩</div>
<div class='paperStatus'>
<h3><span class='paperStep'>Step 5: </span>Papers Awaiting Final Review from the Reviewer:
<?php echo count($awaitingFinalReview); ?>
</h3>
<?php if(empty($awaitingFinalReview)) { ?>
<!--<p>There are no papers awaiting final review at this time.</p>-->
<?php } else { ?>
<hr>
<?php forEach ($awaitingFinalReview as $paper) { ?>
<div class='adminPaper'>
<?php echo paperTitle($paper);?>
<?php echo submittedBy($paper);?>
<?php echo getDraftfilename($paper);?>
<?php echo getReviewer($paper);?>
<?php echo reviewerInitialRecommendation($paper); ?>
<?php echo firstReviewFilename($paper); ?>
<?php echo getEditorInitialDecision($paper); ?>
<?php echo getRevisedFilename($paper); ?>
<?php echo paperNote($paper); ?>
<?php echo deletePaper($paper); ?>
</div>
<?php }
} //ends $awaitingFinalReview loop ?>
</div>
<div class='paperBridge paperBridge4'>⇩</div>
<div class='paperStatus'>
<h3><span class='paperStep'>Step 6 (Final): </span>
Papers with Second Review Complete, Awaiting Your Final Decision:
<?php echo count($finalReviewDone); ?>
</h3>
<?php if(empty($finalReviewDone)) { ?>
<!--<p>There are no papers awaiting revisions at this time.</p>-->
<?php } else { ?>
<hr>
<?php forEach ($finalReviewDone as $paper) { ?>
<div class='adminPaper'>
<?php echo paperTitle($paper);?>
<?php echo submittedBy($paper);?>
<?php echo getDraftfilename($paper);?>
<?php echo getReviewer($paper);?>
<?php echo reviewerInitialRecommendation($paper); ?>
<?php echo firstReviewFilename($paper); ?>
<?php echo getRevisedFlename($paper); ?>
<?php echo getEditorInitialDecision($paper); ?>
<?php echo paperNote($paper); ?>
<?php echo deletePaper($paper); ?>
</div>
<?php }
} //ends $awaitingFinalReview loop ?>
</div>
<div class='paperBridge paperBridge5'>⇩</div>
<div class='paperStatus'>
<h3>Papers with a Final Status of <span style='color: green;'>ACCEPTED:</span>
<?php echo count($accepted); ?></h3>
<?php if(empty($accepted)) { ?>
<!--<p>There are no papers awaiting revisions at this time.</p>-->
<?php } else { ?>
<hr>
<?php forEach ($accepted as $paper) { ?>
<div class='adminPaper'>
<?php echo paperTitle($paper);?>
<?php echo submittedBy($paper);?>
<?php echo getDraftfilename($paper);?>
<?php echo getReviewer($paper);?>
<?php echo reviewerInitialRecommendation($paper); ?>
<?php echo firstReviewFilename($paper); ?>
<?php echo getEditorInitialDecision($paper); ?>
<?php echo getRevisedFlename($paper); ?>
<?php echo paperNote($paper); ?>
<?php echo deletePaper($paper); ?>
</div>
<?php }
} //ends $awaitingFinalReview loop ?>
</div>
<div class='paperBridge paperBridge5'>⇩</div>
<div class='paperStatus'>
<h3>Papers with a Final Status of <span style='color: red;'>REJECTED:</span>
<?php echo count($rejected); ?></h3>
<?php if(empty($rejected)) { ?>
<!--<p>There are no papers awaiting revisions at this time.</p>-->
<?php } else { ?>
<hr>
<?php forEach ($rejected as $paper) { ?>
<div class='adminPaper'>
<?php echo paperTitle($paper);?>
<?php echo submittedBy($paper);?>
<?php echo getDraftfilename($paper);?>
<?php echo getReviewer($paper);?>
<?php echo reviewerInitialRecommendation($paper); ?>
<?php echo firstReviewFilename($paper); ?>
<?php echo getEditorInitialDecision($paper); ?>
<?php echo getRevisedFilename($paper); ?>
<?php echo finalReviewFilename($paper); ?>
<?php echo paperNote($paper); ?>
<?php echo deletePaper($paper); ?>
</div>
<?php }
} //ends $awaitingFinalReview loop ?>
</div>
<?php } ?>
<script type='text/javascript' src='admin/JS/adminPaper.js'></script><file_sep>/controller/userUploads.php
<?php
//Handle when an author clicks to submit a new paper from the dashboard
if (isset($_POST['newPaper'])) {
$newPaper = TRUE;
}
//Handle when an author clicks to cancel new paper submission from the newPaper.php dialog
if (isset($_POST['paperSubmitCancel'])) {
$newPaper = TRUE;
$newPaperCancel = TRUE;
}
//Handle when the author submits a new paper from the newPaper.php dialog
if (isset($_POST['paperSubmit'])) {
$title = filter_input(INPUT_POST, 'paperTitle');
if ($title == FALSE) {
$newPaperError = "Please enter a paper title";
}
//prevents duplicate submissions when the user refreshes
if ($_SESSION['titleSubmitted'] != $title) {
$newPaper = TRUE;
$randomPad = rand(1000, 9999);
//var_dump($_FILES);
$doc_dir = getcwd().'/uploads/drafts/';
$doc_file = $doc_dir.$randomPad."-".basename($_FILES["paperFile"]["name"]);
$filetype = pathinfo($doc_file, PATHINFO_EXTENSION);
//echo $filetype;
if ($_FILES["paperFile"]["size"] > 10000000) {
$newPaperError = "Filesize must be less than 10MB";
}
if ($filetype != "doc" && $filetype != "docx") {
$newPaperError = "File must be a MS Word file";
}
if (file_exists($doc_file)) {
$newPaperError = "File already exists";
}
if (!isset($newPaperError)) {
if (move_uploaded_file($_FILES["paperFile"]["tmp_name"], $doc_file)) {
require_once 'model/papersDB.php';
uploadDraft($_SESSION['username'],
$randomPad."-".basename($_FILES["paperFile"]["name"]),
$title);
$newPaperSubmitted = TRUE;
} else {
$newPaperError = "Something went wrong. Please try again.";
}
}
$_SESSION['titleSubmitted'] = $title;
}
}
//Handle author revision upload
if (isset($_POST['revisionSubmit'])) {
//echo "HI THERE";
$paperID = filter_input(INPUT_POST, 'paperID', FILTER_VALIDATE_INT);
require_once 'model/papersDB.php';
if ($paperID && !checkForRevision($paperID)) {
$randomPad = rand(1000, 9999);
$doc_dir = getcwd().'/uploads/revisions/';
$doc_file = $doc_dir.$randomPad."-".basename($_FILES["revisionFile"]["name"]);
$filetype = pathinfo($doc_file, PATHINFO_EXTENSION);
if ($_FILES["revisionFile"]["size"] > 10000000) {
$revisionError = "Filesize must be less than 10MB";
}
if ($filetype != "doc" && $filetype != "docx") {
$revisionError = "File must be a MS Word file";
}
if (file_exists($doc_file)) {
$revisionError = "File already exists";
}
if (!isset($revisionError)) {
if (move_uploaded_file($_FILES["revisionFile"]["tmp_name"], $doc_file)) {
uploadRevision($paperID, $randomPad."-".basename($_FILES["revisionFile"]["name"]));
} else {
$revisionError = "Something went wrong. Please try again.";
}
}
}
}
//handle reviewer first review recommendation and submission
if (isset($_POST['firstReviewSubmit'])) {
$paperID = filter_input(INPUT_POST, 'paperID', FILTER_VALIDATE_INT);
$recommendation = filter_input(INPUT_POST, 'recommendation');
require_once 'model/papersDB.php';
if ($paperID && $recommendation && empty(checkForFirstReview($paperID))) {
$randomPad = rand(1000, 9999);
$doc_dir = getcwd().'/uploads/firstReview/';
$doc_file = $doc_dir.$randomPad."-".basename($_FILES["reviewFile"]["name"]);
$filetype = pathinfo($doc_file, PATHINFO_EXTENSION);
if ($_FILES["reviewFile"]["size"] > 10000000) {
$reviewError = "Filesize must be less than 10MB";
}
if ($filetype != "doc" && $filetype != "docx") {
$reviewError = "File must be a MS Word file";
}
if (file_exists($doc_file)) {
$reviewError = "File already exists";
}
if (!isset($reviewError)) {
if (move_uploaded_file($_FILES["reviewFile"]["tmp_name"], $doc_file)) {
uploadFirstReview($paperID, $randomPad."-".basename($_FILES["reviewFile"]["name"]),
$recommendation);
} else {
$reviewError = "Something went wrong. Please try again.";
}
}
}
}
//handle reviewer final review recommendation and submission
if (isset($_POST['finalReviewSubmit'])) {
$paperID = filter_input(INPUT_POST, 'paperID', FILTER_VALIDATE_INT);
$recommendation = filter_input(INPUT_POST, 'recommendation');
require_once 'model/papersDB.php';
if ($paperID && $recommendation && checkForFinalReview($paperID) == NULL) {
$randomPad = rand(1000, 9999);
$doc_dir = getcwd().'/uploads/finalReview/';
$doc_file = $doc_dir.$randomPad."-".basename($_FILES["reviewFile"]["name"]);
$filetype = pathinfo($doc_file, PATHINFO_EXTENSION);
if ($_FILES["reviewFile"]["size"] > 10000000) {
$reviewError = "Filesize must be less than 10MB";
}
if ($filetype != "doc" && $filetype != "docx") {
$reviewError = "File must be a MS Word file";
}
if (file_exists($doc_file)) {
$reviewError = "File already exists";
}
if (!isset($reviewError)) {
if (move_uploaded_file($_FILES["reviewFile"]["tmp_name"], $doc_file)) {
uploadFinalReview($paperID, $randomPad."-".basename($_FILES["reviewFile"]["name"]),
$recommendation);
} else {
$reviewError = "Something went wrong. Please try again.";
}
}
}
}
?><file_sep>/admin/adminSettings.php
<?php
?>
<div class="mainWrapperWithNav">
settings
</div>
<file_sep>/newPaper.php
<?php if (isset($newPaperSubmitted) || isset($newPaperCancel)) { ?>
<div class='paperSubmitted'>
<?php } elseif (isset($newPaperError)) { ?>
<div class='newPaper'>
<?php } else { ?>
<div class='newPaper newPaperAppear'>
<?php } ?>
<form method='post' action='index.php' enctype="multipart/form-data">
<label for='paperTitle'>Paper Title</label><br>
<input type='text' name='paperTitle' id='paperTitle' required><br>
<label for='paperFile'>Upload File (MS Word format)
<?php if(isset($newPaperError)) {
echo "<span class='miniWarning'>".$newPaperError."</span>";
} ?>
</label>
<input type='file' class='upload' name='paperFile' id='paperFile' required><hr>
<input type='submit' name='paperSubmit' value='Submit Paper'><br>
</form>
<form method='post' action='index.php'>
<input type='submit' name='paperSubmitCancel' value='Cancel'>
</form>
</div>
<file_sep>/controller/newUser.php
<?php
//new user request flag
if ($_POST['newUserRequest']) {
$newUserRequested = TRUE;
}
//Handling the new user page after the user has selected a role
if ($_POST['newAuthorRegister']) {
$newAuthorRequested = TRUE;
$newUserRequested = FALSE;
}
if ($_POST['newReviewerRegister']) {
$newReviewerRequested = TRUE;
$newUserRequested = FALSE;
}
//Error handling from the registration script
if (isset($_GET['err'])) {
//Get variables from the registration page if there is an error
$newUserError = TRUE;
$nameBlank = filter_input(INPUT_GET, 'u', FILTER_SANITIZE_STRIPPED);
$firstNameBlank = filter_input(INPUT_GET, 'f', FILTER_SANITIZE_STRIPPED);
$lastNameBlank = filter_input(INPUT_GET, 'l', FILTER_SANITIZE_STRIPPED);
$affiliationBlank = filter_input(INPUT_GET, 'a', FILTER_SANITIZE_STRIPPED);
$emailBlank = filter_input(INPUT_GET, 'e', FILTER_SANITIZE_STRIPPED);
$emailInvalid = filter_input(INPUT_GET, 'ei', FILTER_SANITIZE_STRIPPED);
$userPWBlank = filter_input(INPUT_GET, 'pw', FILTER_SANITIZE_STRIPPED);
$userPW2Blank = filter_input(INPUT_GET, 'pw2', FILTER_SANITIZE_STRIPPED);
$userPWTooShort = filter_input(INPUT_GET, 'pws', FILTER_SANITIZE_STRIPPED);
$nameFilled = filter_input(INPUT_GET, 'username', FILTER_SANITIZE_STRIPPED);
$firstNameFilled = filter_input(INPUT_GET, 'firstname', FILTER_SANITIZE_STRIPPED);
$lastNameFilled = filter_input(INPUT_GET, 'lastname', FILTER_SANITIZE_STRIPPED);
$affiliationFilled = filter_input(INPUT_GET, 'affiliation', FILTER_SANITIZE_STRIPPED);
$emailFilled = filter_input(INPUT_GET, 'email', FILTER_SANITIZE_EMAIL);
//gets the role from the 'r' parameter
$errRole = filter_input(INPUT_GET, 'r');
if ($errRole == 'a') {
$errRole = 'Author';
}
if ($errRole == 'r') {
$errRole = 'Reviewer';
}
$newUserErrorRole = 'Registration: New '.$errRole;
if ($_GET['err'] == 'pwm') {
$newUserError = 'Passwords do not match.';
$userPWError = TRUE;
}
if ($_GET['err'] == 'u') {
$newUserError = 'Username is taken';
$nameError = TRUE;
}
}
?><file_sep>/js/readNotes.js
//click the button to open the dialog box to submit a note for a specific paper
$('.viewNoteButton').click(function() {
var paperID = $(this).attr('paperID');
var textFor = "#textFor" + paperID;
var paperText = $(textFor).text();
$("#textAreaFor" + paperID).val(paperText);
var noteBox = "#makeNoteFor" + paperID;
$("body").animate({'scrollTop': 0}, 500, function() {
$(noteBox).slideDown(500);
});
});
//click to close the dialog box for adding a note to a specific paper
$('.closeNoteButton').click(function() {
var paperID = $(this).attr('paperID');
var noteBox = "#makeNoteFor" + paperID;
var top = $(this).offset();
$(noteBox).slideUp(300);
});<file_sep>/forgotPW.php
<?php
include "static/header.php";
?>
<!DOCTYPE html>
<html>
<div class='mainWrapper'>
<form class='loginForm' method='post' action='forgotPW.php'>
<label for='forgot_username'>Username</label>
<input type='text' id='forgot_username' name='username' placeholder='Username'><br>
<label for='forgot_email'>Username</label>
<input type='text' id='forgot_email' name='email' placeholder='email'><br>
<input type='submit'
</form>
</div>
</html>
<file_sep>/model/usersDB.php
<?php
require_once 'database.php';
function checkUsername($username) {
global $db;
$query = 'SELECT * FROM users WHERE username=:username';
$statement = $db->prepare($query);
$statement->bindValue(":username", $username);
$statement->execute();
$results = $statement->fetchAll();
if ($results) {
return TRUE;
} else {
return FALSE;
}
}
function addUser($user) {
//var_dump($user);
global $db;
$query = "INSERT INTO users (username, account_created, first_name,".
"last_name, affiliation, email, passwordHash, role) VALUES (:username, ".
":account_created, :first_name, :last_name, :affiliation, :email, :passwordHash, ".
":role)";
$accountCreated = date("Y-m-d H:i:s");
$passwordOptions = ['cost' => 11];
$passwordHash = password_hash($user['password'], PASSWORD_BCRYPT, $passwordOptions);
$statement = $db->prepare($query);
$statement->bindValue(":username", strtolower($user['username']));
$statement->bindValue(":account_created", $accountCreated);
$statement->bindValue(":first_name", $user['firstName']);
$statement->bindValue(":last_name", $user['lastName']);
$statement->bindValue(":affiliation", $user['affiliation']);
$statement->bindValue(":email", $user['email']);
$statement->bindValue(":passwordHash", $passwordHash);
$statement->bindValue(":role", $user['role']);
$statement->execute();
}
function login($name, $password) {
//echo "---------------<br>";
//echo "username: ".$name."<br>";
if (!isset($_SESSION['username'])) {
$lastLogin = getLastLogin($name);
global $db;
$query = "SELECT * FROM users WHERE username=:username";
$statement = $db->prepare($query);
$statement->bindValue(":username", strtolower($name));
$statement->execute();
$result = $statement->fetch();
$pwcheck = password_verify(substr($password, 0, 60), $result['passwordHash']);
if (password_verify($password, $result['passwordHash'])) {
updateTimestamp($name);
//$_SESSION['lastLogin'] = $lastLogin;
return array($result, $lastLogin);
} else {
return FALSE;
}
}
}
function updateTimestamp($name) {
global $db;
$query = "UPDATE users SET last_login=CURRENT_TIMESTAMP WHERE username=:username";
$statement = $db->prepare($query);
//$statement->bindValue(":timestamp", date("Y-m-d H:i:s"));
$statement->bindValue(":username", strtolower($name));
$statement->execute();
}
function getLastLogin($name) {
global $db;
$query = "SELECT last_login FROM users WHERE username=:username";
$statement = $db->prepare($query);
$statement->bindValue(":username", strtolower($name));
$statement->execute();
return $statement->fetch();
}
?><file_sep>/controller/adminFunctions.php
<?php
require_once 'model/database.php';
require_once 'model/adminDB.php';
if ($_POST['deletePaperConfirm']) {
$deletePaperID = filter_input(INPUT_POST, 'paperID');
}
function getMessageCounts() {
$allMessages = getAllMessages();
$newMessages = 0;
$oldMessages = 0;
$previousLogin = date($_SESSION['previousLogin']);
forEach($allMessages as $message) {
if ($previousLogin < date($message['whenSent'])) {
$newMessages++;
} else {
$oldMessages++;
}
}
return array($newMessages, $oldMessages);
}
function getMessageLists() {
$needsReply = array();
$alreadyReplied = array();
$allMessages = getAllMessages();
forEach($allMessages as $message) {
if (empty($message['whenReplied'])) {
array_push($needsReply, $message);
} else {
array_push($alreadyReplied, $message);
}
}
return array($needsReply, $alreadyReplied);
}
function getPaperCounts() {
$allPapers = getAllPapers();
$newPapers = 0;
$oldPapers = 0;
$previousLogin = date($_SESSION['previousLogin']);
forEach($allPapers as $paper) {
if ($previousLogin < date($paper['whenSubmitted'])) {
$newPapers++;
} else {
$oldPapers++;
}
}
return array($newPapers, $oldPapers);
}
function getUserCounts() {
$allUsers = getAllUsers();
$newUsers = 0;
$oldUsers = 0;
$previousLogin = date($_SESSION['previousLogin']);
forEach($allUsers as $user) {
if ($previousLogin < date($user['account_created'])) {
$newUsers++;
} else {
$oldUsers++;
}
}
return array($newUsers, $oldUsers);
}
//'awaiting_assignment','awaiting_review','awaiting_revisions','revisions_submitted','accepted','rejected'
function getPapersByStatus($papers) {
$needsAssignment = array();
$awaitingInitialReview = array();
$needsPostReviewStatus = array();
$awaitingRevisions = array();
$awaitingFinalReview = array();
$finalReviewDone = array();
$accepted = array();
$rejected = array();
$recentlyUpdated = array();
forEach($papers as $paper) {
if ($paper['status'] === 'awaiting_assignment') {
array_push($needsAssignment, $paper);
}
if ($paper['status'] === 'awaiting_review' && empty($paper['firstReviewFilename'])) {
array_push($awaitingInitialReview, $paper);
}
if ($paper['status'] === 'awaiting_review' && !empty($paper['firstReviewFilename'])) {
array_push($needsPostReviewStatus, $paper);
}
if ($paper['status'] === 'awaiting_revisions') {
array_push($awaitingRevisions, $paper);
}
if ($paper['status'] === 'revisions_submitted' && empty($paper['finalReviewFilename'])) {
array_push($awaitingFinalReview, $paper);
}
if ($paper['status'] === 'revisions_submitted' && !empty($paper['finalReviewFilename'])) {
array_push($finalReviewDone, $paper);
}
if ($paper['status'] === 'accepted') {
array_push($accepted, $paper);
}
if ($paper['status'] === 'rejected') {
array_push($rejected, $paper);
}
}
forEach($papers as $paper) {
if ($paper['recentlyUpdated'] == 1) {
array_push($recentlyUpdated, $paper);
}
}
$output = array("needsAssignment" => $needsAssignment,
"awaitingInitialReview" => $awaitingInitialReview,
"needsPostReviewStatus" => $needsPostReviewStatus,
"awaitingRevisions" => $awaitingRevisions,
"awaitingFinalReview" => $awaitingFinalReview,
"finalReviewDone" => $finalReviewDone,
"accepted" => $accepted,
"rejected" => $rejected,
"recentlyUpdated" => $recentlyUpdated);
return $output;
}
//options for assigning a reviewer to a paper
function reviewerOptionList() {
$reviewers = getAllReviewers();
//var_dump($reviewers);
$list = "<option></option>";
forEach($reviewers as $reviewer) {
$list = $list."<option class='reviewer paperOptionList' value=".$reviewer['username'].'>'.
$reviewer['first_name'].' '.$reviewer['last_name'].' - '.
$reviewer['affiliation'].'</option>';
}
return $list;
}
if (isset($_POST['deletePaper'])) {
$paperID = filter_input(INPUT_POST, "paperID", FILTER_SANITIZE_NUMBER_INT);
$adminPage = "adminPapers.php";
//only the editor can delete papers from the system
if ($_SESSION['username'] === 'admin' && $paperID) {
deletePaperDB($paperID);
}
}
if (isset($_POST['changeReviewer']) &&
isset($_POST['reviewer']) &&
isset($_POST['paperID'])) {
require_once 'model/papersDB.php';
$reviewer = filter_input(INPUT_POST, "reviewer", FILTER_SANITIZE_STRIPPED);
$paperID = filter_input(INPUT_POST, "paperID", FILTER_SANITIZE_NUMBER_INT);
if($reviewer &&
$paperID &&
empty(getPaperInfo($paperID)['firstReviewFilename'])) {
assignReviewer($paperID, $reviewer);
}
}
if (isset($_POST['adminNote'])) {
$adminPage = "adminPapers.php";
$noteText = filter_input(INPUT_POST, "noteText", FILTER_SANITIZE_STRING);
$paperID = filter_input(INPUT_POST, "paperID", FILTER_SANITIZE_NUMBER_INT);
if (!empty($noteText) && !empty($paperID)) {
addEditorNotes($paperID, $noteText);
}
}
if (isset($_POST['deleteNote'])) {
$adminPage = "adminPapers.php";
$paperID = filter_input(INPUT_POST, "paperID", FILTER_SANITIZE_NUMBER_INT);
if (!empty($paperID)) {
deleteEditorNotes($paperID, $_SESSION['username']);
}
}
if ($_POST['changePaperStatus']) {
$paperID = filter_input(INPUT_POST, "paperID", FILTER_SANITIZE_NUMBER_INT);
$status = filter_input(INPUT_POST, 'editorStatus', FILTER_SANITIZE_STRING);
require_once 'model/papersDB.php';
$paper = getPaperInfo($paperID);
if ($paperID && $status && !empty($paper['firstReviewFilename'])) {
updateStatus($paperID, $status);
}
}
?>
<file_sep>/userMessages.php
<?php
require_once 'controller/messages.php';
$userMessages = getMessageList($_SESSION['username']);
$repliedMessages = $userMessages[0];
$needsReply = $userMessages[1];
//var_dump($repliedMessages);
?>
<h2>Replies to your Messages:</h2>
<div class='messageList'>
<?php if (count($repliedMessages) == 0) {
echo "<p>You have no messages with replies at this time!</p>";
} else {
forEach ($repliedMessages as $message) { ?>
<div class='messageWraper'>
<p class='messageLineHeader'>Your Message Sent On <?php
echo date("M j, Y, g:i a", strtotime($message['whenSent'])); ?>
</p>
<p class='messageLineHeader'>Re: <?php echo $message['title']; ?></p>
<p class='messageLine'>Message: <?php echo $message['message']; ?><p>
<p class='messageLineHeader'>Editor Replied On <?php
echo date("M j, Y, g:i a", strtotime($message['whenReplied'])); ?>
</p>
<p class='messageLine'>Reply: <?php echo $message['reply']; ?><p>
</div>
<?php }
} ?>
</div>
<hr>
<br>
<h2>Your Messages Awaiting a Reply:</h2>
<div class='messageList'>
<?php if (count($needsReply) == 0) {
echo "<p>You have no messages that need a reply!</p>";
} else {
forEach ($needsReply as $message) { ?>
<div class='messageWraper'>
<p class='messageLineHeader'>Your Message Sent On <?php
echo date("M j, Y, g:i a", strtotime($message['whenSent'])); ?>
</p>
<p class='messageLineHeader'>Re: <?php echo $message['title']; ?></p>
<p class='messageLine'>Message: <?php echo $message['message']; ?><p>
</div>
<?php }
} ?>
</div>
<hr>
<br>
<div class='messageAdmin'>
<p class='tip'>Please use the following form to contact the Editor. They
are responsible for assigning your papers to reviewers as well as
handling any requests to delete submitted papers from the system.</p>
<form method='post' action='index.php'>
<label class='paperTitleLabel' for='selectPaperTitle'>Which paper is this about?</label><br>
<select class='selectPaperTitle' id='selectPaperTitle' name='messageTitle' required>
<?php forEach ($yourPapers as $paper) {
echo "<option value='".$paper['title']."'>".$paper['title']."</option>";
} ?>
<option value='General Question' selected>General Question - No specific paper</option>
</select>
<br>
<textarea class='messageText' name='message' placeholder="Type your message here..." required></textarea>
<br>
<input type='hidden' name='fromUsername' value='<?php echo $_SESSION['username']; ?>'>
<input class='submitButton' type='submit' name='sendMessage' value='Send Message'>
<?php //echo "STATUS: ".$_SESSION['messageSent']; ?>
<?php if(isset($_SESSION['messageSent'])) {
//echo "STUFF";
echo "<span class='alert'>".$messageStatus."</span>";
} ?>
</form>
</div>
| 05171f962c0e350878631c6ef9f2ad1ac027daa8 | [
"JavaScript",
"SQL",
"PHP"
] | 27 | PHP | Cheezily/PaperTracker | 8e911e77708c44010af59b1ae71dc0ddc80e7548 | d97402b420a83f26b880f45e866378aa97b869a4 |
refs/heads/master | <file_sep>package workflow.tmp.rest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import loggee.api.EMethodLogPolicy;
import loggee.api.Logged;
import workflow.engine.Cmt;
import workflow.engine.Engine;
import workflow.model.ProcessData;
@Path("/workflow")
@RequestScoped
@Logged(booleanMethodLogPolicy = EMethodLogPolicy.REGULAR, logMethodParametersAfterCall = true)
public class EngineRestService {
@Inject
@Cmt
private Engine engine;
@GET
@Path("/runEngine")
@Produces(value = "application/json")
public boolean runEngine() {
ProcessData processData = engine.run();
engine.disposeStatefulKnowledgeSession(processData);
long start = System.currentTimeMillis();
engine.proceed(processData);
long end = System.currentTimeMillis();
System.err.println("DURATION: " + (end - start));
return true;
}
@GET
@Path("/strainEngine/{nrOfProcesses}")
@Produces(value = "application/json")
public boolean strainEngine(@PathParam("nrOfProcesses") Integer nrOfProcesses) throws InterruptedException, ExecutionException {
List<Future<ProcessData>> futureProcessDataList = new ArrayList<Future<ProcessData>>();
Future<ProcessData> futureProcessData;
for (int i = 0; i < nrOfProcesses; i++) {
futureProcessData = engine.runAsynchronously();
futureProcessDataList.add(futureProcessData);
}
for (Future<ProcessData> currentFutureProcessData : futureProcessDataList) {
ProcessData processData = currentFutureProcessData.get();
engine.disposeStatefulKnowledgeSession(processData);
long start = System.currentTimeMillis();
engine.proceed(processData);
long end = System.currentTimeMillis();
// System.err.println("DURATION: " + (end - start));
}
return true;
}
@GET
@Path("/runEngine/{sessionId}/{processInstanceId}/{workItemId}/{tryTrigger}")
@Produces(value = "application/json")
public boolean resumeEngine(@PathParam("sessionId") Integer sessionId, @PathParam("processInstanceId") Long processInstanceId,
@PathParam("workItemId") Long workItemId, @PathParam("tryTrigger") Boolean tryTrigger) {
engine.resume(sessionId, processInstanceId, workItemId, tryTrigger);
return true;
}
}
<file_sep>package workflow.model;
public enum EInputVariableScope {
PROCESS, TASK;
}
<file_sep>package workflow.event;
public class EventTypes {
public static final String PERSON_CHANGED = "PERSON_CHANGED";
}
<file_sep>package workflow.history;
import java.util.Map;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.inject.Singleton;
import javax.persistence.EntityManagerFactory;
import javax.transaction.HeuristicMixedException;
import javax.transaction.HeuristicRollbackException;
import javax.transaction.InvalidTransactionException;
import javax.transaction.NotSupportedException;
import javax.transaction.RollbackException;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import org.drools.WorkingMemory;
import org.drools.audit.WorkingMemoryLogger;
import org.drools.audit.event.LogEvent;
import org.drools.audit.event.RuleFlowLogEvent;
import org.drools.audit.event.RuleFlowNodeLogEvent;
import org.drools.audit.event.RuleFlowVariableLogEvent;
import org.drools.event.KnowledgeRuntimeEventManager;
import workflow.model.ProcessData;
@Singleton
@Lock(LockType.READ)
public class HistoryLogger extends WorkingMemoryLogger {
private EntityManagerFactory entityManagerFactory;
private TransactionManager transactionManager;
private Map<String, Object> parameters;
public HistoryLogger() {
super();
}
public HistoryLogger(KnowledgeRuntimeEventManager session, EntityManagerFactory entityManagerFactory, TransactionManager transactionManager,
Map<String, Object> parameters) {
super(session);
this.entityManagerFactory = entityManagerFactory;
this.transactionManager = transactionManager;
this.parameters = parameters;
}
public HistoryLogger(WorkingMemory workingMemory) {
super(workingMemory);
}
@Override
public void logEventCreated(LogEvent logEvent) {
int logEventType = logEvent.getType();
String logEventClassSimpleName = logEvent.getClass().getSimpleName();
String processId;
String processName;
Long processInstanceId;
String nodeId;
String nodeName;
String nodeInstanceId;
String variableId;
String variableInstanceId;
String objectToString;
if (logEvent instanceof RuleFlowLogEvent) {
RuleFlowLogEvent ruleFlowLogEvent = (RuleFlowLogEvent) logEvent;
processId = ruleFlowLogEvent.getProcessId();
processName = ruleFlowLogEvent.getProcessName();
processInstanceId = ruleFlowLogEvent.getProcessInstanceId();
} else {
processId = null;
processName = null;
processInstanceId = null;
}
if (logEvent instanceof RuleFlowNodeLogEvent) {
RuleFlowNodeLogEvent ruleFlowNodeLogEvent = (RuleFlowNodeLogEvent) logEvent;
nodeId = ruleFlowNodeLogEvent.getNodeId();
nodeName = ruleFlowNodeLogEvent.getNodeName();
nodeInstanceId = ruleFlowNodeLogEvent.getNodeInstanceId();
} else {
nodeId = null;
nodeName = null;
nodeInstanceId = null;
}
if (logEvent instanceof RuleFlowVariableLogEvent) {
RuleFlowVariableLogEvent ruleFlowVariableLogEvent = (RuleFlowVariableLogEvent) logEvent;
variableId = ruleFlowVariableLogEvent.getVariableId();
variableInstanceId = ruleFlowVariableLogEvent.getVariableInstanceId();
objectToString = ruleFlowVariableLogEvent.getObjectToString();
return;
} else {
variableId = null;
variableInstanceId = null;
objectToString = null;
}
// // System.err.println("HISTORY " + logEvent);
// // System.err.println("HISTORY " + parameters);
Transaction suspendedTransaction = null;
try {
boolean newTransaction;
// Transaction transaction = transactionManager.getTransaction();
// if (transaction == null) {
suspendedTransaction = transactionManager.suspend();
transactionManager.begin();
newTransaction = true;
// } else {
// newTransaction = false;
// }
ProcessData processData = new ProcessData();
processData.setTimeStamp(System.nanoTime());
processData.setLogEventType(logEventType);
processData.setLogEventClassSimpleName(logEventClassSimpleName);
processData.setProcessId(processId);
processData.setProcessName(processName);
processData.setProcessInstanceId(processInstanceId);
processData.setNodeId(nodeId);
processData.setNodeName(nodeName);
processData.setNodeInstanceId(nodeInstanceId);
processData.setVariableId(variableId);
processData.setVariableInstanceId(variableInstanceId);
processData.setObjectToString(objectToString);
entityManagerFactory.createEntityManager().persist(processData);
if (newTransaction) {
transactionManager.commit();
}
} catch (SystemException e) {
e.printStackTrace();
setRollbackOnlyOnTransactionManager();
} catch (NotSupportedException e) {
e.printStackTrace();
setRollbackOnlyOnTransactionManager();
} catch (SecurityException e) {
e.printStackTrace();
setRollbackOnlyOnTransactionManager();
} catch (IllegalStateException e) {
e.printStackTrace();
setRollbackOnlyOnTransactionManager();
} catch (RollbackException e) {
e.printStackTrace();
setRollbackOnlyOnTransactionManager();
} catch (HeuristicMixedException e) {
e.printStackTrace();
setRollbackOnlyOnTransactionManager();
} catch (HeuristicRollbackException e) {
e.printStackTrace();
setRollbackOnlyOnTransactionManager();
} finally {
if (suspendedTransaction != null) {
try {
transactionManager.resume(suspendedTransaction);
} catch (InvalidTransactionException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
setRollbackOnlyOnTransactionManager();
e.printStackTrace();
} catch (SystemException e) {
setRollbackOnlyOnTransactionManager();
e.printStackTrace();
}
}
}
}
private void setRollbackOnlyOnTransactionManager() {
try {
transactionManager.setRollbackOnly();
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (SystemException e1) {
e1.printStackTrace();
}
}
}
<file_sep>package workflow.businesstask;
import vrds.model.RepoItem;
public interface IBusinessTaskHandler {
// TODO Split this interface into 2 parts, one that defines methods that are
// going to be called by the WorkflowTaskProcessor and another that defines methods
// that are going to be called by the UI
void initTask(RepoItem businessTask);
void readVariable(RepoItem businessTask);
void writeVariable(RepoItem businessTask, String variableName, Object value);
void finishTask(RepoItem businessTask);
}
<file_sep>package workflow.taskprocessor;
import java.util.HashSet;
import java.util.List;
import javax.inject.Inject;
import vrds.model.EAttributeType;
import vrds.model.RepoItem;
import vrds.model.RepoItemAttribute;
import vrds.model.attributetype.LongAttributeValueHandler;
import workflow.businesstask.IBusinessTaskHandler;
// TODO Transaction
public class DefaultWorkflowTaskHandler implements IWorkflowTaskHandler {
private static final String WORKFLOW_TASK_ID = "workflowTaskId";
private static final String BUSINESS_TASKS = "businessTasks";
@Inject
private IBusinessTaskHandler businessTaskHandler;
@Override
public void initTask(Long processRepoItemId, String taskName) {
RepoItem processTask = createNewProcessTask(processRepoItemId, taskName);
List<RepoItem> listOfbusinessTasks = createBusinessTasks();
// TODO Add business tasks to process task
for (RepoItem businessTask : listOfbusinessTasks) {
businessTaskHandler.initTask(businessTask);
}
}
@Override
public void finishTask(Long businessTaskId, String taskName) {
// TODO Auto-generated method stub
// FIXME This is extremely simplified.
// Different logic must be called depending on the task.
if (isLast(businessTaskId)) {
RepoItem businessTask = getBusinessTask(businessTaskId);
Long workflowTaskId = businessTask.getValue(WORKFLOW_TASK_ID, LongAttributeValueHandler.getInstance());
finishWorkflowTask(workflowTaskId);
}
}
private List<RepoItem> createBusinessTasks() {
// TODO Auto-generated method stub
// businessTask has an attribute 'finished'
return null;
}
private RepoItem getBusinessTask(Long businessTaskId) {
// TODO Auto-generated method stub
return null;
}
private boolean isLast(Long businessTaskId) {
// TODO Auto-generated method stub
return false;
}
private RepoItem createNewProcessTask(Long processRepoItemId, String taskName) {
// TODO Persist processTask
RepoItem processTask = new RepoItem();
HashSet<RepoItemAttribute> attributesOfProcessTask = new HashSet<>();
RepoItemAttribute businessTasksOfProcessTask = new RepoItemAttribute();
businessTasksOfProcessTask.setNameAndType(BUSINESS_TASKS, EAttributeType.REPO_ITEM);
attributesOfProcessTask.add(businessTasksOfProcessTask);
processTask.setRepoItemAttributes(attributesOfProcessTask);
return processTask;
}
private void finishWorkflowTask(Long workflowTaskId) {
// TODO
}
}
<file_sep>package workflow.workitem;
import org.drools.runtime.process.WorkItem;
import org.drools.runtime.process.WorkItemHandler;
import org.drools.runtime.process.WorkItemManager;
import vrds.model.RepoItem;
import vrds.model.attributetype.StringAttributeValueHandler;
public class TempWorkItemHandler implements WorkItemHandler {
private static final String INPUT_VARIABLE_SOURCE = "inputVariableSource";
private static final String INPUT_BEHAVIOUR_SOURCE = "inputBehaviourSource";
@Override
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
// TODO Auto-generated method stub
}
@Override
public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
// TODO Auto-generated method stub
}
public void tmp(RepoItem task, RepoItem process, WorkItem workItem, WorkItemManager manager) {
String inputVariableSource = task.getValue(INPUT_VARIABLE_SOURCE, StringAttributeValueHandler.getInstance());
String inputVariableDescription = getStringValue(inputVariableSource, workItem);
String inputBehaviourSource = task.getValue(INPUT_VARIABLE_SOURCE, StringAttributeValueHandler.getInstance());
String inputBehaviourDescription = getStringValue(inputVariableSource, workItem);
}
public String getStringValue(String expression, WorkItem workItem) {
int indexOfDelimiter = expression.indexOf(".");
String processParameterName = expression.substring(0, indexOfDelimiter);
String attributeName = expression.substring(indexOfDelimiter);
RepoItem repoItem = (RepoItem) workItem.getParameter(processParameterName);
String value = repoItem.getValue(attributeName, StringAttributeValueHandler.getInstance());
return value;
}
}
<file_sep>package workflow.tmp.workitem;
import java.util.List;
import javax.persistence.EntityManager;
import org.drools.runtime.process.ProcessInstance;
import org.drools.runtime.process.WorkItem;
import org.drools.runtime.process.WorkItemHandler;
import org.drools.runtime.process.WorkItemManager;
import org.jbpm.persistence.processinstance.ProcessInstanceInfo;
import workflow.engine.ThiefEntityManagerFactory;
import workflow.model.Member;
public class TmpWorkItemHandler implements WorkItemHandler {
private Long workItemId;
private ThiefEntityManagerFactory thiefEntityManagerFactory;
public TmpWorkItemHandler(ThiefEntityManagerFactory thiefEntityManagerFactory) {
this.thiefEntityManagerFactory = thiefEntityManagerFactory;
}
@Override
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
System.err.println("Work item name: " + workItem.getName());
// TODO delete
System.err.println("TMP: " + workItem.getParameter("tmp"));
List<EntityManager> entityManagers = thiefEntityManagerFactory.getEntityManagers();
if (entityManagers != null) {
for (EntityManager entityManager : entityManagers) {
ProcessInstanceInfo processInstanceInfo = entityManager.find(ProcessInstanceInfo.class, workItem.getProcessInstanceId());
if (processInstanceInfo != null) {
Member member = new Member();
member.setName("memberName" + entityManager);
entityManager.persist(member);
try {
// entityManager.flush();
// System.err.println("WORK_ITEM_HANDLER Saved " + member.getName());
} catch (Exception e) {
// System.err.println("WORK_ITEM_HANDLER " + e.getMessage());
}
}
}
}
workItemId = workItem.getId();
// System.err.println("WORK_ITEM_HANDLER execute workItem " + workItem.getName() + ", work item id: " + workItemId);
}
@Override
public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
// System.err.println("WORK_ITEM_HANDLER abort workItem " + workItem.getName());
}
public Long getWorkItemId() {
return workItemId;
}
}
<file_sep>package workflow.businesstask;
import java.util.List;
import vrds.model.EAttributeType;
import vrds.model.MetaAttribute;
import vrds.model.RepoItem;
import vrds.model.RepoItemAttribute;
import vrds.model.attributetype.StringAttributeValueHandler;
import workflow.model.ProcessVariableDefinition;
public class DefaultBusinessTaskHandler implements IBusinessTaskHandler {
/*
* BusinessTask process (process instance) task (workflow task)
*/
private static final String DYNAMIC_TAG = "dynamicTag";
private static final String PROCESS = "process";
private static final String TASK_SPECIFIC_PROCESS_VARIABLES_DEFINITION = "taskSpecificProcessVariablesDefinition";
private static final String IO_VARIABLE_SOURCE = "ioVariableSource";
private static final String INPUT_BEHAVIOUR_SOURCE = "inputBehaviourSource";
@Override
public void initTask(RepoItem businessTask) {
preProcess(businessTask);
initialIO(businessTask);
// TODO notify actors
}
@Override
public void readVariable(RepoItem businessTask) {
// TODO Auto-generated method stub
}
@Override
public void writeVariable(RepoItem businessTask, String variableName, Object value) {
RepoItem task = getBusinessTaskDefinition(businessTask);
RepoItemAttribute attribute = task.getAttribute(variableName);
if (attribute == null) {
// TODO Where and what kind of exception should be thrown.
throw new RuntimeException();
} else {
attribute.setValue(value);
}
String inputBehaviourSource = task.getValue(INPUT_BEHAVIOUR_SOURCE, StringAttributeValueHandler.getInstance());
callInputBehaviourService(businessTask.getId(), inputBehaviourSource);
setContextDependentIO(task);
}
public void set(String taskVariableName, Object value) {
}
@Override
public void finishTask(RepoItem businessTask) {
postProcess(businessTask);
close(businessTask);
}
private void preProcess(RepoItem businessTask) {
}
private void initialIO(RepoItem businessTask) {
RepoItem businessTaskDefinition = getBusinessTaskDefinition(businessTask);
String taskSpecificProcessVariableDefinitionData = businessTaskDefinition.getValue(TASK_SPECIFIC_PROCESS_VARIABLES_DEFINITION,
StringAttributeValueHandler.getInstance());
List<ProcessVariableDefinition> taskSpecificProcessVariableDefinitionList = parseIoVariableSourceData(taskSpecificProcessVariableDefinitionData);
for (ProcessVariableDefinition taskSpecificProcessVariableDefinition : taskSpecificProcessVariableDefinitionList) {
RepoItemAttribute ioAttribute = new RepoItemAttribute();
ioAttribute.setRepoItem(businessTask);
ioAttribute.setNameAndType(taskSpecificProcessVariableDefinition.getName(), taskSpecificProcessVariableDefinition.getType().getInputVariableType()
.getAttributeType());
persist(ioAttribute);
}
setContextDependentIO(businessTask);
}
private void postProcess(RepoItem businessTask) {
// TODO Auto-generated method stub
}
private void close(RepoItem businessTask) {
// TODO Auto-generated method stub
}
private void callInputBehaviourService(Long taskId, String inputBehaviourSource) {
// TODO Auto-generated method stub
}
private void setContextDependentIO(RepoItem businessTask) {
String ioVariableSourceData = businessTask.getValue(IO_VARIABLE_SOURCE, StringAttributeValueHandler.getInstance());
List<ProcessVariableDefinition> contextDependentProcessVariableDefinitionList = parseIoVariableSourceData(ioVariableSourceData);
// TODO Remove previous, not used attributes
for (ProcessVariableDefinition contextDependentProcessVariableDefinition : contextDependentProcessVariableDefinitionList) {
RepoItemAttribute ioAttribute = new RepoItemAttribute();
ioAttribute.setRepoItem(businessTask);
ioAttribute.setNameAndType(contextDependentProcessVariableDefinition.getName(), contextDependentProcessVariableDefinition.getType()
.getInputVariableType().getAttributeType());
MetaAttribute dynamicTag = new MetaAttribute();
dynamicTag.setOwnerAttribute(ioAttribute);
dynamicTag.setNameAndType(DYNAMIC_TAG, EAttributeType.STRING);
persist(ioAttribute);
}
}
private List<ProcessVariableDefinition> parseIoVariableSourceData(String staticIO) {
/*
* accessRight;REPO::AccessRight;PROCESS;ALL::REPO::AccessRight
*/
// TODO Auto-generated method stub
return null;
}
private RepoItem getBusinessTaskDefinition(RepoItem businessTask) {
// TODO Auto-generated method stub
return null;
}
private void persist(RepoItemAttribute ioAttribute) {
// TODO Auto-generated method stub
}
}
<file_sep>package workflow.engine;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
import javax.annotation.Resource;
import javax.ejb.AsyncResult;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.transaction.TransactionManager;
import loggee.api.Logged;
import org.drools.KnowledgeBase;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.impl.EnvironmentFactory;
import org.drools.io.ResourceFactory;
import org.drools.persistence.jpa.JPAKnowledgeService;
import org.drools.runtime.Environment;
import org.drools.runtime.EnvironmentName;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.runtime.process.ProcessInstance;
import org.drools.runtime.process.WorkflowProcessInstance;
import workflow.domain.Person;
import workflow.history.HistoryLogger;
import workflow.model.ProcessData;
import workflow.tmp.workitem.TmpWorkItemHandler;
import workflow.util.Primary;
import workflow.util.WorkflowHistory;
@Logged
@Umt
@ApplicationScoped
public class UMTEngine implements Engine {
private static final String PROCESS_DEFINITION_DIRECTORY_PATH = "bpmn/";
private static final String PROCESS_NAME = "MainProcess5";
private static final String PROCESS_EXTENSION = "bpmn2";
@Inject
@Primary
private EntityManager entityManager;
@Inject
@WorkflowHistory
private EntityManager workflowHistoryEntityManager;
@Resource(mappedName = "java:jboss/TransactionManager")
private TransactionManager transactionManager;
private String workItemName = "TmpWorkItem";
@Override
public Future<ProcessData> runAsynchronously() {
ProcessData processData = run();
return new AsyncResult<ProcessData>(processData);
}
@Override
public ProcessData run() {
ThiefEntityManagerFactory thiefEntityManagerFactory = new ThiefEntityManagerFactory(entityManager.getEntityManagerFactory());
int sessionId;
long processInstanceId;
Map<String, Object> parameters;
KnowledgeBuilder knowledgeBuilder;
KnowledgeBase knowledgeBase;
Environment env;
StatefulKnowledgeSession statefulKnowledgeSession;
TmpWorkItemHandler handler;
ProcessInstance processInstance;
handler = new TmpWorkItemHandler(thiefEntityManagerFactory);
Person person = new Person();
person.setName("Joe");
Person person2 = new Person();
person2.setName("Adam");
parameters = new HashMap<String, Object>();
int nrOfPersons = 100;
for (int i = 0; i < nrOfPersons; i++) {
person = new Person();
person.setName("PersoPersoPersoPersoPersoPersoPersoPersoPersoPerso");
parameters.put(i + "", person);
}
env = buildEnvironment(thiefEntityManagerFactory);
// Build knowledge base
knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
knowledgeBuilder.add(ResourceFactory.newClassPathResource(PROCESS_DEFINITION_DIRECTORY_PATH + PROCESS_NAME + "." + PROCESS_EXTENSION),
ResourceType.BPMN2);
knowledgeBase = knowledgeBuilder.newKnowledgeBase();
// Create knowledge session
// StatefulKnowledgeSession statefulKnowledgeSession = knowledgeBase.newStatefulKnowledgeSession();
statefulKnowledgeSession = JPAKnowledgeService.newStatefulKnowledgeSession(knowledgeBase, null, env);
sessionId = statefulKnowledgeSession.getId();
// System.err.println("Session id: " + sessionId);
// Add history logger
new HistoryLogger(statefulKnowledgeSession, workflowHistoryEntityManager.getEntityManagerFactory(), transactionManager, parameters);
// Add logger to knowledge session
// KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(statefulKnowledgeSession, "d:/tmp/workflow.log");
// Put stuff into knowledge session
statefulKnowledgeSession.setGlobal("person2", person2);
statefulKnowledgeSession.getWorkItemManager().registerWorkItemHandler(workItemName, handler);
// Start process
processInstance = statefulKnowledgeSession.createProcessInstance(PROCESS_NAME, parameters);
processInstanceId = processInstance.getId();
// System.err.println("Process instance id: " + processInstanceId);
statefulKnowledgeSession.startProcessInstance(processInstanceId);
// // Complete task(s)
// workItemId = handler.getWorkItemId();
//
// // System.err.println("Work item id: " + workItemId);
//
// statefulKnowledgeSession.getWorkItemManager().completeWorkItem(workItemId, null);
// Signal event
statefulKnowledgeSession.signalEvent("RESUME", null, processInstanceId);
ProcessData processData = new ProcessData();
processData.setSessionId(sessionId);
processData.setProcessInstanceId(processInstanceId);
processData.setWorkItemId(handler.getWorkItemId());
processData.setStatefulKnowledgeSession(statefulKnowledgeSession);
return processData;
}
@Override
public void proceed(ProcessData processData) {
ThiefEntityManagerFactory thiefEntityManagerFactory = new ThiefEntityManagerFactory(entityManager.getEntityManagerFactory());
int sessionId = processData.getSessionId();
long processInstanceId = processData.getProcessInstanceId();
Map<String, Object> parameters;
KnowledgeBuilder knowledgeBuilder;
KnowledgeBase knowledgeBase;
Environment env;
StatefulKnowledgeSession statefulKnowledgeSession;
TmpWorkItemHandler handler;
ProcessInstance processInstance;
Long workItemId;
handler = new TmpWorkItemHandler(thiefEntityManagerFactory);
Person person = new Person();
person.setName("Joe");
Person person2 = new Person();
person2.setName("Adam");
parameters = new HashMap<String, Object>();
parameters.put("person", person);
env = buildEnvironment(thiefEntityManagerFactory);
// Rebuild
knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
knowledgeBuilder.add(ResourceFactory.newClassPathResource(PROCESS_DEFINITION_DIRECTORY_PATH + PROCESS_NAME + ".bpmn2"), ResourceType.BPMN2);
knowledgeBase = knowledgeBuilder.newKnowledgeBase();
statefulKnowledgeSession = JPAKnowledgeService.loadStatefulKnowledgeSession(sessionId, knowledgeBase, null, env);
statefulKnowledgeSession.getWorkItemManager().registerWorkItemHandler(workItemName, handler);
new HistoryLogger(statefulKnowledgeSession, workflowHistoryEntityManager.getEntityManagerFactory(), transactionManager, parameters);
processInstance = statefulKnowledgeSession.getProcessInstance(processInstanceId);
// if (processInstance instanceof ProcessInstanceImpl) {
// ProcessInstanceImpl processInstanceImpl = (ProcessInstanceImpl) processInstance;
//
// InternalKnowledgeRuntime knowledgeRuntime = processInstanceImpl.getKnowledgeRuntime();
// if (knowledgeRuntime == null) {
// processInstanceImpl.setKnowledgeRuntime((InternalKnowledgeRuntime) statefulKnowledgeSession);
// }
// }
// statefulKnowledgeSession.signalEvent("Trigger", null);
// Signal same event again
statefulKnowledgeSession.signalEvent("RESUME", null, processInstanceId);
// Complete task(s)
workItemId = processData.getWorkItemId();
// System.err.println("Work item id: " + workItemId);
statefulKnowledgeSession.getWorkItemManager().completeWorkItem(workItemId, null);
// Check various stuff after process has finished
// System.err.println("process variable 'person': " + ((WorkflowProcessInstance) processInstance).getVariable("person"));
// System.err.println("process parameter 'person': " + parameters.get("person"));
// System.err.println("global 'person2': " + statefulKnowledgeSession.getGlobal("person2"));
// org.jbpm.process.instance.ProcessInstance jbpmProcessInstance = (org.jbpm.process.instance.ProcessInstance) processInstance;
// VariableScopeInstance variableContextInstance = (VariableScopeInstance) jbpmProcessInstance.getContextInstance(VariableScope.VARIABLE_SCOPE);
// Map<String, Object> variables = variableContextInstance.getVariables();
//
// // System.err.println("process variables: " + variables.entrySet());
// final long processId = processInstance.getId();
// Map<String, Object> variables2 = statefulKnowledgeSession.execute(
// new GenericCommand<Map<String, Object>>() {
// private static final long serialVersionUID = 1L;
//
// public Map<String, Object> execute(Context context) {
// StatefulKnowledgeSession ksession = ((KnowledgeCommandContext) context).getStatefulKnowledgesession();
// org.jbpm.process.instance.ProcessInstance processInstance = (org.jbpm.process.instance.ProcessInstance) ksession.getProcessInstance(processId);
// VariableScopeInstance variableScope = (VariableScopeInstance) processInstance.getContextInstance(VariableScope.VARIABLE_SCOPE);
// Map<String, Object> variables = variableScope.getVariables();
// return variables;
// }
// }
// );
//
// // System.err.println("process variables via command: " + variables2.entrySet());
// logger.close();
}
@Override
public void resume(Integer sessionId, Long processInstanceId, Long workItemId, Boolean tryTrigger) {
ThiefEntityManagerFactory thiefEntityManagerFactory = new ThiefEntityManagerFactory(entityManager.getEntityManagerFactory());
String workItemName = "TmpWorkItem";
Map<String, Object> parameters;
KnowledgeBuilder knowledgeBuilder;
KnowledgeBase knowledgeBase;
Environment env;
StatefulKnowledgeSession statefulKnowledgeSession;
TmpWorkItemHandler handler;
ProcessInstance processInstance;
handler = new TmpWorkItemHandler(thiefEntityManagerFactory);
Person person = new Person();
person.setName("Joe");
Person person2 = new Person();
person2.setName("Adam");
parameters = new HashMap<String, Object>();
parameters.put("person", person);
env = buildEnvironment(thiefEntityManagerFactory);
// Rebuild
knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
knowledgeBuilder.add(ResourceFactory.newClassPathResource(PROCESS_DEFINITION_DIRECTORY_PATH + PROCESS_NAME + ".bpmn2"), ResourceType.BPMN2);
knowledgeBase = knowledgeBuilder.newKnowledgeBase();
statefulKnowledgeSession = JPAKnowledgeService.loadStatefulKnowledgeSession(sessionId, knowledgeBase, null, env);
statefulKnowledgeSession.getWorkItemManager().registerWorkItemHandler(workItemName, handler);
new HistoryLogger(statefulKnowledgeSession, workflowHistoryEntityManager.getEntityManagerFactory(), transactionManager, parameters);
processInstance = statefulKnowledgeSession.getProcessInstance(processInstanceId);
statefulKnowledgeSession.startProcessInstance(processInstanceId);
if (tryTrigger) {
statefulKnowledgeSession.signalEvent("RESUME", null);
}
if (workItemId > 0) {
// Complete task(s)
statefulKnowledgeSession.getWorkItemManager().completeWorkItem(workItemId, null);
} else {
statefulKnowledgeSession.getWorkItemManager().completeWorkItem(handler.getWorkItemId(), null);
}
// Check various stuff after process has finished
// System.err.println("process variable 'person': " + ((WorkflowProcessInstance) processInstance).getVariable("person"));
// System.err.println("process parameter 'person': " + parameters.get("person"));
// System.err.println("global 'person2': " + statefulKnowledgeSession.getGlobal("person2"));
// org.jbpm.process.instance.ProcessInstance jbpmProcessInstance = (org.jbpm.process.instance.ProcessInstance) processInstance;
// VariableScopeInstance variableContextInstance = (VariableScopeInstance) jbpmProcessInstance.getContextInstance(VariableScope.VARIABLE_SCOPE);
// Map<String, Object> variables = variableContextInstance.getVariables();
//
// // System.err.println("process variables: " + variables.entrySet());
// final long processId = processInstance.getId();
// Map<String, Object> variables2 = statefulKnowledgeSession.execute(
// new GenericCommand<Map<String, Object>>() {
// private static final long serialVersionUID = 1L;
//
// public Map<String, Object> execute(Context context) {
// StatefulKnowledgeSession ksession = ((KnowledgeCommandContext) context).getStatefulKnowledgesession();
// org.jbpm.process.instance.ProcessInstance processInstance = (org.jbpm.process.instance.ProcessInstance) ksession.getProcessInstance(processId);
// VariableScopeInstance variableScope = (VariableScopeInstance) processInstance.getContextInstance(VariableScope.VARIABLE_SCOPE);
// Map<String, Object> variables = variableScope.getVariables();
// return variables;
// }
// }
// );
//
// // System.err.println("process variables via command: " + variables2.entrySet());
// logger.close();
}
@Override
public void disposeStatefulKnowledgeSession(ProcessData processData) {
processData.getStatefulKnowledgeSession().dispose();
}
private Environment buildEnvironment(ThiefEntityManagerFactory thiefEntityManagerFactory) {
Environment env;
env = EnvironmentFactory.newEnvironment();
env.set(EnvironmentName.ENTITY_MANAGER_FACTORY, thiefEntityManagerFactory);
env.set(EnvironmentName.TRANSACTION_MANAGER, transactionManager);
return env;
}
}
<file_sep>package workflow.util;
public class PrintUtil {
public static void printErr(String message) {
// System.err.println("PRINT_UTIL " + message);
}
}
<file_sep>package workflow.rest.endpoint;
import javax.inject.Inject;
import workflow.taskprocessor.IWorkflowTaskHandler;
public class BusinessTaskRestEndpoint {
@Inject
private IWorkflowTaskHandler workflowTaskHandler;
public void finishTask(Long businessTaskId, String taskName) {
workflowTaskHandler.finishTask(businessTaskId, taskName);
}
}
<file_sep>package workflow.model;
import java.io.Serializable;
public class ProcessVariableDefinition implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private InputVariableTypeData type;
private EInputVariableScope inputVariableScope;
private InputVariableSelectionData inputVariableSelectionData;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public InputVariableTypeData getType() {
return type;
}
public void setType(InputVariableTypeData type) {
this.type = type;
}
public EInputVariableScope getInputVariableScope() {
return inputVariableScope;
}
public void setInputVariableScope(EInputVariableScope eInputVariableScope) {
this.inputVariableScope = eInputVariableScope;
}
public InputVariableSelectionData getInputVariableSelectionData() {
return inputVariableSelectionData;
}
public void setInputVariableSelectionData(InputVariableSelectionData inputVariableSelectionData) {
this.inputVariableSelectionData = inputVariableSelectionData;
}
}
<file_sep>package workflow.engine;
import java.util.concurrent.Future;
import workflow.model.ProcessData;
public interface Engine {
ProcessData run();
Future<ProcessData> runAsynchronously();
void proceed(ProcessData processData);
void resume(Integer sessionId, Long processInstanceId, Long workItemId, Boolean tryTrigger);
void disposeStatefulKnowledgeSession(ProcessData processData);
}
| 57d4b69efbed6077c6f170307992482b7b62f1cd | [
"Java"
] | 14 | Java | workline/workflow_application-jbpm | aaea7cc9b33ab227d25fb7a406a96b9edab99820 | ac8fbe181ca2acf79047bbe2486b7c073b62d8f5 |
refs/heads/main | <file_sep>crypto{0fb_15_5ymm37r1c4l_!!!11!}<file_sep>Here is my super-strong RSA implementation, because it's 1600 bits strong it should be unbreakable... at least I think so!
inferius.py
output.txt<file_sep>Change the Json value from Clothes to flag.
Solution : crypto{sh0pp1ng_f0r_fl4g5}<file_sep> PEM is a popular format for sending and receiving keys, certificates, and other cryptographic material. It looks like:
-----BEGIN RSA PUBLIC KEY-----
MIIBCgKC... (a whole bunch of base64)
-----END RSA PUBLIC KEY-----
It wraps base64-encoded data by a one-line header and footer to indicate how to parse the data within. Perhaps unexpectedly, it's important for there to be the correct number of hyphens in the header and footer, otherwise cryptographic tools won't be able to recognise the file.
The data that gets base64-encoded is DER-encoded ASN.1 values. Confused? Here is more information about what these acronyms mean but the complexity is there for historical reasons and going too deep into the details may drive you insane.
Extract the private key d as a decimal integer from this PEM-formatted RSA key.
privacy_enhanced_mail.pem
<file_sep>GCD FLAG : crypto{10245,-8404}<file_sep>from pwn import xor
Key1 = bytes.fromhex('<KEY>')
Key2_3 = bytes.fromhex('c1545756687e7573db23aa1c3452a098b71a7fbf0fddddde5fc1')
Flag = bytes.fromhex('04ee9855208a2cd59091d04767ae47963170d1660df7f56f5faf')
print(xor(Key1,Key2_3,Flag))<file_sep>connect to nc socket.cryptohack.org 13389 via terminal
in the next line pass:
{"document":"<KEY>"}
again when server says the documnet added
in the next line pass:
{"document":"<KEY>"}
there you go the flag
{"error": "Document system crash, leaking flag: crypto{m0re_th4n_ju5t_p1g30nh0le_pr1nc1ple}"}
when strings of same hash value tries to add to the system, it crashes and leaks the flag
so i got this string values in hex form @https://crypto.stackexchange.com/questions/1434/are-there-two-known-strings-which-have-the-same-md5-hash-value/15889#15889
<file_sep>Several of the challenges are dynamic and require you to talk to our challenge servers over the network. This allows you to perform man-in-the-middle attacks on people trying to communicate, or directly attack a vulnerable service. To keep things consistent, our interactive servers always send and receive JSON objects.
Python makes such network communication easy with the telnetlib module. Conveniently, it's part of Python's standard library, so let's use it for now.
For this challenge, connect to socket.cryptohack.org on port 11112. Send a JSON object with the key buy and value flag.
The example script below contains the beginnings of a solution for you to modify, and you can reuse it for later challenges.
Connect at nc socket.cryptohack.org 11112<file_sep>Used Google to find Subdomain
https://subdomainfinder.c99.nl/scans/2020-09-10/cryptohack.org
Flag: crypto{thx_redpwn_for_inspiration}<file_sep>After Conversion the solution is
Integer to Message Conversion flag :
crypto{3nc0d1n6_4ll_7h3_w4y_d0wn}<file_sep>Flag : crypto{aloha}<file_sep> The previous set of challenges showed how AES performs a keyed permutation on a block of data. In practice, we need to encrypt messages much longer than a single block. A block cipher mode of operation describes how to use a cipher like AES on such messages.
All block cipher modes have serious weaknesses when used incorrectly. The challenges in this category take you to a different section of the website where you can interact with APIs and exploit those weaknesses. Get yourself acquainted with the interface and use it to take your next flag!
Play at http://aes.cryptohack.org/block_cipher_starter
<file_sep>
#a= 12
#b= 8
a = 66528
b = 52920
if a < b:
b = b-a
def gcd(a,b):
while b!=0:
t = b
b = a % b
a = t
return a
print("GCD of given value is : {}".format(gcd(a,b)))<file_sep>M = 12
e = 65537
p = 17
q = 23
C = pow(M,e,(17*23))
print(C)<file_sep>Looking at Fermat's little theorem...
if p is prime, for every integer a:
pow(a, p) = a mod p
and, if p is prime and a is an integer coprime with p:
pow(a, p-1) = 1 mod p
So lets check
pow(273246787654, 65536) mod 65537
Notice that 65536 is exactly 65537-1,
If 273246787654 and 65537 are coprime,
then the result is one
Number obtained = 1<file_sep>JavaScript Object Signing and Encryption (JOSE) is a framework specifying ways to securely transmit information on the internet. It's most well-known for JSON Web Tokens (JWTs), which are used to authorise yourself on a website or application. JWTs typically do this by storing your "login session" in your browser after you have authenticated yourself by entering your username and password. In other words, the website gives you a JWT that contains your user ID, and can be presented to the site to prove who you are without logging in again. JWTs look like this:
<KEY>
You can recognise it because it's base64-encoded data split into three parts (separated by a .): the header, the payload, and the signature. In fact, it's a variant of base64 encoding, where the + and / have been replaced by different special characters since those characters can cause issues in URLs.
Some developers believe that the JWT encoding is like encryption, so they put sensitive data inside the tokens. To prove them wrong, decode the JWT above to find the flag. There are online tools to do this quickly, but working with Python's PyJWT library will prepare you best for future challenges. <file_sep>
from Crypto.Util.number import inverse, long_to_bytes
n = 742449129124467073921545687640895127535705902454369756401331
e = 3
ct = 39207274348578481322317340648475596807303160111338236677373
#factorized n from factordb.com and obtained below
p = 752708788837165590355094155871
q = 986369682585281993933185289261
N = (p-1)*(q-1)
d = inverse(e,N)
message = pow(ct, d, n)
decrypted = long_to_bytes(message)
print(decrypted)
<file_sep>Flag : crypto{Doom_Principle_Strikes_Again}
Generate a token by setting admin = true, changing private to public key and algorithm to HS256 and put it in token field of Play at section in http://web.cryptohack.org/rsa-or-hmac/ to get the flag<file_sep>My boss has so many emails he's set up a server to just sign everything automatically. He also stores encrypted messages to himself for easy access. I wonder what he's been saying.
Connect at nc socket.cryptohack.org 13374
13374.py<file_sep>Flag : crypto{X0Rly_n0t!}<file_sep>#!/usr/bin/env python3
from Crypto.Util.number import getPrime, inverse, bytes_to_long, long_to_bytes
n = 110581795715958566206600392161360212579669637391437097703685154237017351570464767725324182051199901920318211290404777259728923614917211291562555864753005179326101890427669819834642007924406862482343614488768256951616086287044725034412802176312273081322195866046098595306261781788276570920467840172004530873767
e = 1
ct = 44981230718212183604274785925793145442655465025264554046028251311164494127485
d = -1
#The relationship between N, e, and d is given by:
#d*e = 1 mod (p-1)(q-1)
#if we pick e =1, then d = 1 mod (p-1)(q-1)
#cipher text c = m^e (mod N) i.e. c = m mod N but m < N so m mod N is m so we have c = m
#decrypting given ct will give the flag
#referred from stackoverflow https://stackoverflow.com/questions/17490282/why-is-this-commit-that-sets-the-rsa-public-exponent-to-1-problematic
decrypted = long_to_bytes(ct)
print(decrypted)
<file_sep>from Crypto.Util.number import long_to_bytes
integer = 11515195063862318899931685488813747395775516287289682636499965282714637259206269
string_value = long_to_bytes(integer)
print("Integer to Message Conversion flag :")
print(string_value)
<file_sep>#101^17 mod 22663
a = 101
p = 22663
n = 17
print(pow(a,n,p))<file_sep>b'crypto{s0m3th1ng5_c4n_b3_t00_b1g}'<file_sep>I read that AES keys should be randomly-generated bytes. But I want to use a password, and aren't MD5 hashes just as good?
For this challenge you may script your HTTP requests to the endpoints, or alternatively attack the ciphertext offline. Good luck!
Play at http://aes.cryptohack.org/passwords_as_keys<file_sep>p = 29
ints = [14, 6, 11]
value = [a for a in range(p) if pow(a,2,p) in ints]
print(min(value))
<file_sep>import base64
Hex_String = "<KEY>"
byte_value = bytearray.fromhex(Hex_String)
base64_value = base64.b64encode(byte_value)
print("Byte to Base64 Conversion flag :")
print(base64_value)
<file_sep>After Conversion the solution is
Byte to Base64 Conversion flag :
crypto/Base+64+Encoding+is+Web+Safe/'<file_sep>We have a supercomputer at work, so I've made sure my encryption is secure by picking massive numbers!
source.py
output.txt<file_sep>Flag : crypto{3ucl1d_w0uld_b3_pr0ud}
#Took refrence from https://blog.maple3142.net/2020/12/12/cryptohack-writeups/<file_sep>After 100 iterations the flag obtained is crypto{3nc0d3_d3c0d3_3nc0d3}
Run pwntools_example.py <file_sep>Flag : crypto{inmatrix}<file_sep>import json
import requests
from binascii import unhexlify
encrypted_flag = requests.get(f'http://aes.cryptohack.org/block_cipher_starter/encrypt_flag/')
ciphertext = json.loads(encrypted_flag.content)['ciphertext']
print("Ciphertext : {}".format(ciphertext))
plaintext_hex = requests.get(f'http://aes.cryptohack.org/block_cipher_starter/decrypt/{ciphertext}/')
plaintext = (json.loads(plaintext_hex.content)['plaintext'])
print("Plaintext : {}".format(plaintext))
print("Flag : {}".format(unhexlify(plaintext)))<file_sep>In Quadratic Residues we learnt what it means to take the square root modulo an integer. We also saw that taking a root isn't always possible.
In the previous case when p = 29, even the simplest method of calculating the square root was fast enough, but as p gets larger, this method becomes wildly unreasonable.
Lucky for us, we have a way to check whether an integer is a quadratic residue with a single calculation thanks to Legendre. In the following, we will assume we are working modulo a prime p.
Before looking at Legendre's symbol, let's take a brief detour to see an interesting property of quadratic (non-)residues.
Quadratic Residue * Quadratic Residue = Quadratic Residue
Quadratic Residue * Quadratic Non-residue = Quadratic Non-residue
Quadratic Non-residue * Quadratic Non-residue = Quadratic Residue
Want an easy way to remember this? Replace "Quadratic Residue" with +1 and "Quadratic Non-residue" with -1, all three results are the same!
So what's the trick? The Legendre Symbol gives an efficient way to determine whether an integer is a quadratic residue modulo an odd prime p.
Legendre's Symbol: (a / p) ≡ a(p-1)/2 mod p obeys:
(a / p) = 1 if a is a quadratic residue and a ≢ 0 mod p
(a / p) = -1 if a is a quadratic non-residue mod p
(a / p) = 0 if a ≡ 0 mod p
Which means given any integer a, calculating pow(a,(p-1)/2,p) is enough to determine if a is a quadratic residue.
Now for the flag. Given the following 1024 bit prime and 10 integers, find the quadratic residue and then calculate its square root; the square root is your flag. Of the two possible roots, submit the larger one as your answer.
So Legendre's symbol tells us which integer is a quadratic residue, but how do we find the square root?! The prime supplied obeys p = 3 mod 4, which allows us easily compute the square root. The answer is online, but you can figure it our yourself if you think about Fermat's little theorem.<file_sep> Poor Johan has been answering emails all day and the students are all asking the same questions. Can you read his messages?
johan.py
output.txt<file_sep>
def gcd_extended(a,b):
if a==0:
return b,0,1
gcd, p1, q1 = gcd_extended(b%a,a)
x = q1-(b//a)*p1
y = p1
return gcd, x, y
p = 26513
q = 32321
gcd, u, v = gcd_extended(p,q)
print("GCD FLAG : crypto{{{},{}}}".format(u,v))<file_sep>GCD of given value is : 1512<file_sep>{'flag': 'crypto{jwt_contents_can_be_easily_viewed}<file_sep>from Crypto.Util.number import inverse
#x ≡ 2 mod 5
#x ≡ 3 mod 11
#x ≡ 5 mod 17
#https://faculty.math.illinois.edu/~ruan/347Sp18HW/HW12sol.pdf
#x = a1N1y1 + a2N2y2 + a3N3y3 (mod N)
#y1 = inverse(n2*n3,n1)
#y2 = inverse(n1*n3,n2)
#y3 = inverse(n1*n2,n3)
print((2*11*17*inverse(11*17,5) + 3*5*17*inverse(5*17,11) + 5*5*11*inverse(5*11,17)) % 935)<file_sep># a ≡ b mod m.
# 11 ≡ a mod 6
# Can be written as a = 11 % 6
a = 11 % 6
print(a)
#8146798528947 ≡ b mod 17
# Can be written as b = 8146798528947 % 17
b = 8146798528947 % 17
print(b)
<file_sep>Solution smallest of two integers
: 4<file_sep>p = 28151
g = 2
flag = False
while not flag:
for n in range(2,p):
if pow(g,n,p) ==1:
break
if n == p-2:
print(g)
flag = True
g=g+1<file_sep>p = 991
g = 209
#d = ?, such that g*d mod 991=1
for d in range(991):
if (g*d)%991==1:
print(d)
break<file_sep>Flag = crypto{The_Cryptographic_Doom_Principle}
Generate a new token Using none algorithm and set admin value to true as mentioned below
def create_session(username):
encoded = jwt.encode({'username': username, 'admin': True}, SECRET_KEY, algorithm="none")
return {"session": encoded.decode()}
Secret key will be empty, no need to worry
After generating the token, head to Cryptohack.org and in the play at section place it under token and click submit, u will obtain the flag<file_sep>Used Factordb.com to solve this and obtained : 19704762736204164635843<file_sep>As mentioned in the previous challenge, PEM is just a nice wrapper above DER encoded ASN.1. In some cases you may come across DER files directly; for instance many Windows utilities prefer to work with DER files by default. However, other tools expect PEM format and have difficulty importing a DER file, so it's good to know how to convert one format to another.
An SSL certificate is a crucial part of the modern web, binding a cryptographic key to details about an organisation. We'll cover more about these and PKI in the TLS category. Presented here is a DER-encoded x509 RSA certificate. Find the modulus of the certificate, giving your answer as a decimal.
2048b-rsa-example-cert.der<file_sep>b'crypto{1f_y0u_Kn0w_En0uGH_y0u_Kn0w_1t_4ll}'<file_sep># Cryptohack.org CTFs done for College assignment
<file_sep>Decrypted Message : 13371337 <file_sep>Check out my document system about particle physics, where every document is uniquely referenced by hash.
Connect at nc socket.cryptohack.org 13389
13389.py<file_sep>Flag : crypto{r0undk3y}<file_sep>Single word : Authorization<file_sep>import jwt
Token = '<KEY>'
str = jwt.decode(Token, verify=False)
print(str)<file_sep>Finding large primes is slow, so I've devised an optimisation.
descent.py
output.txt<file_sep> <NAME>
Professor in Computer Science in the Theoretical Computer Science
Group at the School of Computer Science and Communication at KTH Royal Institute of Technology in Stockholm, Sweden.
Flag: crypto{1f_y0u_d0nt_p4d_y0u_4r3_Vuln3rabl3}<file_sep>In Legendre Symbol we introduced a fast way to determine whether a number is a square root modulo a prime. We can go further: there are algorithms for efficiently calculating such roots. The best one in practice is called Tonelli-Shanks, which gets its funny name from the fact that it was first described by an Italian in the 19th century and rediscovered independently by <NAME> in the 1970s.
All primes that aren't 2 are of the form p ≡ 1 mod 4 or p ≡ 3 mod 4, since all odd numbers obey these congruences. As the previous challenge hinted, in the p ≡ 3 mod 4 case, a really simple formula for computing square roots can be derived directly from Fermat's little theorem. That leaves us still with the p ≡ 1 mod 4 case, so a more general algorithm is required.
In a congruence of the form r2 ≡ a mod p, Tonelli-Shanks calculates r.
Tonelli-Shanks doesn't work for composite (non-prime) moduli. Finding square roots modulo composites is computationally equivalent to integer factorization.
The main use-case for this algorithm is finding elliptic curve co-ordinates. Its operation is somewhat complex so we're not going to discuss the details, however, implementations are easy to find and Sage has one built-in.
Find the square root of a modulo the 2048-bit prime p. Give the smaller of the two roots as your answer.
output.txt<file_sep>import base64
import json
import jwt # note this is the PyJWT module, not python-jwt
SECRET_KEY = 'secret' #key from PyJWT https://pyjwt.readthedocs.io/en/stable/
def create_session(username):
encoded = jwt.encode({'username': username, 'admin': True}, SECRET_KEY, algorithm="HS256")
return {"session": encoded.decode()}
token = create_session('admin')
print(token)
<file_sep>The Solution obtained is : 9<file_sep>We'll pick up from the last challenge and imagine we've picked a modulus p, and we will restrict ourselves to the case when p is prime.
The integers modulo p define a field, denoted Fp.
If the modulus is not prime, the set of integers modulo n define a ring.
A finite field Fp is the set of integers {0,1,...,p-1}, and under both addition and multiplication there is an inverse element b for every element a in the set, such that a + b = 0 and a * b = 1.
A field is a general name for a commutative ring in which every non-zero element has a multiplicative inverse.
Note that the identity element for addition and multiplication is different! This is because the identity when acted with the operator should do nothing: a + 0 = a and a * 1 = a.
Lets say we pick p = 17. Calculate 317 mod 17. Now do the same but with 517 mod 17.
What would you expect to get for 716 mod 17? Try calculating that.
This interesting fact is known as Fermat's little theorem. We'll be needing this (and its generalisations) when we look at RSA cryptography.
Now take the prime p = 65537. Calculate 27324678765465536 mod 65537.
Did you need a calculator? <file_sep>Flag obtained : crypto{k3y5__r__n07__p455w0rdz?}<file_sep>Hex_String = "<KEY>"
byte_value = bytearray.fromhex(Hex_String)
print("HEX to Byte Conversion flag :")
print(byte_value)<file_sep>My primes should be more than large enough now!
modulus_inutilis.py
output.txt<file_sep>Smallest exponent should be fastest, right?
salty.py
output.txt<file_sep>The following integers: 588, 665, 216, 113, 642, 4, 836, 114, 851, 492, 819, 237 are successive large powers of an integer x, modulo a three digit prime p.
Find p and x to obtain the flag.
You can do this with a pen and paper. We've included this challenge as an excuse for you to get used to algebra and modular mathematics.<file_sep>Flag : crypto{0x10_15_my_f4v0ur173_by7e}<file_sep>After Conversion the solution is
crypto{You_will_be_working_with_hex_strings_a_lot}<file_sep>The most common signing algorithms used in JWTs are HS256 and RS256. The first is a symmetric signing scheme using a HMAC with the SHA256 hash function. The second is an asymmetric signing scheme based on RSA.
A lot of guides on the internet recommend using HS256 as it's more straightforward. The secret key used to sign a token is the same as the key used to verify it.
However, if the signing secret key is compromised, an attacker can sign arbitrary tokens and forge sessions of other users, potentially causing total compromise of a webapp. HS256 makes the secret key harder to secure than an asymmetric keypair, as the key must be available on all servers that verify HS256 tokens (unless better infrastructure with a separate token verifying service is in place, which usually isn't the case). In contrast, with the asymmetric scheme of RS256, the signing key can be better protected while the verifying key is distributed freely.
Even worse, developers sometimes use a default or weak HS256 secret key.
Here is a snippet of source code with one function to create a session and another function to authorise a session and check for admin permissions. But there's a strange comment about the secret key. What are you going to do?
Play at http://web.cryptohack.org/jwt-secrets<file_sep>I've encrypted the flag with my secret key, you'll never be able to guess it.
Remember the flag format and how it might help you in this challenge!
0e0b213f26041e480b26217f27342e175d0e070a3c5b103e2526217f27342e175d0e077e263451150104<file_sep>So far we've been using the product of small primes for the modulus, but small primes aren't much good for RSA as they can be factorised using modern methods.
What is a "small prime"? There was an RSA Factoring Challenge with cash prizes given to teams who could factorise RSA moduli. This gave insight to the public into how long various key sizes would remain safe. Computers get faster, algorithms get better, so in cryptography it's always prudent to err on the side of caution.
These days, using primes that are at least 1024 bits long is recommended—multiplying two such 1024 primes gives you a modulus that is 2048 bits large. RSA with a 2048-bit modulus is called RSA-2048.
Some say that to really remain future-proof you should use RSA-4096 or even RSA-8192. However, there is a tradeoff here; it takes longer to generate large prime numbers, plus modular exponentiations are predictably slower with a large modulus.
Factorise the 150-bit number 510143758735509025530880200653196460532653147 into its two constituent primes. Give the smaller one as your answer. <file_sep>import base64
import json
import jwt # note this is the PyJWT module, not python-jwt
SECRET_KEY = ''
def create_session(username):
encoded = jwt.encode({'username': username, 'admin': True}, SECRET_KEY, algorithm="none")
return {"session": encoded.decode()}
token = create_session('admin')
print(token)
<file_sep>import jwt # note this is the PyJWT module, not python-jwt
import requests
url = "http://web.cryptohack.org"
PUBLIC_KEY = "/rsa-or-hmac/get_pubkey/"
username = 'admin'
resp = requests.get(url+PUBLIC_KEY)
pubkey = resp.json()
key = pubkey['pubkey']
print(key)
encoded = jwt.encode({'username': username, 'admin': True}, key, algorithm='HS256')
print(encoded)
<file_sep># Import the necessary libraries
from PIL import Image
import numpy as np
# creating a image1 object
im1 = Image.open("CryptoHack/General/XOR/Lemur XOR/lemur.png")
numpydata = np.array(im1)
# creating a image2 object
im2 = Image.open("CryptoHack/General/XOR/Lemur XOR/flag.png")
numpydata1 = np.array(im2)
numpydata2 = np.bitwise_xor(numpydata,numpydata1)
# image from our numpyarray
Image.fromarray(numpydata2).show()
<file_sep>from Crypto.Cipher import AES
import hashlib
import json
import requests
import binascii
response = requests.get(f'http://aes.cryptohack.org/passwords_as_keys/encrypt_flag/')
ciphertext = json.loads(response.content)['ciphertext']
with open("/usr/share/dict/words") as f:
for words in f:
words = words.strip()
KEY = hashlib.md5(words.encode()).digest()
ciphertextfromhex = bytes.fromhex(ciphertext)
cipher = AES.new(KEY, AES.MODE_ECB)
try:
decrypted = cipher.decrypt(ciphertextfromhex)
if decrypted.startswith('crypto{'.encode()):
print("Flag obtained : {}".format(decrypted.decode('utf-8')))
break
except ValueError as e:
print(str(e))<file_sep>crypto{MYAES128}
Note: Tried to decrypt as said in Website but didn't worked so tried different method to decrypt<file_sep>
given_String = "label"
flag = ''
for i in given_String:
flag += chr(ord(i)^13)
print('crypto{{{}}}'.format(flag))<file_sep>When you connect to a website over HTTPS, the first TLS message sent by the server is the ServerHello containing the server TLS certificate. Your browser verifies that the TLS certificate is valid, and if not, will terminate the TLS handshake. Verification includes ensuring that:
- the name on the certificate matches the domain
- the certificate has not expired
- the certificate is ultimately signed (via a "chain of trust") by a root key of a Certificate Authority (CA) that's trusted by your browser or operating system
Since CAs have the power to sign any certificate, the security of the internet depends upon these organisations to issue TLS certificates to the correct people: they must only issue certificates to the real domain owners. However with Windows trusting root certificates from over 100 organisations by default, there's a number of opportunities for hackers, politics, or incompetence to break the whole model. If you could trick just a single CA to issue you a certificate for microsoft.com, you could use the corresponding private key to sign malware and bypass trust controls on Windows. CAs are strongly incentivised to be careful since their business depends upon people trusting them, however in practice they have failed several times.
In 2011 Comodo CA was compromised and the hacker was able to issue certificates for Gmail and other services. In 2016, Symantec was found to have issued over 150 certificates without the domain owner's knowledge, as well as 2400 certificates for domains that were never registered.
Due to such events, together with the fact that fraudulent certificates can take a long time to be discovered, since 2018 Certificate Transparency has been enforced by Google Chrome. Every CA must publish all certificates that they issue to a log, which anyone can search.
Attached is an RSA public key in PEM format. Find the subdomain of cryptohack.org which uses these parameters in its TLS certificate, and visit that subdomain to obtain the flag.
transparency.pem<file_sep>Okay so I got a bit carefree with my last script, but this time I've protected myself while keeping everything really big. Nothing will stop me and my supercomputer now!
source.py
output.txt<file_sep>Using one prime factor was definitely a bad idea so I'll try using over 30 instead.
If it's taking forever to factorise, read up on factorisation algorithms and make sure you're using one that's optimised for this scenario.<file_sep>
number = [99, 114, 121, 112, 116, 111, 123, 65, 83, 67, 73, 73, 95, 112, 114, 49, 110, 116, 52, 98, 108, 51, 125]
print("The ASCII Value to get Flag")
print("".join(chr(o) for o in number))
<file_sep>After Conversion the solution is
crypto{ASCII_pr1nt4bl3}<file_sep>
def matrix2bytes(matrix):
""" Converts a 4x4 matrix into a 16-byte array. """
m2b = []
for i in range(0,4):
for j in range(0,4):
m2b.append(matrix[i][j])
return m2b
def flagex(m2b):
Flag = ""
for i in m2b:
Flag+= chr(i)
return Flag
matrix = [
[99, 114, 121, 112],
[116, 111, 123, 105],
[110, 109, 97, 116],
[114, 105, 120, 125],
]
mat2bytes = matrix2bytes(matrix)
print(flagex(mat2bytes))
<file_sep>state = [
[206, 243, 61, 34],
[171, 11, 93, 31],
[16, 200, 91, 108],
[150, 3, 194, 51],
]
round_key = [
[173, 129, 68, 82],
[223, 100, 38, 109],
[32, 189, 53, 8],
[253, 48, 187, 78],
]
def flagex(m2b):
Flag = ""
for i in m2b:
Flag+= chr(i)
return Flag
def add_round_key(s, k):
matrix = list()
for i in range(0,4):
for j in range(0,4):
matrix.append(s[i][j]^k[i][j])
return matrix
roundkey = add_round_key(state, round_key)
print(flagex(roundkey))
<file_sep>
from Crypto.PublicKey import RSA
pem = open("CryptoHack/General/Data Formats/Privacy-Enhanced Mail/privacy_enhanced_mail.pem","r")
rsa_key = RSA.importKey(pem.read())
print(rsa_key.d)<file_sep> Let's look at JWT algorithms. The first part of a JWT is the JOSE header, and when you decode it, looks like this:
{"typ":"JWT","alg":"HS256"}
This tells the server it's a JWT and which algorithm to use to verify it. Can you see the issue here? The server has to process this untrusted input before it is actually able to verify the integrity of the token! In ideal cryptographic protocols, you verify messages you receive before performing any further operations on them, otherwise in Moxie Marlinspike's words, "it will somehow inevitably lead to doom".
The "none" algorithm in JWTs is a case in point. The link below takes you to a page where you can interact with a broken session API, which emulates a vulnerability that existed in a lot of JWT libraries. Use it to bypass authorisation and get the flag.
Play at http://web.cryptohack.org/no-way-jose
<file_sep>Imagine you lean over and look at a cryptographer's notebook. You see some notes in the margin:
4 + 9 = 1
5 - 7 = 10
2 + 3 = 5
At first you might think they've gone mad. Maybe this is why there are so many data leaks nowadays you'd think, but this is nothing more than modular arithmetic modulo 12 (albeit with some sloppy notation).
You may not have been calling it modular arithmetic, but you've been doing these kinds of calculations since you learnt to tell the time (look again at those equations and think about adding hours).
Formally, "calculating time" is described by the theory of congruences. We say that two integers are congruent modulo m if a ≡ b mod m.
Another way of saying this, is that when we divide the integer a by m, the remainder is b. This tells you that if m divides a (this can be written as m | a) then a ≡ 0 mod m.
Calculate the following integers:
11 ≡ a mod 6
8146798528947 ≡ b mod 17
The solution is the smaller of the two integers. <file_sep>The Chinese Remainder Theorem gives a unique solution to a set of linear congruences if their moduli are coprime.
This means, that given a set of arbitrary integers ai, and pairwise coprime integers ni, such that the following linear congruences hold:
Note "pairwise coprime integers" means that if we have a set of integers {n1, n2, ..., ni}, all pairs of integers selected from the set are coprime: gcd(ni, nj) = 1.
x ≡ a1 mod n1
x ≡ a2 mod n2
...
x ≡ an mod nn
There is a unique solution x ≡ a mod N where N = n1 * n2 * ... * nn.
In cryptography, we commonly use the Chinese Remainder Theorem to help us reduce a problem of very large integers into a set of several, easier problems.
Given the following set of linear congruences:
x ≡ 2 mod 5
x ≡ 3 mod 11
x ≡ 5 mod 17
Find the integer a such that x ≡ a mod 935
Starting with the congruence with the largest modulus, use that for x ≡ a mod p we can write x = a + k*p for arbitrary integer k.<file_sep>#3 * d ≡ 1 mod 13?
#reference https://cp-algorithms.com/algebra/module-inverse.html
a = 3
p = 13
print(pow(a,p-2) % p)<file_sep>Apart from the KeyExpansion phase, we've sketched out all the components of AES. We've shown how SubBytes provides confusion and ShiftRows and MixColumns provide diffusion, and how these two properties work together to repeatedly circulate non-linear transformations over the state. Finally, AddRoundKey seeds the key into this substitution-permutation network, making the cipher a keyed permutation.
Decryption involves performing the steps described in the "Structure of AES" challenge in reverse, applying the inverse operations. Note that the KeyExpansion still needs to be run first, and the round keys will be used in reverse order. AddRoundKey and its inverse are identical due to XOR being associative.
We've provided the key expansion code, and ciphertext that's been properly encrypted by AES-128. Copy in all the building blocks you've coded so far, and complete the decrypt function that implements the steps shown in the diagram. The decrypted plaintext is the flag.
Yes, you can cheat on this challenge, but where's the fun in that?
The code used in these exercises has been taken from Bo Zhu's super simple Python AES implementation, so we've reproduced the license here.
aes_decrypt.py
LICENSE<file_sep>data = "<KEY>"
decoded_hex = bytes.fromhex(data)
print("Hex value of Data is {}".format(decoded_hex))
print(''.join(chr(c ^ (decoded_hex[0]^ord('c'))) for c in decoded_hex))
<file_sep>from pwn import xor
string = bytes.fromhex('0e0b213f26041e480b26217f27342e175d0e070a3c5b103e2526217f27342e175d0e077e263451150104')
# as we already know the flag format i.e crypto{}
flag = xor(string[:7], 'crypto{') + xor(string[-1], '}')
print(flag)
print(xor(string, flag))<file_sep>Flag : crypto{x0r_i5_ass0c1at1v3}<file_sep>I asked my friends to encrypt our secret flag before sending it to me, but instead of using my key, they've all used their own! Can you help?
source.py
output.txt<file_sep>import json
import requests
from binascii import unhexlify
response = requests.get(f'http://aes.cryptohack.org/symmetry/encrypt_flag/')
ivciphertext = json.loads(response.content)['ciphertext']
print("Response combined with iv and Cipher text : {}".format(ivciphertext))
iv = ivciphertext[:32]#First 32 is Initialization vector
print("iv seprated from Cipher text : {}".format(iv))
ciphertext = ivciphertext[32:] #Remainingthat is from 32 onwards it will be cipher text
print("Final Cipher text obtained : {}".format(ciphertext))
response = requests.get(f'http://aes.cryptohack.org/symmetry/encrypt/{ciphertext}/{iv}/')
print(unhexlify(json.loads(response.content)['ciphertext']))<file_sep>Get the Encrypt Flag and pass it to Decrypt Flag and then pass it to hex decoder to obtain Flag
Before the code was not written, directly the above method is followed, now the code and solution added
crypto{bl0ck_c1ph3r5_4r3_f457_!}<file_sep>It was taking forever to get a 2048 bit prime, so I just generated one and used it twice.
If you're stuck, look again at the formula for Euler's totient.
output.txt<file_sep>We've looked at multiplication and division in modular arithmetic, but what does it mean to take the square root modulo an integer?
For the following discussion, let's work modulo p = 29. We can take the integer a = 11 and calculate a2 = 5 mod 29.
As a = 11, a2 = 5, we say the square root of 5 is 11.
This feels good, but now let's think about the square root of 18. From the above, we know we need to find some integer a such that a2 = 18
Your first idea might be to start with a = 1 and loop to a = p-1. In this discussion p isn't too large and we can quickly look.
Have a go, try coding this and see what you find. If you've coded it right, you'll find that for all a ∈ Fp* you never find an a such that a2 = 18.
What we are seeing, is that for the elements of F*p, not every element has a square root. In fact, what we find is that for roughly one half of the elements of Fp*, there is no square root.
We say that an integer x is a Quadratic Residue if there exists an a such that a2 = x mod p. If there is no such solution, then the integer is a Quadratic Non-Residue.
In other words, x is a quadratic residue when it is possible to take the square root of x modulo an integer p.
In the below list there are two non-quadratic residues and one quadratic residue.
Find the quadratic residue and then calculate its square root. Of the two possible roots, submit the smaller one as the flag.
If a2 = x then (-a)2 = x. So if x is a quadratic residue in some finite field, then there are always two solutions for a.
p = 29
ints = [14, 6, 11] <file_sep>Flag : crypto{sh4r1ng_s3cret5_w1th_fr13nd5}<file_sep>Some block cipher modes, such as OFB, CTR, or CFB, turn a block cipher into a stream cipher. The idea behind stream ciphers is to produce a pseudorandom keystream which is then XORed with the plaintext. One advantage of stream ciphers is that they can work of plaintext of arbitrary length, with no padding required.
OFB is an obscure cipher mode, with no real benefits these days over using CTR. This challenge introduces an unusual property of OFB.
Play at http://aes.cryptohack.org/symmetry<file_sep>There's another issue caused by allowing attackers to specify their own algorithms but not carefully validating them. Attackers can mix and match the algorithms that are used to sign and verify data. When one of these is a symmetric algorithm and one is an asymmetric algorithm, this creates a beautiful vulnerability.
We've made a one-line change to the PyJWT library source code for this challenge to allow the exploit, since the library now blocks it. To create the signature, you may need to patch your JWT library too.
Play at http://web.cryptohack.org/rsa-or-hmac<file_sep>Flag = crypto{jwt_secret_keys_must_be_protected}
encode with Secret key as 'secret' referred from "https://pyjwt.readthedocs.io/en/stable/"
and put the token in Play at section and get the flag<file_sep> The traditional way to store sessions is with session ID cookies. After you login to a website, a session object is created for you on the backend (the server), and your browser (the client) is given a cookie which identifies that object. As you make requests to the site, your browser automatically sends the session ID cookie to the backend server, which uses that ID to find your session in its own memory and thus authorise you to perform actions.
JWTs work differently. After you login, the server sends your web browser the whole session object in a JWT, containing a payload of key-value pairs describing your username, privileges, and other info. Also included is a signature created using the server's secret key, designed to prevent you from tampering with the payload. Your web browser saves the token into local storage.
diagram showing JWT usage
On subsequent requests, your browser sends the token to the backend server. The server verifies the signature first, and then reads the token payload to authorise you.
To summarise, with session ID cookies, sessions live on the server, but with JWTs, sessions live on the client.
The main advantage of JWTs over session ID cookies is that they are easy to scale. Organisations need a way to share sessions across multiple backend servers. When a client switches from using one server or resource to another, that client's session should still work. Furthermore, for large orgs there could be millions of sessions. Since JWTs live on the client, they solve these problems: any backend server can authorise a user just by checking the signature on the token and reading the data inside.
Unfortunately there are some downsides to JWTs, as they are often configured in an insecure way, and clients are free to modify them and see if the server will still verify them. We'll look at these exploits in the next challenges. For now, the flag is the name of the HTTP header used by the browser to send JWTs to the server. <file_sep>Why is everyone so obsessed with multiplying two primes for RSA. Why not just use one?
output.txt<file_sep>Here's a bunch of RSA public keys I gathered from people on the net together with messages that they sent.
As excerpt.py shows, everyone was using PKCS#1 OAEP to encrypt their own messages. It shouldn't be possible to decrypt them, but perhaps there are issues with some of the keys?
excerpt.py
keys_and_messages.zip<file_sep>from ast import literal_eval
#Execute below statement to obtain pem file from der
#openssl x509 -in 2048b-rsa-example-cert.der -inform der -out 2048b-rsa-DER-to-PEM.pem
#Get the Modulus value from the pem File by executing below command
#openssl x509 -in 2048b-rsa-DER-to-PEM.pem -text -noout
#https://megamorf.gitlab.io/cheat-sheets/openssl/
#Obtain the the Modulus value and find the decimal value
Modulus = "00:b4:cf:d1:5e:33:29:ec:0b:cf:ae:76:f5:fe:2d:c8:99:c6:78:79:b9:18:f8:0b:d4:ba:b4:d7:9e:02:52:06:09:f4:18:93:4c:d4:70:d1:42:a0:29:13:92:73:50:77:f6:04:89:ac:03:2c:d6:f1:06:ab:ad:6c:c0:d9:d5:a6:ab:ca:cd:5a:d2:56:26:51:e5:4b:08:8a:af:cc:19:0f:25:34:90:b0:2a:29:41:0f:55:f1:6b:93:db:9d:b3:cc:dc:ec:eb:c7:55:18:d7:42:25:de:49:35:14:32:92:9c:1e:c6:69:e3:3c:fb:f4:9a:f8:fb:8b:c5:e0:1b:7e:fd:4f:25:ba:3f:e5:96:57:9a:24:79:49:17:27:d7:89:4b:6a:2e:0d:87:51:d9:23:3d:06:85:56:f8:58:31:0e:ee:81:99:78:68:cd:6e:44:7e:c9:da:8c:5a:7b:1c:bf:24:40:29:48:d1:03:9c:ef:dc:ae:2a:5d:f8:f7:6a:c7:e9:bc:c5:b0:59:f6:95:fc:16:cb:d8:9c:ed:c3:fc:12:90:93:78:5a:75:b4:56:83:fa:fc:41:84:f6:64:79:34:35:1c:ac:7a:85:0e:73:78:72:01:e7:24:89:25:9e:da:7f:65:bc:af:87:93:19:8c:db:75:15:b6:e0:30:c7:08:f8:59"
str = Modulus.replace(":","")
print(int(str,16))
<file_sep>from Crypto.Util.number import inverse
p = 857504083339712752489993810777
q = 1029224947942998075080348647219
e = 65537
N = (p-1)*(q-1)
print(N)
d = inverse(e,N)
print("Private Key : {} ".format(d))<file_sep>from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from itertools import combinations
from math import gcd
#reading pem file to get n and e and appending it into keys list
keys = []
for i in range(1, 51):
with open(f'/home/gubbs/Downloads/keys_and_messages/{i}.pem') as f:
keys.append((i, RSA.import_key(f.read())))
#Taking combinations from the imported keys.
for (i, key1), (j, key2) in combinations(keys, 2):
p = gcd(key1.n, key2.n)
if p == 1: # other than 1 jump next if not loop again
continue
q1 = key1.n//p
q2 = key2.n//p
pkey1 = RSA.construct((key1.n, key1.e, pow(key1.e, -1, (p-1)*(q1-1)), p, q1)) # constructing all values, p,q, n, e, d
pkey2 = RSA.construct((key2.n, key2.e, pow(key2.e, -1, (p-1)*(q2-1)), p, q2))
with open(f'/home/gubbs/Downloads/keys_and_messages/{i}.ciphertext') as f:
print(PKCS1_OAEP.new(pkey1).decrypt(bytes.fromhex(f.read()))) #decrypting the cipher using the available keys
with open(f'/home/gubbs/Downloads/keys_and_messages/{j}.ciphertext') as f:
print(PKCS1_OAEP.new(pkey2).decrypt(bytes.fromhex(f.read())))
| 24ff9eba5e669e7a203058440f76c9f9a99117c6 | [
"Markdown",
"Python"
] | 106 | Markdown | Sharath-Cy/CTFs | ffe0af8eec23edb24f4ecefc9c0f00d552579beb | 2fe7300cf121c26bfb068586df0a9d786eb9ac4b |
refs/heads/main | <repo_name>agri-chip-reader/quickchip-backend<file_sep>/src/main/java/controller/HomeController.java
package controller;
import business.AdminService;
import data.entities.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping
@CrossOrigin
public class HomeController {
@Autowired
private AdminService adminService;
@GetMapping
public String home(){
return "Hello Azure Changes!";
}
@PostMapping("/addViewer")
public User addUser(@RequestBody User user){
return adminService.addUser(user);
}
@PostMapping("/login")
public void login(@RequestBody User user){
adminService.authorize(user);
}
}
<file_sep>/README.md
# quickchip-backend
<file_sep>/src/main/java/business/ImagesService.java
package business;
import data.dto.UserInsert;
import data.entities.Images;
import data.repositories.ImageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
@Transactional
public class ImagesService {
@Autowired
private ImageRepository imagesRepository;
public List<String> getListImages(){
List<Images> imagesList =imagesRepository.findAll();
List<String> paths = new ArrayList<>();
for(Images image : imagesList){
paths.add(image.getPath());
}
return paths;
}
public Images addImage(UserInsert userInsert){
return imagesRepository.save(new Images(userInsert.getPath(),userInsert.getEmail()));
}
public void deleteImages(){
imagesRepository.deleteAll();
}
}
<file_sep>/src/main/java/business/ProcessImage.java
package business;
import org.springframework.stereotype.Service;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
@Service
public class ProcessImage {
private Image image = null;
private String path;
private void process() throws IOException {
URL url = new URL(path);
Image image = ImageIO.read(url);
}
public ProcessImage(String value) throws IOException {
this.path=value;
process();
}
public ProcessImage(){}
}
<file_sep>/src/main/java/controller/ViewerController.java
package controller;
import business.ImagesService;
import data.dto.UserInsert;
import data.entities.Images;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/view")
@CrossOrigin
public class ViewerController {
@Autowired
private ImagesService imagesService;
@GetMapping
public String home(){
return "Hello Azure Changes!";
}
@GetMapping("/all")
public List<String> getListImages(){
return imagesService.getListImages();
}
@PostMapping("/add")
public void addImage(@RequestBody UserInsert userInsert){
imagesService.addImage(userInsert);
}
@GetMapping("/deleteAll")
public void deleteAll(){
imagesService.deleteImages();
}
}
<file_sep>/src/main/java/data/entities/Images.java
package data.entities;
import javax.persistence.*;
import java.sql.Date;
import java.time.LocalDate;
@Entity
@Table(name = "images")
public class Images {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private long id;
@Column(name = "path")
private String path;
@Column(name = "userinsert")
private String userInsert;
@Column(name = "date")
private Date date;
public Images(String path, String userInsert) {
this.path = path;
this.userInsert = userInsert;
this.date=new Date(LocalDate.now().getYear(),LocalDate.now().getMonthValue(),LocalDate.now().getDayOfMonth());
}
public Images() {}
public long getId() {
return id;
}
public String getPath() {
return path;
}
public String getUserInsert() {
return userInsert;
}
public Date getDate() {
return date;
}
public void setPath(String path) {
this.path = path;
}
public void setUserInsert(String userInsert) {
this.userInsert = userInsert;
}
}
<file_sep>/src/main/java/com/agri/quickchip/QuickchipApplication.java
package com.agri.quickchip;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.io.Resource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.URL;
//import java.awt.*;
//import com.microsoft.azure.storage.blob.StorageURL;
@SpringBootApplication
@ComponentScan({"controller", "business" , "data"})
@EntityScan("data")
@EnableJpaRepositories("data.repositories")
public class QuickchipApplication {
public static void main(String[] args) throws IOException {
SpringApplication.run(QuickchipApplication.class, args);
}
}
| 7fd93e36b9904ef7d3fdc19be34d8d3a0f8ab1c9 | [
"Markdown",
"Java"
] | 7 | Java | agri-chip-reader/quickchip-backend | 4d5d3b5bed0eb00d53de501a9ba5f223a7506d0f | 9530e1b35a62f8bf7be8f71042f3034cf3f833b4 |
refs/heads/master | <repo_name>baldachin/LearnStock<file_sep>/demo01.py
import pandas as pd
from pandas_datareader import data as web
import datetime
start = datetime.datetime(2016,1,1)
end = datetime.date.today()
# 第一个参数是我们要获取股票数据的股票代码串,
# 第二个是源(“yahoo”代表Yahoo财经),
# 第三个是开始日期,第四个是结束日期
apple = web.get_data_yahoo("AAPL", start, end)
# print(apple.head())
import matplotlib.pyplot as plt # 导入matplotlib包
%matplotlib inline # 这条线是必要的在Jupyter notebook中显示plot
%pylab inline # 在这个Jupyter notebook中,控制图的默认大小
pylab.rcParams['figure.figsize'] = (15, 9) # 改变plot的大小
apple["Adj Close"].plot(grid = True) # plot AAPL调整后的收盘价 | 3268f28f6f713aee1e4b0041b9301ea7a2dc9dfb | [
"Python"
] | 1 | Python | baldachin/LearnStock | a993163f6bba5b4ca4b6770e1710ed4eb84ea1b8 | 557e0a9e3d94cd702d5ef02d0fe03696a30f2005 |
refs/heads/master | <repo_name>deebhatti/SeleniumJune14<file_sep>/README.md
# SeleniumJune14
an optional description can be provided here.
Some important instructions will come here
<file_sep>/TestNGDemo/src/demo/Annotations.java
package demo;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Annotations {
@BeforeSuite
public void beforeSuite(){
System.out.println("Before Suite will always execute prior to all"
+ "annotations in the suite");
}
@AfterSuite
public void afterSuite(){
System.out.println("After Suite will always execute at last afte"
+ "r all the annotations");
}
@BeforeClass
public void beforeClass(){
System.out.println("Before Class will always execute prior to "
+ "@BeforeMethod and @Test");
}
@AfterClass
public void afterClass(){
System.out.println("After Class will always execute later to @After"
+ "Method and @Test");
}
@BeforeMethod
public void beforeMEthod(){
System.out.println("Before Method will execute before every "
+ "@Test");
}
@AfterMethod
public void afterMethod(){
System.out.println("After Method is executed after every @Test");
}
@BeforeTest
public void beforeTest(){
System.out.println("Before Test will always execute prior to @Before"
+ "Class, @BeforeMEthod and @Test");
}
@AfterTest
public void afterTest(){
System.out.println("AfterTest will always execute later to @After"
+ "Method, @AfterClass");
}
@Test
public void testCase1(){
System.out.println("Inside first Test case");
}
@Test
public void testCase2(){
System.out.println("Inside second Test case");
}
}
| 69fb84d40ba0194131abc6642fe0a1bc8aba64b9 | [
"Markdown",
"Java"
] | 2 | Markdown | deebhatti/SeleniumJune14 | 5a32fd8088dd5bbc76c70a3d3cdb9385d34a7e0b | 04b4d47ccfaae67e538252c4296a0831688d3dd0 |
refs/heads/master | <file_sep>package com.youer.adapter;
import java.util.List;
import com.example.youer.R;
import com.way.app.PushApplication;
import com.way.bean.User;
import com.youer.adapter.PhotoGridAdapter.ViewHolder;
import com.youer.modal.MImage;
import com.youer.modal.MStory;
import com.youer.modal.MStory1;
import com.youer.tool.DensityUtil;
import com.youer.tool.Utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
public class HuibenDetailAdapter extends BaseAdapter {
List<Integer> m_storyList;
Context m_context;
LayoutInflater m_layoutInflater;
//float m_rate=(float)446/(float)630;
public HuibenDetailAdapter(Context context,List<Integer> storyList){
this.m_context=context;
this.m_storyList=storyList;
this.m_layoutInflater=LayoutInflater.from(m_context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return this.m_storyList.size();
}
@Override
public Object getItem(int index) {
// TODO Auto-generated method stub
return this.m_storyList.get(index);
}
@Override
public long getItemId(int index) {
// TODO Auto-generated method stub
return index;
}
@Override
public View getView(int index, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
int story=this.m_storyList.get(index);
ImageView imageView = null;
if (convertView == null) {
imageView = new ImageView(m_context);
//如果是横屏,GridView会展示4列图片,需要设置图片的大小
//imageView.setAdjustViewBounds(true);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
convertView=imageView;
// imageView.setPadding(3, 3, 3, 3);
} else {
imageView=(ImageView) convertView;
}
BitmapDrawable drawable;
// 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(m_context.getResources(), story, options);
// 调用上面定义的方法计算inSampleSize值
options.inSampleSize = Utils.calculateInSampleSize(options, options.outWidth, options.outHeight);
float rate=(float)options.outHeight/(float)options.outWidth;
// 使用获取到的inSampleSize值再次解析图片
options.inJustDecodeBounds = false;
Bitmap bitmap= BitmapFactory.decodeResource(m_context.getResources(),story, options);
drawable= new BitmapDrawable(m_context.getResources(), bitmap);
imageView.setImageDrawable(drawable);
ListView.LayoutParams lp;
lp=new ListView.LayoutParams(
DensityUtil.getLogicalWidth()-DensityUtil.dip2px(6),(int) ((DensityUtil.getLogicalWidth()
-DensityUtil.dip2px(6))*rate));
imageView.setLayoutParams(lp);
imageView.setPadding(DensityUtil.dip2px(3), DensityUtil.dip2px(3), DensityUtil.dip2px(3),DensityUtil.dip2px(3));
/**
* 最关键在此,把options.inJustDecodeBounds = true;
Bitmap bitmap; * 这里再decodeFile(),返回的bitmap为空,但此时调用options.outHeight时,已经包含了图片的高了
*/
imageView.setImageDrawable(drawable);
return convertView;
}
}
<file_sep>package com.youer.activity;
import java.util.List;
import com.example.youer.R;
import com.example.youer.R.layout;
import com.example.youer.R.menu;
import com.youer.adapter.HuibenAdapter;
import com.youer.adapter.HuibenDetailAdapter;
import com.youer.modal.MImage;
import com.youer.modal.MStory1;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class HuibenDetailActivity extends Activity implements OnClickListener {
ListView list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_huiben_detail);
final MStory1 story=(MStory1) getIntent().getSerializableExtra("story");
String title=story.mName;
TextView titleTxt=(TextView)findViewById(R.id.titile_txt);
if(title!=null&&!title.equalsIgnoreCase(""))
titleTxt.setText(title);
list=(ListView)findViewById(R.id.list);
HuibenDetailAdapter adapter=new HuibenDetailAdapter(this,story.mImgList);
list.setAdapter(adapter);
ImageView back=(ImageView)findViewById(R.id.back);
back.setOnClickListener(this);
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
this.finish();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
int count=list.getChildCount();
for(int i=0;i<count;i++){
View view=list.getChildAt(i);
if(view instanceof ImageView){
ImageView img=(ImageView)view;
BitmapDrawable bitmapDrawable=(BitmapDrawable) img.getDrawable();
if(bitmapDrawable!=null){
Bitmap bitmap=bitmapDrawable.getBitmap();
if(!bitmap.isRecycled()){
bitmap.recycle();
}
}
}
if(view instanceof ViewGroup){
ViewGroup container=(ViewGroup)view;
int childCount1=container.getChildCount();
for(int j=0;j<childCount1;j++){
View view1=container.getChildAt(j);
if(view1 instanceof ImageView){
ImageView img=(ImageView)view1;
BitmapDrawable bitmapDrawable=(BitmapDrawable) img.getDrawable();
if(bitmapDrawable!=null){
Bitmap bitmap=bitmapDrawable.getBitmap();
if(!bitmap.isRecycled()){
bitmap.recycle();
}
}
}
if(view1 instanceof ViewGroup){
ViewGroup container1=(ViewGroup)view1;
int childCount2=container1.getChildCount();
for(int k=0;k<childCount2;k++){
View view2=container1.getChildAt(k);
if(view2 instanceof ImageView){
ImageView img=(ImageView)view2;
BitmapDrawable bitmapDrawable=(BitmapDrawable) img.getDrawable();
if(bitmapDrawable!=null){
Bitmap bitmap=bitmapDrawable.getBitmap();
if(!bitmap.isRecycled()){
bitmap.recycle();
}
}
}
}
}
}
}
}
}
}
<file_sep>package com.youer.adapter;
import java.util.List;
import com.example.youer.R;
import com.youer.adapter.NewsAdapter2.ViewHolder1;
import com.youer.adapter.StoryAdapter.ViewHolder;
import com.youer.modal.MImage;
import com.youer.modal.MMedia;
import com.youer.modal.MNews;
import com.youer.modal.MStory;
import com.youer.modal.MVideo;
import com.youer.tool.DensityUtil;
import com.youer.tool.Utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class PhotoAdapter extends BaseAdapter {
Context m_context;
List<MMedia> m_mediaList;
LayoutInflater m_layoutInflater;
int width;
int height;
public PhotoAdapter(Context context,List<MMedia> mediaList){
this.m_context=context;
this.m_mediaList=mediaList;
this.m_layoutInflater=LayoutInflater.from(m_context);
this.height=this.width=DensityUtil.dip2px(200);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return this.m_mediaList.size();
}
@Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
MMedia media=this.m_mediaList.get(position);
if(media.mIsVideo)
return 1;
else
return 0;
}
@Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 2;
}
@Override
public Object getItem(int index) {
// TODO Auto-generated method stub
MMedia media=this.m_mediaList.get(index);
return media;
}
@Override
public long getItemId(int index) {
// TODO Auto-generated method stub
return index;
}
@Override
public View getView(int index, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
MMedia media=this.m_mediaList.get(index);
ViewHolder viewHolder=null;
int type = getItemViewType(index);
if (convertView!= null &&convertView.getTag()!=null)
viewHolder = (ViewHolder) convertView.getTag();
else{
if(type==0)
convertView=this.m_layoutInflater.inflate(R.layout.photo_item, null);
else
convertView=this.m_layoutInflater.inflate(R.layout.photo_item1, null);
viewHolder=new ViewHolder();
viewHolder.mTitleImageView=(ImageView) convertView.findViewById(R.id.title_img);
viewHolder.mTitleTxt=(TextView) convertView.findViewById(R.id.title);
convertView.setTag(viewHolder);
}
viewHolder.mTitleTxt.setText(media.mName);
if(media.mIsVideo){
List<MVideo> videoList=media.mVideoList;
if(videoList!=null&&videoList.size()>0){
MVideo video=videoList.get(0);
BitmapDrawable drawable;
Bitmap bitmap;
// 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
MImage image=video.mImage;
if(image.mIsLocal){
BitmapFactory.decodeResource(m_context.getResources(), image.mResourceId, options);
// 调用上面定义的方法计算inSampleSize值
options.inSampleSize = Utils.calculateInSampleSize(options, width, height);
// 使用获取到的inSampleSize值再次解析图片
options.inJustDecodeBounds = false;
bitmap= BitmapFactory.decodeResource(m_context.getResources(), image.mResourceId, options);
}
else{
BitmapFactory.decodeFile(image.mFilePath, options);
options.inSampleSize = Utils.calculateInSampleSize(options, width, height);
// 使用获取到的inSampleSize值再次解析图片
options.inJustDecodeBounds = false;
bitmap= BitmapFactory.decodeFile(image.mFilePath, options);
}
drawable= new BitmapDrawable(m_context.getResources(), bitmap);
viewHolder.mTitleImageView.setImageDrawable(drawable);
}
}else{
List<MImage> imageList=media.mPhotoList;
if(imageList!=null&&imageList.size()>0){
MImage image=imageList.get(0);
BitmapDrawable drawable;
Bitmap bitmap;
// 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
if(image.mIsLocal){
BitmapFactory.decodeResource(m_context.getResources(), image.mResourceId, options);
// 调用上面定义的方法计算inSampleSize值
options.inSampleSize = Utils.calculateInSampleSize(options, width, height);
// 使用获取到的inSampleSize值再次解析图片
options.inJustDecodeBounds = false;
bitmap= BitmapFactory.decodeResource(m_context.getResources(), image.mResourceId, options);
}
else{
BitmapFactory.decodeFile(image.mFilePath, options);
options.inSampleSize = Utils.calculateInSampleSize(options, width, height);
// 使用获取到的inSampleSize值再次解析图片
options.inJustDecodeBounds = false;
bitmap= BitmapFactory.decodeFile(image.mFilePath, options);
}
drawable= new BitmapDrawable(m_context.getResources(), bitmap);
viewHolder.mTitleImageView.setImageDrawable(drawable);
}
}
return convertView;
}
static class ViewHolder {
public TextView mTitleTxt;
public ImageView mTitleImageView;
}
}
<file_sep>package com.way.app;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import android.annotation.TargetApi;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.text.TextUtils;
import android.widget.RemoteViews;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.youer.activity.MainActivity;
import com.youer.modal.MChatMsgEntity;
import com.youer.modal.MUser;
import com.way.baidupush.client.PushMessageReceiver;
import com.way.baidupush.client.PushMessageReceiver.EventHandler;
import com.way.baidupush.server.BaiduPush;
import com.way.bean.Message;
import com.way.bean.User;
import com.way.common.util.SharePreferenceUtil;
import com.way.db.MessageDB;
import com.way.db.RecentDB;
import com.way.db.UserDB;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.example.youer.R;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class PushApplication extends Application implements EventHandler {
public final static String API_KEY = "<KEY>";
public final static String SECRIT_KEY = "<KEY>";
public static final String SP_FILE_NAME = "push_msg_sp";
public static final int[] heads = { R.drawable.h0, R.drawable.h1,
R.drawable.h2, R.drawable.h3, R.drawable.h4, R.drawable.h5,
R.drawable.h6, R.drawable.h7, R.drawable.h8, R.drawable.h9,
R.drawable.h10, R.drawable.h11, R.drawable.h12, R.drawable.h13,
R.drawable.h14, R.drawable.h15, R.drawable.h16, R.drawable.h17,
R.drawable.h18 };
public static final int[] heads1={R.drawable.laoshi1,R.drawable.jiazhang1};
public static final int NUM_PAGE = 6;// 总共有多少页
public static int NUM = 20;// 每页20个表情,还有最后一个删除button
private static PushApplication mApplication;
private BaiduPush mBaiduPushServer;
private Map<String, Integer> mFaceMap = new LinkedHashMap<String, Integer>();
private SharePreferenceUtil mSpUtil;
private UserDB mUserDB;
private MessageDB mMsgDB;
private RecentDB mRecentDB;
private List<User> mUserList;
private MediaPlayer mMediaPlayer;
private NotificationManager mNotificationManager;
private Notification mNotification;
private Gson mGson;
List<User> m_userList;
List<MChatMsgEntity> m_chatList=null;
int index=0;
public synchronized static PushApplication getInstance() {
return mApplication;
}
@Override
public void onCreate() {
super.onCreate();
mApplication = this;
CrashHandler.getInstance().init(this);
initFaceMap();
initData();
initImageLoader(getApplicationContext());
}
public static void initImageLoader(Context context) {
// This configuration tuning is custom. You can tune every option, you may tune some of them,
// or you can create default configuration by
// ImageLoaderConfiguration.createDefault(this);
// method.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.threadPriority(Thread.NORM_PRIORITY - 2)
.threadPoolSize(3)
.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
.denyCacheImageMultipleSizesInMemory()
.memoryCacheSize(2*1024*1024)
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
.discCacheSize(50 * 1024 * 1024)
.discCacheFileCount(100)
.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
}
private void initData() {
this.initUserData();
//this.initChatContent();
mBaiduPushServer = new BaiduPush(BaiduPush.HTTP_METHOD_POST,
SECRIT_KEY, API_KEY);
// 不转换没有 @Expose 注解的字段
mGson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
.create();
mSpUtil = new SharePreferenceUtil(this, SP_FILE_NAME);
mUserDB = new UserDB(this);
mMsgDB = new MessageDB(this);
mRecentDB = new RecentDB(this);
mMediaPlayer = MediaPlayer.create(this, R.raw.office);
mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
if (mSpUtil.getId()==0) {
PushMessageReceiver.ehList.add(this);// 监听推送的消息
index=1;//老师
initFriend();
User user=getCurrentUser();
mSpUtil.setId(user.getId());
mSpUtil.setRole(user.getRole());
mSpUtil.setHeadIcon(user.getHeadIcon());
mSpUtil.setNick(user.getNick());
//mSpUtil.setTag(SexAdapter.SEXS[mSexWheel.getCurrentItem()]);
}
if(TextUtils.isEmpty( mSpUtil.getUserId()))
PushManager.startWork(getApplicationContext(),
PushConstants.LOGIN_TYPE_API_KEY, PushApplication.API_KEY);
int id=mSpUtil.getId();
int role=mSpUtil.getRole();
String userId=mSpUtil.getUserId();
String name=mSpUtil.getNick();
String channelId=mSpUtil.getChannelId();
mUserList = mUserDB.getUser();
}
void initFriend(){
if(index==0){
mUserDB.addUser(this.m_userList.get(1));
mUserDB.addUser(this.m_userList.get(2));
}else{
mUserDB.addUser(this.m_userList.get(0));
}
}
public User getCurrentUser(){
return this.m_userList.get(index);
}
// void initChatContent(){
// MChatMsgEntity chat1=new MChatMsgEntity();
// chat1.setDate("2012-12-12 12:00");
// chat1.setName(this.m_userList.get(1).mName);
// chat1.setMsgType(false);
// chat1.setText("下个星期五家长开放日,");
// chat1.setTimeShow(false);
//
// MChatMsgEntity chat2=new MChatMsgEntity();
// chat2.setDate("2012-12-12 12:00");
// chat2.setName(this.m_userList.get(1).mName);
// chat2.setMsgType(true);
// chat2.setText("好的");
// chat2.setTimeShow(false);
//
// MChatMsgEntity chat3=new MChatMsgEntity();
// chat3.setDate("2012-12-12 12:00");
// chat3.setName(this.m_userList.get(1).mName);
// chat3.setMsgType(true);
// chat3.setText("多少点");
// chat3.setTimeShow(false);
//
// MChatMsgEntity chat4=new MChatMsgEntity();
// chat4.setDate("2012-12-12 12:00");
// chat4.setName(this.m_userList.get(1).mName);
// chat4.setMsgType(false);
// chat4.setText("九点");
// chat4.setTimeShow(true);
// }
//
void initUserData(){
this.m_userList=new ArrayList<User>();
User user1=new User();
user1.setId(1);
user1.setNick("a李老师");
user1.setRole(0);
user1.setHeadIcon(0);
user1.setUserId("954515449122882861");
user1.setPhoneNum("13416111872");
m_userList.add(user1);
User user2=new User();
user2.setId(2);
user2.setNick("a小明家长");
user2.setRole(1);
user2.setUserId("701586223983023931");
user2.setHeadIcon(1);
user2.setPhoneNum("13660606574");
m_userList.add(user2);
User user3=new User();
user3.setId(3);
user3.setNick("a小红家长");
user3.setUserId("828868000250887501");
user3.setRole(1);
user3.setHeadIcon(1);
user3.setPhoneNum("15819095037");
m_userList.add(user3);
}
//
public synchronized BaiduPush getBaiduPush() {
if (mBaiduPushServer == null)
mBaiduPushServer = new BaiduPush(BaiduPush.HTTP_METHOD_POST,
SECRIT_KEY, API_KEY);
return mBaiduPushServer;
}
public synchronized Gson getGson() {
if (mGson == null)
// 不转换没有 @Expose 注解的字段
mGson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
.create();
return mGson;
}
public NotificationManager getNotificationManager() {
if (mNotificationManager == null)
mNotificationManager = (NotificationManager) getSystemService(android.content.Context.NOTIFICATION_SERVICE);
return mNotificationManager;
}
public synchronized MediaPlayer getMediaPlayer() {
if (mMediaPlayer == null)
mMediaPlayer = MediaPlayer.create(this, R.raw.office);
return mMediaPlayer;
}
public synchronized UserDB getUserDB() {
if (mUserDB == null)
mUserDB = new UserDB(this);
return mUserDB;
}
public synchronized RecentDB getRecentDB() {
if (mRecentDB == null)
mRecentDB = new RecentDB(this);
return mRecentDB;
}
public synchronized MessageDB getMessageDB() {
if (mMsgDB == null)
mMsgDB = new MessageDB(this);
return mMsgDB;
}
public synchronized List<User> getUserList() {
if (mUserList == null)
mUserList = getUserDB().getUser();
return mUserList;
}
public synchronized SharePreferenceUtil getSpUtil() {
if (mSpUtil == null)
mSpUtil = new SharePreferenceUtil(this, SP_FILE_NAME);
return mSpUtil;
}
public Map<String, Integer> getFaceMap() {
if (!mFaceMap.isEmpty())
return mFaceMap;
return null;
}
/**
* 创建挂机图标
*/
@SuppressWarnings("deprecation")
public void showNotification() {
if (!mSpUtil.getMsgNotify())// 如果用户设置不显示挂机图标,直接返回
return;
int icon = R.drawable.notify_general;
CharSequence tickerText = getResources().getString(
R.string.app_is_run_background);
long when = System.currentTimeMillis();
mNotification = new Notification(icon, tickerText, when);
// 放置在"正在运行"栏目中
mNotification.flags = Notification.FLAG_ONGOING_EVENT;
RemoteViews contentView = new RemoteViews(getPackageName(),
R.layout.notify_status_bar_latest_event_view);
contentView.setImageViewResource(R.id.icon,
heads[mSpUtil.getHeadIcon()]);
contentView.setTextViewText(R.id.title, mSpUtil.getNick());
contentView.setTextViewText(R.id.text, tickerText);
contentView.setLong(R.id.time, "setTime", when);
// 指定个性化视图
mNotification.contentView = contentView;
Intent intent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 指定内容意图
mNotification.contentIntent = contentIntent;
// 下面是4.0notify
// Bitmap icon = BitmapFactory.decodeResource(getResources(),
// heads[mSpUtil.getHeadIcon()]);
// Notification.Builder notificationBuilder = new Notification.Builder(
// this).setContentTitle(mSpUtil.getNick())
// .setContentText(tickerText)
// .setSmallIcon(R.drawable.notify_general)
// .setWhen(System.currentTimeMillis())
// .setContentIntent(contentIntent).setLargeIcon(icon);
// Notification n = notificationBuilder.getNotification();
// n.flags |= Notification.FLAG_NO_CLEAR;
mNotificationManager.notify(PushMessageReceiver.NOTIFY_ID,
mNotification);
}
private void initFaceMap() {
// TODO Auto-generated method stub
mFaceMap.put("[呲牙]", R.drawable.f000);
mFaceMap.put("[调皮]", R.drawable.f001);
mFaceMap.put("[流汗]", R.drawable.f002);
mFaceMap.put("[偷笑]", R.drawable.f003);
mFaceMap.put("[再见]", R.drawable.f004);
mFaceMap.put("[敲打]", R.drawable.f005);
mFaceMap.put("[擦汗]", R.drawable.f006);
mFaceMap.put("[猪头]", R.drawable.f007);
mFaceMap.put("[玫瑰]", R.drawable.f008);
mFaceMap.put("[流泪]", R.drawable.f009);
mFaceMap.put("[大哭]", R.drawable.f010);
mFaceMap.put("[嘘]", R.drawable.f011);
mFaceMap.put("[酷]", R.drawable.f012);
mFaceMap.put("[抓狂]", R.drawable.f013);
mFaceMap.put("[委屈]", R.drawable.f014);
mFaceMap.put("[便便]", R.drawable.f015);
mFaceMap.put("[炸弹]", R.drawable.f016);
mFaceMap.put("[菜刀]", R.drawable.f017);
mFaceMap.put("[可爱]", R.drawable.f018);
mFaceMap.put("[色]", R.drawable.f019);
mFaceMap.put("[害羞]", R.drawable.f020);
mFaceMap.put("[得意]", R.drawable.f021);
mFaceMap.put("[吐]", R.drawable.f022);
mFaceMap.put("[微笑]", R.drawable.f023);
mFaceMap.put("[发怒]", R.drawable.f024);
mFaceMap.put("[尴尬]", R.drawable.f025);
mFaceMap.put("[惊恐]", R.drawable.f026);
mFaceMap.put("[冷汗]", R.drawable.f027);
mFaceMap.put("[爱心]", R.drawable.f028);
mFaceMap.put("[示爱]", R.drawable.f029);
mFaceMap.put("[白眼]", R.drawable.f030);
mFaceMap.put("[傲慢]", R.drawable.f031);
mFaceMap.put("[难过]", R.drawable.f032);
mFaceMap.put("[惊讶]", R.drawable.f033);
mFaceMap.put("[疑问]", R.drawable.f034);
mFaceMap.put("[睡]", R.drawable.f035);
mFaceMap.put("[亲亲]", R.drawable.f036);
mFaceMap.put("[憨笑]", R.drawable.f037);
mFaceMap.put("[爱情]", R.drawable.f038);
mFaceMap.put("[衰]", R.drawable.f039);
mFaceMap.put("[撇嘴]", R.drawable.f040);
mFaceMap.put("[阴险]", R.drawable.f041);
mFaceMap.put("[奋斗]", R.drawable.f042);
mFaceMap.put("[发呆]", R.drawable.f043);
mFaceMap.put("[右哼哼]", R.drawable.f044);
mFaceMap.put("[拥抱]", R.drawable.f045);
mFaceMap.put("[坏笑]", R.drawable.f046);
mFaceMap.put("[飞吻]", R.drawable.f047);
mFaceMap.put("[鄙视]", R.drawable.f048);
mFaceMap.put("[晕]", R.drawable.f049);
mFaceMap.put("[大兵]", R.drawable.f050);
mFaceMap.put("[可怜]", R.drawable.f051);
mFaceMap.put("[强]", R.drawable.f052);
mFaceMap.put("[弱]", R.drawable.f053);
mFaceMap.put("[握手]", R.drawable.f054);
mFaceMap.put("[胜利]", R.drawable.f055);
mFaceMap.put("[抱拳]", R.drawable.f056);
mFaceMap.put("[凋谢]", R.drawable.f057);
mFaceMap.put("[饭]", R.drawable.f058);
mFaceMap.put("[蛋糕]", R.drawable.f059);
mFaceMap.put("[西瓜]", R.drawable.f060);
mFaceMap.put("[啤酒]", R.drawable.f061);
mFaceMap.put("[飘虫]", R.drawable.f062);
mFaceMap.put("[勾引]", R.drawable.f063);
mFaceMap.put("[OK]", R.drawable.f064);
mFaceMap.put("[爱你]", R.drawable.f065);
mFaceMap.put("[咖啡]", R.drawable.f066);
mFaceMap.put("[钱]", R.drawable.f067);
mFaceMap.put("[月亮]", R.drawable.f068);
mFaceMap.put("[美女]", R.drawable.f069);
mFaceMap.put("[刀]", R.drawable.f070);
mFaceMap.put("[发抖]", R.drawable.f071);
mFaceMap.put("[差劲]", R.drawable.f072);
mFaceMap.put("[拳头]", R.drawable.f073);
mFaceMap.put("[心碎]", R.drawable.f074);
mFaceMap.put("[太阳]", R.drawable.f075);
mFaceMap.put("[礼物]", R.drawable.f076);
mFaceMap.put("[足球]", R.drawable.f077);
mFaceMap.put("[骷髅]", R.drawable.f078);
mFaceMap.put("[挥手]", R.drawable.f079);
mFaceMap.put("[闪电]", R.drawable.f080);
mFaceMap.put("[饥饿]", R.drawable.f081);
mFaceMap.put("[困]", R.drawable.f082);
mFaceMap.put("[咒骂]", R.drawable.f083);
mFaceMap.put("[折磨]", R.drawable.f084);
mFaceMap.put("[抠鼻]", R.drawable.f085);
mFaceMap.put("[鼓掌]", R.drawable.f086);
mFaceMap.put("[糗大了]", R.drawable.f087);
mFaceMap.put("[左哼哼]", R.drawable.f088);
mFaceMap.put("[哈欠]", R.drawable.f089);
mFaceMap.put("[快哭了]", R.drawable.f090);
mFaceMap.put("[吓]", R.drawable.f091);
mFaceMap.put("[篮球]", R.drawable.f092);
mFaceMap.put("[乒乓球]", R.drawable.f093);
mFaceMap.put("[NO]", R.drawable.f094);
mFaceMap.put("[跳跳]", R.drawable.f095);
mFaceMap.put("[怄火]", R.drawable.f096);
mFaceMap.put("[转圈]", R.drawable.f097);
mFaceMap.put("[磕头]", R.drawable.f098);
mFaceMap.put("[回头]", R.drawable.f099);
mFaceMap.put("[跳绳]", R.drawable.f100);
mFaceMap.put("[激动]", R.drawable.f101);
mFaceMap.put("[街舞]", R.drawable.f102);
mFaceMap.put("[献吻]", R.drawable.f103);
mFaceMap.put("[左太极]", R.drawable.f104);
mFaceMap.put("[右太极]", R.drawable.f105);
mFaceMap.put("[闭嘴]", R.drawable.f106);
}
@Override
public void onMessage(Message message) {
// TODO Auto-generated method stub
}
@Override
public void onBind(String method, int errorCode, String content) {
// TODO Auto-generated method stub
if (errorCode == 0) {// 如果绑定账号成功,由于第一次运行,给同一tag的人推送一条新人消息
// User u = new User(mSpUtil.getId(),mSpUtil.getUserId(),mSpUtil.getRole(), mSpUtil.getChannelId(),
// mSpUtil.getNick(), mSpUtil.getHeadIcon(), 0);
//mUserDB.addUser(u);// 把自己添加到数据库
// com.way.bean.Message msgItem = new com.way.bean.Message(
// System.currentTimeMillis(), "hi", mSpUtil.getTag());
// task = new SendMsgAsyncTask(mGson.toJson(msgItem), "");
// task.setOnSendScuessListener(new OnSendScuessListener() {
//
// @Override
// public void sendScuess() {
// startActivity(new Intent(FirstSetActivity.this,
// MainActivity.class));
// if (mConnectServerDialog != null
// && mConnectServerDialog.isShowing())
// mConnectServerDialog.dismiss();
//
// if (mLoginOutTimeProcess != null
// && mLoginOutTimeProcess.running)
// mLoginOutTimeProcess.stop();
// T.showShort(mApplication, R.string.first_start_scuess);
// finish();
// }
// });
// task.send();
}
}
@Override
public void onNotify(String title, String content) {
// TODO Auto-generated method stub
}
@Override
public void onNetChange(boolean isNetConnected) {
// TODO Auto-generated method stub
}
@Override
public void onNewFriend(User u) {
// TODO Auto-generated method stub
}
}
<file_sep>package com.youer.activity;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import com.example.youer.R;
import com.youer.modal.MVideo;
import com.youer.tool.AppDataManager;
import com.youer.tool.DensityUtil;
import com.youer.view.FullScreenVideoView;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AlphaAnimation;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.PopupWindow;
import android.widget.Toast;
import android.widget.VideoView;
public class VideoActivity extends Activity implements OnClickListener {
ImageView m_view=null;
int m_currentIndex=0;
LinearLayout m_popupView=null;
LinearLayout m_videoContainer=null;
View m_top=null;
boolean m_fullScreen=false;
LinearLayout view;
int m_videoContainerHeight;
int m_width;
int m_height;
FrameLayout.LayoutParams m_lp=null;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.video_popup);
this.m_width=DensityUtil.getLogicalWidth();
this.m_height=DensityUtil.getLogicalHeight();
MVideo video=(MVideo) getIntent().getExtras().getSerializable("video");
ImageView back=(ImageView) findViewById(R.id.back);
float rate=getIntent().getFloatExtra("rate", 0);
if(rate==0){
BitmapDrawable drawable;
Bitmap bitmap;
if(video.mImage.mIsLocal){
drawable=(BitmapDrawable) this.getResources().getDrawable(video.mImage.mResourceId);
bitmap= drawable.getBitmap();
}
else{
bitmap= BitmapFactory.decodeFile(video.mImage.mFilePath);
drawable= new BitmapDrawable(this.getResources(), bitmap);
}
rate=(float)bitmap.getHeight()/(float)bitmap.getWidth();
}
m_top=findViewById(R.id.top_bg);
this.m_videoContainerHeight=this.m_height;
this.m_videoContainer=(LinearLayout)findViewById(R.id.video_container);
VideoView video1=(VideoView) findViewById(R.id.video);
//video1.setVisibility(View.INVISIBLE);
FrameLayout.LayoutParams videoContainerLp=(LayoutParams) this.m_videoContainer.getLayoutParams();
videoContainerLp.height=Math.min((int)(rate*this.m_width),this.m_height-DensityUtil.dip2px(54)-this.getBarHeight());
videoContainerLp.width=this.m_width;
videoContainerLp.topMargin=Math.max((this.m_height-DensityUtil.dip2px(54)-this.getBarHeight()-videoContainerLp.height)/2,DensityUtil.dip2px(54));
this.m_videoContainer.setLayoutParams(videoContainerLp);
//this.m_videoContainer.setVisibility(View.INVISIBLE);
back.setOnClickListener(this);
final FullScreenVideoView videoView=(FullScreenVideoView) findViewById(R.id.video);
MediaController mediaController = new MediaController(this);
//把MediaController对象绑定到VideoView上
mediaController.setAnchorView(videoView);
//设置VideoView的控制器是mediaController
videoView.setMediaController(mediaController);
//这两种方法都可以 videoView.setVideoPath("file:///sdcard/love_480320.mp4");
if(!video.mIsLocal)
videoView.setVideoURI(Uri.parse(video.mFilePath));
else
videoView.setVideoPath("android.resource://" + getPackageName()+"/"+R.raw.test1);
//启动后就播放
videoView.start();
m_popupView=(LinearLayout) findViewById(R.id.popup);
m_popupView.setOnClickListener(this);
m_popupView.setVisibility(View.VISIBLE);
this.m_lp=(FrameLayout.LayoutParams) this.m_popupView.getLayoutParams();
this.m_lp.height=0;
this.m_lp.width=0;
// android:layout_marginTop="57dp"
// android:layout_marginRight="5dp"
// android:layout_gravity="right"
this.m_popupView.setLayoutParams(m_lp);
// android:layout_width="198dp"
// android:layout_height="87dp"
ImageView expand=(ImageView) findViewById(R.id.expand);
expand.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
updatePopup();
}});
}
public int getBarHeight(){
Class<?> c = null;
Object obj = null;
Field field = null;
int x = 0, sbar = 38;//默认为38,貌似大部分是这样的
try {
c = Class.forName("com.android.internal.R$dimen");
obj = c.newInstance();
field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
sbar = getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
e1.printStackTrace();
}
return sbar;
}
void updatePopup(){
if(m_popupView.getVisibility()==View.INVISIBLE)
{
m_popupView.setVisibility(View.VISIBLE);
this.m_lp.height=LayoutParams.MATCH_PARENT;
this.m_lp.width=LayoutParams.MATCH_PARENT;
this.m_popupView.setLayoutParams(m_lp);
//fadeIn(m_popupView, 500);
}
else {
//m_popupView.setVisibility(View.INVISIBLE);
m_popupView.setVisibility(View.INVISIBLE);
this.m_lp.height=DensityUtil.dip2px(0);
this.m_lp.width=DensityUtil.dip2px(0);
this.m_popupView.setLayoutParams(m_lp);
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.back:
this.finish();
break;
case R.id.download_container:
updatePopup();
String systemImageDir = "/sdcard/meinvqiushi/image/";
m_view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(m_view.getDrawingCache());
m_view.setDrawingCacheEnabled(false);
SimpleDateFormat formatter = new SimpleDateFormat("yy-MM-dd");
formatter.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
long ms = System.currentTimeMillis();
String dt = formatter.format(ms);
String fileName = dt + "_" + ms + ".png";
if( AppDataManager.getInstance().SaveImage(bitmap, fileName)){
//success
//Log.i("downLoadImage", "downLoadImage click"+fileName);
String msg ="成功下载" + ":" + systemImageDir;
Toast toast=Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}else{
//fail
Toast.makeText(this, "下载失败", Toast.LENGTH_SHORT).show();
}
break;
case R.id.share_container:
updatePopup();
break;
case R.id.popup:
m_popupView.setVisibility(View.INVISIBLE);
break;
case R.id.gallery_container:
updateFullScreen();
break;
}
}
public void updateFullScreen(){
if(m_fullScreen){
FrameLayout.LayoutParams lp=(android.widget.FrameLayout.LayoutParams) view.getLayoutParams();
lp.topMargin=DensityUtil.dip2px(56);
view.setLayoutParams(lp);
m_top.setVisibility(View.VISIBLE);
fadeIn(m_top,200);
m_fullScreen=false;
}
else{
m_top.setVisibility(View.INVISIBLE);
FrameLayout.LayoutParams lp=(android.widget.FrameLayout.LayoutParams) view.getLayoutParams();
lp.topMargin=0;
view.setLayoutParams(lp);
m_fullScreen=true;
}
}
public static void fadeIn(View view, int durationMillis) {
AlphaAnimation fadeImage = new AlphaAnimation(0, 1);
fadeImage.setDuration(durationMillis);
fadeImage.setInterpolator(new DecelerateInterpolator());
view.startAnimation(fadeImage);
}
}
<file_sep>package com.youer.modal;
import java.io.Serializable;
public class MVideo implements Serializable{
public int mId;
public boolean mIsLocal=true;
public int mResourceId;
public String mFilePath;
public MImage mImage;
}
<file_sep>package com.youer.adapter;
import java.util.List;
import com.example.youer.R;
import com.youer.modal.MImage;
import com.youer.modal.MVideo;
import com.youer.tool.DensityUtil;
import com.youer.tool.Utils;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class VideoGridAdapter extends BaseAdapter {
private int imageCol = 3;
private int ownposition;
List<MVideo> m_videoList;
LayoutInflater m_layoutInflate;
int width;
int height;
public int getOwnposition() {
return ownposition;
}
public void setOwnposition(int ownposition) {
this.ownposition = ownposition;
}
private Context m_context;
// 定义整型数组 即图片源
// 声明 ImageAdapter
public VideoGridAdapter(Context c,List<MVideo> videoList) {
m_context = c;
this.m_layoutInflate=LayoutInflater.from(c);
this.m_videoList=videoList;
this.height=this.width=DensityUtil.getLogicalHeight() / imageCol - 6;
}
// 获取图片的个数
public int getCount() {
return m_videoList.size();
}
// 获取图片在库中的位置
public Object getItem(int position) {
MVideo video=this.m_videoList.get(position);
return video;
}
// 获取图片ID
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = null;
ViewHolder holder = null;
if (convertView == null) {
holder=new ViewHolder();
convertView = this.m_layoutInflate.inflate(R.layout.video_item, null);
imageView=(ImageView) convertView.findViewById(R.id.title_img);
//如果是横屏,GridView会展示4列图片,需要设置图片的大小
GridView.LayoutParams lp;
if (imageCol == 4) {
lp=new GridView.LayoutParams(
DensityUtil.getLogicalHeight() / imageCol - 6, DensityUtil.getLogicalHeight()
/ imageCol - 6);
convertView.setLayoutParams(lp);
} else {//如果是竖屏,GridView会展示3列图片,需要设置图片的大小
lp=new GridView.LayoutParams(
DensityUtil.getLogicalWidth() / imageCol-DensityUtil.dip2px(6),DensityUtil.getLogicalWidth()
/ imageCol-DensityUtil.dip2px(6));
convertView.setLayoutParams(lp);
}
imageView.setPadding(0, DensityUtil.dip2px(3), DensityUtil.dip2px(3),0);
//imageView.setAdjustViewBounds(true);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
holder.mImageView=imageView;
convertView.setTag(holder);
// imageView.setPadding(3, 3, 3, 3);
} else {
holder = (ViewHolder) convertView.getTag();
imageView=holder.mImageView;
}
MVideo video=this.m_videoList.get(position);
BitmapDrawable drawable;
Bitmap bitmap;
MImage image=video.mImage;
// 第一次解析将inJustDecodeBounds设置为true,来获取图片大小
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
if(image.mIsLocal){
BitmapFactory.decodeResource(m_context.getResources(), image.mResourceId, options);
// 调用上面定义的方法计算inSampleSize值
options.inSampleSize = Utils.calculateInSampleSize(options, width, height);
// 使用获取到的inSampleSize值再次解析图片
options.inJustDecodeBounds = false;
bitmap= BitmapFactory.decodeResource(m_context.getResources(), image.mResourceId, options);
}
else{
BitmapFactory.decodeFile(image.mFilePath, options);
options.inSampleSize = Utils.calculateInSampleSize(options, width, height);
// 使用获取到的inSampleSize值再次解析图片
options.inJustDecodeBounds = false;
bitmap= BitmapFactory.decodeFile(image.mFilePath, options);
}
drawable= new BitmapDrawable(m_context.getResources(), bitmap);
holder.mImageView.setImageDrawable(drawable);
return convertView;
}
static class ViewHolder{
ImageView mImageView;
}
}
<file_sep>package com.youer.activity;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import com.baidu.android.common.logging.Log;
import com.baidu.android.pushservice.CustomPushNotificationBuilder;
import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.baidu.inf.iis.bcs.BaiduBCS;
import com.baidu.inf.iis.bcs.auth.BCSCredentials;
import com.baidu.inf.iis.bcs.model.ObjectMetadata;
import com.baidu.inf.iis.bcs.request.PutObjectRequest;
import com.example.youer.R;
import com.google.gson.Gson;
import com.way.adapter.RecentAdapter;
import com.way.app.PushApplication;
import com.way.baidupush.client.PushMessageReceiver;
import com.way.baidupush.client.PushMessageReceiver.EventHandler;
import com.way.bean.MessageItem;
import com.way.bean.RecentItem;
import com.way.bean.User;
import com.way.common.util.SharePreferenceUtil;
import com.way.common.util.T;
import com.way.db.MessageDB;
import com.way.db.RecentDB;
import com.way.db.UserDB;
import com.way.swipelistview.SwipeListView;
import com.youer.adapter.ChatMsgAdapter;
import com.youer.adapter.ImageAdapter;
import com.youer.adapter.NewsAdapter2;
import com.youer.adapter.NotifyAdapter;
import com.youer.modal.MAd;
import com.youer.modal.MChatMsgEntity;
import com.youer.modal.MImage;
import com.youer.modal.MMedia;
import com.youer.modal.MNews;
import com.youer.modal.MNotify;
import com.youer.modal.MUser;
import com.youer.modal.MVideo;
import com.youer.tool.AppDataManager;
import com.youer.tool.DensityUtil;
import com.youer.tool.Utils;
import com.youer.view.MyGallery;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.util.Base64;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener, EventHandler {
LinearLayout m_content=null;
LinearLayout m_firstContent=null;
LinearLayout m_secondContent=null;
LinearLayout m_thirdContent=null;
LinearLayout m_fourthContent=null;
ImageView m_firstImg=null;
ImageView m_secondImg=null;
ImageView m_thirdImg=null;
ImageView m_fourthImg=null;
int m_screenHeight=0;
int m_currentSelectIndex=0;
NotifyAdapter m_notifyAdapter=null;
List<MNotify> m_notifyList=null;
int m_width;
int m_height;
LayoutInflater m_layoutInflater=null;
private Button m_btnSend;
private EditText m_editTextContent;
private ListView m_listView;
private ChatMsgAdapter m_adapter;
private List<MChatMsgEntity> m_dataArrays = new ArrayList<MChatMsgEntity>();
private boolean isLogin = false;
String appid = "";
String channelid = "";
String userid = "";
private LinkedList<RecentItem> mRecentDatas;
private RecentAdapter mAdapter;
private PushApplication mApplication;
private UserDB mUserDB;
private MessageDB mMsgDB;
private RecentDB mRecentDB;
private SharePreferenceUtil mSpUtil;
private Gson mGson;
private SwipeListView mRecentListView;
public static final int NEW_MESSAGE = 0x000;// 有新消息
public static final int NEW_FRIEND = 0x001;// 有好友加入
View m_secondView;
ListView m_thirdView;
NewsAdapter2 m_newsAdapter;
private int preSelImgIndex = 0;
private final int KEHOUQUAN=100001;
private final int STORY=100002;
private final int QIMENG=100003;
private final int HUIBEN=100004;
private final int PHOTO=100005;
private final int SETTING=100006;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
AppDataManager.getInstance().init(this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.m_layoutInflater=LayoutInflater.from(this);
DensityUtil util=new DensityUtil(this);
this.m_content=(LinearLayout) findViewById(R.id.content);
this.m_firstImg=(ImageView) findViewById(R.id.first);
this.m_firstImg.setOnClickListener(this);
this.m_secondImg=(ImageView) findViewById(R.id.second);
this.m_secondImg.setOnClickListener(this);
this.m_thirdImg=(ImageView) findViewById(R.id.third);
this.m_thirdImg.setOnClickListener(this);
this.m_fourthImg=(ImageView) findViewById(R.id.fourth);
this.m_fourthImg.setOnClickListener(this);
this.m_width=DensityUtil.getLogicalWidth();
this.m_height=DensityUtil.getLogicalHeight();
this.reMeasure();
//initData();
this.createFirstContent();
this.createSecondContent();
this.createThirdContent();
this.createFourthContent();
this.m_content.addView(m_firstContent);
selectView(0);
}
void selectView(int index){
switch(index){
case 0:
this.m_firstImg.setImageDrawable(this.getResources().getDrawable(R.drawable.home_click));
this.m_secondImg.setImageDrawable(this.getResources().getDrawable(R.drawable.message_no_click));
this.m_thirdImg.setImageDrawable(this.getResources().getDrawable(R.drawable.news_no_click));
this.m_fourthImg.setImageDrawable(this.getResources().getDrawable(R.drawable.kehou_no_click));
break;
case 1:
this.m_firstImg.setImageDrawable(this.getResources().getDrawable(R.drawable.home_no_click));
this.m_secondImg.setImageDrawable(this.getResources().getDrawable(R.drawable.message_click));
this.m_thirdImg.setImageDrawable(this.getResources().getDrawable(R.drawable.news_no_click));
this.m_fourthImg.setImageDrawable(this.getResources().getDrawable(R.drawable.kehou_no_click));
break;
case 2:
this.m_firstImg.setImageDrawable(this.getResources().getDrawable(R.drawable.home_no_click));
this.m_secondImg.setImageDrawable(this.getResources().getDrawable(R.drawable.message_no_click));
this.m_thirdImg.setImageDrawable(this.getResources().getDrawable(R.drawable.news_click));
this.m_fourthImg.setImageDrawable(this.getResources().getDrawable(R.drawable.kehou_no_click));
break;
case 3:
this.m_firstImg.setImageDrawable(this.getResources().getDrawable(R.drawable.home_no_click));
this.m_secondImg.setImageDrawable(this.getResources().getDrawable(R.drawable.message_no_click));
this.m_thirdImg.setImageDrawable(this.getResources().getDrawable(R.drawable.news_no_click));
this.m_fourthImg.setImageDrawable(this.getResources().getDrawable(R.drawable.kehou_click));
break;
}
}
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case NEW_FRIEND:
User u = (User) msg.obj;
// mUserDB.addUser(u);
// if (mLeftFragment == null)
// mLeftFragment = (LeftFragment) getSupportFragmentManager()
// .findFragmentById(R.id.main_left_fragment);
// mLeftFragment.updateAdapter();// 更新
T.showShort(mApplication, "好友列表已更新!");
break;
case NEW_MESSAGE:
// String message = (String) msg.obj;
com.way.bean.Message msgItem = (com.way.bean.Message) msg.obj;
String userId = msgItem.getUser_id();
int id=msgItem.getId();
int role=msgItem.getRole();
String nick = msgItem.getNick();
String content = msgItem.getMessage();
int headId = msgItem.getHead_id();
// try {
// headId = Integer
// .parseInt(JsonUtil.getFromUserHead(message));
// } catch (Exception e) {
// L.e("head is not integer " + e);
// }
if (mUserDB.selectInfo(id) == null) {// 如果不存在此好友,则添加到数据库
User user = new User(id,userId,role, msgItem.getChannel_id(), nick,
headId, 0,"");
mUserDB.addUser(user);
}
// TODO Auto-generated method stub
MessageItem item = new MessageItem(
MessageItem.MESSAGE_TYPE_TEXT, nick,
System.currentTimeMillis(), content, headId, true, 1);
mMsgDB.saveMsg(id, item);
// 保存到最近会话列表
RecentItem recentItem = new RecentItem(id,userId,role, headId, nick,
content, 0, System.currentTimeMillis());
mRecentDB.saveRecent(recentItem);
mAdapter.addFirst(recentItem);
T.showShort(mApplication, nick + ":" + content);
break;
default:
break;
}
}
};
@Override
public void onStart() {
super.onStart();
//PushManager.activityStarted(this);
}
@Override
protected void onNewIntent(Intent intent) {
// 如果要统计Push引起的用户使用应用情况,请实现本方法,且加上这一个语句
setIntent(intent);
handleIntent(intent);
}
@Override
public void onStop() {
super.onStop();
//PushManager.activityStoped(this);
}
@Override
public void onResume() {
super.onResume();
if (!PushManager.isPushEnabled(this))
PushManager.resumeWork(this);
PushMessageReceiver.ehList.add(this);
initRecentData();
mApplication.getNotificationManager().cancel(
PushMessageReceiver.NOTIFY_ID);
PushMessageReceiver.mNewNum = 0;
//showChannelIds();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// mHomeWatcher.setOnHomePressedListener(null);
// mHomeWatcher.stopWatch();
PushMessageReceiver.ehList.remove(this);// 暂停就移除监听
}
private void initRecentData() {
// TODO Auto-generated method stub
mRecentDatas = mRecentDB.getRecentList();
//mAdapter = new RecentAdapter(this, mRecentDatas, mRecentListView);
//mRecentListView.setAdapter(mAdapter);
mAdapter = new RecentAdapter(this, mRecentDatas, this.m_listView);
if(this.m_listView!=null)
this.m_listView.setAdapter(mAdapter);
}
/**
* 处理Intent
*
* @param intent
* intent
*/
private void handleIntent(Intent intent) {
String action = intent.getAction();
if (Utils.ACTION_RESPONSE.equals(action)) {
String method = intent.getStringExtra(Utils.RESPONSE_METHOD);
if (PushConstants.METHOD_BIND.equals(method)) {
String toastStr = "";
int errorCode = intent.getIntExtra(Utils.RESPONSE_ERRCODE, 0);
if (errorCode == 0) {
String content = intent
.getStringExtra(Utils.RESPONSE_CONTENT);
try {
JSONObject jsonContent = new JSONObject(content);
JSONObject params = jsonContent
.getJSONObject("response_params");
appid = params.getString("appid");
channelid = params.getString("channel_id");
userid = params.getString("user_id");
} catch (JSONException e) {
Log.e(Utils.TAG, "Parse bind json infos error: " + e);
}
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sp.edit();
editor.putString("appid", appid);
editor.putString("channel_id", channelid);
editor.putString("user_id", userid);
editor.commit();
showChannelIds();
toastStr = "Bind Success";
} else {
toastStr = "Bind Fail, Error Code: " + errorCode;
if (errorCode == 30607) {
Log.d("Bind Fail", "update channel token-----!");
}
}
Toast.makeText(this, toastStr, Toast.LENGTH_LONG).show();
}
} else if (Utils.ACTION_LOGIN.equals(action)) {
String accessToken = intent
.getStringExtra(Utils.EXTRA_ACCESS_TOKEN);
PushManager.startWork(getApplicationContext(),
PushConstants.LOGIN_TYPE_ACCESS_TOKEN, accessToken);
isLogin = true;
} else if (Utils.ACTION_MESSAGE.equals(action)) {
String message = intent.getStringExtra(Utils.EXTRA_MESSAGE);
String summary = "Receive message from server:\n\t";
Log.e(Utils.TAG, summary + message);
JSONObject contentJson = null;
String contentStr = message;
try {
contentJson = new JSONObject(message);
contentStr = contentJson.toString(4);
} catch (JSONException e) {
Log.d(Utils.TAG, "Parse message json exception.");
}
summary += contentStr;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(summary);
builder.setCancelable(true);
Dialog dialog = builder.create();
dialog.setCanceledOnTouchOutside(true);
dialog.show();
} else {
Log.i(Utils.TAG, "Activity normally start!");
}
}
private void showChannelIds() {
String appId = null;
String channelId = null;
String clientId = null;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
appId = sp.getString("appid", "");
channelId = sp.getString("channel_id", "");
clientId = sp.getString("user_id", "");//828868000250887501,
Resources resource = this.getResources();
String pkgName = this.getPackageName();
}
void initNotifyData(){
SharedPreferences dataSetting=getSharedPreferences("initData", 0);
SharedPreferences.Editor editor = dataSetting.edit();
//editor.clear();
//editor.commit();
String dataListStr=dataSetting.getString("data",null);
if(dataListStr==null){
List<MMedia> mediaList=new ArrayList<MMedia>();
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);//
int day = c.get(Calendar.DAY_OF_MONTH);//
this.m_notifyList=new ArrayList<MNotify>();
MNotify notify1=new MNotify();
notify1.mTitle="春节放假通知";
notify1.mDescription="今年春节放假时间1月30日至2月5日(星期六)";
notify1.mTime=year+"/"+month+"/"+day;
notify1.mContent="今年春节放假时间1月30日至2月5日(星期六)";
this.m_notifyList.add(notify1);
MNotify notify2=new MNotify();
notify2.mTitle="2013招生通知";
notify2.mTime="2013/4/22";
notify2.mIsNative=false;
notify2.mRedirectUrl="http://php1.hontek.com.cn/wordpress/archives/372.html";
this.m_notifyList.add(notify2);
MNotify notify3=new MNotify();
notify3.mTitle="开学了【相册】";
notify3.mDescription="新学期开学了,孩子在升旗";
notify3.mTime="2013/9/1";
List<MImage> imageList3=new ArrayList<MImage>();
MImage image1=new MImage();
image1.mResourceId=R.drawable.kaixue1;
MImage image2=new MImage();
image2.mResourceId=R.drawable.kaixue2;
MImage image3=new MImage();
image3.mResourceId=R.drawable.kaixue3;
MImage image4=new MImage();
image4.mResourceId=R.drawable.kaixue4;
MImage image5=new MImage();
image5.mResourceId=R.drawable.kaixue5;
imageList3.add(image1);
imageList3.add(image2);
imageList3.add(image3);
imageList3.add(image4);
imageList3.add(image5);
notify3.mImageList=imageList3;
this.m_notifyList.add(notify3);
MMedia media1=new MMedia();
media1.mName="开学了";
media1.mPhotoList=imageList3;
mediaList.add(media1);
MNotify notify4=new MNotify();
notify4.mTitle="活动图片";
notify4.mTime="2013/9/1";
List<MImage> imageList4=new ArrayList<MImage>();
MImage image6=new MImage();
image6.mResourceId=R.drawable.zuopin1;
MImage image7=new MImage();
image7.mResourceId=R.drawable.zuopin2;
MImage image8=new MImage();
image8.mResourceId=R.drawable.zuopin3;
MImage image9=new MImage();
image9.mResourceId=R.drawable.zuopin4;
MImage image10=new MImage();
image10.mResourceId=R.drawable.zuopin5;
imageList4.add(image6);
imageList4.add(image7);
imageList4.add(image8);
imageList4.add(image9);
imageList4.add(image10);
notify4.mImageList=imageList4;
this.m_notifyList.add(notify4);
MMedia media2=new MMedia();
media2.mName="活动图片";
media2.mPhotoList=imageList4;
mediaList.add(media2);
MNotify notify5=new MNotify();
notify5.mTitle="大一班歌词活动【视频】";
notify5.mTime="2013/9/1";
List<MVideo> videoList=new ArrayList<MVideo>();
MVideo video=new MVideo();
MImage image=new MImage();
image.mResourceId=R.drawable.test1;
video.mImage=image;
video.mFilePath="test1";
videoList.add(video);
notify5.mVideoList=videoList;
this.m_notifyList.add(notify5);
MMedia media3=new MMedia();
media3.mName="大一班歌词活动";
media3.mVideoList=videoList;
media3.mIsVideo=true;
mediaList.add(media3);
AppDataManager.getInstance().mMediaList=mediaList;
AppDataManager.getInstance().mNotifyList=this.m_notifyList;
AppDataManager.getInstance().saveData();
AppDataManager.getInstance().saveMediaData();
}
else{
try {
AppDataManager.getInstance().getData();
AppDataManager.getInstance().getMediaData();
m_notifyList=AppDataManager.getInstance().mNotifyList;
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void initView() {
m_listView = (ListView) this.m_secondView.findViewById(R.id.list);
m_listView.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
RecentItem item = (RecentItem) mAdapter
.getItem(position);
User u = new User(item.getId(),item.getUserId(), item.getRole(),"", item.getName(),
item.getHeadImg(), 0,"");
mMsgDB.clearNewCount(item.getId());
Intent toChatIntent = new Intent(MainActivity.this,
ChatActivity.class);
toChatIntent.putExtra("user", u);
startActivity(toChatIntent);
}
});
ImageView contact=(ImageView)this.m_secondView.findViewById(R.id.contact);
contact.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
Intent intent=new Intent(MainActivity.this,ContactActivity.class);
startActivity(intent);
}
});
this.m_listView.setAdapter(mAdapter);
}
private String[] msgArray = new String[] { "[媚眼]测试啦[媚眼]", "测试啦", "测试啦",
"测试啦", "测试啦", "你妹[苦逼]", "测[惊讶]你妹", "测你妹[胜利]",
"测试啦" };
private String[] m_dataArray = new String[] { "2012-12-12 12:00",
"2012-12-12 12:10", "2012-12-12 12:11", "2012-12-12 12:20",
"2012-12-12 12:30", "2012-12-12 12:35", "2012-12-12 12:40",
"2012-12-12 12:50", "2012-12-12 12:50" };
private final static int COUNT = 8;
public void initData() {
// for (int i = 0; i < COUNT; i++) {
// MChatMsgEntity entity = new MChatMsgEntity();
// entity.setDate(m_dataArray[i]);
// if (i % 2 == 0) {
// entity.setName("你妹");
// entity.setMsgType(true);
// } else {
// entity.setName("没么");
// entity.setMsgType(false);
// }
//
//
// entity.setText(msgArray[i]);
// m_dataArrays.add(entity);
// }
//
// m_adapter = new ChatMsgAdapter(this, m_dataArrays);
// m_listView.setAdapter(m_adapter);
mApplication = PushApplication.getInstance();
mSpUtil = mApplication.getSpUtil();
mGson = mApplication.getGson();
mUserDB = mApplication.getUserDB();
mMsgDB = mApplication.getMessageDB();
mRecentDB = mApplication.getRecentDB();
}
@SuppressLint("NewApi")
void createFirstContent(){
this.initNotifyData();
m_firstContent=new LinearLayout(this);
m_firstContent.setOrientation(1);
View view=this.m_layoutInflater.inflate(R.layout.first_layout, m_firstContent);
ImageView fabu=(ImageView)view.findViewById(R.id.fabu);
fabu.setOnClickListener(this);
ImageView website=(ImageView)view.findViewById(R.id.website);
website.setOnClickListener(this);
LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
m_firstContent.setLayoutParams(lp);
this.m_notifyAdapter=new NotifyAdapter(this,this.m_notifyList);
AppDataManager.getInstance().mNotifyAdapter=this.m_notifyAdapter;
ListView notifyListView=(ListView) view.findViewById(R.id.list);
notifyListView.setVerticalScrollBarEnabled(false);
notifyListView.setCacheColorHint(Color.WHITE);
//notifyListView.setDividerHeight(DensityUtil.dip2px(7));
notifyListView.setDivider(this.getResources().getDrawable(R.drawable.news_diver));
notifyListView.setFadingEdgeLength(0);
//actualListView.setSelector(R.drawable.news_item_select);
//actualListView.setVerticalFadingEdgeEnabled(false);
notifyListView.setHorizontalFadingEdgeEnabled(false);
if (Integer.parseInt(Build.VERSION.SDK) >= 9)
notifyListView.setOverScrollMode(View.OVER_SCROLL_NEVER);
else
notifyListView.setVerticalFadingEdgeEnabled(false);
notifyListView.setDividerHeight(DensityUtil.dip2px(8));
this.createAdBanner(notifyListView);
notifyListView.setAdapter(m_notifyAdapter);
//m_firstContent.addView(notifyListView);
notifyListView.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View view, int index,
long arg3) {
// TODO Auto-generated method stub
MNotify notify=m_notifyList.get(index-1);
if(notify.mIsNative){
Intent intent=new Intent(MainActivity.this,NotifyContentActivity.class);
intent.putExtra("notify",(Serializable)notify);
startActivity(intent);
}
else if(notify.mRedirectUrl!=null&&!notify.mRedirectUrl.equalsIgnoreCase("")){
Intent intent=new Intent(MainActivity.this,NormalWebViewActivity.class);
intent.putExtra("url", notify.mRedirectUrl);
startActivity(intent);
}
}
});
}
private List<Drawable> m_imgList = new ArrayList<Drawable>();
private void InitImgList() {
// 加载图片数据(本demo仅获取本地资源,实际应用中,可异步加载网络数据)
m_imgList=AppDataManager.getInstance().getDrawableList();
}
void createAdBanner(ListView listView){
InitImgList();
//final LinearLayout focusContainer=new LinearLayout(this);
FrameLayout adFrameLayout=new FrameLayout(this);
ListView.LayoutParams lp1=new ListView.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
//FrameLayout.LayoutParams lp1=new FrameLayout.LayoutParams(DensityUtil.getLogicalWidth()-30,LayoutParams.WRAP_CONTENT);
//lp1.gravity=Gravity.CENTER;
adFrameLayout.setLayoutParams(lp1);
//create nav and game
MyGallery gallery=new MyGallery(this);
gallery.setFadingEdgeLength(0);
gallery.setSoundEffectsEnabled(false);
gallery.setKeepScreenOn(true);
//gallery.setBackgroundColor(Color.RED);
LayoutParams lp4=new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);//DensityUtil.dip2px(m_adHeight)
gallery.setLayoutParams(lp4);
adFrameLayout.addView(gallery);
gallery.setAdapter(new ImageAdapter(this,this.m_imgList));
gallery.setFocusable(true);
final TextView desTxt=new TextView(this);
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int selIndex, long arg3) {
//修改上一次选中项的背景
selIndex = selIndex % m_imgList.size();
desTxt.setText(AppDataManager.getInstance().getAd(selIndex).mDescription);
//ImageView preSelImg = (ImageView) focusContainer.findViewById(preSelImgIndex);
//preSelImg.setImageDrawable(MainActivity.this.getResources().getDrawable(R.drawable.ic_focus));
//修改当前选中项的背景
//ImageView curSelImg = (ImageView) focusContainer.findViewById(selIndex);
//curSelImg.setImageDrawable(MainActivity.this.getResources().getDrawable(R.drawable.ic_focus_select));
preSelImgIndex = selIndex;
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
gallery.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> parent, View item, int index,
long arg3) {
// TODO Auto-generated method stub
MAd ad=AppDataManager.getInstance().getAd(index);
if(ad.mIsGallery){
List<MImage> m_imageList=new ArrayList<MImage>();
MImage img1=new MImage();
img1.mResourceId=R.drawable.kaifangri1;
m_imageList.add(img1);
MImage img2=new MImage();
img2.mResourceId=R.drawable.kaifangri2;
m_imageList.add(img2);
MImage img3=new MImage();
img3.mResourceId=R.drawable.kaifangri3;
m_imageList.add(img3);
MImage img4=new MImage();
img4.mResourceId=R.drawable.kaifangri1;
m_imageList.add(img4);
Intent intent=new Intent(MainActivity.this,GalleryActivity.class);
intent.putExtra("imageList",(Serializable)m_imageList);
intent.putExtra("index",String.valueOf(index));
startActivity(intent);
}
else{
if(ad.mType.equalsIgnoreCase("0")){
Intent intent = new Intent(MainActivity.this,NormalWebViewActivity.class);
intent.putExtra("url",ad.mInfo);
MainActivity.this.startActivity(intent);
}
}
}});
RelativeLayout bottomNavPoint=new RelativeLayout(this);
bottomNavPoint.setBackgroundResource(R.drawable.banner_bottom_bg);
bottomNavPoint.setId(1000);
FrameLayout.LayoutParams lp3=new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,DensityUtil.dip2px(20));
//lp3.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
//lp3.setMargins(0, 50, 0, 10);
// lp3.topMargin=100;
lp3.gravity=Gravity.BOTTOM;
//lp3.bottomMargin= DensityUtil.dip2px(5);
//bottomNavPoint.setOrientation(LinearLayout.VERTICAL);
//bottomNavPoint.setBackgroundColor(Color.RED);
bottomNavPoint.setLayoutParams(lp3);
adFrameLayout.addView(bottomNavPoint);
desTxt.setPadding(DensityUtil.dip2px(20), 0, 0, 0);
desTxt.setTextSize(13);
desTxt.setTextColor(Color.WHITE);
RelativeLayout.LayoutParams lp6=new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,DensityUtil.dip2px(20));
desTxt.setLayoutParams(lp6);
bottomNavPoint.addView(desTxt);
View view=new View(this);
RelativeLayout.LayoutParams lp5=new RelativeLayout.LayoutParams(0,0 );
lp5.addRule(RelativeLayout.BELOW,1000);
lp5.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
view.setLayoutParams(lp5);
adFrameLayout.addView(view);
LayoutParams lp2=new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT );
lp2.gravity=Gravity.CENTER;
//adFrameLayout.setBackgroundResource(R.drawable.news_bg);
listView.addHeaderView(adFrameLayout);
}
void createSecondContent(){
m_secondContent=new LinearLayout(this);
LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
m_secondContent.setLayoutParams(lp);
m_secondView=this.m_layoutInflater.inflate(R.layout.second_layout,this.m_secondContent);
//initView();
initData();
}
@SuppressLint("NewApi")
void createThirdContent(){
m_thirdView=new ListView(this);
LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(DensityUtil.getLogicalWidth()-DensityUtil.dip2px(20), LayoutParams.MATCH_PARENT);
lp.setMargins(DensityUtil.dip2px(10), DensityUtil.dip2px(10), DensityUtil.dip2px(10), DensityUtil.dip2px(10));
m_thirdView.setLayoutParams(lp);
m_thirdView.setVerticalScrollBarEnabled(false);
m_thirdView.setCacheColorHint(Color.WHITE);
m_thirdView.setDividerHeight(DensityUtil.dip2px(7));
m_thirdView.setDivider(this.getResources().getDrawable(R.drawable.news_diver));
m_thirdView.setFadingEdgeLength(0);
m_thirdView.setHorizontalFadingEdgeEnabled(false);
if (Integer.parseInt(Build.VERSION.SDK) >= 9)
m_thirdView.setOverScrollMode(View.OVER_SCROLL_NEVER);
else
m_thirdView.setVerticalFadingEdgeEnabled(false);
final List<MNews> newsList=AppDataManager.getInstance().getNews();
if(newsList!=null)
m_newsAdapter=new NewsAdapter2(this,newsList);
else
m_newsAdapter=new NewsAdapter2(this,new ArrayList<MNews>());
m_thirdView.setAdapter(m_newsAdapter);
this.m_thirdView.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index,
long arg3) {
// TODO Auto-generated method stub
MNews news=newsList.get(index);
Intent intent=new Intent(MainActivity.this,NormalWebViewActivity.class);
intent.putExtra("url", news.mRedirectUrl);
startActivity(intent);
}
});
}
void createFourthContent(){
m_fourthContent=new LinearLayout(this);
LinearLayout.LayoutParams lp=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
m_fourthContent.setLayoutParams(lp);
View view=this.m_layoutInflater.inflate(R.layout.fourth_layout, m_fourthContent);
LinearLayout firstCol=(LinearLayout) view.findViewById(R.id.first_col);
LinearLayout secondCol=(LinearLayout) view.findViewById(R.id.second_col);
int leftMargin=DensityUtil.dip2px(40);
int rightMargin=DensityUtil.dip2px(25);
int topMargin=DensityUtil.dip2px(20);
int bottomMargin=DensityUtil.dip2px(20);
int textTopMargin=DensityUtil.dip2px(10);
int textSize=15;
int textColor=Color.GRAY;
int unitWidth=DensityUtil.getLogicalWidth()/2-leftMargin-rightMargin;
int unitHeight=unitWidth;
//gushi start
LinearLayout gushiLayout=new LinearLayout(this);
gushiLayout.setId(this.STORY);
gushiLayout.setOrientation(1);
LinearLayout.LayoutParams lp3=new LinearLayout.LayoutParams(unitWidth, LayoutParams.WRAP_CONTENT);
lp3.leftMargin=leftMargin;
lp3.rightMargin=rightMargin;
lp3.topMargin=topMargin;
lp3.bottomMargin=bottomMargin;
gushiLayout.setLayoutParams(lp3);
ImageView gushiImg=new ImageView(this);
gushiImg.setScaleType(ScaleType.FIT_XY);
LinearLayout.LayoutParams lp31=new LinearLayout.LayoutParams(unitWidth,unitHeight);
gushiImg.setLayoutParams(lp31);
gushiImg.setImageDrawable(this.getResources().getDrawable(R.drawable.gushi));
gushiLayout.addView(gushiImg);
TextView gushiTxt=new TextView(this);
LinearLayout.LayoutParams lp32=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
lp32.gravity=Gravity.CENTER;
gushiTxt.setGravity(Gravity.CENTER);
lp32.topMargin=textTopMargin;
gushiTxt.setLayoutParams(lp32);
gushiTxt.setTextSize(textSize);
gushiTxt.setTextColor(textColor);
gushiTxt.setText(this.getResources().getString(R.string.gushi));
gushiLayout.addView(gushiTxt);
gushiLayout.setOnClickListener(this);
firstCol.addView(gushiLayout);
//gushi end
//huiben start
LinearLayout lianxirenLayout=new LinearLayout(this);
lianxirenLayout.setId(this.HUIBEN);
lianxirenLayout.setOrientation(1);
LinearLayout.LayoutParams lp2=new LinearLayout.LayoutParams(unitWidth, LayoutParams.WRAP_CONTENT);
lp2.leftMargin=rightMargin;
lp2.rightMargin=leftMargin;
lp2.topMargin=topMargin;
lp2.bottomMargin=bottomMargin;
lianxirenLayout.setLayoutParams(lp2);
ImageView lianxirenImg=new ImageView(this);
lianxirenImg.setScaleType(ScaleType.FIT_XY);
LinearLayout.LayoutParams lp21=new LinearLayout.LayoutParams(unitWidth,unitHeight);
lianxirenImg.setLayoutParams(lp21);
lianxirenImg.setImageDrawable(this.getResources().getDrawable(R.drawable.huiben));
lianxirenLayout.addView(lianxirenImg);
TextView lianxirenTxt=new TextView(this);
LinearLayout.LayoutParams lp22=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
lp22.gravity=Gravity.CENTER;
lianxirenTxt.setGravity(Gravity.CENTER);
lp22.topMargin=textTopMargin;
lianxirenTxt.setLayoutParams(lp22);
lianxirenTxt.setTextSize(textSize);
lianxirenTxt.setTextColor(textColor);
lianxirenTxt.setText(this.getResources().getString(R.string.huiben));
lianxirenLayout.addView(lianxirenTxt);
lianxirenLayout.setOnClickListener(this);
secondCol.addView(lianxirenLayout);
//huiben end
//kehouquan start
LinearLayout kehouquanLayout=new LinearLayout(this);
kehouquanLayout.setId(this.KEHOUQUAN);
kehouquanLayout.setOrientation(1);
LinearLayout.LayoutParams lp1=new LinearLayout.LayoutParams(unitWidth, LayoutParams.WRAP_CONTENT);
lp1.leftMargin=leftMargin;
lp1.rightMargin=rightMargin;
lp1.topMargin=0;
lp1.bottomMargin=bottomMargin;
kehouquanLayout.setLayoutParams(lp1);
ImageView kehouquanImg=new ImageView(this);
kehouquanImg.setScaleType(ScaleType.FIT_XY);
LinearLayout.LayoutParams lp11=new LinearLayout.LayoutParams(unitWidth,unitHeight);
kehouquanImg.setLayoutParams(lp11);
kehouquanImg.setImageDrawable(this.getResources().getDrawable(R.drawable.kehouquan));
kehouquanLayout.addView(kehouquanImg);
TextView kehouquanTxt=new TextView(this);
LinearLayout.LayoutParams lp12=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
lp12.gravity=Gravity.CENTER;
kehouquanTxt.setGravity(Gravity.CENTER);
lp12.topMargin=textTopMargin;
kehouquanTxt.setLayoutParams(lp12);
kehouquanTxt.setTextSize(textSize);
kehouquanTxt.setTextColor(textColor);
kehouquanTxt.setText(this.getResources().getString(R.string.kehouquan));
kehouquanLayout.addView(kehouquanTxt);
kehouquanLayout.setOnClickListener(this);
firstCol.addView(kehouquanLayout);
//kehouquan end
//photo start
LinearLayout photoLayout=new LinearLayout(this);
photoLayout.setId(this.PHOTO);
photoLayout.setOrientation(1);
LinearLayout.LayoutParams lp4=new LinearLayout.LayoutParams(unitWidth, LayoutParams.WRAP_CONTENT);
lp4.leftMargin=rightMargin;
lp4.rightMargin=leftMargin;
lp4.topMargin=0;
lp4.bottomMargin=bottomMargin;
photoLayout.setLayoutParams(lp4);
ImageView photoImg=new ImageView(this);
photoImg.setScaleType(ScaleType.FIT_XY);
LinearLayout.LayoutParams lp41=new LinearLayout.LayoutParams(unitWidth,unitHeight);
photoImg.setLayoutParams(lp41);
photoImg.setImageDrawable(this.getResources().getDrawable(R.drawable.photo));
photoLayout.addView(photoImg);
TextView photoTxt=new TextView(this);
LinearLayout.LayoutParams lp42=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
lp42.gravity=Gravity.CENTER;
photoTxt.setGravity(Gravity.CENTER);
lp42.topMargin=textTopMargin;
photoTxt.setLayoutParams(lp42);
photoTxt.setTextSize(textSize);
photoTxt.setTextColor(textColor);
photoTxt.setText(this.getResources().getString(R.string.photo));
photoLayout.addView(photoTxt);
photoLayout.setOnClickListener(this);
secondCol.addView(photoLayout);
//photo end
//qimeng start
LinearLayout qimengLayout=new LinearLayout(this);
qimengLayout.setId(this.QIMENG);
qimengLayout.setOrientation(1);
LinearLayout.LayoutParams lp5=new LinearLayout.LayoutParams(unitWidth, LayoutParams.WRAP_CONTENT);
lp5.leftMargin=leftMargin;
lp5.rightMargin=rightMargin;
lp5.topMargin=0;
lp5.bottomMargin=0;
qimengLayout.setLayoutParams(lp5);
ImageView qimengImg=new ImageView(this);
qimengImg.setScaleType(ScaleType.FIT_XY);
LinearLayout.LayoutParams lp51=new LinearLayout.LayoutParams(unitWidth,unitHeight);
qimengImg.setLayoutParams(lp51);
qimengImg.setImageDrawable(this.getResources().getDrawable(R.drawable.qimeng));
qimengLayout.addView(qimengImg);
TextView qimengTxt=new TextView(this);
LinearLayout.LayoutParams lp52=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
lp52.gravity=Gravity.CENTER;
qimengTxt.setGravity(Gravity.CENTER);
lp52.topMargin=textTopMargin;
qimengTxt.setLayoutParams(lp52);
qimengTxt.setTextSize(textSize);
qimengTxt.setTextColor(textColor);
qimengTxt.setText(this.getResources().getString(R.string.qimeng));
qimengLayout.addView(qimengTxt);
qimengLayout.setOnClickListener(this);
firstCol.addView(qimengLayout);
//qimeng end
//setting start
LinearLayout settingLayout=new LinearLayout(this);
settingLayout.setId(this.SETTING);
settingLayout.setOrientation(1);
LinearLayout.LayoutParams lp6=new LinearLayout.LayoutParams(unitWidth, LayoutParams.WRAP_CONTENT);
lp6.leftMargin=rightMargin;
lp6.rightMargin=leftMargin;
lp6.topMargin=0;
lp6.bottomMargin=0;
settingLayout.setLayoutParams(lp6);
ImageView settingImg=new ImageView(this);
settingImg.setScaleType(ScaleType.FIT_XY);
LinearLayout.LayoutParams lp61=new LinearLayout.LayoutParams(unitWidth,unitHeight);
settingImg.setLayoutParams(lp61);
settingImg.setImageDrawable(this.getResources().getDrawable(R.drawable.setting));
settingLayout.addView(settingImg);
TextView settingTxt=new TextView(this);
LinearLayout.LayoutParams lp62=new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
lp62.gravity=Gravity.CENTER;
settingTxt.setGravity(Gravity.CENTER);
lp62.topMargin=textTopMargin;
settingTxt.setLayoutParams(lp62);
settingTxt.setTextSize(textSize);
settingTxt.setTextColor(textColor);
settingTxt.setText(this.getResources().getString(R.string.setting));
settingLayout.addView(settingTxt);
settingLayout.setOnClickListener(this);
secondCol.addView(settingLayout);
//setting end
}
void reMeasure(){
float rate=(float)123/(float)180;
int imgWidth=this.m_width/4;
int imgHeight=(int) (imgWidth*rate+0.5);
LinearLayout.LayoutParams firstLp=new LinearLayout.LayoutParams(imgWidth,imgHeight);
this.m_firstImg.setLayoutParams(firstLp);
LinearLayout.LayoutParams secondLp=new LinearLayout.LayoutParams(imgWidth,imgHeight);
this.m_secondImg.setLayoutParams(secondLp);
LinearLayout.LayoutParams thirdLp=new LinearLayout.LayoutParams(imgWidth,imgHeight);
this.m_thirdImg.setLayoutParams(thirdLp);
LinearLayout.LayoutParams fourthLp=new LinearLayout.LayoutParams(imgWidth,imgHeight);
this.m_fourthImg.setLayoutParams(fourthLp);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public int getBarHeight(){
Class<?> c = null;
Object obj = null;
Field field = null;
int x = 0, sbar = 38;//
try {
c = Class.forName("com.android.internal.R$dimen");
obj = c.newInstance();
field = c.getField("status_bar_height");
x = Integer.parseInt(field.get(obj).toString());
sbar = getResources().getDimensionPixelSize(x);
} catch (Exception e1) {
e1.printStackTrace();
}
return sbar;
}
void removeView(int currentSelectIndex){
switch(currentSelectIndex){
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
}
}
private final static String MSGKEY = "msgkey";
private void send() {
String contString = m_editTextContent.getText().toString();
if (contString.length() > 0) {
MChatMsgEntity entity = new MChatMsgEntity();
entity.setDate(getDate());
entity.setMsgType(false);
entity.setText(contString);
m_dataArrays.add(entity);
m_adapter.notifyDataSetChanged();
m_editTextContent.setText("");
m_listView.setSelection(m_listView.getCount() - 1);
PushManager.sendMsgToUser(this,appid ,"954515449122882861", MSGKEY, contString);
}
}
private String getDate() {
Calendar c = Calendar.getInstance();
String year = String.valueOf(c.get(Calendar.YEAR));
String month = String.valueOf(c.get(Calendar.MONTH));
String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH) + 1);
String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
String mins = String.valueOf(c.get(Calendar.MINUTE));
StringBuffer sbBuffer = new StringBuffer();
sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":"
+ mins);
return sbBuffer.toString();
}
boolean m_secondViewHasCreate=false;
@Override
public void onClick(View view) {
// TODO Auto-generated method stub
switch(view.getId()){
case R.id.first:
if(this.m_currentSelectIndex==0)
return;
this.m_currentSelectIndex=0;
this.m_content.removeAllViews();
this.m_content.addView(m_firstContent);
break;
case R.id.second:
if(this.m_currentSelectIndex==1)return;
this.m_currentSelectIndex=1;
if(!this.m_secondViewHasCreate){
this.initView();
this.m_secondViewHasCreate=true;
}
this.m_content.removeAllViews();
this.m_content.addView(m_secondContent);
break;
case R.id.third:
if(this.m_currentSelectIndex==2)
return;
this.m_currentSelectIndex=2;
this.m_content.removeAllViews();
this.m_content.addView(m_thirdView);
break;
case R.id.fourth:
if(this.m_currentSelectIndex==3)
return;
this.m_currentSelectIndex=3;
this.m_content.removeAllViews();
this.m_content.addView(m_fourthContent);
break;
case R.id.btn_send:
send();
break;
case STORY:
Intent intent=new Intent(MainActivity.this,StoryListActivity.class);
startActivity(intent);
break;
case HUIBEN:
intent=new Intent(MainActivity.this,HuibenListActivity.class);
startActivity(intent);
break;
case PHOTO:
intent=new Intent(MainActivity.this,PhotoListActivity.class);
startActivity(intent);
break;
case R.id.fabu:
intent=new Intent(MainActivity.this,EditContentActivity.class);
startActivity(intent);
break;
case R.id.website:
String host = "bcs.duapp.com";
BCSCredentials credentials = new BCSCredentials("IT1wrHzZQCOQUSzeaUR1lCgb", "<KEY>");
BaiduBCS baiduBCS = new BaiduBCS(credentials, host);
// baiduBCS.setDefaultEncoding("GBK");
baiduBCS.setDefaultEncoding("UTF-8"); // Default UTF-8
InputStream fileContent=this.getResources().openRawResource(R.raw.baba1);
//File file =new File("/sdcard/ayouer/image/");
//InputStream fileContent;
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType("image/jpg");
try {
objectMetadata.setContentLength(fileContent.available());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PutObjectRequest request = new PutObjectRequest("sst-youer", "/image/test", fileContent, objectMetadata);
ObjectMetadata result = baiduBCS.putObject(request).getResult();
;
intent=new Intent(MainActivity.this,NormalWebViewActivity.class);
intent.putExtra("url", "http://hpefhy.zgyey.com/Default.aspx");
startActivity(intent);
break;
}
this.selectView(this.m_currentSelectIndex);
}
@Override
public void onMessage(com.way.bean.Message message) {
// TODO Auto-generated method stub
Message handlerMsg = handler.obtainMessage(NEW_MESSAGE);
handlerMsg.obj = message;
handler.sendMessage(handlerMsg);
}
@Override
public void onBind(String method, int errorCode, String content) {
// TODO Auto-generated method stub
}
@Override
public void onNotify(String title, String content) {
// TODO Auto-generated method stub
}
@Override
public void onNetChange(boolean isNetConnected) {
// TODO Auto-generated method stub
if (!isNetConnected) {
T.showShort(this, R.string.net_error_tip);
//mNetErrorView.setVisibility(View.VISIBLE);
} else {
//mNetErrorView.setVisibility(View.GONE);
}
}
@Override
public void onNewFriend(User u) {
// TODO Auto-generated method stub
Message handlerMsg = handler.obtainMessage(NEW_FRIEND);
handlerMsg.obj = u;
handler.sendMessage(handlerMsg);
}
}
<file_sep>package com.youer.adapter;
import java.util.List;
import com.example.youer.R;
import com.way.app.PushApplication;
import com.way.bean.User;
import com.youer.modal.MStory;
import com.youer.modal.MStory1;
import com.youer.tool.DensityUtil;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
public class HuibenAdapter extends BaseAdapter {
List<MStory1> m_storyList;
Context m_context;
LayoutInflater m_layoutInflater;
//float m_rate=(float)446/(float)630;
public HuibenAdapter(Context context,List<MStory1> storyList){
this.m_context=context;
this.m_storyList=storyList;
this.m_layoutInflater=LayoutInflater.from(m_context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return this.m_storyList.size();
}
@Override
public Object getItem(int index) {
// TODO Auto-generated method stub
return this.m_storyList.get(index);
}
@Override
public long getItemId(int index) {
// TODO Auto-generated method stub
return index;
}
@Override
public View getView(int index, View view, ViewGroup parent) {
// TODO Auto-generated method stub
MStory1 story=this.m_storyList.get(index);
ViewHolder holder=null;
if(view==null){
view=this.m_layoutInflater.inflate(R.layout.huiben_list_item,null);
holder=new ViewHolder();
holder.mTitleImageView=(ImageView) view.findViewById(R.id.story_title_img);
holder.mTitle=(TextView) view.findViewById(R.id.title);
holder.mTime=(TextView) view.findViewById(R.id.time);
view.setTag(holder);
}else{
holder=(ViewHolder) view.getTag();
}
holder.mTitleImageView.setBackgroundResource(story.mTitleImg);
RelativeLayout.LayoutParams imgLp=new RelativeLayout.LayoutParams(DensityUtil.getLogicalWidth()-DensityUtil.dip2px(20),(int) (story.mRate*(DensityUtil.getLogicalWidth()-DensityUtil.dip2px(20))));
imgLp.width=DensityUtil.getLogicalWidth()-DensityUtil.dip2px(20);
imgLp.height=(int) (imgLp.width*story.mRate);
holder.mTitleImageView.setLayoutParams(imgLp);
holder.mTitle.setText(story.mName);
return view;
}
static class ViewHolder{
public ImageView mTitleImageView;
public TextView mTitle;
public TextView mTime;
}
}
<file_sep>package com.way.bean;
import java.io.Serializable;
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String UserId;//
private String channelId;
private String nick;//
private int headIcon;//
private int group;
private int role;
private int id;
private String phoneNum="13416111872";
public User(int id,String UserId,int role, String channelId, String nick, int headIcon,
int group,String phoneNum) {
// TODO Auto-generated constructor stub
this.UserId = UserId;
this.channelId = channelId;
this.nick = nick;
this.headIcon = headIcon;
this.group = group;
this.role=role;
this.id=id;
this.phoneNum=phoneNum;
}
public User() {
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum=phoneNum;
}
public String getUserId() {
return UserId;
}
public void setUserId(String userId) {
UserId = userId;
}
public int getId(){
return this.id;
}
public void setId(int id){
this.id=id;
}
public int getRole(){
return this.role;
}
public void setRole(int role){
this.role=role;
}
public String getChannelId() {
return channelId;
}
public void setChannelId(String channelId) {
this.channelId = channelId;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
public int getHeadIcon() {
return headIcon;
}
public void setHeadIcon(int headIcon) {
this.headIcon = headIcon;
}
public int getGroup() {
return group;
}
public void setGroup(int group) {
this.group = group;
}
@Override
public String toString() {
return "User [UserId=" + UserId + ", channelId=" + channelId
+ ", nick=" + nick + ", headIcon=" + headIcon + ", group="
+ group + "]";
}
}
<file_sep>youeryuan
=========
<file_sep>package com.youer.modal;
import java.io.Serializable;
import java.util.List;
public class MNotify implements Serializable{
public int mId;
public String mTitle;
public String mDescription;
public String mContent;
public List<MVideo> mVideoList;
public List<MImage> mImageList;
public boolean mIsNative=true;
public String mRedirectUrl;
public String mTime;
}
| 5da9e278b012a1507f28efa8fcb74b37cdb215b6 | [
"Markdown",
"Java"
] | 12 | Java | Zhishine/youeryuan | dbce3d97559f156649a35ffccb2fe8699a6c3d34 | bb731185fa0d2ed75b122a7dae80ccd79070c554 |
refs/heads/master | <repo_name>Yujingchen/client-panel<file_sep>/src/actions/types.js
export const NOTIFY_USER = "NOTIFY_USER";
export const DISABEL_BALANCE_ON_ADD = "DISABEL_BALANCE_ON_ADD";
export const DISABEL_BALANCE_ON_EDIT = "DISABEL_BALANCE_ON_EDIT";
export const ALLOW_REGISTRATION = "ALLOW_REGISTRATION";
| 9a3412980f6c320256755bd0d1267599eddbb7cb | [
"JavaScript"
] | 1 | JavaScript | Yujingchen/client-panel | d764c1a07f6353dbffa9ee0d065d2d29c8b2f576 | bc0f82e89fdd41ddb16316888098506e8701b81e |
refs/heads/master | <file_sep>-- phpMyAdmin SQL Dump
-- version 4.3.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: 2015-07-16 08:17:37
-- 服务器版本: 5.6.21-log
-- PHP Version: 5.3.29
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
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 utf8 */;
--
-- Database: `library`
--
-- --------------------------------------------------------
--
-- 表的结构 `book`
--
CREATE TABLE IF NOT EXISTS `book` (
`bookId` int(11) NOT NULL,
`bookName` varchar(80) NOT NULL,
`bookAuthor` varchar(20) NOT NULL,
`bookPress` varchar(30) NOT NULL,
`bookPressTime` varchar(4) NOT NULL,
`bookISBN` varchar(100) NOT NULL,
`bookPicture` varchar(100) NOT NULL,
`bookType` int(11) NOT NULL,
`bookInfo` text NOT NULL,
`bookAddTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`bookFindNumber` varchar(20) NOT NULL,
`bookTotalAmount` tinyint(4) NOT NULL,
`bookAccessAmount` tinyint(4) NOT NULL,
`bookHistory` int(11) DEFAULT '0'
) ENGINE=InnoDB AUTO_INCREMENT=46 DEFAULT CHARSET=utf8;
--
-- 转存表中的数据 `book`
--
INSERT INTO `book` (`bookId`, `bookName`, `bookAuthor`, `bookPress`, `bookPressTime`, `bookISBN`, `bookPicture`, `bookType`, `bookInfo`, `bookAddTime`, `bookFindNumber`, `bookTotalAmount`, `bookAccessAmount`, `bookHistory`) VALUES
(2, '福尔摩斯探案全集', '亚瑟·柯南·道尔', '中华书局', '2012', '978-7-101-08911-0', 'http://localhost:8000/LibraryTest/context/img/book/1507130858142.jpg', 3, '《福尔摩斯探案全集》可谓是开辟了侦探小说历史“黄金时代”的不朽经典。福尔摩斯小说,一百多年来被译成57种文字,风靡全世界,被推理迷们称为推理小说中的《圣经》,是历史上最受读者推崇、绝对不能错过的侦探小说,也是一本老少咸宜的奇妙书籍。从《暗红习作 》诞生到现在的一百多年间,福尔摩斯打遍天下无敌手,影响力早已越过推理一隅,成为人们心中神探的代名词。《福尔摩斯探案全集》的出版使福尔摩斯在英国读者中成为妇孺皆知的英雄,也使其作者柯南·道尔一举成名,后人更是称其为“侦探小说之父”。', '2015-07-13 12:58:14', 'I561.456', 4, 0, 3),
(3, '平凡的世界', '路遥', '北京十月文艺出版社', '2012', '978-7-5302-1200-4', 'http://localhost:8000/LibraryTest/context/img/book/1507130904203.jpg', 4, '《平凡的世界(套装共3册)》是一部现实主义小说,也是小说化的家族史。作家高度浓缩了中国西北农村的历史变迁过程,作品达到了思想性与艺术性的高度统一,特别是主人公面对困境艰苦奋斗的精神,对今天的大学生朋友仍有启迪。这是一部全景式地表现中国当代城乡社会生活的长篇小说。《平凡的 世界(套装共3册)》共三部。作者在近十年问广阔背景上,通过复杂的矛盾纠葛,刻画了社会各阶层众多普通人的形象。劳动与爱情,挫折与追求,痛苦与欢乐,日常生活与巨大社会冲突,纷繁地交织在一起,深刻地展示了普通人在大时代历史进程中所走过的艰难曲折的道路。', '2015-07-13 13:04:20', 'I247.57', 5, 1, 3),
(4, '神雕侠侣', '金庸', '广州出版社', '2013', '978-7-5462-1335-4', 'http://localhost:8000/LibraryTest/context/img/book/1507130905244.jpg', 5, '《神雕侠侣》讲述了南宋年间,蒙古大军围攻襄阳城。大侠郭靖带领城内军民殊死抵抗。郭靖义弟杨康的遗腹子杨过投身古墓派,并与师父小龙女展开一场为世俗所不容的师徒之恋。欲杀郭靖为父报仇的杨过,最终却感于郭靖“侠之大者、为国为民”的赤子之心,毅然助其守城。屡建奇功的神雕大侠杨过,身受断臂之痛、情花之毒,却不畏艰难险阻,一心追求自己的真爱,经历世人难以想象的种种磨难,有情人终成眷属。', '2015-07-13 13:05:24', 'I247.58', 6, 4, 3),
(5, '鲁迅全集', '鲁迅', '人民文学出版社', '2005', '7-02-005033-6', 'http://localhost:8000/LibraryTest/context/img/book/1507130906445.jpg', 11, '新版《鲁迅全集》由原来的16卷增至18卷,书信、日记各增加了一卷,共计创作10卷,书信4卷,日记3卷,索引1卷,总字数约700万字。与1981年版相比,此次《鲁迅全集》修订集中在三个方面:佚文佚信的增收;原著的文本校勘;注释的增补修改。 ★收文:书信、日记各增加了一卷 此次修订,增收新的佚文23篇,佚信20封,鲁迅致许广平的《两地书》原信68封,鲁迅与增田涉答问函件集编文字约10万字。 ', '2015-07-13 13:06:44', 'I210.1', 9, 4, 1),
(11, '倚天屠龙记', '金庸', '广州出版社', '2013', '978-7-5462-1337-8', 'http://localhost:8000/LibraryTest/context/img/book/1507130910136.jpg', 5, '《金庸作品集(16-19):倚天屠龙记(新修版)(套装共4册)》以元朝末年为历史背景,叙述了明教教主、武当弟子张无忌率领明教教众和江湖豪杰反抗元朝暴政的故事。不祥的屠龙刀使主人公少年张无忌幼失怙恃,身中玄冥毒掌,历尽江湖险恶、种种磨难,最终却造就他一身的绝世武功和慈悲心怀。他是统驭万千教众和武林豪杰的盟主,为救世人于水火可以慷慨赴死;他是优柔寡断的多情少年,面对深爱他的赵敏、周芷若和蛛儿,始终无法做出感情抉择。\r\n', '2015-07-13 13:10:13', 'I247', 5, 3, 0),
(12, '南音', '笛安', '长江文艺出版社', '2012', '978-7-5354-5252-8', 'http://localhost:8000/LibraryTest/context/img/book/1507130913557.jpg', 4, '《南音(上)》编辑推荐:经过了《西决》的舒缓,以及《东霓》的恣意,“龙城三部曲”的落幕之作——《南音》更为复杂,也更为沉重。前两部中登场过的几乎所有角色,在《南音》里都将面临全新的考验。一幕幕更为尖锐的冲突就此上演,关于忠诚和背叛,关于在几种质地不同却同样真诚的“爱”里 的选择,甚至关于正邪是非,关于罪孽和救赎,关于生死。笛安用超越年龄的睿智、沉稳与娴熟的文字,丰满而立体的展现了一个家族的命运。', '2015-07-13 13:13:55', 'I247.5', 4, 0, 2),
(13, '最好的我们', '八月长安', '湖南文艺出版社', '2013', '978-7-5404-6264-2', 'http://localhost:8000/LibraryTest/context/img/book/1507130914358.jpg', 4, '本书以怀旧的笔触讲述了女主角耿耿和男主角余淮同桌三年的故事,耿耿余淮,这么多年一路走过的成长故事极为打动人心,整个故事里有的都是在成长过程中细碎的点点滴滴,将怀旧写到了极致,将记忆也写到了极致。', '2015-07-13 13:14:35', 'I247.56', 6, 5, 0),
(14, '原来你还在这里', '辛夷坞', '朝华出版社', '2007', '978-7-5054-1773-1', 'http://localhost:8000/LibraryTest/context/img/book/1507130918069.jpg', 13, '苏韵锦爱上了高中同学程铮,程铮也深深爱着她。但是家庭背景不同的二人,生活上的差异要彼此分开。而韵锦在分开之后才发觉有了程铮的孩子。个性强的韵锦没有告知程铮。在几年后,韵锦事业有成发觉程铮又出现在她的生活中,她们的爱情会开花结果吗?\r\n', '2015-07-13 13:18:06', 'I247.1', 6, 1, 0),
(15, '超级公务员', '水浒', '中国青年出版社', '2014', '978-7-5153-1772-4', 'http://localhost:8000/LibraryTest/context/img/book/15071309185110.jpg', 4, '这是一部当代的新官场小说,也是一部标准的主旋律小说。把官场小说和主旋律小说结合到一起,是这部小说的最大特色。小说写了一个出身草根家庭的“普通”青年,是怎样从一个社会底层的大学生一步步成为你不大可能想象的超级公务员,三十岁出头就担任了正局级市委书记。这位主人公的仕途,可谓惊心动魄。他靠着自己的良心和智慧,一路过五关斩六将,横扫江湖混混儿、黑商和贪官。这部小说还触及了当今社会改革的部分难点和热点。从书中,你可以体会到做一个受人民欢迎的好官实在太难。钢铁是怎样炼成的,看了本书你就会有答案。', '2015-07-13 13:18:51', 'I247.50', 7, 5, 0),
(16, '人的问题', '托马斯·内格尔', '上海译文出版社', '2014', '978-7-5327-6561-4', 'http://localhost:8000/LibraryTest/context/img/book/15071309193811.jpg', 8, '《人的问题》探讨人生的意义、本质和价值。作者从对待死亡、性行为、社会不平等、自由和价值等更为基本的哲学问题,引申出有关人格同一性、意识、自由和价值等更为基本的哲学问题。贯串全书的中心,乃是个体的人生观及其与各种非个人的实在概念的关系这一问题。正是这个问题,突破了哲学内部的界线,从伦理学延伸到形而上学。同样出于对这个问题的关注,引发了论述心的哲学、论荒诞、论道德运气的文章。作者的论述清晰明了,体现了分析哲学的特有风格。\r\n', '2015-07-13 13:19:38', 'B821-49', 4, 3, 0),
(17, '圣经导读', '戈登·菲 道格拉斯·斯图尔特', '北京大学出版社', '2005', '7-301-09324-1', 'http://localhost:8000/LibraryTest/context/img/book/15071309204112.jpg', 12, '《圣经导读》由两位著名的圣经学者联手合著。书中概述了圣经著作的主要文学类型,并且提出了不同类型的解释原则。作者在每一部分都提供了深入浅出的实例分析,帮助读者学会解读圣经的方法。该书出版后备受欢迎,已成为圣经读者必备的参考书。\r\n', '2015-07-13 13:20:41', 'B971', 2, 2, 0),
(19, '微观经济理论', '安德鲁·马斯-科莱尔', '中国人民大学出版社', '2014', '978-7-300-19986-3', 'http://localhost:8000/LibraryTest/context/img/book/15071309215413.jpg', 9, '《微观经济理论》一书是最近十余年来欧美经济学界最具影响力的微观经济学教科书。本书涵盖了当今经济学基础理论中的几乎所有重大命题、核心思想和严格的数学证明,是一本高度抽象和严谨但又强调直觉的大作。本书是公认的微观经济理论的圣经,已被国外几乎所有的一流大学采用,是经济学学子的必读教科书。\r\n', '2015-07-13 13:21:54', 'F016', 6, 1, 0),
(20, '山月不知心底事', '辛夷坞', '朝华出版社', '2008', '978-7-5054-1834-9', 'http://localhost:8000/LibraryTest/context/img/book/15071309225314.jpg', 13, '十七年前的月亮下,叶骞泽对向远说:我们永远不会分开,后来他还是离开了,向远一直以为,分开他们的是时间,是距离,是人生不可控制的转折,后来才知道,即使他贸住了叶骞泽,总有一天,当他遇上了叶灵,她还是会爱上她。\r\n', '2015-07-13 13:22:53', 'I247.23', 3, 1, 0),
(21, '元好问诗编年校注', '元好问', '中华书局', '2011', '978-7-101-07579-3', 'http://localhost:8000/LibraryTest/context/img/book/15071309234415.jpg', 11, '此为金元大家元好问诗集的全新整理本,分校勘、编年、注释三部分。校勘部分以毛本为底本,以李诗本、李全本、施本为主校本,参校方本、郭本、姚本,力求超越前贤,接近元好问诗的原貌;编年方面,主要以狄宝心的《元好问年谱新编》为基础,结合校注成果,对元氏全部诗作做系统考察,对相关成果得失做全面梳理;注释方面,近世注本皆为选本,此次针对现今研究需要提供较详的全诗注释\r\n', '2015-07-13 13:23:44', 'I222.746', 2, 2, 0),
(22, '晨昏', '辛夷坞', '江苏文艺出版社', '2013', '978-7-5399-6200-9', 'http://localhost:8000/LibraryTest/context/img/book/15071309243016.jpg', 13, '“有我陪着你,什么都不用害怕。”一句话,像是一个魔咒,攥住了两个人的心,注定了三个人的宿命。妖艳的止安是一团火,柔软的止怡是一汪水。纪廷就在这水火之间,辜负了水的温柔,却无法触及火的热烈。或许是可以触及的,只是太过滚烫,所以更多的时候只是远望。如果他不顾一切,那火将焚毁的又岂止是他一个人的身?“你到底是不想,不敢,还是……不行?” “你知道吗,纪廷,我看不起你。”为了报复,也是因为疲惫,止安选择了远离。可逃得越远,也意味着她的不安越深。 夜航鸟不停地飞啊飞啊飞,心中的岛屿就在那里,却不敢停下。 这才发现自己走得那么急,竟然是因为不敢回头,害怕蓦然回首,再也找不到当初的那个少年。\r\n', '2015-07-13 13:24:30', 'I246.56', 4, 0, 0),
(23, '天机', '蔡骏', '南海出版公司', '2014', '978-7-5442-7051-9', 'http://localhost:8000/LibraryTest/context/img/book/15071309253117.jpg', 4, '本书是中国当代长篇小说。本套书共四本。一个十九人的旅游团无意中来到泰国一个神秘城市南明市,找不到出口离开。这个神秘城市设施一应俱全,但空无一人,时间定格在一年前,手机也没有信号。十九人开始寻找出路,在此过程中,三个人接连神秘死去。\r\n', '2015-07-13 13:25:31', 'I24.34', 3, 3, 0),
(24, '长相思', '桐华', '湖南文艺出版社', '2013', '978-7-5404-6007-5', 'http://localhost:8000/LibraryTest/context/img/book/15071309261218.jpg', 13, '本书为中国当代长篇小说。讲述了:生命是一场又一场的相遇和别离,是一次又一次的遗忘和开始,可总有些事,一旦发生,就留下印迹;总有个人,一旦来过,就无法忘记。这一场清水镇的相遇改变了所有人的命运,甚至改变了整个大荒的命运。只为贪图那一点温暖、一点陪伴,一点不知道什么时候会消散的死心塌地。相思是一杯有毒的美酒,入喉甘美,销魂蚀骨,直到入心入肺,便再也无药可解,毒发时撕心裂肺,只有心上人的笑容可解,陪伴可解,若是不得,便只余刻骨相思,至死不休。\r\n', '2015-07-13 13:26:12', 'I243.5', 3, 2, 0),
(27, '亚瑟王之死', '托马斯·马洛礼', '人民文学出版社', '2005', '978-7-02-006135-8', 'http://localhost:8000/LibraryTest/context/img/book/15071309272619.jpg', 4, '《亚瑟王之死(上下册)(插图本)》是欧洲骑士文学中的一朵奇葩,在西方流传之广仅次于《圣经》和莎士比亚的作品。他讲述了著名的不列颠国王亚瑟及其圆桌骑士的故事。字里行间充满了冒险、传奇、各种奇迹和精彩的打斗场面。最令人爱不释手的是骑士与贵妇人之间惊世骇俗的爱情描写。', '2015-07-13 13:27:26', 'I561.41', 2, 2, 0),
(28, '金粉世家', '张恨水', '人民文学出版社', '2009', '978-7-02-007192-0', 'http://localhost:8000/LibraryTest/context/img/book/15071309281320.jpg', 4, '小说以豪门公子金燕西与平民女子冷清秋恋爱、结婚、反目、离散为主线,深刻描写了北洋军阀统治时期贵族之家的盛衰,多角度地透视了上层显宦世家金玉其外、败絮其中的生活与思想面貌。\r\n', '2015-07-13 13:28:13', 'I146.57', 3, 2, 0),
(29, '一九八四', '乔治·奥威尔', '译林出版社', '2011', '978-7-5447-2002-1', 'http://localhost:8000/LibraryTest/context/img/book/15071309285621.jpg', 4, '本书是一本英汉对照的英国现代长篇小说。', '2015-07-13 13:28:56', 'I561.45', 2, 2, 0),
(30, '牧羊少年奇幻之旅', '保罗·柯艾略', '南海出版公司', '2009', '978-7-5442-4419-0', 'http://localhost:8000/LibraryTest/context/img/book/15071309294422.jpg', 6, '牧羊少年圣地亚哥接连两次做了同一个梦,梦见埃及金字塔附近藏有一批宝藏。少年卖掉羊群,历尽千辛万苦一路向南,跨海来到非洲,穿越“死亡之海”撒哈拉大沙漠……期间奇遇不断,在一位炼金术士的指引下,他终于到达金字塔前,悟出了宝藏的真正所在……\r\n', '2015-07-13 13:29:44', 'I777.45', 2, 2, 0),
(31, '偷影子的人', '马克·莱维', '湖南文艺出版社', '2012', '978-7-5404-5595-8', 'http://localhost:8000/LibraryTest/context/img/book/15071309303723.jpg', 4, '不知道姓氏的克蕾儿。这就是你在我生命里的角色,我童年时的小女孩,今日蜕变成了女人,一段青梅竹马的回忆,一个时间之神没有应允的愿望。\r\n', '2015-07-13 13:30:37', 'I565.45', 6, 3, 0),
(32, '谁杀了她', '东野圭吾', '南海出版公司', '2012', '978-7-5442-5699-5', 'http://localhost:8000/LibraryTest/context/img/book/15071309311624.jpg', 3, '本书是一部让东野圭吾提心吊胆、日本出版社吃足苦头、引爆网路推理大战的最高争议作,《谁杀了她》回归究极解谜之趣、开启实验推理新格局,东野圭吾向读者下战书,书末为谜团投下未解悬念震撼弹!\r\n', '2015-07-13 13:31:16', 'I313.45', 7, 3, 0),
(34, '你的孤独虽败犹荣', '刘同', '中信出版社', '2014', '978-7-5086-4505-6', 'http://localhost:8000/LibraryTest/context/img/book/15071309320625.jpg', 8, '“很长一段日子里,我靠写东西度过了太多的小无聊,伪伤感,假满足与真茫然 。我在意细节,算敏感。但知道体谅,算善良。我说喜欢便是喜欢,我不想回答便是真的不知道如何作答。有时我佯装镇定或笑得开心,心里总觉得自己与这个世界格格不入。不停对抗,学着顺从,冷静旁观,终明白我们都不应该是别人世界的参与者,而是自己世界的建造者。\r\n', '2015-07-13 13:32:06', 'B821.49', 6, 1, 0),
(35, '我是猫', '夏目漱石', '安徽师范大学出版社', '2014', '978-7-5676-0512-1', 'http://localhost:8000/LibraryTest/context/img/book/15071309333926.jpg', 4, '本书主人公以一只猫的身份, 俯视着日本当时的社会, 俯视着二十世纪所谓现代文明的大潮, 同时发出种种嘲弄和讥讽。\r\n', '2015-07-13 13:33:39', 'I313.44', 2, 0, 0),
(36, '安娜·卡列尼娜', '列夫·托尔斯泰', '上海译文出版社', '2013', '978-7-5327-5899-9', 'http://localhost:8000/LibraryTest/context/img/book/15071309342427.jpg', 4, '本书是俄罗斯文豪列夫·托尔斯泰的主要作品之一。贵族妇女安娜追求爱情幸福,却在卡列宁的虚伪、冷漠和弗龙斯基的自私面前碰得头破血流,最终落得卧轨自杀、陈尸车站的下场。庄园主莱温反对土地私有制,抵制资本主义制度,同情贫苦农民,却又无法摆脱贵族习气而陷入无法解脱的矛盾之中。矛盾的时期、矛盾的制度、矛盾的人物、矛盾的心理,使全书在矛盾的漩涡中颠簸。\r\n', '2015-07-13 13:34:24', 'I512.44', 2, 2, 0),
(37, '目送', '龙应台', '生活·读书·新知三联书店', '2009', '978-7-108-03291-1', 'http://localhost:8000/LibraryTest/context/img/book/15071309350528.jpg', 11, '目送共由七十四篇散文组成,是为一本极具亲情、感人至深的文集。由父亲的逝世、母亲的苍老、儿子的离开、朋友的牵挂、兄弟的携手共行,写出失败和脆弱、失落和放手,写出缠绵不舍和绝然的虚无。正如作者所说:“我慢慢地、慢慢地了解到,所谓父女母子一场,只不过意味着,你和他的缘分就是今生今世不断地在目送他的背影渐行渐远。\r\n', '2015-07-13 13:35:05', 'I267', 2, 2, 0),
(39, '白夜行', '东野圭吾', '南海出版社', '2008', '978-7-5442-4251-6', 'http://localhost:8000/LibraryTest/context/img/book/15071309354929.jpg', 4, '“我的天空里没有太阳,总是黑夜,但并不暗,因为有东西代替了太阳。虽然没有太阳那么明亮,但对我来说已经足够。凭借着这份光,我便能把黑夜当成白天。我从来就没有太阳,所以不怕失去”。\r\n', '2015-07-13 13:35:49', 'I313.4', 7, 4, 0),
(40, '货币金融学', '弗雷德里克·S·米什金', '中国人民大学出版社', '2011', '978-7-300-12926-6', 'http://localhost:8000/LibraryTest/context/img/book/15071309363330.jpg', 3, '本书是货币银行学领域的一本经典著作,自十几年前引入中国以来,一直畅销不衰。由于次贷危机及其所引发的一系列事件极大地改变了金融体系的结构与中央银行的运作模式,因此,本书有关这方面的内容几乎全部进行了改写。此外,围绕次贷危机,本书适时增加了很多新的内容、应用和专栏。虽然本版较前一版做了较大的改动,但依然保留了其作为最畅销货币银行学教材的基本优点,即建立一个统一的分析框架,用基本经济学理论帮助学生理解金融市场结构、外汇市场、金融机构管理以及货币政策在经济中的作用等问题。本书适用于货币金融学课程,同时,作为一部经典著作,它也可以作为很多渴望了解货币金融知识的人的学习用书和参考读物。\r\n', '2015-07-13 13:36:33', 'F820', 4, 2, 0),
(42, '微观经济学十八讲', '平新乔', '北京大学出版社', '2001', '7-301-04880-7', 'http://localhost:8000/LibraryTest/context/img/book/15071309371131.jpg', 9, '本书包括了消费者选择、企业行为、市场产业组织与博弈论、信息经济学与公共经济学等基本内容,反映了微观经济学在世纪之初的最新研究成果。\r\n', '2015-07-13 13:37:11', 'F16', 4, 3, 0),
(43, '洞穴奇案', '彼得·萨伯', '三联书店', '2012', '978-7-108-03987-3', 'http://localhost:8000/LibraryTest/context/img/book/15071309380232.jpg', 10, '本书讲述五名洞穴探险人受困山洞,水尽粮绝;为了生存,大家约定抽签吃掉一人,牺牲一个以救活其余四人。威特摩尔是这一方案的提议人,不过抽签前又收回了意见,其它四人却执意坚持,结果恰好是威特摩尔被抽中。获救后,这四人以杀人罪被起诉。\r\n', '2015-07-13 13:38:02', 'D971.2', 2, 2, 0),
(44, '风险社会', '乌尔里希·贝克', '译林出版社', '2004', '7-80657-565-0', 'http://localhost:8000/LibraryTest/context/img/book/15071309384233.jpg', 10, '乌尔里希·贝克将后现代社会诠释为风险社会,其主要特征在于:人类面临着威胁其生存的由社会所制造的风险。我们身处其中的社会充斥着组织化不负责任的态度,尤其是,风险的制造者以风险牺牲品为代价来保护自己的利益。作者认为西方的经济制度、法律制度和政治制度不仅卷入了风险制造,而且参与了对风险真相的掩盖。贝克力倡反思性现代化,其特点是既洞察到现代性中理性的困境,又试图以理性的精神来治疗这种困境。\r\n', '2015-07-13 13:38:42', 'C91', 5, 4, 0),
(45, '相约星期二', '米奇·阿尔博姆', '上海译文出版社', '1998', '7-5327-2234-1', 'http://localhost:8000/LibraryTest/context/img/book/15071309391834.jpg', 8, '莫里是一位年逾七旬,身患绝症的社会学心理教授,1994年,当他知道自己即将因病离开这个世界的时候,他与自己的学生,美国著名专栏作家米奇・阿尔博姆相约,每个星期二给学生上最后一门课,课程的名字是人生,课程的内容是这位社会学教授对人生宝贵的思考,课程总共上了十四周,最后一堂是老人的葬礼。老人谢世后,学生把听课笔记整理出版,定名为《相约星期二》。书中涉及有关世界与死亡,家庭与感情,金钱与永恒的爱等人生永远的话题。该书一出,立即引起全美的轰动,连续40周名列美国图书畅销排行榜。中译本出版后,也引起了国内各界的广泛关注―――感召力是没有国界的。作家余秋雨在此书的序言中说:“他把课堂留下了,课堂越变越大,现在延伸到了中国。我向过路的朋友们大声招呼:来,值得进去听听。”\r\n', '2015-07-13 13:39:18', 'B821', 2, 1, 0);
-- --------------------------------------------------------
--
-- 表的结构 `bookstore`
--
CREATE TABLE IF NOT EXISTS `bookstore` (
`userId` int(11) NOT NULL DEFAULT '0',
`bookId` int(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- 转存表中的数据 `bookstore`
--
INSERT INTO `bookstore` (`userId`, `bookId`) VALUES
(14, 2),
(14, 4),
(32, 4),
(14, 13);
-- --------------------------------------------------------
--
-- 表的结构 `borrow`
--
CREATE TABLE IF NOT EXISTS `borrow` (
`userId` int(11) NOT NULL DEFAULT '0',
`bookId` int(11) NOT NULL DEFAULT '0',
`borrowDate` date DEFAULT NULL,
`borrowReturnDate` date DEFAULT NULL,
`isLate` tinyint(4) DEFAULT '0',
`isAgainBor` tinyint(4) DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- 转存表中的数据 `borrow`
--
INSERT INTO `borrow` (`userId`, `bookId`, `borrowDate`, `borrowReturnDate`, `isLate`, `isAgainBor`) VALUES
(14, 3, '2015-07-15', '2015-09-15', 0, 1),
(14, 5, '2015-07-15', '2015-08-15', 0, 0),
(14, 12, '2015-07-15', '2015-08-15', 0, 0),
(30, 2, '2015-07-14', '2015-08-14', 0, 0),
(32, 3, '2015-07-14', '2015-08-14', 0, 0),
(32, 4, '2015-07-14', '2015-08-14', 0, 0);
-- --------------------------------------------------------
--
-- 表的结构 `returning`
--
CREATE TABLE IF NOT EXISTS `returning` (
`returnId` int(11) NOT NULL,
`userId` int(11) NOT NULL DEFAULT '0',
`bookId` int(11) NOT NULL DEFAULT '0',
`borrowDate` date DEFAULT NULL,
`returnDate` date DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
--
-- 转存表中的数据 `returning`
--
INSERT INTO `returning` (`returnId`, `userId`, `bookId`, `borrowDate`, `returnDate`) VALUES
(1, 14, 2, '2015-07-14', '2015-07-15'),
(2, 15, 2, '2015-07-14', '2015-07-15'),
(3, 14, 12, '2015-07-15', '2015-07-15'),
(4, 14, 4, '2015-07-15', '2015-07-15');
-- --------------------------------------------------------
--
-- 表的结构 `subscribe`
--
CREATE TABLE IF NOT EXISTS `subscribe` (
`userId` int(11) NOT NULL DEFAULT '0',
`bookId` int(11) NOT NULL DEFAULT '0',
`stete` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- --------------------------------------------------------
--
-- 表的结构 `type`
--
CREATE TABLE IF NOT EXISTS `type` (
`typeId` int(11) NOT NULL,
`typeName` varchar(20) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;
--
-- 转存表中的数据 `type`
--
INSERT INTO `type` (`typeId`, `typeName`) VALUES
(3, '侦探小说'),
(4, '长篇小说'),
(5, '武侠小说'),
(6, '中篇小说'),
(7, '诗歌'),
(8, '哲学'),
(9, '经济学'),
(10, '社会学'),
(11, '作品集'),
(12, '文学研究'),
(13, '爱情小说');
-- --------------------------------------------------------
--
-- 表的结构 `user`
--
CREATE TABLE IF NOT EXISTS `user` (
`userId` int(11) NOT NULL,
`userName` varchar(16) NOT NULL,
`userPassword` char(32) NOT NULL,
`useright` tinyint(4) DEFAULT '0',
`userNickname` varchar(20) DEFAULT NULL,
`userEmail` varchar(50) DEFAULT NULL,
`userPhone` varchar(11) DEFAULT NULL
) ENGINE=InnoDB AUTO_INCREMENT=33 DEFAULT CHARSET=utf8;
--
-- 转存表中的数据 `user`
--
INSERT INTO `user` (`userId`, `userName`, `userPassword`, `useright`, `userNickname`, `userEmail`, `userPhone`) VALUES
(14, 'caoxun01', '<PASSWORD>', 0, NULL, '<EMAIL>', '13902011060'),
(15, 'caoxun02', '<PASSWORD>', 0, NULL, '<EMAIL>', '13902011060'),
(16, 'admin', '<PASSWORD>', 2, NULL, '<EMAIL>', '13902011060'),
(20, 'library04', 'e10adc3949ba59abbe56e057f20f883e', 1, NULL, NULL, NULL),
(21, 'library05', 'e10adc3949ba59abbe56e057f20f883e', 1, NULL, NULL, NULL),
(24, 'library06', 'e10adc3949ba59abbe56e057f20f883e', 1, NULL, NULL, NULL),
(26, 'library07', 'e10adc3949ba59abbe56e057f20f883e', 1, NULL, NULL, NULL),
(28, 'library08', 'e10adc3949ba59abbe56e057f20f883e', 1, NULL, NULL, NULL),
(29, 'library01', 'e10adc3949ba59abbe56e057f20f883e', 1, NULL, NULL, NULL),
(30, 'caoxun03', 'df1af3438da74c1fda32b1f2490b6114', 0, NULL, '<EMAIL>', '13902011060'),
(31, 'caoxun04', 'df1af3438da74c1fda32b1f2490b6114', 0, NULL, '<EMAIL>', '13902011060'),
(32, 'caoxun05', 'df1af3438da74c1fda32b1f2490b6114', 0, NULL, '<EMAIL>', '13902011060');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `book`
--
ALTER TABLE `book`
ADD PRIMARY KEY (`bookId`), ADD UNIQUE KEY `bookISBN` (`bookISBN`), ADD UNIQUE KEY `bookFindNumber` (`bookFindNumber`), ADD KEY `book_type_fk1` (`bookType`);
--
-- Indexes for table `bookstore`
--
ALTER TABLE `bookstore`
ADD PRIMARY KEY (`userId`,`bookId`), ADD KEY `bookStore_book_fk1` (`bookId`);
--
-- Indexes for table `borrow`
--
ALTER TABLE `borrow`
ADD PRIMARY KEY (`userId`,`bookId`), ADD KEY `borrow_user_fk1` (`userId`), ADD KEY `borrow_book_fk1` (`bookId`);
--
-- Indexes for table `returning`
--
ALTER TABLE `returning`
ADD PRIMARY KEY (`returnId`,`userId`,`bookId`), ADD KEY `return_user_fk1` (`userId`), ADD KEY `return_book_fk1` (`bookId`);
--
-- Indexes for table `subscribe`
--
ALTER TABLE `subscribe`
ADD PRIMARY KEY (`userId`,`bookId`), ADD KEY `subscribe_user_fk1` (`userId`), ADD KEY `subscribe_book_fk1` (`bookId`);
--
-- Indexes for table `type`
--
ALTER TABLE `type`
ADD PRIMARY KEY (`typeId`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`userId`), ADD UNIQUE KEY `userName` (`userName`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `book`
--
ALTER TABLE `book`
MODIFY `bookId` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=46;
--
-- AUTO_INCREMENT for table `returning`
--
ALTER TABLE `returning`
MODIFY `returnId` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT for table `type`
--
ALTER TABLE `type`
MODIFY `typeId` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=14;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `userId` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=33;
--
-- 限制导出的表
--
--
-- 限制表 `book`
--
ALTER TABLE `book`
ADD CONSTRAINT `book_type_fk1` FOREIGN KEY (`bookType`) REFERENCES `type` (`typeId`);
--
-- 限制表 `bookstore`
--
ALTER TABLE `bookstore`
ADD CONSTRAINT `bookStore_book_fk1` FOREIGN KEY (`bookId`) REFERENCES `book` (`bookId`),
ADD CONSTRAINT `bookStore_user_fk1` FOREIGN KEY (`userId`) REFERENCES `user` (`userId`);
--
-- 限制表 `borrow`
--
ALTER TABLE `borrow`
ADD CONSTRAINT `borrow_book_fk1` FOREIGN KEY (`bookId`) REFERENCES `book` (`bookId`),
ADD CONSTRAINT `borrow_user_fk1` FOREIGN KEY (`userId`) REFERENCES `user` (`userId`);
--
-- 限制表 `returning`
--
ALTER TABLE `returning`
ADD CONSTRAINT `return_book_fk1` FOREIGN KEY (`bookId`) REFERENCES `book` (`bookId`),
ADD CONSTRAINT `return_user_fk1` FOREIGN KEY (`userId`) REFERENCES `user` (`userId`);
--
-- 限制表 `subscribe`
--
ALTER TABLE `subscribe`
ADD CONSTRAINT `subscribe_book_fk1` FOREIGN KEY (`bookId`) REFERENCES `book` (`bookId`),
ADD CONSTRAINT `subscribe_user_fk1` FOREIGN KEY (`userId`) REFERENCES `user` (`userId`);
/*!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>package com.nku403.serviceimpl;
import java.util.List;
import com.nku403.daoimpl.ReturningDAO;
import com.nku403.entity.Returning;
import com.nku403.entity.User;
import com.nku403.service.ReturningService;
public class ReturningServiceImpl implements ReturningService {
private ReturningDAO returningDAO;
@Override
public void ReturnBook(Returning returning) {
// TODO Auto-generated method stub
returningDAO.save(returning);
}
public ReturningDAO getReturningDAO() {
return returningDAO;
}
public void setReturningDAO(ReturningDAO returningDAO) {
this.returningDAO = returningDAO;
}
@Override
public List FindHistory(User user) {
// TODO Auto-generated method stub
return returningDAO.findByProperty("id.user", user);
}
}
<file_sep>package com.nku403.action;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletContext;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.nku403.entity.Book;
import com.nku403.entity.Bookstore;
import com.nku403.entity.BookstoreId;
import com.nku403.entity.User;
import com.nku403.service.BookService;
import com.nku403.service.BookStoreService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class BookStoreAction extends ActionSupport {
private int bookId;
public void setBookId(int bookId) {
this.bookId = bookId;
}
public int getBookId() {
return bookId;
}
public void addToBookStore() throws IOException{
ServletContext sc = ServletActionContext.getRequest().getSession()
.getServletContext();
ApplicationContext ac = WebApplicationContextUtils
.getWebApplicationContext(sc);
BookStoreService bsservice = (BookStoreService) ac.getBean("BookStoreService");
BookService bservice = (BookService) ac.getBean("BookService");
User user = (User) ActionContext.getContext().getSession().get("user");
Book book = bservice.findBookById(bookId);
System.out.println(user.getUserName());
BookstoreId bookstoreid = new BookstoreId();
bookstoreid.setBook(book);
bookstoreid.setUser(user);
Bookstore bookstore = new Bookstore();
bookstore.setId(bookstoreid);
Bookstore temp = bsservice.findBookInBookStore(bookstoreid);
JSONObject json = new JSONObject();
if(temp != null){
json.accumulate("info", "exist");
System.out.println(json.toString());
ServletActionContext.getResponse().getWriter().print(json.toString());
return;
}
bsservice.addToBookStore(bookstore);
json.accumulate("info", "success");
System.out.println(json.toString());
ServletActionContext.getResponse().getWriter().print(json.toString());
//service.addToBookStore();
}
public void getBookShelf(){
ServletContext sc = ServletActionContext.getRequest().getSession()
.getServletContext();
ApplicationContext ac = WebApplicationContextUtils
.getWebApplicationContext(sc);
BookStoreService bookstoreservice = (BookStoreService) ac.getBean("BookStoreService");
List temp = bookstoreservice.getBookStoreList((User) ServletActionContext.getContext().getSession().get("user"));
ServletActionContext.getRequest().setAttribute("bookstorelist", temp);
}
}
<file_sep>package com.nku403.service;
import java.util.List;
import com.nku403.entity.User;
public interface UserService {
public void add(User user);
public List findUser(User user);
public List findUserByRight(short i);
public User findUserById(int id);
public void delUser(User user);
}
<file_sep>package com.nku403.service;
import java.util.List;
import com.nku403.entity.Returning;
import com.nku403.entity.User;
public interface ReturningService {
public void ReturnBook(Returning returning);
public List FindHistory(User user);
}
<file_sep>package com.nku403.serviceimpl;
import java.util.List;
import com.nku403.daoimpl.BorrowDAO;
import com.nku403.entity.Borrow;
import com.nku403.entity.BorrowId;
import com.nku403.entity.User;
import com.nku403.service.BorrowService;
public class BorrowServiceImpl implements BorrowService {
private BorrowDAO borrowDAO;
@Override
public void addBorrow(Borrow borrow) {
// TODO Auto-generated method stub
borrowDAO.save(borrow);
}
public void setBorrowDAO(BorrowDAO borrowDAO) {
this.borrowDAO = borrowDAO;
}
public BorrowDAO getBorrowDAO() {
return borrowDAO;
}
@Override
public Borrow findBorrowById(BorrowId borrowid) {
// TODO Auto-generated method stub
return borrowDAO.findById(borrowid);
}
@Override
public void delBorrow(Borrow borrow) {
// TODO Auto-generated method stub
borrowDAO.delete(borrow);
}
@Override
public List curBorrow(User user) {
// TODO Auto-generated method stub
return borrowDAO.findByProperty("id.user", user);
}
@Override
public void againBorrow(Borrow borrow) {
// TODO Auto-generated method stub
borrowDAO.attachDirty(borrow);
}
}
<file_sep>7.9-10:06
新增预约表,library.sql文件80行之后复制运行添加,新增dao层完毕
7.13-21:49
书目表所有信息录入完毕<file_sep>-- book表
-- totalamount是总数,accessamount是可借总数 bookHistory是历史借阅量
create table book(
bookId int AUTO_INCREMENT,
bookName varchar(80) not null,
bookAuthor varchar(20) not null,
bookPress varchar(30) not null,
bookPressTime varchar(4) not null,
bookISBN varchar(20) unique not null ,
bookPicture varchar(100) not null,
bookType int not null,
bookInfo text not null,
bookAddTime timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
bookFindNumber varchar(20) unique not null,
bookTotalAmount tinyint(4) not null,
bookAccessAmount tinyint(4) not null,
bookHistory int DEFAULT '0',
primary key(bookId)
)DEFAULT CHARSET=utf8;
-- user
-- 用户权限 0-会员 1-图书管理员 2-系统管理员
create table user(
userId int AUTO_INCREMENT,
userName varchar(16) not null unique,
userPassword char(32) not null,
useright tinyint(4) DEFAULT '0',
userNickname varchar(20),
userEmail varchar(50) not null,
userPhone varchar(11) not null,
primary key(userId)
)DEFAULT CHARSET=utf8;
-- type
create table type(
typeId int AUTO_INCREMENT,
typeName varchar(20) not null,
primary key(typeId)
)DEFAULT CHARSET=utf8;
alter table book
add constraint book_type_fk1 foreign key(bookType) references type(typeId);
create table borrow(
borrowId int AUTO_INCREMENT,
userId int,
bookId int,
borrowDate timestamp,
borrowReturnDate timestamp,
primary key (borrowId,userId,bookId)
)DEFAULT CHARSET=utf8;
alter table borrow
add constraint borrow_user_fk1 foreign key(userId) references user(userId),
add constraint borrow_book_fk1 foreign key(bookId) references book(bookId);
create table returning(
returnId int AUTO_INCREMENT,
userId int,
bookId int,
returnDate timestamp,
primary key(returnId,userId,bookId)
)DEFAULT CHARSET=utf8;
alter table returning
add constraint return_user_fk1 foreign key(userId) references user(userId),
add constraint return_book_fk1 foreign key(bookId) references book(bookId);
create table bookStore(
userId int,
bookId int,
primary key(userId,bookId)
)DEFAULT CHARSET=utf8;
alter table bookStore
add constraint bookStore_user_fk1 foreign key(userId) references user(userId),
add constraint bookStore_book_fk1 foreign key(bookId) references book(bookId);
create table subscribe(
subscribId int AUTO_INCREMENT,
userId int,
bookId int,
stete varchar(20),
primary key (subscribId,userId,bookId)
) DEFAULT CHARSET=utf8;
alter table subscribe
add constraint subscribe_user_fk1 foreign key(userId) references user(userId),
add constraint subscribe_book_fk1 foreign key(bookId) references book(bookId);
<file_sep>package com.nku403.action;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletContext;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.nku403.entity.Book;
import com.nku403.entity.Borrow;
import com.nku403.entity.BorrowId;
import com.nku403.entity.Returning;
import com.nku403.entity.ReturningId;
import com.nku403.entity.User;
import com.nku403.service.BookService;
import com.nku403.service.BorrowService;
import com.nku403.service.ReturningService;
import com.nku403.service.UserService;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class ReturingAction extends ActionSupport {
private int bookId;
private int userId;
public void setBookId(int bookId) {
this.bookId = bookId;
}
public int getBookId() {
return bookId;
}
public void returnBook() throws IOException, ParseException{
ServletContext sc = ServletActionContext.getRequest().getSession()
.getServletContext();
ApplicationContext ac = WebApplicationContextUtils
.getWebApplicationContext(sc);
ReturningService retservice = (ReturningService) ac.getBean("ReturningService");
UserService uservice = (UserService) ac.getBean("UserService");
BookService bookservice = (BookService) ac.getBean("BookService");
BorrowService boservice = (BorrowService) ac.getBean("BorrowService");
JSONObject json = new JSONObject();
User user = uservice.findUserById(userId);
if(user == null){
json.accumulate("retinfo", "nouser");
ServletActionContext.getResponse().getWriter().print(json.toString());
return;
}
Book book = bookservice.findBookById(bookId);
if(book == null){
json.accumulate("retinfo", "nobook");
ServletActionContext.getResponse().getWriter().print(json.toString());
return;
}
BorrowId borrowid = new BorrowId();
borrowid.setBook(book);
borrowid.setUser(user);
Borrow borrow = boservice.findBorrowById(borrowid);
if(borrow == null){
json.accumulate("retinfo", "noborrow");
ServletActionContext.getResponse().getWriter().print(json.toString());
return;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date retdate = sdf.parse(sdf.format(new Date()));
System.out.println(retdate);
Date bordate = sdf.parse(sdf.format(borrow.getBorrowDate()));
boservice.delBorrow(borrow);
book.setBookAccessAmount((short) (book.getBookAccessAmount() + 1));
bookservice.updateHistory(book);
ReturningId retId = new ReturningId();
retId.setBook(book);
retId.setUser(user);
Returning ret = new Returning();
ret.setBorrowDate(bordate);
ret.setReturnDate(retdate);
ret.setId(retId);
retservice.ReturnBook(ret);
json.accumulate("retinfo", "success");
ServletActionContext.getResponse().getWriter().print(json.toString());
}
public void findHistory() throws ParseException{
ServletContext sc = ServletActionContext.getRequest().getSession()
.getServletContext();
ApplicationContext ac = WebApplicationContextUtils
.getWebApplicationContext(sc);
ReturningService retservice = (ReturningService) ac.getBean("ReturningService");
User user = (User) ActionContext.getContext().getSession().get("user");
List temp = retservice.FindHistory(user);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
for(int i = 0;i < temp.size();i++){
Returning ret = (Returning) temp.get(i);
ret.setBorrowDate(sdf.parse(sdf.format(ret.getBorrowDate())));
ret.setReturnDate(sdf.parse(sdf.format(ret.getReturnDate())));
}
ServletActionContext.getRequest().setAttribute("hisList", temp);
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getUserId() {
return userId;
}
}
<file_sep>package com.nku403.action;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.nku403.entity.Book;
import com.nku403.entity.Borrow;
import com.nku403.entity.BorrowId;
import com.nku403.entity.User;
import com.nku403.service.BookService;
import com.nku403.service.BorrowService;
import com.opensymphony.xwork2.ActionSupport;
public class BorrowAction extends ActionSupport {
private int bookId;
public void setBookId(int bookId) {
this.bookId = bookId;
}
public int getBookId() {
return bookId;
}
public void borrowBook() throws ParseException, IOException{
ServletContext sc = ServletActionContext.getRequest().getSession()
.getServletContext();
ApplicationContext ac = WebApplicationContextUtils
.getWebApplicationContext(sc);
BorrowService boservice = (BorrowService) ac.getBean("BorrowService");
BookService bservice = (BookService) ac.getBean("BookService");
Book book = bservice.findBookById(bookId);
User user = (User) ServletActionContext.getContext().getSession().get("user");
BorrowId borrowid = new BorrowId();
borrowid.setBook(book);
borrowid.setUser(user);
Borrow temp = boservice.findBorrowById(borrowid);
JSONObject json = new JSONObject();
if(temp != null)
{
json.accumulate("borinfo", "exist");
System.out.print(json.toString());
ServletActionContext.getResponse().getWriter().print(json.toString());
return;
}
if(book.getBookAccessAmount() == 0)
{
json.accumulate("borinfo", "less");
ServletActionContext.getResponse().getWriter().print(json.toString());
return;
}
List booklist = boservice.curBorrow(user);
System.out.println(booklist.size());
if(booklist.size() > 10){
json.accumulate("borinfo", "more");
ServletActionContext.getResponse().getWriter().print(json.toString());
return;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date bordate = sdf.parse(sdf.format(new Date()));
System.out.println("11"+bordate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(bordate);
calendar.add(Calendar.MONTH, 1);
Date retdate = sdf.parse(sdf.format(calendar.getTime()));
System.out.println("22"+retdate);
Borrow borrow = new Borrow();
borrow.setBorrowDate(bordate);
borrow.setBorrowReturnDate(retdate);
borrow.setId(borrowid);
borrow.setIsAgainBor((short) 0);
borrow.setIsLate((short) 0);
boservice.addBorrow(borrow);
json.accumulate("borinfo", "success");
System.out.println(json.toString());
ServletActionContext.getResponse().getWriter().print(json.toString());
book.setBookHistory(book.getBookHistory() + 1);
book.setBookAccessAmount((short) (book.getBookAccessAmount() - 1));
bservice.updateHistory(book);
}
public void curBorrow() throws ParseException{
ServletContext sc = ServletActionContext.getRequest().getSession()
.getServletContext();
ApplicationContext ac = WebApplicationContextUtils
.getWebApplicationContext(sc);
BorrowService boservice = (BorrowService) ac.getBean("BorrowService");
List temp = boservice.curBorrow((User) ServletActionContext.getContext().getSession().get("user"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
for(int i = 0; i < temp.size();i++){
Borrow borrow = (Borrow) temp.get(i);
borrow.setBorrowDate(sdf.parse(sdf.format(borrow.getBorrowDate())));
borrow.setBorrowReturnDate(sdf.parse(sdf.format(borrow.getBorrowReturnDate())));
System.out.println(borrow.getBorrowReturnDate());
}
ServletActionContext.getRequest().setAttribute("curBor", temp);
}
public void againBorrow() throws IOException, ParseException{
ServletContext sc = ServletActionContext.getRequest().getSession()
.getServletContext();
ApplicationContext ac = WebApplicationContextUtils
.getWebApplicationContext(sc);
BorrowService boservice = (BorrowService) ac.getBean("BorrowService");
BookService bservice = (BookService) ac.getBean("BookService");
Book book = bservice.findBookById(bookId);
User user = (User) ServletActionContext.getContext().getSession().get("user");
JSONObject json = new JSONObject();
BorrowId borrowid = new BorrowId();
borrowid.setBook(book);
borrowid.setUser(user);
Borrow borrow = boservice.findBorrowById(borrowid);
if(borrow.getIsAgainBor() == 1){
json.accumulate("againinfo", "again");
ServletActionContext.getResponse().getWriter().print(json.toString());
return;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(borrow.getBorrowReturnDate());
calendar.add(Calendar.MONTH, 1);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
borrow.setIsAgainBor((short) 1);
borrow.setBorrowReturnDate(sdf.parse(sdf.format(calendar.getTime())));
boservice.againBorrow(borrow);
json.accumulate("againinfo", "success");
json.accumulate("retdate",sdf.format(calendar.getTime()));
ServletActionContext.getResponse().getWriter().print(json.toString());
}
}
<file_sep>package com.nku403.serviceimpl;
import java.util.List;
import com.nku403.daoimpl.UserDAO;
import com.nku403.entity.User;
import com.nku403.service.UserService;
public class UserServiceImpl implements UserService {
private UserDAO userDAO;
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDao) {
this.userDAO = userDao;
}
@Override
public void add(User user) {
// TODO Auto-generated method stub
userDAO.save(user);
}
@Override
public List findUser(User user) {
// TODO Auto-generated method stub
return userDAO.findByExample(user);
}
@Override
public List findUserByRight(short right) {
// TODO Auto-generated method stub
return userDAO.findByUseright(right);
}
@Override
public User findUserById(int id) {
return userDAO.findById(id);
// TODO Auto-generated method stub
}
@Override
public void delUser(User user) {
// TODO Auto-generated method stub
userDAO.delete(user);
}
}
<file_sep>package com.nku403.daoimpl;
import java.util.Date;
import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.nku403.entity.Returning;
import com.nku403.entity.ReturningId;
/**
* A data access object (DAO) providing persistence and search support for
* Returning entities. Transaction control of the save(), update() and delete()
* operations can directly support Spring container-managed transactions or they
* can be augmented to handle user-managed Spring transactions. Each of these
* methods provides additional information for how to configure it for the
* desired type of transaction control.
*
* @see com.nku403.entity.Returning
* @author MyEclipse Persistence Tools
*/
public class ReturningDAO extends HibernateDaoSupport {
private static final Logger log = LoggerFactory
.getLogger(ReturningDAO.class);
// property constants
protected void initDao() {
// do nothing
}
public void save(Returning transientInstance) {
log.debug("saving Returning instance");
Transaction tran=getSession().beginTransaction();
try {
getHibernateTemplate().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
tran.commit();
getSession().flush();
getSession().close();
}
public void delete(Returning persistentInstance) {
log.debug("deleting Returning instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Returning findById(com.nku403.entity.ReturningId id) {
log.debug("getting Returning instance with id: " + id);
try {
Returning instance = (Returning) getHibernateTemplate().get(
"com.nku403.entity.Returning", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(Returning instance) {
log.debug("finding Returning instance by example");
try {
List results = getHibernateTemplate().findByExample(instance);
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public List findByProperty(String propertyName, Object value) {
log.debug("finding Returning instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Returning as model where model."
+ propertyName + "= ?";
return getHibernateTemplate().find(queryString, value);
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List findAll() {
log.debug("finding all Returning instances");
try {
String queryString = "from Returning";
return getHibernateTemplate().find(queryString);
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public Returning merge(Returning detachedInstance) {
log.debug("merging Returning instance");
try {
Returning result = (Returning) getHibernateTemplate().merge(
detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(Returning instance) {
log.debug("attaching dirty Returning instance");
try {
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(Returning instance) {
log.debug("attaching clean Returning instance");
try {
getHibernateTemplate().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public static ReturningDAO getFromApplicationContext(ApplicationContext ctx) {
return (ReturningDAO) ctx.getBean("ReturningDAO");
}
}<file_sep>package com.nku403.service;
import java.util.List;
import com.nku403.entity.Bookstore;
import com.nku403.entity.BookstoreId;
import com.nku403.entity.User;
public interface BookStoreService {
public void addToBookStore(Bookstore bookstore);
public Bookstore findBookInBookStore(BookstoreId bookstoreid);
public List getBookStoreList(User user);
}
<file_sep>package com.nku403.daoimpl;
import java.util.List;
import org.hibernate.LockMode;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.nku403.entity.Subscribe;
import com.nku403.entity.SubscribeId;
/**
* A data access object (DAO) providing persistence and search support for
* Subscribe entities. Transaction control of the save(), update() and delete()
* operations can directly support Spring container-managed transactions or they
* can be augmented to handle user-managed Spring transactions. Each of these
* methods provides additional information for how to configure it for the
* desired type of transaction control.
*
* @see com.nku403.entity.Subscribe
* @author MyEclipse Persistence Tools
*/
public class SubscribeDAO extends HibernateDaoSupport {
private static final Logger log = LoggerFactory
.getLogger(SubscribeDAO.class);
// property constants
public static final String STETE = "stete";
protected void initDao() {
// do nothing
}
public void save(Subscribe transientInstance) {
log.debug("saving Subscribe instance");
Transaction tran=getSession().beginTransaction();
try {
getHibernateTemplate().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
tran.commit();
getSession().flush();
getSession().close();
}
public void delete(Subscribe persistentInstance) {
log.debug("deleting Subscribe instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public Subscribe findById(com.nku403.entity.SubscribeId id) {
log.debug("getting Subscribe instance with id: " + id);
try {
Subscribe instance = (Subscribe) getHibernateTemplate().get(
"com.nku403.entity.Subscribe", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List findByExample(Subscribe instance) {
log.debug("finding Subscribe instance by example");
try {
List results = getHibernateTemplate().findByExample(instance);
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public List findByProperty(String propertyName, Object value) {
log.debug("finding Subscribe instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Subscribe as model where model."
+ propertyName + "= ?";
return getHibernateTemplate().find(queryString, value);
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List findByStete(Object stete) {
return findByProperty(STETE, stete);
}
public List findAll() {
log.debug("finding all Subscribe instances");
try {
String queryString = "from Subscribe";
return getHibernateTemplate().find(queryString);
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public Subscribe merge(Subscribe detachedInstance) {
log.debug("merging Subscribe instance");
try {
Subscribe result = (Subscribe) getHibernateTemplate().merge(
detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(Subscribe instance) {
log.debug("attaching dirty Subscribe instance");
try {
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(Subscribe instance) {
log.debug("attaching clean Subscribe instance");
try {
getHibernateTemplate().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public static SubscribeDAO getFromApplicationContext(ApplicationContext ctx) {
return (SubscribeDAO) ctx.getBean("SubscribeDAO");
}
}<file_sep>package com.nku403.serviceimpl;
import java.util.List;
import com.nku403.daoimpl.TypeDAO;
import com.nku403.entity.Type;
import com.nku403.service.TypeService;
public class TypeServiceImpl implements TypeService {
private TypeDAO typeDAO;
public TypeDAO getTypeDAO() {
return typeDAO;
}
public void setTypeDAO(TypeDAO typeDAO) {
this.typeDAO = typeDAO;
}
@Override
public String addType(Type type) {
// TODO Auto-generated method stub
typeDAO.save(type);
return "success";
}
@Override
public List getAllType() {
// TODO Auto-generated method stub
return typeDAO.findAll();
}
@Override
public Type findTypeById(int id) {
// TODO Auto-generated method stub
return typeDAO.findById(id);
}
}
<file_sep>package com.nku403.entity;
import java.util.Date;
/**
* Borrow entity. @author MyEclipse Persistence Tools
*/
public class Borrow implements java.io.Serializable {
// Fields
private BorrowId id;
private Date borrowDate;
private Date borrowReturnDate;
private Short isLate;
private Short isAgainBor;
// Constructors
/** default constructor */
public Borrow() {
}
/** minimal constructor */
public Borrow(BorrowId id) {
this.id = id;
}
/** full constructor */
public Borrow(BorrowId id, Date borrowDate, Date borrowReturnDate,
Short isLate, Short isAgainBor) {
this.id = id;
this.borrowDate = borrowDate;
this.borrowReturnDate = borrowReturnDate;
this.isLate = isLate;
this.isAgainBor = isAgainBor;
}
// Property accessors
public BorrowId getId() {
return this.id;
}
public void setId(BorrowId id) {
this.id = id;
}
public Date getBorrowDate() {
return this.borrowDate;
}
public void setBorrowDate(Date borrowDate) {
this.borrowDate = borrowDate;
}
public Date getBorrowReturnDate() {
return this.borrowReturnDate;
}
public void setBorrowReturnDate(Date borrowReturnDate) {
this.borrowReturnDate = borrowReturnDate;
}
public Short getIsLate() {
return this.isLate;
}
public void setIsLate(Short isLate) {
this.isLate = isLate;
}
public Short getIsAgainBor() {
return this.isAgainBor;
}
public void setIsAgainBor(Short isAgainBor) {
this.isAgainBor = isAgainBor;
}
} | ae76414f0d2b73a4c11fd22d5caf71b4e79d2d8a | [
"Java",
"SQL",
"Text"
] | 16 | SQL | NickXun/Library | 8ca7b8fcb33b5ecb5071916d85619d4cd8856f3d | 42434e112426d6b1d8ac610364afc991ea76291d |
refs/heads/master | <file_sep>import imaplib
import configparser
import os
import email
import datetime
import codecs
now = datetime.datetime.now()
def open_connection(verbose=False):
config = configparser.ConfigParser()
config.read([os.path.expanduser('cred.cfg')])
hostname = config.get('server', 'hostname')
username = config.get('server', 'username')
password = config.get('server', '<PASSWORD>')
if verbose: print('Connecting to ', hostname)
connection = imaplib.IMAP4_SSL(hostname)
if verbose: print('Logging in as ', username)
connection.login(username, password)
return connection
if __name__=='__main__':
f = codecs.open(now.strftime("%Y%m%d") + '.csv', 'a', 'utf-8')
c = open_connection(verbose=True)
try:
c.list()
c.select(mailbox='INBOX',readonly=True)
#result, emdata = c.uid('search', None, "ALL")
result, emdata = c.sort('DATE', 'UTF-8', 'ALL')
for x in emdata[0].split():
# print('Processing: ',x)
ret, data = c.fetch(x,'(RFC822)')
if ret != 'OK':
print('Error with message: ',x)
msg = email.message_from_bytes(data[0][1])
# print(str(msg))
try:
fromhdr = email.header.make_header(email.header.decode_header(msg['From']))
fromstr = str(fromhdr).replace('\n', ' ').replace('\r', ' ').replace('|','\|').replace('"','\\"')
subjhdr = email.header.make_header(email.header.decode_header(msg['Subject']))
subjstr = str(subjhdr).replace('\n', ' ').replace('\r', ' ').replace('|','\|').replace('"','\\"')
date_tuple = email.utils.parsedate_tz(msg['Date'])
if date_tuple:
local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
# print ("Local Date:", local_date.strftime("%a, %d %b %Y %H:%M:%S"))
# print('%s|%s|%s' % (local_date.strftime("%Y-%m-%d %H:%M:%S"),fromstr, subjstr))
f.write('%s|%s|%s|%s\n' % (x,local_date.strftime("%Y-%m-%d %H:%M:%S"),fromstr, subjstr))
except:
print("Ignoring: ",str(msg))
finally:
c.logout()
f.close()
| 0c31a39f988030db1e93372b1806d090a88df6bd | [
"Python"
] | 1 | Python | aravindc/python2 | a4a50247ef0a33ae6db8ee1b395c316bf53e0ef2 | 1ee5a70ea82f249763de2626216deed572e189a2 |
refs/heads/master | <repo_name>nisrulz/SelfieApp<file_sep>/app/src/main/java/jslovers/github/nisrulz/selfie/SelfieListAdapter.java
package jslovers.github.nisrulz.selfie;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Collections;
import java.util.List;
public class SelfieListAdapter extends RecyclerView.Adapter<SelfieListAdapter.ItemViewHolder> {
List<Selfie> selfieList;
Context context;
public SelfieListAdapter(Context context, List<Selfie> selfieList) {
this.selfieList = selfieList;
this.context = context;
}
@Override public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.rvlist_item, parent, false);
return new ItemViewHolder(view);
}
@Override public void onBindViewHolder(ItemViewHolder holder, int position) {
// Set the name of selfie in the holder
holder.txtvw_name.setText(selfieList.get(position).getName());
// Set the image in the holder using the helper
Bitmap takenImage = BitmapFactory.decodeFile(selfieList.get(position).getPath());
holder.imgvw_selfie.setImageBitmap(takenImage);
}
@Override public int getItemCount() {
return selfieList.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
TextView txtvw_name;
ImageView imgvw_selfie;
public ItemViewHolder(View itemView) {
super(itemView);
// Setup the view id in the item view holder
txtvw_name = (TextView) itemView.findViewById(R.id.txtvw_name);
imgvw_selfie = (ImageView) itemView.findViewById(R.id.imgvw_selfie);
}
}
// Helper functions for managing items of the list
private void remove(int position) {
selfieList.remove(position);
notifyItemRemoved(position);
}
private void swap(int firstPosition, int secondPosition) {
Collections.swap(selfieList, firstPosition, secondPosition);
notifyItemMoved(firstPosition, secondPosition);
}
}
<file_sep>/app/src/main/java/jslovers/github/nisrulz/selfie/MainActivity.java
package jslovers.github.nisrulz.selfie;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import github.nisrulz.recyclerviewhelper.RVHItemClickListener;
import github.nisrulz.recyclerviewhelper.RVHItemDividerDecoration;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_IMAGE_CAPTURE = 100;
RecyclerView myrecyclerview;
ArrayList<Selfie> selfieList;
SelfieListAdapter adapter;
LinearLayout ll_emptystate;
String currentPhotoPath;
String currentPhotoName;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Get the reference of empty state view
ll_emptystate = (LinearLayout) findViewById(R.id.emptystate);
myrecyclerview = (RecyclerView) findViewById(R.id.rv_selfielist);
selfieList = new ArrayList<>();
adapter = new SelfieListAdapter(this, selfieList);
myrecyclerview.hasFixedSize();
myrecyclerview.setLayoutManager(new LinearLayoutManager(this));
myrecyclerview.setAdapter(adapter);
// Set the divider
myrecyclerview.addItemDecoration(
new RVHItemDividerDecoration(this, LinearLayoutManager.VERTICAL));
// Set On Click
myrecyclerview.addOnItemTouchListener(
new RVHItemClickListener(this, new RVHItemClickListener.OnItemClickListener() {
@Override public void onItemClick(View view, int position) {
Intent i = new Intent(MainActivity.this, DetailActivity.class);
i.putExtra("path", selfieList.get(position).getPath());
i.putExtra("name", selfieList.get(position).getName());
startActivity(i);
}
}));
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
takePictureUsingIntent();
}
});
showEmptyStateIfListEmpty();
}
private void takePictureUsingIntent() {
currentPhotoName = getFileName();
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
getPhotoFileUri(currentPhotoName)); // set the image file name
// If you call startActivityForResult() using an intent that no app can handle, your app will crash.
// So as long as the result is not null, it's safe to use the intent.
if (intent.resolveActivity(getPackageManager()) != null) {
// Start the image capture intent to take photo
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
}
}
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Selfie selfie = new Selfie(currentPhotoName, currentPhotoPath);
selfieList.add(selfie);
showEmptyStateIfListEmpty();
adapter.notifyDataSetChanged();
}
}
private String getFileName() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "SelFie_" + timeStamp + "_";
return imageFileName;
}
// Returns the Uri for a photo stored on disk given the fileName
public Uri getPhotoFileUri(String fileName) {
// Only continue if the SD Card is mounted
if (isExternalStorageAvailable()) {
// Get safe storage directory for photos
// Use `getExternalFilesDir` on Context to access package-specific directories.
// This way, we don't need to request external read/write runtime permissions.
File mediaStorageDir =
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"SelFie");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()) {
System.out.println("failed to create directory");
}
// Return the file target for the photo based on filename
File newFile = new File(mediaStorageDir.getPath() + File.separator + fileName);
currentPhotoPath = newFile.getPath();
return Uri.fromFile(newFile);
}
return null;
}
// Returns true if external storage for photos is available
private boolean isExternalStorageAvailable() {
String state = Environment.getExternalStorageState();
return state.equals(Environment.MEDIA_MOUNTED);
}
// Setup empty state function
private void showEmptyStateIfListEmpty() {
if (ll_emptystate != null) {
if (selfieList != null && selfieList.size() != 0) {
ll_emptystate.setVisibility(View.GONE);
} else {
ll_emptystate.setVisibility(View.VISIBLE);
}
}
}
// Options Menu
@Override public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_deleteall) {
if (selfieList != null && adapter != null) {
selfieList.clear();
showEmptyStateIfListEmpty();
adapter.notifyDataSetChanged();
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
<file_sep>/Readme.md
# **SelFie App**
A simple app to demonstrate building applications in android. The app lets you take selfies and show it as list inside the app.
[](https://twitter.com/nisrulz)
# Screenshots
 
# Pull Requests
+ I welcome and encourage all pull requests.
+ It usually will take me within 24-48 hours to respond to any issue or request.
### Created & Maintained By
[<NAME>](https://github.com/nisrulz) ([@nisrulz](https://www.twitter.com/nisrulz))
### Credits
Graphics used in the app are taken from [freepik.com](http://www.freepik.com)
License
=======
Copyright 2016 <NAME>
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.
<file_sep>/app/src/main/java/jslovers/github/nisrulz/selfie/SplashActivity.java
package jslovers.github.nisrulz.selfie;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
public class SplashActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make it fullscreen
// IMPORTANT : Call this before the call to setContentView
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
// Use a handler to execute code with a delay
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override public void run() {
// Start the MainActivity using intent
startActivity(new Intent(SplashActivity.this, MainActivity.class));
overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
finish();
}
}, 1500);
}
}
| 719be868a241d63c46f0b6ae2ca442a518748ba5 | [
"Markdown",
"Java"
] | 4 | Java | nisrulz/SelfieApp | 99902b2bca4907213370f9b0bc43735187d87714 | 0100b4c6806ab34aa4e84d7ad3d067d9eba3f1a5 |
refs/heads/master | <file_sep>/*
* Copyright (c) 2020. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
* Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
* Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
* Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
* Vestibulum commodo. Ut rhoncus gravida arcu.
*/
package gr.techzombie;
import java.util.ArrayList;
import java.util.Scanner;
public class MobilePhone {
private final Scanner input = new Scanner(System.in);
public MobilePhone() {
}
//Contacts contacts;
ArrayList<Contacts> epafes = new ArrayList<>();
public void printInfo (){
System.out.print("\n1. show info\n2. add contact\n3. show all contacts\n4. exit\n");
}
public void addContact(){
System.out.println("dwse name:");
String name = input.nextLine();
System.out.println("dwse number");
int number = input.nextInt();
input.nextLine();
epafes.add(new Contacts(name,number));
printInfo();
}
public void showContacts(){
for (Contacts epafe : epafes)
System.out.println(epafe.getName() + " " + epafe.getNumber());
printInfo();
}
}
| 44751e7741d3e7ff179a8a78e25070a9877c9c15 | [
"Java"
] | 1 | Java | kosmas1991/MobilePhoneContacts | ce56190b024209ee29e06b684763c20925396a2e | 2121c94c0e7a47b3b45613c975fad79c8be1766e |
refs/heads/master | <file_sep>healthit.baseurl=https://dashboard.healthit.gov/api/open-api.php
<file_sep>package com.example.healthitdata.service;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.healthitdata.domain.BasicEhrNotesUsage;
import com.example.healthitdata.exception.DataServiceException;
import com.example.healthitdata.service.data.IHealthITDataService;
@Service
public class HealthITService implements IHealthITService {
@Autowired
IHealthITDataService healthITDataService;
@Override
public List<BasicEhrNotesUsage> getBasicEhrNotesUsageDescOrder(Integer year) throws DataServiceException {
List<BasicEhrNotesUsage> basicEhrNotesUsageList = healthITDataService.getBasicEhrNotesUsageList(year);
return basicEhrNotesUsageList.stream()
.sorted(Comparator.comparingDouble(BasicEhrNotesUsage::getPercentage).reversed())
.collect(Collectors.toList());
}
}
| 195835f0649813f631805508e0c25b531ecb5d3d | [
"Java",
"INI"
] | 2 | INI | gchirayil/healthitdata | bb9688fcd3727a7b0c340d4da17d65332b5f99fd | b2792d71cde43bda0aae2eb57ce4fba1ec44f8a2 |
refs/heads/master | <file_sep>import numpy as np
from sigmoid import sigmoid
from sigmoidGradient import sigmoidGradient
def nnCostFunction(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, Lambda):
"""computes the cost and gradient of the neural network. The
parameters for the neural network are "unrolled" into the vector
nn_params and need to be converted back into the weight matrices.
The returned parameter grad should be a "unrolled" vector of the
partial derivatives of the neural network.
"""
# Reshape nn_params back into the parameters theta1 and theta2, the weight matrices
# for our 2 layer neural network
# Obtain theta1 and theta2 back from nn_params
theta1 = nn_params[0:(hidden_layer_size*(input_layer_size+1))].reshape((input_layer_size+1),hidden_layer_size).T
theta2 = nn_params[(hidden_layer_size*(input_layer_size+1)):].reshape((hidden_layer_size+1),num_labels).T
# Setup some useful variables
m, _ = X.shape
X = np.column_stack((np.ones((m, 1)), X))
# You need to return the following variables correctly
J = 0
theta1_grad = np.zeros(theta1.shape);
theta2_grad = np.zeros(theta2.shape);
# ====================== YOUR CODE HERE ======================
# Instructions: You should complete the code by working through the
# following parts.
#
# Part 1: Feedforward the neural network and return the cost in the
# variable J. After implementing Part 1, you can verify that your
# cost function computation is correct by verifying the cost
# computed in ex4.py
#
# Part 2: Implement the backpropagation algorithm to compute the gradients
# theta1_grad and theta2_grad. You should return the partial derivatives of
# the cost function with respect to theta1 and theta2 in theta1_grad and
# theta2_grad, respectively. After implementing Part 2, you can check
# that your implementation is correct by running checkNNGradients
#
# Note: The vector y passed into the function is a vector of labels
# containing values from 1...K. You need to map this vector into a
# binary vector of 1's and 0's to be used with the neural network
# cost function.
#
# Hint: We recommend implementing backpropagation using a for-loop
# over the training examples if you are implementing it for the
# first time.
#
# Part 3: Implement regularization with the cost function and gradients.
#
# Hint: You can implement this around the code for
# backpropagation. That is, you can compute the gradients for
# the regularization separately and then add them to theta1_grad
# and theta2_grad from Part 2.
#
# =========================================================================
yk = np.zeros((m,num_labels))
for i in range(0,m):
yk[i,y[i]-1]=1
#Partie 1
# Z2 = <EMAIL>
# A2 = sigmoid(Z2)
# A2 = np.column_stack((np.ones((m, 1)), A2))
# Z3 = <EMAIL>
# h_theta = sigmoid(Z3)
#
# Jint = (np.log(h_theta)*(-yk))-(np.log(1-h_theta)*(1-yk))
#
# J = np.sum(Jint)/(m)
#Partie 2, regularisation en 3.4
Z2 = <EMAIL>
A2 = sigmoid(Z2)
A2 = np.column_stack((np.ones((m, 1)), A2))
Z3 = <EMAIL>
h_theta = sigmoid(Z3)
Jint = (np.log(h_theta)*(-yk))-(np.log(1-h_theta)*(1-yk))
Part1 = np.sum(theta1[:,1:]**2)
Part2 = np.sum(theta2[:,1:]**2)
Reg = (Lambda/(2*m))*(Part1 + Part2)
J = (np.sum(Jint)/(m))+Reg
#Partie 3, backpropagation
delta_3 = np.zeros((m,num_labels))
delta_3 = h_theta - yk
#print(delta_3.shape)
#print(theta2.shape)
#print(sigmoidGradient(Z2).shape)
delta_2 = (theta2[:,1:].T@delta_3.T).T*sigmoidGradient(Z2)
#delta_2 = delta_int[:,1:num_labels]
#print(delta_int.shape)
#print(delta_2.shape)
delta = np.zeros((m,num_labels))
DELTA_1 = delta_2.T@X
DELTA_2 = delta_3.T@A2
theta1_grad = DELTA_1/m
theta1_grad[:,1:] = theta1_grad[:,1:] + (Lambda*theta1[:,1:])/m
theta2_grad = DELTA_2/m
theta2_grad[:,1:] = theta2_grad[:,1:] + (Lambda*theta2[:,1:])/m
# =========================================================================
# Unroll gradient
grad = np.hstack((theta1_grad.T.ravel(), theta2_grad.T.ravel()))
return J, grad<file_sep>import sys
import numpy as np
from scipy import optimize
from matplotlib import pyplot
sys.path.append('..')
def trainLinearReg(linearRegCostFunction, X, y, lambda_=0.0, maxiter=200):
# Initialize Theta
initial_theta = np.zeros(X.shape[1])
# Create "short hand" for the cost function to be minimized
costFunction = lambda t: linearRegCostFunction(X, y, t, lambda_)
# Now, costFunction is a function that takes in only one argument
options = {'maxiter': maxiter}
# Minimize using scipy
res = optimize.minimize(costFunction, initial_theta, jac=True, method='TNC', options=options)
return res.x
def featureNormalize(X):
mu = np.mean(X, axis=0)
X_norm = X - mu
sigma = np.std(X_norm, axis=0, ddof=1)
X_norm /= sigma
return X_norm, mu, sigma
def plotFit(polyFeatures, min_x, max_x, mu, sigma, theta, p):
# We plot a range slightly bigger than the min and max values to get
# an idea of how the fit will vary outside the range of the data points
x = np.arange(min_x - 15, max_x + 25, 0.05).reshape(-1, 1)
# Map the X values
X_poly = polyFeatures(x, p)
X_poly -= mu
X_poly /= sigma
# Add ones
X_poly = np.concatenate([np.ones((x.shape[0], 1)), X_poly], axis=1)
# Plot
pyplot.plot(x, np.dot(X_poly, theta), '--', lw=2)
<file_sep>import numpy as np
from sigmoid import sigmoid
def lrCostGradient(theta, X, y, Lambda):
"""computes the gradient of the cost w.r.t. to the parameters
theta for regularized logistic regression .
"""
# ====================== YOUR CODE HERE ======================
# Instructions: Compute the cost of a particular choice of theta.
# You should set J to the cost.
#
# Hint: The computation of the cost function and gradients can be
# efficiently vectorized. For example, consider the computation
#
# sigmoid(X @ theta) or np.dot(X, theta)
#
# Each row of the resulting matrix will contain the value of the
# prediction for that example. You can make use of this to vectorize
# the cost function and gradient computations.
#
m = X.shape[0]
n = X.shape[1]
theta = theta.reshape((n,1))
#Unregularized version
# grad = 0.
# grad = (np.transpose(X))@(sigmoid(X@theta)-y)/m
#Regularized version
grad = np.zeros((n,1))
h_theta = sigmoid(X@theta)
error = h_theta - y
grad= X.T@error/m
grad[1:,0] = grad[1:,0] + (Lambda*theta[1:,0])/m
# =============================================================
return grad.flatten() # ATTENTION: à conserver pour utiliser scipy.optimization.fmin_cg
<file_sep>
# coding: utf-8
# # Dog Breed Classifier
#
# This notebook leverages a pretrained InceptionV3 model (on ImageNet) to prepare a _Dog Breed Classifier_
# It showcases how __Transfer Learning__ can be utilized to prepare high performing models
# Pandas and Numpy for data structures and util fucntions
import re
#import tqdm
import itertools
import numpy as np
import pandas as pd
from IPython import get_ipython
from numpy.random import rand
from datetime import datetime
pd.options.display.max_colwidth = 600
import warnings
warnings.filterwarnings('ignore')
# Scikit Imports
from sklearn import preprocessing
from sklearn.metrics import roc_curve, auc, precision_recall_curve
from sklearn.model_selection import train_test_split
# Matplot Imports
import matplotlib.pyplot as plt
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
# plt.rcParams.update(params)
# get_ipython().run_line_magic('matplotlib', 'inline')
#
# # pandas display data frames as tables
# from IPython.display import display, HTML
import warnings
warnings.filterwarnings('ignore')
from keras import regularizers
from keras.models import Model
from keras.optimizers import Adam
from keras.layers import Dropout
from keras.layers import Conv2D,MaxPooling2D, GlobalAveragePooling2D
from keras.layers import BatchNormalization
from keras.layers import Activation,Dense,Flatten
from keras.models import Sequential,load_model
from keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img
from keras.applications import vgg16 as vgg
from keras.applications import inception_v3 as inception
from keras.applications import mobilenet_v2 as mobilenet
from keras.applications import densenet
from keras.utils.np_utils import to_categorical
# ---------------------------------------------------------------------------------------------------------------
# LOAD DATA
# ---------------------------------------------------------------------------------------------------------------
from pythonTools import importData, plot_batch, load_batch
print('Load data...')
feature_values, label_names, dataset_df = importData('rawKeras')
from keras.preprocessing.image import img_to_array, load_img
target_size = 192;
feature_values = np.array([img_to_array(
load_img(img, # color_mode = "grayscale",
target_size=(target_size, target_size))
) for img
in dataset_df['image_path'].values.tolist()
]).astype('float32')
feature_nb = feature_values.shape[1]
instance_nb = feature_values.shape[0]
# ---------------------------------------------------------------------------------------------------------------
# transformation des labels selon différents codages
# Noms des labels
labelNames_unique = label_names.unique()
print(labelNames_unique)
# nb de classes
label_nb = labelNames_unique.shape[0]
print(label_nb)
# indices
le = preprocessing.LabelEncoder()
le.fit(labelNames_unique)
labelIndices_unique = le.transform(labelNames_unique)
labelIndices = le.transform(label_names)
# one-hot-encoding
# labelOhe = pd.get_dummies(label_names.reset_index(drop=True)).values
labels_ohe_names = pd.get_dummies(label_names.reset_index(drop=True), sparse=True)
labels_ohe = np.asarray(labels_ohe_names)
print(labels_ohe.shape)
print(labels_ohe[:2])
# ---------------------------------------------------------------------------------------------------------------
# Seafloor dataset exploratory analysis
print('------------------------------')
print('Seafloor Dataset Summary ')
print('Instance Nb:', instance_nb)
print('Feature Nb:', feature_nb)
print('Label Nb:', label_nb)
# Visualize a Sample Set
batch_df = load_batch(dataset_df,batch_size=25)
plot_batch(batch_df, grid_width=5, grid_height=5, im_scale_x=128, im_scale_y=128)
############################################################################################################
# ## Prepare Train-Test Datasets
# We use a 70-30 split to prepare the two dataset
x_train, x_test, y_train, y_test = train_test_split(feature_values,
label_names,
test_size=0.333,
stratify=np.array(label_names),
random_state=42)
print(x_train.shape, x_test.shape)
# Prepare Validation Dataset
x_train, x_val, y_train, y_val = train_test_split(x_train,
y_train,
test_size=0.15,
stratify=np.array(y_train),
random_state=42)
# Prepare target variables for train, test and validation datasets
# In[14]:
y_train_ohe = pd.get_dummies(y_train.reset_index(drop=True)).as_matrix()
y_val_ohe = pd.get_dummies(y_val.reset_index(drop=True)).as_matrix()
y_test_ohe = pd.get_dummies(y_test.reset_index(drop=True)).as_matrix()
# ## Data Augmentation
#
# Since number of samples per class are not very high, we utilize data augmentation to prepare different variations of different samples available. We do this using the ```ImageDataGenerator utility``` from ```keras```
BATCH_SIZE = 32
# Create train generator.
train_datagen = ImageDataGenerator(rescale=1./255,
rotation_range=30,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip = 'true')
train_generator = train_datagen.flow(x_train, y_train_ohe, shuffle=False, batch_size=BATCH_SIZE, seed=1)
# Create validation generator
val_datagen = ImageDataGenerator(rescale = 1./255)
val_generator = train_datagen.flow(x_val, y_val_ohe, shuffle=False, batch_size=BATCH_SIZE, seed=1)
# ## Prepare Deep Learning Classifier
#
# * Load InceptionV3 pretrained on ImageNet without its top/classification layer
# * Add additional custom layers on top of InceptionV3 to prepare custom classifier
# ---------------------------------------------------------------------------------------------------------------
# DEFINITION DU MODELE INCEPTIONV3
# ---------------------------------------------------------------------------------------------------------------
# Get the InceptionV3 model so we can do transfer learning
base_inception = inception.InceptionV3(weights='imagenet', include_top = False, input_shape=(192, 192, 3))
# Add a global spatial average pooling layer
out = base_inception.output
out = GlobalAveragePooling2D()(out)
out = Dense(512, activation='relu')(out)
out = Dense(512, activation='relu')(out)
total_classes = y_train_ohe.shape[1]
predictions = Dense(total_classes, activation='softmax')(out)
# * Stack the two models (InceptionV3 and custom layers) on top of each other
# * Compile the model and view its summary
model = Model(inputs=base_inception.input, outputs=predictions)
# only if we want to freeze layers
for layer in base_inception.layers:
layer.trainable = False
# Compile
model.compile(Adam(lr=.0001), loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
# ---------------------------------------------------------------------------------------------------------------
# DEFINITION DU MODELE VGG16
# ---------------------------------------------------------------------------------------------------------------
NUM_CLASSES = 6
LEARNING_RATE = 1e-4
from keras.optimizers import Adam
base_model = vgg.VGG16(weights='imagenet',
include_top=False,
input_shape=(192, 192, 3))
last = base_model.get_layer('block3_pool').output
x = GlobalAveragePooling2D()(last)
x = BatchNormalization()(x)
x = Dense(256, activation='relu')(x)
x = Dense(256, activation='relu')(x)
x = Dropout(0.6)(x)
pred = Dense(NUM_CLASSES, activation='softmax')(x)
model = Model(base_model.input, pred)
for layer in base_model.layers:
layer.trainable = False
model.compile(loss='binary_crossentropy',
optimizer=Adam(lr=LEARNING_RATE),
metrics=['accuracy'])
model.summary()
# ---------------------------------------------------------------------------------------------------------------
# DEFINITION DU MODELE MobileNetV2
# ---------------------------------------------------------------------------------------------------------------
# base_model = mobilenet.MobileNetV2(weights='imagenet', include_top = False, input_shape=(192, 192, 3))
# ---------------------------------------------------------------------------------------------------------------
# DEFINITION DU MODELE DENSENET
# ---------------------------------------------------------------------------------------------------------------
# base_model = densenet.DenseNet201(weights='imagenet', include_top = False, input_shape=(192, 192, 3))
# ---------------------------------------------------------------------------------------------------------------
# Model Training
# ---------------------------------------------------------------------------------------------------------------
EPOCHS = 15
batch_size = BATCH_SIZE
train_steps_per_epoch = x_train.shape[0] // batch_size
val_steps_per_epoch = x_val.shape[0] // batch_size
history = model.fit_generator(train_generator,
steps_per_epoch=train_steps_per_epoch,
validation_data=val_generator,
validation_steps=val_steps_per_epoch,
epochs=EPOCHS,
verbose=1)
model.save('SEABED_CLASSIFICATION.hdf5')
# ---------------------------------------------------------------------------------------------------------------
# Visualize Model Performance
# ---------------------------------------------------------------------------------------------------------------
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))
t = f.suptitle('Deep Neural Net Performance', fontsize=12)
f.subplots_adjust(top=0.85, wspace=0.3)
epochs = list(range(1,EPOCHS+1))
print(history.history)
ax1.plot(epochs, history.history['accuracy'], label='Train Accuracy')
ax1.plot(epochs, history.history['val_accuracy'], label='Validation Accuracy')
ax1.set_xticks(epochs)
ax1.set_ylabel('Accuracy Value')
ax1.set_xlabel('Epoch')
ax1.set_title('Accuracy')
l1 = ax1.legend(loc="best")
ax2.plot(epochs, history.history['loss'], label='Train Loss')
ax2.plot(epochs, history.history['val_loss'], label='Validation Loss')
ax2.set_xticks(epochs)
ax2.set_ylabel('Loss Value')
ax2.set_xlabel('Epoch')
ax2.set_title('Loss')
l2 = ax2.legend(loc="best")
plt.show()
# Plot training & validation accuracy values
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
# Plot training & validation loss values
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
# ---------------------------------------------------------------------------------------------------------------
# Test Model Performance
# ---------------------------------------------------------------------------------------------------------------
# scaling test features
x_test /= 255.
test_predictions = model.predict(x_test)
print(test_predictions)
predictions = pd.DataFrame(test_predictions, columns=labels_ohe_names.columns)
predictions.head()
test_labels = list(y_test)
predictions = list(predictions.idxmax(axis=1))
print(predictions[:10])
# ---------------------------------------------------------------------------------------------------------------
# Test Model Performance
# ---------------------------------------------------------------------------------------------------------------
import model_evaluation_utils as meu
meu.get_metrics(true_labels=test_labels,
predicted_labels=predictions)
meu.display_classification_report(true_labels=test_labels,
predicted_labels=predictions,
classes=list(labels_ohe_names.columns))
meu.display_confusion_matrix(true_labels=test_labels,
predicted_labels=predictions,
classes=list(labels_ohe_names.columns))
# ---------------------------------------------------------------------------------------------------------------
# Visualize Model Performance¶
# ---------------------------------------------------------------------------------------------------------------
grid_width = 5
grid_height = 5
f, ax = plt.subplots(grid_width, grid_height)
f.set_size_inches(15, 15)
batch_size = 25
dataset = x_test
label_dict = dict(enumerate(labels_ohe_names.columns.values))
model_input_shape = (1,)+model.get_input_shape_at(0)[1:]
random_batch_indx = np.random.permutation(np.arange(0,len(dataset)))[:batch_size]
img_idx = 0
for i in range(0, grid_width):
for j in range(0, grid_height):
actual_label = np.array(y_test)[random_batch_indx[img_idx]]
prediction = model.predict(dataset[random_batch_indx[img_idx]].reshape(model_input_shape))[0]
label_idx = np.argmax(prediction)
predicted_label = label_dict.get(label_idx)
conf = round(prediction[label_idx], 2)
ax[i][j].axis('off')
ax[i][j].set_title('Actual: '+actual_label+'\nPred: '+predicted_label + '\nConf: ' +str(conf))
ax[i][j].imshow(dataset[random_batch_indx[img_idx]])
img_idx += 1
plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0.5, hspace=0.55)
import cnn_utils as utils
print(label_dict)
utils.plot_predictions(model=model,
dataset=x_test,
dataset_labels=y_test,
label_dict=label_dict,
batch_size=batch_size,
grid_height=5,
grid_width=5)
plt.show()
<file_sep>#%% Machine Learning Class - Exercise Aral Sea Surface Estimation
plt.close('all')
# package
import numpy as np
import matplotlib.pyplot as plt
plt.ioff() # to see figure avant input
# ------------------------------------------------
# YOUR CODE HERE
from preprocessing import preprocessing
from unsupervisedTraining import unsupervisedTraining
from displayFeatures3d import displayFeatures3d
from unsupervisedClassifying import unsupervisedClassifying
from displayImageLabel import displayImageLabel
# ------------------------------------------------
# ------------------------------------------------
#%% Examen des données, prétraitements et extraction des descripteurs
# Chargement des données et prétraitements
featLearn,img73,img87 = preprocessing()
#%% Apprentissage / Learning / Training
# Apprentissage de la fonction de classement
# ------------------------------------------------
# YOUR CODE HERE
model=unsupervisedTraining(featLearn,'kmeans')
# ------------------------------------------------
# ------------------------------------------------
# prediction des labels sur la base d'apprentissage
# ------------------------------------------------
# YOUR CODE HERE
labels=model.labels_
# ------------------------------------------------
# ------------------------------------------------
# Visualisation des resultats
# ------------------------------------------------
# YOUR CODE HERE
displayFeatures2d(featLearn,labels)
displayFeatures3d(featLearn,labels)
# ------------------------------------------------
# ------------------------------------------------
#%% Classement et estimation de la diminution de surface
# Classifying / Predicting / Testing
# mise en forme de l'image de 1973 et 1987 en matrice Num Pixels / Val Pixels
# ------------------------------------------------
# YOUR CODE HERE
I73=np.zeros([img73.shape[0]*img73.shape[1],3])
for i in range(0,2):
I73[:,i]=img73[:,:,i].flatten()
I87=np.zeros([img87.shape[0]*img87.shape[1],3])
for i in range(0,2):
I87[:,i]=img87[:,:,i].flatten()
# ------------------------------------------------
# ------------------------------------------------
# Classement des deux jeux de données et visualisation des résultats en image
# ------------------------------------------------
# YOUR CODE HERE
label73=unsupervisedClassifying(model,I73)
label87=unsupervisedClassifying(model,I87)
displayImageLabel(label73,img73)
displayImageLabel(label87,img87)
# ------------------------------------------------
# ------------------------------------------------
plt.show()
#%% Estimation de la surface perdue
answer = input('Numero de la classe de la mer ? ')
cl_mer = int(answer)
# ------------------------------------------------
# YOUR CODE HERE
nbmer73=0
for i in label73:
if(i==cl_mer):
nbmer73+=1
nbmer87=0
for i in label87:
if(i==cl_mer):
nbmer87+=1
Pourc=(1-nbmer87/nbmer73)*100
print('Pourcentage evolution: ',Pourc)
# ------------------------------------------------
# ------------------------------------------------
<file_sep># TP15: Seafloor classification
## 1 - Introduction
Disposant d'un ensemble d'images dont on veut prédire la classe, deux possibilités s'offrent pour apprendre un modèle profond de classement.
- La première possibilité se nomme "Transfer Learning" associé au "fine tuning" dont les principes sont d'utiliser un réseau de neurones profond entrainé dans un autre contexte et de l'adapter à nos données:
- La seconde possibilité est de créer et d'entrainer un modèle profond ex-nihilo (from scratch, en partant de zéro).
L'objectif de ce TP est d'appliquer ces deux possibilités au problème de classification de patchs d'images sonar en types de fond marin que vous avez déjà traités dans un TP précédent. Vous reprendrez les fonctions d'import des patchs que vous avez mises au point. Il faudra néanmoins utiliser les lignes de code suivantes pour que les données soient dans la forme attendue par keras:
```python
from keras.preprocessing.image import img_to_array, load_img
target_size = 192;
feature_values = np.array([img_to_array(
load_img(img, # color_mode = "grayscale",
target_size=(target_size, target_size))
) for img
in dataset_df['image_path'].values.tolist()
]).astype('float32')
```
A noter que la taille des patchs est automatiquement réduite à 192x192 pixels, vous pouvez réduire cette taille en fonction des performances de votre machine. Attention, une taille trop basse peut impliquer une erreur si vous réutilisez par la suite un modèle déjà entrainé (par exemple VGG16).
La création d'ensemble d'apprentissage, de validation et de test se fera en divisant la base en trois parts. Il faudrait pour ce petit jeu de données réaliser une procédure de cross-validation. Compte tenu du temps pour réaliser cette procédure, elle sera ici laissée de coté.
## 2 - Transfer learning par fine tuning
- Les concepts du transfer learning sont expliqués dans les liens ci-dessous:
- https://www.youtube.com/watch?v=FQM13HkEfBk&index=20&list=PLkDaE6sCZn6Gl29AoE31iwdVwSG-KnDzF
- http://cs231n.github.io/transfer-learning/
- https://flyyufelix.github.io/2016/10/03/fine-tuning-in-keras-part1.html et https://flyyufelix.github.io/2016/10/08/fine-tuning-in-keras-part2.html
- Vous commencerez par le fine tuning en vous inspirant des codes Keras fournis...
- [https://github.com/dipanjanS/hands-on-transfer-learning-with-python/blob/master/notebooks/Ch06%20-%20Image%20Recognition%20and%20Classification/CIFAR10_CNN_Classifier.ipynb](https://github.com/dipanjanS/hands-on-transfer-learning-with-python/blob/master/notebooks/Ch06 - Image Recognition and Classification/CIFAR10_CNN_Classifier.ipynb) et [https://github.com/dipanjanS/hands-on-transfer-learning-with-python/blob/master/notebooks/Ch06%20-%20Image%20Recognition%20and%20Classification/CIFAR10_VGG16_Transfer_Learning_Classifier.ipynb](https://github.com/dipanjanS/hands-on-transfer-learning-with-python/blob/master/notebooks/Ch06 - Image Recognition and Classification/CIFAR10_VGG16_Transfer_Learning_Classifier.ipynb)
- [https://github.com/dipanjanS/hands-on-transfer-learning-with-python/blob/master/notebooks/Ch06%20-%20Image%20Recognition%20and%20Classification/Dog_Breed_EDA.ipynb](https://github.com/dipanjanS/hands-on-transfer-learning-with-python/blob/master/notebooks/Ch06 - Image Recognition and Classification/Dog_Breed_EDA.ipynb) et [https://github.com/dipanjanS/hands-on-transfer-learning-with-python/blob/master/notebooks/Ch06%20-%20Image%20Recognition%20and%20Classification/Dog_Breed_Transfer_Learning_Classifier.ipynb](https://github.com/dipanjanS/hands-on-transfer-learning-with-python/blob/master/notebooks/Ch06 - Image Recognition and Classification/Dog_Breed_Transfer_Learning_Classifier.ipynb)
- ...pour faire du transfer learning du modèle vgg16 (dont les paramètres ont été appris sur la base d'images "imageNet") pour l'appliquer aux patchs d'images sonar. Vous procéderez ainsi:
- les modèles sont téléchargeables ici: https://drive.google.com/open?id=1qFwqoNU1fsvl8fu-7eRCmjoPNZZNzPSJ
- Résumer l'approche du transfer learning/fine tuning
- Vous précisérez votre choix concernant les paramètres des fonctions appelées en particulier expliquer votre démarche concernant les phases de preprocessing des images, de data augmentation, de classification, etc.
- remarque: comme les images sonar sont en niveaux de gris et que le modèle VGG prend en entrée des images couleurs, il s'agira de dupliquer ce canal sur les canaux R, G et B.
- Vous évaluerez les performances obtenues;
- (Bonus) Essayez et comparez d'autres architectures (Resnet, Inception etc...https://keras.io/applications/).
## 3 - Proposition de votre propre achitecture
- Vous proposerez ensuite une architecture de réseau profond convolutif et évaluerez ses performances. Vous pourrez vous appuyer sur les vidéos d'<NAME> déjà fournis et sur ce tutorial [https://github.com/dipanjanS/hands-on-transfer-learning-with-python/blob/master/notebooks/Ch06%20-%20Image%20Recognition%20and%20Classification/CIFAR10_CNN_Classifier.ipynb](https://github.com/dipanjanS/hands-on-transfer-learning-with-python/blob/master/notebooks/Ch06 - Image Recognition and Classification/CIFAR10_CNN_Classifier.ipynb). Si vous voulez allez plus loin, il existe des cours et des vidéos utiles de Stanford University: http://cs231n.github.io/neural-networks-1/, http://cs231n.github.io/neural-networks-2/, http://cs231n.github.io/neural-networks-3/, https://www.youtube.com/watch?v=wEoyxE0GP2M&list=PL3FW7Lu3i5JvHM8ljYj-zLfQRF3EO8sYv&index=6, https://www.youtube.com/watch?v=wEoyxE0GP2M&list=PL3FW7Lu3i5JvHM8ljYj-zLfQRF3EO8sYv&index=7)
- Expliquez brièvement votre architecture et en particulier à quoi servent les couches (et leur enchainement) de votre architecture.
- Vous comparerez ensuite les deux performances sur la matrice de confusion et les métriques de performance classiques.
# A rendre
Pour la prochaine séance, au choix (N'oublier pas les deux noms en cas de binômes):
- un fichier zip avec *.py et un cr au format pdf
- un fichier .ipynb avec compte-rendu et code<file_sep>import numpy as np
def linearRegCostFunction(X, y, theta, Lambda):
"""computes the
cost of using theta as the parameter for linear regression to fit the
data points in X and y. Returns the cost in J and the gradient in grad
"""
# Initialize some useful values
m,n = X.shape # number of training examples
theta = theta.reshape((n,1)) # in case where theta is a vector (n,)
y = y.reshape((m,1))
J = np.zeros((m,n))
grad = np.zeros((m,n))
# ====================== YOUR CODE HERE ======================
# Instructions: Compute the cost and gradient of regularized linear
# regression for a particular choice of theta.
#
# You should set J to the cost and grad to the gradient.
#
h_theta = X@theta
Jint = (h_theta-y)**2
J = (np.sum(Jint)/(2*m))
part2 = theta**2
J = J +(np.sum(part2[1:,0])*Lambda/(2*m))
error = h_theta - y
grad= X.T@error/m
grad[1:,0] = grad[1:,0] + (Lambda*theta[1:,0])/m
# =========================================================================
return J.flatten(), grad.flatten()<file_sep># %% Machine Learning Class - Exercise Aral Sea Surface Estimation
# package
import numpy as np
import matplotlib.pyplot as plt
from displayFeatures2d import displayFeatures2d
from displayFeatures3d import displayFeatures3d
from displayImageLabel import displayImageLabel
from unsupervisedClassifying import unsupervisedClassifying
from unsupervisedTraining import unsupervisedTraining
plt.ioff() # to see figure avant input
# ------------------------------------------------
# YOUR CODE HERE
from preprocessing import preprocessing
# ------------------------------------------------
# ------------------------------------------------
# %% Examen des données, prétraitements et extraction des descripteurs
# Chargement des données et prétraitements
featLearn, img73, img87 = preprocessing()
# %% Apprentissage / Learning / Training
# Apprentissage de la fonction de classement
# ------------------------------------------------
model = unsupervisedTraining(featLearn, 'kmeans')
# ------------------------------------------------
# prediction des labels sur la base d'apprentissage
# ------------------------------------------------
labels = model.labels_
# ------------------------------------------------
# Visualisation des resultats
# ------------------------------------------------
displayFeatures2d(featLearn, labels)
displayFeatures3d(featLearn, labels)
# ------------------------------------------------
# %% Classement et estimation de la diminution de surface
# Classifying / Predicting / Testing
# mise en forme de l'image de 1973 et 1987 en matrice Num Pixels / Val Pixels
# ------------------------------------------------
n_img73 = np.zeros([img73.shape[0] * img73.shape[1], 3])
for i in range(0, 2):
n_img73[:, i] = img73[:, :, i].flatten()
# print(n_img73)
n_img87 = np.zeros([img87.shape[0] * img87.shape[1], 3])
for i in range(0, 2):
n_img87[:, i] = img87[:, :, i].flatten()
# print(n_img73)
# ------------------------------------------------
# Classement des deux jeux de données et visualisation des résultats en image
# ------------------------------------------------
label_img73 = unsupervisedClassifying(model, n_img73)
label_img87 = unsupervisedClassifying(model, n_img87)
displayImageLabel(label_img73, img73)
displayImageLabel(label_img87, img87)
# ------------------------------------------------
# %% Estimation de la surface perdue
answer = input('Numero de la classe de la mer ? ')
cl_mer = int(answer)
# ------------------------------------------------
surface_73 = 0
for i in label_img73:
if i == cl_mer:
surface_73 += 1
print('surface en pixels de la classe: ', surface_73)
surface_87 = 0
for i in label_img87:
if i == cl_mer:
surface_87 += 1
print('surface en pixels de la classe: ', surface_87)
evo_surface = (1-surface_87/surface_73)*100
print('evolution de la surface: ', evo_surface, "%")
# ------------------------------------------------
<file_sep><table>
<tr>
<td><NAME></br>
<NAME></td>
<td>BE machine Learning (TP7)</td>
<td>FIPA_2020 </br>26/11/2019</td>
</table>
# 🐚 - Classification d'images satellites de la mer d'Aral
------
## 1 - Examen des données, pré-traitements et extraction des descripteurs:
### Question 1:
*Compléter une fonction preprocessing() permettant de charger les deux images et de les afficher.* *indication : loadImages().*
Fonction `preprocessing()`:
```python
#%% def preprocessing
def preprocessing():
# ------------------------------------------------
# YOUR CODE HERE
img73, img87 = loadImages()
featLearn = 0
# Redimensionnement
img73 = img73[120:820, 180:800, :]
img87 = img87[120:820, 180:800, :]
# Affichage des images
plt.figure(1);
plt.imshow(img73);
plt.show()
plt.figure(2);
plt.imshow(img87);
plt.show()
# ------------------------------------------------
# ------------------------------------------------
#%% sortie
return featLearn,img73,img87
```
### Question 2:
*Que peut-on deduire de l’analyse de ces images ? Comment sont codees les valeurs des pixels ?*
Ces images sont codees en RGB
### Question 3:
*Les images sont en couleurs et nous allons utiliser les composantes des couleurs comme descripteurs de classification. Quelle est la dimension de l’espace des descripteurs lorsque l’image est codee en RGB (RVB) ?*
L’espaces des descripteurs est de dimension 3 soit une dimension par couleur codés sur 8
bits (de 0 à 255).
### Question 4:
*Tronquer de la meme maniere les deux images pour faire disparaıtre le texte dans la partie haute et basse des images:*
**Img73:**
| Avant | Apres |
| ------------------------------------------------------------ | ------------------------------- |
| <img src="IMG/Aral1973_Clean.jpg" alt="Aral1973_Clean" title="Img73_old" style="zoom:50%;" /> |  |
**Img87:**
| Avant | Apres |
| ------------------------------------------------------------ | ------------------------------- |
| <img src="IMG/Aral1987_Clean.jpg" alt="Aral1973_Clean" title="Img73_old" style="zoom:50%;" /> |  |
------
## 2 - Constitution d'un ensemble de donnees d'apprentissage
------
### Question 5:
*Completer la fonction preprocessing() par une partie qui vise a constituer une base d’apprentissage. Pour cela, realisez un sous-echantillonnage de l’image de 1973 avec un pas de 500 points (indication : selectFeatureVectors.py). Quel est le nombre de donnees d’apprentissage ?*
Fonction `preprocessing()`:
```python
#%% def preprocessing
def preprocessing():
# ------------------------------------------------
# YOUR CODE HERE
img73, img87 = loadImages()
featLearn = 0
# Redimensionnement
img73 = img73[120:820, 180:800, :]
img87 = img87[120:820, 180:800, :]
# Affichage des images
plt.figure(1);
plt.imshow(img73);
plt.show()
plt.figure(2);
plt.imshow(img87);
plt.show()
# Echantillonnage
featLearn, nbPix, nbFeat = selectFeatureVectors(img73, 500)
print('nb pix:', nbPix, '\r')
print('nb feat:', nbFeat, '\r')
# print('featLearn:', featLearn, '\r')
# ------------------------------------------------
# ------------------------------------------------
#%% sortie
return featLearn,img73,img87
```
> Output:
>
> ```
> nb pix: 868
> nb feat: 3
> ```
Nous avons donc ici pour l'image de 1973 un nombre de données d’apprentissage egal a un tableau de dimension (868,3).
## 3 - Premiere analyse des donnees
### Question 6:
*Dans preprocessing, visualiser en 2D et 3D les valeurs des descripteurs. La visualisation en 2D des vecteurs d’apprentissage se fait par la fonction displayFeatures2d(feat) et en 3D displayFeatures3d(feat).*
Fonction `preprocessing()`:
```python
#%% def preprocessing
def preprocessing():
# ------------------------------------------------
# YOUR CODE HERE
img73, img87 = loadImages()
featLearn = 0
# Redimensionnement
img73 = img73[120:820, 180:800, :]
img87 = img87[120:820, 180:800, :]
# Affichage des images
plt.figure(1);
plt.imshow(img73);
plt.show()
plt.figure(2);
plt.imshow(img87);
plt.show()
# Echantillonnage
featLearn, nbPix, nbFeat = selectFeatureVectors(img73, 500)
print('nb pix:', nbPix, '\r')
print('nb feat:', nbFeat, '\r')
# print('featLearn:', featLearn, '\r')
# Affichage 2D et 3D
displayFeatures2d(featLearn)
displayFeatures3d(featLearn)
# ------------------------------------------------
# ------------------------------------------------
#%% sortie
return featLearn,img73,img87
```
> Output:
>
> | displayFeature2D | displayFeature3D |
> | ------------------------------------------------------------ | --------------------------------------------- |
> | <img src="IMG/displayFeature2D.png" alt="displayFeature2D" style="zoom: 67%;" /> |  |
### Question 7:
*Decrivez explicitement ces graphiques en expliquant ce qu’ils representent, en donnant leurs caracteristiques pour les histogrammes et les nuages de points (differents groupes ? a quelles informations peut-on les relier ?)*
<u>**displayFeatures2d:**</u>
Ce graphique nous montre à la fois les valeurs des pixels par couleur dans l’image et leur repartition dans l’image. Les histogrammes montre la valeur du pixel correspodnant au point sur le nuages de point de chaque couleur.
<u>**displayFeatures3d:**</u>
Ici nous avons un nuage de points correspondant aux 3 niveaux RBG, ces niveaux sont representes dans le meme graphique ce qui nous permet de penser que la couleure du lac se situe en bas a gauche de ce graphique, dans les niveaux les plus sombres,
## 4 - approche non supervisee par la methode des k-means
### Question 8:
*Decrire la methode des centres mobiles*:
La methode des centres mobiles sert a partitionner en différentes classes des individus pour lesquels on dispose de mesures ou de valeurs. Ces individus sont représentés comme des points de l’espace ayant pour coordonnées ces valeurs. On cherche à regrouper autant que possible les individus les plus semblables (du point de vue des valeurs que l’on possède) tout en séparant les classes le mieux possible les unes des autres.
La méthode des centres mobiles s’applique lorsque l’on sait à l’avance combien de classes on veut obtenir. Pour initialiser l’algorithme, on tire au hasard autant d’individus que de classes souhaités appartenant à la population, ce sont les centres initiaux.
Ensuite, On répartit l’ensemble des individus dans les classes en regroupant autour de chaque centre l’ensemble des individus qui sont plus proches du centre que des autres centres. Puis on détermine les centres de gravité des classes ainsi obtenues et on désigne ces points comme les nouveaux centres.
On répète ces deux étapes jusqu’à la stabilisation de l’algorithme, c’est-à-dire jusqu’à ce que le
découpage en classes obtenu ne soit presque plus modifié par une itération suplémentaire.
### Question 9:
*Appeler et completer le script `unsupervisedTraining.py` qui permet realiser un apprentissage non supervise du modele de classement (classifieur) a l’aide de la fonction KMeans() du package scikit learn (puissant package de Machine Learning pour python). Comment utilise-t-on cette fonction ? Quels en sont les parametres de controle importants ?*
Contenu du script python `unsupervisedTraining.py` :
```python
# %% def unsupervisedTraining
def unsupervisedTraining(featLearn, method='kmeans'):
''' apprentissage avec la fonction KMeans() et GaussianMixture
de scikit-learn :
- featLearn est la matrice de l'ensemble d'apprentissage
- method: type d'algorithme de Machine Learning utilisé (KMeans et GaussianMixture)
- nbCluster est le nombre de cluster = nombre de classes rentré par l'utilisateur en début de fonction
- renvoie model: le modèle de classement ou classifieur
'''
# fixer le nombre de classes
answer = input('nombre de classes:')
nbCluster = int(answer)
if method == 'kmeans':
init = 'random'
n_init = 10
max_iter = 300
model = KMeans(nbCluster, init, n_init, max_iter).fit(featLearn)
elif method == 'gmm':
pass
# ------------------------------------------------
# YOUR CODE HERE
# ------------------------------------------------
# ------------------------------------------------
# sortie
return model
```
la fonction `Kmeans()` prend en argument le nombre de classes (nbCluster), la méthode du choix des centres initiaux (ici nous utilisons un choix aléatoire) et le nombre maximum d’itérations effectuer par la fonction pour converger.
### Question 10:
*Completer `aralsea_main.py` pour predire les labels sur la base d’apprentissage grace au modele appris.*
Implementation dans `aralsea_main.py` :
```python
# %% Apprentissage / Learning / Training
# Apprentissage de la fonction de classement
# ------------------------------------------------
model = unsupervisedTraining(featLearn, 'kmeans')
# ------------------------------------------------
# prediction des labels sur la base d'apprentissage
# ------------------------------------------------
labels = model.labels_
# ------------------------------------------------
```
### Question 11:
*Il est maintenant possible de visualiser les valeurs des descripteurs d’apprentissage et leur appartenance a l’une des classes (un des clusters). Nous utiliserons la fonction : `displayFeatures2d` et `displayFeatures3d`. Completer `aralsea_main.py`. Faire varier le parametrage de la fonction KMeans et analyser les differences et la qualite de l’apprentissage.*
Implementation dans `aralsea_main.py` :
```python
# Visualisation des resultats
# ------------------------------------------------
displayFeatures2d(featLearn, labels)
displayFeatures3d(featLearn, labels)
# ------------------------------------------------
```
> Output:
>
> | displayFeature2D | displayFeature3D |
> | ------------------------------------------------------------ | ------------------------------------------------------------ |
> | <img src="IMG/displayFeature2D_2classes_kmean.png" alt="displayFeature2D" style="zoom: 67%;" /> |  |
**<u>Variation des parametres de Kmeans :</u>**
* NbClusters : Lorsqu’on augmente le nombres de classes, on augmente le nombres de couleurs sur le graphique mais pour notre application, le nombres de 2 est suffisant.
* Le nombre d’essai pour une valeur de 1, a pour effet de retourner des valeurs erronées quand les centroides initiaux sont mauvais.
* Le nombre d’itérations à pour effet de laisser de définir de mauvaises limites entres les classes quand il est trop petit.
### Question 12:
*A ce stade, vous avez choisi les hyper-parametres de vos methodes de machine learning et obtenu le modele de classement, nous pouvons alors utiliser les donnees d’apprentissage pour classifier l’ensemble des deux images. Il faut calculer les descripteurs sur toute l’image (mise sous la forme d’une matrice) puis utiliser le modele de classement issu de l’apprentissage du k-means). Completer les scripts `aralsea_main.py` et `unsupervisedClassifying.py`.*
Script python `unsupervisedClassifying.py`:
```python
# %% def unsupervisedClassifying
def unsupervisedClassifying(model, feat):
''' classement/prédiction à partir d'un modèle de classement non supervisé
feat est la matrice du jeu de données à classer
label est la classe prédite
'''
# ------------------------------------------------
label = model.predict(feat)
# ------------------------------------------------
return label
```
Implementation dans `aralsea_main.py`:
```python
# %% Classement et estimation de la diminution de surface
# Classifying / Predicting / Testing
# mise en forme de l'image de 1973 et 1987 en matrice Num Pixels / Val Pixels
# ------------------------------------------------
n_img73 = np.zeros([img73.shape[0] * img73.shape[1], 3])
for i in range(0, 2):
n_img73[:, i] = img73[:, :, i].flatten()
#print(n_img73)
n_img87 = np.zeros([img87.shape[0] * img87.shape[1], 3])
for i in range(0, 2):
n_img87[:, i] = img87[:, :, i].flatten()
#print(n_img73)
# ------------------------------------------------
```
### Question 13:
*Pour visualiser le resultat de classification, il faut que chaque classe predite puisse etre affectee au pixel correspondant de l’image. Cette image est calculee et visualisee par la fonction `displayImageLabel.py`. Completer `aralsea_main.py`*
Implementation de `displayImageLabel()` dans `aralsea_main.py`:
```python
# Classement des deux jeux de données et visualisation des résultats en image
# ------------------------------------------------
label_img73 = unsupervisedClassifying(model, n_img73)
label_img87 = unsupervisedClassifying(model, n_img87)
displayImageLabel(label_img73, img73)
displayImageLabel(label_img87, img87)
# ------------------------------------------------
```
> Output:
>
> | img 1973 | img 1987 |
> | ------------------------------------------------------------ | ------------------------------------------------------------ |
> | <img src="IMG/DisplayImgLabel_73.png" alt="displayFeature2D" /> | <img src="IMG/DisplayImgLabel_87.png" alt="displayFeature2D" /> |
### Question 14:
*Apres avoir identifiee sur l’image la couleur de la classe (et son numero) de la zone correspondant a la mer d’Aral, il est possible d’en estimer la surface (i.e. le nombre de pixels) sur les deux images et d’en estimer l’evolution. Quelle est approximativement cette evolution en % ? Pour repondre a cette question completer `aralsea_main.py.`*
Calcul de l'evolution de la surface dans `aralsea_main.py`:
```python
# %% Estimation de la surface perdue
answer = input('Numero de la classe de la mer ? ')
cl_mer = int(answer)
# ------------------------------------------------
surface_73 = 0
for i in label_img73:
if i == cl_mer:
surface_73 += 1
print('surface en pixels de la classe: ', surface_73)
surface_87 = 0
for i in label_img87:
if i == cl_mer:
surface_87 += 1
print('surface en pixels de la classe: ', surface_87)
evo_surface = (1-surface_87/surface_73)*100
print('evolution de la surface: ', evo_surface, "%")
# ------------------------------------------------
```
Ici nous calculons le nombre de pixels de la classe representant le lac entre 1973 et 1987, puis nous en deduisons l'évolution de la surface. Elle est approximativement de 20.97 %.
### Question 15:
*Analyser en fonction des parametres du kmeans et du mode de codage des couleurs la creation de classe dans l’espace des descripteurs et donner l’impact que cela a sur le pourcentage estime ?*
Si nous considerons 3 classes, l’evolution de la mer est de 23,64 %.
Si nous considerons 4 classes, l’evolution de la mer est de 25.25 %.
Lorsque les paramètres de la fonction Kmeans évoluent, le résultat final évolu aussi, la définiton du nombres de classes est le point le plus important de la fonction, c’est le paramètre qui a le plus d’impact sur le résultat.
## 4 - Approche non-supervisee par GMM
### Question 16:
*Decrire en detail, l’apprentissage du classifieur non supervise base sur les melanges de gaussiennes.*
Les données sont générées à partir d’échantillons provenant de K différentes lois gaussiennes, ayant chacune des moyennes et des covariances différentes.
### Question 17:
*Completer votre code pour apprendre un classifieur base des melanges de gaussiennes.*
<NAME> - <NAME>
FIPA2020<file_sep><table>
<tr>
<td><NAME> </br><NAME></td>
<td>FIPA20 </br>20/09/2018</td>
</table>
# SEABED CLASSIFICATION
## Introduction
Lors de l'utilisation du dernier jeu de données sur les fonds marins, nous avons travaillé sur le ### qui se compose du random forest [...] .
Dans cet apprentissage, nous allons mettre en avant le machine learning avec un apprentissage profond via des réseaux de neurones convolutionnel.
Nous disposons d'un ensemble d'images dont on veut prédire la classe, deux possibilités s'offrent à nous pour apprendre un modèle profond de classement.
- La première possibilité se nomme "Transfer Learning" associé au "fine tuning" dont les principes sont d'utiliser un réseau de neurones profond entrainé dans un autre contexte et de l'adapter à nos données;
- La seconde possibilité est de créer et d'entrainer un modèle profond ex-nihilo (from scratch, en partant de zéro).

## Intégration des Modèles de DEEP LEARNING
### Transfer Learning
Dans le cadre de transfert learning, nous implémentons des solutions déjà existantes avec un réseau de neurones profond entrainé :
- VGG16
- InceptionV3
- MobileNetV2
- DenseNet201
### Paramétrage
Les paramètres sont définis avec :
- `LEARNING_RATE` de 0.0001
- `INPUT_SHAPE` avec 192 px sur 192 px et le domaine RGB a été remplacé par 3 fois le niveau de gris initial
- `EPOCHS` pour l'apprentissage sera défini à 30 boucles.
### Choix des modèles
Le **Deep Learning** a suscité de plus en plus d'attention au fil des années.
Il n’est pas surprenant que de nombreux travaux de recherche ont été partagés dans des conférences et revues réputées dans le monde entier centré sur le Deep Learning. C'est notamment les architectures de classification des images qui sont à l'honneur depuis quelques années, avec des améliorations régulièrement partagées.
Jetons un coup d'œil à certaines architectures de classification d'images avancées qui donnent les meilleures performances :
* **AlexNet**: Conçu par l'un des pionniers du deep learning, <NAME> et son équipe, ce
réseau a réduit le taux d'erreur à seulement 15,3%. C'était aussi l'une des premières
architectures qui tire partit des GPU pour accélérer le processus d'apprentissage.
* **VGG-16**: Le réseau du Visual Geometry Group d'Oxford est l'une des architectures les plus performantes, largement utilisées pour l'analyse comparative d'autres conceptions.
VGG-16 utilise une architecture simple basée sur 3 x 3 couches convolutionnelles empilées une
sur l'autre (16 fois), suivi d'une couche de mise en commun maximale pour atteindre de formidables
performances. Ce modèle a été remplacé par un modèle légèrement plus complexe nommé VGG19.
* **Inception**: également connu sous le nom de **GoogleNet**, ce réseau a été introduit dans le
Défi de reconnaissance visuelle à grande échelle ImageNet (ILSVRC) en 2014, et atteint un taux d'erreur de 6,67%. Ce fut l'une des premières architectures à atteindre des performances presque humaines. La nouveauté derrière ce réseau était l'utilisation d'une couche de démarrage, qui implique la concaténation de noyaux de tailles différentes à au même niveau.
* **ResNet**: introduit par Microsoft Research Asia, le réseau résiduel (ResNet) était une nouvelle architecture utilisant la normalisation par lots et le saut des connexions pour atteindre un taux d'erreur de seulement 3,57%. Il est beaucoup plus profond (152 couches) et plus complexe que des architectures plus simples comme VGG.
* **MobileNet**: Alors que la plupart des architectures sont dans la course aux armements pour surpasser les autres, chaque nouveau réseau complexe nécessite encore plus de puissance de calcul. MobileNet s'écarte de ces architectures et est conçu pour être adapté aux systèmes mobiles et embarqués. Ce réseau utilise une nouvelle idée de utilisant des convolutions séparables en profondeur pour réduire le nombre total de paramètres requis pour former un réseau.
Nous pouvons créer notre propre modèle manuellement la condition : `MyCNN`. En effet, nous implémentons l'architecture de son choix avec différents niveaux de convolution.
Dans notre cas, `MyCNN` avec un CNN très simple avec seulement cinq couches (deux convolutionnel, un pool max, une couche dense et une couche softmax finale) construits à l'aide de Keras.
Pour améliorer les performances globales de généralisation, le modèle contient également une couche BatchNormalization avec une couche DropOut. Ces couches nous aident à garder la forme en échec et empêche également le réseau de mémoriser le jeu de données lui-même.
Et il est tout à fait possible et nécessaire d'utiliser la base d'une architecture ci-dessus et de la modifier (voir ci-dessous).
### Modification des modèles
Il sera toujours nécessaire de modifier notre modèle pour faire correspondre à notre besoin. En effet, la sortie de notre classifieur nécéssite au moins 6 classes.
Or l'architecture de base des modèle ci-dessous ne le permet pas d'office, il faut donc ajouter une sortie pour 6 classes avec la ligne suivante:
``` python
predictions = Dense(label_nb, activation='softmax')(out)
```
Vous pouvez même ajouter des niveaux de covolution ou modfier l'architecture aux modèles ci dessous en modifiant la condition avec `My`.
Ainsi en rajoutant `My` devant le nom du modèle dans la variable `MODEL_DEFINED`, va vous permettre de modifier cette architecture, exemple : `MODEL_DEFINED = "MyVGG16"`.
### Compilation du modèle
Une fois les modifications apportées, nous pouvons compiler notre moodèle et l'afficher avec `model.summary()`
### Entrainement de votre architecture
Une fois votre architecture généré, il faudra entrainer le modèle avec notre jeu de données via le `fit_generator`.
RAPPEL :
La BATCH SIZE est un hyperparamètre de descente de gradient qui contrôle le nombre d'échantillons d'apprentissage à analyser avant la mise à jour des paramètres internes du modèle.
Le nombre d'EPOCHS est un hyperparamètre de descente de gradient qui contrôle le nombre de passages complets dans l'ensemble de données d'apprentissage.
Le paramètre `verbose` permet l'affichage des EPOCHS dans le terminal lorsqu'il est à 1. Pour un soucis de confort de lecture dans Jupyter, il est passé à 0. Cette étape peut prendre 1h.
### Exporter le modèle
Lorsque votre modèle est convainquant, il est important de l'exporter pour éviter de réaliser la phase d'apprentissage à chaque fois.
### Prédiction
A présent, nous réutilisons notre modèle pour prédire sur les valeurs de `x_test` et nous retourne les labels qu'il a prédit dans la variable `predictions`.
De plus, nous calculons le temps d'execution pour faire une analyse en conclusion.
Nous pouvons à présent afficher les résultats associés à notre modèle et les écarts avec la réalité.
Nous pouvons retourner les performances sur la matrice de confusion et les métriques de performance classiques.
La matrice de confusion est un simple tableau présentant le nombre d’instances appartenant à chacune de ces six catégories.
La métrique de performance ou exactitude désigne simplement la proportion d’instances qui ont été classées correctement.
## Comparatif des modèles et des architectures
Le comparatif a été réalisé sur un ordinateur portable ThinkPad avec un processeur Intel Core i7 sans carte graphique compatible avec TensorFlow.
A présent, nous avons comparé les differentes architectures en une seule et unique fois avec le même jeu de données et avec les mêmes valeurs d'entrainement, d'évaluation et de test ainsi que le même nombre d'EPOCHS.
### 1- VGG16
#### Description
Le réseau du Visual Geometry Group d'Oxford est l'une des architectures les plus performantes, largement utilisées pour l'analyse comparative d'autres conceptions.
VGG-16 utilise une architecture simple basée sur 3 x 3 couches convolutionnelles empilées une
sur l'autre (16 fois), suivi d'une couche de mise en commun maximale pour atteindre de formidables
performances. Ce modèle a été remplacé par un modèle légèrement plus complexe nommé VGG19.
#### Apprentissage
Le temps d'apprentissage est de 5419 secondes.
Le poids du modèle est de : 176 mb.

#### Prédiction Globale
Le temps de prédiction est de 7 secondes.
Nous obtenons les scores suivants :
- Accuracy: 0.9211
- Precision: 0.9474
#### Matrice de confusion
```
precision recall f1-score support
Posidonia 1.00 1.00 1.00 7
Ripple 45° 1.00 0.50 0.67 6
Ripple vertical 0.67 1.00 0.80 6
Rock 1.00 1.00 1.00 6
Sand 1.00 1.00 1.00 6
Silt 1.00 1.00 1.00 7
accuracy 0.92 38
macro avg 0.94 0.92 0.91 38
weighted avg 0.95 0.92 0.92 38
```
#### Métriques de performance
```
Posidonia Ripple 45° Ripple vertical Rock Sand Silt
Actual: Posidonia 7 0 0 0 0 0
Ripple 45° 0 3 3 0 0 0
Ripple vertical 0 0 6 0 0 0
Rock 0 0 0 6 0 0
Sand 0 0 0 0 6 0
Silt 0 0 0 0 0 7
```
#### Plot du résultat

### 2- InceptionV3
#### Description
Egalement connu sous le nom de **GoogleNet**, ce réseau a été introduit dans le
Défi de reconnaissance visuelle à grande échelle ImageNet (ILSVRC) en 2014, et atteint un taux d'erreur de 6,67%. Ce fut l'une des premières architectures à atteindre des performances presque humaines.
La nouveauté derrière ce réseau était l'utilisation d'une couche de démarrage, qui implique la concaténation de noyaux de tailles différentes à au même niveau.
#### Apprentissage
Le temps d'apprentissage est de 1924 secondes.
Le poids du modèle est de : 262 mb.

#### Prédiction Globale
Le temps de prédiction est de 3.7 secondes.
Nous obtenons les scores suivants :
- Accuracy: 0.5263
- Precision: 0.4662
#### Matrice de confusion
```
precision recall f1-score support
Posidonia 0.00 0.00 0.00 7
Ripple 45° 0.83 0.83 0.83 6
Ripple vertical 0.83 0.83 0.83 6
Rock 1.00 0.67 0.80 6
Sand 0.29 1.00 0.44 6
Silt 0.00 0.00 0.00 7
accuracy 0.53 38
macro avg 0.49 0.56 0.49 38
weighted avg 0.47 0.53 0.46 38
```
#### Métriques de performance
```
Posidonia Ripple 45° Ripple vertical Rock Sand Silt
Actual: Posidonia 0 0 0 0 7 0
Ripple 45° 0 5 1 0 0 0
Ripple vertical 0 1 5 0 0 0
Rock 1 0 0 4 1 0
Sand 0 0 0 0 6 0
Silt 0 0 0 0 7 0
```
#### Plot du résultat

### 3- MobileNetV2
#### Description
Alors que la plupart des architectures sont dans la course aux armements pour surpasser les autres, chaque nouveau réseau complexe nécessite encore plus de puissance de calcul. MobileNet s'écarte de ces architectures et est conçu pour être adapté aux systèmes mobiles et embarqués.
Ce réseau utilise une nouvelle idée de utilisant des convolutions séparables en profondeur pour réduire le nombre total de paramètres requis pour former un réseau.
#### Apprentissage
Le temps d'apprentissage est de 1437 secondes.
Le poids du modèle est de : 27 mb.

#### Prédiction Globale
Le temps de prédiction est de 3.6 secondes.
Nous obtenons les scores suivants :
- Accuracy: 0.1579
- Precision: 0.0287
#### Matrice de confusion
```
precision recall f1-score support
Posidonia 0.00 0.00 0.00 7
Ripple 45° 0.18 1.00 0.31 6
Ripple vertical 0.00 0.00 0.00 6
Rock 0.00 0.00 0.00 6
Sand 0.00 0.00 0.00 6
Silt 0.00 0.00 0.00 7
accuracy 0.16 38
macro avg 0.03 0.17 0.05 38
weighted avg 0.03 0.16 0.05 38
```
#### Métriques de performance
```
Posidonia Ripple 45° Ripple vertical Rock Sand Silt
Actual: Posidonia 0 5 0 0 2 0
Ripple 45° 0 6 0 0 0 0
Ripple vertical 0 6 0 0 0 0
Rock 0 6 0 0 0 0
Sand 0 6 0 0 0 0
Silt 0 4 0 0 3 0
```
#### Plot du résultat

### 4- MyCNN - Mon réseau neuronal convolutif personnalisé
#### Description
`MyCNN` avec un CNN très simple avec seulement cinq couches (deux convolutionnel, un pool max, une couche dense et une couche softmax finale) construits à l'aide de Keras.
Pour améliorer les performances globales de généralisation, le modèle contient également une couche BatchNormalization avec une couche DropOut. Ces couches nous aident à garder la forme en échec et empêche également le réseau de mémoriser le jeu de données lui-même.
#### Apprentissage
Le temps d'apprentissage est de 688 secondes.
Le poids du modèle est de : 443 mb.

#### Prédiction Globale
Le temps de prédiction est de 3.6 secondes.
Nous obtenons les scores suivants :
- Accuracy: 0.1579
- Precision: 0.0287
#### Matrice de confusion
```
precision recall f1-score support
Posidonia 0.00 0.00 0.00 7
Ripple 45° 0.00 0.00 0.00 6
Ripple vertical 0.75 1.00 0.86 6
Rock 0.35 1.00 0.52 6
Sand 1.00 0.67 0.80 6
Silt 1.00 0.43 0.60 7
accuracy 0.50 38
macro avg 0.52 0.52 0.46 38
weighted avg 0.52 0.50 0.45 38
```
#### Métriques de performance
```
Posidonia Ripple 45° Ripple vertical Rock Sand Silt
Actual: Posidonia 0 0 0 7 0 0
Ripple 45° 0 0 2 4 0 0
Ripple vertical 0 0 6 0 0 0
Rock 0 0 0 6 0 0
Sand 2 0 0 0 4 0
Silt 4 0 0 0 0 3
```
#### Plot du résultat

### 4- MyVGG16 - Mon VGG16 personnalisé
#### Description
`MyVGG16` avec un CNN qui est inspiré de l'architecture du VGG16 de base et nous avons modifié la fin.
En effet, nous avons intégré des couches supplémentaires de convolution. Pour améliorer les performances globales de généralisation, le modèle contient également une couche BatchNormalization avec une couche DropOut. Ces couches nous aident à garder la forme en échec et empêche également le réseau de mémoriser le jeu de données lui-même.
Malheuresement mon ordinateur n'a pas supporté les couches supplémentaires et m'a retourné:
```
Process finished with exit code 137 (interrupted by signal 9: SIGKILL)
```
## CONCLUSION
Nous avons pu étudier l'apprentissage via Transfer Learning est le résultat est intéressant:
- *VGG16* est hyper performant mais long à l'execution. Mếme si la version personnalisée est compliquée à mettre en place.
- *MobileNetV2* a des résultats médiocres avec 30 EPOCHS mais possèdent des propriétés intérressantes pour l'embarqué.
- MyCNN, mon architecture est vraiment simpliste et pourtant les résultats sont plus que corrects.<file_sep>#
import numpy as np
from numpy.random import rand
import scipy as sp
from scipy.io import loadmat
from sklearn import metrics
import pandas as pd
pd.options.display.max_colwidth = 600
import skimage
from skimage import transform
# %matplotlib inline
import matplotlib.pyplot as plt
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize':'x-large',
'xtick.labelsize':'x-large',
'ytick.labelsize':'x-large'}
plt.rcParams.update(params)
#
import warnings
warnings.filterwarnings('ignore')
# This function loads raw data from the dataSet directory or scatFeatures from matfile
def importData(feature_type):
# Paramètres
DATASET_PATH = r'./dataset/imgs/'
LABEL_PATH = r'./dataset/labels/labels.csv'
SCATFEAT_PATH = r'./dataset/imdb_200x200_SmallSonarTex_db_6classes_scatValOnly.mat'
# Charger le fichier CSV
dataset_df = pd.read_csv(LABEL_PATH)
# We add another column to the labels dataset to identify image path
dataset_df['image_path'] = dataset_df.apply(lambda row: (DATASET_PATH + row["id"]), axis=1)
if (feature_type == 'raw'):
feature_values = np.array([plt.imread(img).reshape(40000,) for img in dataset_df['image_path'].values.tolist()])
elif (feature_type == 'rawKeras'):
print('inclure dans le starterCode')
from keras.preprocessing.image import img_to_array, load_img
target_size = 192;
feature_values = np.array([img_to_array(
load_img(img, # color_mode = "grayscale",
target_size=(target_size, target_size))
) for img
in dataset_df['image_path'].values.tolist()
]).astype('float32')
elif (feature_type == 'scat'):
# Si on remplace par les descripteurs du scattering operator
a = loadmat(SCATFEAT_PATH)
feature_values = a['featVal']
print(feature_values.shape)
# Récupération des labels
label_names = dataset_df['seafloor']
return feature_values, label_names, dataset_df
# This function prepares a random batch from the dataset
def load_batch(dataset_df, batch_size = 25):
batch_df = dataset_df.loc[np.random.permutation(np.arange(0,
len(dataset_df)))[:batch_size],:]
return batch_df
# This function plots sample images in specified size and in defined grid
def plot_batch(images_df, grid_width, grid_height, im_scale_x, im_scale_y):
DATASET_PATH = r'./dataset/imgs/'
LABEL_PATH = r'./dataset/labels/labels.csv'
f, ax = plt.subplots(grid_width, grid_height)
f.set_size_inches(6, 6)
img_idx = 0
for i in range(0, grid_width):
for j in range(0, grid_height):
ax[i][j].axis('off')
ax[i][j].set_title(images_df.iloc[img_idx]['seafloor'][:10])
# resize image
# ttt = sp.misc.imresize(ttt,(im_scale_x,im_scale_y)) # scipy version deprecated
ttt = plt.imread(DATASET_PATH + images_df.iloc[img_idx]['id'])
ttt = skimage.transform.resize(ttt,(im_scale_x,im_scale_y)) # skimage version
# ttt = Image.open(DATASET_PATH + images_df.iloc[img_idx]['id'])
# ttt = ttt.resize((im_scale_x,im_scale_y), Image.ANTIALIAS) # PIL version
ax[i][j].imshow(ttt)
img_idx += 1
plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0.1)<file_sep>import numpy as np
from sigmoid import sigmoid
def lrCostFunction(theta, X, y, Lambda):
"""computes the cost of using
theta as the parameter for regularized logistic regression.
"""
# ====================== YOUR CODE HERE ======================
# Instructions: Compute the cost of a particular choice of theta.
# You should set J to the cost.
#
# Hint: The computation of the cost function and gradients can be
# efficiently vectorized. For example, consider the computation
#
# sigmoid(X @ theta) or np.dot(X, theta)
#
# Each row of the resulting matrix will contain the value of the
# prediction for that example. You can make use of this to vectorize
# the cost function and gradient computations.
#
m,n = X.shape
taille = y.size
J = 0
theta = theta.reshape((n,1))
#Unregularized version
# h_theta = sigmoid(X@theta)
# y = np.transpose(y)
# Jint = (-y@np.log(h_theta))-((1-y)@np.log(1-h_theta))
# J = np.sum(Jint)/(taille)
#Regularized version
h_theta = sigmoid(X@theta)
y = np.transpose(y)
Jint = (-y@np.log(h_theta))-((1-y)@np.log(1-h_theta))
part2 = theta**2
J = (np.sum(Jint)/(m))
J = J +(np.sum(part2[1:,0])*Lambda/(2*m))
# =============================================================
return J
<file_sep>import numpy as np
from lrCostFunction import lrCostFunction
from lrCostGradient import lrCostGradient
from scipy.optimize import fmin_cg
def learnOneVsAll(X, y, num_labels, Lambda):
"""trains multiple logistic regression classifiers and returns all
the classifiers in a matrix all_theta, where the i-th row of all_theta
corresponds to the classifier for label i
"""
# Some useful variables
m, n = X.shape
# You need to return the following variables correctly
all_theta = np.zeros((num_labels, n))
# Set Initial theta
initial_theta = np.zeros((n, 1))
# ====================== YOUR CODE HERE ======================
# Instructions: You should complete the following code to train num_labels
# logistic regression classifiers with regularization
# parameter lambda.
#
#
# Hint: You can use (y == c)*1 to obtain a vector of 1's and 0's that tell use
# whether the ground truth is true/false for this class.
#
# Note: For this assignment, we recommend using fmin_cg to optimize the cost
# function. It is okay to use a for-loop (for c = 1:num_labels) to
# loop over the different classes.
# première solution
for i in range(1,num_labels+1):
print('Optimizing for handwritten number %d...' %i)
y_1vsAll = (y == i)*1
result = fmin_cg(lrCostFunction, fprime=lrCostGradient, x0=initial_theta, \
args=(X, y_1vsAll, Lambda), maxiter=50, disp=False,\
full_output=True)
all_theta[i-1,:] = result[0]
print('Done!')
# deuxième solution: si celle-ci est retenue, il faut changer le retour de la
# fonction predictOneVsAll.py de p+1 en (p[p==0]=10)
# for i in range(num_labels):
#
#
# iclass = i if i else num_labels #class "10" corresponds to handwritten zero
# print('Optimizing for handwritten number %d...' %i)
# y_1vsAll = (y == iclass)*1
#
# result = fmin_cg(lrCostFunction, fprime=lrCostGradient, x0=initial_theta, \
# args=(X, y_1vsAll, Lambda), maxiter=50, disp=False,\
# full_output=True)
#
# all_theta[i,:] = result[0]
#
# =========================================================================
# This function will return all_theta
return all_theta
<file_sep>#%% package
import numpy as np
from scipy import ndimage
#%% def loadImages
def loadImages():
''' fonction de lecture des images
de la mer d'Aral 1973 et 1987
'''
# definition du chemin aux images
path='';
im73_filename = 'Aral1973_Clean.jpg';
im87_filename = 'Aral1987_Clean.jpg';
# lectures des images
im73 = ndimage.imread(im73_filename)
im87 = ndimage.imread(im87_filename)
#%% sortie
return im73, im87<file_sep>import numpy as np
from computeCost import computeCost
def gradientDescent(X, y, theta, alpha, num_iters):
"""
Performs gradient descent to learn theta
theta, cost_history, theta_history = gradientDescent(X, y, theta, alpha, num_iters) updates theta by
taking num_iters gradient steps with learning rate alpha
"""
# Initialize some useful values
m = y.size # number of training examples
n = theta.size # number of parameters
cost_history = np.zeros(num_iters) # cost over iters
theta_history = np.zeros((n,num_iters)) # theta over iters
for i in range(num_iters):
# ====================== YOUR CODE HERE ======================
# Instructions: Perform a single gradient step on the parameter vector
# theta.
#
# Hint: While debugging, it can be useful to print out the values
# of the cost function (computeCost) and gradient here.
cost_history[i] = computeCost(X, y, theta)
theta_history[:,i] = theta.reshape((2,))
# ============================================================
return theta, cost_history, theta_history
<file_sep>
#%% package
import numpy as np
import matplotlib.pyplot as plt
from loadImages import loadImages
from selectFeatureVectors import selectFeatureVectors
from displayFeatures2d import displayFeatures2d
from displayFeatures3d import displayFeatures3d
#%% def preprocessing
def preprocessing():
# ------------------------------------------------
# YOUR CODE HERE
img73,img87=loadImages()
featLearn=0
#Redimensionnement
img73=img73[80:820,180:800,:]
img87=img87[80:820,180:800,:]
#Affichage des images
plt.figure();
plt.imshow(img73);
plt.figure();
plt.imshow(img87);
#Echantillonnage
featLearn,nbPix,nbFeat=selectFeatureVectors(img73,500)
#Affichage 2D et 3D
displayFeatures2d(featLearn)
displayFeatures3d(featLearn)
# ------------------------------------------------
# ------------------------------------------------
#%% sortie
return featLearn,img73,img87
<file_sep># coding: utf-8
# SEABED CLASSIFICATION WITH <NAME> and <NAME>
#
# This released have been possible with this notebook : https://github.com/dipanjanS/hands-on-transfer-learning-with-python
#Requierements
import warnings
from keras.optimizers import *
import pandas as pd
from numpy.random import rand
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from pythonTools import importData, plot_batch, load_batch
import matplotlib.pyplot as plt
from keras.models import Model
from keras.layers import Dense, GlobalAveragePooling2D, BatchNormalization, Dropout
from keras.preprocessing.image import ImageDataGenerator
from keras.preprocessing.image import img_to_array, load_img
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot
# ---------------------------------------------------------------------------------------------------------------
# DATALOGGER IN FILE TO EXPORT THE RESULTS
# ---------------------------------------------------------------------------------------------------------------
import sys
sys.stdout = open('datalogger.txt', 'w')
# ---------------------------------------------------------------------------------------------------------------
# PARAMETERS
# ---------------------------------------------------------------------------------------------------------------
BATCH_SIZE = 32
LEARNING_RATE = 0.0001
INPUT_SHAPE = (192, 192, 3)
EPOCHS = 2
warnings.filterwarnings('ignore')
pd.options.display.max_colwidth = 600
params = {'legend.fontsize': 'x-large',
'figure.figsize': (15, 5),
'axes.labelsize': 'x-large',
'axes.titlesize': 'x-large',
'xtick.labelsize': 'x-large',
'ytick.labelsize': 'x-large'}
# ---------------------------------------------------------------------------------------------------------------
# LOAD DATA
# ---------------------------------------------------------------------------------------------------------------
print('Load data...')
feature_values, label_names, dataset_df = importData('rawKeras')
target_size = 192
feature_values = np.array([img_to_array(load_img(img, target_size=(target_size, target_size)))
for img in dataset_df['image_path'].values.tolist()]).astype('float32')
feature_nb = feature_values.shape[1]
instance_nb = feature_values.shape[0]
# LABEL NAMES
labelNames_unique = label_names.unique()
# CLASSES NUMBER
label_nb = labelNames_unique.shape[0]
# INDICES
le = preprocessing.LabelEncoder()
le.fit(labelNames_unique)
labelIndices_unique = le.transform(labelNames_unique)
labelIndices = le.transform(label_names)
# ONE-HOT-ENCODING
labels_ohe_names = pd.get_dummies(label_names.reset_index(drop=True), sparse=True)
labels_ohe = np.asarray(labels_ohe_names)
# ---------------------------------------------------------------------------------------------------------------
# Seafloor dataset exploratory analysis
print('------------------------------')
print('Seafloor Dataset Summary ')
print("This model will be learned : ", labelNames_unique)
print('Instance Nb:', instance_nb)
print('Feature Nb:', feature_nb)
print('Label Nb:', label_nb)
# ---------------------------------------------------------------------------------------------------------------
# VISUALIZE A SAMPLE SET
# ---------------------------------------------------------------------------------------------------------------
batch_df = load_batch(dataset_df, batch_size=25)
plot_batch(batch_df, grid_width=5, grid_height=5, im_scale_x=128, im_scale_y=128)
plt.show()
# ---------------------------------------------------------------------------------------------------------------
# PREPARE TRAIN / TEST / VALIDATION DATASET
# ---------------------------------------------------------------------------------------------------------------
x_train, x_val, y_train, y_val = train_test_split(feature_values,
label_names,
test_size=0.12,
stratify=np.array(label_names),
random_state=42)
x_train, x_test, y_train, y_test = train_test_split(x_train,
y_train,
test_size=0.12,
stratify=np.array(y_train),
random_state=42)
# ---------------------------------------------------------------------------------------------------------------
# ONE-HOT-ENCODING
# ---------------------------------------------------------------------------------------------------------------
y_train_ohe = pd.get_dummies(y_train.reset_index(drop=True)).as_matrix()
y_val_ohe = pd.get_dummies(y_val.reset_index(drop=True)).as_matrix()
y_test_ohe = pd.get_dummies(y_test.reset_index(drop=True)).as_matrix()
# ---------------------------------------------------------------------------------------------------------------
# TRAIN GENERATOR
# ---------------------------------------------------------------------------------------------------------------
train_datagen = ImageDataGenerator(rescale=1. / 255,
rotation_range=30,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip='true')
train_generator = train_datagen.flow(x_train, y_train_ohe, shuffle=False, batch_size=BATCH_SIZE, seed=1)
# ---------------------------------------------------------------------------------------------------------------
# VALIDATION GENERATOR
# ---------------------------------------------------------------------------------------------------------------
val_datagen = ImageDataGenerator(rescale=1. / 255)
val_generator = train_datagen.flow(x_val, y_val_ohe, shuffle=False, batch_size=BATCH_SIZE, seed=1)
# ---------------------------------------------------------------------------------------------------------------
# IMPORT AND COMPILE THE DEEP LEARNING CLASSIFIER
# ---------------------------------------------------------------------------------------------------------------
# GET THE MODEL ARCHITECTURE
print("This software can be used with this models : \n"
"- VGG16 \n"
"- InceptionV3 \n"
"- MobileNetV2 \n"
"- DenseNet201 \n"
"- MyCNN \n"
"You can also customize your model with the command 'My' like 'MyVGG16', 'MyInceptionV3'... \n")
model_list = ['VGG16', 'InceptionV3', 'MobileNetV2', 'MyCNN', 'MyVGG16','InceptionV3', 'DenseNet201']
for model_define in model_list:
net = model_define
if net == 'VGG16' or net == 'MyVGG16':
from keras.applications import vgg16 as vgg
base_model = vgg.VGG16(weights='imagenet',
include_top=False,
input_shape=INPUT_SHAPE)
elif net == 'ResNet50':
from keras.applications import ResNet50V2
base_model = ResNet50V2(weights='imagenet',
include_top=False,
input_shape=INPUT_SHAPE)
elif net == 'InceptionV3':
from keras.applications import inception_v3 as inception
base_model = inception.InceptionV3(weights='imagenet',
include_top=False,
input_shape=INPUT_SHAPE)
elif net == 'MobileNetV2':
from keras.applications import mobilenet_v2 as mobilenet
base_model = mobilenet.MobileNetV2(weights='imagenet',
include_top=False,
input_shape=INPUT_SHAPE)
elif net == 'DenseNet201':
from keras.applications import densenet
base_model = densenet.DenseNet201(weights='imagenet',
include_top=False,
input_shape=INPUT_SHAPE)
elif net == 'MyCNN':
# CNN model with image augmentation and regularization
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from keras.models import Sequential
from keras.optimizers import RMSprop
model = Sequential()
# Convolution and pooling layers
model.add(Conv2D(16, kernel_size=(3, 3), activation='relu',
input_shape=INPUT_SHAPE))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.2))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1024, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(2048, activation='relu'))
model.add(Dense(2048, activation='relu'))
model.add(Dense(label_nb, activation='softmax'))
else:
exit()
# ---------------------------------------------------------------------------------------------------------------
# COMPUTE THE EXECUTION TIME
# ---------------------------------------------------------------------------------------------------------------
import timeit
start = timeit.default_timer()
# ---------------------------------------------------------------------------------------------------------------
# GENERATE AND COMPILE THE MODEL ARCHITECTURE TO RETURN 6 CLASSES
# ---------------------------------------------------------------------------------------------------------------
if net == 'MyCNN':
print("Generate your Neural Networks!")
model.compile(Adam(lr=LEARNING_RATE), loss='categorical_crossentropy', metrics=['accuracy'])
model.name = net
model.summary()
elif net[:2] == 'My':
print("Personnalisation of your ", net, " architecture")
from keras.layers import GlobalAveragePooling2D, Dense
out = GlobalAveragePooling2D()(base_model.output)
out = Dense(512, trainable=True, activation='relu')(out)
out = Dense(1024, trainable=True, activation='relu')(out)
out = Dense(2048, trainable=True, activation='relu')(out)
out = Dense(2048, trainable=True, activation='relu')(out)
out = Dense(6, trainable=True, activation='sigmoid')(out)
out = BatchNormalization()(out)
predictions = Dense(label_nb, activation='softmax')(out)
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(Adam(lr=LEARNING_RATE), loss='categorical_crossentropy', metrics=['accuracy'])
model.name = net
model.summary()
else :
print("Classic ", net, " architecture")
# CHANGE ONLY THE LAST LAYER
from keras.layers import GlobalAveragePooling2D, Dense
out = GlobalAveragePooling2D()(base_model.output)
out = BatchNormalization()(out)
predictions = Dense(label_nb, activation='softmax')(out)
model = Model(inputs=base_model.input, outputs=predictions)
model.compile(Adam(lr=LEARNING_RATE), loss='categorical_crossentropy', metrics=['accuracy'])
model.name = net
model.summary()
# ---------------------------------------------------------------------------------------------------------------
# SHOW THE SVG OF THE MODEL
# ---------------------------------------------------------------------------------------------------------------
try:
SVG(model_to_dot(model, show_shapes=True,
show_layer_names=True, rankdir='TB').create(prog='dot', format='svg'))
except:
print("Please check your installation of Graphviz")
# ---------------------------------------------------------------------------------------------------------------
# COMPUTE MODEL PERFORMANCE
# ---------------------------------------------------------------------------------------------------------------
train_steps_per_epoch = x_train.shape[0] // BATCH_SIZE
val_steps_per_epoch = x_val.shape[0] // BATCH_SIZE
history = model.fit_generator(train_generator,
steps_per_epoch=train_steps_per_epoch,
validation_data=val_generator,
validation_steps=val_steps_per_epoch,
epochs=EPOCHS,
verbose=1)
stop = timeit.default_timer()
print('Time for ', net, " : ", stop - start)
# ---------------------------------------------------------------------------------------------------------------
# PLOT MODEL PERFORMANCE
# ---------------------------------------------------------------------------------------------------------------
f, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))
t = f.suptitle(net, fontsize=15)
f.subplots_adjust(top=0.85, wspace=0.3)
epochs = list(range(1, EPOCHS + 1))
ax1.plot(epochs, history.history['accuracy'], label='Train Accuracy')
ax1.plot(epochs, history.history['val_accuracy'], label='Validation Accuracy')
ax1.set_xticks(epochs)
ax1.set_ylabel('Accuracy Value')
ax1.set_xlabel('Epoch')
ax1.set_title('Accuracy')
l1 = ax1.legend(loc="best")
ax2.plot(epochs, history.history['loss'], label='Train Loss')
ax2.plot(epochs, history.history['val_loss'], label='Validation Loss')
ax2.set_xticks(epochs)
ax2.set_ylabel('Loss Value')
ax2.set_xlabel('Epoch')
ax2.set_title('Loss')
l2 = ax2.legend(loc="best")
plt.show()
# ---------------------------------------------------------------------------------------------------------------
# EXPORT THE MODEL
# ---------------------------------------------------------------------------------------------------------------
import os
model.save('SEABED_CLASSIFICATION.hdf5')
print("The size of your ML Model : ", os.path.getsize('SEABED_CLASSIFICATION.hdf5'))
# ---------------------------------------------------------------------------------------------------------------
# COMPUTE MODEL PERFORMANCE WITH THE TEST VALUES
# ---------------------------------------------------------------------------------------------------------------
# scaling test features
x_test /= 255.
test_predictions = model.predict(x_test)
predictions = pd.DataFrame(test_predictions, columns=labels_ohe_names.columns)
predictions.head()
test_labels = list(y_test)
predictions = list(predictions.idxmax(axis=1))
# ---------------------------------------------------------------------------------------------------------------
# PRINT MODEL PERFORMANCE
# ---------------------------------------------------------------------------------------------------------------
import model_evaluation_utils as meu
meu.get_metrics(true_labels=test_labels,
predicted_labels=predictions)
meu.display_classification_report(true_labels=test_labels,
predicted_labels=predictions,
classes=list(labels_ohe_names.columns))
meu.display_confusion_matrix(true_labels=test_labels,
predicted_labels=predictions,
classes=list(labels_ohe_names.columns))
# ---------------------------------------------------------------------------------------------------------------
# PLOT MODEL PERFORMANCE
# ---------------------------------------------------------------------------------------------------------------
grid_width = 5
grid_height = 5
f, ax = plt.subplots(grid_width, grid_height)
f.set_size_inches(15, 15)
batch_size = BATCH_SIZE
dataset = x_test
label_dict = dict(enumerate(labels_ohe_names.columns.values))
model_input_shape = (1,)+model.get_input_shape_at(0)[1:]
random_batch_indx = np.random.permutation(np.arange(0,len(dataset)))[:batch_size]
img_idx = 0
for i in range(0, grid_width):
for j in range(0, grid_height):
actual_label = np.array(y_test)[random_batch_indx[img_idx]]
prediction = model.predict(dataset[random_batch_indx[img_idx]].reshape(model_input_shape))[0]
label_idx = np.argmax(prediction)
predicted_label = label_dict.get(label_idx)
conf = round(prediction[label_idx], 2)
ax[i][j].axis('off')
ax[i][j].set_title('Actual: '+actual_label+'\nPred: '+predicted_label + '\nConf: ' +str(conf))
ax[i][j].imshow(dataset[random_batch_indx[img_idx]])
img_idx += 1
plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0.5, hspace=0.55)
plt.show()<file_sep># COURSERA - MACHINE LEARNING
Le répertoire intégre les solutions pour le cours de Machine Learning de <NAME> sur le MOOC Coursera.
<file_sep>
#%% package
import numpy as np
import matplotlib.pyplot as plt
from loadImages import loadImages
from selectFeatureVectors import selectFeatureVectors
from displayFeatures2d import displayFeatures2d
from displayFeatures3d import displayFeatures3d
#%% def preprocessing
def preprocessing():
# ------------------------------------------------
# YOUR CODE HERE
img73, img87 = loadImages()
featLearn = 0
# Redimensionnement
img73 = img73[120:820, 180:800, :]
img87 = img87[120:820, 180:800, :]
# Affichage des images
plt.figure(1);
plt.imshow(img73);
plt.show()
plt.figure(2);
plt.imshow(img87);
plt.show()
# Echantillonnage
featLearn, nbPix, nbFeat = selectFeatureVectors(img73, 500)
print('nb pix:', nbPix, '\r')
print('nb feat:', nbFeat, '\r')
# print('featLearn:', featLearn, '\r')
# Affichage 2D et 3D
displayFeatures2d(featLearn)
displayFeatures3d(featLearn)
# ------------------------------------------------
# ------------------------------------------------
#%% sortie
return featLearn,img73,img87
<file_sep>#%% package
import numpy as np
from sklearn.cluster import KMeans
#%% def unsupervisedClassifying
def unsupervisedClassifying(model, feat):
''' classement/prédiction à partir d'un modèle de classement non supervisé
feat est la matrice du jeu de données à classer
label est la classe prédite
'''
# A ce stade, vous avez choisi les hyper-paramètres de vos méthodes de machine learning
#et obtenu le modèle de classement, nous pouvons alors utiliser les données d’apprentissage pour
#classifier l’ensemble des deux images. Il faut calculer les descripteurs sur toute l’image (mise sous
#la forme d’une matrice) puis utiliser le modèle de classement issu de l’apprentissage du k-means).
#Compléter les scripts aralsea main.py et unsupervisedClassifying.py.
# ------------------------------------------------
# YOUR CODE HERE
label=model.predict(feat)
# ------------------------------------------------
# ------------------------------------------------
# sortie
return label
| f3568bcc635f02f8335701811040d31be277d836 | [
"Markdown",
"Python"
] | 20 | Python | TonyCalvez/INTELLIGENCE_ARTIFICIELLE | 21b749ca84784d9e219008db99edf56d5f4e49e9 | 13e07ae82e49000dd4070695318d23426998511c |
refs/heads/main | <file_sep>#!/bin/bash
echo "build this package isolated"
cd
cd catkin_ws
catkin_make_isolated --pkg autonomus_transport_industrial_system<file_sep>//
// Created by robomaster on 2020/8/17.
//
#include "../include/tag_follower.h"
#include <ros/ros.h>
#include <pluginlib/class_list_macros.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "tag_follower");
ros::NodeHandle nh;
AutonomusTransportIndustrialSystem::TagFollower tg(nh);
ros::Timer tag_timer = nh.createTimer(ros::Duration(0.1), &AutonomusTransportIndustrialSystem::TagFollower::tagMakePlan, &tg);
ros::spin();
return EXIT_SUCCESS;
}<file_sep>/*
* @Author: <NAME>
* @Date: 2020-04-10 08:57:47
* @LastEditTime: 2020-08-17 19:57:24
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: /autonomus_transport_industrial_system/src/test.cpp
*/
#include <ros/ros.h>
#include <tf/transform_broadcaster.h>
#include <tf/transform_listener.h>
#include <tf/message_filter.h>
#include "../include/utility.h"
#include "../include/PoseDrawer.h"
#include "../include/PointCloud.h"
#include "../include/NavigationGoal.h"
#include "../include/ExtractionDisplay.h"
int main(int argc, char **argv)
{
ros::init(argc, argv, "test");
ros::NodeHandle nh;
AutonomusTransportIndustrialSystem::ExtractionDisplay exd(nh);
AutonomusTransportIndustrialSystem::PoseDrawer pd(nh);
AutonomusTransportIndustrialSystem::NavigationGoal ng(nh);
ros::Rate rate(0.5);
while (ros::ok())
{
// 广播可视化提取点
exd.extraction_pub.publish(exd.extraction_array);
ros::spinOnce();
rate.sleep();
}
return EXIT_SUCCESS;
}
<file_sep>/*
* @Author: <NAME>
* @Date: 2020-08-17 19:17:42
* @LastEditTime: 2020-08-17 19:37:24
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: /autonomus_transport_industrial_system/include/tag_follower.h
*/
#ifndef TAG_FOLLOWER_
#define TAG_FOLLOWER_
#include <iostream>
#include <string>
#include <ros/ros.h>
#include <tf/tf.h>
#include <tf/transform_listener.h>
#include <nav_msgs/Odometry.h>
#include "tf/transform_datatypes.h"
#include <ros/service_client.h>
#include <opencv2/opencv.hpp>
#include <tf/transform_broadcaster.h>
#include "autonomus_transport_industrial_system/tagDetected.h"
#include "autonomus_transport_industrial_system/netComTag.h"
#include "utility.h"
namespace AutonomusTransportIndustrialSystem
{
class TagFollower
{
private:
ros::NodeHandle nh;
tf::StampedTransform tag_transform;
tf::TransformListener tag_listener;
// 如果发现tag,发送service给navigationGoal
ros::ServiceClient abort_move_base;
ros::ServiceServer tag_service;
// 检测到为true, 没有检测到为false
enum DetectStatus
{
DETECTED = true,
UNDETECTED = false
};
enum DetectLogic
{
ALWAYS_NO_DETECTED,
TRANSITION,
ALWAYS_DETECTED
};
autonomus_transport_industrial_system::tagDetected is_tag_detected;
autonomus_transport_industrial_system::tagDetected is_tag_detected_last;
const int UN_INITIALIZE = -1;
const int IS_DONE = -2;
// -1: 未初始化;0~2:目标tag
int tag_num = UN_INITIALIZE;
DetectLogic check_transition_status;
tf::TransformBroadcaster broadcaster;
bool is_cancel_move_base = false;
/**
* tag 的ros service回调函数:由netWorkCom发送
* @param req
* @param res
* @return
*/
bool tagServiceCallBack(autonomus_transport_industrial_system::netComTag::Request & req, autonomus_transport_industrial_system::netComTag::Response& res);
/**
* 每次监听到新的导航点都重置一次tag的service
*/
void initialize();
/**
* 检查tag检测的跳变状态
* @param is_tag_detected 本次检测结果
* @param is_tag_detected_last 上次检测结果
* @return
*/
int checkTransition(autonomus_transport_industrial_system::tagDetected is_tag_detected,
autonomus_transport_industrial_system::tagDetected is_tag_detected_last);
void genTraj(const cv::Point2d& p_0, double w_0, const cv::Point2d& p_1, double w_1);
public:
TagFollower(ros::NodeHandle given_nh) : nh(given_nh)
{
// 此处采取Service向netComModule订阅目标信息,修改tf监听值
tag_service = nh.advertiseService("netComTag", &TagFollower::tagServiceCallBack, this);
// 此处采取Service向navigationGoal广播tag是否被识别
abort_move_base = nh.serviceClient<autonomus_transport_industrial_system::tagDetected>("is_tag_detected");
initialize();
check_transition_status = ALWAYS_NO_DETECTED;
}
~TagFollower() = default;
/**
* 最主要的函数:协调tag_follow的整个流程
* @param event 回调函数
*/
void tagMakePlan(const ros::TimerEvent& event);
};
void TagFollower::tagMakePlan(const ros::TimerEvent &event)
{
if (tag_num == UN_INITIALIZE)
{
ROS_INFO_STREAM("tag num is not initialize.");
return;
}
else if (tag_num == IS_DONE)
{
ROS_INFO_STREAM("The mission is finished.");
return;
}
else
{
// 读取tag的tf
try
{
tag_listener.lookupTransform("/camera_front", "/tag_"+std::to_string(tag_num), ros::Time(0), tag_transform);
double roll, pitch, yaw;
tf::Matrix3x3(tag_transform.getRotation()).getEulerYPR(yaw, pitch, roll);
ROS_INFO_STREAM("Actual omega = " << roll << ", angle = " << 180 * roll / M_PI);
is_tag_detected.request.is_tag_detected = DETECTED;
// 如果发现tag且状态发生跳变,则发送service以中断move_base导航,同时生成轨迹
if (checkTransition(is_tag_detected, is_tag_detected_last) != ALWAYS_NO_DETECTED && GetEuclideanDistance(tag_transform) <= 2.0)
{
if (is_cancel_move_base == true)
{
abort_move_base.call(is_tag_detected);
is_cancel_move_base = false;
}
// 不断重新生成轨迹
genTraj(cv::Point2d(0,0), 0,
cv::Point2d(tag_transform.getRotation().x(), tag_transform.getRotation().y()), roll);
}
is_tag_detected_last.request.is_tag_detected = is_tag_detected.request.is_tag_detected;
if (GetEuclideanDistance(tag_transform) <= 0.2)
{
tag_num = IS_DONE;
}
}
catch (tf::TransformException &ex)
{
ROS_WARN_STREAM("tf lookup is not exist : " << ex.what());
is_tag_detected.request.is_tag_detected = UNDETECTED;
return;
}
}
}
bool TagFollower::tagServiceCallBack(autonomus_transport_industrial_system::netComTag::Request &req,
autonomus_transport_industrial_system::netComTag::Response &res)
{
tag_num = req.tag_num;
ROS_INFO_STREAM("TagCB: tag " << tag_num << " detected.");
initialize();
res.status = true;
return true;
}
void TagFollower::initialize()
{
is_tag_detected.request.is_tag_detected = UNDETECTED;
is_tag_detected_last.request.is_tag_detected = UNDETECTED;
is_cancel_move_base = true;
// 初始化service
abort_move_base.call(is_tag_detected);
}
int TagFollower::checkTransition(autonomus_transport_industrial_system::tagDetected is_tag_detected,
autonomus_transport_industrial_system::tagDetected is_tag_detected_last)
{
if (is_tag_detected.request.is_tag_detected == DETECTED && is_tag_detected_last.request.is_tag_detected == UNDETECTED)
{
check_transition_status = TRANSITION;
return check_transition_status;
}
else if (is_tag_detected.request.is_tag_detected == DETECTED && is_tag_detected_last.request.is_tag_detected == DETECTED)
{
check_transition_status = ALWAYS_DETECTED;
return check_transition_status;
}
else
{
check_transition_status = ALWAYS_NO_DETECTED;
return check_transition_status;
}
}
void TagFollower::genTraj(const cv::Point2d& p_0, double w_0, const cv::Point2d& p_1, double w_1)
{
/***** 求出交点(第三个控制点) ****/
// y = a*x + b, where y = 0
double a = tan(w_1 / M_PI * 180);
double b = p_1.y - a * p_1.x;
cv::Point2d p_2((-b / a), 0);
ROS_INFO_STREAM("Intersection point : " << p_2);
broadcaster.sendTransform(tf::StampedTransform(tf::Transform(tf::Quaternion(0,0,0,1), tf::Vector3(p_2.x, p_2.y, 0)), ros::Time::now(), "base_link", "p_2"));
}
}
#endif<file_sep>//
// Created by lifuguan on 2020/8/23.
//
#ifndef ROBOT_PLANNER_H
#define ROBOT_PLANNER_H
#include <math.h>
#include <ros/ros.h>
#include <costmap_2d/costmap_2d_ros.h>
#include <costmap_2d/costmap_2d.h>
#include <nav_core/base_global_planner.h>
#include <geometry_msgs/PoseStamped.h>
#include <angles/angles.h>
#include <base_local_planner/world_model.h>
#include <base_local_planner/costmap_model.h>
#include <nav_msgs/Path.h>
#include <geometry_msgs/PoseWithCovarianceStamped.h>
#include <visualization_msgs/Marker.h>
#include <tf/tf.h>
namespace AutonomusTransportIndustrialSystem
{
/**
* 情人节走心形
*/
class ValentineRobotPlanner
{
public:
/**
* 构造函数
* @param given_nh
*/
ValentineRobotPlanner(ros::NodeHandle given_nh);
~ValentineRobotPlanner() = default;
private:
ros::NodeHandle nh;
nav_msgs::Path global_path_;
ros::Publisher path_pub_;
ros::Timer path_timer_;
// ???
std::string global_frame_;
int dt_ = 3;
double theta_ = 0;
double delta_theta_;
const int step_time_tot_ = 2000;
int step_time_ = 0;
double p_x_, p_y_;
/**
* 定时回调函数:循环广播路径
* @param event
*/
void showGlobalPathCallBack(const ros::TimerEvent& event);
};
ValentineRobotPlanner::ValentineRobotPlanner(ros::NodeHandle given_nh):nh(given_nh)
{
path_pub_ = nh.advertise<nav_msgs::Path>("valentine_path", 1, true);
delta_theta_ = 2 * M_PI / step_time_;
path_timer_ = nh.createTimer(ros::Duration(0.02), &ValentineRobotPlanner::showGlobalPathCallBack, this);
// ???
path_timer_.stop();
// ???
global_path_.header.frame_id = "map";
}
void ValentineRobotPlanner::showGlobalPathCallBack(const ros::TimerEvent &event)
{
if (step_time_ == step_time_tot_)
{
p_x_ = 0; p_y_ = 0; theta_ = 0;
step_time_ = 0;
}
else
{
p_x_ = cos(theta_)*(1+cos(theta_));
p_y_ = sin(theta_)*(1+cos(theta_));
theta_ += delta_theta_;
step_time_ += 1;
}
}
}
#endif //ROBOT_PLANNER_H
<file_sep>/*
* @Author: lifuguan
* @Date: 2020-02-21 17:11:17
* @LastEditTime: 2020-05-15 00:23:31
* @LastEditors: Please set LastEditors
* @Description: 功能性头文件,包含各种基本函数
* @FilePath: /autonomus_transport_industrial_system/src/utility.h
*/
#ifndef UTILITY_H
#define UTILITY_H
#include <tf/tf.h>
#include <tf/transform_listener.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Quaternion.h>
namespace AutonomusTransportIndustrialSystem
{
struct hash_pair
{
template <class T1, class T2>
size_t operator()(const std::pair<T1, T2>& p) const
{
auto hash1 = std::hash<T1>{}(p.first);
auto hash2 = std::hash<T2>{}(p.second);
return hash1 ^ hash2;
}
// 这个没啥用
friend std::ostream& operator<<(std::ostream &out, const std::pair<double, double>& p)
{
out << "("<< p.first << ", " << p.second << ")";
return out;
}
};
class Utility
{
public:
/**
* @description: 计算两点之间距离
* @param pose_1 第一个点
* @param pose_2 第二个点
* @return: double型变量,返回欧几里得距离
*/
double GetEuclideanDistance(const geometry_msgs::PoseStamped &pose_1, const geometry_msgs::PoseStamped &pose_2);
/**
* @description: 计算两点之间距离(友元函数)
* @param transform 两个tf之间的静态变化呢
* @return: double型变量,返回欧几里得距离
*/
friend double GetEuclideanDistance(tf::StampedTransform transform);
/**
* @description: 计算两点之间距离
* @param transform 两个tf之间的静态变化呢
* @return: double型变量,返回欧几里得距离
*/
double GetEuclideanDistance(tf::StampedTransform transform);
/**
* @description: 将四元数转换成欧拉角
* @param orientation 四元数
* @note: roll代表绕x轴旋转,pitch代表绕y轴旋转,yaw代表绕z轴旋转
* @return: 返回一个double型数组 RPY[rall, pitch, yaw, \t]
*/
double *GetYawFromOrientation(const geometry_msgs::Quaternion &orientation);
private:
};
double AutonomusTransportIndustrialSystem::Utility::GetEuclideanDistance(
const geometry_msgs::PoseStamped &pose_1, const geometry_msgs::PoseStamped &pose_2)
{
return hypot(pose_1.pose.position.x - pose_2.pose.position.x, pose_1.pose.position.y - pose_2.pose.position.y);
}
double AutonomusTransportIndustrialSystem::Utility::GetEuclideanDistance(tf::StampedTransform transform)
{
return hypot(transform.getOrigin().getX(), transform.getOrigin().getY());
}
double *AutonomusTransportIndustrialSystem::Utility::GetYawFromOrientation(
const geometry_msgs::Quaternion &orientation)
{
tf::Quaternion q;
tf::quaternionMsgToTF(orientation, q);
tf::Matrix3x3 m(q);
static double RPY[4];
m.getRPY(RPY[0], RPY[1], RPY[2]);
return RPY;
}
double GetEuclideanDistance(tf::StampedTransform transform)
{
return hypot(transform.getOrigin().getX(), transform.getOrigin().getY());
}
} // namespace AutonomusTransportIndustrialSystem
#endif //PROJECT_UTILITY_H<file_sep>#!/usr/bin/env python
'''
Author: lifuguan
Date: 2020-08-04 16:07:21
LastEditTime: 2020-08-09 17:42:00
LastEditors: Please set LastEditors
Description: Aimed to draw the relative position between frame /odom and frame /map
FilePath: /autonomus_transport_industrial_system/scripts/drawError.py
'''
import rospy
from matplotlib import pyplot as plt
from nav_msgs.msg import Odometry
import numpy as np
import time
import math
class DrawTraj(object):
odom_time, cb_time = 0, 0
x_odom = []
y_odom = []
x_rf2o = []
y_rf2o = []
def __init__(self):
pass
def isCBAlive(self):
return False if self.cb_time - self.odom_time > 2 else True
def odomCallBack(self, data):
self.x_odom.append(data.pose.pose.position.x)
self.y_odom.append(data.pose.pose.position.y)
def rf2oCallBack(self, data):
self.x_rf2o.append(data.pose.pose.position.x)
self.y_rf2o.append(data.pose.pose.position.y)
self.odom_time = time.time()
# check if data is not received. If so, exit and plot the figure
def cbMonitor(self, plt):
self.cb_time = time.time()
if not self.isCBAlive():
rospy.logwarn("No odom data received!Exit!")
return True
else:
return False
if __name__ == "__main__":
rospy.init_node("DrawingTraj")
de = DrawTraj()
# gazebo's odom, without nosie
rospy.Subscriber("odom", Odometry, de.odomCallBack)
# rf2o_odometry's odom
rospy.Subscriber("odom_rf2o", Odometry, de.rf2oCallBack)
rospy.sleep(2)
rospy.Timer(rospy.Duration(3), de.cbMonitor)
while not rospy.is_shutdown():
if de.cbMonitor(plt) == True:
break
ax1 = plt.subplot(1, 2, 1)
plt.title("odom display")
plt.plot(de.x_odom, de.y_odom, color="b", label="/imu_traj")
plt.plot(de.x_rf2o, de.y_rf2o, color="r", label="/rf2o_traj")
plt.legend()
# down-sampling for gazebo's /odom
rate = len(de.y_odom) / len(de.y_rf2o)
print rate, len(de.x_rf2o)
ax2 = plt.subplot(1, 2, 2)
errs = []
for i in range(len(de.x_rf2o)):
print i
errs.append(
math.hypot(de.x_odom[i * rate] - de.x_rf2o[i],
de.y_odom[i * rate] - de.y_rf2o[i]))
t_ = list(range(0, len(errs)))
print len(errs)
plt.plot(t_,
errs,
color="g",
linewidth=1,
linestyle=':',
label='Only rf2o errors')
plt.legend()
plt.show()
<file_sep><!--
* @Author: <NAME>
* @Date: 2020-07-20 18:07:28
* @LastEditTime: 2020-07-20 18:10:31
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: /autonomus_transport_industrial_system/note.md
-->
# 个人笔记
## 关于AMCL的注意事项
- Navigation模块只从*amcl_pose*获得瞬时速度并参与后续计算
- 从*tf*处获得odom和漂移
- 所以,*amcl_pose*并不需要反馈到前面的位姿处 | 2b25545898da0a8fc339a6d0a947d2fc6aed7afe | [
"Markdown",
"Python",
"C++",
"Shell"
] | 8 | Shell | Albert-Lucif4/pepper-ros-slam-autotransport | 9a8c605076d69242e485787aeca2c317e73fb21a | 0a8ee72b7ddf75178849eacbaca9f8aa6910f5d1 |
refs/heads/master | <repo_name>hu9o/NewgroundsAPIUnity<file_sep>/Assets/Newgrounds/Code/SendString.cs
#region References
using System.Collections;
using System.Text;
#endregion
namespace Newgrounds
{
public class SendString
{
#region Public Fields
public string m_contents = "";
#endregion
#region Constructor
public SendString()
{
}
#endregion
#region Public Functions
public SendString(string commandName)
{
AddCommand ("command_id", commandName);
}
public void AddCommand(string command, string argument)
{
if (m_contents != "")
{
m_contents += "&";
}
m_contents += command + "=" + argument;
}
public void AddCommand(string command, int argument)
{
AddCommand (command, argument.ToString());
}
public byte[] ByteArray()
{
API.m_output += "Sending data to server: " + m_contents + '\n';
return Encoding.UTF8.GetBytes(m_contents.ToCharArray ());
}
#endregion
}
}
| 3f26987f1c7f44ae22223eb934dcda4484086708 | [
"C#"
] | 1 | C# | hu9o/NewgroundsAPIUnity | 230a11fe292351fbed05d28e074f036e287809fe | 6c9385c40e35ff60fc15348278f87e54c2099e50 |
refs/heads/master | <repo_name>ash-ish/AlgorithmsImplementation<file_sep>/algos/src/main/java/s4m3d5/Solution.java
/*
* s4h3f5
90
*
*
* */
package s4m3d5;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String word = input.nextLine();
int indexOfRequiredCharacter = input.nextInt();
int length = word.length();
int maxRepetitionLength = 0;
int totalLength = 0,count = -1;//count is initialized with -1 for resetting count using i
for(int i = 0; i < length; i++) {
char c = word.charAt(i);
if(c >= 49 && c <= 57) {
count = i - count -1;
int temp = Integer.parseInt(String.valueOf(c));
maxRepetitionLength = totalLength + count;
totalLength = (totalLength + count )*temp;
}
}
int value = indexOfRequiredCharacter % maxRepetitionLength;
System.out.println(totalLength);
System.out.println(maxRepetitionLength);
input.close();
}
}
<file_sep>/algos/src/main/java/com/epam/algos/RabinKarp.java
package com.epam.algos;
/*
* Rabin-Karp Algorithm
*
* input:
* ccaccbdadba
* dba
*
* output:
* true
*/
import java.util.HashMap;
import java.util.Scanner;
public class RabinKarp {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(isInputPresent(input.next(), input.next()));
input.close();
}
private static boolean isInputPresent(String paragraph, String word) {
boolean result = false;
long hashCode = getHastCode(word);
int paragraphLength = paragraph.length();
int wordLength = word.length();
int i = 0, j = 0;
boolean firstIterationOfParagraph = true;
int number = 0;
while (i < paragraphLength) {
int count = 0;
int presentValue = 0;
int tenPower = wordLength - 1;
j = i;
if (firstIterationOfParagraph) {
while (count < wordLength) {
number += alphabetNumber(paragraph.charAt(j)) * Math.pow(10, tenPower);
tenPower--;
j++;
i++;
count++;
}
i -= 1;
firstIterationOfParagraph = false;
} else {
int previousIntitialValue = (int) (alphabetNumber(paragraph.charAt(i - wordLength))
* Math.pow(10, wordLength - 1));
presentValue = alphabetNumber(paragraph.charAt(i));
number = ((number - previousIntitialValue) * 10) + presentValue;
}
if (number == hashCode) {
result = true;
break;
}
i++;
}
return result;
}
private static long getHastCode(String word) {
int length = word.length();
HashMap<Character, Integer> characterToNumber = new HashMap<Character, Integer>();
for (int i = 97, j = 1; i <= 122; i++, j++) {
char c = (char) i;
characterToNumber.put(c, j);
}
int number = 0;
for (int i = 0; i < length; i++) {
number += characterToNumber.get(word.charAt(i)) * Math.pow(10, length - i - 1);
}
return number;
}
private static int alphabetNumber(char alphabet) {
HashMap<Character, Integer> characterToNumber = new HashMap<Character, Integer>();
for (int i = 97, j = 1; i <= 122; i++, j++) {
char c = (char) i;
characterToNumber.put(c, j);
}
return characterToNumber.get(alphabet);
}
}
<file_sep>/algos/src/main/java/advancedhammingdistance/hammingdistanceofallpossiblenumbers.java
package advancedhammingdistance;
public class hammingdistanceofallpossiblenumbers {
public static void main(String[] args) {
int[] a = {4, 6};
System.out.println( hammingDistance(a));
}
public static int hammingDistance(int[] A) {
// int l = A.length;
//
// for(int i=0;i<l;i++){
// StringBuilder sb = new StringBuilder();
// int binary = A[i];
// while(binary > 0){
// sb.append(binary%2);
// binary /= 2;
// }
//
// A[i] = Integer.parseInt(sb.reverse().toString());
// }
//
// for(int i : A)
// System.out.println(i);
int parity = A[0] ^ A[1];
System.out.println(parity);
System.out.println();
int count = 0;
while(parity > 0) {
count += (parity & 1);
parity >>= 1;
}
return count;
// for(int i=0;i<l;i++){
// for(int j=0;j<l;j++){
//
// }
// }
//
// System.out.println();
// return l;
}
}
<file_sep>/algos/src/main/java/binarysearch/practice.java
package binarysearch;
import java.util.Scanner;
public class practice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int []arr = new int[n];
for(int i=0;i<n;i++)
arr[i] = input.nextInt();
int target = input.nextInt();
System.out.println(binarySearch(arr,n,target));
input.close();
}
public static int binarySearch(int arr[],int n, int target) {
int start = 0, end = n-1;
while(start <= end) {
int mid = (start + end)/2;
if(arr[mid] == target)
return 1;
else if(arr[mid] < target)
start = mid+1;
else
end = mid - 1;
}
return -1;
}
}
<file_sep>/algos/src/main/java/binarysearch/ArrayRotation.java
package binarysearch;
import java.util.Scanner;
public class ArrayRotation {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int []arr = new int[n];
for(int i=0;i<n;i++)
arr[i] = input.nextInt();
int numberOfRotation = binarySearch(arr,n);
System.out.println(numberOfRotation);
input.close();
}
public static int binarySearch(int arr[],int n) {
int start = 0, end = n-1;
while(start <= end) {
if(arr[start] < arr[end])
return start;
else {
int mid = (start + end)/2;
if(arr[mid] < arr[(mid+1)%n] && arr[mid] <arr[(mid-1)%n])
return mid;
else if(arr[mid] > arr[end])
start = mid + 1;
else if(arr[mid] < arr[end])
end = mid - 1;
}
}
return -1;
}
}
<file_sep>/algos/src/main/java/linkedlist/Main.java
package linkedlist;
public class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insert("A");
list.insert("B");
list.insert("C");
list.show();
System.out.println("-------------------------------");
list.insertAtStart("zz");
list.show();
System.out.println("-------------------------------");
list.insertAt(3,"teesraa");
list.show();
System.out.println("-------------------------------");
list.insertAt(1,"pehlaa");
list.show();
System.out.println("-------------------------------");
list.deleteAt(3);
list.show();
System.out.println("-------------------------------");
list.deleteAt(1);
list.show();
System.out.println("-------------------------------");
}
}
| 113a98a5a9e52663732bba8f7879ac852a62c608 | [
"Java"
] | 6 | Java | ash-ish/AlgorithmsImplementation | 83c9474d0d0b9196c0618d18110f40d04b63bf4a | 41a1b90ebfcc7b6d224eb6ad35b951f7b1b36d58 |
refs/heads/master | <repo_name>pablogiral/event-deliveroo<file_sep>/web/config/environment.js
export default {
apiPath: 'http://localhost:8081/'
};<file_sep>/web/src/index.js
import config from '../config/environment';
console.log(config);
var headers = new Headers();
var getOrders = {
method: 'GET',
headers: headers,
mode: 'no-cors',
cache: 'default'
};
fetch(config.apiPath + 'orders', getOrders)
.then(function(response) {
console.log(response);
return response.blob();
});
<file_sep>/slides/slides.md
## hola!

<!-- .element: class="fragment" data-fragment-index="1" -->
---
## ¿Quiénes somos?
----
#### <NAME>
-  https://github.com/ogomezso
-  https://www.linkedin.com/in/ogomezso
----
#### <NAME>
-  https://github.com/jocnunez
-  https://www.linkedin.com/in/josenunnez
----
- 
---
## ¿Qué vamos a hacer hoy?
---
 ¿Qué es DEVOPS?
----
1. Cultura DEVOPS
2. Herramientas Comunes
3. Ciclo de Vida de un Aplicación en esta cultura.
---
 DOCKER!!!
----
1. Contenedores
2. Docker 101
3. Docker Compose / Docker Swarm
----

---
# EVENT DELIVEROO
----

----

---
# Testing
----
* Unit Tests
* Integration Tests
* Acceptance Tests
---
# Tools
----
* bundlers
* Cross platform builders
* WPA
---
# Coding
----
* Frameworks
* Design Patterns
* Web Components
---
# Lets build a front for our App<file_sep>/README.md
## LEVANTAR APP MODO SWARM POR PRIMERA VEZ
1.- Al levantar nuestra applicacion por primera vez necesitaremos setear nuestra infraestrcutura, para no complicar demasiado la cosa (y de paso practicar lo haremos de la siguiente forma)
*Creamos las redes docker que usaremos:
````
$ docker network create --driver=bridge --subnet=192.168.2.0/24 --gateway=192.168.2.10 event-deliveroo-env-network
$ docker network create --driver=bridge --subnet=192.168.3.0/24 --gateway=192.168.3.10 event-deliveroo-app-network
````
* Arrancaremos nuestros contenedores de Infraestrcutura
````
$ cd environment
$ ./handle-containers startenv
````
Con esto tendremos en nuestro entorno local:
* Una red docker (con driver overlay) para nuestra infra.
* Un cluster de Kafka listo para recibir peticiones
* Una instancia de MongoDB que usaremos como persistencia de nuestros servicios
* Una consola de zipkin que nos permitira mantener la trazabilizad de las peticions a traves de nuestros servicios
* Un recolector de metricas (Prometheus) que nos permitirá conocer el estado de nuestros servicios en todo momento
* Una instancia de grafana con la que podremos construir dashboards con las metricas recogidas de Prometheus.
* **NOTA:** Para aprovisionar correctamente nuestra instancia de Mongo, deberemos correr en nuestro cliente favorito (https://robomongo.org/download) el siguiente comando:
```
db.createCollection( "orders", { capped: true, size: 100000 } )
```
2.- Debemos comprobar en que ip levantamos cada uno de nuestros servicios de infraestrucuctura, usando los comandos docker apropiados para ello:
````
$ docker network ls
$ docker network inspect env-stack_event-deliveroo-env-network
````
3.- Cambiar en los application.yml de los proyectos que lo requieran las referencias a la IP/puerto del servicio que lo requiera.
4.- Levantar nuestro ecosistema de aplicación, ejecutando el comando:
````
$ cd environment
$ ./handle-containers startapp
````
- Con este comando:
- Construiremos los artefactos de nuestros servicios pasando todos los test que tuvieramos configurados (UT, IT).
- Construiremos la imágenes docker de cada uno de nuestros servicios
- Levantaremos un nuevo stack de swarm con su propia red para estos.
## LEVANTAR APP MODO SWARM UNA VEZ CONFIGURADA
Bastara con correr los comandos:
````
$ cd environment
$ ./handle-containers start
````
## PARAR APP
````
$ cd environment
$ ./handle-containers stop
````
## VER SLIDES CON REVEAL-MD
Con node:
````
$ cd slides
$ reveal-md slides.md --css style.css
````
| 648ba8e33f83d63e5a7faad5f8eacdb7739bddf9 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | pablogiral/event-deliveroo | 30f0815291c1edf7e961b9028527194b04ddc900 | bc9e66a7f7dfc3ada690ec9f831ba71ac485a8bb |
refs/heads/master | <file_sep># generated from genmsg/cmake/pkg-genmsg.cmake.em
message(STATUS "project1_solution: 1 messages, 0 services")
set(MSG_I_FLAGS "-Iproject1_solution:/home/ccc_v1_w_NmY1N_85909/asn28980_1/asn28981_1/work/catkin_ws/src/project1_solution/msg;-Istd_msgs:/opt/ros/indigo/share/std_msgs/cmake/../msg")
# Find all generators
find_package(gencpp REQUIRED)
find_package(genlisp REQUIRED)
find_package(genpy REQUIRED)
add_custom_target(project1_solution_generate_messages ALL)
# verify that message/service dependencies have not changed since configure
get_filename_component(_filename "/home/ccc_v1_w_NmY1N_85909/asn28980_1/asn28981_1/work/catkin_ws/src/project1_solution/msg/TwoInts.msg" NAME_WE)
add_custom_target(_project1_solution_generate_messages_check_deps_${_filename}
COMMAND ${CATKIN_ENV} ${PYTHON_EXECUTABLE} ${GENMSG_CHECK_DEPS_SCRIPT} "project1_solution" "/home/ccc_v1_w_NmY1N_85909/asn28980_1/asn28981_1/work/catkin_ws/src/project1_solution/msg/TwoInts.msg" ""
)
#
# langs = gencpp;genlisp;genpy
#
### Section generating for lang: gencpp
### Generating Messages
_generate_msg_cpp(project1_solution
"/home/ccc_v1_w_NmY1N_85909/asn28980_1/asn28981_1/work/catkin_ws/src/project1_solution/msg/TwoInts.msg"
"${MSG_I_FLAGS}"
""
${CATKIN_DEVEL_PREFIX}/${gencpp_INSTALL_DIR}/project1_solution
)
### Generating Services
### Generating Module File
_generate_module_cpp(project1_solution
${CATKIN_DEVEL_PREFIX}/${gencpp_INSTALL_DIR}/project1_solution
"${ALL_GEN_OUTPUT_FILES_cpp}"
)
add_custom_target(project1_solution_generate_messages_cpp
DEPENDS ${ALL_GEN_OUTPUT_FILES_cpp}
)
add_dependencies(project1_solution_generate_messages project1_solution_generate_messages_cpp)
# add dependencies to all check dependencies targets
get_filename_component(_filename "/home/ccc_v1_w_NmY1N_85909/asn28980_1/asn28981_1/work/catkin_ws/src/project1_solution/msg/TwoInts.msg" NAME_WE)
add_dependencies(project1_solution_generate_messages_cpp _project1_solution_generate_messages_check_deps_${_filename})
# target for backward compatibility
add_custom_target(project1_solution_gencpp)
add_dependencies(project1_solution_gencpp project1_solution_generate_messages_cpp)
# register target for catkin_package(EXPORTED_TARGETS)
list(APPEND ${PROJECT_NAME}_EXPORTED_TARGETS project1_solution_generate_messages_cpp)
### Section generating for lang: genlisp
### Generating Messages
_generate_msg_lisp(project1_solution
"/home/ccc_v1_w_NmY1N_85909/asn28980_1/asn28981_1/work/catkin_ws/src/project1_solution/msg/TwoInts.msg"
"${MSG_I_FLAGS}"
""
${CATKIN_DEVEL_PREFIX}/${genlisp_INSTALL_DIR}/project1_solution
)
### Generating Services
### Generating Module File
_generate_module_lisp(project1_solution
${CATKIN_DEVEL_PREFIX}/${genlisp_INSTALL_DIR}/project1_solution
"${ALL_GEN_OUTPUT_FILES_lisp}"
)
add_custom_target(project1_solution_generate_messages_lisp
DEPENDS ${ALL_GEN_OUTPUT_FILES_lisp}
)
add_dependencies(project1_solution_generate_messages project1_solution_generate_messages_lisp)
# add dependencies to all check dependencies targets
get_filename_component(_filename "/home/ccc_v1_w_NmY1N_85909/asn28980_1/asn28981_1/work/catkin_ws/src/project1_solution/msg/TwoInts.msg" NAME_WE)
add_dependencies(project1_solution_generate_messages_lisp _project1_solution_generate_messages_check_deps_${_filename})
# target for backward compatibility
add_custom_target(project1_solution_genlisp)
add_dependencies(project1_solution_genlisp project1_solution_generate_messages_lisp)
# register target for catkin_package(EXPORTED_TARGETS)
list(APPEND ${PROJECT_NAME}_EXPORTED_TARGETS project1_solution_generate_messages_lisp)
### Section generating for lang: genpy
### Generating Messages
_generate_msg_py(project1_solution
"/home/ccc_v1_w_NmY1N_85909/asn28980_1/asn28981_1/work/catkin_ws/src/project1_solution/msg/TwoInts.msg"
"${MSG_I_FLAGS}"
""
${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/project1_solution
)
### Generating Services
### Generating Module File
_generate_module_py(project1_solution
${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/project1_solution
"${ALL_GEN_OUTPUT_FILES_py}"
)
add_custom_target(project1_solution_generate_messages_py
DEPENDS ${ALL_GEN_OUTPUT_FILES_py}
)
add_dependencies(project1_solution_generate_messages project1_solution_generate_messages_py)
# add dependencies to all check dependencies targets
get_filename_component(_filename "/home/ccc_v1_w_NmY1N_85909/asn28980_1/asn28981_1/work/catkin_ws/src/project1_solution/msg/TwoInts.msg" NAME_WE)
add_dependencies(project1_solution_generate_messages_py _project1_solution_generate_messages_check_deps_${_filename})
# target for backward compatibility
add_custom_target(project1_solution_genpy)
add_dependencies(project1_solution_genpy project1_solution_generate_messages_py)
# register target for catkin_package(EXPORTED_TARGETS)
list(APPEND ${PROJECT_NAME}_EXPORTED_TARGETS project1_solution_generate_messages_py)
if(gencpp_INSTALL_DIR AND EXISTS ${CATKIN_DEVEL_PREFIX}/${gencpp_INSTALL_DIR}/project1_solution)
# install generated code
install(
DIRECTORY ${CATKIN_DEVEL_PREFIX}/${gencpp_INSTALL_DIR}/project1_solution
DESTINATION ${gencpp_INSTALL_DIR}
)
endif()
add_dependencies(project1_solution_generate_messages_cpp std_msgs_generate_messages_cpp)
if(genlisp_INSTALL_DIR AND EXISTS ${CATKIN_DEVEL_PREFIX}/${genlisp_INSTALL_DIR}/project1_solution)
# install generated code
install(
DIRECTORY ${CATKIN_DEVEL_PREFIX}/${genlisp_INSTALL_DIR}/project1_solution
DESTINATION ${genlisp_INSTALL_DIR}
)
endif()
add_dependencies(project1_solution_generate_messages_lisp std_msgs_generate_messages_lisp)
if(genpy_INSTALL_DIR AND EXISTS ${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/project1_solution)
install(CODE "execute_process(COMMAND \"/usr/bin/python\" -m compileall \"${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/project1_solution\")")
# install generated code
install(
DIRECTORY ${CATKIN_DEVEL_PREFIX}/${genpy_INSTALL_DIR}/project1_solution
DESTINATION ${genpy_INSTALL_DIR}
)
endif()
add_dependencies(project1_solution_generate_messages_py std_msgs_generate_messages_py)
<file_sep>#!/usr/bin/env python
import rospy
import numpy
import tf
import tf2_ros
import geometry_msgs.msg
def message_from_transform(T):
msg = geometry_msgs.msg.Transform()
q = tf.transformations.quaternion_from_matrix(T)
translation = tf.transformations.translation_from_matrix(T)
msg.translation.x = translation[0]
msg.translation.y = translation[1]
msg.translation.z = translation[2]
msg.rotation.x = q[0]
msg.rotation.y = q[1]
msg.rotation.z = q[2]
msg.rotation.w = q[3]
return msg
def publish_transforms():
object_transform = geometry_msgs.msg.TransformStamped()
object_T = tf.transformations.concatenate_matrices(
tf.transformations.quaternion_matrix(
tf.transformations.quaternion_from_euler(0.79,0.0,0.79)),
tf.transformations.translation_matrix([0.0,1.0,1.0])
)
object_inverse = tf.transformations.inverse_matrix(object_T)
object_transform.transform = message_from_transform(object_T)
object_transform.header.stamp = rospy.Time.now()
object_transform.header.frame_id = "base_frame"
object_transform.child_frame_id = "object_frame"
br.sendTransform(object_transform)
################################################
robot_transform = geometry_msgs.msg.TransformStamped()
robot_transform.header.stamp = rospy.Time.now()
robot_transform.header.frame_id = "base_frame"
robot_transform.child_frame_id = "robot_frame"
robot_T = tf.transformations.concatenate_matrices(
tf.transformations.quaternion_matrix(
tf.transformations.quaternion_about_axis(1.5, (0,0,1)) ),
tf.transformations.translation_matrix([0,-1,0])
)
robot_inverse = tf.transformations.inverse_matrix(robot_T)
robot_transform.transform = message_from_transform(robot_T)
br.sendTransform(robot_transform)
##############################################
camera_transform = geometry_msgs.msg.TransformStamped()
camera_transform.header.stamp = rospy.Time.now()
camera_transform.header.frame_id = "robot_frame"
camera_transform.child_frame_id = "camera_frame"
camera_T = tf.transformations.concatenate_matrices(
tf.transformations.quaternion_matrix(
tf.transformations.quaternion_from_euler(0,0,0)),
tf.transformations.translation_matrix([0.0,0.1,0.1])
)
camera_inverse = tf.transformations.inverse_matrix(camera_T)
t1 = tf.transformations.concatenate_matrices(camera_inverse,robot_inverse,object_T)
dir = tf.transformations.translation_from_matrix(t1)
x_axis = [1,0,0]
axis_rot = numpy.cross(x_axis,dir)
cos_angle = numpy.vdot(x_axis,dir) / numpy.linalg.norm(dir)
angle = numpy.arccos(cos_angle)
camera_q = tf.transformations.quaternion_about_axis(angle,axis_rot)
camera_T = tf.transformations.concatenate_matrices(
camera_T,tf.transformations.quaternion_matrix(camera_q)
)
camera_transform.transform = message_from_transform(camera_T)
br.sendTransform(camera_transform)
if __name__ == '__main__':
rospy.init_node('project2_solution')
br = tf2_ros.TransformBroadcaster()
rospy.sleep(0.5)
while not rospy.is_shutdown():
publish_transforms()
rospy.sleep(0.05)
<file_sep>#!/usr/bin/env python
import rospy
from std_msgs.msg import Int16
from project1_solution.msg import TwoInts
rospy.init_node('solution')
def callback(msg):
# print msg.a
# print msg.b
sum = msg.a + msg.b
pub.publish(sum)
pub = rospy.Publisher('sum', Int16, queue_size=10)
sub = rospy.Subscriber('two_ints', TwoInts, callback)
rospy.spin()<file_sep>FILE(REMOVE_RECURSE
"CMakeFiles/project1_solution_gencpp"
)
# Per-language clean rules from dependency scanning.
FOREACH(lang)
INCLUDE(CMakeFiles/project1_solution_gencpp.dir/cmake_clean_${lang}.cmake OPTIONAL)
ENDFOREACH(lang)
<file_sep># ColumbiaX-Robotics
This repository contains all the project files from the Columbia University's Robotics course on Edx.
<file_sep># generated from genmsg/cmake/pkg-msg-paths.cmake.develspace.in
set(project1_solution_MSG_INCLUDE_DIRS "/home/ccc_v1_w_NmY1N_85909/asn28980_1/asn28981_1/work/catkin_ws/src/project1_solution/msg")
set(project1_solution_MSG_DEPENDENCIES std_msgs)
| fac88351dcf84d856b0d93fc3d4526cdca61882a | [
"Markdown",
"Python",
"CMake"
] | 6 | CMake | hardesh/ColumbiaX-Robotics | 1e542a637772fd1223b48e55a71ac75c5500900f | a906beddecb9faf91d716bb1a800aed31e2bb218 |
refs/heads/master | <file_sep>package com.hakanor.todolist;
import androidx.appcompat.app.AppCompatActivity;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements ExampleDialog.ExampleDialogListener {
private CoordinatorLayout coordinatorLayout;
private ArrayList<ExampleItem> mExampleList = new ArrayList<ExampleItem>();
private RecyclerView mRecyclerView;
private ExampleAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private static final int REQUEST_CODE_SPEECH_INPUT=1000;
ArrayList<String> result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinatorLayout = findViewById(R.id.coordinator_layout);
buildRecyclerView();
loadData();
//Voice FLOAT ACTION BUTTON //
FloatingActionButton vab = findViewById(R.id.vab);
vab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
speak();
}
});
//FLOAT ACTION BUTTON //
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
openDialog();
}
});
}
@Override
protected void onStop(){
super.onStop();
saveData();
}
// NON ON CREATE //
// NON ON CREATE //
private void saveData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(mExampleList);
editor.putString("task list", json);
editor.apply();
}
private void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list", null);
Type type = new TypeToken<ArrayList<ExampleItem>>() {}.getType();
mExampleList = gson.fromJson(json, type);
if (mExampleList == null) {
mExampleList = new ArrayList<>();
}
mAdapter.setItems(mExampleList);
}
public void speak() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak for a new task!");
try {
startActivityForResult(intent,MainActivity.REQUEST_CODE_SPEECH_INPUT);
}
catch (Exception e){
}
}
public void removeItem(int position) {
ExampleItem temp=mExampleList.get(position);
mExampleList.remove(position);
mAdapter.notifyItemRemoved(position);
showSnackbar(temp,position);
}
public void showSnackbar(final ExampleItem temp, final int position){
Snackbar snackbar = Snackbar.make(coordinatorLayout,"Task done!",Snackbar.LENGTH_LONG)
.setAction("UNDO", new View.OnClickListener() {
@Override
public void onClick(View v) {
insertItem(position,temp.getText1(),temp.getText2());
Snackbar snackbar1=Snackbar.make(coordinatorLayout,"Undo Successful :]",Snackbar.LENGTH_SHORT);
snackbar1.show();
}
});
snackbar.show();
}
public void insertItem(int position,String text1,String text2) {
mExampleList.add(position, new ExampleItem(R.drawable.check, text1, text2));
mAdapter.notifyItemInserted(position);
}
//DIALOG //
public void openDialog(){
ExampleDialog exampleDialog = new ExampleDialog();
exampleDialog.show(getSupportFragmentManager(),"Add New Task");
}
// --------------------------------------------------------------------//
//Genel //
public void buildRecyclerView() {
mRecyclerView = findViewById(R.id.recyclerView);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new ExampleAdapter(mExampleList);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
mAdapter.setOnItemClickListener(new ExampleAdapter.OnItemClickListener() {
@Override
public void onItemClick(int position) {
mExampleList.get(position).getText1();
mExampleList.get(position).getText2();
mExampleList.get(position);
Intent intent = new Intent(MainActivity.this, NewActivity.class);
intent.putExtra("mExampleList",mExampleList);
intent.putExtra("position",position);
startActivityForResult(intent, 1);
}
@Override
public void onDeleteClick(int position) {
removeItem(position);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK) {
String et1 = data.getStringExtra("editText1");
String et2 = data.getStringExtra("editText2");
int position=data.getIntExtra("position",0);
if(mExampleList.get(position).getText1().equals(et1) && mExampleList.get(position).getText2().equals(et2)){
//Bir değişiklik yapılmamış demektir.
}
else{
mExampleList.get(position).setText1(et1);
mExampleList.get(position).setText2(et2);
mAdapter.notifyDataSetChanged();
}
}
}
if(requestCode==REQUEST_CODE_SPEECH_INPUT){
switch(requestCode){
case REQUEST_CODE_SPEECH_INPUT:{
if(resultCode==RESULT_OK && null!=data)
result=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
try {
mExampleList.add(new ExampleItem(R.drawable.check, "Voice Task", result.get(0)));
mAdapter.notifyDataSetChanged();
result.removeAll(result);
}
catch(Exception e){
Toast.makeText(this, "Creating task canceled.", Toast.LENGTH_SHORT).show();
}
}
break;
}
}
}
@Override
public void applyTexts(String title, String desc) {
if(!title.equals("")){
mExampleList.add(new ExampleItem(R.drawable.check, title, desc));
mAdapter.setItems(mExampleList);
Toast.makeText(this, "New task added.", Toast.LENGTH_SHORT).show();
}
}
}<file_sep>package com.hakanor.todolist;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class NewActivity extends AppCompatActivity {
private EditText editText1;
private EditText editText2;
private ImageView edit_button;
private ImageView check_button;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
Intent intent = getIntent();
ArrayList<ExampleItem> mExampleList = (ArrayList<ExampleItem>) intent.getSerializableExtra("mExampleList");
final int position = intent.getIntExtra("position",0);
editText1 = findViewById(R.id.editText1);
editText2 = findViewById(R.id.editText2);
editText1.setBackgroundResource(android.R.drawable.editbox_background);
editText2.setBackgroundResource(android.R.drawable.editbox_background);
editText1.setText(mExampleList.get(position).getText1());
editText2.setText(mExampleList.get(position).getText2());
edit_button=findViewById(R.id.edit_button);
check_button=findViewById(R.id.check_button);
edit_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editText1.setEnabled(true);
editText1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
editText1.post(new Runnable() {
@Override
public void run() {
InputMethodManager inputMethodManager= (InputMethodManager) NewActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(editText1, InputMethodManager.SHOW_IMPLICIT);
}
});
}
});
editText1.requestFocus();
editText2.setEnabled(true);
check_button.setVisibility(View.VISIBLE);
}
});
check_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("editText1", editText1.getText().toString());
intent.putExtra("editText2", editText2.getText().toString());
intent.putExtra("position", position);
setResult(RESULT_OK, intent);
finish();
}
});
}
}
| 3f58609b47def8853c8e6adac766aec011480ff2 | [
"Java"
] | 2 | Java | compeboy/ToDoList | 4cd87d698278a6554727c373893830829a5d9cae | 7a21c7d3f9c7bf1757a7c791c1af25e6db4cba7a |
refs/heads/master | <file_sep>'''Дана дата из трех чисел (день, месяц и год).
Вывести yes, если такая дата существует (например, 12 02 1999 - yes, 22 13 2001 - no).
Считать, что в феврале всегда 28 дней.
'''
#вводим дни, месяцы, года
#проводим проверку отдельно по каждому значению
# в функцию
def countday(mm):
if mm == 2:
return 28
elif mm == 4 or mm == 6 or mm == 9 or mm == 11:
return 30
else:
return 31
def checkDate(dd, mm, gg):
if mm<1 or mm > 12 or dd<1 or dd> countday(mm):
return False
else:
return True
def main():
dd = int(input('введите день 1,2,3...' ))
mm = int(input('введите месяц 1,2,3... ' ))
gg = int(input('введите год 0000... ' ))
if checkDate(dd,mm,gg):
print('Yes')
else:
print('No')
main()<file_sep>def main():
import random
#сделать возможность продолжить игру
#добавить баланс = 100 каждая игра стоит по 10
#если угадали с первой попытки то +50 со второго +30 с третьего +20
#если баланса не хватает на игру то выводим сообщение об этом и завершаем игру
#вести стастику пройгрышей и выйгрышей
end = 1
balance = 100
win = 0
stat_win = 0
count_game = 0
while end == 1:
computer = random.randint(1, 10)
print(f' Баланс равен {balance}, стоимость игры 10')
balance = balance - 10
for i in range(3):
user = int(input('Введите число: '))
if user > computer:
print('Введенное число больше')
elif user < computer:
print('Введенное число меньше')
else:
print('УРА! Угадали!')
win = win + 1
if i == 0:
balance = balance + 50
elif i == 1:
balance = balance + 30
else:
balance = balance + 20
break
else:
print(f'Попытки закончены. Вы проиграли. Загаданное число = {computer}')
count_game = count_game + 1
stat_win = win / count_game
print(f'Побед {win} всего игр {count_game} процент побед {stat_win}')
print("Ваш баланс", balance)
if balance <= 0:
print(f'Баланс равен : {balance}. Игра окончена!')
end = 0
else:
end = int(input("Продолжить игру? да- 1, нет- 0 :"))
main()<file_sep>'''Вывести на экран фигуру из звездочек:
*******
*******
*******
*******
(квадрат из n строк, в каждой строке n звездочек)'''
def main():
N = 0
N = int(input("строк-столбцов N: "))
for i in range(N):
print('*'*N)
main()<file_sep>'''Определите, является ли данное число простым.'''
def isSimple(number):
for i in range (2, number):
if number % i == 0:
return False
return True
def main():
number = int(input( "Введите число "))
if isSimple(number) == True:
print( "Простое")
else:
print("Не простое")
main()<file_sep>def price_discount(total):
if total >= 1000 and total < 2000:
return total * 0.95
elif total >= 2000:
return total * 0.9
else:
return total
def main():
N = int(input("Кол-во товаров: "))
total = 0
maxcost = 0
dopgood = 0
for i in range(N):
cost = int(input("Введите стоимость товара: "))
total = total+ cost
if cost>maxcost :
maxcost= cost
print("Самый дорогой товар ", maxcost)
print(" общая стоимость ", total)
dis = price_discount(total)
print("Цена со скидкой", dis )
main()
<file_sep>'''написать программу.
которая выводит таблицу значений функций y= -2.4x**2+ 5*x-3
в диапазоне -2 до 2 с шагом 0,5 '''
def main():
x = -2
print("*"*20)
print("x"," | ", "y")
print("*" * 20)
while x <= 2:
y = -2.4 * x**2 + 5 * x - 3
print(x , " | " , y)
x = x + 0.5
main()<file_sep>'''Дано время отправления часы и минуты,
дано время в пути часы и минуты.
написать функцию определяющую время прибытия
(часы не могу быть больше 24, минуты больше 60)'''
def calcTimeArrival(deptimeHour, deptimeMin, travelTimeHour, travelTimeMin):
calcHour = deptimeHour + travelTimeHour
calcmin = deptimeMin + travelTimeMin
if calcmin >= 60:
calcHour = calcHour + 1
calcmin = calcmin - 60
if calcHour >= 24:
calcHour = calcHour - 24
return calcHour, calcmin
def main():
deptimeHour = int(input('введите часы отправления ' ))
deptimeMin = int(input('введите и минуты отправления ' ))
travelTimeHour = int(input('введите сколько часов в пути ' ))
travelTimeMin = int(input('введите и минут в пути ' ))
hour, min = calcTimeArrival(deptimeHour, deptimeMin, travelTimeHour, travelTimeMin)
print(hour, min)
main()<file_sep>'''Реализуйте серию из n игр "Камень, ножницы, бумага" с компьютером.
В результате выведите статистику: сколько игр выиграл пользователь,
сколько раз каждого вида ходов было выбрано.
Дополните игру анализом компьютера ваших ходов и выбор наиболее подходящего против вас хода.'''
import random
def moveUser(start, end, message):
while True:
count = int(input(message))
if count >= start and count<= end:
break
else:
print(f"Не корретное значение, допустимое значение от {start} до {end}")
return count
def moveComputer(sto, sci , paper):
if sto == sci and sci == paper:
return random.randint(1, 3)
else:
if sto <= sci and sto <= paper:
return 3
elif sci<= paper and sci <= sto:
return 1
else:
return 2
def main():
end = 0
sto = 0
sci = 0
pap = 0
loss = 0
win = 0
math = 0
while end == 0:
count = moveUser(1,3,"Введите Камень- 1 или Ножницы-2 или Бумага-3 :")
if count == 1:
sto += 1
elif count == 2:
sci += 1
else:
pap += 1
value = moveComputer(sto, sci, pap)
if count == value:
print("Ничья")
elif count == 1 and value == 2 or count == 2 and value == 3 or count == 3 and value == 1:
print("Вы победили")
win += 1
else:
print("Вы проиграли, компьютер загадал ", value)
loss += 1
math += 1
print(f" Всего игр {math}, побед {win}, поражений {loss}")
print(f"Вы выбрали камень {sto} раз, ножницы {sci} раз, бумага {pap} раз")
end = int(input(' Продолжить да 0 нет 1'))
main()
<file_sep>a = int(input())
s1 = (a // 100000) + (a // 10000 % 10) + (a // 1000 % 10)
s2 = (a % 1000 // 100) + (a % 1000 // 10 % 10) + (a % 1000 % 10)
if s1 == s2:
print("Счастливый")
else:
print("Обычный")<file_sep>def check_masa(massa):
if massa < 94 or massa > 727:
return False
else:
return True
def find_max(m1, m2, m3):
if m1 >= m2 and m1 >= m3:
max = m1
elif m2 >= m3 and m2 >= m1:
max = m2
else:
max = m3
return max
def main():
m1 = int(input('Введите массу толстяка 1 '))
m2 = int(input('Введите массу толстяка 2 '))
m3 = int(input('Введите массу толстяка 3 '))
if not check_masa(m1) or not check_masa(m2) or not check_masa(m3):
print('данные не корректны')
else:
max_ves = find_max(m1, m2, m3)
print(max_ves)
main()
<file_sep>'''Выведите на экран таблицу умножения для чисел от 1 до 10'''
def main():
for i in range(1, 10):
for j in range(1, 10):
print((i*j), end=" ")
print("")
main()<file_sep>'''дан список температур за N дней, определить самую высокую температуру,
определить кол-во дней с минимальной температурой.
определить среднюю температуру.
кол-во дней с температурой попадающей в указанный диапазон (например от 10 до 20)'''
def madelist():
templist = []
daycount = int(input("введите количество дней"))
for i in range(daycount):
tempday = int(input(f'Введите температуру {i} дня'))
templist.append(tempday)
return templist
def main():
while True:
madelist()
<file_sep>'''Дано время отправления часы и минуты,
дано время в пути часы и минуты.
написать функцию определяющую время прибытия
(часы не могу быть больше 24, минуты больше 60)'''
"""ввод времени в пути
ввод времени отправления
проверка на правильность данных
определение времени прибытия
вывод времни прибытия"""
addhour = 0
remMin = 0
def hour( deptimeHour, travelTimeHour):
if hour <0 or hour > 24:
return False
else:
return True
def minutes( deptimeMin, travelTimeMin):
if minutes <0 or minutes > 24:
return False
else:
return True
def arTime(arTimeMin):
if arTimeMin > 60:
addhour = arTimeMin//60
remMin = arTimeMin%60*60
else:
addhour = 0
remMin = 0
return addhour,remMin
deptimeHour = int(input('введите часы отправления ' ))
deptimeMin = int(input('введите и минуты отправления ' ))
travelTimeHour = int(input('введите сколько часов в пути ' ))
travelTimeMin = int(input('введите и минут в пути ' ))
hour
minutes
print('ok')
arTimeHour = deptimeHour + travelTimeHour
arTimeMin = deptimeMin + travelTimeMin
arTime
arTimeHour= arTimeHour + addhour
arTimeMin = arTimeMin + remMin
if arTimeHour > 24:
arTimeHour = arTimeHour// 24
else:
True
print('время прибытия', 'часов', arTimeHour, ' минут', arTimeMin) | 593eff6c4a6f9240ac0399b70757a725c3477033 | [
"Python"
] | 13 | Python | sneggoroddd/GlobalProekt | 568caba98ebd7420a20a504f3e1150780631667a | 03f343ec8e9758432e381523eea1bf225e7c5cd6 |
refs/heads/master | <file_sep>class Resume < ApplicationRecord
mount_uploader :attachment, AttachmentUploader
validates :name, presence: true
end
| 8d02d44fdfbf5817f44216c55365a3fb9e37b23b | [
"Ruby"
] | 1 | Ruby | karthikakb/fileupload | 5f01db896533be07f718421348cee68b3198d10e | e876decc327b64241b4a5ce7e54ccfa70c70a602 |
refs/heads/master | <file_sep>(function() {
//=include ./events/events.js
//=include ./events/mutex.js
//=include ./events/colleague.js
//=include ./events/mediator.js
//=include ./utilities/date-utils.js
//=include ./utilities/number-utils.js
//=include ./utilities/uuid-utils.js
//=include ./components/calendar/calendar.js
//=include ./components/dialer/dialer.js
//=include ./components/sliders/increment-slider.js
//=include ./components/sliders/year-increment-slider.js
//=include ./components/sliders/month-increment-slider.js
//=include ./components/sliders/ydialer-increment-slider.js
//=include ./components/controls/picker-controls.js
//=include ./components/partial.js
function DatePicker(options) {
//super()
Colleague.call(this, new Mediator(), DatePicker.prototype.component);
this.generateEvents();
if (options === undefined) {
options = this.deepCopyObject(DatePicker.prototype.defaults);
} else {
options = Object.assign(this.deepCopyObject(DatePicker.prototype.defaults), this.deepCopyObject(options));
}
options.mediator = this.mediator;
this.context = options.parent;
this.scale = (options.scale !== undefined && DatePicker.prototype.enum.scales[options.scale] !== undefined) ?
options.scale : DatePicker.prototype.defaults.scale;
this.min_date = options.min_date instanceof Date ?
options.min_date :
undefined;
this.max_date = options.max_date instanceof Date && options.max_date > this.min_date ?
options.max_date :
undefined;
this.date = options.date instanceof Date && options.date >= this.min_date && options.date <= this.max_date ?
options.date : undefined;
if (this.date === undefined) {
if (this.max_date) {
this.date = new Date(this.max_date.getUTCFullYear(), this.max_date.getUTCMonth(), this.max_date.getUTCDate());
options.date = new Date(this.max_date.getUTCFullYear(), this.max_date.getUTCMonth(), this.max_date.getUTCDate());
} else if (this.min_date) {
this.date = new Date(this.min_date.getUTCFullYear(), this.min_date.getUTCMonth(), this.min_date.getUTCDate());
options.date = new Date(this.min_date.getUTCFullYear(), this.min_date.getUTCMonth(), this.min_date.getUTCDate());
} else {
this.date = new Date();
options.date = new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate());
}
}
this.prev_date = new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate());
this.lang = options.lang !== undefined &&
DatePicker.prototype.enum.languages[options.lang] !== undefined ?
DatePicker.prototype.enum.languages[options.lang] : 'en';
//Setting up the controls
this.controls = new PickerControls(options);
//Setting up the partials
this.partials = {};
options.value = options.date;
options.scale = DatePicker.prototype.enum.scales.day;
this.partials.day = new Partial(options);
options.scale = DatePicker.prototype.enum.scales.week;
this.partials.week = new Partial(options);
options.scale = DatePicker.prototype.enum.scales.month;
this.partials.month = new Partial(options);
options.scale = DatePicker.prototype.enum.scales.year;
this.partials.year = new Partial(options);
//Subscribe all partials to global events
this.subscribe();
//Generating markup and appending to DOM
this.generateSVG(options.icons);
this.generateHTML();
this.patchSVGURLs();
}
//Binding the prototype of the Parent object
//Properties will be overriden on this one.
DatePicker.prototype = Object.create(Colleague.prototype);
//Binding the constructor to the prototype
DatePicker.prototype.constructor = Colleague;
//Binding all Types to the namespace (for retrieval by external programmers)
DatePicker.prototype.Partial = Partial;
DatePicker.prototype.Calendar = Calendar;
DatePicker.prototype.IncrementSlider = IncrementSlider;
DatePicker.prototype.MonthIncrementSlider = MonthIncrementSlider;
DatePicker.prototype.YearIncrementSlider = YearIncrementSlider;
DatePicker.prototype.Colleague = Colleague;
DatePicker.prototype.Mediator = Mediator;
DatePicker.prototype.DateUtils = DateUtils;
DatePicker.prototype.NumberUtils = NumberUtils;
DatePicker.prototype.UUIDUtils = UUIDUtils;
DatePicker.prototype.component = 'DATEPICKER';
DatePicker.prototype.defaults = {
date: new Date(),
scale: "day",
icons: {
"arrow-prev-big": '<svg><symbol id="arrow-prev-big"><rect fill="none" x="0" y="0" width="30" height="30" height="30"/><polygon points="18,23.2 9.3,15.5 18,7.8 "/></symbol></svg>',
"arrow-next-big": '<svg><symbol id="arrow-next-big"><use transform="translate(30,0) scale(-1,1)" xlink:href="#arrow-prev-big" /></svg>',
"arrow-prev-small": '<svg><symbol id="arrow-prev-small"><rect fill="none" width="20" height="20"/><polygon points="12,16.2 5.3,10.3 12,4.4 "/></symbol></svg>',
"arrow-next-small": '<svg></symbol><symbol id="arrow-next-small"><use transform="translate(20,0) scale(-1,1)" xlink:href="#arrow-prev-small" /></symbol></svg>'
},
parent: 'body',
lang: 'en'
};
DatePicker.prototype.enum = {
scales: {
day: "day",
week: "week",
month: "month",
year: "year"
},
languages: {
en: 'en',
fr: 'fr'
},
callbacks: {
dateUpdate: 'dateUpdate',
minDateUpdate: 'minDateUpdate',
maxDateUpdate: 'maxDateUpdate',
scaleUpdate: 'scaleUpdate',
notify: 'notify',
emit: 'emit',
commit: 'commit',
rollback: 'rollback'
},
components: {
partials: {
day: "DAYPARTIAL",
week: "WEEKPARTIAL",
month: "MONTHPARTIAL",
year: "YEARPARTIAL"
},
sub: {
day: {
mis: "DAYMIS",
yis: "DAYYIS",
cal: "DAYCAL",
},
week: {
mis: "WEEKMIS",
yis: "WEEKYIS",
cal: "WEEKCAL",
},
month: {
yis: "MONTHYIS",
mdi: "MONTHDIALER",
},
year: {
yds: "YDIALERIS",
ydi: "YEARDIALER",
},
controls: {
pcs: "PICKERCONTROLS"
}
}
}
};
DatePicker.prototype.getAPI = function() {
var self = this;
return {
getDate: function() {
return self.getDate();
},
setDate: function(date) {
self.setDate(date);
},
incrementDate: function(commit, scale) {
return self.incrementDate(commit, scale);
},
decrementDate: function(commit, scale) {
return self.decrementDate(commit, scale);
},
getMinDate: function() {
return self.getMinDate();
},
setMinDate: function(date) {
self.setMinDate(date);
},
getMaxDate: function() {
return self.getMaxDate();
},
setMaxDate: function(date) {
self.setMaxDate(date);
},
getPeriod: function() {
return self.getPeriod();
},
getScales: function() {
return self.getScales();
},
getScale: function() {
return self.getScale();
},
changeScale: function(scale) {
self.changeScale(scale);
},
addEventListener: function(e, c) {
self.addEventListener(e, c);
},
getHTML: function() {
return self.getHTML();
},
getComponents: function() {
return self.getComponents();
},
getComponent: function(comp) {
return self.getComponent(comp);
},
commit: function() {
self.commit();
},
rollback: function() {
self.rollback();
},
patchSVGURLs: function() {
self.patchSVGURLs();
}
};
};
DatePicker.prototype.getDate = function() {
return new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate());
};
DatePicker.prototype.setDate = function(date) {
if (date !== undefined && date instanceof Date &&
(this.min_date === undefined || date >= this.min_date) &&
(this.max_date === undefined || date <= this.max_date)) {
this.date = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
this.emit(this.mediation.events.broadcast.gupdate, { date: date });
this.callCallback(DatePicker.prototype.enum.callbacks.dateUpdate, date);
return true;
}
return false;
};
DatePicker.prototype.incrementDate = function(commit, scale) {
commit = commit === undefined ? false : !!commit;
this.controls.incrementDate(commit, scale);
};
DatePicker.prototype.decrementDate = function(commit, scale) {
commit = commit === undefined ? false : !!commit;
this.controls.decrementDate(commit, scale);
};
DatePicker.prototype.getMinDate = function() {
if (this.min_date === undefined) return undefined;
return new Date(this.min_date.getUTCFullYear(), this.min_date.getUTCMonth(), this.min_date.getUTCDate());
};
DatePicker.prototype.setMinDate = function(date) {
if (date !== undefined && date instanceof Date && (this.max_date === undefined || date < this.max_date)) {
this.min_date = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
this.emit(this.mediation.events.broadcast.gupdate, { min_date: date });
if (this.date < this.min_date) {
this.setDate(this.min_date);
}
this.callCallback(DatePicker.prototype.enum.callbacks.minDateUpdate, date);
return true;
}
return false;
};
DatePicker.prototype.getMaxDate = function() {
if (this.max_date === undefined) return undefined;
return new Date(this.max_date.getUTCFullYear(), this.max_date.getUTCMonth(), this.max_date.getUTCDate());
};
DatePicker.prototype.setMaxDate = function(date) {
if (date !== undefined && date instanceof Date && (this.min_date === undefined || date > this.min_date)) {
this.max_date = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
this.emit(this.mediation.events.broadcast.gupdate, { max_date: date });
if (this.date > this.max_date) {
this.setDate(this.max_date);
}
this.callCallback(DatePicker.prototype.enum.callbacks.maxDateUpdate, date);
return true;
}
return false;
};
DatePicker.prototype.getPeriod = function() {
var period = {};
switch (this.scale) {
case DatePicker.prototype.enum.scales.day:
period.date = this.getDate();
break;
case DatePicker.prototype.enum.scales.week:
period = DateUtils.getWeekFALDays(this.date);
period.start = this.min_date !== undefined && period.start.getTime() < this.min_date.getTime() ? this.getMinDate() : period.start;
period.end = this.max_date !== undefined && period.end.getTime() > this.max_date.getTime() ? this.getMaxDate() : period.end;
break;
case DatePicker.prototype.enum.scales.month:
period.start = this.getDate();
period.start.setUTCDate(1);
period.end = this.getDate();
period.end.setUTCDate(DateUtils.daysInMonth(period.end.getUTCFullYear(), period.end.getUTCMonth()));
period.start = this.min_date !== undefined && period.start.getTime() < this.min_date.getTime() ? this.getMinDate() : period.start;
period.end = this.max_date !== undefined && period.end.getTime() > this.max_date.getTime() ? this.getMaxDate() : period.end;
break;
case DatePicker.prototype.enum.scales.year:
period.start = this.getDate();
period.start.setUTCMonth(0);
period.start.setUTCDate(1);
period.end = this.getDate();
period.end.setUTCMonth(11);
period.end.setUTCDate(31);
period.start = this.min_date !== undefined && period.start.getTime() < this.min_date.getTime() ? this.getMinDate() : period.start;
period.end = this.max_date !== undefined && period.end.getTime() > this.max_date.getTime() ? this.getMaxDate() : period.end;
break;
}
return period;
};
DatePicker.prototype.getScales = function() {
return DatePicker.prototype.enum.scales;
};
DatePicker.prototype.getScale = function() {
return this.scale;
};
DatePicker.prototype.changeScale = function(scale) {
this.scale = DatePicker.prototype.enum.scales[scale] === undefined ?
DatePicker.prototype.enum.scales.day : DatePicker.prototype.enum.scales[scale];
this.body.removeChild(this.body.children[0]);
this.body.appendChild(this.partials[this.scale].getHTML());
this.callCallback(DatePicker.prototype.enum.callbacks.scaleUpdate, scale);
};
DatePicker.prototype.getHTML = function() {
return this.html;
};
DatePicker.prototype.getComponents = function() {
return DatePicker.prototype.enum.components;
};
DatePicker.prototype.getComponent = function(comp) {
switch (comp) {
case DatePicker.prototype.enum.components.partials.day:
return this.partials[DatePicker.prototype.enum.scales.day];
case DatePicker.prototype.enum.components.partials.week:
return this.partials[DatePicker.prototype.enum.scales.week];
case DatePicker.prototype.enum.components.partials.month:
return this.partials[DatePicker.prototype.enum.scales.month];
case DatePicker.prototype.enum.components.partials.year:
return this.partials[DatePicker.prototype.enum.scales.year];
case DatePicker.prototype.enum.components.sub.day.mis:
return this.partials[DatePicker.prototype.enum.scales.day].components.minput;
case DatePicker.prototype.enum.components.sub.day.yis:
return this.partials[DatePicker.prototype.enum.scales.day].components.yinput;
case DatePicker.prototype.enum.components.sub.day.cal:
return this.partials[DatePicker.prototype.enum.scales.day].components.calendar;
case DatePicker.prototype.enum.components.sub.week.yis:
return this.partials[DatePicker.prototype.enum.scales.week].components.minput;
case DatePicker.prototype.enum.components.sub.week.mis:
return this.partials[DatePicker.prototype.enum.scales.week].components.yinput;
case DatePicker.prototype.enum.components.sub.week.cal:
return this.partials[DatePicker.prototype.enum.scales.week].components.calendar;
case DatePicker.prototype.enum.components.sub.month.yis:
return this.partials[DatePicker.prototype.enum.scales.month].components.yinput;
case DatePicker.prototype.enum.components.sub.month.mdi:
return this.partials[DatePicker.prototype.enum.scales.month].components.mdialer;
case DatePicker.prototype.enum.components.sub.year.yds:
return this.partials[DatePicker.prototype.enum.scales.year].components.ydinput;
case DatePicker.prototype.enum.components.sub.year.ydi:
return this.partials[DatePicker.prototype.enum.scales.year].components.ydialer;
case DatePicker.prototype.enum.components.sub.controls.pcs:
return this.controls;
default:
return undefined;
}
};
DatePicker.prototype.addEventListener = function(e, callback) {
if (typeof e === "string") {
for (var key in DatePicker.prototype.enum.callbacks) {
if (e === key) {
this.registerCallback(e, callback);
break;
}
}
} else {
throw new Error('Illegal Argument: addEventListener takes a string as first parameter');
}
};
DatePicker.prototype.commit = function() {
var date = new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate());
this.prev_date = new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate());
this.emit(this.mediation.events.broadcast.commit, {});
this.callCallback(DatePicker.prototype.enum.callbacks.commit, date);
};
DatePicker.prototype.rollback = function() {
var date = new Date(this.prev_date.getUTCFullYear(), this.prev_date.getUTCMonth(), this.prev_date.getUTCDate());
this.date = new Date(this.prev_date.getUTCFullYear(), this.prev_date.getUTCMonth(), this.prev_date.getUTCDate());
this.emit(this.mediation.events.broadcast.rollback, {});
this.callCallback(DatePicker.prototype.enum.callbacks.rollback, date);
};
DatePicker.prototype.generateHTML = function() {
var self = this,
callback = function(e) {
self.onModeBtnClick(e.target);
};
var datepicker = document.createElement('div');
datepicker.className = "date-picker";
var content = document.createElement('div');
content.className = "date-picker-content";
var moderow = document.createElement('div');
moderow.className = "date-picker-mode-button-row";
var button;
for (var key in DatePicker.prototype.enum.scales) {
button = document.createElement('span');
button.scale = key;
button.innerHTML = key.charAt(0).toUpperCase() + key.slice(1);
button.addEventListener('click', callback);
if (this.scale === key) {
moderow.current = button;
button.className = "date-picker-mode-button active";
} else {
button.className = "date-picker-mode-button";
}
moderow.appendChild(button);
}
var body = document.createElement('div');
body.className = "date-picker-body";
body.appendChild(this.partials[this.scale].getHTML());
content.appendChild(moderow);
content.appendChild(body);
document.addEventListener('click', function(e) {
var isChild = false,
node = e.target;
while (node !== null) {
if (node == datepicker) {
isChild = true;
}
node = node.parentNode;
}
var html = self.controls.getHTML();
if (!isChild && html.className !== "date-picker-input") {
html.className = "date-picker-input";
self.commit();
}
});
datepicker.appendChild(this.controls.getHTML());
datepicker.appendChild(content);
this.html = datepicker;
this.body = body;
//Appending HTML to options.parent
var parent;
if (typeof this.context === "string") {
parent = document.querySelector(this.context);
parent.appendChild(this.html);
} else if (this.context.nodeType !== undefined) {
parent = this.context;
parent.appendChild(this.html);
}
};
DatePicker.prototype.onModeBtnClick = function(span) {
var buttons = this.html.children[1].children[0];
buttons.current.className = "date-picker-mode-button";
buttons.current = span;
this.changeScale(span.scale);
this.emit(this.mediation.events.broadcast.pcupdate, { scale: span.scale });
buttons.current.className = "date-picker-mode-button active";
};
/**
* Initializes the SVG icons for the DatePicker
* @param options <Object> List of options for the DatePicker
**/
DatePicker.prototype.generateSVG = function(icons) {
//If icons are already set, return
if (document.querySelector("svg#dp-icons")) {
return document.querySelector("svg#dp-icons");
}
var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
idsmall = ['arrow-prev-small', 'arrow-next-small'],
idbig = ['arrow-prev-big', 'arrow-next-big'];
svg.id = "dp-icons";
svg.style.display = "none";
this.svg = svg;
this._initIcons(idbig, icons);
this._initIcons(idsmall, icons);
document.querySelector('body').appendChild(svg);
return svg;
};
DatePicker.prototype._initIcons = function(ids, icons) {
var valid = false;
var id;
var elements = [],
element;
if (icons !== undefined) {
valid = true;
for (var i = 0; i < ids.length; i++) {
id = ids[i];
//Verifies if the icons passed are HTMLElements
try {
if (typeof icons[id] === "string") {
element = document.createElement('div');
element.innerHTML = icons[id];
element = element.firstChild;
element.id = id;
elements.push(element);
} else if (icons[id].nodeType !== undefined) {
elements.push(icons[id]);
} else {
throw new Error("Illegal argument: Icons passed in option.icons are not HTML string nor HTMLElements. Falling back to base icons for the group of icons " + ids.toString() + ".");
}
} catch (e) {
valid = false;
console.error(e);
}
}
}
if (!valid) {
for (var j = 0; j < ids.length; j++) {
id = ids[j];
element = document.createElement('svg');
element.innerHTML = DatePicker.prototype.defaults.icons[id];
element = element.firstChild.firstChild;
this.svg.appendChild(element);
}
} else {
for (var k = 0; k < elements.length; k++) {
this.svg.appendChild(elements[k]);
}
}
};
//Fixes references to inline SVG elements when the <base> tag is in use.
//Related to http://stackoverflow.com/a/18265336/796152
//https://gist.github.com/leonderijke/c5cf7c5b2e424c0061d2
DatePicker.prototype.patchSVGURLs = function() {
if (document.querySelector("base")) {
var baseUrl = window.location.href
.replace(window.location.hash, "");
[].slice.call(document.querySelectorAll("use[*|href]"))
.filter(function(element) {
return (element.getAttribute("xlink:href").indexOf("#") === 0);
})
.forEach(function(element) {
element.setAttribute("xlink:href", baseUrl + element.getAttribute("xlink:href"));
});
}
};
DatePicker.prototype.generateEvents = function() {
//Commit & rollback
this.mediation.events.broadcast.commit = this._constructEventString(Events.scope.broadcast, Events.desc.commit);
this.mediation.events.broadcast.rollback = this._constructEventString(Events.scope.broadcast, Events.desc.rollback);
//Updates
this.mediation.events.broadcast.dupdate = this._constructEventString(Events.scope.broadcast, Events.desc.update.day);
this.mediation.events.broadcast.wupdate = this._constructEventString(Events.scope.broadcast, Events.desc.update.week);
this.mediation.events.broadcast.mupdate = this._constructEventString(Events.scope.broadcast, Events.desc.update.month);
this.mediation.events.broadcast.yupdate = this._constructEventString(Events.scope.broadcast, Events.desc.update.year);
this.mediation.events.broadcast.pcupdate = this._constructEventString(Events.scope.broadcast, Events.desc.update.controls);
//Requests
this.mediation.events.broadcast.decday = this._constructEventString(Events.scope.broadcast, Events.desc.request.decrement.day);
this.mediation.events.broadcast.decweek = this._constructEventString(Events.scope.broadcast, Events.desc.request.decrement.week);
this.mediation.events.broadcast.decmonth = this._constructEventString(Events.scope.broadcast, Events.desc.request.decrement.month);
this.mediation.events.broadcast.decyear = this._constructEventString(Events.scope.broadcast, Events.desc.request.decrement.year);
this.mediation.events.broadcast.incday = this._constructEventString(Events.scope.broadcast, Events.desc.request.increment.day);
this.mediation.events.broadcast.incweek = this._constructEventString(Events.scope.broadcast, Events.desc.request.increment.week);
this.mediation.events.broadcast.incmonth = this._constructEventString(Events.scope.broadcast, Events.desc.request.increment.month);
this.mediation.events.broadcast.incyear = this._constructEventString(Events.scope.broadcast, Events.desc.request.increment.year);
};
DatePicker.prototype.subscribe = function() {
//Commit & rollback
this.mediator.subscribe(this.mediation.events.broadcast.commit, this.partials.day);
this.mediator.subscribe(this.mediation.events.broadcast.commit, this.partials.week);
this.mediator.subscribe(this.mediation.events.broadcast.commit, this.partials.month);
this.mediator.subscribe(this.mediation.events.broadcast.commit, this.partials.year);
this.mediator.subscribe(this.mediation.events.broadcast.rollback, this.partials.day);
this.mediator.subscribe(this.mediation.events.broadcast.rollback, this.partials.week);
this.mediator.subscribe(this.mediation.events.broadcast.rollback, this.partials.month);
this.mediator.subscribe(this.mediation.events.broadcast.rollback, this.partials.year);
//Updates
this.mediator.subscribe(this.mediation.events.broadcast.gupdate, this.partials.day);
this.mediator.subscribe(this.mediation.events.broadcast.gupdate, this.partials.week);
this.mediator.subscribe(this.mediation.events.broadcast.gupdate, this.partials.month);
this.mediator.subscribe(this.mediation.events.broadcast.gupdate, this.partials.year);
this.mediator.subscribe(this.mediation.events.broadcast.dupdate, this.partials.day);
this.mediator.subscribe(this.mediation.events.broadcast.wupdate, this.partials.week);
this.mediator.subscribe(this.mediation.events.broadcast.mupdate, this.partials.month);
this.mediator.subscribe(this.mediation.events.broadcast.yupdate, this.partials.year);
this.mediator.subscribe(this.mediation.events.broadcast.gupdate, this.controls);
this.mediator.subscribe(this.mediation.events.broadcast.pcupdate, this.controls);
//Requests
this.mediator.subscribe(this.mediation.events.broadcast.decday, this.partials.day);
this.mediator.subscribe(this.mediation.events.broadcast.decweek, this.partials.week);
this.mediator.subscribe(this.mediation.events.broadcast.decmonth, this.partials.day);
this.mediator.subscribe(this.mediation.events.broadcast.decyear, this.partials.day);
this.mediator.subscribe(this.mediation.events.broadcast.incday, this.partials.day);
this.mediator.subscribe(this.mediation.events.broadcast.incweek, this.partials.week);
this.mediator.subscribe(this.mediation.events.broadcast.incmonth, this.partials.day);
this.mediator.subscribe(this.mediation.events.broadcast.incyear, this.partials.day);
this.partials.day.subscribe(this);
this.partials.week.subscribe(this);
this.partials.month.subscribe(this);
this.partials.year.subscribe(this);
this.controls.subscribe(this);
};
/**
* @override
**/
DatePicker.prototype.notify = function(e) {
if (e.scope === Events.scope.emit) {
switch (e.desc) {
//Updates
case Events.desc.update.day:
this.emit(this.mediation.events.broadcast.wupdate, e.data);
this.emit(this.mediation.events.broadcast.mupdate, e.data);
this.emit(this.mediation.events.broadcast.yupdate, e.data);
this.emit(this.mediation.events.broadcast.pcupdate, e.data);
break;
case Events.desc.update.week:
this.emit(this.mediation.events.broadcast.dupdate, e.data);
this.emit(this.mediation.events.broadcast.mupdate, e.data);
this.emit(this.mediation.events.broadcast.yupdate, e.data);
this.emit(this.mediation.events.broadcast.pcupdate, e.data);
break;
case Events.desc.update.month:
this.emit(this.mediation.events.broadcast.dupdate, e.data);
this.emit(this.mediation.events.broadcast.wupdate, e.data);
this.emit(this.mediation.events.broadcast.yupdate, e.data);
this.emit(this.mediation.events.broadcast.pcupdate, e.data);
break;
case Events.desc.update.year:
this.emit(this.mediation.events.broadcast.dupdate, e.data);
this.emit(this.mediation.events.broadcast.wupdate, e.data);
this.emit(this.mediation.events.broadcast.mupdate, e.data);
this.emit(this.mediation.events.broadcast.pcupdate, e.data);
break;
//Requests
case Events.desc.request.decrement.day:
this.emit(this.mediation.events.broadcast.decday, e.data);
break;
case Events.desc.request.decrement.week:
this.emit(this.mediation.events.broadcast.decweek, e.data);
break;
case Events.desc.request.decrement.month:
this.emit(this.mediation.events.broadcast.decmonth, e.data);
break;
case Events.desc.request.decrement.year:
this.emit(this.mediation.events.broadcast.decyear, e.data);
break;
case Events.desc.request.increment.day:
this.emit(this.mediation.events.broadcast.incday, e.data);
break;
case Events.desc.request.increment.week:
this.emit(this.mediation.events.broadcast.incweek, e.data);
break;
case Events.desc.request.increment.month:
this.emit(this.mediation.events.broadcast.incmonth, e.data);
break;
case Events.desc.request.increment.year:
this.emit(this.mediation.events.broadcast.incyear, e.data);
break;
case Events.desc.commit:
this.commit();
break;
default:
break;
}
if (e.data.date instanceof Date) {
this.date = new Date(e.data.date.getUTCFullYear(), e.data.date.getUTCMonth(), e.data.date.getUTCDate());
this.callCallback(DatePicker.prototype.enum.callbacks.dateUpdate, e.data.date);
}
}
Colleague.prototype.notify.call(this, e);
};
DatePicker.prototype.deepCopyObject = function(options) {
return deepCopyObject(options, {});
};
var deepCopyObject = function(object, copy) {
for (var key in object) {
if (typeof object[key] === "string" || typeof object[key] === "number" || typeof object[key] === "function") {
copy[key] = object[key];
} else if (typeof object[key] === "object" && object[key] !== null) {
if (object[key] instanceof Date) {
object[key].setHours(0, 0, 0, 0);
copy[key] = new Date(object[key].getUTCFullYear(), object[key].getUTCMonth(), object[key].getUTCDate());
} else if (object[key].nodeType !== undefined) {
copy[key] = object[key];
} else {
copy[key] = deepCopyObject(object[key], {});
}
}
}
return copy;
};
window.DatePicker = DatePicker;
return window.DatePicker;
})();<file_sep>var Calendar =
(function() {
function Calendar(options, component) {
//super()
component = component === undefined ? Calendar.prototype.component : component;
Colleague.call(this, options.mediator, component);
this.mediation.events.emit.commit = this._constructEventString(Events.scope.emit, Events.desc.commit);
this.mediation.events.emit.cupdate = this._constructEventString(Events.scope.emit, Events.desc.update.cal);
//Upper/Lower bounds to date value
this.min_date = options.min_date instanceof Date ?
new Date(options.min_date.getUTCFullYear(), options.min_date.getUTCMonth(), options.min_date.getUTCDate()) :
undefined;
this.max_date = options.max_date instanceof Date && options.max_date > this.min_date ?
new Date(options.max_date.getUTCFullYear(), options.max_date.getUTCMonth(), options.max_date.getUTCDate()) :
undefined;
//Date that is modified by the user
this.date = new Date(options.date.getUTCFullYear(), options.date.getUTCMonth(), options.date.getUTCDate());
//Scale for this instance
this.scale = (options.scale && Calendar.prototype.enum.scales[options.scale]) ?
Calendar.prototype.enum.scales[options.scale] :
Calendar.prototype.enum.scales.day;
this.months = {};
this.html = this.getCalendarHTML();
}
//Binding the prototype of the Parent object
//Properties will be overriden on this one.
Calendar.prototype = Object.create(Colleague.prototype);
//Binding the constructor to the prototype
Calendar.prototype.constructor = Colleague;
//Component for Event Strings
Calendar.prototype.component = 'CALENDAR';
Calendar.prototype.enum = {
scales: {
day: "day",
week: "week",
}
};
Calendar.prototype.getHTML = function() {
return this.html;
};
Calendar.prototype.getDate = function() {
return this.prev_date;
};
Calendar.prototype.setDate = function(date) {
if (date instanceof Date && (this.min_date === undefined || date >= this.min_date) && (this.max_date === undefined || date <= this.max_date)) {
this.date = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
}
};
Calendar.prototype._initCalendarIndex = function() {
if (this.months[this.date.getUTCFullYear()] === undefined) {
this.months[this.date.getUTCFullYear()] = {};
}
};
Calendar.prototype.getCalendarHTML = function() {
this._initCalendarIndex();
var calendar;
if (this.months[this.date.getUTCFullYear()][this.date.getUTCMonth()] !== undefined) {
calendar = this.months[this.date.getUTCFullYear()][this.date.getUTCMonth()];
return calendar;
} else {
calendar = this.generateHTML();
this.months[this.date.getUTCFullYear()][this.date.getUTCMonth()] = calendar;
return calendar;
}
};
Calendar.prototype.updateCalendarHTML = function() {
var oldc = this.html,
parentNode = this.html.parentNode;
if (!(oldc.cdata.year === this.date.getUTCFullYear() && oldc.cdata.month === this.date.getUTCMonth())) {
parentNode.removeChild(oldc);
this.html = this.getCalendarHTML();
parentNode.appendChild(this.html);
this.updateSelection();
}
};
Calendar.prototype.generateHTML = function() {
var self = this,
calendar = document.createElement('div'),
daysInMonth = DateUtils.daysInMonth(this.date.getUTCFullYear(), this.date.getUTCMonth()),
daysInPrevMonth = DateUtils.daysInMonth(this.date.getUTCFullYear(), NumberUtils.mod(this.date.getUTCMonth() - 1, 12)),
firstDayOfMonth = DateUtils.firstOfMonth(this.date),
callback;
if (this.scale === Calendar.prototype.enum.scales.day) {
callback = function(e) {
self.onSpanClick(e.target);
};
} else if (this.scale === Calendar.prototype.enum.scales.week) {
callback = function(e) {
self.onRowClick(e.target);
};
}
calendar.className = "date-picker-month-calendar";
var row, span, rows = [],
spans = [],
day = 1;
//Going through weeks
for (var i = 0; i < 6; i++) {
//Creating week
row = document.createElement('div');
row.className = "date-picker-week-row";
if (this.scale === Calendar.prototype.enum.scales.week) {
row.addEventListener('click', callback);
}
var j = 0;
if (i === 0) {
//First week potentially has days from another month.
for (; j < firstDayOfMonth; j++) {
span = document.createElement('span');
span.className = "date-picker-day-cell disabled";
span.innerHTML = daysInPrevMonth - (firstDayOfMonth - (j + 1));
span.cdata = {
selectable: false,
day: daysInPrevMonth - (firstDayOfMonth - j),
month: NumberUtils.mod(this.date.getUTCMonth() - 1, 12),
year: NumberUtils.mod(this.date.getUTCMonth() - 1, 12) === 11 ? this.date.getUTCFullYear() - 1 : this.date.getUTCFullYear()
};
row.appendChild(span);
spans.push(span);
}
}
//Starting at j = x where x is either 0 if past first week or x is firstDayOfMonth
for (; j < 7; j++) {
span = document.createElement('span');
span.cdata = {
selectable: day <= daysInMonth,
//Takes in account days of next month
day: day > daysInMonth ? day - daysInMonth : day,
month: day > daysInMonth ? NumberUtils.mod(this.date.getUTCMonth() + 1, 12) : this.date.getUTCMonth(),
year: day > daysInMonth && NumberUtils.mod(this.date.getUTCMonth() + 1, 12) === 0 ?
this.date.getUTCFullYear() + 1 : this.date.getUTCFullYear()
};
//Default class
span.className = "date-picker-day-cell";
//If greater than daysInMonth, the date is in next month and should be disabled.
if (day > daysInMonth) {
span.className = "date-picker-day-cell disabled";
} else if (span.cdata.day === this.date.getUTCDate()) {
if (this.scale === Calendar.prototype.enum.scales.day) {
span.className = "date-picker-day-cell active";
calendar.current = span;
} else if (span.cdata.day === this.date.getUTCDate() && this.scale === Calendar.prototype.enum.scales.week) {
row.className = "date-picker-week-row active";
calendar.current = span;
}
}
span.innerHTML = span.cdata.day;
if (this.scale === Calendar.prototype.enum.scales.day) {
span.addEventListener('click', callback);
}
row.appendChild(span);
spans.push(span);
day++;
}
row.cdata = {
start: new Date(
row.children[0].cdata.year,
row.children[0].cdata.month,
row.children[0].cdata.day
),
end: new Date(
row.children[6].cdata.year,
row.children[6].cdata.month,
row.children[6].cdata.day
),
};
row.cdata.disabled = self._isRowDisabled(row);
rows.push(row);
calendar.appendChild(row);
}
calendar.cdata = {
year: this.date.getUTCFullYear(),
month: this.date.getUTCMonth()
};
return calendar;
};
Calendar.prototype._isRowDisabled = function(row) {
if ((this.min_date !== undefined && row.cdata.end < this.min_date) ||
(this.max_date !== undefined && row.cdata.start > this.max_date)) {
return true;
}
for (var i = 0; i < row.children.length; i++) {
if (row.children[i].className.indexOf("disabled") === -1) {
return false;
}
}
return true;
};
Calendar.prototype.updateSelection = function(span) {
var calendar = this.html;
this.removeSelection();
if (span === undefined) {
for (var i = 0; i < this.html.children.length; i++) {
for (var j = 0; j < this.html.children[i].children.length; j++) {
this.applyClass(this.html.children[i].children[j]);
}
this.html.children[i].cdata.disabled = this._isRowDisabled(this.html.children[i]);
}
} else {
this.newSelection(span);
}
};
Calendar.prototype.applyClass = function(span) {
var span_date = new Date(span.cdata.year, span.cdata.month, span.cdata.day);
span.className = "date-picker-day-cell disabled";
if ((this.min_date !== undefined && span_date < this.min_date) ||
(this.max_date !== undefined && span_date > this.max_date)) {
span.className = "date-picker-day-cell disabled";
} else if (span.cdata.day === this.date.getUTCDate() && span.cdata.month === this.date.getUTCMonth()) {
this.newSelection(span);
} else if (span.cdata.month == this.date.getUTCMonth()) {
span.className = "date-picker-day-cell";
}
};
Calendar.prototype.newSelection = function(span) {
if (span.cdata.day === this.date.getUTCDate()) {
this.html.current = span;
if (this.scale === Calendar.prototype.enum.scales.day) {
this.html.current.className = "date-picker-day-cell active";
} else if (this.scale === Calendar.prototype.enum.scales.week) {
this.html.current.parentNode.className = "date-picker-week-row active";
}
}
};
Calendar.prototype.removeSelection = function() {
if (this.scale === Calendar.prototype.enum.scales.day) {
this.html.current.className = "date-picker-day-cell";
} else if (this.scale === Calendar.prototype.enum.scales.week) {
this.html.current.parentNode.className = "date-picker-week-row";
}
};
Calendar.prototype.onRowClick = function(target) {
if (target.className.indexOf("date-picker-day-cell") !== -1) {
target = target.parentNode;
}
if (target.cdata.disabled === false) {
this.date.setUTCDate(target.cdata.start.getUTCDate());
this.emit(this.mediation.events.emit.cupdate, { date: new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate()) });
this.updateSelection(target.children[0]);
}
};
Calendar.prototype.onSpanClick = function(span) {
var daysInMonth = DateUtils.daysInMonth(this.date.getUTCFullYear(), this.date.getUTCMonth());
if (span.cdata.selectable === true && span.cdata.day <= daysInMonth && span.cdata.day > 0) {
this.date.setUTCDate(span.cdata.day);
this.emit(this.mediation.events.emit.cupdate, { date: new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate()) });
this.updateSelection(span);
}
};
Calendar.prototype.subscribe = function(parent) {
if (parent !== undefined) {
this.mediator.subscribe(this.mediation.events.emit.cupdate, parent);
this.mediator.subscribe(this.mediation.events.emit.commit, parent);
}
};
Calendar.prototype.notify = function(e) {
if (e.scope === Events.scope.broadcast) {
switch (e.desc) {
case Events.desc.update.partial:
if (e.data.min_date !== undefined && e.data.min_date instanceof Date &&
(this.max_date === undefined || e.data.min_date < this.max_date)) {
this.min_date = new Date(e.data.min_date.getUTCFullYear(), e.data.min_date.getUTCMonth(), e.data.min_date.getUTCDate());
if (this.date < this.min_date) {
this.setDate(this.min_date);
this.emit(this.mediation.events.emit.cupdate, { date: new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate()) });
}
}
if (e.data.max_date !== undefined && e.data.max_date instanceof Date &&
(this.min_date === undefined || e.data.max_date > this.min_date)) {
this.max_date = new Date(e.data.max_date.getUTCFullYear(), e.data.max_date.getUTCMonth(), e.data.max_date.getUTCDate());
if (this.date > this.max_date) {
this.setDate(this.max_date);
this.emit(this.mediation.events.emit.cupdate, { date: new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate()) });
}
}
case Events.desc.update.cal:
if (e.data.date !== undefined) {
this.setDate(e.data.date);
}
this.updateSelection();
this.updateCalendarHTML();
break;
case Events.desc.request.decrement.day:
this.setDate(DateUtils.dateAddDays(this.date, -1));
this.emit(this.mediation.events.emit.cupdate, { date: new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate()) });
if (e.data.commit) {
this.emit(this.mediation.events.emit.commit, { date: new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate()) });
}
this.updateCalendarHTML();
this.updateSelection();
break;
case Events.desc.request.increment.day:
this.setDate(DateUtils.dateAddDays(this.date, 1));
this.emit(this.mediation.events.emit.cupdate, { date: new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate()) });
if (e.data.commit) {
this.emit(this.mediation.events.emit.commit, { date: new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate()) });
}
this.updateCalendarHTML();
this.updateSelection();
break;
case Events.desc.request.decrement.week:
console.log(DateUtils.getDateInPreviousWeek(this.date));
this.setDate(DateUtils.getDateInPreviousWeek(this.date));
this.emit(this.mediation.events.emit.cupdate, { date: new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate()) });
if (e.data.commit) {
this.emit(this.mediation.events.emit.commit, { date: new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate()) });
}
this.updateCalendarHTML();
this.updateSelection();
break;
case Events.desc.request.increment.week:
console.log(DateUtils.getDateInPreviousWeek(this.date));
this.setDate(DateUtils.getDateInNextWeek(this.date));
this.emit(this.mediation.events.emit.cupdate, { date: new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate()) });
if (e.data.commit) {
this.emit(this.mediation.events.emit.commit, { date: new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate()) });
}
this.updateCalendarHTML();
this.updateSelection();
break;
default:
break;
}
}
this.constructor.prototype.notify.call(this, e);
};
return Calendar;
})();<file_sep>var MonthIncrementSlider = (function() {
function MonthIncrementSlider(options, component) {
//super()
component = component === undefined ? MonthIncrementSlider.prototype.component : component;
IncrementSlider.call(this, options, component);
this.mediation.events.emit.commit = this._constructEventString(Events.scope.emit, Events.desc.commit);
this.mediation.events.emit.mupdate = this._constructEventString(Events.scope.emit, Events.desc.update.mis);
this.lang = options.lang !== undefined &&
MonthIncrementSlider.prototype.enum.languages[options.lang] !== undefined ?
MonthIncrementSlider.prototype.enum.languages[options.lang] : 'en';
this.date = this.value;
this.min_date = this.min_value;
this.max_date = this.max_value;
this.generateHTML();
}
//Binding the prototype of the Parent object
//Properties will be overriden on this one.
MonthIncrementSlider.prototype = Object.create(IncrementSlider.prototype);
//Binding the constructor to the prototype
MonthIncrementSlider.prototype.constructor = IncrementSlider;
//Component for Event Strings
MonthIncrementSlider.prototype.component = 'MINCSLIDER';
//Enumerable Values
//Building upon prototype
MonthIncrementSlider.prototype.enum = IncrementSlider.prototype.enum;
MonthIncrementSlider.prototype.enum.languages = {
en: 'en',
fr: 'fr'
};
/**
* @override
**/
MonthIncrementSlider.prototype.setValue = function(value) {
this.date = new Date(value.getUTCFullYear(), value.getUTCMonth(), value.getUTCDate());
this.value = this.date;
this.setUIValue();
this.callCallback(IncrementSlider.prototype.enum.callbacks.valuechange);
};
MonthIncrementSlider.prototype.setMinValue = function(value) {
if (value instanceof Date &&
(this.max_date === undefined || value < this.max_date)) {
this.min_date = new Date(value.getUTCFullYear(), value.getUTCMonth(), value.getUTCDate());
this.min_value = this.min_date;
this.callCallback(IncrementSlider.prototype.enum.callbacks.minchange);
}
};
MonthIncrementSlider.prototype.setMaxValue = function(value) {
if (value instanceof Date &&
(this.min_date === undefined || value > this.min_date)) {
this.max_date = new Date(value.getUTCFullYear(), value.getUTCMonth(), value.getUTCDate());
this.max_value = this.max_date;
this.callCallback(IncrementSlider.prototype.enum.callbacks.maxchange);
}
};
/**
* @override
**/
MonthIncrementSlider.prototype.setUIValue = function() {
this.input.children[0].innerHTML = DateUtils.getMonthString(this.date.getUTCMonth(), this.lang);
};
/**
* @override
**/
MonthIncrementSlider.prototype.testMin = function() {
return this.min_date !== undefined &&
this.min_date.getUTCFullYear() === this.date.getUTCFullYear() && this.min_date.getUTCMonth() === this.date.getUTCMonth();
};
/**
* @override
**/
MonthIncrementSlider.prototype.testMax = function() {
return this.max_date !== undefined &&
this.max_date.getUTCFullYear() === this.date.getUTCFullYear() && this.max_date.getUTCMonth() === this.date.getUTCMonth();
};
/**
* @override
**/
MonthIncrementSlider.prototype.onPrevClick = function() {
if (this.prev.isDisabled === true) {
return;
}
var self = this;
var year = this.date.getUTCFullYear(),
month = NumberUtils.mod(this.date.getUTCMonth() - 1, 12),
apply = false;
//If no min_date, no constraints.
if (this.min_date === undefined || this.min_date.getUTCFullYear() < year - 1) {
apply = true;
this.decrementMonth();
if (month === 11) {
this.date.setUTCFullYear(year - 1);
}
//If min year is = to year, must check for month and day.
} else if (this.min_date.getUTCFullYear() === year && month !== 11) {
//Check if action is valid
if (this.min_date.getUTCMonth() < month || this.min_date.getUTCMonth() === month) {
apply = true;
this.decrementMonth();
}
//Granted min month = month
//Resets the day if conflict between min day and currently selected day
if (this.min_date.getUTCMonth() === month && this.min_date.getUTCDay() > this.date.getUTCDay()) {
this.date.setUTCDate(this.min_date.getUTCDate());
}
} else if (this.min_date.getUTCFullYear() === year - 1 && month === 11) {
if (this.min_date.getUTCMonth() < month || this.min_date.getUTCMonth() === month) {
apply = true;
this.decrementMonth();
this.date.setUTCFullYear(year - 1);
}
if (this.min_date.getUTCMonth() === month && this.min_date.getUTCDay() > this.date.getUTCDay()) {
this.date.setUTCDate(this.min_date.getUTCDate());
}
} else if (this.min_date.getUTCFullYear() === year - 1 && month !== 11) {
apply = true;
this.decrementMonth();
}
if (apply) {
this.setValue(this.date);
this.updateUIControls();
this.emit(this.mediation.events.emit.mupdate, { date: this.date });
IncrementSlider.prototype.onPrevClick.call(this);
}
};
/**
* @override
**/
MonthIncrementSlider.prototype.onNextClick = function() {
if (this.next.isDisabled === true) {
return;
}
var year = this.date.getUTCFullYear(),
month = NumberUtils.mod(this.date.getUTCMonth() + 1, 12),
apply = false;
//If no max_date, no constraints.
if (this.max_date === undefined || this.max_date.getUTCFullYear() > year + 1) {
apply = true;
this.incrementMonth();
if (month === 0) {
this.date.setUTCFullYear(year + 1);
}
//If max year is = to year, must check for month and day.
} else if (this.max_date.getUTCFullYear() === year && month !== 0) {
//Check if action is valid
if (this.max_date.getUTCMonth() > month || this.max_date.getUTCMonth() === month) {
apply = true;
this.incrementMonth();
}
//Granted max month = month
//Resets the day if conflict between max day and currently selected day
if (this.max_date.getUTCMonth() === month && this.max_date.getUTCDay() < this.date.getUTCDay()) {
this.date.setUTCDate(this.max_date.getUTCDate());
}
} else if (this.max_date.getUTCFullYear() === year + 1 && month === 0) {
if (this.max_date.getUTCMonth() > month || this.max_date.getUTCMonth() === month) {
apply = true;
this.incrementMonth();
this.date.setUTCFullYear(year + 1);
}
if (this.max_date.getUTCMonth() === month && this.max_date.getUTCDay() < this.date.getUTCDay()) {
this.date.setUTCDate(this.max_date.getUTCDate());
}
} else if (this.max_date.getUTCFullYear() === year + 1 && month !== 0) {
apply = true;
this.incrementMonth();
} else {
//do nothing
}
if (apply) {
this.setValue(this.date);
this.updateUIControls();
this.emit(this.mediation.events.emit.mupdate, { date: this.date });
IncrementSlider.prototype.onNextClick.call(this);
}
};
MonthIncrementSlider.prototype.incrementMonth = function() {
var month = NumberUtils.mod(this.date.getUTCMonth() + 1, 12),
daysInMonth = month !== 0 ?
DateUtils.daysInMonth(this.date.getUTCFullYear(), month) :
DateUtils.daysInMonth(this.date.getUTCFullYear() + 1, month);
//To prevent invalid dates like Feb 30th
//Takes in account change of year
if (this.date.getUTCDate() > daysInMonth) {
this.date.setUTCDate(daysInMonth);
}
this.date.setUTCMonth(month);
};
MonthIncrementSlider.prototype.decrementMonth = function() {
var month = NumberUtils.mod(this.date.getUTCMonth() - 1, 12),
daysInMonth = month !== 11 ?
DateUtils.daysInMonth(this.date.getUTCFullYear(), month) :
DateUtils.daysInMonth(this.date.getUTCFullYear() - 1, month);
//To prevent invalid dates like Feb 30th
//Takes in account change of year
if (this.date.getUTCDate() > daysInMonth) {
this.date.setUTCDate(daysInMonth);
}
this.date.setUTCMonth(month);
};
MonthIncrementSlider.prototype.subscribe = function(parent) {
if (parent !== undefined) {
this.mediator.subscribe(this.mediation.events.emit.mupdate, parent);
this.mediator.subscribe(this.mediation.events.emit.commit, parent);
}
};
/**
* @override
**/
MonthIncrementSlider.prototype.notify = function(e) {
if (e.scope === Events.scope.broadcast) {
switch (e.desc) {
case Events.desc.update.partial:
if (e.data.min_date !== undefined) {
this.setMinValue(e.data.min_date);
}
if (e.data.max_date !== undefined) {
this.setMaxValue(e.data.max_date);
}
case Events.desc.update.mis:
if (e.data.date !== undefined && e.data.date instanceof Date) {
this.setValue(e.data.date);
}
this.updateUIControls();
break;
case Events.desc.request.decrement.month:
this.onPrevClick();
if (e.data.commit) {
this.emit(this.mediation.events.emit.commit, { date: new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate()) });
}
break;
case Events.desc.request.increment.month:
this.onNextClick();
if (e.data.commit) {
this.emit(this.mediation.events.emit.commit, { date: new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate()) });
}
break;
default:
break;
}
}
IncrementSlider.prototype.notify.call(this, e);
};
return MonthIncrementSlider;
})();<file_sep>var DateUtils = {
//Normally one shouldn't include translations directly into code.
//However in this case there is so little translations that it doesn't matter.
months: {
en: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
fr: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"]
},
days: {
en: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
fr: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"],
},
daysuffix: {
en: ['th','st','nd','rd','th'],
fr: ['er','']
},
getMonthString: function(month, language){
return this.months[language][month];
},
isLeapYear: function(year){
return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
},
daysInMonth: function(year, month){
return [31, (this.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
},
weeksInMonth: function(year, month){
var weeks = month == 2 ? ((this.isLeapYear(year)) ? 5 : 4) : 5;
return this.firstOfMonth(new Date(year,month, 1)) > 4 ? weeks + 1 : weeks;
},
firstOfMonth: function(date){
return new Date(date.getUTCFullYear(), date.getUTCMonth(), 1).getDay();
},
getDateInPreviousWeek: function(date){
var d = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
d.setUTCDate(d.getUTCDate() - 7);
return d;
},
getDateInNextWeek: function(date){
var d = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
d.setUTCDate(d.getUTCDate() + 7);
return d;
},
dateAddDays: function(date, days){
var d = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
d.setUTCDate(d.getUTCDate() + days);
return d;
},
//Get the week's first and last days.
getWeekFALDays: function(date){
var week = {};
week.start = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
week.start.setDate(week.start.getUTCDate() - week.start.getUTCDay());
week.end = new Date(week.start.getUTCFullYear(), week.start.getUTCMonth(), week.start.getUTCDate());
week.end.setDate(week.end.getUTCDate() + 6);
return week;
},
//http://stackoverflow.com/a/26426761/4442749
getDOY: function(date) {
var dayCount = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
var mn = date.getMonth();
var dn = datestr.getDate();
var dayOfYear = dayCount[mn] + dn;
if(mn > 1 && this.isLeapYear()) dayOfYear++;
return dayOfYear;
},
//http://stackoverflow.com/a/6117889/4442749
getWeekNumber: function (d) {
// Copy date so don't modify original
d = new Date(+d);
d.setHours(0,0,0);
// Set to nearest Thursday: current date + 4 - current day number
// Make Sunday's day number 7
d.setDate(d.getDate() + 4 - (d.getDay()||7));
// Get first day of year
var yearStart = new Date(d.getFullYear(),0,1);
// Calculate full weeks to nearest Thursday
var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
// Return array of year and week number
return [d.getFullYear(), weekNo];
},
//Take note that the %U will return 1-52 rather than 0-53
formatDate: function(date, formatstr, language){
var datestr = "", i = 0, op;
language = language === undefined || this.months[language] === undefined ?
'en':
language;
while(formatstr !== ""){
if(formatstr.charAt(0) === "%"){
op = formatstr.substring(0,2);
formatstr = formatstr.substring(2);
switch (op) {
case '%a':
datestr += this.days[language][date.getUTCDay()].substring(0,3);
break;
case '%b':
datestr += this.months[language][date.getUTCMonth()].substring(0,3);
break;
case '%c':
datestr += date.getUTCMonth() + 1;
break;
case '%D':
datestr += date.getUTCDate() + this.daysuffix[Math.min(date.getUTCDate(), this.daysuffix.length-1)];
break;
case '%d':
datestr += (date.getUTCDate() < 10)? '0' + date.getUTCDate(): date.getUTCDate();
break;
case '%e':
datestr += date.getUTCDate();
break;
case '%j':
datestr += this.getDOY(date);
break;
case '%M':
datestr += this.getMonthString(date.getUTCMonth(), language);
break;
case '%m':
datestr += (date.getUTCMonth() < 10)? '0' + date.getUTCMonth(): date.getUTCMonth();
break;
case '%U':
datestr += this.getWeekNumber(date);
break;
case '%W':
datestr += this.days[language][date.getUTCDay()];
break;
case '%w':
datestr += date.getUTCDay();
break;
case '%Y':
datestr += date.getUTCFullYear();
break;
case '%y':
datestr += date.getUTCFullYear() % 100;
break;
default:
break;
}
}else{
datestr += formatstr.substring(0,1);
formatstr = formatstr.substring(1);
}
}
return datestr;
},
};
<file_sep>var PickerControls = (function() {
function PickerControls(options, component) {
//super()
component = component === undefined ? PickerControls.prototype.component : component;
IncrementSlider.call(this, options, component);
this.generateEvents();
//Upper/Lower bounds to date value
this.min_date = options.min_date instanceof Date ?
new Date(options.min_date.getUTCFullYear(), options.min_date.getUTCMonth(), options.min_date.getUTCDate()) :
undefined;
this.max_date = options.max_date instanceof Date && options.max_date > this.min_date ?
new Date(options.max_date.getUTCFullYear(), options.max_date.getUTCMonth(), options.max_date.getUTCDate()) :
undefined;
this.min_value = this.min_date;
this.max_value = this.max_date;
//Date that is modified by the user
this.date = new Date(options.date.getUTCFullYear(), options.date.getUTCMonth(), options.date.getUTCDate());
//Scale for this instance
this.scale = (options.scale && PickerControls.prototype.enum.scales[options.scale]) ?
PickerControls.prototype.enum.scales[options.scale] :
PickerControls.prototype.enum.scales.day;
this.lang = options.lang !== undefined &&
PickerControls.prototype.enum.languages[options.lang] !== undefined ?
PickerControls.prototype.enum.languages[options.lang] : 'en';
this.generateHTML();
}
//Binding the prototype of the Parent object
//Properties will be overriden on this one.
PickerControls.prototype = Object.create(IncrementSlider.prototype);
//Binding the constructor to the prototype
PickerControls.prototype.constructor = IncrementSlider;
//Component for Event Strings
PickerControls.prototype.component = 'PCONTROLS';
//Enumerable Values
//Building upon prototype
PickerControls.prototype.enum = IncrementSlider.prototype.enum;
PickerControls.prototype.enum.scales = {
day: "day",
week: "week",
month: "month",
year: "year"
};
PickerControls.prototype.enum.languages = {
en: 'en',
fr: 'fr'
};
/**
* @override
**/
PickerControls.prototype.setValue = function(value) {
if (value !== undefined &&
(this.min_date === undefined || value >= this.min_date) &&
(this.max_date === undefined || value <= this.max_date)) {
this.date = new Date(value.getUTCFullYear(), value.getUTCMonth(), value.getUTCDate());
}
switch (this.scale) {
case PickerControls.prototype.enum.scales.day:
case PickerControls.prototype.enum.scales.month:
case PickerControls.prototype.enum.scales.year:
this.period = new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate());
break;
case PickerControls.prototype.enum.scales.week:
this.period = DateUtils.getWeekFALDays(this.date);
break;
}
this.value = this.date;
this.setUIValue();
this.callCallback(PickerControls.prototype.enum.callbacks.valuechange, value);
};
/**
* @override
**/
PickerControls.prototype.setUIValue = function() {
var uivalue = "";
switch (this.scale) {
case PickerControls.prototype.enum.scales.day:
switch (this.lang) {
case PickerControls.prototype.enum.languages.en:
uivalue = DateUtils.formatDate(this.period, '%a, %M %e %Y', this.lang);
break;
case PickerControls.prototype.enum.languages.fr:
uivalue = DateUtils.formatDate(this.period, 'le %e%D %M %Y').toLowerCase();
uivalue = uivalue.charAt(0).toUpperCase() + uivalue.slice(1);
break;
default:
break;
}
break;
case PickerControls.prototype.enum.scales.week:
switch (this.lang) {
case PickerControls.prototype.enum.languages.en:
uivalue = DateUtils.formatDate(this.period.start, '%b %e');
uivalue += " - ";
uivalue += DateUtils.formatDate(this.period.end, '%b %e, %Y');
break;
case PickerControls.prototype.enum.languages.fr:
uivalue = "Semaine du ";
uivalue += DateUtils.formatDate(this.period.start, '%e%D %M');
uivalue += " au ";
uivalue += DateUtils.formatDate(this.period.end, '%e%D %M %Y');
break;
default:
break;
}
break;
case PickerControls.prototype.enum.scales.month:
switch (this.lang) {
case PickerControls.prototype.enum.languages.en:
case PickerControls.prototype.enum.languages.fr:
uivalue = DateUtils.formatDate(this.period, '%M %Y');
break;
default:
break;
}
break;
case PickerControls.prototype.enum.scales.year:
uivalue = this.period.getUTCFullYear();
break;
default:
break;
}
this.input.children[1].innerHTML = uivalue;
};
/**
* @override
**/
PickerControls.prototype.generateHTML = function() {
var self = this;
var inner =
'<svg class="date-picker-global-increment prev"><use xlink:href="#arrow-prev-big"></svg>' +
'<div class="date-picker-date-label"></div>' +
'<svg class="date-picker-global-increment next"><use xlink:href="#arrow-next-big"></svg>';
this.input = document.createElement('div');
this.input.className = "date-picker-input";
this.input.innerHTML = inner;
this.setValue();
this.prev = this.input.children[0];
this.input.children[1].addEventListener('click', function() {
if (self.input.className.indexOf('open') !== -1) {
self.input.className = "date-picker-input";
} else {
self.input.className = "date-picker-input open";
}
});
this.prev.addEventListener('click', function() {
self.onPrevClick();
});
this.next = this.input.children[2];
this.next.addEventListener('click', function() {
self.onNextClick();
});
this.updateUIControls();
};
PickerControls.prototype.updateUIControls = function() {
//Hiding previous button if at the min value
if (this.testMin()) {
this.prev.setAttribute("class", "date-picker-global-increment prev disabled");
this.prev.isDisabled = true;
//Hiding next button if at the max value
} else if (this.testMax()) {
this.next.setAttribute("class", "date-picker-global-increment next disabled");
this.next.isDisabled = true;
//Else making sure button is visible
} else {
if (this.min_value !== undefined) {
this.prev.setAttribute("class", "date-picker-global-increment prev");
this.prev.isDisabled = false;
}
if (this.max_value !== undefined) {
this.next.setAttribute("class", "date-picker-global-increment next");
this.next.isDisabled = false;
}
}
};
/**
* @override
**/
PickerControls.prototype.testMin = function() {
switch (this.scale) {
case PickerControls.prototype.enum.day:
return this.min_date !== undefined && this.min_date === this.date;
case PickerControls.prototype.enum.week:
return this.min_date !== undefined &&
DateUtils.getWeekFALDays(this.min_date).end >= DateUtils.getWeekFALDays(this.date).start;
case PickerControls.prototype.enum.month:
return this.min_date !== undefined &&
this.min_date.getUTCFullYear() === this.date.getUTCFullYear() && this.min_date.getUTCMonth() === this.date.getUTCMonth();
case PickerControls.prototype.enum.year:
return this.min_date !== undefined && this.min_date.getUTCFullYear() === this.date.getUTCFullYear();
}
};
/**
* @override
**/
PickerControls.prototype.testMax = function() {
switch (this.scale) {
case PickerControls.prototype.enum.day:
return this.min_date !== undefined && this.min_date === this.date;
case PickerControls.prototype.enum.week:
return this.max_date !== undefined &&
DateUtils.getWeekFALDays(this.max_date).start <= DateUtils.getWeekFALDays(this.date).end;
case PickerControls.prototype.enum.month:
return this.max_date !== undefined &&
this.max_date.getUTCFullYear() === this.date.getUTCFullYear() && this.max_date.getUTCMonth() === this.date.getUTCMonth();
case PickerControls.prototype.enum.year:
return this.max_date !== undefined && this.max_date.getUTCFullYear() === this.date.getUTCFullYear();
}
};
/**
* @override
**/
PickerControls.prototype.onPrevClick = function() {
if (this.prev.isDisabled === true) {
return;
}
this.decrementDate();
};
PickerControls.prototype.decrementDate = function(commit, scale) {
var e = {};
var decscale;
e.commit = commit === undefined || commit === true;
if (scale !== undefined) {
decscale = scale;
} else {
decscale = this.scale;
}
switch (decscale) {
case PickerControls.prototype.enum.scales.day:
this.emit(this.mediation.events.emit.decday, e);
break;
case PickerControls.prototype.enum.scales.week:
this.emit(this.mediation.events.emit.decweek, e);
break;
case PickerControls.prototype.enum.scales.month:
this.emit(this.mediation.events.emit.decmonth, e);
break;
case PickerControls.prototype.enum.scales.year:
this.emit(this.mediation.events.emit.decyear, e);
break;
}
};
/**
* @override
**/
PickerControls.prototype.onNextClick = function() {
if (this.next.isDisabled === true) {
return;
}
this.incrementDate();
};
PickerControls.prototype.incrementDate = function(commit, scale) {
var e = {};
var incscale;
e.commit = commit === undefined || commit === true;
if (scale !== undefined) {
incscale = scale;
} else {
incscale = this.scale;
}
switch (incscale) {
case PickerControls.prototype.enum.scales.day:
this.emit(this.mediation.events.emit.incday, e);
break;
case PickerControls.prototype.enum.scales.week:
this.emit(this.mediation.events.emit.incweek, e);
break;
case PickerControls.prototype.enum.scales.month:
this.emit(this.mediation.events.emit.incmonth, e);
break;
case PickerControls.prototype.enum.scales.year:
this.emit(this.mediation.events.emit.incyear, e);
break;
}
};
PickerControls.prototype.generateEvents = function() {
this.mediation.events.emit.pcupdate = this._constructEventString(Events.scope.emit, Events.desc.update.pcs);
this.mediation.events.emit.decday = this._constructEventString(Events.scope.emit, Events.desc.request.decrement.day);
this.mediation.events.emit.decweek = this._constructEventString(Events.scope.emit, Events.desc.request.decrement.week);
this.mediation.events.emit.decmonth = this._constructEventString(Events.scope.emit, Events.desc.request.decrement.month);
this.mediation.events.emit.decyear = this._constructEventString(Events.scope.emit, Events.desc.request.decrement.year);
this.mediation.events.emit.incday = this._constructEventString(Events.scope.emit, Events.desc.request.increment.day);
this.mediation.events.emit.incweek = this._constructEventString(Events.scope.emit, Events.desc.request.increment.week);
this.mediation.events.emit.incmonth = this._constructEventString(Events.scope.emit, Events.desc.request.increment.month);
this.mediation.events.emit.incyear = this._constructEventString(Events.scope.emit, Events.desc.request.increment.year);
};
PickerControls.prototype.subscribe = function(parent) {
if (parent !== undefined) {
this.mediator.subscribe(this.mediation.events.emit.pcupdate, parent);
this.mediator.subscribe(this.mediation.events.emit.decday, parent);
this.mediator.subscribe(this.mediation.events.emit.decweek, parent);
this.mediator.subscribe(this.mediation.events.emit.decmonth, parent);
this.mediator.subscribe(this.mediation.events.emit.decyear, parent);
this.mediator.subscribe(this.mediation.events.emit.incday, parent);
this.mediator.subscribe(this.mediation.events.emit.incweek, parent);
this.mediator.subscribe(this.mediation.events.emit.incmonth, parent);
this.mediator.subscribe(this.mediation.events.emit.incyear, parent);
}
};
/**
* @override
**/
PickerControls.prototype.notify = function(e) {
if (e.scope === Events.scope.broadcast) {
switch (e.desc) {
case Events.desc.update.controls:
case Events.desc.update.global:
if (e.data.min_date !== undefined && e.data.min_date instanceof Date &&
(this.max_date === undefined || e.data.min_date < this.max_date)) {
this.min_date = new Date(e.data.min_date.getUTCFullYear(), e.data.min_date.getUTCMonth(), e.data.min_date.getUTCDate());
}
if (e.data.max_date !== undefined && e.data.max_date instanceof Date &&
(this.min_date === undefined || e.data.max_date > this.min_date)) {
this.max_date = new Date(e.data.max_date.getUTCFullYear(), e.data.max_date.getUTCMonth(), e.data.max_date.getUTCDate());
}
if (e.data.scale !== undefined && PickerControls.prototype.enum.scales[e.data.scale] !== undefined) {
this.scale = PickerControls.prototype.enum.scales[e.data.scale];
this.setValue();
}
if (e.data.date !== undefined && e.data.date instanceof Date) {
this.setValue(e.data.date);
}
this.updateUIControls();
break;
default:
break;
}
}
IncrementSlider.prototype.notify.call(this, e);
};
return PickerControls;
})();<file_sep>var NumberUtils = {
mod: function(n, m) {
return ((n % m) + m) % m;
}
};
<file_sep>var IncrementSlider = (function(){
function IncrementSlider(options, component){
//super()
component = component === undefined? IncrementSlider.prototype.component : component;
Colleague.call(this, options.mediator, component);
this.mediation.events.emit.bupdate = this._constructEventString(Events.scope.emit, Events.desc.update.bis);
this.min_value = options.min_value;
this.max_value = options.max_value;
this.value = options.value;
}
//Binding the prototype of the Parent object
//Properties will be overriden on this one.
IncrementSlider.prototype = Object.create(Colleague.prototype);
//Binding the constructor to the prototype
IncrementSlider.prototype.constructor = Colleague;
//Component for Event Strings
IncrementSlider.prototype.component = 'INCSLIDER';
IncrementSlider.prototype.enum = {
callbacks: {
notify: "notify",
emit: "emit",
prev: "prev",
maxchange: "maxchange",
minchange: "minchange",
valuechange: "valuechange",
next: "next",
event: "event"
}
};
IncrementSlider.prototype.generateHTML = function(){
var self = this;
var inner =
'<span class="increment-input-value"></span>' +
'<nav>' +
'<svg class="increment-input-button prev"><use xlink:href="#arrow-prev-small"></svg>' +
'<svg class="increment-input-button next"><use xlink:href="#arrow-next-small"></svg>' +
'</nav>';
this.input = document.createElement('div');
this.input.className = "increment-input";
this.input.innerHTML = inner;
this.setUIValue();
this.prev = this.input.children[1].children[0];
this.prev.addEventListener('click', function(){
self.onPrevClick();
});
this.next = this.input.children[1].children[1];
this.next.addEventListener('click', function(){
self.onNextClick();
});
};
IncrementSlider.prototype.getHTML = function () {
return this.input;
};
IncrementSlider.prototype.getValue = function () {
return this.value;
};
IncrementSlider.prototype.setValue = function(value){
this.value = value;
this.setUIValue();
this.callCallback(IncrementSlider.prototype.enum.callbacks.valuechange);
};
IncrementSlider.prototype.onPrevClick = function () {
this.callCallback(IncrementSlider.prototype.enum.callbacks.prev);
};
IncrementSlider.prototype.onNextClick = function () {
this.callCallback(IncrementSlider.prototype.enum.callbacks.next);
};
IncrementSlider.prototype.setUIValue = function(){
this.input.children[0].innerHTML = this.value;
};
IncrementSlider.prototype.updateUIControls = function(){
//Hiding previous button if at the min value
if(this.testMin()){
this.prev.setAttribute("class", "increment-input-button prev disabled");
this.prev.isDisabled = true;
//Hiding next button if at the max value
}else if(this.testMax()){
this.next.setAttribute("class", "increment-input-button next disabled");
this.next.isDisabled = true;
//Else making sure button is visible
}else{
if(this.min_value !== undefined){
this.prev.setAttribute("class", "increment-input-button prev");
this.prev.isDisabled = false;
}
if(this.max_value !== undefined){
this.next.setAttribute("class", "increment-input-button next");
this.next.isDisabled = false;
}
}
};
IncrementSlider.prototype.testMin = function(){
return this.min_value !== undefined && this.min_value == this.getValue();
};
IncrementSlider.prototype.testMax = function(){
return this.max_value !== undefined && this.max_value == this.getValue();
};
IncrementSlider.prototype.subscribe = function (parent) {
if(parent !== undefined){
this.mediator.subscribe(this.mediation.events.emit.gupdate, parent);
this.mediator.subscribe(this.mediation.events.emit.bupdate, parent);
}
};
return IncrementSlider;
})();
<file_sep>var YDialerIncrementSlider = (function(){
function YDialerIncrementSlider(options, component){
//super()
component = component === undefined? YDialerIncrementSlider.prototype.component : component;
IncrementSlider.call(this, options, component);
this.mediation.events.emit.ydupdate = this._constructEventString(Events.scope.emit, Events.desc.update.yds);
//Upper/Lower bounds to date value
this.min_date = options.min_date instanceof Date ?
new Date(options.min_date.getUTCFullYear(), options.min_date.getUTCMonth(), options.min_date.getUTCDate()) :
undefined;
this.max_date = options.max_date instanceof Date && options.max_date > this.min_date?
new Date(options.max_date.getUTCFullYear(), options.max_date.getUTCMonth(), options.max_date.getUTCDate()) :
undefined;
//Date that is modified by the user
this.date = new Date(options.date.getUTCFullYear(), options.date.getUTCMonth(), options.date.getUTCDate());
this.index = 0;
this.updateRange();
this.generateHTML();
}
//Binding the prototype of the Parent object
//Properties will be overriden on this one.
YDialerIncrementSlider.prototype = Object.create(IncrementSlider.prototype);
//Binding the constructor to the prototype
YDialerIncrementSlider.prototype.constructor = IncrementSlider;
//Component for Event Strings
YDialerIncrementSlider.prototype.component = 'YDINCSLIDER';
YDialerIncrementSlider.prototype.enum = {
callbacks: {
notify: "notify",
emit: "emit",
prev: "prev",
datechange: "datechange",
next: "next",
event: "event"
}
};
YDialerIncrementSlider.prototype.setDate = function(date){
this.date = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
this.callCallback(YDialerIncrementSlider.prototype.enum.callbacks.datechange, date);
};
YDialerIncrementSlider.prototype.setMinValue = function(value){
if(value instanceof Date &&
(this.max_date === undefined || value < this.max_date)){
this.min_date = new Date(value.getUTCFullYear(), value.getUTCMonth(), value.getUTCDate());
this.min_value = this.min_date;
this.callCallback(IncrementSlider.prototype.enum.callbacks.minchange);
}
};
YDialerIncrementSlider.prototype.setMaxValue = function(value){
if(value instanceof Date &&
(this.min_date === undefined || value > this.min_date)){
this.max_date = new Date(value.getUTCFullYear(), value.getUTCMonth(), value.getUTCDate());
this.max_value = this.max_date;
this.callCallback(IncrementSlider.prototype.enum.callbacks.maxchange);
}
};
YDialerIncrementSlider.prototype.updateRange = function () {
var medianyear = this.date.getUTCFullYear(),
factor = (8 - NumberUtils.mod(medianyear, 8));
if(this.range === undefined){
this.range = {};
this.range.max = factor === 8? medianyear : medianyear + factor;
this.range.min = this.range.max - 7;
this.range.init_max = this.range.max;
this.range.init_min = this.range.min;
}else{
this.range.max = factor === 8? medianyear : medianyear + factor;
this.range.min = this.range.max - 7;
}
};
YDialerIncrementSlider.prototype.update = function () {
this.updateRange();
this.index = (this.range.max - this.range.init_max)/8;
};
YDialerIncrementSlider.prototype.onPrevClick = function () {
if(this.prev.isDisabled === true){
return;
}
if(this.min_date === undefined || this.range.max - 8 >= this.min_date.getUTCFullYear()){
this.range.max -= 8 ;
this.range.min -= 8 ;
this.index--;
this.updateUIControls();
this.emit(this.mediation.events.emit.ydupdate, {index: this.index});
IncrementSlider.prototype.onPrevClick.call(this);
}
};
YDialerIncrementSlider.prototype.onNextClick = function () {
if(this.next.isDisabled === true){
return;
}
if(this.max_date === undefined || this.range.min + 8 <= this.max_date.getUTCFullYear()){
this.range.max += 8 ;
this.range.min += 8 ;
this.index++;
this.updateUIControls();
this.emit(this.mediation.events.emit.ydupdate, {index: this.index});
IncrementSlider.prototype.onPrevClick.call(this);
}
};
/**
* @override
**/
YDialerIncrementSlider.prototype.testMin = function () {
return this.min_date !== undefined && this.min_date.getUTCFullYear() >= this.range.min;
};
/**
* @override
**/
YDialerIncrementSlider.prototype.testMax = function () {
return this.max_date !== undefined && this.max_date.getUTCFullYear() <= this.range.max;
};
YDialerIncrementSlider.prototype.subscribe = function (parent) {
if(parent !== undefined){
this.mediator.subscribe(this.mediation.events.emit.ydupdate, parent);
}
};
/**
* @override
**/
YDialerIncrementSlider.prototype.notify = function (e) {
if(e.scope === Events.scope.broadcast){
switch(e.desc){
case Events.desc.update.partial:
if(e.data.min_date !== undefined){
this.setMinValue(e.data.min_date);
}
if(e.data.max_date !== undefined){
this.setMaxValue(e.data.max_date);
}
case Events.desc.update.yds:
if(e.data.date !== undefined && e.data.date instanceof Date){
this.setDate(e.data.date);
this.update();
}
if(this.min_date > this.date){
this.setDate(this.min_date);
this.update();
}
if(this.max_date < this.date){
this.setDate(this.max_date);
this.update();
}
this.updateUIControls();
break;
default:
break;
}
}
IncrementSlider.prototype.notify.call(this, e);
};
return YDialerIncrementSlider;
})();
<file_sep>var gulp = require('gulp');
var gutil = require('gulp-util');
var bower = require('bower');
var include = require('gulp-include');
var sass = require('gulp-sass');
var minifyCss = require('gulp-cssnano');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var paths = {
sass: ['./src/scss/**/*.scss'],
js: ['./src/js/date-picker.js']
};
gulp.task('default', ['dev-sass', 'dev-js']);
gulp.task('dist', ['dist-sass', 'dist-js']);
gulp.task('distmin', ['dist-sassmin', 'dist-jsmin']);
gulp.task('dev-js', function(done) {
gulp.src(paths.js)
.pipe(include())
.on('error', console.log)
.pipe(gulp.dest("./src/"))
.on('end', done);
});
gulp.task('dist-js', function(done) {
gulp.src(paths.js)
.pipe(include())
.on('error', console.log)
.pipe(gulp.dest("./dist/"))
.on('end', done);
});
gulp.task('dist-jsmin', function(done) {
gulp.src(paths.js)
.pipe(include())
.on('error', console.log)
.pipe(uglify(false))
.pipe(rename({ extname: '.min.js' }))
.pipe(gulp.dest("./dist/"))
.on('end', done);
});
gulp.task('dev-sass', function(done) {
gulp.src(paths.sass)
.pipe(sass({
errLogToConsole: true
}))
.pipe(rename({ extname: '.css' }))
.pipe(gulp.dest('./src'))
.on('end', done);
});
gulp.task('dist-sass', function(done) {
gulp.src(paths.sass)
.pipe(sass({
errLogToConsole: true
}))
.pipe(rename({ extname: '.css' }))
.pipe(gulp.dest('./dist'))
.on('end', done);
});
gulp.task('dist-sassmin', function(done) {
gulp.src(paths.sass)
.pipe(sass({
errLogToConsole: true
}))
.pipe(minifyCss({
keepSpecialComments: 0
}))
.pipe(rename({ extname: '.min.css' }))
.pipe(gulp.dest('./dist'))
.on('end', done);
});
<file_sep>var Events = {
scope: {
broadcast: "BROADCAST",
emit: "EMIT"
},
desc: {
commit: "COMMIT",
rollback: "ROLLBACK",
request: {
decrement: {
day: "DECREMENTDAY",
week: "DECREMENTWEEK",
month: "DECREMENTMONTH",
year: "DECREMENTYEAR",
},
increment: {
day: "INCREMENTDAY",
week: "INCREMENTWEEK",
month: "INCREMENTMONTH",
year: "INCREMENTYEAR",
}
},
update: {
global: "UPDATE",
controls: "CTRLUPDATE",
day: "DAYSCALEUPDATE",
week: "WEEKSCALEUPDATE",
month: "MONTHSCALEUPDATE",
year: "YEARSCALEUPDATE",
partial: "PARTIALUPDATE",
bis: "ISUPDATE",
pcs: "PCONTROLUPDATE",
yds: "YDISUPDATE",
mis: "MISUPDATE",
yis: "YISUPDATE",
cal: "CALUPDATE",
mdi: "MDIALER",
ydi: "YDIALER"
}
}
};
<file_sep>var Partial = (function() {
function Partial(options, parent) {
//super()
Colleague.call(this, options.mediator, Partial.prototype.component);
//Scale for this instance
this.scale = (options.scale && Partial.prototype.enum.scales[options.scale]) ?
Partial.prototype.enum.scales[options.scale] :
Partial.prototype.enum.scales.day;
this.generateEvents();
//Date that is modified by the user
this.date = new Date(options.date.getUTCFullYear(), options.date.getUTCMonth(), options.date.getUTCDate());
//Saved state in case of rollback
this.prev_date = new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate());
//UI components of which the Partial is comprised.
this.components = {};
this.generateHTML(options);
}
//Binding the prototype of the Parent object
//Properties will be overriden on this one.
Partial.prototype = Object.create(Colleague.prototype);
//Binding the constructor to the prototype
Partial.prototype.constructor = Colleague;
//Component for Event Strings
Partial.prototype.component = 'PARTIAL';
Partial.prototype.enum = {
scales: {
day: "day",
week: "week",
month: "month",
year: "year"
}
};
Partial.prototype.getHTML = function() {
return this.html;
};
Partial.prototype.rollback = function() {
this.date = new Date(this.prev_date.getUTCFullYear(), this.prev_date.getUTCMonth(), this.prev_date.getUTCDate());
var date = new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate());
this.emit(this.mediation.events.broadcast.pupdate, { date: date });
};
Partial.prototype.commit = function() {
this.prev_date = new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate());
};
Partial.prototype.generateHTML = function(options) {
switch (this.scale) {
case Partial.prototype.enum.scales.day:
case Partial.prototype.enum.scales.week:
this.html = this.calendarPartialHTML(options);
break;
case Partial.prototype.enum.scales.month:
case Partial.prototype.enum.scales.year:
this.html = this.dialerPartialHTML(options);
break;
default:
break;
}
};
Partial.prototype.calendarPartialHTML = function(options) {
var container = document.createElement('div'),
wrapper = document.createElement('div');
options.min_value = options.min_date;
options.max_value = options.max_date;
this.components.yinput = new YearIncrementSlider(options);
this.components.minput = new MonthIncrementSlider(options);
this.components.calendar = new Calendar(options);
if (this.scale === Partial.prototype.enum.scales.day) {
container.className = "date-picker-mode-day active";
wrapper.className = "date-picker-content-wrapper";
} else if (this.scale === Partial.prototype.enum.scales.week) {
container.className = "date-picker-mode-week active";
wrapper.className = "date-picker-content-wrapper";
}
wrapper.appendChild(this.components.yinput.getHTML());
wrapper.appendChild(this.components.minput.getHTML());
wrapper.appendChild(this.components.calendar.getHTML());
container.appendChild(wrapper);
return container;
};
Partial.prototype.dialerPartialHTML = function(options) {
var container = document.createElement('div'),
wrapper = document.createElement('div');
options.min_value = options.min_date;
options.max_value = options.max_date;
if (this.scale === Partial.prototype.enum.scales.month) {
this.components.yinput = new YearIncrementSlider(options);
this.components.mdialer = new Dialer(options);
container.className = "date-picker-mode-month active";
wrapper.className = "date-picker-content-wrapper";
wrapper.appendChild(this.components.yinput.getHTML());
wrapper.appendChild(this.components.mdialer.getHTML());
} else if (this.scale === Partial.prototype.enum.scales.year) {
options.value = "Financial Year";
this.components.ydinput = new YDialerIncrementSlider(options);
this.components.ydialer = new Dialer(options);
container.className = "date-picker-mode-year active";
wrapper.className = "date-picker-content-wrapper";
wrapper.appendChild(this.components.ydinput.getHTML());
wrapper.appendChild(this.components.ydialer.getHTML());
}
container.appendChild(wrapper);
return container;
};
Partial.prototype.generateEvents = function() {
switch (this.scale) {
case Partial.prototype.enum.scales.day:
//Targetted at the Calendar {scale=day} class
this.mediation.events.broadcast.decday = this._constructEventString(Events.scope.broadcast, Events.desc.request.decrement.day);
this.mediation.events.broadcast.incday = this._constructEventString(Events.scope.broadcast, Events.desc.request.increment.day);
//Targetted at the MonthIncrementSlider class
this.mediation.events.broadcast.decmonth = this._constructEventString(Events.scope.broadcast, Events.desc.request.decrement.month);
this.mediation.events.broadcast.incmonth = this._constructEventString(Events.scope.broadcast, Events.desc.request.increment.month);
//Targetted at the YearIncrementSlider class
this.mediation.events.broadcast.decyear = this._constructEventString(Events.scope.broadcast, Events.desc.request.decrement.year);
this.mediation.events.broadcast.incyear = this._constructEventString(Events.scope.broadcast, Events.desc.request.increment.year);
//Updates
this.mediation.events.broadcast.cupdate = this._constructEventString(Events.scope.broadcast, Events.desc.update.cal);
this.mediation.events.broadcast.mupdate = this._constructEventString(Events.scope.broadcast, Events.desc.update.mis);
this.mediation.events.broadcast.yupdate = this._constructEventString(Events.scope.broadcast, Events.desc.update.yis);
break;
case Partial.prototype.enum.scales.week:
//Targetted at the Calendar {scale=week} class
this.mediation.events.broadcast.decweek = this._constructEventString(Events.scope.broadcast, Events.desc.request.decrement.week);
this.mediation.events.broadcast.incweek = this._constructEventString(Events.scope.broadcast, Events.desc.request.increment.week);
//Updates
this.mediation.events.broadcast.cupdate = this._constructEventString(Events.scope.broadcast, Events.desc.update.cal);
this.mediation.events.broadcast.mupdate = this._constructEventString(Events.scope.broadcast, Events.desc.update.mis);
this.mediation.events.broadcast.yupdate = this._constructEventString(Events.scope.broadcast, Events.desc.update.yis);
break;
case Partial.prototype.enum.scales.month:
this.mediation.events.broadcast.dupdate = this._constructEventString(Events.scope.broadcast, Events.desc.update.mdi);
this.mediation.events.broadcast.yupdate = this._constructEventString(Events.scope.broadcast, Events.desc.update.yis);
break;
case Partial.prototype.enum.scales.year:
this.mediation.events.broadcast.dupdate = this._constructEventString(Events.scope.broadcast, Events.desc.update.ydi);
this.mediation.events.broadcast.ydupdate = this._constructEventString(Events.scope.broadcast, Events.desc.update.yds);
break;
default:
break;
}
this.mediation.events.emit.commit = this._constructEventString(Events.scope.emit, Events.desc.commit);
this.mediation.events.broadcast.pupdate = this._constructEventString(Events.scope.broadcast, Events.desc.update.partial);
this.mediation.events.emit.pupdate = this._constructEventString(Events.scope.emit, Events.desc.update[this.scale]);
};
Partial.prototype.subscribe = function(parent) {
if (parent !== undefined) {
this.mediator.subscribe(this.mediation.events.emit.commit, parent);
this.mediator.subscribe(this.mediation.events.emit.pupdate, parent);
}
switch (this.scale) {
case Partial.prototype.enum.scales.day:
this.subscribeDay();
break;
case Partial.prototype.enum.scales.week:
this.subscribeWeek();
break;
case Partial.prototype.enum.scales.month:
this.subscribeMonth();
break;
case Partial.prototype.enum.scales.year:
this.subscribeYear();
break;
default:
break;
}
};
Partial.prototype.subscribeDay = function() {
this.mediator.subscribe(this.mediation.events.broadcast.decyear, this.components.yinput);
this.mediator.subscribe(this.mediation.events.broadcast.incyear, this.components.yinput);
this.mediator.subscribe(this.mediation.events.broadcast.decmonth, this.components.minput);
this.mediator.subscribe(this.mediation.events.broadcast.incmonth, this.components.minput);
this.mediator.subscribe(this.mediation.events.broadcast.decday, this.components.calendar);
this.mediator.subscribe(this.mediation.events.broadcast.incday, this.components.calendar);
this.mediator.subscribe(this.mediation.events.broadcast.pupdate, this.components.yinput);
this.mediator.subscribe(this.mediation.events.broadcast.pupdate, this.components.minput);
this.mediator.subscribe(this.mediation.events.broadcast.pupdate, this.components.calendar);
this.mediator.subscribe(this.mediation.events.broadcast.yupdate, this.components.yinput);
this.mediator.subscribe(this.mediation.events.broadcast.mupdate, this.components.minput);
this.mediator.subscribe(this.mediation.events.broadcast.cupdate, this.components.calendar);
this.components.yinput.subscribe(this);
this.components.minput.subscribe(this);
this.components.calendar.subscribe(this);
};
Partial.prototype.subscribeWeek = function() {
this.mediator.subscribe(this.mediation.events.broadcast.decweek, this.components.calendar);
this.mediator.subscribe(this.mediation.events.broadcast.incweek, this.components.calendar);
this.mediator.subscribe(this.mediation.events.broadcast.pupdate, this.components.yinput);
this.mediator.subscribe(this.mediation.events.broadcast.pupdate, this.components.minput);
this.mediator.subscribe(this.mediation.events.broadcast.pupdate, this.components.calendar);
this.mediator.subscribe(this.mediation.events.broadcast.yupdate, this.components.yinput);
this.mediator.subscribe(this.mediation.events.broadcast.mupdate, this.components.minput);
this.mediator.subscribe(this.mediation.events.broadcast.cupdate, this.components.calendar);
this.components.yinput.subscribe(this);
this.components.minput.subscribe(this);
this.components.calendar.subscribe(this);
};
Partial.prototype.subscribeMonth = function() {
this.mediator.subscribe(this.mediation.events.broadcast.pupdate, this.components.yinput);
this.mediator.subscribe(this.mediation.events.broadcast.pupdate, this.components.mdialer);
this.mediator.subscribe(this.mediation.events.broadcast.yupdate, this.components.yinput);
this.mediator.subscribe(this.mediation.events.broadcast.dupdate, this.components.mdialer);
this.components.yinput.subscribe(this);
this.components.mdialer.subscribe(this);
};
Partial.prototype.subscribeYear = function() {
this.mediator.subscribe(this.mediation.events.broadcast.pupdate, this.components.ydinput);
this.mediator.subscribe(this.mediation.events.broadcast.pupdate, this.components.ydialer);
this.mediator.subscribe(this.mediation.events.broadcast.ydupdate, this.components.ydinput);
this.mediator.subscribe(this.mediation.events.broadcast.dupdate, this.components.ydialer);
this.components.ydinput.subscribe(this);
this.components.ydialer.subscribe(this);
};
/**
* @override
**/
Partial.prototype.notify = function(e) {
this.forward(e);
if (e.scope === Events.scope.broadcast) {
if (e.data.min_date !== undefined && e.data.date instanceof Date) {
this.min_date = new Date(e.data.min_date.getUTCFullYear(), e.data.min_date.getUTCMonth(), e.data.min_date.getUTCDate());
}
if (e.data.max_date !== undefined && e.data.date instanceof Date) {
this.max_date = new Date(e.data.max_date.getUTCFullYear(), e.data.max_date.getUTCMonth(), e.data.max_date.getUTCDate());
}
}
if (e.data.date !== undefined && e.data.date instanceof Date) {
this.date = new Date(e.data.date.getUTCFullYear(), e.data.date.getUTCMonth(), e.data.date.getUTCDate());
}
this.constructor.prototype.notify.call(this, e);
};
Partial.prototype.forward = function(e) {
if (e.scope === Events.scope.emit) {
if (e.desc === Events.desc.commit) {
this.emit(this.mediation.events.emit.commit, e.data);
} else {
switch (this.scale) {
case Partial.prototype.enum.scales.day:
case Partial.prototype.enum.scales.week:
switch (e.desc) {
case Events.desc.update.mis:
this.emit(this.mediation.events.broadcast.yupdate, e.data);
this.emit(this.mediation.events.broadcast.cupdate, e.data);
break;
case Events.desc.update.yis:
this.emit(this.mediation.events.broadcast.mupdate, e.data);
this.emit(this.mediation.events.broadcast.cupdate, e.data);
break;
case Events.desc.update.cal:
this.emit(this.mediation.events.broadcast.mupdate, e.data);
this.emit(this.mediation.events.broadcast.yupdate, e.data);
break;
default:
break;
}
break;
case Partial.prototype.enum.scales.month:
switch (e.desc) {
case Events.desc.update.mdi:
this.emit(this.mediation.events.broadcast.yupdate, e.data);
break;
case Events.desc.update.yis:
this.emit(this.mediation.events.broadcast.dupdate, e.data);
break;
default:
break;
}
break;
case Partial.prototype.enum.scales.year:
switch (e.desc) {
case Events.desc.update.ydi:
this.emit(this.mediation.events.broadcast.ydupdate, e.data);
break;
case Events.desc.update.yds:
this.emit(this.mediation.events.broadcast.dupdate, e.data);
break;
default:
break;
}
break;
default:
break;
}
this.emit(this.mediation.events.emit.pupdate, e.data);
}
} else if (e.scope === Events.scope.broadcast) {
switch (e.desc) {
case Events.desc.commit:
this.commit();
break;
case Events.desc.rollback:
this.rollback();
break;
case Events.desc.request.increment.day:
this.emit(this.mediation.events.broadcast.incday, e.data);
break;
case Events.desc.request.increment.week:
this.emit(this.mediation.events.broadcast.incweek, e.data);
break;
case Events.desc.request.increment.month:
this.emit(this.mediation.events.broadcast.incmonth, e.data);
break;
case Events.desc.request.increment.year:
this.emit(this.mediation.events.broadcast.incyear, e.data);
break;
case Events.desc.request.decrement.day:
this.emit(this.mediation.events.broadcast.decday, e.data);
break;
case Events.desc.request.decrement.week:
this.emit(this.mediation.events.broadcast.decweek, e.data);
break;
case Events.desc.request.decrement.month:
this.emit(this.mediation.events.broadcast.decmonth, e.data);
break;
case Events.desc.request.decrement.year:
this.emit(this.mediation.events.broadcast.decyear, e.data);
break;
default:
this.emit(this.mediation.events.broadcast.pupdate, e.data);
break;
}
}
};
return Partial;
})();<file_sep>var Dialer = (function(){
function Dialer(options, component){
//Scale for this instance
this.scale = (options.scale && Dialer.prototype.enum.scales[options.scale]) ?
Dialer.prototype.enum.scales[options.scale] :
Dialer.prototype.enum.scales.month;
this.scale_initial = this.scale.substring(0,1);
component = component === undefined? this.scale_initial.toUpperCase() + Dialer.prototype.component : component;
//super()
Colleague.call(this, options.mediator, component);
this.mediation.events.emit.dupdate = this._constructEventString(Events.scope.emit, Events.desc.update[this.scale_initial + "di"]);
//Upper/Lower bounds to date value
this.min_date = options.min_date instanceof Date ?
new Date(options.min_date.getUTCFullYear(), options.min_date.getUTCMonth(), options.min_date.getUTCDate()) :
undefined;
this.max_date = options.max_date instanceof Date && options.max_date > this.min_date?
new Date(options.max_date.getUTCFullYear(), options.max_date.getUTCMonth(), options.max_date.getUTCDate()) :
undefined;
//Date that is modified by the user
this.date = new Date(options.date.getUTCFullYear(), options.date.getUTCMonth(), options.date.getUTCDate());
this.lang = options.lang !== undefined &&
Dialer.prototype.enum.languages[options.lang] !== undefined ?
Dialer.prototype.enum.languages[options.lang] : 'en';
this.dialers = [];
this.indexes = [];
this.index = 0;
this.generateInitialMax();
this.html = this.getDialerHTML();
}
//Binding the prototype of the Parent object
//Properties will be overriden on this one.
Dialer.prototype = Object.create(Colleague.prototype);
//Binding the constructor to the prototype
Dialer.prototype.constructor = Colleague;
//Component for Event Strings
Dialer.prototype.component = 'DIALER';
Dialer.prototype.enum = {
scales: {
month : "month",
year : "year",
},
languages: {
en: 'en',
fr: 'fr'
}
};
Dialer.prototype.getHTML = function(){
return this.html;
};
Dialer.prototype.getDate = function () {
return this.prev_date;
};
Dialer.prototype.setDate = function (date) {
if(date instanceof Date && (this.min_date === undefined || date >= this.min_date) && (this.max_date === undefined || date <= this.max_date)){
this.date = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
}
};
Dialer.prototype.getDialerHTML = function () {
var dialer;
if(this.dialers[this.indexes.indexOf(this.index)] !== undefined){
dialer = this.dialers[this.indexes.indexOf(this.index)];
return dialer;
}else{
dialer = this.generateHTML();
this.indexes.push(this.index);
this.dialers.push(dialer);
return dialer;
}
};
Dialer.prototype.updateDialerHTML = function () {
var parentNode = this.html.parentNode;
parentNode.removeChild(this.html);
this.html = this.getDialerHTML();
parentNode.appendChild(this.html);
this.updateSelection();
};
Dialer.prototype.generateInitialMax = function () {
var medianyear = this.date.getUTCFullYear(),
factor = (8 - NumberUtils.mod(medianyear, 8));
this.init_max = factor === 8? medianyear : medianyear + factor;
};
Dialer.prototype.generateHTML = function () {
var self = this,
i = 0,
dialer = document.createElement('div'),
callback = function(e){
self.onSpanClick(e.target);
};
var span;
if(this.scale === Dialer.prototype.enum.scales.month){
for(i = 0; i < 12; i++){
span = document.createElement('span');
span.ddata = {
month : i,
};
span.innerHTML = DateUtils.getMonthString(i, this.lang).substring(0,3);
this.applyClass(span, dialer);
span.addEventListener('click', callback);
dialer.appendChild(span);
}
}else if(this.scale === Dialer.prototype.enum.scales.year){
for(i = 0; i < 8; i++){
span = document.createElement('span');
span.ddata = {
year : this.init_max - (8-i) + this.index*8
};
span.innerHTML = span.ddata.year;
this.applyClass(span, dialer);
span.addEventListener('click', callback);
dialer.appendChild(span);
}
}
return dialer;
};
Dialer.prototype.applyClass = function (span, context) {
if(this.testMin(span) && this.testMax(span)){
span.className = "date-picker-"+this.scale+"-cell";
this.newSelection(span, context);
span.ddata.disabled = false;
}else{
span.ddata.disabled = true;
span.className = "date-picker-"+this.scale+"-cell disabled";
}
};
Dialer.prototype.testMin = function (span) {
if(this.min_date === undefined) return true;
if(this.scale === Dialer.prototype.enum.scales.month){
return !(this.min_date.getUTCMonth() > span.ddata.month &&
this.min_date.getUTCFullYear() >= this.date.getUTCFullYear());
}else if(this.scale === Dialer.prototype.enum.scales.year){
return this.min_date.getUTCFullYear() <= span.ddata.year;
}
};
Dialer.prototype.testMax = function (span) {
if(this.max_date === undefined) return true;
if(this.scale === Dialer.prototype.enum.scales.month){
return !(this.max_date.getUTCMonth() < span.ddata.month &&
this.max_date.getUTCFullYear() <= this.date.getUTCFullYear());
}else if(this.scale === Dialer.prototype.enum.scales.year){
return this.max_date.getUTCFullYear() >= span.ddata.year;
}
};
Dialer.prototype.updateSelection = function (span) {
var dialer = this.html,
date = {year : this.date.getUTCFullYear(), month : this.date.getUTCMonth()};
if(dialer.current !== undefined && dialer.current.ddata[this.scale] !== date[this.scale]){
this.removeSelection();
}
if(span === undefined){
for (var i = 0; i < this.html.children.length; i++) {
this.applyClass(this.html.children[i]);
}
}else{
this.applyClass(span);
}
};
Dialer.prototype.newSelection = function (span, context) {
var date = {month: this.date.getUTCMonth(), year: this.date.getUTCFullYear()};
if(span.ddata[this.scale] === date[this.scale]){
if(context !== undefined){
context.current = span;
if(this.scale === Dialer.prototype.enum.scales.month){
context.current.className = "date-picker-month-cell active";
}else if (this.scale === Dialer.prototype.enum.scales.year){
context.current.className = "date-picker-year-cell active";
}
}else{
this.html.current = span;
if(this.scale === Dialer.prototype.enum.scales.month){
this.html.current.className = "date-picker-month-cell active";
}else if (this.scale === Dialer.prototype.enum.scales.year){
this.html.current.className = "date-picker-year-cell active";
}
}
}
};
Dialer.prototype.removeSelection = function () {
if(this.html.current !== undefined){
if(this.scale === Dialer.prototype.enum.scales.month){
this.html.current.className = "date-picker-month-cell";
}else if (this.scale === Dialer.prototype.enum.scales.year){
this.html.current.className = "date-picker-year-cell";
}
}
};
Dialer.prototype.onSpanClick = function (span) {
if(span.ddata.disabled === false){
if(this.scale === Dialer.prototype.enum.scales.month){
this.date.setUTCMonth(span.ddata.month);
}else if(this.scale === Dialer.prototype.enum.scales.year){
this.date.setUTCFullYear(span.ddata.year);
}
this.emit(this.mediation.events.emit.dupdate, {date: new Date(this.date.getUTCFullYear(), this.date.getUTCMonth(), this.date.getUTCDate())});
this.updateSelection(span);
}
};
Dialer.prototype.subscribe = function (parent) {
if(parent !== undefined){
this.mediator.subscribe(this.mediation.events.emit.dupdate, parent);
}
};
Dialer.prototype.notify = function (e) {
if(e.scope === Events.scope.broadcast){
switch(e.desc){
case Events.desc.update.partial:
if(e.data.min_date !== undefined && e.data.min_date instanceof Date &&
(this.max_date === undefined || e.data.min_date < this.max_date)){
this.min_date = new Date(e.data.min_date.getUTCFullYear(), e.data.min_date.getUTCMonth(), e.data.min_date.getUTCDate());
this.updateSelection();
}
if(e.data.max_date !== undefined && e.data.max_date instanceof Date &&
(this.min_date === undefined || e.data.max_date > this.min_date)){
this.max_date = new Date(e.data.max_date.getUTCFullYear(), e.data.max_date.getUTCMonth(), e.data.max_date.getUTCDate());
this.updateSelection();
}
if(e.data.date !== undefined){
this.setDate(e.data.date);
if(this.scale === Dialer.prototype.enum.scales.year){
this.updateDialerHTML();
}else if(this.scale === Dialer.prototype.enum.scales.month){
this.updateSelection();
}
}
if(e.data.index !== undefined && typeof e.data.index === "number"){
this.index = e.data.index;
this.updateDialerHTML();
}
break;
case Events.desc.update.mdi:
if(e.data.date !== undefined && e.data.date instanceof Date){
this.setDate(e.data.date);
this.updateSelection();
}
break;
case Events.desc.update.ydi:
if(e.data.index !== undefined && typeof e.data.index === "number"){
this.index = e.data.index;
}
if(e.data.date !== undefined && e.data.date instanceof Date){
this.setDate(e.data.date);
}
this.updateDialerHTML();
break;
default:
break;
}
}
this.constructor.prototype.notify.call(this, e);
};
return Dialer;
})();
<file_sep># DatePicker
An easy, out of the box date picker allowing the user to pick dates in four different
scales, from day to year.
## Getting Started { Production }
### Method 1: Clone the Repository
#### 1. Clone the Repository
Change directory to the directory of your choice and then clone this repository
using `git clone https://github.com/p-hebert/date-picker`
#### 2. Add the dist files to your project
DatePicker does not have any external dependencies to any other libraries. As
such you can directly import the javascript and css from the `dist/` folder in
your HTML:
```
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="./date-picker.css">
<script src="./date-picker.js"></script>
</head>
<body>
...
</body>
</html>
```
#### 3. Call the DatePicker Constructor
DatePicker is simple to use. All you need to do is call
`new DatePicker();` and a DatePicker will be automatically generated. You can also
pass some options, such as boundary dates, target HTMLElement, etc. See the
**API** section for more details.
### Method 2: Use Bower
#### 1. Add repository as dependency
Run the following command:
`bower install 'https://github.com/p-hebert/date-picker' --save`
#### 2. Add the dist files to your project
DatePicker does not have any external dependencies to any other libraries. As
such you can directly import the javascript and css from the `dist/` folder in
your HTML:
```
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="./bower_components/date-picker/dist/date-picker.css">
<script src="./bower_components/date-picker/dist/date-picker.js"></script>
</head>
<body>
...
</body>
</html>
```
#### 3. Call the DatePicker Constructor
DatePicker is simple to use. All you need to do is call
`new DatePicker();` and a DatePicker will be automatically generated. You can also
pass some options, such as boundary dates, target HTMLElement, etc. See the
**API** section for more details.
## Getting Started { Development }
#### 1. Clone the repository
Change directory to the directory of your choice and then clone this repository
using `git clone https://github.com/p-hebert/date-picker`.
#### 2. Install build dependencies
1. Run `npm install` to install all node dependencies. You must have the node package
manager installed in order for this to work.
2. Run `bower install` to install all bower dependencies. bower will be installed
by default after the npm install.
#### 3. Build via Gulp
Currently the gulpfile only has one command, the default command. As such run `gulp`
in order to build the javascript.
You will find the javascript and compiled scss under `src/` as `date-picker.js` and
`date-picker.css`
## API
### Options Parameters
| Parameter | type | Description | Defaults to |
| ------------- | --------------------- | ---------------------------------------- | ------------ |
| `date` | Date | Default date to be displayed | new Date() |
| `min_date` | Date | Minimum date allowed for the date picker | undefined |
| `max_date` | Date | Maximum date allowed for the date picker | undefined |
| `scale` | string | First scale to be shown. Valid values are 'day', 'week', 'month', 'year' | 'day' |
| `parent` | string or HTMLElement | Either a selector supported by [`document.querySelector()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) or an HTMLElement. | 'body' |
| `lang` | string | Language of the DatePicker. Currently only English and French are supported | 'en' |
| `icons` | object | Arrow icons used for the DatePicker. If you feel like a change of style, you can change those. However make sure to follow the default structure or your icons won't show up. | <see below> |
#### `icons` Default
~~~~
{
"arrow-prev-big": '<svg>...</svg>',
"arrow-next-big": '<svg>...</svg>',
"arrow-prev-small": '<svg>...</svg>',
"arrow-next-small": '<svg>...</svg>'
}
~~~~
#### A Note on Options
All options passed are deep-copied, and as such the options object you pass will
not be tied to the DatePicker. Any modification on the options object will not
affect the DatePicker inner state.
### API Calls
| Method | Description | Stable? |
| ------------- | ---------------------------------------- | ------------ |
| `getAPI()` | Provides a proxy comprised of all the API calls listed below | **Yes** |
| `getDate()` | Accessor for the current date | **Yes** |
| `setDate(Date: date)` | Mutator for the current date | **Yes** |
| `incrementDate(boolean: commit, string: scale)` | Increments the date by one unit of the specified scale.
Setting commit to true will also issue a commit event. commit defaults to false, while scale defaults to current scale. | **Yes** |
| `decrementDate(boolean: commit, string: scale)` | Decrements the date by one unit of the specified scale.
Setting commit to true will also issue a commit event. commit defaults to false, while scale defaults to current scale. | **Yes** |
| `getMinDate()` | Accessor for the min date | **Yes** |
| `setMinDate(Date: date)` | Mutator for the max date | **Yes** |
| `getMinDate()` | Accessor for the max date | **Yes** |
| `setMaxDate(Date: date)` | Mutator for the min date | **Yes** |
| `getScales()` | Returns the four scales for the date as an object | **Yes** |
| `getScale()` | Accessor for the current scale | **Yes** |
| `changeScale(string: scale)` | Mutator for the current scale | **Yes** |
| `addEventListener(string: e, function: callback)` | Adds an event listener to the specified event. Event must be available in `DatePicker.prototype.enum.callbacks`. See note below for more details. | **Yes** |
| `getComponents()` | Returns the list of components listed in `DatePicker.prototype.enum.components` | **Yes** |
| `getComponent(string: comp)` | Returns the requested component. Must be listed in `DatePicker.prototype.enum.components` | **Yes** |
| `commit()` | Overrides the previous date selection with current date selection. Emits a 'commit' event. By default the DatePicker calls this method when the user clicks outside of the dropdown zone and closes the dropdown. | **Yes** |
| `rollback()` | Overrides the current date selection with previous date selection. Emits a 'rollback' event. | **Yes** |
| `patchSVGURLs()` | Applies the SVG patch for the bug listed [here](https://gist.github.com/leonderijke/c5cf7c5b2e424c0061d2). Called on initialization by default. | **Yes** |
#### Notes on API
- `addEventListener(string: e, function: callback)`: Can only listen to
DatePicker events. To listen on component events, use
`getComponent(component).registerCallback(e, callback)` where `e` is available in the
component's prototype.enum.callbacks. Support for component event listening is
not standardized.
- `getComponent(string: comp)`: Modifying the inner state of components will result in
inconsistencies, so be careful with what you aim to do with this. Moreover if you are
using the minified version prototype names are mangled.
## Currently Known Issues
- The French version is buggy at best.
- There seems to be some issues with the SVG arrows' links to the icons.
## Authorship
- Design and UX by @gregorybp
- Markup and styling by @geeyoam
- Javascript by @p-hebert
<file_sep>var Colleague = (function(){
function Colleague(mediator, component){
this.mediator = mediator;
this.callbacks = {};
this.mediator.register(this);
this.mediation.component = component;
this.mediation.events = {
broadcast:{ gupdate: this._constructEventString(Events.scope.broadcast, Events.desc.update.global) },
emit: { gupdate: this._constructEventString(Events.scope.emit, Events.desc.update.global) }
};
}
Colleague.prototype.constructor = Colleague;
//Component for Event Strings
Colleague.prototype.component = 'COLLEAGUE';
Colleague.prototype.enum = {
callbacks: {
notify: "notify",
emit: "emit"
}
};
Colleague.prototype.registerCallback = function (name, callback) {
var exists = false,
callbacks;
if(this.enum.callbacks !== undefined){
callbacks = [this.enum.callbacks, Colleague.prototype.enum.callbacks];
}else{
callbacks = [Colleague.prototype.enum.callbacks];
}
for(var i = 0; i < callbacks.length; i++){
for(var key in callbacks[i]){
if(key === name){
exists = true;
break;
}
}
}
if(exists && typeof callback === "function"){
if(this.callbacks[name] === undefined) this.callbacks[name] = [];
this.callbacks[name].push(callback);
return true;
}else{
return false;
}
};
Colleague.prototype.callCallback = function (name, data) {
if(name === undefined) throw new Error();
var index;
index = this.enum.callbacks !== undefined ? this.enum.callbacks[name] : undefined;
index = index === undefined ? Colleague.prototype.enum.callbacks[name] : index;
if(this.callbacks[index] !== undefined){
for (var i = 0; i < this.callbacks[index].length; i++) {
this.callbacks[index][i].call(this, data);
}
}
};
Colleague.prototype.emit = function (eventStr, data) {
var e = {
name: eventStr,
source: this.mediation.component + ':' + this.mediation.uuid,
data: data
};
if(eventStr.indexOf(Events.scope.emit) !== -1){
e.scope = Events.scope.emit;
}else if(eventStr.indexOf(Events.scope.broadcast) !== -1){
e.scope = Events.scope.broadcast;
}
var desc = eventStr, index = desc.indexOf('_');
while(index !== -1){
desc = desc.substring(index+1);
index = desc.indexOf('_');
}
e.desc = desc;
this.mediator.notify(this, e);
this.callCallback(Colleague.prototype.enum.callbacks.emit, e);
};
Colleague.prototype.notify = function (e) {
this.callCallback(Colleague.prototype.enum.callbacks.notify, e);
};
Colleague.prototype._constructEventString = function (scope, desc) {
return this.mediation.component + ':' + this.mediation.uuid + '_' + scope + '_' + desc;
};
return Colleague;
})();
| 715dda977c1ef0d4ccd0e6e7ec33e0452e221a69 | [
"JavaScript",
"Markdown"
] | 14 | JavaScript | p-hebert/date-picker | 51351193aa8bd770124f4a1cc00709812bf6d47e | 0957cdcbc1c455847deaa1f1799774020278ce64 |
refs/heads/master | <file_sep>const menuMobile = document.getElementsByClassName("menu-mobile-btn")[0];
const navigation = document.getElementsByClassName("navigation")[0];
const subMenu = document.getElementsByClassName("sub-menu")[0];
let menus = document.getElementsByClassName("menu");
menuMobile.addEventListener('click',onClickMenuMobile);
let isShow = false;
let isShowMore = false;
function onClickMenuMobile() {
navigation.style.display = isShow===false ? 'flex' : 'none';
isShow = !isShow;
if(isShowMore){
subMenu.style.display = "none";
isShowMore = false;
}
}
for(let i = 0; i < menus.length; i++) {
if(menus[i].localName != "div"){
menus[i].onclick = onClickMenu;
}
else{
menus[i].onclick = onClickMore;
}
}
//hide menu when click on menu item
function onClickMenu() {
if(isShow){
navigation.style.display = "none";
}
}
function onClickMore() {
if(isShowMore){
subMenu.style.display = "none"
}else{
subMenu.style.display = "flex"
}
isShowMore = !isShowMore;
}<file_sep>const modal = document.getElementsByClassName("modal-buy-ticket")[0];
const modalContainer = document.getElementsByClassName("modal-container")[0]
function onClickBuyTicket (){
modal.style.display ="flex"
}
function onClickCloseModal(){
modal.style.display = "none"
}
modal.addEventListener('click', onClickCloseModal)
modalContainer.addEventListener('click', (e) => {
e.stopPropagation()
})<file_sep>// let head = document.getElementsByClassName("header")[0];
// let content = document.getElementsByClassName("content")[0];
// console.log("top:",head.offsetHeight)
// content.style.top = head.offsetHeight + "px";
let index = 1;
function autoSlideShow() {
const slide = document.getElementsByClassName("slide")
slide[0].style.display = "block"
setInterval(() =>{
slide[ (index-1 ) < 0 ? slide.length-1 : index-1].style.display = "none";
slide[index].style.display = "block";
index = (index+1) > 2 ? 0 : index + 1
},2000)
}
autoSlideShow() | 6b7d2ca57adb5e1a21520c15df4f93930c9f4cb9 | [
"JavaScript"
] | 3 | JavaScript | AlexisPQA/theband | bd5724a6c66a59c3b10655d46a19b9ae9a97b61b | 6329df2137126af6b384a9cd9ee261790aa4c755 |
refs/heads/master | <file_sep>package hunau.com.mydatauser.entity;
import javax.persistence.*;
/**
* @param
* @Description:
* @Return:
* @Author: 蔡文静
* @单位:湖南农业大学物联网工程专业
* @Date:
* @开发版本:综合练习VO.1
*/
import javax.persistence.*;
import org.hibernate.validator.constraints.NotBlank;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.hibernate.validator.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
@Entity
@Table(name="tb_user")
public class User {
@Id
@GeneratedValue
private Integer id;
@NotEmpty(message="名字不能为空")
@Column(length=40)
private String name;
@NotEmpty(message="密码不能为空")
@Column(length=50)
private String pwd;
private String sexy;
private Date birthday;
private boolean isuse;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name==null?null:name.trim();
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd==null?null:pwd.trim();
}
public boolean isIsuse() {
return isuse;
}
public void setIsuse(boolean isuse)
{
this.isuse = isuse;
}
public String getSexy() {
return sexy;
}
public void setSexy(String sexy) {
this.sexy = sexy;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"学号=" + id +
", 姓名='" + name + '\'' +
", 密码='" + pwd + '\'' +
", 性别='" + sexy + '\'' +
", 生日=" +new SimpleDateFormat("yyyy年MM月dd日").format(birthday) +'\''+
",年龄="+age+'\''+
", 是否有效=" + isuse +
'}';
}
}
<file_sep>package hunau.com.mydatauser.Dao;
import hunau.com.mydatauser.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @param
* @Description:
* @Return:
* @Author: 蔡文静
* @单位:湖南农业大学物联网工程专业
* @Date:
* @开发版本:综合练习VO.1
*/
@Mapper
@Repository
public interface UserDao {
@Select("select id,name,pwd,sexy,birthday,isuse from tb_user where name like'%${value}%'")
//@Transactional(readOnly = true)
List<User> findBy(String name);
@Select("select id,name,pwd,sexy,birthday,isuse from tb_user where id=#{id}")
User selectUser(int id);
}
<file_sep>package hunau.com.mydatauser;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@MapperScan("hunau.com.mydatauser.Dao")
@EnableWebMvc
@SpringBootApplication
public class MydatauserApplication {
public static void main(String[] args) {
SpringApplication.run(MydatauserApplication.class, args);
}
}
<file_sep>package hunau.com.mydatauser.controller;
import hunau.com.mydatauser.Dao.UserDao;
import hunau.com.mydatauser.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @param
* @Description:
* @Return:
* @Author: 蔡文静
* @单位:湖南农业大学物联网工程专业
* @Date:
* @开发版本:综合练习VO.1
*/
@Controller
public class UserController {
// @Resource
//private UserDao userDao;
@Autowired
UserService userService;
@RequestMapping("/query")
public String Query(Model model){
model.addAttribute("users", userService.findBy("小吴"));
return "query";
}
@RequestMapping("showUser/{id}")
public String showUser(@PathVariable int id,Model model){
model.addAttribute("name",userService.selectUser(id).toString());
return "showuser";
}
} | af220504cd463b3c90278eb70506f985e1761460 | [
"Java"
] | 4 | Java | Cwwjj/mydatauser | e0923968ca867a788609b16be1f6900f36f963fb | e40f091f7171ca946b8a233fcc8a9849ab2219f7 |
refs/heads/master | <file_sep>package com.starbattle.ingame.game.particles;
import java.util.HashMap;
import org.newdawn.slick.Color;
import org.newdawn.slick.Graphics;
public class ParticleContainer
{
private HashMap<String,ParticleEffect> effects=new HashMap<String,ParticleEffect>();
public ParticleContainer()
{
effects.put("Splash",new ParticleEffect( "test"));
effects.put("Splash2",new ParticleEffect( "test2"));
}
public void spawnEffect(String name, float x, float y)
{
ParticleEffect effect=effects.get(name);
effect.spawnEffect(x, y);
}
public void render(Graphics g)
{
int count=0;
for(ParticleEffect effect: effects.values())
{
count+=effect.render();
}
g.setColor(new Color(255,255,255));
g.drawString("PEC: "+count,10,30);
}
public void update(int delta)
{
for(ParticleEffect effect: effects.values())
{
effect.update(delta);
}
}
}
<file_sep>package com.starbattle.gameserver.main;
public class BattleResults {
}
<file_sep>package com.starbattle.gameserver.game.physics;
public class ObjectGravity {
private final static float G_EARTH = 9.81f;
private final static float TIME_UNITS= 0.03f;
private float g_factor;
private float time;
private float jumpSpeed;
private float lastValue;
private boolean inAir=false;
private ObjectMovement objectMovement;
public ObjectGravity(ObjectMovement objectMovement) {
g_factor=G_EARTH;
this.objectMovement=objectMovement;
}
public void setG_factor(float g_factor) {
this.g_factor = g_factor;
}
public void update(float delta)
{
if(inAir)
{
//update time
float deltaTime=TIME_UNITS*delta;
time+=deltaTime;
//update y (vertikaler wurf formel)
float jumpY = (float)(jumpSpeed * time - (g_factor / 2) * Math.pow(time, 2));
float yDelta=jumpY-lastValue;
lastValue=jumpY;
//update location
objectMovement.verticalMovement(yDelta);
}
}
public void jump(float speed)
{
if(!inAir)
{
jumpSpeed=speed;
startGravity();
}
}
public void startFalling()
{
if(!inAir)
{
jumpSpeed=0;
startGravity();
}
}
public void cancelMovement()
{
inAir=false;
}
private void startGravity()
{
inAir=true;
time=0;
lastValue=0;
}
public boolean isInAir() {
return inAir;
}
}
<file_sep>package com.starbattle.gameserver.map;
import java.util.ArrayList;
import org.newdawn.slick.tiled.TiledMap;
import com.starbattle.gameserver.game.Team;
public class GameTileLoader {
// IDs in Game TileSet (resource/tilesets/gameset.png) for Blocks
public final static int TILE_COLLISION = 1;
public final static int TILE_DEATHBLOCK = 2;
public final static int TILE_SPAWNPOINT_BLUE = 3;
public final static int TILE_SPAWNPOINT_RED = 4;
public final static int TILE_FLAG_BLUE = 5;
public final static int TILE_FLAG_RED = 6;
private static SpawnPointList spawnPointList;
private static GameTiles getSpecialTile(int id) {
for (GameTiles tile : GameTiles.values()) {
if (tile.getTileID() == id) {
return tile;
}
}
return null;
}
public static void findGameTiles(TiledMap map, int gameLayerID) {
spawnPointList = new SpawnPointList();
// search
for (int x = 0; x < map.getWidth(); x++) {
for (int y = 0; y < map.getHeight(); y++) {
int tileID = map.getTileId(x, y, gameLayerID);
GameTiles specialTile = getSpecialTile(tileID);
if (specialTile != null) {
foundGameTile(specialTile, x, y);
}
}
}
}
private static void foundGameTile(GameTiles tile, int x, int y) {
switch (tile) {
case SPAWNPOINT_BLUE:
spawnPointList.add(new SpawnPoint(x, y, Team.BLUE_TEAM));
break;
case SPAWMPOINT_RED:
spawnPointList.add(new SpawnPoint(x, y, Team.RED_TEAM));
break;
}
}
public static SpawnPointList getSpawnPointList() {
return spawnPointList;
}
}
<file_sep>package com.starbattle.ingame.render;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import com.starbattle.ingame.game.location.Location;
import com.starbattle.ingame.game.player.PlayerDisplay;
import com.starbattle.ingame.game.player.PlayerObject;
import com.starbattle.ingame.game.viewport.Viewport;
import com.starbattle.ingame.resource.PlayerGraphics;
import com.starbattle.ingame.resource.ResourceContainer;
import com.starbattle.ingame.resource.player.PlayerGraphicPart;
import com.starbattle.ingame.resource.player.PlayerGraphicResource;
public class PlayerRender {
private final static float ARMPIT_Y = -6;
private final static float FOOTPIT_Y = 20;
private final static float ARM_X_DIFFERENCE = 3;
private final static float FOOT_X_DIFFERENCE = 4;
private final static float ARMROTATION_X = 16;
private final static float ARMROTATION_Y = 14;
private final static float FOOTOTATION_X = 16;
private final static float FOOTROTATION_Y = 14;
private final static float BODY_WIDTH = 64;
private final static float BODY_HEIGHT = 96;
/*
* private final static float ARM_WIDTH = 32; private final static float
* ARM_HEIGHT = 48; private final static float FOOT_WIDTH = 32; private
* final static float FOOT_HEIGHT = 48;
*/
private final static float MAX_LEG_ANGLE = 120;
private final static float MAX_ARM_ANGLE = 180;
private ResourceContainer resourceContainer;
public PlayerRender(ResourceContainer resourceContainer) {
this.resourceContainer = resourceContainer;
}
private float bodyAngle;
private boolean mirrored;
private PlayerGraphicResource resource;
public void render(Graphics g, PlayerObject player, Viewport viewport) {
Location location = viewport.getScreenLocation(player.getLocation());
PlayerDisplay display = player.getDisplay();
PlayerGraphics graphics = display.getGraphic();
float[] angles = display.getRotation();
boolean mirrored = display.isLookingLeft();
render(g, location, graphics, angles, mirrored);
}
public void render(Graphics g, Location location, PlayerGraphics graphics, float[] angles, boolean mirrored) {
float xpos = location.getXpos();
float ypos = location.getYpos();
resource = resourceContainer.getPlayerGraphics().get(graphics);
// get body image
Image body = resource.getBodyPart(PlayerGraphicPart.BODY);
if (mirrored) {
body = body.getFlippedCopy(true, false);
}
this.mirrored = mirrored;
// draw centered
// get player rotation angle
float lFootAnlge = angles[0];
float lArmAngle = angles[1];
float rFootAnlge = angles[2];
float rArmAngle = angles[3];
bodyAngle = angles[4];
// calc body
body.setCenterOfRotation(BODY_WIDTH / 2, BODY_HEIGHT / 2);
body.setRotation(bodyAngle);
// draw right arm and foot (behind body)
drawBodyPart(g, PlayerGraphicPart.RIGHT_FOOT, xpos, ypos, rFootAnlge);
drawBodyPart(g, PlayerGraphicPart.RIGHT_ARM, xpos, ypos, rArmAngle);
// draw body
body.drawCentered(xpos, ypos);
// draw left arm and foot (infront body)
drawBodyPart(g, PlayerGraphicPart.LEFT_FOOT, xpos, ypos, lFootAnlge);
drawBodyPart(g, PlayerGraphicPart.LEFT_ARM, xpos, ypos, lArmAngle);
}
private float getNormalizedAngle(float angle, float max) {
if (angle > max) {
angle = max;
} else if (angle < -max) {
angle = -max;
}
return angle + bodyAngle;
}
private void drawBodyPart(Graphics g, PlayerGraphicPart part, float x, float y, float partAnlge) {
float pitPos = 0;
float rotationPosX = 0;
float rotationPosY = 0;
float xDiff = 0;
float anlgeMax = 0;
// get image
Image partImage = resource.getBodyPart(part);
if (mirrored) {
partImage = partImage.getFlippedCopy(true, false);
}
// calc pit and rotation offset for pivot rotation
if (part == PlayerGraphicPart.LEFT_ARM || part == PlayerGraphicPart.RIGHT_ARM) {
// arm
pitPos = ARMPIT_Y;
rotationPosX = ARMROTATION_X;
rotationPosY = ARMROTATION_Y;
xDiff = ARM_X_DIFFERENCE;
anlgeMax = MAX_ARM_ANGLE;
if (part == PlayerGraphicPart.LEFT_ARM) {
xDiff *= -1;
}
} else {
// foot
pitPos = FOOTPIT_Y;
rotationPosX = FOOTOTATION_X;
rotationPosY = FOOTROTATION_Y;
xDiff = FOOT_X_DIFFERENCE;
anlgeMax = MAX_LEG_ANGLE;
if (part == PlayerGraphicPart.LEFT_FOOT) {
xDiff *= -1;
}
}
partAnlge = getNormalizedAngle(partAnlge, anlgeMax);
float a = (float) Math.toRadians(bodyAngle + 90);
// get part pit angle difference in position to body
float xpos = x + (float) (Math.cos(a) * pitPos);
float ypos = y + (float) (Math.sin(a) * pitPos);
// change pivotpos by horizontal difference
float normalAngle = (float) (a + Math.PI / 2);
float xDiffX = (float) (Math.cos(normalAngle) * xDiff);
float xDiffY = (float) (Math.sin(normalAngle) * xDiff);
xpos -= xDiffX;
ypos -= xDiffY;
partImage.setCenterOfRotation(rotationPosX, rotationPosY);
partImage.setRotation(partAnlge);
float px = xpos - rotationPosX;
float py = ypos - rotationPosY;
partImage.draw(px, py);
}
}
<file_sep>package com.starbattle.client.main;
import com.starbattle.client.connection.NetworkConnection;
import com.starbattle.client.connection.NetworkConnectionListener;
import com.starbattle.client.main.error.BugSplashDialog;
import com.starbattle.network.connection.NetworkRegister;
public abstract class ConnectionFactory {
public static NetworkConnection createConnection()
{
NetworkConnection connection = new NetworkConnection(new NetworkConnectionHandler());
// connection.start("localhost", NetworkRegister.TCP_PORT,NetworkRegister.UDP_PORT);
return connection;
}
// reacts if connection to server opened/closed
private static class NetworkConnectionHandler implements NetworkConnectionListener {
@Override
public void onConnect() {
System.out.println("Client connected to Server!");
}
@Override
public void onDisconnect(String cause) {
if(cause!=null)
{
//display disconnect cause
BugSplashDialog.showMessage(cause);
}
// loadingWindow.close();
//window.open(ConnectionErrorView.VIEW_ID);
}
}
}
<file_sep>package com.starbattle.server.manager;
import com.esotericsoftware.kryonet.Connection;
import com.starbattle.network.connection.ConnectionListener;
import com.starbattle.network.connection.objects.NP_ChatMessage;
import com.starbattle.network.connection.objects.NP_FriendRequest;
import com.starbattle.network.connection.objects.NP_HandleFriendRequest;
import com.starbattle.network.connection.objects.NP_Login;
import com.starbattle.network.connection.objects.NP_Logout;
import com.starbattle.network.connection.objects.NP_Register;
import com.starbattle.network.connection.objects.NP_ResetEmail;
import com.starbattle.network.connection.objects.game.NP_PlayerUpdate;
import com.starbattle.network.server.NetworkServer;
import com.starbattle.network.server.PlayerConnection;
import com.starbattle.server.player.PlayerContainer;
public class MainServerManager {
private NetworkServer server;
private PlayerManager playerManager;
private PlayerContainer playerContainer;
private GameManager gameManager;
public MainServerManager(NetworkServer server) {
this.server = server;
playerContainer = new PlayerContainer();
playerManager = new PlayerManager(playerContainer);
gameManager = new GameManager();
}
public ConnectionListener createListener() {
return new ConnectionListener() {
@Override
public void onDisconnect(Connection connection) {
clientDisconnected(connection);
}
@Override
public void onConnect(Connection connection) {
clientConnected(connection);
}
@Override
public void onReceive(Connection connection, Object object) {
receivedObject(connection, object);
}
};
}
private void clientConnected(Connection connection) {
System.out.println("New Client (" + connection.getID() + ") connected to Server!");
}
private void clientDisconnected(Connection connection) {
// remove from login player list
System.out.println("Lost Connection to Client " + connection.getID());
playerManager.logoutPlayer((PlayerConnection) connection);
}
private void receivedObject(Connection connection, Object object) {
PlayerConnection player = (PlayerConnection) connection;
if (object instanceof NP_Login) {
playerManager.tryLogin(player, (NP_Login) object);
} else if (object instanceof NP_Register) {
playerManager.tryRegister(player, (NP_Register) object);
} else if (object instanceof NP_Logout) {
playerManager.logoutPlayer(player);
} else if (object instanceof NP_ResetEmail) {
playerManager.tryResetEmail((NP_ResetEmail) object);
} else if (object instanceof NP_FriendRequest) {
playerManager.trySendFriendRequest(player, (NP_FriendRequest) object);
} else if (object instanceof NP_HandleFriendRequest) {
playerManager.handleFriendRequest(player, (NP_HandleFriendRequest) object);
} else if (object instanceof NP_ChatMessage) {
playerManager.sendChat(player, (NP_ChatMessage) object);
} else if (object instanceof NP_PlayerUpdate) {
gameManager.receivedPlayerUpdate((NP_PlayerUpdate) object, player);
}
}
public PlayerManager getPlayerManager() {
return playerManager;
}
public PlayerContainer getPlayerContainer() {
return playerContainer;
}
public GameManager getGameManager() {
return gameManager;
}
public void close() {
playerManager.close();
gameManager.close();
}
}
<file_sep>package com.starbattle.ingame.game.states;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
import com.starbattle.ingame.game.GameCore;
import com.starbattle.ingame.game.GameManager;
import com.starbattle.ingame.network.ObjectReceiveListener;
import com.starbattle.ingame.resource.ResourceContainer;
import com.starbattle.ingame.resource.player.ResourceException;
import com.starbattle.network.connection.objects.game.NP_ClientReady;
import com.starbattle.network.connection.objects.game.NP_GameUpdate;
import com.starbattle.network.connection.objects.game.NP_PrepareGame;
public class LoadingState extends BasicGameState {
private ResourceContainer resourceContainer;
private GameManager manager;
private boolean finishedLoading = false;
private boolean openGame = false;
private NP_PrepareGame prepareGame;
public LoadingState(GameManager manager, NP_PrepareGame prepareGame) {
this.manager = manager;
this.resourceContainer = manager.getResourceContainer();
this.prepareGame = prepareGame;
}
@Override
public void enter(GameContainer container, StateBasedGame game) throws SlickException {
super.enter(container, game);
// listen for game start from server
manager.getNetwork().setReceiveListener(new ObjectReceiveListener() {
@Override
public void updateGame(NP_GameUpdate message) {
// not used here
}
@Override
public void startGame() {
openGame = true;
}
});
}
@Override
public void init(GameContainer container, StateBasedGame game) throws SlickException {
}
@Override
public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException {
// draw loading screen
g.drawString("Loading...", 10, 30);
}
@Override
public void update(GameContainer container, StateBasedGame game, int delta) throws SlickException {
if (!finishedLoading) {
System.out.println("Start Loading Game:");
// load all resources
try {
System.out.println("Load Resources...");
resourceContainer.loadResources();
manager.initGame(prepareGame);
// load map
String mapName = manager.getMapName();
GameCore gameCore = manager.getGameCore();
System.out.println("Load Map...");
gameCore.loadMap(mapName);
System.out.println("Finished loading!");
finishedLoading = true;
// contact server im finished with loading
manager.getNetwork().sendToServer(new NP_ClientReady());
System.out.println("Waiting for other players to finish...");
} catch (ResourceException e) {
e.printStackTrace();
container.exit();
}
} else {
// wait for other players
if (openGame) {
// open game
System.out.println("Starting Game!");
game.enterState(GameStates.BATTLE_STATE.ordinal());
}
}
}
@Override
public int getID() {
return GameStates.LOADING_STATE.ordinal();
}
}
<file_sep>package com.starbattle.ingame.game.player;
import org.newdawn.slick.Graphics;
import com.starbattle.ingame.game.location.Location;
import com.starbattle.ingame.game.viewport.Viewport;
public class PlayerObject {
private Location location=new Location();
private float weaponangle;
private String name;
private int team;
private PlayerDisplay display;
public PlayerObject(String name, int team)
{
this.name=name;
this.team=team;
display=new PlayerDisplay();
}
public void update(float delta)
{
}
public Location getLocation() {
return location;
}
public PlayerDisplay getDisplay() {
return display;
}
}
<file_sep>package com.starbattle.ingame.debug;
import com.starbattle.ingame.network.GameClientConnection;
import com.starbattle.ingame.network.GameSendConnection;
import com.starbattle.network.connection.objects.game.NP_ClientReady;
import com.starbattle.network.connection.objects.game.NP_GameStart;
public class DebugConnection implements GameSendConnection {
private GameClientConnection client;
public DebugConnection(GameClientConnection client) {
this.client = client;
}
@Override
public void send(Object object) {
System.out.println("Send Important Update: " + object.getClass().getSimpleName());
if (object instanceof NP_ClientReady) {
// Send Game Start to client
client.receivedObject(new NP_GameStart());
}
}
}
<file_sep>package com.starbattle.ingame.game.location;
public class Location {
private float xpos, ypos;
public Location() {
}
public Location(float x, float y) {
xpos = x;
ypos = y;
}
public Location(Location l) {
xpos = l.getXpos();
ypos = l.getYpos();
}
public void move(float x, float y) {
xpos += x;
ypos += y;
}
public void move(Location l) {
xpos += l.getXpos();
ypos += l.getYpos();
}
public void subtract(Location l)
{
xpos -= l.getXpos();
ypos -= l.getYpos();
}
public void jumpTo(float x, float y) {
xpos = x;
ypos = y;
}
public void jumpTo(Location location) {
xpos = location.getXpos();
ypos = location.getYpos();
}
public float getXpos() {
return xpos;
}
public float getYpos() {
return ypos;
}
@Override
public String toString() {
return xpos+" x "+ypos;
}
}
<file_sep>package com.starbattle.client.main;
import java.awt.Dimension;
import java.io.IOException;
import com.starbattle.client.connection.NetworkConnection;
import com.starbattle.client.connection.NetworkConnectionListener;
import com.starbattle.client.main.error.BugSplashDialog;
import com.starbattle.client.main.error.ConnectionErrorListener;
import com.starbattle.client.resource.ClientConfiguration;
import com.starbattle.client.views.error.ConnectionErrorView;
import com.starbattle.client.views.lobby.LobbyView;
import com.starbattle.client.views.lobby.friends.AddFriendView;
import com.starbattle.client.views.login.LoginView;
import com.starbattle.client.views.play.PlayView;
import com.starbattle.client.views.profile.PlayerProfileView;
import com.starbattle.client.views.register.RegisterView;
import com.starbattle.client.views.reset.ResetPasswordView;
import com.starbattle.client.views.settings.SettingsView;
import com.starbattle.client.views.shop.ShopView;
import com.starbattle.client.window.GameWindow;
import com.starbattle.client.window.LoadingWindow;
import com.starbattle.network.connection.NetworkRegister;
public class ClientFactory {
private LoadingWindow loadingWindow;
private GameWindow window;
private NetworkConnection connection;
private boolean shutdown = false;
public static Dimension windowSize=new Dimension(1000,600);
public ClientFactory() {
}
public void initClient() {
// Create Loading Window
loadingWindow = new LoadingWindow();
loadingWindow.setMaxProgress(11);// max progress count
Thread loadingWindowThread=new Thread(new Runnable() {
@Override
public void run() {
loadingWindow.open();
}
});
loadingWindowThread.start();
//init client
loadingWindow.loadProgress();
window = new GameWindow(null, "StarBattle Client");
ClientConfiguration.loadConfiguration();
loadingWindow.loadProgress();
// create network connection
loadingWindow.loadProgress();
// add connection error view
window.addView(new ConnectionErrorView(new ConnectionErrorHandler()));
loadingWindow.loadProgress();
try {
connection.start("localhost", NetworkRegister.TCP_PORT,NetworkRegister.UDP_PORT);
loadingWindow.loadProgress();
openWindow();
} catch (IOException e) {
// TODO Auto-generated catch block
if (!shutdown) {
e.printStackTrace();
ConnectionErrorView.setErrorInfo(e);
loadingWindow.close();
window.open(ConnectionErrorView.VIEW_ID);
}
}
}
private void openWindow() {
// create views
window.addView(new LoginView(connection));
loadingWindow.loadProgress();
window.addView(new RegisterView(connection));
loadingWindow.loadProgress();
window.addView(new ResetPasswordView(connection));
loadingWindow.loadProgress();
window.addView(new LobbyView(connection));
loadingWindow.loadProgress();
window.addView(new PlayView(connection));
loadingWindow.loadProgress();
window.addView(new AddFriendView(connection));
loadingWindow.loadProgress();
window.addView(new SettingsView(connection));
loadingWindow.loadProgress();
window.addView(new ShopView(connection));
loadingWindow.loadProgress();
window.addView(new PlayerProfileView(connection));
loadingWindow.loadProgress();
// open login window
window.open(LoginView.VIEW_ID);
loadingWindow.loadProgress();
loadingWindow.close();
}
private class NetworkConnectionHandler implements NetworkConnectionListener {
@Override
public void onConnect() {
System.out.println("Client connected to Server!");
}
@Override
public void onDisconnect(String cause) {
if (!shutdown) {
if(cause!=null)
{
//display disconnect cause
BugSplashDialog.showMessage(cause);
}
loadingWindow.close();
window.open(ConnectionErrorView.VIEW_ID);
}
}
}
// reacts to options in connection error view user inputs
private class ConnectionErrorHandler implements ConnectionErrorListener {
@Override
public void tryReconnect() {
// open everything agian
window.close();
initClient();
}
@Override
public void exit() {
// close
window.close();
System.exit(0);
}
}
}
<file_sep>package com.starbattle.gameserver.game.physics;
public class Location {
private float xpos, ypos;
public Location() {
}
public Location(float x, float y) {
xpos = x;
ypos = y;
}
public void moveX(float x) {
xpos += x;
}
public void moveY(float y) {
ypos = +y;
}
public float getXpos() {
return xpos;
}
public float getYpos() {
return ypos;
}
}
<file_sep>package com.starbattle.ingame.network;
public interface GameSendConnection {
//Send TCP State-Update
public void send(Object object);
}
<file_sep>package com.starbattle.accounts.manager.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import com.starbattle.accounts.database.DatabaseConnection;
import com.starbattle.accounts.manager.AccountException;
import com.starbattle.accounts.manager.TestAccountManager;
import com.starbattle.accounts.player.FriendRelation;
import com.starbattle.accounts.player.FriendRelationState;
import com.starbattle.accounts.player.PlayerAccount;
import com.starbattle.accounts.validation.RegisterState;
public class TestAccountManagerImpl implements TestAccountManager {
private AccountManagerImpl accountManagerImpl;
// TODO Auto-generated method stub
public TestAccountManagerImpl(AccountManagerImpl accountManagerImpl) {
this.accountManagerImpl = accountManagerImpl;
}
/**
* Reset DB, clear all tables
*
* @throws SQLException
*/
@Override
public void deleteDbValues() throws AccountException, SQLException {
DatabaseConnection dbc = accountManagerImpl.getDatabaseConnection();
Connection conn = dbc.getConnection();
PreparedStatement stmt;
String sqlReferentialFalse = "SET REFERENTIAL_INTEGRITY FALSE";
stmt = dbc.getConnection().prepareStatement(sqlReferentialFalse);
stmt.executeUpdate();
conn.commit();
String[] allTables = accountManagerImpl.getAllTables();
for (int i = 0; i < allTables.length; i++) {
System.out.println(allTables[i]);
String sqlTruncate = "TRUNCATE TABLE " + allTables[i];
stmt = dbc.getConnection().prepareStatement(sqlTruncate);
stmt.execute();
}
conn.commit();
String sqlReferentialTrue = "SET REFERENTIAL_INTEGRITY TRUE";
stmt = dbc.getConnection().prepareStatement(sqlReferentialTrue);
stmt.executeUpdate();
conn.commit();
}
@Override
public void addTestAccount(String accountName, String displayName, String password, String email)
throws AccountException {
PlayerAccount account = new PlayerAccount(accountName, displayName, password, email);
if (accountManagerImpl.canRegisterAccount(account) == RegisterState.Register_Ok) {
accountManagerImpl.registerAccount(account);
}
}
/**
* Add Friend Relation row with state 0 (Friend) (Or edit value if row is
* existing)
*/
@Override
public void setFriends(String accountNameSender, String displayNameReceiver) throws AccountException {
accountManagerImpl.newFriendRequest(accountNameSender, displayNameReceiver);
accountManagerImpl.handleFriendRequest(accountNameSender, displayNameReceiver, true);
}
/**
* Add Friend Relation row with state 1 (Request) (Or edit value if row is
* existing)
*/
@Override
public void setFriendRequest(String accountNameSender, String displayNameReceiver) throws AccountException {
accountManagerImpl.newFriendRequest(accountNameSender, displayNameReceiver);
}
/**
* Return friend state value of the row
* @return
*/
@Override
public FriendRelationState getFriendState(String accountNameSender, String displayNameReceiver) throws AccountException {
List<FriendRelation> friendsList = accountManagerImpl.getFriendRelations(accountNameSender).getFriends();
for (FriendRelation friendRelation : friendsList) {
String disp = friendRelation.getDisplayName();
if (disp.equals(displayNameReceiver)) {
return friendRelation.getRelationState();
}
/*
* if
* ((accountNameSender.equalsIgnoreCase(friendRelation.getAccountName
* ()) &&
* displayNameReceiver.equalsIgnoreCase(friendRelation.getDisplayName
* ()) || (accountNameSender
* .equalsIgnoreCase(friendRelation.getDisplayName()) &&
* displayNameReceiver
* .equalsIgnoreCase(friendRelation.getAccountName())))) { return
* friendRelation.getRelationState().getId(); }
*/
}
throw new AccountException("No Relation between Players!");
}
}
<file_sep>package com.starbattle.client.views.play;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import com.starbattle.client.connection.NetworkConnection;
import com.starbattle.client.layout.DesignButton;
import com.starbattle.client.layout.DesignLabel;
import com.starbattle.client.main.StarBattleClient;
import com.starbattle.client.views.lobby.LobbyView;
import com.starbattle.client.window.ContentView;
public class PlayView extends ContentView{
public final static int VIEW_ID = 4;
private GameSettingsDisplay gameSettingsDisplay=new GameSettingsDisplay();
public PlayView(final NetworkConnection networkConnection){
windowSize = StarBattleClient.windowSize;
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 200, 20));
JPanel topPanel=new JPanel();
topPanel.setBackground(new Color(100,100,100));
topPanel.add(new DesignLabel("Game Settings", 30));
DesignButton play = new DesignButton("Play");
play.setFontSize(25f);
play.setButtonStyle(1);
DesignButton cancel = new DesignButton("Cancel");
cancel.setButtonStyle(1);
cancel.setFontSize(25f);
view.setLayout(new BorderLayout());
cancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
openView(LobbyView.VIEW_ID);
}
});
bottomPanel.setBackground(new Color(100,100,100));
bottomPanel.add(cancel);
bottomPanel.add(play);
view.add(bottomPanel, BorderLayout.SOUTH);
view.add(topPanel,BorderLayout.NORTH);
view.add(gameSettingsDisplay.getView(), BorderLayout.CENTER);
}
@Override
protected void initView() {
}
@Override
protected void onClosing() {
}
@Override
public int getViewID() {
return VIEW_ID;
}
}
<file_sep>package com.starbattle.gameserver.game.input;
import com.starbattle.network.connection.objects.NP_Constants;
import com.starbattle.network.connection.objects.game.NP_PlayerUpdate;
public class MovementControl {
private final static float MOVE_FRAME_LENGTH = 10;
private float moveTimer;
/**
* Move Player Left
*/
private boolean moveLeft;
/**
* Move Player Right
*/
private boolean moveRight;
/**
* Move Up ( Jump or move up in fly mode)
*/
private boolean moveUp;
/**
* Move Down (Fall faster or move trough special blocks???)
*/
private boolean moveDown;
public MovementControl() {
}
public void processInput(NP_PlayerUpdate input) {
int vertical = input.verticalMovement;
int horizontal = input.horizontalMovement;
int action = input.action;
moveTimer = 0;
switch (horizontal) {
case NP_Constants.NO_MOVEMENT:
moveLeft = false;
moveRight = false;
break;
case NP_Constants.FORWARD_MOVEMENT:
moveLeft = true;
break;
case NP_Constants.BACKWARD_MOVEMENT:
moveRight = true;
break;
}
switch (vertical) {
case NP_Constants.NO_MOVEMENT:
moveUp=false;
moveDown=false;
break;
case NP_Constants.FORWARD_MOVEMENT:
moveUp=true;
break;
case NP_Constants.BACKWARD_MOVEMENT:
moveDown = true;
break;
}
}
/**
* NOTE: Uodate only after game logic, so no commands will be ignored!
*
* @param delta
*/
public void update(float delta) {
// reset old commands
moveTimer += delta;
if (moveTimer >= MOVE_FRAME_LENGTH) {
moveLeft = false;
moveRight = false;
moveDown = false;
moveUp=false;
}
}
public boolean isMoveLeft() {
return moveLeft;
}
public boolean isMoveRight() {
return moveRight;
}
public boolean isMoveUp() {
return moveUp;
}
public boolean isMoveDown() {
return moveDown;
}
}
<file_sep>package com.starbattle.ingame.resource;
public enum PlayerGraphics {
ASTRONAUT("Astronaut","astronaut.png"),
ALIEN("Alien","alien.png"),
ASTRONAUT_DARK("Astronaut","astronautDunkel.png");
private String name;
private String file;
private PlayerGraphics(String name, String file) {
this.name=name;
this.file=file;
}
public String getFile() {
return file;
}
public String getName() {
return name;
}
}
<file_sep>package com.starbattle.gameserver.game;
import com.starbattle.gameserver.game.mode.GameMode;
import com.starbattle.gameserver.game.mode.PlayerRespawnListener;
import com.starbattle.gameserver.main.BattleInitialization;
import com.starbattle.gameserver.main.BattleParticipant;
import com.starbattle.gameserver.map.ServerMap;
import com.starbattle.gameserver.player.GamePlayer;
import com.starbattle.gameserver.player.container.PlayerList;
public class GameContainer {
private PlayerList playerList;
private ServerMap serverMap;
private GameMode gameMode;
private GameConnection gameUpdate;
public GameContainer(BattleInitialization init) {
// init mode
gameMode = init.getBattleSettings().getMode();
// init players
for (BattleParticipant participant : init.getBattleParticipants()) {
playerList.initPlayer(participant);
}
}
public void startGame() {
// setup objects
playerList = new PlayerList(new PlayerRespawnListener() {
@Override
public void playerRespawned(GamePlayer player) {
gameMode.onPlayerRespawn(player);
}
});
gameUpdate = new GameConnection(this);
}
public void updateGame(double delta) {
}
public GameConnection getGameUpdate() {
return gameUpdate;
}
public PlayerList getPlayerList() {
return playerList;
}
public ServerMap getServerMap() {
return serverMap;
}
}
<file_sep>package com.starbattle.client.views.play;
public interface ModeSelectionListener {
public void seletMode(GameModeEntry entry);
}
| 6a419e9b47423d3cc73336d8e42fde429f877d48 | [
"Java"
] | 20 | Java | stenn21/dhbwStarbattle | e74364fdcb2ae9bf45f9a5748c38caf79a0090ef | 4b702e5bdca9e56ea9bbb458d48849b6faa11ef6 |
refs/heads/main | <repo_name>daniloalves/python-sample-async<file_sep>/demo_asyncio/app.py
from time import sleep
import logging
import aiohttp
import asyncio
logger = logging.getLogger(__name__)
## Example to call:
# python3 ./app.py
async def main():
# await asyncio.sleep(0.1)
print({'status_code': 200, 'message': 'Your request received and in proccess..'})
return 'ok'
async def mock_answer(time=5):
await asyncio.sleep(0.1)
sleep(time)
print(f"Finished your process in {time} seconds!")
return 'ok'
loop = asyncio.get_event_loop()
tasks = [loop.create_task(mock_answer()),loop.create_task(main())]
wait_tasks = asyncio.wait(tasks)
loop.run_until_complete(wait_tasks)
loop.close()<file_sep>/README.md
## Examples Assynchruns and Thread
* `demo_thread` Is possible a async function, because you can answer de request and run a second thread to process and delivery the information.
* `demo_multiprocess` Is similar `demo_thread` both are very simples.
* `demo_asyncio` Is a native python mode, but I fill not simple to implemented together Flask. Other Web framework like FastAPI have a native mode to Async functions.<file_sep>/requirements.txt
aiohttp==3.6.2
async-timeout==3.0.1
attrs==20.2.0
chardet==3.0.4
click==7.1.2
Flask==1.1.2
idna==2.10
idna-ssl==1.1.0
itsdangerous==1.1.0
Jinja2==2.11.2
MarkupSafe==1.1.1
multidict==4.7.6
pkg-resources==0.0.0
typing-extensions==3.7.4.3
Werkzeug==1.0.1
yarl==1.6.0
<file_sep>/demo_thread/app.py
import threading
from time import sleep
from flask import Flask, jsonify
import logging
logger = logging.getLogger(__name__)
app = Flask(__name__)
app.config['DEBUG'] = True
## Example to call:
# curl http://localhost:5000/main
@app.route('/main')
def main():
t1 = threading.Thread(target=mock_answer, args=(5,))
t1.start()
# t1.join()
return jsonify({'status_code': 200, 'message': 'Your request received and in proccess..'})
def mock_answer(time=5):
sleep(time)
app.logger.debug(f"Finished your process in {time} seconds!")
app.run()<file_sep>/demo_multiprocessing/app.py
from multiprocessing import Process
from time import sleep
from flask import Flask, jsonify
import logging
logger = logging.getLogger(__name__)
app = Flask(__name__)
app.config['DEBUG'] = True
## Example to call:
# curl http://localhost:5000/main
@app.route('/main')
def index():
process = Process(target=mock_answer, args=(3,), daemon=True)
process.start()
return jsonify({'status_code': 200, 'message': 'Your request received and in proccess..'})
def mock_answer(time=5):
sleep(time)
app.logger.debug(f"Finished your process in {time} seconds!")
return 'ok'
app.run()
| 3695f3617de3cef8d85b7ac6d6a31b2545c635eb | [
"Markdown",
"Python",
"Text"
] | 5 | Python | daniloalves/python-sample-async | 7b38e63f1e8f847a887ab8261fa3249d8f4e64b3 | 529a0dfa568615e3ea7ba8882bcb35d1d4fd0ca2 |
refs/heads/master | <repo_name>slav-petev/Team-Snowdrop---March-2017<file_sep>/Code/SimpleConditions/08.MetricConverter/MetricConverterExercise.cs
using System;
namespace _08.MetricConverter
{
class MetricConverterExercise
{
static void Main(string[] args)
{
var length = double.Parse(Console.ReadLine());
var sourceMeasureUnit = Console.ReadLine();
var destinationMeasureUnit = Console.ReadLine();
var lengthInMeters = length;
var millimetersInMeter = 1000;
var centimetersInMeter = 100;
var milesInMeter = 0.000621371192;
var inchesInMeter = 39.3700787;
var kilometersInMeter = 0.001;
var feetInMeter = 3.2808399;
var yardsInMeter = 1.0936133;
switch (sourceMeasureUnit)
{
case "mm":
lengthInMeters = length / millimetersInMeter;
break;
case "cm":
lengthInMeters = length / centimetersInMeter;
break;
case "mi":
lengthInMeters = length / milesInMeter;
break;
case "in":
lengthInMeters = length / inchesInMeter;
break;
case "km":
lengthInMeters = length / kilometersInMeter;
break;
case "ft":
lengthInMeters = length / feetInMeter;
break;
case "yd":
lengthInMeters = length / yardsInMeter;
break;
}
double lengthInDestinationMeasureUnit = lengthInMeters;
switch (destinationMeasureUnit)
{
case "mm":
lengthInDestinationMeasureUnit =
lengthInMeters * millimetersInMeter;
break;
case "cm":
lengthInDestinationMeasureUnit =
lengthInMeters * centimetersInMeter;
break;
case "mi":
lengthInDestinationMeasureUnit =
lengthInMeters * milesInMeter;
break;
case "in":
lengthInDestinationMeasureUnit =
lengthInMeters * inchesInMeter;
break;
case "km":
lengthInDestinationMeasureUnit =
lengthInMeters * kilometersInMeter;
break;
case "ft":
lengthInDestinationMeasureUnit =
lengthInMeters * feetInMeter;
break;
case "yd":
lengthInDestinationMeasureUnit =
lengthInMeters * yardsInMeter;
break;
}
Console.WriteLine("{0} {1}",
lengthInDestinationMeasureUnit,
destinationMeasureUnit);
}
}
}
<file_sep>/Code/AdvancedLoops/14.NumberTable/NumberTableExercise.cs
using System;
namespace _14.NumberTable
{
class NumberTableExercise
{
static void Main(string[] args)
{
var tableSize = int.Parse(
Console.ReadLine());
for (var tableRow = 1;
tableRow <= tableSize;
tableRow++)
{
var numberToPrint = tableRow;
var isMaxNumberPrinted = false;
for (var tableColumn = 1;
tableColumn <= tableSize;
tableColumn++)
{
Console.Write("{0} ", numberToPrint);
if (numberToPrint == tableSize)
{
isMaxNumberPrinted = true;
}
if (isMaxNumberPrinted)
{
numberToPrint--;
}
else
{
numberToPrint++;
}
}
Console.WriteLine();
}
}
}
}
<file_sep>/Code/AdvancedLoops/12.Fibonacci/FibonacciExercise.cs
using System;
namespace _12.Fibonacci
{
class FibonacciExercise
{
static void Main(string[] args)
{
var fibonacciNumberPosition =
int.Parse(Console.ReadLine());
switch (fibonacciNumberPosition)
{
case 0:
case 1:
Console.WriteLine(1);
break;
default:
var firstFibonacciNumber = 1;
var secondFibonacciNumber = 1;
var nextFibonacciNumber = 0;
for (var i = 2;
i <= fibonacciNumberPosition;
i++)
{
nextFibonacciNumber =
firstFibonacciNumber +
secondFibonacciNumber;
firstFibonacciNumber =
secondFibonacciNumber;
secondFibonacciNumber =
nextFibonacciNumber;
}
Console.WriteLine(nextFibonacciNumber);
break;
}
}
}
}
<file_sep>/Code/SimpleConditions/01.ExcellentResult/ExcellentResultExercise.cs
using System;
namespace _01.ExcellentResult
{
class ExcellentResultExercise
{
static void Main(string[] args)
{
var grade = double.Parse(
Console.ReadLine());
if (grade >= 5.50)
{
Console.WriteLine("Excellent!");
}
}
}
}
<file_sep>/Code/DrawingWithLoops/10.Diamond/DiamondExercise.cs
using System;
namespace _10.Diamond
{
class DiamondExercise
{
static void Main(string[] args)
{
var diamondSize = int.Parse(
Console.ReadLine());
var numberOfSymbolsPerLine =
diamondSize;
var numberOfStarsInTop = 0;
if (diamondSize % 2 == 0)
{
numberOfStarsInTop = 2;
}
else
{
numberOfStarsInTop = 1;
}
var numberOfDashesPerSideInTop =
(numberOfSymbolsPerLine -
numberOfStarsInTop) / 2;
Console.WriteLine("{0}{1}{0}",
new string('-', numberOfDashesPerSideInTop),
new string('*', numberOfStarsInTop));
var numberOfDashesBetweenStarsInUpperBody = 0;
if (diamondSize % 2 == 0)
{
numberOfDashesBetweenStarsInUpperBody = 2;
}
else
{
numberOfDashesBetweenStarsInUpperBody = 1;
}
var numberOfDashesPerSideInUpperBody = 0;
if (diamondSize % 2 == 0)
{
numberOfDashesPerSideInUpperBody =
diamondSize / 2 - 2;
}
else
{
numberOfDashesPerSideInUpperBody =
diamondSize / 2 - 1;
}
var upperBodyHeight = 0;
if (diamondSize % 2 == 0)
{
upperBodyHeight =
diamondSize / 2 - 2;
}
else
{
upperBodyHeight =
diamondSize / 2 - 1;
}
for (var i = 0;
i <= upperBodyHeight;
i++)
{
Console.WriteLine("{0}*{1}*{0}",
new string('-', numberOfDashesPerSideInUpperBody),
new string('-', numberOfDashesBetweenStarsInUpperBody));
numberOfDashesPerSideInUpperBody--;
numberOfDashesBetweenStarsInUpperBody += 2;
}
var numberOfDashesPerSideInLowerBody = 1;
var numberOfDashesBetweenStarsInLowerBody =
diamondSize - 4;
var lowerBodyHeight = upperBodyHeight;
for (var i = 0;
i < lowerBodyHeight;
i++)
{
Console.WriteLine("{0}*{1}*{0}",
new string('-', numberOfDashesPerSideInLowerBody),
new string('-', numberOfDashesBetweenStarsInLowerBody));
numberOfDashesPerSideInLowerBody++;
numberOfDashesBetweenStarsInLowerBody =
numberOfDashesBetweenStarsInLowerBody - 2;
}
if (diamondSize > 2)
{
var numberOfStarsInBase =
numberOfStarsInTop;
var numberOfDashesPerSideInBase =
numberOfDashesPerSideInTop;
Console.WriteLine("{0}{1}{0}",
new string('-', numberOfDashesPerSideInBase),
new string('*', numberOfStarsInBase));
}
}
}
}
<file_sep>/Code/SImpleLoops/03.LatinLetters/LatinLettersExercise.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _03.LatinLetters
{
class LatinLettersExercise
{
static void Main(string[] args)
{
for (var currentLetter = 'a';
currentLetter <= 'z';
currentLetter++)
{
Console.WriteLine(currentLetter);
}
}
}
}
<file_sep>/Code/ComplexConditionalStatements/07.FruitShop/FruitShopExcercise.cs
using System;
namespace _07.FruitShop
{
class FruitShopExcercise
{
static void Main(string[] args)
{
var fruit = Console.ReadLine();
var dayOfWeek = Console.ReadLine()
.ToLower();
var quantity = double.Parse(
Console.ReadLine());
var fruitPrice = -1.0;
switch (dayOfWeek)
{
case "monday":
case "tuesday":
case "wednesday":
case "thursday":
case "friday":
var bananaWeekPricePerKg = 2.5;
var appleWeekPricePerKg = 1.2;
var orangeWeekPricePerKg = 0.85;
var grapefruitWeekPricePerKg = 1.45;
var kiwiWeekPricePerKg = 2.7;
var pineappleWeekPricePerKg = 5.5;
var grapesWeekPricePerKg = 3.85;
switch (fruit)
{
case "banana":
fruitPrice = quantity *
bananaWeekPricePerKg;
break;
case "apple":
fruitPrice = quantity *
appleWeekPricePerKg;
break;
case "orange":
fruitPrice = quantity *
orangeWeekPricePerKg;
break;
case "grapefruit":
fruitPrice = quantity *
grapefruitWeekPricePerKg;
break;
case "kiwi":
fruitPrice = quantity *
kiwiWeekPricePerKg;
break;
case "pineapple":
fruitPrice = quantity *
pineappleWeekPricePerKg;
break;
case "grapes":
fruitPrice = quantity *
grapesWeekPricePerKg;
break;
default:
Console.WriteLine("error");
break;
}
break;
case "saturday":
case "sunday":
var bananaWeekendPricePerKg = 2.7;
var appleWeekendPricePerKg = 1.25;
var orangeWeekendPricePerKg = 0.9;
var grapefruitWeekendPricePerKg = 1.6;
var kiwiWeekendPricePerKg = 3.0;
var pineappleWeekendPricePerKg = 5.6;
var grapesWeekendPricePerKg = 4.20;
switch (fruit)
{
case "banana":
fruitPrice = quantity *
bananaWeekendPricePerKg;
break;
case "apple":
fruitPrice = quantity *
appleWeekendPricePerKg;
break;
case "orange":
fruitPrice = quantity *
orangeWeekendPricePerKg;
break;
case "grapefruit":
fruitPrice = quantity *
grapefruitWeekendPricePerKg;
break;
case "kiwi":
fruitPrice = quantity *
kiwiWeekendPricePerKg;
break;
case "pineapple":
fruitPrice = quantity *
pineappleWeekendPricePerKg;
break;
case "grapes":
fruitPrice = quantity *
grapesWeekendPricePerKg;
break;
default:
Console.WriteLine("error");
break;
}
break;
default:
Console.WriteLine("error");
break;
}
if (fruitPrice > -1.0)
{
Console.WriteLine("{0:F2}",
fruitPrice);
}
}
}
}
<file_sep>/Code/SImpleLoops/07.LeftAndRightSum/LeftAndRightSumExercise.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _07.LeftAndRightSum
{
class LeftAndRightSumExercise
{
static void Main(string[] args)
{
var numbersCount = int.Parse(
Console.ReadLine());
var leftSum = 0;
var rightSum = 0;
for (var currentLeftNumberPosition = 0;
currentLeftNumberPosition < numbersCount;
currentLeftNumberPosition++)
{
var currentLeftNumber = int.Parse(
Console.ReadLine());
leftSum += currentLeftNumber;
}
for (var currentRighttNumberPosition = 0;
currentRighttNumberPosition < numbersCount;
currentRighttNumberPosition++)
{
var currentRightNumber = int.Parse(
Console.ReadLine());
rightSum += currentRightNumber;
}
if (leftSum == rightSum)
{
Console.WriteLine("Yes, sum = {0}",
leftSum);
}
else
{
var sumDifference = Math
.Abs(leftSum - rightSum);
Console.WriteLine("No, diff = {0}",
sumDifference);
}
}
}
}
<file_sep>/Code/SimpleConditions/16.NumberFromZeroToOneHundredToText/NumberFromZeroToOneHundredToTextExercise.cs
using System;
namespace _16.NumberFromZeroToOneHundredToText
{
class NumberFromZeroToOneHundredToTextExercise
{
static void Main(string[] args)
{
var number = int.Parse(
Console.ReadLine());
if (number < 0 || number > 100)
{
Console.WriteLine("invalid number");
}
else if (number >= 0 && number < 20)
{
switch (number)
{
case 0:
Console.WriteLine("zero");
break;
case 1:
Console.WriteLine("one");
break;
case 2:
Console.WriteLine("two");
break;
case 3:
Console.WriteLine("three");
break;
case 4:
Console.WriteLine("four");
break;
case 5:
Console.WriteLine("five");
break;
case 6:
Console.WriteLine("six");
break;
case 7:
Console.WriteLine("seven");
break;
case 8:
Console.WriteLine("eight");
break;
case 9:
Console.WriteLine("nine");
break;
case 10:
Console.WriteLine("ten");
break;
case 11:
Console.WriteLine("eleven");
break;
case 12:
Console.WriteLine("twelve");
break;
case 13:
Console.WriteLine("thirteen");
break;
case 14:
Console.WriteLine("fourteen");
break;
case 15:
Console.WriteLine("fifteen");
break;
case 16:
Console.WriteLine("sixteen");
break;
case 17:
Console.WriteLine("seventeen");
break;
case 18:
Console.WriteLine("eighteen");
break;
case 19:
Console.WriteLine("nineteen");
break;
}
}
else if (number >= 20 && number < 100)
{
var firstWord = "";
var secondWord = "";
var remainder = number / 10;
switch (remainder)
{
case 2:
firstWord = "Twenty";
break;
case 3:
firstWord = "Thirty";
break;
case 4:
firstWord = "Fourty";
break;
case 5:
firstWord = "Fifty";
break;
case 6:
firstWord = "Sixty";
break;
case 7:
firstWord = "Seventy";
break;
case 8:
firstWord = "Eighty";
break;
case 9:
firstWord = "Ninety";
break;
}
var quotient = number % 10;
switch (quotient)
{
case 1:
secondWord = "one";
break;
case 2:
secondWord = "two";
break;
case 3:
secondWord = "three";
break;
case 4:
secondWord = "four";
break;
case 5:
secondWord = "five";
break;
case 6:
secondWord = "six";
break;
case 7:
secondWord = "seven";
break;
case 8:
secondWord = "eight";
break;
case 9:
secondWord = "nine";
break;
}
var numberName = "";
if (secondWord == "")
{
numberName = firstWord;
}
else
{
numberName = firstWord + " " + secondWord;
}
Console.WriteLine(numberName);
}
else if (number == 100)
{
Console.WriteLine("One Hundred");
}
}
}
}
<file_sep>/Code/SImpleLoops/01.NumbersFromOneToOneHundred/NumbersFromOneToOneHundredExercise.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _01.NumbersFromOneToOneHundred
{
class NumbersFromOneToOneHundredExercise
{
static void Main(string[] args)
{
for (var i = 1;
i <= 100;
i++)
{
Console.WriteLine(i);
}
}
}
}
<file_sep>/Code/AdvancedLoops/06.NumberInRangeFromOneToHundred/NumberInRangeFromOneToHundredExercise.cs
using System;
namespace _06.NumberInRangeFromOneToHundred
{
class NumberInRangeFromOneToHundredExercise
{
static void Main(string[] args)
{
var number = 0;
var isInvalidNumber = false;
do
{
Console.Write("Enter a number in the range [1...100]: ");
number = int.Parse(
Console.ReadLine());
isInvalidNumber = number < 1 ||
number > 100;
}
while (isInvalidNumber);
Console.WriteLine("The number is: {0}",
number);
}
}
}
<file_sep>/Code/SImpleLoops/11.OddEvenPosition/OddEvenPositionExercise.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _11.OddEvenPosition
{
class OddEvenPositionExercise
{
static void Main(string[] args)
{
var numbersCount = int.Parse(
Console.ReadLine());
var oddSumOutputString = "OddSum=";
var oddMinOutputString = "OddMin=";
var oddMaxOutputString = "OddMax=";
var evenSumOutputString = "EvenSum=";
var evenMinOutputString = "EvenMin=";
var evenMaxOutputString = "EvenMax=";
var sumOfNumbersAtOddPositions = 0.0;
var oddMinOutput = "No";
var oddMaxOutput = "No";
var sumOfNumbersAtEvenPosition = 0.0;
var evenMinOutput = "No";
var evenMaxOutput = "No";
if (numbersCount == 1)
{
var number = double.Parse(
Console.ReadLine());
sumOfNumbersAtOddPositions +=
number;
oddMinOutput = number
.ToString();
oddMaxOutput = number
.ToString();
}
else
{
var oddMin = double.MaxValue;
var oddMax = double.MinValue;
var evenMin = double.MaxValue;
var evenMax = double.MinValue;
for (var currentPosition = 1;
currentPosition <= numbersCount;
currentPosition++)
{
var currentNumber = double.Parse(
Console.ReadLine());
if (currentPosition % 2 == 1)
{
sumOfNumbersAtOddPositions +=
currentNumber;
oddMin = Math.Min(oddMin, currentNumber);
oddMax = Math.Max(oddMax, currentNumber);
}
else
{
sumOfNumbersAtEvenPosition +=
currentNumber;
evenMin = Math.Min(evenMin, currentNumber);
evenMax = Math.Max(evenMax, currentNumber);
}
}
oddMinOutput = oddMin
.ToString();
oddMaxOutput = oddMax
.ToString();
evenMinOutput = evenMin
.ToString();
evenMaxOutput = evenMax
.ToString();
}
Console.WriteLine("{0}{1}",
oddSumOutputString,
sumOfNumbersAtOddPositions);
Console.WriteLine("{0}{1}",
oddMinOutputString,
oddMinOutput);
Console.WriteLine("{0}{1}",
oddMaxOutputString,
oddMaxOutput);
Console.WriteLine("{0}{1}",
evenSumOutputString,
sumOfNumbersAtEvenPosition);
Console.WriteLine("{0}{1}",
evenMinOutputString,
evenMinOutput);
Console.WriteLine("{0}{1}",
evenMaxOutputString,
evenMaxOutput);
}
}
}
<file_sep>/Code/SimpleConditions/07.SumSeconds/SumSecondsExercise.cs
using System;
namespace _07.SumSeconds
{
class SumSecondsExercise
{
static void Main(string[] args)
{
var firstTimeInSeconds =
int.Parse(Console.ReadLine());
var secondTimeInSeconds =
int.Parse(Console.ReadLine());
var thirdTimeInSeconds =
int.Parse(Console.ReadLine());
var totalTimeInSeconds =
firstTimeInSeconds +
secondTimeInSeconds +
thirdTimeInSeconds;
var minutesInTotalTime =
totalTimeInSeconds / 60;
var secondsInTotalTime =
totalTimeInSeconds % 60;
Console.WriteLine("{0}:{1:00}",
minutesInTotalTime,
secondsInTotalTime);
}
}
}
<file_sep>/Code/AdvancedLoops/13.NumberPyramid/NumberPyramidExercise.cs
using System;
namespace _13.NumberPyramid
{
class NumberPyramidExercise
{
static void Main(string[] args)
{
var maximumNumberToPrint = int.Parse(
Console.ReadLine());
var currentNumberToPrint = 1;
var numbersToPrintCount = 1;
while (currentNumberToPrint <= maximumNumberToPrint)
{
for (var i = 0;
i < numbersToPrintCount;
i++)
{
Console.Write("{0} ",
currentNumberToPrint);
currentNumberToPrint++;
if (currentNumberToPrint > maximumNumberToPrint)
{
break;
}
}
numbersToPrintCount++;
Console.WriteLine();
}
}
}
}
<file_sep>/Code/SimpleConditions/06.BonusScore/BonusScoreExercise.cs
using System;
namespace _06.BonusScore
{
class BonusScoreExercise
{
static void Main(string[] args)
{
var inputNumber = double.Parse(
Console.ReadLine());
var bonusPoints = 0.0;
if (inputNumber <= 100)
{
bonusPoints = 5;
}
else if (100 < inputNumber &&
inputNumber <= 1000)
{
bonusPoints = 0.2 * inputNumber;
}
else
{
bonusPoints = 0.1 * inputNumber;
}
var aditionalBonusPoints = 0.0;
if (inputNumber % 2 == 0)
{
aditionalBonusPoints = 1;
}
else if (inputNumber % 10 == 5)
{
aditionalBonusPoints = 2;
}
var totalBonusPoints = bonusPoints +
aditionalBonusPoints;
var finalNumber = inputNumber +
totalBonusPoints;
Console.WriteLine(totalBonusPoints);
Console.WriteLine(finalNumber);
}
}
}
<file_sep>/Code/AdvancedLoops/10.CheckPrime/CheckPrimeExercise.cs
using System;
namespace _10.CheckPrime
{
class CheckPrimeExercise
{
static void Main(string[] args)
{
var number = int.Parse(
Console.ReadLine());
var isPrime = true;
if (number < 2)
{
isPrime = false;
}
else
{
var upperBoundaryToCheck =
(int)Math.Sqrt(number);
for (var i = 2;
i <= upperBoundaryToCheck;
i++)
{
if (number % i == 0)
{
isPrime = false;
break;
}
}
}
if (isPrime)
{
Console.WriteLine("Prime");
}
else
{
Console.WriteLine("Not Prime");
}
}
}
}
<file_sep>/Code/ComplexConditionalStatements/13.PointInTheFigure/PointInTheFigureExcercise.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _13.PointInTheFigure
{
class PointInTheFigureExcercise
{
static void Main(string[] args)
{
var blockSize = int.Parse(
Console.ReadLine());
var pointToCheckX = int.Parse(
Console.ReadLine());
var pointToCheckY = int.Parse(
Console.ReadLine());
var lowerRectangleLowerLeftPointX = 0;
var lowerRectangleLowerLeftPointY = 0;
var lowerRectangleLowerRightPointX =
3 * blockSize;
var lowerRectangleUpperLeftPointY =
blockSize;
var pointHorizontallyInsideLowerRectangle =
lowerRectangleLowerLeftPointX <
pointToCheckX &&
pointToCheckX <
lowerRectangleLowerRightPointX;
var pointVerticallyInsideLowerRectangle =
lowerRectangleLowerLeftPointY <
pointToCheckY &&
pointToCheckY <
lowerRectangleUpperLeftPointY;
var pointInsideLowerRectangle =
pointHorizontallyInsideLowerRectangle &&
pointVerticallyInsideLowerRectangle;
var pointHorizontallyOutsideLowerRectangle =
pointToCheckX <
lowerRectangleLowerLeftPointX ||
lowerRectangleLowerRightPointX <
pointToCheckX;
var pointVericallyOutsideLowerRectangle =
pointToCheckY <
lowerRectangleLowerLeftPointY ||
lowerRectangleUpperLeftPointY <
pointToCheckY;
var pointOutsideLowerRectangle =
pointHorizontallyOutsideLowerRectangle ||
pointVericallyOutsideLowerRectangle;
var pointOnBorderOfLowerRectangle =
!pointInsideLowerRectangle &&
!pointOutsideLowerRectangle;
var upperRectangleLowerLeftPointX =
blockSize;
var upperRectangleLowerLeftPointY =
blockSize;
var upperRectangleLowerRightPointX =
2 * blockSize;
var upperRectangleUpperLeftPointY =
4 * blockSize;
var pointHorizontallyInsideupperRectangle =
upperRectangleLowerLeftPointX <
pointToCheckX &&
pointToCheckX <
upperRectangleLowerRightPointX;
var pointVerticallyInsideUpperRectangle =
upperRectangleLowerLeftPointY <
pointToCheckY &&
pointToCheckY <
upperRectangleUpperLeftPointY;
var pointInsideUpperRectangle =
pointHorizontallyInsideupperRectangle &&
pointVerticallyInsideUpperRectangle;
var pointHorizontallyOutsideUpperRectangle =
pointToCheckX <
upperRectangleLowerLeftPointX ||
upperRectangleLowerRightPointX <
pointToCheckX;
var pointVericallyOutsideUpperRectangle =
pointToCheckY <
upperRectangleLowerLeftPointY ||
upperRectangleUpperLeftPointY <
pointToCheckY;
var pointOutsideUpperRectangle =
pointHorizontallyOutsideUpperRectangle ||
pointVericallyOutsideUpperRectangle;
var pointOnBorderOfUpperRectangle =
!pointInsideUpperRectangle &&
!pointOutsideUpperRectangle;
var pointOnCommonSideOfRectangles =
pointOnBorderOfLowerRectangle &&
pointOnBorderOfUpperRectangle &&
blockSize <
pointToCheckX &&
pointToCheckX < 2 * blockSize;
var pointInsideFigure =
pointInsideLowerRectangle ||
pointInsideUpperRectangle ||
pointOnCommonSideOfRectangles;
var pointOutsideFigure =
pointOutsideLowerRectangle &&
pointOutsideUpperRectangle;
var pointOnBorderOfFigure =
!pointInsideFigure &&
!pointOutsideFigure;
if (pointInsideFigure)
{
Console.WriteLine("inside");
}
else if (pointOnBorderOfFigure)
{
Console.WriteLine("border");
}
else
{
Console.WriteLine("outside");
}
}
}
}
<file_sep>/Code/ComplexConditionalStatements/06.PointOnRectangleBorder/PointOnRectangleBorderExcercise.cs
using System;
namespace _06.PointOnRectangleBorder
{
class PointOnRectangleBorderExcercise
{
static void Main(string[] args)
{
var upperLeftPointXCoordinate =
double.Parse(Console.ReadLine());
var upperLeftPointYCoordinate =
double.Parse(Console.ReadLine());
var lowerRightPointXCoordinate =
double.Parse(Console.ReadLine());
var lowerRightPointYCoordinate =
double.Parse(Console.ReadLine());
var pointToCheckXCoordinate =
double.Parse(Console.ReadLine());
var pointToCheckYCoordinate =
double.Parse(Console.ReadLine());
var isPointHorizontallyBetweenGivenRectanglePoints =
upperLeftPointXCoordinate <=
pointToCheckXCoordinate &&
pointToCheckXCoordinate <=
lowerRightPointXCoordinate;
var isPointOnHorizontalSide =
pointToCheckYCoordinate ==
upperLeftPointYCoordinate ||
pointToCheckYCoordinate ==
lowerRightPointYCoordinate;
var isPointVerticallyBetweenGivenRectanglePoints =
upperLeftPointYCoordinate <=
pointToCheckYCoordinate &&
pointToCheckYCoordinate <=
lowerRightPointYCoordinate;
var isPointOnVerticalSide =
pointToCheckXCoordinate ==
upperLeftPointXCoordinate ||
pointToCheckXCoordinate ==
lowerRightPointXCoordinate;
var isPointHorizontallyOnBorder =
isPointHorizontallyBetweenGivenRectanglePoints &&
isPointOnHorizontalSide;
var isPointVerticallyOnBorder =
isPointVerticallyBetweenGivenRectanglePoints &&
isPointOnVerticalSide;
var isPointOnBorder =
isPointHorizontallyOnBorder ||
isPointVerticallyOnBorder;
if (isPointOnBorder)
{
Console.WriteLine("Border");
}
else
{
Console.WriteLine("Inside / Outside");
}
}
}
}
<file_sep>/Code/SimpleConditions/13.AreaOfFigures/AreaOfFiguresExercise.cs
using System;
namespace _13.AreaOfFigures
{
class AreaOfFiguresExercise
{
static void Main(string[] args)
{
var figureType = Console.ReadLine();
var figureArea = 0.0;
if (figureType == "square")
{
var side = double.Parse(
Console.ReadLine());
figureArea = side * side;
}
else if (figureType == "rectangle")
{
var firstSide = double.Parse(
Console.ReadLine());
var secondSide = double.Parse(
Console.ReadLine());
figureArea = firstSide *
secondSide;
}
else if (figureType == "circle")
{
var radius = double.Parse(
Console.ReadLine());
figureArea = Math.PI *
radius * radius;
}
else if (figureType == "triangle")
{
var side = double.Parse(
Console.ReadLine());
var height = double.Parse(
Console.ReadLine());
figureArea = side * height / 2;
}
Console.WriteLine("{0:F3}",
figureArea);
}
}
}
<file_sep>/Code/SimpleConditions/15.ThreeEqualNumbers/ThreeEqualNumbersExcercise.cs
using System;
namespace _15.ThreeEqualNumbers
{
class ThreeEqualNumbersExercise
{
static void Main(string[] args)
{
var firstNumber = double.Parse(
Console.ReadLine());
var secondNumber = double.Parse(
Console.ReadLine());
var thirdNumber = double.Parse(
Console.ReadLine());
if (firstNumber == secondNumber &&
secondNumber == thirdNumber)
{
Console.WriteLine("yes");
}
else
{
Console.WriteLine("no");
}
}
}
}
<file_sep>/Code/DrawingWithLoops/08.Sunglasses/SunglassesExercise.cs
using System;
namespace _08.Sunglasses
{
class SunglassesExercise
{
static void Main(string[] args)
{
var sunglassesSize = int.Parse(
Console.ReadLine());
var numberOfStarsPerSideInTop =
2 * sunglassesSize;
Console.WriteLine("{0}{1}{0}",
new string('*', numberOfStarsPerSideInTop),
new string(' ', sunglassesSize));
var middleRowNumber = 0;
if (sunglassesSize % 2 == 0)
{
middleRowNumber =
sunglassesSize / 2 - 1;
}
else
{
middleRowNumber =
sunglassesSize / 2;
}
var numberOfSymbolsBetweenStarsInBody =
2 * sunglassesSize - 2;
for (var i = 0;
i < sunglassesSize - 2;
i++)
{
var joiningSymbol = '\0';
if (i == middleRowNumber - 1)
{
joiningSymbol = '|';
}
else
{
joiningSymbol = ' ';
}
Console.WriteLine("*{0}*{1}*{0}*",
new string('/', numberOfSymbolsBetweenStarsInBody),
new string(joiningSymbol, sunglassesSize));
}
var numberOfStarsPerSideInBottom =
numberOfStarsPerSideInTop;
Console.WriteLine("{0}{1}{0}",
new string('*', numberOfStarsPerSideInBottom),
new string(' ', sunglassesSize));
}
}
}
<file_sep>/Code/AdvancedLoops/07.GreatestCommonDivisor/GreatestCommonDivisorExercise.cs
using System;
namespace _07.GreatestCommonDivisor
{
class GreatestCommonDivisorExercise
{
static void Main(string[] args)
{
var firstNumber = int.Parse(
Console.ReadLine());
var secondNumber = int.Parse(
Console.ReadLine());
while (secondNumber > 0)
{
var temp = secondNumber;
secondNumber = firstNumber %
secondNumber;
firstNumber = temp;
}
Console.WriteLine(firstNumber);
}
}
}
<file_sep>/Code/DrawingWithLoops/02.RectangleOfNPerNStars/RectangleOfNPerNStarsExercise.cs
using System;
namespace _02.RectangleOfNPerNStars
{
class RectangleOfNPerNStarsExercise
{
static void Main(string[] args)
{
var rectangleSize = int.Parse(
Console.ReadLine());
for (var i = 0;
i < rectangleSize;
i++)
{
Console.WriteLine(
new string('*', rectangleSize));
}
}
}
}
<file_sep>/Code/SImpleLoops/10.HalfSumElement/HalfSumElementExercise.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _10.HalfSumElement
{
class HalfSumElementExercise
{
static void Main(string[] args)
{
var numbersCount = int.Parse(
Console.ReadLine());
var maxNumber = int.MinValue;
var sumElements = 0;
for (var i = 0;
i < numbersCount;
i++)
{
var currentNumber = int.Parse(
Console.ReadLine());
if (currentNumber > maxNumber)
{
maxNumber = currentNumber;
}
sumElements += currentNumber;
}
var sumElementsWithoutMaxNumber = sumElements -
maxNumber;
if (maxNumber == sumElementsWithoutMaxNumber)
{
Console.WriteLine("Yes");
Console.WriteLine("Sum = {0}",
sumElementsWithoutMaxNumber);
}
else
{
var difference = Math
.Abs(maxNumber - sumElementsWithoutMaxNumber);
Console.WriteLine("No");
Console.WriteLine("Diff = {0}",
difference);
}
}
}
}
<file_sep>/Code/ComplexConditionalStatements/05.InvalidNumber/InvalidNumberExcercise.cs
using System;
namespace _05.InvalidNumber
{
class InvalidNumberExcercise
{
static void Main(string[] args)
{
var number = int.Parse(
Console.ReadLine());
var isNumberInvalid =
number != 0 &&
(number < 100 ||
number > 200);
if (isNumberInvalid)
{
Console.WriteLine("invalid");
}
}
}
}
<file_sep>/Code/SimpleConditions/14.TimePlusFifteenMinutes/TimePlusFifteenMinutesExercise.cs
using System;
namespace _14.TimePlusFifteenMinutes
{
class TimePlusFifteenMinutesExercise
{
static void Main(string[] args)
{
var currentHour = int.Parse(
Console.ReadLine());
var currentMinutes = int.Parse(
Console.ReadLine());
var currentHourInMinutes =
currentHour * 60;
var currentTimeInMinutes =
currentHourInMinutes +
currentMinutes;
var timeAfterFifteenMinutesInMinutes =
currentTimeInMinutes + 15;
var hourAfterFifteenMinutes =
timeAfterFifteenMinutesInMinutes / 60;
var minutesAfterFifteenMinutes =
timeAfterFifteenMinutesInMinutes % 60;
/*
We need to display the hours as a number
between 0 and 23. When we divide by 60,
it is possible to get 24. So, using the
% operator, we get the desired value
between 0 and 23.
*/
var hourAfterFifteenMinutesDisplayValue =
hourAfterFifteenMinutes % 24;
Console.WriteLine("{0}:{1:00}",
hourAfterFifteenMinutesDisplayValue,
minutesAfterFifteenMinutes);
}
}
}
<file_sep>/Code/SImpleLoops/08.OddEvenSum/OddEvenSumExercise.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _08.OddEvenSum
{
class OddEvenSumExercise
{
static void Main(string[] args)
{
var numbersCount = int.Parse(
Console.ReadLine());
var oddSum = 0;
var evenSum = 0;
for (var i = 0;
i < numbersCount;
i++)
{
var currentNumber = int.Parse(
Console.ReadLine());
if (i % 2 == 0)
{
evenSum += currentNumber;
}
else
{
oddSum += currentNumber;
}
}
if (oddSum == evenSum)
{
Console.WriteLine("Yes");
Console.WriteLine("Sum = {0}",
oddSum);
}
else
{
var sumDifference = Math
.Abs(oddSum - evenSum);
Console.WriteLine("No");
Console.WriteLine("Diff = {0}",
sumDifference);
}
}
}
}
<file_sep>/Code/SImpleLoops/12.EqualPairs/EqualPairsExercise.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _12.EqualPairs
{
class EqualPairsExercise
{
static void Main(string[] args)
{
var numberOfPairs = int.Parse(
Console.ReadLine());
// We read the first pair before the loop to avoid the if-check inside it.
// For comparison, see the EqualPairsExercise.txt file.
var firstPairFirstNumber = int.Parse(
Console.ReadLine());
var firstPairSecondNumber = int.Parse(
Console.ReadLine());
var lastPairValue = firstPairFirstNumber +
firstPairSecondNumber;
var maxDifference = 0;
for (var i = 0;
i < numberOfPairs - 1;
i++)
{
var currentPairFirstNumber = int.Parse(
Console.ReadLine());
var currentPairSecondNumber = int.Parse(
Console.ReadLine());
var currentPairValue = currentPairFirstNumber +
currentPairSecondNumber;
var currentDifference = Math.Abs(currentPairValue -
lastPairValue);
if (currentDifference > maxDifference)
{
maxDifference = currentDifference;
}
lastPairValue = currentPairValue;
}
if (maxDifference == 0)
{
Console.WriteLine("Yes, value={0}",
lastPairValue);
}
else
{
Console.WriteLine("No, maxdiff={0}",
maxDifference);
}
}
}
}
<file_sep>/Code/DrawingWithLoops/03.SquareOfStars/SquareOfStarsExercise.cs
using System;
namespace _03.SquareOfStars
{
class SquareOfStarsExercise
{
static void Main(string[] args)
{
var squareSize = int.Parse(
Console.ReadLine());
for (var i = 0;
i < squareSize;
i++)
{
for (var j = 0;
j < squareSize;
j++)
{
Console.Write("* ");
}
Console.WriteLine();
}
}
}
}
<file_sep>/Code/DrawingWithLoops/07.ChristmasTree/ChristmasTreeExercise.cs
using System;
class ChristmasTreeExercise
{
static void Main()
{
var christmasTreeSize =
int.Parse(Console.ReadLine());
var christmasTreeHeight =
christmasTreeSize + 1;
for (var i = 0;
i < christmasTreeHeight;
i++)
{
Console.WriteLine("{0}{1} | {1}{0}",
new string(' ', christmasTreeSize - i),
new string('*', i));
}
}
}
<file_sep>/Code/ComplexConditionalStatements/03.PointInRectangle/PointInRectangleExcercise.cs
using System;
namespace _03.PointInRectangle
{
class PointInRectangleExcercise
{
static void Main(string[] args)
{
var upperLeftPointXCoordinate =
double.Parse(Console.ReadLine());
var upperLeftPointYCoordinate =
double.Parse(Console.ReadLine());
var lowerRightPointXCoordinate =
double.Parse(Console.ReadLine());
var lowerRightPointYCoordinate =
double.Parse(Console.ReadLine());
var pointToCheckXCoordinate =
double.Parse(Console.ReadLine());
var pointToCheckYCoordinate =
double.Parse(Console.ReadLine());
bool isPointHorizontallyInside =
upperLeftPointXCoordinate <=
pointToCheckXCoordinate &&
pointToCheckXCoordinate <=
lowerRightPointXCoordinate;
bool isPointVerticallyInside =
upperLeftPointYCoordinate <=
pointToCheckYCoordinate &&
pointToCheckYCoordinate <=
lowerRightPointYCoordinate;
bool isPointInside =
isPointHorizontallyInside &&
isPointVerticallyInside;
if (isPointInside)
{
Console.WriteLine("Inside");
}
else
{
Console.WriteLine("Outside");
}
}
}
}
<file_sep>/Code/SimpleConditions/04.GreaterNumber/GreaterNumberExercise.cs
using System;
namespace _04.GreaterNumber
{
class GreaterNumberExercise
{
static void Main(string[] args)
{
var firstNumber = double.Parse(
Console.ReadLine());
var secondNumber = double.Parse(
Console.ReadLine());
if (firstNumber > secondNumber)
{
Console.WriteLine(firstNumber);
}
else
{
Console.WriteLine(secondNumber);
}
}
}
}
<file_sep>/Code/AdvancedLoops/08.Factorial/FactorialExercise.cs
using System;
namespace _08.Factorial
{
class FactorialExercise
{
static void Main(string[] args)
{
var number = int.Parse(
Console.ReadLine());
var result = 1;
for (var i = 2;
i <= number;
i++)
{
result *= i;
}
Console.WriteLine(result);
}
}
}
<file_sep>/Code/ComplexConditionalStatements/02.SmallSHop/SmallShopExcercise.cs
using System;
namespace _02.SmallSHop
{
class SmallShopExcercise
{
static void Main(string[] args)
{
var product = Console.ReadLine()
.ToLower();
var town = Console.ReadLine()
.ToLower();
var quantity = double.Parse(
Console.ReadLine());
if (town == "sofia")
{
var coffeePriceInSofia = 0.5;
var waterPriceInSofia = 0.8;
var beerPriceInSofia = 1.2;
var sweetsPriceInSofia = 1.45;
var peanutsPriceInSofia = 1.6;
switch (product)
{
case "coffee":
Console.WriteLine(
quantity *
coffeePriceInSofia);
break;
case "water":
Console.WriteLine(
quantity *
waterPriceInSofia);
break;
case "beer":
Console.WriteLine(
quantity *
beerPriceInSofia);
break;
case "sweets":
Console.WriteLine(
quantity *
sweetsPriceInSofia);
break;
case "peanuts":
Console.WriteLine(
quantity *
peanutsPriceInSofia);
break;
}
}
else if (town == "plovdiv")
{
var coffeePriceInPlovdiv = 0.4;
var waterPriceInPlovdiv = 0.7;
var beerPriceInPlovdiv = 1.15;
var sweetsPriceInPlovdiv = 1.3;
var peanutsPriceInPlovdiv = 1.5;
switch (product)
{
case "coffee":
Console.WriteLine(
quantity *
coffeePriceInPlovdiv);
break;
case "water":
Console.WriteLine(
quantity *
waterPriceInPlovdiv);
break;
case "beer":
Console.WriteLine(
quantity *
beerPriceInPlovdiv);
break;
case "sweets":
Console.WriteLine(
quantity *
sweetsPriceInPlovdiv);
break;
case "peanuts":
Console.WriteLine(
quantity *
peanutsPriceInPlovdiv);
break;
}
}
else if (town == "varna")
{
var coffeePriceInVarna = 0.45;
var waterPriceInVarna = 0.7;
var beerPriceInVarna = 1.1;
var sweetsPriceInVarna = 1.35;
var peanutsPriceInVarna = 1.55;
switch (product)
{
case "coffee":
Console.WriteLine(
quantity *
coffeePriceInVarna);
break;
case "water":
Console.WriteLine(
quantity *
waterPriceInVarna);
break;
case "beer":
Console.WriteLine(
quantity *
beerPriceInVarna);
break;
case "sweets":
Console.WriteLine(
quantity *
sweetsPriceInVarna);
break;
case "peanuts":
Console.WriteLine(
quantity *
peanutsPriceInVarna);
break;
}
}
}
}
}
<file_sep>/Code/DrawingWithLoops/06.RhombusOfStars/Program.cs
using System;
namespace _06.RhombusOfStars
{
class Program
{
static void Main(string[] args)
{
var rhombusSize = int.Parse(
Console.ReadLine());
var numberOfSymbolsPerRow = rhombusSize;
var numberOfStarsInUpperPart = 1;
var numberOfWhitespacesInUpperPart =
numberOfSymbolsPerRow -
numberOfStarsInUpperPart;
var upperPartHeight = rhombusSize;
for (var i = 0;
i < upperPartHeight;
i++)
{
var whitespaces = new string(' ',
numberOfWhitespacesInUpperPart);
Console.Write(whitespaces);
for (var j = 0;
j < numberOfStarsInUpperPart;
j++)
{
Console.Write("* ");
}
Console.WriteLine();
numberOfStarsInUpperPart++;
numberOfWhitespacesInUpperPart--;
}
var numberOfStarsInLowerPart =
rhombusSize - 1;
var numberOfWhitespacesInLowerPart =
numberOfSymbolsPerRow -
numberOfStarsInLowerPart;
var lowerPartHeight =
rhombusSize - 1;
for (var i = 0;
i < lowerPartHeight;
i++)
{
var whitespaces =
new string(' ',
numberOfWhitespacesInLowerPart);
Console.Write(whitespaces);
for (var j = 0;
j < numberOfStarsInLowerPart;
j++)
{
Console.Write("* ");
}
Console.WriteLine();
numberOfStarsInLowerPart--;
numberOfWhitespacesInLowerPart++;
}
}
}
}
<file_sep>/Code/AdvancedLoops/01.NumbersFromOneToNWithStepThree/NumbersFromOneToNWithStepThreeExercise.cs
using System;
namespace _01.NumbersFromOneToNWithStepThree
{
class NumbersFromOneToNWithStepThreeExercise
{
static void Main(string[] args)
{
var number = int.Parse(
Console.ReadLine());
for (var i = 1;
i <= number;
i += 3)
{
Console.WriteLine(i);
}
}
}
}
<file_sep>/Code/AdvancedLoops/05.SequenceTwoTimesKPlusOne/SequenceTwoTimesKPlusOneExercise.cs
using System;
namespace _05.SequenceTwoTimesKPlusOne
{
class SequenceTwoTimesKPlusOneExercise
{
static void Main(string[] args)
{
var sequenceUpperBound = int.Parse(
Console.ReadLine());
var currentNumber = 1;
while (currentNumber <= sequenceUpperBound)
{
Console.WriteLine(currentNumber);
currentNumber = currentNumber * 2
+ 1;
}
}
}
}
<file_sep>/Code/ComplexConditionalStatements/12.Volleyball/VolleyballExcercise.cs
using System;
namespace _12.Volleyball
{
class VolleyballExcercise
{
static void Main(string[] args)
{
var yearType = Console.ReadLine();
var holidays = int.Parse(
Console.ReadLine());
var weekendsInHomeTown = int.Parse(
Console.ReadLine());
var weekendsInYear = 48;
var numberOfWeekendsInSofia =
weekendsInYear - weekendsInHomeTown;
var numberOfVolleyballWeekendsInSofia =
3.0 * numberOfWeekendsInSofia / 4.0;
var volleyballHolidays =
2.0 * holidays / 3.0;
var numberOfVolleyballDaysInSofia =
numberOfVolleyballWeekendsInSofia +
volleyballHolidays;
var numberOfVolleyballDaysInHomeTown = weekendsInHomeTown;
var numberOfVolleyBallDaysInYear =
numberOfVolleyballDaysInSofia +
numberOfVolleyballDaysInHomeTown;
if (yearType == "leap")
{
numberOfVolleyBallDaysInYear *= 1.15;
}
Console.WriteLine(
(int)(numberOfVolleyBallDaysInYear));
}
}
}
<file_sep>/Code/SImpleLoops/02.NumbersEndingInSeven/NumbersEndingInSevenExercise.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _02.NumbersEndingInSeven
{
class NumbersEndingInSevenExercise
{
static void Main(string[] args)
{
/*
We want to print only the
numbers between 1 and 1000
that end in 7. The first such
number is 7. We get every next
such number when we add 10 to the
preceeding number.
*/
for (var i = 7;
i <= 1000;
i += 10)
{
Console.WriteLine(i);
}
}
}
}
<file_sep>/Code/DrawingWithLoops/01.RectangleOfTenPerTenStars/RectangleOfTenPerTenStarsExercise.cs
using System;
namespace _01.RectangleOfTenPerTenStars
{
class RectangleOfTenPerTenStarsExercise
{
static void Main(string[] args)
{
for (var i = 0;
i < 10;
i++)
{
Console.WriteLine(
new string('*', 10));
}
}
}
}
<file_sep>/Code/SImpleLoops/05.MaxNumber/MaxNumberExercise.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _05.MaxNumber
{
class MaxNumberExercise
{
static void Main(string[] args)
{
var numbersCount = int.Parse(
Console.ReadLine());
var maxNumber = int.MinValue;
for (var i = 0;
i < numbersCount;
i++)
{
var currentNumber = int.Parse(
Console.ReadLine());
maxNumber = Math.Max(currentNumber,
maxNumber);
}
Console.WriteLine(maxNumber);
}
}
}
<file_sep>/Code/ComplexConditionalStatements/08.TradeComissions/TradeComissionsExcercise.cs
using System;
namespace _08.TradeComissions
{
class TradeComissionsExcercise
{
static void Main(string[] args)
{
var town = Console.ReadLine()
.ToLower();
var numberOfSales = double.Parse(
Console.ReadLine());
var comissionRate = -1.0;
switch (town)
{
case "sofia":
if (0 <= numberOfSales && numberOfSales <= 500)
{
comissionRate = 0.05;
}
else if (500 < numberOfSales && numberOfSales <= 1000)
{
comissionRate = 0.07;
}
else if (1000 < numberOfSales && numberOfSales <= 10000)
{
comissionRate = 0.08;
}
else if (10000 < numberOfSales)
{
comissionRate = 0.12;
}
break;
case "varna":
if (0 <= numberOfSales && numberOfSales <= 500)
{
comissionRate = 0.045;
}
else if (500 < numberOfSales && numberOfSales <= 1000)
{
comissionRate = 0.075;
}
else if (1000 < numberOfSales && numberOfSales <= 10000)
{
comissionRate = 0.1;
}
else if (10000 < numberOfSales)
{
comissionRate = 0.13;
}
break;
case "plovdiv":
if (0 <= numberOfSales && numberOfSales <= 500)
{
comissionRate = 0.055;
}
else if (500 < numberOfSales && numberOfSales <= 1000)
{
comissionRate = 0.08;
}
else if (1000 < numberOfSales && numberOfSales <= 10000)
{
comissionRate = 0.12;
}
else if (10000 < numberOfSales)
{
comissionRate = 0.145;
}
break;
default:
Console.WriteLine("error");
break;
}
if (numberOfSales >= 0)
{
var tradeComission =
numberOfSales * comissionRate;
Console.WriteLine("{0:F2}",
tradeComission);
}
else
{
Console.WriteLine("error");
}
}
}
}
<file_sep>/Code/DrawingWithLoops/05.SquareFrame/SquareFrameExercise.cs
using System;
namespace _05.SquareFrame
{
class SquareFrameExercise
{
static void Main(string[] args)
{
var frameSize = int.Parse(
Console.ReadLine());
var numberOfDashesPerLine =
frameSize - 2;
Console.Write("+ ");
for (var i = 0;
i < numberOfDashesPerLine;
i++)
{
Console.Write("- ");
}
Console.WriteLine("+");
var frameBodyHeight =
frameSize - 2;
for (var i = 0;
i < frameBodyHeight;
i++)
{
Console.Write("| ");
for (var j = 0;
j < numberOfDashesPerLine;
j++)
{
Console.Write("- ");
}
Console.WriteLine("|");
}
Console.Write("+ ");
for (var i = 0;
i < numberOfDashesPerLine;
i++)
{
Console.Write("- ");
}
Console.WriteLine("+");
}
}
}
<file_sep>/Code/AdvancedLoops/09.SumDigits/SumDigitsExercise.cs
using System;
namespace _09.SumDigits
{
class SumDigitsExercise
{
static void Main(string[] args)
{
var number = int.Parse(
Console.ReadLine());
var digitsSum = 0;
while (number > 0)
{
var lastDigit =
number % 10;
digitsSum +=
lastDigit;
number /= 10;
}
Console.WriteLine(digitsSum);
}
}
}
<file_sep>/Code/ComplexConditionalStatements/11.Cinema/CinemaExcercise.cs
using System;
namespace _11.Cinema
{
class CinemaExcercise
{
static void Main(string[] args)
{
var projectionType =
Console.ReadLine();
var numberOfRowsInHall =
int.Parse(Console.ReadLine());
var numberOfColumnsInHall =
int.Parse(Console.ReadLine());
var numberOfSeatsInHall =
numberOfRowsInHall *
numberOfColumnsInHall;
var premierePrice = 12.00;
var normalPrice = 7.50;
var discountPrice = 5.00;
var totalIncome = -1.00;
switch (projectionType)
{
case "Premiere":
totalIncome =
numberOfSeatsInHall *
premierePrice;
break;
case "Normal":
totalIncome =
numberOfSeatsInHall *
normalPrice;
break;
case "Discount":
totalIncome =
numberOfSeatsInHall *
discountPrice;
break;
}
Console.WriteLine("{0:F2}",
totalIncome);
}
}
}
<file_sep>/Code/DrawingWithLoops/04.TriangleOfDollars/TriangleOfDollarsExercise.cs
using System;
namespace _04.TriangleOfDollars
{
class TriangleOfDollarsExercise
{
static void Main(string[] args)
{
var triangleSize = int.Parse(
Console.ReadLine());
for (var i = 1;
i <= triangleSize;
i++)
{
for (var j = 1;
j <= i;
j++)
{
Console.Write("$ ");
}
Console.WriteLine();
}
}
}
}
<file_sep>/Code/SImpleLoops/09.VowelsSum/VowelsSumExercise.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _09.VowelsSum
{
class VowelsSumExercise
{
static void Main(string[] args)
{
var word = Console.ReadLine();
var vowelsSum = 0;
for (var i = 0;
i < word.Length;
i++)
{
switch (word[i])
{
case 'a':
vowelsSum += 1;
break;
case 'e':
vowelsSum += 2;
break;
case 'i':
vowelsSum += 3;
break;
case 'o':
vowelsSum += 4;
break;
case 'u':
vowelsSum += 5;
break;
}
Console.WriteLine(vowelsSum);
}
}
}
}
<file_sep>/Code/SImpleLoops/06.MinNumber/MinNumberExercise.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _06.MinNumber
{
class MinNumberExercise
{
static void Main(string[] args)
{
var numbersCount = int.Parse(
Console.ReadLine());
var minNumber = int.MaxValue;
for (var i = 0;
i < numbersCount;
i++)
{
var currentNumber = int.Parse(
Console.ReadLine()); ;
minNumber = Math.Min(currentNumber,
minNumber);
}
Console.WriteLine(minNumber);
}
}
}
<file_sep>/Code/AdvancedLoops/02.NumbersFromNToOne/NumbersFromNToOneExercise.cs
using System;
namespace _02.NumbersFromNToOne
{
class NumbersFromNToOneExercise
{
static void Main(string[] args)
{
var number = int.Parse(
Console.ReadLine());
for (var i = number;
i > 0;
i--)
{
Console.WriteLine(i);
}
}
}
}
<file_sep>/Code/AdvancedLoops/11.EnterEvenNumber/EnterEvenNumberExercise.cs
using System;
namespace _11.EnterEvenNumber
{
class EnterEvenNumberExercise
{
static void Main(string[] args)
{
var number = 0;
var isInvalidNumber = false;
do
{
try
{
isInvalidNumber = false;
Console.Write("Enter even number: ");
number = int.Parse(
Console.ReadLine());
if (Math.Abs(number % 2) == 1)
{
Console.WriteLine("The number is not even");
isInvalidNumber = true;
}
}
catch (Exception)
{
isInvalidNumber = true;
Console.WriteLine("Invalid number!");
}
}
while (isInvalidNumber);
Console.WriteLine("Even number entered: {0}",
number);
}
}
}
| 1c58e23e83c1331b4ead0c420dd0ef87628e5c6a | [
"C#"
] | 50 | C# | slav-petev/Team-Snowdrop---March-2017 | 582b7ea9f695c6f09485d0e1e82f885d9b28879b | c5e5aecdda2dfecdbf9d9384896194e8d4e9808d |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace Alauda
{
public enum SpinnerType
{
[Description("数字1")]
One,
[Description("当前单位的一个")]
CurrentOneUnit,
[Description("自定义倍数")]
CustomScale,
[Description("自定义步长")]
CustomIncrement,
}
/// <summary>
/// 数字输入控件
/// </summary>
[TemplatePart(Name = PART_TextBox, Type = typeof(TextBox))]
[TemplatePart(Name = PART_IncrementButton, Type = typeof(Button))]
[TemplatePart(Name = PART_DecrementButton, Type = typeof(Button))]
public class NumberBox : Control
{
private const string PART_TextBox = "PART_TextBox";
private const string PART_IncrementButton = "PART_IncrementButton";
private const string PART_DecrementButton = "PART_DecrementButton";
private Dictionary<string, ulong> baseOrders = new Dictionary<string, ulong>() {
{ "K", 1000 }, { "M", 1000000 }, { "G", 1000000000 } , { "T", 1000000000000 } , { "P", 1000000000000000 } };
private Dictionary<string, ulong> orders = new Dictionary<string, ulong>() {
{ "K", 1000 }, { "M", 1000000 }, { "G", 1000000000 } , { "T", 1000000000000 } , { "P", 1000000000000000 } };
private TextBox _tbxNumber;// 数据输入框部分
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(NumberBox),
new FrameworkPropertyMetadata(0d, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(ValuePropertyChangedCallback)));
static void ValuePropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var oldValue = (double)e.OldValue;
var newValue = (double)e.NewValue;
var control = (NumberBox)sender;
if (control._tbxNumber != null)
{
control.ShowNumber(oldValue, newValue);
}
}
/// <summary>
/// 处理的数字
/// </summary>
public double Value
{
get { return (double)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static readonly DependencyProperty DecimalDigitsProperty = DependencyProperty.Register("DecimalDigits", typeof(int), typeof(NumberBox), new PropertyMetadata(6));
/// <summary>
/// 最多显示的小数位数
/// </summary>
public int DecimalDigits
{
get { return (int)GetValue(DecimalDigitsProperty); }
set { SetValue(DecimalDigitsProperty, value); }
}
public static readonly DependencyProperty BasicUnitProperty = DependencyProperty.Register("BasicUnit", typeof(string), typeof(NumberBox),
new PropertyMetadata(new PropertyChangedCallback(BasicUnitPropertyChangedCallback)));
static void BasicUnitPropertyChangedCallback(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var value = (string)e.NewValue;
var control = (NumberBox)sender;
control.orders.Clear();
foreach (var item in control.baseOrders)
{
control.orders.Add(item.Key, item.Value);
}
//control.orders.Add("K" + value, 1000);
//control.orders.Add("M" + value, 1000000);
//control.orders.Add("G" + value, 1000000000);
//control.orders.Add("T" + value, 1000000000000);
//control.orders.Add("P" + value, 1000000000000000);
var length = value.Length;
for (var index = 1; index <= length; index++)
{
var suffix = value.Substring(0, index);
control.orders.Add("K" + suffix, 1000);
control.orders.Add("M" + suffix, 1000000);
control.orders.Add("G" + suffix, 1000000000);
control.orders.Add("T" + suffix, 1000000000000);
control.orders.Add("P" + suffix, 1000000000000000);
}
control.orders.Add(value, 1);
}
/// <summary>
/// 基本单位,进制采用K,M,G,T,P
/// </summary>
public string BasicUnit
{
get { return (string)GetValue(BasicUnitProperty); }
set { SetValue(BasicUnitProperty, value); }
}
public static readonly DependencyProperty IsUnitFormatEnabledProperty = DependencyProperty.Register("IsUnitFormatEnabled", typeof(bool), typeof(NumberBox), new PropertyMetadata(true));
/// <summary>
/// 获取或设置用单位格式化数值是否可用
/// </summary>
public bool IsUnitFormatEnabled
{
get { return (bool)GetValue(IsUnitFormatEnabledProperty); }
set { SetValue(IsUnitFormatEnabledProperty, value); }
}
public static readonly DependencyProperty HasIntervalPrecedingUnitProperty = DependencyProperty.Register("HasIntervalPrecedingUnit", typeof(bool), typeof(NumberBox), new PropertyMetadata(true));
/// <summary>
/// 获取或设置在单位前是否显示一个空白
/// </summary>
public bool HasIntervalPrecedingUnit
{
get { return (bool)GetValue(HasIntervalPrecedingUnitProperty); }
set { SetValue(HasIntervalPrecedingUnitProperty, value); }
}
public static readonly DependencyProperty AllowSpinnerSpinProperty = DependencyProperty.Register("AllowSpinnerSpin", typeof(bool), typeof(NumberBox), new PropertyMetadata(true));
/// <summary>
/// 启用/禁用微调按钮,在默认情况下就是右侧上下按钮
/// </summary>
public bool AllowSpinnerSpin
{
get { return (bool)GetValue(AllowSpinnerSpinProperty); }
set { SetValue(AllowSpinnerSpinProperty, value); }
}
public static readonly DependencyProperty MouseWheelSpinnerActiveProperty = DependencyProperty.Register("MouseWheelSpinnerActive", typeof(bool), typeof(NumberBox), new PropertyMetadata(true));
/// <summary>
/// 启用/禁用鼠标滚动微调
/// </summary>
public bool MouseWheelSpinnerActive
{
get { return (bool)GetValue(MouseWheelSpinnerActiveProperty); }
set { SetValue(MouseWheelSpinnerActiveProperty, value); }
}
public static readonly DependencyProperty SpinnerMoudleProperty = DependencyProperty.Register("SpinnerMoudle", typeof(SpinnerType), typeof(NumberBox), new PropertyMetadata(SpinnerType.One));
/// <summary>
/// 微调模式
/// </summary>
public SpinnerType SpinnerMoudle
{
get { return (SpinnerType)GetValue(SpinnerMoudleProperty); }
set { SetValue(SpinnerMoudleProperty, value); }
}
public static readonly DependencyProperty IncrementProperty = DependencyProperty.Register("Increment", typeof(double), typeof(NumberBox));
/// <summary>
/// 微调的增量,在微调模式CustomIncrement下可用
/// </summary>
public double Increment
{
get { return (double)GetValue(IncrementProperty); }
set { SetValue(IncrementProperty, value); }
}
public static readonly DependencyProperty ScaleProperty = DependencyProperty.Register("Scale", typeof(double), typeof(NumberBox));
/// <summary>
/// 微调缩放的比例,在微调模式CustomScale下可用
/// </summary>
public double Scale
{
get { return (double)GetValue(ScaleProperty); }
set { SetValue(ScaleProperty, value); }
}
public static readonly new DependencyProperty BackgroundProperty = DependencyProperty.Register("Background", typeof(Brush), typeof(NumberBox));
public new Brush Background
{
get { return (Brush)GetValue(BackgroundProperty); }
set { SetValue(BackgroundProperty, value); }
}
public static readonly DependencyProperty InputBackgroundProperty = DependencyProperty.Register("InputBackground", typeof(Brush), typeof(NumberBox));
/// <summary>
/// 输入区域背景颜色
/// </summary>
public Brush InputBackground
{
get { return (Brush)GetValue(InputBackgroundProperty); }
set { SetValue(InputBackgroundProperty, value); }
}
public static readonly DependencyProperty SpinnerSpinBackgroundProperty = DependencyProperty.Register("SpinnerSpinBackground", typeof(Brush), typeof(NumberBox));
/// <summary>
/// 微调区域的背景颜色
/// </summary>
public Brush SpinnerSpinBackground
{
get { return (Brush)GetValue(SpinnerSpinBackgroundProperty); }
set { SetValue(SpinnerSpinBackgroundProperty, value); }
}
public static readonly DependencyProperty IsFocusProperty = DependencyProperty.Register("IsFocus", typeof(bool), typeof(NumberBox));
public bool IsFocus
{
get { return (bool)GetValue(IsFocusProperty); }
set { SetValue(IsFocusProperty, value); }
}
public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(NumberBox));
/// <summary>
/// 圆角尺寸
/// </summary>
public CornerRadius CornerRadius { get; set; }
static NumberBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(NumberBox), new FrameworkPropertyMetadata(typeof(NumberBox)));
}
public NumberBox()
{
this.MouseWheel += Self_MouseWheel;
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_tbxNumber = GetTemplateChild(PART_TextBox) as TextBox;
_tbxNumber.KeyDown += _tbxNumber_KeyDown;
_tbxNumber.PreviewMouseDown += _tbxNumber_PreviewMouseDown;
_tbxNumber.GotFocus += _tbxNumber_GotFocus;
_tbxNumber.LostFocus += _tbxNumber_LostFocus;
ShowNumber(0, Value);// 初始化界面值
var btnUp = GetTemplateChild(PART_IncrementButton) as Button;
if (btnUp != null)
{
btnUp.Click += Button_up_Click;
}
var btnDown = GetTemplateChild(PART_DecrementButton) as Button;
if (btnDown != null)
{
btnDown.Click += Button_down_Click;
}
}
private void _tbxNumber_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Enter) return;
DoChanged();
}
private void _tbxNumber_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
_tbxNumber.Focus();
e.Handled = true;
}
private void _tbxNumber_GotFocus(object sender, RoutedEventArgs e)
{
IsFocus = true;
_tbxNumber.SelectAll();
_tbxNumber.PreviewMouseDown -= _tbxNumber_PreviewMouseDown;
}
private void _tbxNumber_LostFocus(object sender, RoutedEventArgs e)
{
_tbxNumber.PreviewMouseDown += _tbxNumber_PreviewMouseDown;
IsFocus = false;
DoChanged();
}
private void ShowNumber(double oldValue, double newValue)
{
if (!IsUnitFormatEnabled)
{
_tbxNumber.Text = newValue.ToString();
_tbxNumber.SelectionStart = _tbxNumber.Text.Length;
return;
}
var displayValue = 0d;
var decimalDigits = 0;
var unit = BasicUnit;
if (newValue < 1e3 && newValue > -1e3)
{
displayValue = newValue;
decimalDigits = 0;
}
else if (newValue < 1e6 && newValue > -1e6)
{
displayValue = newValue / 1e3;
decimalDigits = 3;
unit = "K" + BasicUnit;
}
else if (newValue < 1e9 && newValue > -1e9)
{
displayValue = newValue / 1e6;
decimalDigits = 6;
unit = "M" + BasicUnit;
}
else if (newValue < 1e12 && newValue > -1e12)
{
displayValue = newValue / 1e9;
decimalDigits = 9;
unit = "G" + BasicUnit;
}
else if (newValue < 1e15 && newValue > -1e15)
{
displayValue = newValue / 1e12;
decimalDigits = 12;
unit = "T" + BasicUnit;
}
else if (newValue < 1e18 && newValue > -1e18)
{
displayValue = newValue / 1e15;
decimalDigits = 15;
unit = "P" + BasicUnit;
}
else
{
Value = oldValue;// 超出范围用旧值重新覆盖
}
if (decimalDigits > DecimalDigits)
{
decimalDigits = DecimalDigits;
}
if (string.IsNullOrWhiteSpace(unit))
{
_tbxNumber.Text = displayValue.ToString();
}
else
{
if (HasIntervalPrecedingUnit)
{
_tbxNumber.Text = string.Format("{0:F" + decimalDigits + "} {1}", displayValue, unit);
}
else
{
_tbxNumber.Text = string.Format("{0:F" + decimalDigits + "}{1}", displayValue, unit);
}
}
_tbxNumber.SelectionStart = _tbxNumber.Text.Length;
}
private void DoChanged()
{
var text = _tbxNumber.Text;
// 为空时
if (string.IsNullOrEmpty(text))
{
Value = 0;
return;
}
if (!text.EndsWith(" "))
{
// 为整数时
double newNumber;
if (double.TryParse(text, out newNumber))
{
var oldNumber = Value;
if (oldNumber == newNumber)
{
ShowNumber(0, Value);
}
else
{
Value = newNumber;
}
return;
}
// 有后缀时
foreach (var item in orders.Keys)
{
if (text.ToLower().EndsWith(item.ToLower()))
{
decimal numberD;
var numText = text.Substring(0, text.Length - item.Length);
if (decimal.TryParse(numText, out numberD))
{
var order = orders[item];
newNumber = (double)(numberD * order);
var oldNumber = Value;
if (oldNumber == newNumber)
{
ShowNumber(0, Value);
}
else
{
Value = newNumber;
}
return;
}
else
{
continue;
}
}
}
}
// 输入错误字符时
var temp = Value;
Value = Value + 1;
Value = temp;
//var oldStart = _tbxNumber.SelectionStart;
//_tbxNumber.Text = Number.ToString();
//_tbxNumber.SelectionStart = oldStart > 0 ? oldStart - 1 : 1;
}
private void Button_down_Click(object sender, RoutedEventArgs e)
{
switch (SpinnerMoudle)
{
case SpinnerType.One:
Value = Value - 1;
break;
case SpinnerType.CurrentOneUnit:
Value = Value - GetFormatOneUnit(Value);
break;
case SpinnerType.CustomScale:
Value = Value - Value * Scale;
break;
case SpinnerType.CustomIncrement:
Value = Value - Increment;
break;
}
}
private void Button_up_Click(object sender, RoutedEventArgs e)
{
switch (SpinnerMoudle)
{
case SpinnerType.One:
Value = Value + 1;
break;
case SpinnerType.CurrentOneUnit:
Value = Value + GetFormatOneUnit(Value);
break;
case SpinnerType.CustomScale:
Value = Value + Value * Scale;
break;
case SpinnerType.CustomIncrement:
Value = Value + Increment;
break;
}
}
// 当鼠标在空间上滚动时
private void Self_MouseWheel(object sender, MouseWheelEventArgs e)
{
if (!MouseWheelSpinnerActive) return;
var scale = e.Delta / 120;
switch (SpinnerMoudle)
{
case SpinnerType.One:
Value = Value + scale * 1;
break;
case SpinnerType.CurrentOneUnit:
Value = Value + scale * GetFormatOneUnit(Value);
break;
case SpinnerType.CustomScale:
Value = Value + scale * Value * Scale;
break;
case SpinnerType.CustomIncrement:
Value = Value + scale * Increment;
break;
}
}
private double GetFormatOneUnit(double newValue)
{
double retValue = 1;
if (newValue < 1e3 && newValue > -1e3)
{
retValue = 1;
}
else if (newValue < 1e6 && newValue > -1e6)
{
retValue = 1e3;
}
else if (newValue < 1e9 && newValue > -1e9)
{
retValue = 1e6;
}
else if (newValue < 1e12 && newValue > -1e12)
{
retValue = 1e9;
}
else if (newValue < 1e15 && newValue > -1e15)
{
retValue = 1e12;
}
else if (newValue < 1e18 && newValue > -1e18)
{
retValue = 1e15;
}
else
{
retValue = 1;
}
return retValue;
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
namespace Alauda
{
public class MultiSelectorAttach : DependencyObject
{
public static IList GetSelectedItemList(DependencyObject obj)
{
return (IList)obj.GetValue(SelectedItemListProperty);
}
public static void SetSelectedItemList(DependencyObject obj, IList value)
{
obj.SetValue(SelectedItemListProperty, value);
}
// Using a DependencyProperty as the backing store for SelectedItemList. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedItemListProperty =
DependencyProperty.RegisterAttached("SelectedItemList", typeof(IList), typeof(MultiSelectorAttach), new PropertyMetadata(new PropertyChangedCallback(SelectedItemListPropertyChanged)));
private static void SelectedItemListPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
MultiSelector selector = sender as MultiSelector;
if (selector != null)
{
if (e.OldValue == null && e.NewValue != null)
{
selector.SelectionChanged += Selector_SelectionChanged; ;
}
else if (e.OldValue != null && e.NewValue == null)
{
selector.SelectionChanged -= Selector_SelectionChanged;
}
}
}
private static void Selector_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selector = sender as MultiSelector;
SetSelectedItemList(selector, selector.SelectedItems);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Alauda
{
public class MultiLineView : ItemsControl
{
private bool AutoScroll = true;
static MultiLineView()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MultiLineView), new FrameworkPropertyMetadata(typeof(MultiLineView)));
}
public MultiLineView()
{
AddHandler(ScrollViewer.ScrollChangedEvent, new ScrollChangedEventHandler(ScroolViewer_ScrollChanged), true);
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var scrollViewer = GetTemplateChild("PART_ScroolViewer") as ScrollViewer;
}
private void ScroolViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
var scrollViewer = e.OriginalSource as ScrollViewer;
// User scroll event : set or unset autoscroll mode
if (e.ExtentHeightChange == 0)
{ // Content unchanged : user scroll event
if (scrollViewer.VerticalOffset == scrollViewer.ScrollableHeight)
{ // Scroll bar is in bottom
// Set autoscroll mode
AutoScroll = true;
}
else
{ // Scroll bar isn't in bottom
// Unset autoscroll mode
AutoScroll = false;
}
}
// Content scroll event : autoscroll eventually
if (AutoScroll && e.ExtentHeightChange != 0)
{ // Content changed and autoscroll mode set
// Autoscroll
scrollViewer.ScrollToVerticalOffset(scrollViewer.ExtentHeight);
}
e.Handled = true;
}
}
}
<file_sep>using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace Alauda
{
/// <summary>
/// 图标按钮
/// </summary>
public class IconButton : Button
{
public static DependencyProperty NormalImageProperty = DependencyProperty.Register("NormalImage", typeof(ImageSource), typeof(IconButton), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsArrange, null));
public ImageSource NormalImage
{
get
{
return (ImageSource)GetValue(NormalImageProperty);
}
set
{
SetValue(NormalImageProperty, value);
}
}
public static DependencyProperty PressedImageProperty = DependencyProperty.Register("PressedImage", typeof(ImageSource), typeof(IconButton), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsArrange, null));
public ImageSource PressedImage
{
get
{
return (ImageSource)GetValue(PressedImageProperty);
}
set
{
SetValue(PressedImageProperty, value);
}
}
public static DependencyProperty HoverImageProperty = DependencyProperty.Register("HoverImage", typeof(ImageSource), typeof(IconButton), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsArrange, null));
public ImageSource HoverImage
{
get
{
return (ImageSource)GetValue(HoverImageProperty);
}
set
{
SetValue(HoverImageProperty, value);
}
}
public static DependencyProperty DisabledImageProperty = DependencyProperty.Register("DisabledImage", typeof(ImageSource), typeof(IconButton), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsArrange, null));
public ImageSource DisabledImage
{
get
{
return (ImageSource)GetValue(DisabledImageProperty);
}
set
{
SetValue(DisabledImageProperty, value);
}
}
public static DependencyProperty ImageSizeProperty = DependencyProperty.Register("ImageSize", typeof(double), typeof(IconButton));
public double ImageSize
{
get
{
return (double)GetValue(ImageSizeProperty);
}
set
{
SetValue(ImageSizeProperty, value);
}
}
static IconButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(IconButton), new FrameworkPropertyMetadata(typeof(IconButton)));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using Alauda.Extension;
namespace Alauda
{
public class EnumToDescriptionStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null || !(value is Enum) ? "" : ((Enum)value).GetDescription();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return null;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace Alauda
{
public class FrequencyUnitFormatConverter : IValueConverter
{
private Dictionary<string, ulong> orders = new Dictionary<string, ulong>() {
{ "KHz", 1000 },
{ "MHz", 1000000 },
{ "Hz", 1000000000 }
};
public FrequencyUnitFormatConverter()
{
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return FormatUnitNumber(0);
double number;
if (!double.TryParse(value.ToString(), out number))
{
FormatUnitNumber(0);
}
return FormatUnitNumber(number);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return UnFormatUnitNumber(value.ToString());
}
private string FormatUnitNumber(double value)
{
var displayValue = 0d;
var devimalDigit = 0;
var unit = "Hz";
if (value < 1e3 && value > -1e3)
{
displayValue = value;
devimalDigit = 0;
}
else if (value < 1e6 && value > -1e6)
{
displayValue = value / 1e3;
devimalDigit = 3;
unit = "KHz";
}
else if (value < 1e18 && value > -1e18)
{
displayValue = value / 1e6;
devimalDigit = 6;
unit = "MHz";
}
//else if (value < 1e12 && value > -1e12)
//{
// displayValue = value / 1e9;
// devimalDigit = 6;
// unit = "G" + Unit;
//}
//else if (value < 1e15 && value > -1e15)
//{
// displayValue = value / 1e12;
// devimalDigit = 6;
// unit = "T" + Unit;
//}
//else if (value < 1e18 && value > -1e18)
//{
// displayValue = value / 1e15;
// devimalDigit = 6;
// unit = "P" + Unit;
//}
else
{
displayValue = 1e18;// 用旧值重新覆盖
}
return string.Format("{0:F" + devimalDigit + "} {1}", displayValue, unit);
}
private double UnFormatUnitNumber(string unitStaring)
{
// 为空时
var text = unitStaring.Trim();
if (string.IsNullOrEmpty(text))
{
return 0;
}
// 为整数时
double number;
if (double.TryParse(text, out number))
{
return number;
}
// 有后缀时
foreach (var item in orders.Keys)
{
if (text.ToLower().EndsWith(item.ToLower()))
{
double numberD;
var numText = text.Substring(0, text.Length - item.Length);
if (double.TryParse(numText, out numberD))
{
var order = orders[item];
var newNumber = (double)(numberD * order);
return newNumber;
}
else
{
break;
}
}
}
// 输入错误字符时
return 0;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace Alauda
{
public class IntSecondToFormatStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int timeSecond;
if (!int.TryParse(value.ToString(), out timeSecond))
{
return string.Empty;
}
var timeSpan = TimeSpan.FromSeconds(timeSecond);
var format = @"mm\:ss";
if (timeSpan.Hours > 0)
{
format = @"hh\:mm\:ss";
}
return timeSpan.ToString(format);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var timeString = value.ToString();
TimeSpan span;
if (TimeSpan.TryParse(timeString, out span))
{
return (int)span.TotalSeconds;
}
return 0;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace Alauda
{
public static class FocusBehavior
{
public static bool GetIsFocus(DependencyObject d)
{
return (bool)d.GetValue(IsFocusProperty);
}
public static void SetIsFocus(DependencyObject d, bool val)
{
d.SetValue(IsFocusProperty, val);
}
public static readonly DependencyProperty IsFocusProperty =
DependencyProperty.RegisterAttached(
"IsFocus",
typeof(bool),
typeof(FocusBehavior),
new FrameworkPropertyMetadata(false,
FrameworkPropertyMetadataOptions.None,
(d, e) =>
{
if ((bool)e.NewValue)
{
if (d is UIElement)
{
((UIElement)d).Focus();
if(d is TextBox)
{
((TextBox)d).SelectAll();
}
}
}
}
)
);
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Alauda
{
/// <summary>
/// 多选下拉框
/// </summary>
public class MultiComboBox : ComboBox
{
public static DependencyProperty WaterMarkProperty = DependencyProperty.Register("WaterMark", typeof(string), typeof(MultiComboBox), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsArrange, null));
/// <summary>
/// 未选中时内容区域显示的水印
/// </summary>
public string WaterMark
{
get
{
return (string)GetValue(WaterMarkProperty);
}
set
{
SetValue(WaterMarkProperty, value);
}
}
public static DependencyProperty SelectedItemsProperty = DependencyProperty.Register("SelectedItems", typeof(IList), typeof(MultiComboBox));
/// <summary>
/// 选中的项
/// </summary>
public IList SelectedItems
{
get
{
return (IList)GetValue(SelectedItemsProperty);
}
set
{
SetValue(SelectedItemsProperty, value);
}
}
public ICommand SelectedChangedCommand
{
get
{
return new ActionCommand(SelectedChanged);
}
}
public ICommand ClearClickCommand
{
get
{
return new ActionCommand(ClearClick);
}
}
static MultiComboBox()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MultiComboBox), new FrameworkPropertyMetadata(typeof(MultiComboBox)));
}
public void SelectedChanged()
{
StringBuilder sb = new StringBuilder();
foreach (var item in this.SelectedItems)
{
var type = item.GetType();
var pInfo = type.GetProperty(DisplayMemberPath, typeof(string));
sb.Append(pInfo.GetValue(item, null)).Append(";");
}
this.Text = sb.ToString().TrimEnd(';');
}
public void ClearClick()
{
SelectedItems.Clear();
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace Alauda.Enumerator
{
public class SingleChildEnumerator : IEnumerator
{
internal SingleChildEnumerator(object Child)
{
_child = Child;
_count = Child == null ? 0 : 1;
}
object IEnumerator.Current
{
get { return (_index == 0) ? _child : null; }
}
bool IEnumerator.MoveNext()
{
_index++;
return _index < _count;
}
void IEnumerator.Reset()
{
_index = -1;
}
private int _index = -1;
private int _count = 0;
private object _child;
}
}
<file_sep>using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace Alauda
{
public class CloseWindowBehavior : Behavior<Window>
{
public bool CloseTrigger
{
get { return (bool)GetValue(CloseTriggerProperty); }
set { SetValue(CloseTriggerProperty, value); }
}
public static readonly DependencyProperty CloseTriggerProperty =
DependencyProperty.Register("CloseTrigger", typeof(bool), typeof(CloseWindowBehavior), new PropertyMetadata(false, OnCloseTriggerChanged));
private static void OnCloseTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var behavior = d as CloseWindowBehavior;
if (behavior != null)
{
behavior.OnCloseTriggerChanged();
}
}
private void OnCloseTriggerChanged()
{
// when closetrigger is true, close the window
if (this.CloseTrigger)
{
this.AssociatedObject.Close();
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace Alauda
{
public class EnumToBooleanConverter : IValueConverter
{
private bool _isReversed;
public bool IsReversed { get { return _isReversed; } set { _isReversed = value; } }
public EnumToBooleanConverter()
: this(false)
{
}
public EnumToBooleanConverter(bool isReversed)
{
_isReversed = isReversed;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null && parameter == null ? false : value.Equals(parameter) ^ _isReversed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value != null && value.Equals(true) ^ _isReversed ? parameter : Binding.DoNothing;
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace Alauda.Enumerator
{
public class DoubleChildEnumerator : IEnumerator
{
internal DoubleChildEnumerator(object child1, object child2)
{
Debug.Assert(child1 != null, "First child should be non-null.");
Debug.Assert(child2 != null, "Second child should be non-null.");
_child1 = child1;
_child2 = child2;
}
object IEnumerator.Current
{
get
{
switch (_index)
{
case 0:
return _child1;
case 1:
return _child2;
default:
return null;
}
}
}
bool IEnumerator.MoveNext()
{
_index++;
return _index < 2;
}
void IEnumerator.Reset()
{
_index = -1;
}
private int _index = -1;
private object _child1;
private object _child2;
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;
namespace Alauda
{
public class NumberUnitFormatConvertorExtension : MarkupExtension
{
private string _unit;
private int _decimalDigit;
private bool _hasIntervalBeforeUnit;
[ConstructorArgument("unit")]
public string Unit
{
get { return _unit; }
set { _unit = value; }
}
[ConstructorArgument("decimalDigit")]
public int DecimalDigit
{
get { return _decimalDigit; }
set { _decimalDigit = value; }
}
[ConstructorArgument("hasIntervalBeforeUnit")]
public bool HasIntervalBeforeUnit
{
get { return _hasIntervalBeforeUnit; }
set { _hasIntervalBeforeUnit = value; }
}
public NumberUnitFormatConvertorExtension()
: this("")
{
}
public NumberUnitFormatConvertorExtension(string unit)
{
this.Unit = unit;
DecimalDigit = 6;
HasIntervalBeforeUnit = true;
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return new NumberUnitFormatConvertor(_unit)
{
DecimalDigit = this._decimalDigit,
HasIntervalBeforeUnit = this._hasIntervalBeforeUnit
};
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;
namespace Alauda
{
public class IntSecondToFormatStringConverterExtension : MarkupExtension
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
return new IntSecondToFormatStringConverter();
}
}
}
<file_sep>using Alauda.Enumerator;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Alauda.Standard;
using System.Collections.ObjectModel;
namespace Alauda
{
public class InputDecorator : Decorator
{
public static readonly DependencyProperty BackgroundProperty =
Panel.BackgroundProperty.AddOwner(typeof(InputDecorator),
new FrameworkPropertyMetadata(
(Brush)null,
FrameworkPropertyMetadataOptions.AffectsRender));
UIElement _prefix = null;
UIElement _suffix = null;
public InputDecorator() : base()
{
}
/// <summary>
/// The Background property defines the brush used to fill the area within the InputDecorator.
/// </summary>
public Brush Background
{
get { return (Brush)GetValue(BackgroundProperty); }
set { SetValue(BackgroundProperty, value); }
}
public UIElement Prefix
{
get
{
return _prefix;
}
set
{
if (_prefix != value)
{
if (_prefix != null)
{
// notify the visual layer that the old bullet has been removed.
RemoveVisualChild(_prefix);
//need to remove old element from logical tree
RemoveLogicalChild(_prefix);
}
_prefix = value;
AddLogicalChild(value);
// notify the visual layer about the new child.
AddVisualChild(value);
// If we decorator content exists we need to move it at the end of the visual tree
UIElement child = Child;
if (child != null)
{
RemoveVisualChild(child);
AddVisualChild(child);
}
InvalidateMeasure();
}
}
}
public UIElement Suffix
{
get
{
return _suffix;
}
set
{
if (_suffix != value)
{
if (_suffix != null)
{
// notify the visual layer that the old bullet has been removed.
RemoveVisualChild(_suffix);
//need to remove old element from logical tree
RemoveLogicalChild(_suffix);
}
_suffix = value;
AddLogicalChild(value);
// notify the visual layer about the new child.
AddVisualChild(value);
// If we decorator content exists we need to move it at the end of the visual tree
UIElement child = Child;
if (child != null)
{
RemoveVisualChild(child);
AddVisualChild(child);
}
InvalidateMeasure();
}
}
}
/// <summary>
/// Returns enumerator to logical children.
/// </summary>
protected override IEnumerator LogicalChildren
{
get
{
if (_prefix == null && _suffix == null)
{
return base.LogicalChildren;
}
if (_prefix == null)
{
if (Child == null)
{
return new SingleChildEnumerator(_suffix);
}
return new DoubleChildEnumerator(Child, _suffix);
}
if (_suffix == null)
{
if (Child == null)
{
return new SingleChildEnumerator(_prefix);
}
return new DoubleChildEnumerator(Child, _prefix);
}
return new ThreeChildEnumerator(_prefix, Child, _suffix);
}
}
/// <summary>
/// Override from UIElement
/// </summary>
protected override void OnRender(DrawingContext dc)
{
// Draw background in rectangle inside border.
Brush background = this.Background;
if (background != null)
{
dc.DrawRectangle(background,
null,
new Rect(0, 0, RenderSize.Width, RenderSize.Height));
}
}
/// <summary>
/// Returns the Visual children count.
/// </summary>
protected override int VisualChildrenCount
{
get { return (Child == null ? 0 : 1) + (_prefix == null ? 0 : 1) + (_suffix == null ? 0 : 1); }
}
/// <summary>
/// Returns the child at the specified index.
/// </summary>
protected override Visual GetVisualChild(int index)
{
if (index < 0 || index > VisualChildrenCount - 1)
{
throw new ArgumentOutOfRangeException("index", index, "ArgumentOutOfRange");
}
if (index == 0)
{
if (_prefix != null) return _prefix;
else return Child;
}
if (index == 1)
{
if (_prefix != null) return Child;
else return _suffix;
}
if (index == 2)
{
if (_suffix == null || _prefix == null) return Child;
else return _suffix;
}
return Child;
}
/// <summary>
/// Updates DesiredSize of the InputDecorator. Called by parent UIElement.
/// This is the first pass of layout.
/// </summary>
/// <param name="constraint">Constraint size is an "upper limit" that InputDecorator should not exceed.</param>
/// <returns>InputDecorator' desired size.</returns>
protected override Size MeasureOverride(Size constraint)
{
Size prefixSize = new Size();
Size contentSize = new Size();
Size suffixSize = new Size();
UIElement prefix = Prefix;
UIElement content = Child;
UIElement suffix = Suffix;
// If we have bullet we should measure it first
if (prefix != null)
{
prefix.Measure(constraint);
prefixSize = prefix.DesiredSize;
}
// If we have second child (content) we should measure it
if (content != null)
{
Size contentConstraint = constraint;
contentConstraint.Width = Math.Max(0.0, contentConstraint.Width - prefixSize.Width);
content.Measure(contentConstraint);
contentSize = content.DesiredSize;
}
// If we have bullet we should measure it first
if (suffix != null)
{
suffix.Measure(constraint);
suffixSize = suffix.DesiredSize;
}
Size desiredSize = new Size(prefixSize.Width + contentSize.Width + suffixSize.Width, Math.Max(prefixSize.Height, Math.Max(contentSize.Height, suffixSize.Height)));
return desiredSize;
}
/// <summary>
/// InputDecorator arranges its children - Bullet and Child.
/// Bullet is aligned vertically with the center of the content's first line
/// </summary>
/// <param name="arrangeSize">Size that InputDecorator will assume to position children.</param>
protected override Size ArrangeOverride(Size arrangeSize)
{
UIElement prefix = Prefix;
UIElement content = Child;
UIElement suffix = Suffix;
double contentOffsetX = 0;
double bulletOffsetY = 0;
Size prefixSize = new Size();
Size contentSize = new Size();
Size suffixSize = new Size();
// Arrange the bullet if exist
if (prefix != null)
{
prefix.Arrange(new Rect(prefix.DesiredSize));
prefixSize = prefix.RenderSize;
contentOffsetX = prefixSize.Width;
}
// Arrange the content if exist
if (content != null)
{
// Helper arranges child and may substitute a child's explicit properties for its DesiredSize.
// The actual size the child takes up is stored in its RenderSize.
contentSize = arrangeSize;
if (prefix != null)
{
contentSize.Width = Math.Max(content.DesiredSize.Width, arrangeSize.Width - prefix.DesiredSize.Width);
contentSize.Height = Math.Max(content.DesiredSize.Height, arrangeSize.Height);
}
content.Arrange(new Rect(contentOffsetX, 0, contentSize.Width, contentSize.Height));
double centerY = GetFirstLineHeight(content) * 0.5d;
bulletOffsetY += Math.Max(0d, centerY - prefixSize.Height * 0.5d);
}
// Arrange the bullet if exist
if (suffix != null)
{
suffix.Arrange(new Rect(suffix.DesiredSize));
suffixSize = suffix.RenderSize;
contentOffsetX = suffixSize.Width + contentSize.Width;
}
// Re-Position the bullet if exist
if (prefix != null && !DoubleUtil.IsZero(bulletOffsetY))
{
prefix.Arrange(new Rect(0, bulletOffsetY, prefix.DesiredSize.Width, prefix.DesiredSize.Height));
}
return arrangeSize;
}
// This method calculates the height of the first line if the element is TextBlock or FlowDocumentScrollViewer
// Otherwise returns the element height
private double GetFirstLineHeight(UIElement element)
{
// We need to find TextBlock/FlowDocumentScrollViewer if it is nested inside ContentPresenter
// Common scenario when used in styles is that InputDecorator content is a ContentPresenter
UIElement text = FindText(element);
//ReadOnlyCollection<LineResult> lr = null;
//if (text != null)
//{
// TextBlock textElement = ((TextBlock)text);
// if (textElement.IsLayoutDataValid)
// lr = textElement.GetLineResults();
//}
//else
//{
// text = FindFlowDocumentScrollViewer(element);
// if (text != null)
// {
// TextDocumentView tdv = ((IServiceProvider)text).GetService(typeof(ITextView)) as TextDocumentView;
// if (tdv != null && tdv.IsValid)
// {
// ReadOnlyCollection<ColumnResult> cr = tdv.Columns;
// if (cr != null && cr.Count > 0)
// {
// ColumnResult columnResult = cr[0];
// ReadOnlyCollection<ParagraphResult> pr = columnResult.Paragraphs;
// if (pr != null && pr.Count > 0)
// {
// ContainerParagraphResult cpr = pr[0] as ContainerParagraphResult;
// if (cpr != null)
// {
// TextParagraphResult textParagraphResult = cpr.Paragraphs[0] as TextParagraphResult;
// if (textParagraphResult != null)
// {
// lr = textParagraphResult.Lines;
// }
// }
// }
// }
// }
// }
//}
//if (lr != null && lr.Count > 0)
//{
// Point ancestorOffset = new Point();
// text.TransformToAncestor(element).TryTransform(ancestorOffset, out ancestorOffset);
// return lr[0].LayoutBox.Height + ancestorOffset.Y * 2d;
//}
return element.RenderSize.Height;
}
private TextBlock FindText(Visual root)
{
// Cases where the root is itself a TextBlock
TextBlock text = root as TextBlock;
if (text != null)
return text;
ContentPresenter cp = root as ContentPresenter;
if (cp != null)
{
if (VisualTreeHelper.GetChildrenCount(cp) == 1)
{
DependencyObject child = VisualTreeHelper.GetChild(cp, 0);
// Cases where the child is a TextBlock
TextBlock textBlock = child as TextBlock;
if (textBlock == null)
{
AccessText accessText = child as AccessText;
if (accessText != null &&
VisualTreeHelper.GetChildrenCount(accessText) == 1)
{
// Cases where the child is an AccessText whose child is a TextBlock
textBlock = VisualTreeHelper.GetChild(accessText, 0) as TextBlock;
}
}
return textBlock;
}
}
else
{
AccessText accessText = root as AccessText;
if (accessText != null &&
VisualTreeHelper.GetChildrenCount(accessText) == 1)
{
// Cases where the root is an AccessText whose child is a TextBlock
return VisualTreeHelper.GetChild(accessText, 0) as TextBlock;
}
}
return null;
}
private FlowDocumentScrollViewer FindFlowDocumentScrollViewer(Visual root)
{
FlowDocumentScrollViewer text = root as FlowDocumentScrollViewer;
if (text != null)
return text;
ContentPresenter cp = root as ContentPresenter;
if (cp != null)
{
if (VisualTreeHelper.GetChildrenCount(cp) == 1)
return VisualTreeHelper.GetChild(cp, 0) as FlowDocumentScrollViewer;
}
return null;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;
using Alauda.Extension;
namespace Alauda
{
public class EnumerationExtension : MarkupExtension
{
private Type _enumType;
private IEnumerable<EnumerationMember> members;
public class EnumerationMember
{
public string Description { get; set; }
public object Enumerator { get; set; }
public object Value { get; set; }
}
public Type EnumType
{
get { return _enumType; }
private set
{
if (_enumType == value)
return;
var enumType = Nullable.GetUnderlyingType(value) ?? value;
if (enumType.IsEnum == false)
throw new ArgumentException("Type must be an Enum.");
_enumType = value;
}
}
public EnumerationExtension(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException("enumType");
EnumType = enumType;
}
protected EnumerationExtension()
{
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
members = GetAllValuesAndDescriptions(EnumType);
return members;
}
public IEnumerable<EnumerationMember> GetAllValuesAndDescriptions(Type t)
{
if (!t.IsEnum)
throw new ArgumentException("t must be an enum type");
var enumValues = Enum.GetValues(t).Cast<Enum>();
var s= (
from Enum enumValue in enumValues
select new EnumerationMember
{
Value = Convert.ChangeType(enumValue, enumValue.GetTypeCode()),
Enumerator = enumValue,
Description = enumValue.GetDescription()
}).ToList();
return s;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace Alauda
{
public class NumberUnitFormatConvertor : IValueConverter
{
private Dictionary<string, ulong> orders = new Dictionary<string, ulong>() {
{ "K", 1000 }, { "M", 1000000 }, { "G", 1000000000 } , { "T", 1000000000000 } , { "P", 1000000000000000 } };
private string _unit;
public string Unit { get { return _unit; } set { _unit = value; } }
public int DecimalDigit { get; set; }
public bool HasIntervalBeforeUnit { get; set; }
public NumberUnitFormatConvertor()
: this("")
{
}
public NumberUnitFormatConvertor(string unit)
{
DecimalDigit = 6;
HasIntervalBeforeUnit = true;
_unit = unit;
var length = _unit.Length;
if (length <= 0) return;
for (var index = 1; index <= length; index++)
{
var suffix = _unit.Substring(0, index);
orders.Add("K" + suffix, 1000);
orders.Add("M" + suffix, 1000000);
orders.Add("G" + suffix, 1000000000);
orders.Add("T" + suffix, 1000000000000);
orders.Add("P" + suffix, 1000000000000000);
}
orders.Add(_unit, 1);
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return FormatUnitNumber(0);
double number;
if (!double.TryParse(value.ToString(), out number))
{
FormatUnitNumber(0);
}
return FormatUnitNumber(number);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return UnFormatUnitNumber(value.ToString());
}
private string FormatUnitNumber(double value)
{
var displayValue = 0d;
var devimalDigit = 0;
var unit = Unit;
if (value < 1e3 && value > -1e3)
{
displayValue = value;
devimalDigit = 0;
}
else if (value < 1e6 && value > -1e6)
{
displayValue = value / 1e3;
devimalDigit = 3;
unit = "K" + Unit;
}
else if (value < 1e9 && value > -1e9)
{
displayValue = value / 1e6;
devimalDigit = 6;
unit = "M" + Unit;
}
else if (value < 1e12 && value > -1e12)
{
displayValue = value / 1e9;
devimalDigit = 6;
unit = "G" + Unit;
}
else if (value < 1e15 && value > -1e15)
{
displayValue = value / 1e12;
devimalDigit = 6;
unit = "T" + Unit;
}
else if (value < 1e18 && value > -1e18)
{
displayValue = value / 1e15;
devimalDigit = 6;
unit = "P" + Unit;
}
else
{
displayValue = 1e18;// 用旧值重新覆盖
}
if (devimalDigit > DecimalDigit)
{
devimalDigit = DecimalDigit;
}
if (string.IsNullOrWhiteSpace(unit))
{
return string.Format("{0:F" + devimalDigit + "}", displayValue);
}
else
{
if (HasIntervalBeforeUnit)
{
return string.Format("{0:F" + devimalDigit + "} {1}", displayValue, unit);
}
else
{
return string.Format("{0:F" + devimalDigit + "}{1}", displayValue, unit);
}
}
}
private double UnFormatUnitNumber(string unitStaring)
{
// 为空时
var text = unitStaring.Trim();
if (string.IsNullOrEmpty(text))
{
return 0;
}
// 为整数时
double number;
if (double.TryParse(text, out number))
{
return number;
}
// 有后缀时
foreach (var item in orders.Keys)
{
if (text.ToLower().EndsWith(item.ToLower()))
{
double numberD;
var numText = text.Substring(0, text.Length - item.Length);
if (double.TryParse(numText, out numberD))
{
var order = orders[item];
var newNumber = (double)(numberD * order);
return newNumber;
}
else
{
break;
}
}
}
// 输入错误字符时
return 0;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;
namespace Alauda
{
public class LongBytesToFormatStringConverterExtension : MarkupExtension
{
private bool isUseSpeed;
[ConstructorArgument("isUseSpeed")]
public bool IsUseSpeed
{
get
{
return isUseSpeed;
}
set
{
isUseSpeed = value;
}
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return new LongBytesToFormatStringConverter(isUseSpeed);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls.Primitives;
namespace Alauda
{
/// <summary>
/// 带凸显状态的开关
/// </summary>
public class HighlightedSwitch : ToggleButton
{
public static DependencyProperty IsHighlightedProperty = DependencyProperty.Register("IsHighlighted", typeof(bool), typeof(HighlightedSwitch));
public bool IsHighlighted
{
get
{
return (bool)GetValue(IsHighlightedProperty);
}
set
{
SetValue(IsHighlightedProperty, value);
}
}
static HighlightedSwitch()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(HighlightedSwitch), new FrameworkPropertyMetadata(typeof(HighlightedSwitch)));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;
namespace Alauda
{
public class EnumToDescriptionStringConverterExtension : MarkupExtension
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
return new EnumToDescriptionStringConverter();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace Alauda
{
public class EqualObjectToBooleanConverter : IValueConverter
{
private bool _isReversed;
public bool IsReversed { get { return _isReversed; } set { _isReversed = value; } }
public EqualObjectToBooleanConverter()
: this(false)
{
}
public EqualObjectToBooleanConverter(bool isReversed)
{
_isReversed = isReversed;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (value == parameter || value.Equals(parameter)) ^ _isReversed;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Binding.DoNothing;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace Alauda
{
public class LongBytesToFormatStringConverter : IValueConverter
{
private bool isUseSpeed;
public bool IsUseSpeed
{
get
{
return isUseSpeed;
}
set
{
isUseSpeed = value;
}
}
public LongBytesToFormatStringConverter()
: this(false)
{
}
public LongBytesToFormatStringConverter(bool isUseSpeed)
{
this.IsUseSpeed = isUseSpeed;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
long bytes;
if (!long.TryParse(value.ToString(), out bytes))
{
return string.Empty;
}
if (isUseSpeed)
{
return FileSizeToSpeedDisplayString(bytes);
}
else
{
return FileSizeToDisplayString(bytes);
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return 0;
}
/// <summary>
/// 将字节大小转换为显示字符串
/// </summary>
/// <param name="size"></param>
private string FileSizeToSpeedDisplayString(long size)
{
var displayValue = 0d;
var devimalDigit = 0;
var unit = "B/s";
if (size < 1024L)
{
displayValue = size;
devimalDigit = 0;
}
else if (size < Math.Pow(1024L, 2))
{
displayValue = size / 1024;
devimalDigit = 0;
unit = "KB/s";
}
else if (size < Math.Pow(1024L, 3))
{
displayValue = size / Math.Pow(1024L, 2);
devimalDigit = 2;
unit = "MB/s";
}
else if (size < Math.Pow(1024L, 4))
{
displayValue = size / Math.Pow(1024L, 3);
devimalDigit = 4;
unit = "GB/s";
}
else if (size < Math.Pow(1024L, 5))
{
displayValue = size / Math.Pow(1024L, 4);
devimalDigit = 6;
unit = "TB/s";
}
else if (size < Math.Pow(1024L, 6))
{
displayValue = size / Math.Pow(1024L, 5);
devimalDigit = 6;
unit = "PB/s";
}
else
{
displayValue = size;
devimalDigit = 0;
}
return string.Format("{0:F" + devimalDigit + "} {1}", displayValue, unit);
}
/// <summary>
/// 将字节大小转换为显示字符串
/// </summary>
/// <param name="size"></param>
private string FileSizeToDisplayString(long size)
{
var displayValue = 0d;
var devimalDigit = 0;
var unit = "B";
if (size < 1024L)
{
displayValue = size;
devimalDigit = 0;
}
else if (size < Math.Pow(1024L, 2))
{
displayValue = size / 1024;
devimalDigit = 0;
unit = "KB";
}
else if (size < Math.Pow(1024L, 3))
{
displayValue = size / Math.Pow(1024L, 2);
devimalDigit = 2;
unit = "MB";
}
else if (size < Math.Pow(1024L, 4))
{
displayValue = size / Math.Pow(1024L, 3);
devimalDigit = 4;
unit = "GB";
}
else if (size < Math.Pow(1024L, 5))
{
displayValue = size / Math.Pow(1024L, 4);
devimalDigit = 6;
unit = "TB";
}
else if (size < Math.Pow(1024L, 6))
{
displayValue = size / Math.Pow(1024L, 5);
devimalDigit = 6;
unit = "PB";
}
else
{
displayValue = size;
devimalDigit = 0;
}
return string.Format("{0:F" + devimalDigit + "} {1}", displayValue, unit);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup;
namespace Alauda
{
public class EqualObjectToBooleanConverterExtension : MarkupExtension
{
private bool _isReversed;
[ConstructorArgument("isReversed")]
public bool IsReversed
{
get { return _isReversed; }
set { _isReversed = value; }
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return new EqualObjectToBooleanConverter(_isReversed);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace Alauda
{
public class AppWindow : Window
{
public static DependencyProperty CaptionHeightProperty =
DependencyProperty.Register("CaptionHeight", typeof(double), typeof(AppWindow),
new FrameworkPropertyMetadata(28d, FrameworkPropertyMetadataOptions.AffectsArrange, null));
static AppWindow()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(AppWindow), new FrameworkPropertyMetadata(typeof(AppWindow)));
}
private WindowChrome _chrome;
public AppWindow()
{
_chrome = new WindowChrome()
{
ResizeBorderThickness = new Thickness(0),
CaptionHeight = 28,
CornerRadius = new CornerRadius(0),
GlassFrameThickness = new Thickness(0)
};
WindowChrome.SetWindowChrome(this, _chrome);
}
public double CaptionHeight
{
get => (double)GetValue(CaptionHeightProperty);
set
{
SetValue(CaptionHeightProperty, value);
_chrome.CaptionHeight = value;
WindowChrome.SetWindowChrome(this, _chrome);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace Alauda
{
public class LeftCornerRadiusConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value != null && value is CornerRadius)
{
var cornerRadius = (CornerRadius)value;
return new CornerRadius(cornerRadius.TopLeft, 0, 0, cornerRadius.BottomLeft);
}
return Binding.DoNothing;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Alauda
{
/// <summary>
/// 可切换选中状态的图标按钮
/// </summary>
public class IconCheckButton : ToggleButton
{
public ImageSource UnCheckImage
{
get
{
return (ImageSource)GetValue(UnCheckImageProperty);
}
set
{
SetValue(UnCheckImageProperty, value);
}
}
public static DependencyProperty UnCheckImageProperty = DependencyProperty.Register("UnCheckImage", typeof(ImageSource), typeof(IconCheckButton), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsArrange, null));
public ImageSource CheckImage
{
get
{
return (ImageSource)GetValue(CheckImageProperty);
}
set
{
SetValue(CheckImageProperty, value);
}
}
public static DependencyProperty CheckImageProperty = DependencyProperty.Register("CheckImage", typeof(ImageSource), typeof(IconCheckButton), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsArrange, null));
static IconCheckButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(IconCheckButton), new FrameworkPropertyMetadata(typeof(IconCheckButton)));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace Alauda
{
/// <summary>
/// 进度条控件
/// </summary>
public class ProgressBar : Slider
{
public static new DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(ProgressBar), new PropertyMetadata(new PropertyChangedCallback(ValuePropertyChangedCallback)));
public new double Value
{
get
{
return (double)GetValue(ValueProperty);
}
set
{
SetValue(ValueProperty, value);
}
}
static void ValuePropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var sender = (ProgressBar)d;
var newValue = (double)e.NewValue;
sender.ValueWidth = newValue / (sender.Maximum - sender.Minimum) * sender.ActualWidth;
}
public static DependencyProperty Value2Property = DependencyProperty.Register("Value2", typeof(double), typeof(ProgressBar), new PropertyMetadata(new PropertyChangedCallback(Value2PropertyChangedCallback)));
public double Value2
{
get
{
return (double)GetValue(Value2Property);
}
set
{
SetValue(Value2Property, value);
}
}
static void Value2PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var sender = (ProgressBar)d;
var newValue = (double)e.NewValue;
sender.Value2Width = newValue / (sender.Maximum - sender.Minimum) * sender.ActualWidth;
}
public static DependencyProperty ValueWidthProperty = DependencyProperty.Register("ValueWidth", typeof(double), typeof(ProgressBar));
public double ValueWidth
{
get
{
return (double)GetValue(ValueWidthProperty);
}
set
{
SetValue(ValueWidthProperty, value);
}
}
public static DependencyProperty Value2WidthProperty = DependencyProperty.Register("Value2Width", typeof(double), typeof(ProgressBar));
public double Value2Width
{
get
{
return (double)GetValue(Value2WidthProperty);
}
set
{
SetValue(Value2WidthProperty, value);
}
}
static ProgressBar()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(ProgressBar), new FrameworkPropertyMetadata(typeof(ProgressBar)));
}
public ProgressBar()
{
this.SizeChanged += ProgressBar_SizeChanged;
}
private void ProgressBar_SizeChanged(object sender, SizeChangedEventArgs e)
{
ValuePropertyChangedCallback(sender as ProgressBar, new DependencyPropertyChangedEventArgs(ValueProperty, Value, Value));
Value2PropertyChangedCallback(sender as ProgressBar, new DependencyPropertyChangedEventArgs(Value2Property, Value2, Value2));
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Alauda
{
public class TextField : TextBox
{
public static DependencyProperty CursorColorProperty =
DependencyProperty.Register("CursorColor", typeof(Color), typeof(TextField),
new FrameworkPropertyMetadata(Colors.DeepSkyBlue, FrameworkPropertyMetadataOptions.AffectsArrange, null));
public static DependencyProperty OnSubmittedCommandProperty =
DependencyProperty.Register("OnSubmittedCommand", typeof(ICommand), typeof(TextField),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsArrange, null));
static TextField()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(TextField), new FrameworkPropertyMetadata(typeof(TextField)));
}
public TextField()
{
this.KeyDown += TextField_KeyDown;
}
public Color CursorColor
{
get => (Color)GetValue(CursorColorProperty);
set => SetValue(CursorColorProperty, value);
}
public ICommand OnSubmittedCommand
{
get => (ICommand)GetValue(OnSubmittedCommandProperty);
set => SetValue(OnSubmittedCommandProperty, value);
}
private void TextField_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
if (OnSubmittedCommand != null && OnSubmittedCommand.CanExecute(this))
OnSubmittedCommand?.Execute(this);
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace Alauda
{
public class ReadOnlyService : DependencyObject
{
#region IsReadOnly
/// <summary>
/// IsReadOnly Attached Dependency Property
/// </summary>
private static readonly DependencyProperty BehaviorProperty =
DependencyProperty.RegisterAttached("IsReadOnly", typeof(bool), typeof(ReadOnlyService),
new FrameworkPropertyMetadata(false));
/// <summary>
/// Gets the IsReadOnly property.
/// </summary>
public static bool GetIsReadOnly(DependencyObject d)
{
return (bool)d.GetValue(BehaviorProperty);
}
/// <summary>
/// Sets the IsReadOnly property.
/// </summary>
public static void SetIsReadOnly(DependencyObject d, bool value)
{
d.SetValue(BehaviorProperty, value);
}
#endregion IsReadOnly
}
}
<file_sep># Alauda
Some wpf custom controls and some control's attach property.
<file_sep>using Microsoft.Xaml.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
namespace Alauda
{
/// <summary>
/// Custom behavior that allows for DataGrid Rows to be ReadOnly on per-row basis
/// </summary>
public class DataGridRowReadOnlyBehavior : Behavior<DataGrid>
{
protected override void OnAttached()
{
base.OnAttached();
if (this.AssociatedObject == null)
throw new InvalidOperationException("AssociatedObject must not be null");
AssociatedObject.BeginningEdit += AssociatedObject_BeginningEdit;
}
private void AssociatedObject_BeginningEdit(object sender, DataGridBeginningEditEventArgs e)
{
var isReadOnlyRow = ReadOnlyService.GetIsReadOnly(e.Row);
if (isReadOnlyRow)
e.Cancel = true;
}
protected override void OnDetaching()
{
AssociatedObject.BeginningEdit -= AssociatedObject_BeginningEdit;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Media;
using System.Collections;
using System.Windows.Controls.Primitives;
namespace Alauda
{
public class DataGridAttach : DependencyObject
{
#region IsScrollToSelectedItem
public static bool GetIsScrollToSelectedItemEnabled(DependencyObject obj)
{
return (bool)obj.GetValue(IsScrollToSelectedItemEnabledProperty);
}
public static void SetIsScrollToSelectedItemEnabled(DependencyObject obj, bool value)
{
obj.SetValue(IsScrollToSelectedItemEnabledProperty, value);
}
// Using a DependencyProperty as the backing store for IsScrollToSelectedItemEnabled. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsScrollToSelectedItemEnabledProperty =
DependencyProperty.RegisterAttached("IsScrollToSelectedItemEnabled", typeof(bool), typeof(DataGridAttach), new PropertyMetadata(false, new PropertyChangedCallback(IsScrollToSelectedItemEnabledPropertyChanged)));
public static void IsScrollToSelectedItemEnabledPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
DataGrid dataGrid = obj as DataGrid;
if (dataGrid != null)
{
bool isEnabled = (bool)args.NewValue;
if (isEnabled)
{
dataGrid.SelectionChanged += DataGrid_SelectionChanged;
}
else
{
dataGrid.SelectionChanged -= DataGrid_SelectionChanged;
}
}
}
private static void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.AddedItems == null || e.AddedItems.Count == 0) return;
try
{
var item = e.AddedItems[0];
var dg = (DataGrid)sender;
dg.ScrollIntoView(item);
}
catch
{
}
}
#endregion
#region DataGridDoubleClickCommand
public static readonly DependencyProperty DataGridDoubleClickProperty =
DependencyProperty.RegisterAttached("DataGridDoubleClickCommand", typeof(ICommand), typeof(DataGridAttach), new PropertyMetadata(new PropertyChangedCallback(AttachOrRemoveDataGridDoubleClickEvent)));
public static void AttachOrRemoveDataGridDoubleClickEvent(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
DataGrid dataGrid = obj as DataGrid;
if (dataGrid != null)
{
ICommand cmd = (ICommand)args.NewValue;
if (args.OldValue == null && args.NewValue != null)
{
dataGrid.MouseDoubleClick += ExecuteDataGridDoubleClick;
}
else if (args.OldValue != null && args.NewValue == null)
{
dataGrid.MouseDoubleClick -= ExecuteDataGridDoubleClick;
}
}
}
private static void ExecuteDataGridDoubleClick(object sender, MouseButtonEventArgs args)
{
DependencyObject obj = sender as DependencyObject;
var ancestor = FindAncestor<DataGridRow>(args.OriginalSource as DependencyObject);
if (ancestor != null)
{
ICommand cmd = (ICommand)obj.GetValue(DataGridDoubleClickProperty);
if (cmd != null)
{
if (cmd.CanExecute(obj))
{
cmd.Execute(obj);
}
}
}
}
public static ICommand GetDataGridDoubleClickCommand(DependencyObject obj)
{
return (ICommand)obj.GetValue(DataGridDoubleClickProperty);
}
public static void SetDataGridDoubleClickCommand(DependencyObject obj, ICommand value)
{
obj.SetValue(DataGridDoubleClickProperty, value);
}
#endregion
private static T FindAncestor<T>(DependencyObject dependencyObject)
where T : DependencyObject
{
var parent = VisualTreeHelper.GetParent(dependencyObject);
if (parent == null) return null;
var parentT = parent as T;
return parentT ?? FindAncestor<T>(parent);
}
}
}
| 0c1b793ac89f450a2af05bfa63dda2bbd88d1ae0 | [
"Markdown",
"C#"
] | 33 | C# | bubdm/Alauda | 51ce2eb27af0548176d5bb1be59ea5fed21f226a | 271c174122b4121f52389a84f20b8d86c14a2896 |
refs/heads/master | <file_sep>const React = require('react')
const ReactDOM = require('react-dom')
const $ = require('jquery')
//import ColsMod from "apiCollMod.js";
const {congressMod, congressCollection} = require('./apiCollMod.js')
console.log(React)
console.log(congressCollection)
let HomeView = React.createClass({
render: function(){
let legislatorStuff = this.props.congressData.map(function(userObj, i){
console.log(userObj.first_name)
return < PersonsOfCongress congressData={userObj} key={i} />
})
return (
<div className="row">
<div className="head">
<h2> our elected robots of congress </h2>
</div>
{legislatorStuff}
</div>
)
}
})
class PersonsOfCongress extends React.Component{
constructor () {
super();
}
render(){
let repData = this.props.congressData
console.log(repData)
return(
<div className="col-sm-6 col-md-4">
<div className="thumbnail">
<img src={`https://robohash.org/${repData.first_name}`}/>
<div className="caption">
<h4>{repData.title}. {repData.first_name} {repData.last_name} - {repData.chamber}: {repData.party}</h4>
<p><a href="#" className="btn btn-default" role="button">Details</a></p>
</div>
</div>
</div>
)
}
}
$.getJSON('https:congress.api.sunlightfoundation.com/legislators?apikey=ea71fbe43def436ab78408444b414952').then(function(serverRes){
// rendering + passing the serverResponse as props (userDataList)
console.log(serverRes.results)
ReactDOM.render(<HomeView congressData={serverRes.results} />, document.querySelector('#app-container') )
})
<file_sep>const react = require('react')
const reactDOM = require('react-dom')
const Backbone = require('backbone')
//const STORE = require('./store.js')
//const singleView = require('./selfclick.js')
class pageViews extends React.Component{
constructor(){
super();
}
render(){
switch(this.props.viewType){
case "home"
return //< HomeView />
break;
case "single"
return //< SelfView />
break:
default:
return(
<div>
<h1>Try Again</h1>
</div>
)
}
}
}
module.exports= PageViews
| 6996c50278c56430178a5aaf8dace52b41850af4 | [
"JavaScript"
] | 2 | JavaScript | marmstr1123/assignment-21-convert-to-React | 4fe48e3a6c5625bceb875e1e87a746e73e5d90f5 | 4429ebbdbd948d25bee0703dfa5526346e40db68 |
refs/heads/master | <repo_name>rummik/zsh-wake<file_sep>/wake.plugin.zsh
#!/bin/zsh
function wake {
emulate -L zsh
cmd=${1:-help}
[[ $# -gt 0 ]] && shift
if [[ ! -d ~/.wake ]]; then
mkdir -p ~/.wake
fi
if ! whence -- "-wake-$cmd" > /dev/null; then
-wake-up $cmd
else
"-wake-$cmd" $@
fi
}
function -wake-list {
ls ~/.wake
}
function -wake-help {
<<-EOF
Usage
wake [up] <host>
wake add <host> <mac>
wake update <host> <mac>
wake delete <host>
wake list
EOF
}
function -wake-up {
local host=$1 file=~/.wake/$1
if [[ ! -f $file ]]; then
print "$host doesn't exist"
else
print waking $host
wakeonlan -f $file
fi
}
function -wake-add {
local host=$1 file=~/.wake/$1 mac=$2
if [[ ! -f $file ]]; then
print $mac > $file
print added $host
else
print $host already exists
fi
}
function -wake-update {
local host=$1 file=~/.wake/$1 mac=$2
if [[ ! -f $file ]]; then
print "$host doesn't exist"
else
print $mac > $file
print updated $host
fi
}
function -wake-remove {
local file=~/.wake/$1
if [[ ! -f $file ]]; then
print "$host doesn't exist"
else
rm $file
print removed $host
fi
}
| a81b591223c1c016f5bab9a5bac996c05231ccc3 | [
"Shell"
] | 1 | Shell | rummik/zsh-wake | 0fa34f5f72c081aa7bf6c7b57f03065afa5463a6 | 39819aad2b7cfa919d931048b893a8559e470142 |
refs/heads/master | <repo_name>mayweed/6.00x<file_sep>/6.00.1x/finalExam/dict_invert.py
#!/usr/bin/python
def dict_invert(d):
'''
d: dict
Returns an inverted dictionary according to the instructions above
'''
dico_inv={}
for k,v in d.items():
if v in list(dico_inv.keys()):
dico_inv[v].append(k)
dico_inv[v].sort()
else:
dico_inv[v]=[k]
return dico_inv
#d={1:10, 2:20, 3:30}
#d = {1:10, 2:20, 3:30, 4:30}
#d = {4:True, 2:True, 0:True}
d={0: 9, 9: 9, 5: 9}
print(dict_invert(d))
<file_sep>/6.00.1x/pset1/bobcount.py
#!/usr/bin/python
s= input('--> ')
bobcount=0
count=0
#while count < (len(s) - 3):
for count in range(len(s)):
if s[count:count+3] == 'bob':
bobcount += 1
count +=2
else:
continue
count +=1
print("Number of bob:" + str(bobcount))
<file_sep>/6.00.1x/quizz/dotProduct.py
#!/usr/bin/python
def dotProduct(listA, listB):
'''
listA: a list of numbers
listB: a list of numbers of the same length as listA
'''
product=0
#lists got same length...(way easier...)
length=len(listA)
while length !=0:
product+=(listA.pop()*listB.pop())
length -=1
#use return here to validate
print(product)
dotProduct([1, 2, 3],[4,5,6])
<file_sep>/6.00.1x/pset2/bisearch_debt_year.py
#!/usr/bin/python
"""
Those 2 values for testing purposes only
Res=90325.03
"""
balance=999999
annualInterestRate=0.18
owed_sum=balance
monthlyInterestRate=annualInterestRate/12.0
lower_bound=round((balance/12.0),2)
upper_bound=round(balance *((1 + monthlyInterestRate)**12)/12.0,2)
monthlyPayment=lower_bound+(upper_bound-lower_bound)/2.0
# the delta named espilon(!) cf course
epsilon=0.2
def remaining_balance(owed_sum):
"""
Yields the remaining balance with interest after one
monthlyPayment
"""
unpaid_balance= owed_sum - monthlyPayment
x=unpaid_balance + (monthlyInterestRate*unpaid_balance)
return x
def calculate_balance(owed_sum,monthlyPayment):
"""
Yields the remaining balance after 12 months of payment
"""
for i in range(1,13):
x= remaining_balance(owed_sum)
owed_sum=x
return owed_sum
# At the beginning you owe everything
remainingBalance=balance
while abs(remainingBalance) >= epsilon :
owed_sum=balance
monthlyPayment=lower_bound+(upper_bound-lower_bound)/2.0
# use the function to store the balance at the end of the year
remainingBalance=calculate_balance(owed_sum,monthlyPayment)
#here only one upper or lower move (cf output!!)
if remainingBalance < 0:
#can and should pay more
upper_bound=monthlyPayment
if remainingBalance > 0:
lower_bound=monthlyPayment
#Seems better to me to put monthlyPayment her (cf output) but
#it does not pass that way. I _have to_ put that assignment
# between owed_sum and remainingBalance to pass the test..
#monthlyPayment=lower_bound+(upper_bound-lower_bound)/2.0
#print("L/M/U:",lower_bound,monthlyPayment,upper_bound)
print("Lowest payment: ",round(monthlyPayment,2))
<file_sep>/6.00.1x/finalExam/prof.py
!/usr/bin/python
class Person(object):
def __init__(self, name):
self.name = name
def say(self, stuff):
return self.name + ' says: ' + stuff
def __str__(self):
return self.name
class Lecturer(Person):
def lecture(self, stuff):
return 'I believe that ' + Person.say(self, stuff)
#6.3 add 'Prof.'
class Professor(Lecturer):
def say(self, stuff):
return 'Prof. '+self.name + ' says: ' + self.lecture(stuff)
# 6.1
#class ArrogantProfessor(Professor):
# def say(self, stuff):
# return self.name + ' says: ' + self.lecture(stuff)
# def lecture(self,stuff):
# return 'It is obvious that ' + Person.say(self,stuff)
# 6.2
class ArrogantProfessor(Professor):
def say(self, stuff):
return self.name + ' says: ' + self.lecture(stuff)
def lecture(self,stuff):
return 'It is obvious that ' + Lecturer.lecture(self,stuff)
<file_sep>/6.00.1x/pset6/test_dico.py
#!/usr/bin/python
import string
# does NOT work in circle(cf x/y/z)
def build_shift_dict(shift):
'''
Creates a dictionary that can be used to apply a cipher to a letter.
The dictionary maps every uppercase and lowercase letter to a
character shifted down the alphabet by the input shift. The dictionary
should have 52 keys of all the uppercase letters and all the lowercase
letters only.
shift (integer): the amount by which to shift every letter of the
alphabet. 0 <= shift < 26
Returns: a dictionary mapping a letter (string) to
another letter (string).
'''
#cant use mk_dict in the IDE
#one or two dicos??
# no: use ord + shift mod 26?? cf wikipedia
minuscules=string.ascii_lowercase
maj=string.ascii_uppercase
dico={}
for i in range(len(minuscules)):
#c'est l'indice qui change ne pas oublier les () pour la précédence
dico[minuscules[i]]= minuscules[(i+shift)%26]
for i in range(len(maj)):
#c'est l'indice qui change ne pas oublier les () pour la précédence
dico[maj[i]]= maj[(i+shift)%26]
print(dico)
build_shift_dict(0)
<file_sep>/6.00.1x/pset2/ndigits.py
#!/usr/bin/python
s=input('--> A number please: ')
def ndigits(number):
"""
This function takes as input a number postive or negative and outputs the number of
digits in number.
"""
count=1
if abs(number//10) == 0:return 1
else:return count+1*ndigits(abs(number//10))
print(ndigits(int(s)))
<file_sep>/6.00.1x/quizz/flattenList.py
#!/usr/bin/python
def flatten(aList):
'''
aList: a list
Returns a copy of aList, which is a flattened version of aList
'''
liste=[]
#base case
if len(aList) ==0:
return aList
for element in aList:
if type(element)==list:
for item in (element):
if type(item)==list:
liste+=flatten(item)
else:liste.append(item)
else:liste.append(element)
return liste
test_mit=[[1,'a',['cat'],2],[[[3]],'dog'],4,5]
first_test=[[1,2,3],'a']
test_bc=[1,2,3,['a','b']]
i=flatten(test_mit)
print(i)
<file_sep>/6.00.1x/pset2/debt_year.py
#!/usr/bin/python
"""
Those 2 values for testing purposes only
"""
balance=999999
annualInterestRate=0.18
owed_sum=balance
monthlyInterestRate=annualInterestRate/12.0
monthlyPayment=10
def remaining_balance(owed_sum):
unpaid_balance= owed_sum - monthlyPayment
x=unpaid_balance + (monthlyInterestRate*unpaid_balance)
return round(x)
def calculate_balance(owed_sum,monthlyPayment):
for i in range(1,13):
#print("MonthlyPayment ",monthlyPayment)
x= remaining_balance(owed_sum)
#print("Month/remB ",i,x)
owed_sum=x
return owed_sum
x=calculate_balance(owed_sum,monthlyPayment)
while x >= 0:
owed_sum=balance
monthlyPayment += 10
x=calculate_balance(owed_sum,monthlyPayment)
print("Lowest payment: ",monthlyPayment)
<file_sep>/6.00.1x/pset1/polysum.py
#!/usr/bin/python
import math
def polysum(n,s):
"""
This function takes as input the number of sides n and the length
of each side s of a polygon. It returns as output the sum of the
area and the square of the polygon perimeter .
"""
def perimeter(numberofside,length):
return numberofside*length
def area(numberofside,length):
aire=((0.25*n*s**2)/math.tan(math.pi/n))
return round(aire,2)
return round(area(n,s)+perimeter(n,s)**2,4)
<file_sep>/6.00.2x/finger_ex/parseTemps.py
#!/usr/bin/python
import pylab
fileTemps='julyTemps.txt'
def parseTemps(fileTemps):
highTemps=[]
lowTemps=[]
with open(fileTemps, 'r') as inFile:
for line in inFile:
#want to get read of that first
fields=line.split()
if len(line) < 3 or not line[0].isdigit():
continue
else:
highTemps.append(int(fields[1]))
lowTemps.append(int(fields[2]))
# A tuple of the two lists!!
return(highTemps,lowTemps)
def producePlot(highTemps,lowTemps):
diffTemps=[]
count=0
while count < len(highTemps):
diffTemps.append(highTemps[count]-lowTemps[count])
count+=1
# with numpy: diffTemps = list(np.array(highTemps) - np.array(lowTemps))
# very nice!!! should learn numpy a bit ^^
pylab.plot(range(1,32),diffTemps)
pylab.title('Day by Day Ranges in Temperature in Boston in July 2012')
pylab.xlabel('Days')
pylab.ylabel('Temperature Ranges')
pylab.show()
high,low=parseTemps(fileTemps)
producePlot(high,low)
<file_sep>/6.00.1x/pset2/guess_what.py
#!/usr/bin/python
# Must use bisection search
# Do not forget: update high/low separately. Middle is a formula!!
low=0
high=100
guessed=False
print("Please think of a number between 0 and 100!")
#I do like the use of this boolean
while not guessed:
#middle is a formula
guess=(high+low)/2
print("Is your secret number {0} ?".format(guess))
user_hint=input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low."
"Enter 'c' to indicate I guessed correctly.")
if user_hint=='h':
#if it's too high, it's good new high ;)
high=guess
elif user_hint=='l':
low=guess
elif user_hint=='c':
guessed=True
else:
print("Sorry, I did not understand your input.")
print('Game over. Your secret number was: {0}'.format(guess))
<file_sep>/6.00.1x/pset1/vowels.py
#!/usr/bin/python
# git remote add origin https://github.com/mayweed/6.00x.git
# git push -u origin master
#s/raw_input()/input()/if py > 3
s = input('--> ')
count=0
for x in s:
if x in ['a','e','i','o','u']:
count +=1
print("Number of vowels: " , count)
<file_sep>/6.00.1x/pset3/hangman/ps3_hangman.py
#!/usr/bin/python
# 6.00 Problem Set 3
#
# Hangman game
#
import random
import string
WORDLIST_FILENAME='/home/guillaume/scripts/6.00x/pset3/hangman/words.txt'
def loadWords():
"""
Returns a list of valid words. Words are strings of lowercase letters.
Depending on the size of the word list, this function may
take a while to finish.
"""
print ("Loading word list from file...")
# inFile: file
with open(WORDLIST_FILENAME,'r',1) as inFile:
line = inFile.readline()
# wordlist: list of strings
wordlist = line.split()
print ("{0} words loaded.".format(len(wordlist)))
return wordlist
def chooseWord(wordlist):
"""
wordlist (list): list of words (strings)
Returns a word from wordlist at random
"""
return random.choice(wordlist)
# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = loadWords()
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
count=len(secretWord)
for i in secretWord:
if i in lettersGuessed: count-=1
else: continue
if count ==0: return True
else: return False
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
secretword_bis=''
for i in secretWord:
if i in lettersGuessed: secretword_bis+=i
else: secretword_bis+=' _ '
return secretword_bis
def getAvailableLetters(lettersGuessed):
'''
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters that represents what letters have not
yet been guessed.
'''
letters=string.ascii_lowercase
letters_bis=''
for i in letters:
if i in lettersGuessed:continue
else:letters_bis+=i
return letters_bis
def hangman(secretWord):
'''
secretWord: string, the secret word to guess.
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secretWord contains.
* Ask the user to supply one guess (i.e. letter) per round.
* The user should receive feedback immediately after each guess
about whether their guess appears in the computers word.
* After each round, you should also display to the user the
partially guessed word so far, as well as letters that the
user has not yet guessed.
Follows the other limitations detailed in the problem write-up.
'''
print("Welcome to the game Hangman!")
print("I'm thinking about a word that is {0} letters long".format(len(secretWord)))
print("-----------")
#you always got 8 guesses. Why? Because...
guesses= 8
letters_guessed=[]
word=''
count_guess=guesses
count=0
#game loop
while count <= guesses:
print("You have {0} guesses left".format(count_guess))
print("Available Letters: {0}".format(getAvailableLetters(letters_guessed)))
user_guess=input("Please guess a letter: ")
if user_guess in string.ascii_uppercase:
user_guess=user_guess.lower()
if user_guess in letters_guessed:
print("Oops! You've already guessed that letter: {0}".format(getGuessedWord(secretWord,letters_guessed)))
print("-----------")
continue
if user_guess in secretWord:
letters_guessed.append(user_guess)
print("Good guess: {0}".format(getGuessedWord(secretWord,letters_guessed)))
if user_guess not in secretWord:
print("Oops! That letter is not in my word: {0}".format(getGuessedWord(secretWord,letters_guessed)))
count_guess -=1
count +=1
if isWordGuessed(secretWord,letters_guessed):
print("-----------")
print("Congratulations! You Won!")
break
if count_guess==0 and getGuessedWord(secretWord,letters_guessed) != secretWord:
print("-----------")
print("Sorry you ran out of guesses! The word was else")
break
print("-----------")
letters_guessed.append(user_guess)
# When you've completed your hangman function, uncomment these two lines
# and run this file to test! (hint: you might want to pick your own
# secretWord while you're testing)
secretWord = chooseWord(wordlist).lower()
hangman(secretWord)
<file_sep>/6.00.1x/pset3/radexposure.py
#!/usr/bin/python
import math
#!! does not work with float step !!
#Test case 1
start=0
stop=4
step=0.25
r=0
def f(x):
return 10*math.e**(math.log(0.5)/5.27 * x)
def rectangle_area(start,step):
'''
compute the area of a rectangle with length as start point
and step as width
'''
length=f(start)
return length*step
def radiationExposure(start, stop, step):
'''
Computes and returns the amount of radiation exposed
to between the start and stop times. Calls the
function f (defined for you in the grading script)
to obtain the value of the function at any point.
start: integer, the time at which exposure begins
stop: integer, the time at which exposure ends
step: float, the width of each rectangle.
You can assume that the step size will always partition the space evenly.
returns: float, the amount of radiation exposed to between start and stop times.
'''
rad=0.0
#the amount of radiation
while start < stop:
rad+=rectangle_area(start,step)
start+=step
# print(start,rad)
return rad
<file_sep>/6.00.1x/pset7/ps7_skeleton.py
import random
import math
import string
import operator
class AdoptionCenter:
"""
The AdoptionCenter class stores the important information that a
client would need to know about, such as the different numbers of
species stored, the location, and the name. It also has a method to adopt a pet.
"""
def __init__(self, name, species_types, location):
self.name=name
self.species_types=species_types
# enforce float... and parse deeper location...
#also works that way but less deep (no access to x or y separately)
#self.location=(float(location[0]),float(location[1]))
self.x=float(location[0])
self.y=float(location[1])
self.location=(self.x,self.y)
def get_number_of_species(self, animal):
for k,v in self.species_types.items():
if k==animal:
return v
def get_location(self):
return self.location
def get_species_count(self):
#when it's zero should not appear...
copy_dico={}
for k,v in self.species_types.items():
if v != 0:
copy_dico[k]=v
return copy_dico
def get_name(self):
return self.name
def adopt_pet(self, species):
for k,v in self.species_types.items():
if species==k:
self.species_types[k]-=1
class Adopter:
"""
Adopters represent people interested in adopting a species.
They have a desired species type that they want, and their score is
simply the number of species that the shelter has of that species.
"""
def __init__(self, name, desired_species):
self.name=name
self.desired_species=desired_species
def get_name(self):
return self.name
def get_desired_species(self):
return self.desired_species
def get_score(self, adoption_center):
#the species dico
species_dico= adoption_center.get_species_count()
# yep a float...
num_desired=0.0
for species in self.get_desired_species().split(' '):
if species in list(species_dico.keys()):
num_desired+=species_dico[species]
return num_desired
class FlexibleAdopter(Adopter):
"""
A FlexibleAdopter still has one type of species that they desire,
but they are also alright with considering other types of species.
considered_species is a list containing the other species the adopter will consider
Their score should be 1x their desired species + .3x all of their desired species
"""
def __init__(self, name, desired_species, considered_species):
Adopter.__init__(self,name,desired_species)
self.considered_species=considered_species
def get_score(self,adoption_center):
#do not forget self in the call unless instance error
adopter_score=Adopter.get_score(self,adoption_center)
species_dico= adoption_center.get_species_count()
num_desired=0.0
#here it's a _list_ of strings (no split)
for considered_species in self.considered_species:
if considered_species in list(species_dico.keys()):
num_desired+=species_dico[considered_species]
return adopter_score + 0.3 * num_desired
class FearfulAdopter(Adopter):
"""
A FearfulAdopter is afraid of a particular species of animal.
If the adoption center has one or more of those animals in it, they will
be a bit more reluctant to go there due to the presence of the feared species.
Their score should be 1x number of desired species - .3x the number of feared species
"""
def __init__(self, name, desired_species, feared_species):
Adopter.__init__(self,name,desired_species)
self.feared_species=feared_species
def get_score(self,adoption_center):
adopter_score=Adopter.get_score(self,adoption_center)
species_dico= adoption_center.get_species_count()
num_feared=0.0
#here it's a string
for feared_species in self.feared_species.split(' '):
if feared_species in species_dico:
num_feared+=species_dico[feared_species]
score= adopter_score - 0.3 * num_feared
#to pass one test case for that class only
if score < 0 : return 0.0
else: return score
class AllergicAdopter(Adopter):
"""
An AllergicAdopter is extremely allergic to a one or more species and cannot
even be around it a little bit! If the adoption center contains one or more of
these animals, they will not go there.
Score should be 0 if the center contains any of the animals, or 1x number of desired animals if not
"""
def __init__(self, name, desired_species, allergic_species):
Adopter.__init__(self,name,desired_species)
self.allergic_species=allergic_species
def get_score(self,adoption_center):
species_dico= adoption_center.get_species_count()
for aspecies in self.allergic_species:
if aspecies in species_dico:
return 0.0
return Adopter.get_score(self,adoption_center)
class MedicatedAllergicAdopter(AllergicAdopter):
"""
A MedicatedAllergicAdopter is extremely allergic to a particular species
However! They have a medicine of varying effectiveness, which will be given in a dictionary
To calculate the score for a specific adoption center, we want to find what is the most
allergy-inducing species that the adoption center has for the particular MedicatedAllergicAdopter.
To do this, first examine what species the AdoptionCenter has that the MedicatedAllergicAdopter is allergic to,
then compare them to the medicine_effectiveness dictionary. Take the lowest medicine_effectiveness found for these species,
and multiply that value by the Adopter's calculate score method.
"""
# Your Code Here, should contain an __init__ and a get_score method.
def __init__(self,name,desired_species,allergic_species,medicine_effectiveness):
AllergicAdopter.__init__(self,name,desired_species,allergic_species)
self.medicine_effectiveness=medicine_effectiveness
def get_score(self,adoption_center):
min_seen=1.0
species_dico= adoption_center.get_species_count()
for aspecies in species_dico:
if aspecies in self.allergic_species and aspecies in self.medicine_effectiveness:
if self.medicine_effectiveness[aspecies] < min_seen:
min_seen=self.medicine_effectiveness[aspecies]
return Adopter.get_score(self,adoption_center)*min_seen
class SluggishAdopter(Adopter):
"""
A SluggishAdopter really dislikes travelleng. The further away the
AdoptionCenter is linearly, the less likely they will want to visit it.
Since we are not sure the specific mood the SluggishAdopter will be in on a
given day, we will asign their score with a random modifier depending on
distance as a guess.
Score should be
If distance < 1 return 1 x number of desired species
elif distance < 3 return random between (.7, .9) times number of desired species
elif distance < 5. return random between (.5, .7 times number of desired species
else return random between (.1, .5) times number of desired species
"""
def __init__(self, name, desired_species, location):
Adopter.__init__(self,name,desired_species)
self.location=(float(location[0]),float(location[1]))
def get_linear_distance(self,to_location):
distance=math.sqrt(((to_location[0]-self.location[0])**2)+((to_location[1]-self.location[1])**2))
return distance
def get_score(self,adoption_center):
distance=self.get_linear_distance(adoption_center.get_location())
species_dico= adoption_center.get_species_count()
num=0
desired_species=self.desired_species.split(' ')
#Desired species: not the num of self.desired_species
# but the total count of desired species in an adoption center
# did not succeed in using get_number_of_species() method
for species in desired_species:
num+=species_dico.get(species,0)
if distance < 1: return 1*num
elif distance >= 1 and distance < 3:return random.uniform(.7,.9)*num
elif distance >= 3 and distance < 5:return random.uniform(.5,.7)*num
else: return random.uniform (.1,.5)*num
def get_ordered_adoption_center_list(adopter, list_of_adoption_centers):
"""
The method returns a list of an organized adoption_center such that the scores
for each AdoptionCenter to the Adopter will be ordered from highest score to lowest score.
"""
scoreboard=[]
# Check adopter class with isinstance() and add object/score in a tuple
# oki...for grader should return a list of ac object on which it will call get_name()
for ac in list_of_adoption_centers:
if isinstance(adopter,Adopter):
score=adopter.get_score(ac)
scoreboard.append((ac,score))
elif isinstance(adopter,FlexibleAdopter):
score=adopter.get_score(ac)
scoreboard.append((ac,score))
elif isinstance(adopter,FearfulAdopter):
score=adopter.get_score(ac)
scoreboard.append((ac,score))
elif isinstance(adopter,AllergicAdopter):
score=adopter.get_score(ac)
scoreboard.append((ac,score))
elif isinstance(adopter,MedicatedAllergicAdopter):
score=adopter.get_score(ac)
scoreboard.append((ac,score))
elif isinstance(adopter,SluggishAdopter):
score=adopter.get_score(ac)
scoreboard.append((ac,score))
#SORT: see http://stackoverflow.com/questions/11450277/complex-sort-with-multiple-parameters
scoreboard.sort(key=lambda sortado:(-item[1],item[0].get_name()))
# list of my ordered AdoptionCenter objects
liste_ac=[]
for item in scoreboard:
liste_ac.append(item[0])
return liste_ac
def get_adopters_for_advertisement(adoption_center, list_of_adopters, n):
"""
The function returns a list of the top n scoring Adopters from list_of_adopters (in numerical order of score)
"""
scoreboard=[]
#check adopter and calculate score
for adopter in list_of_adopters:
if isinstance(adopter,Adopter):
score=adopter.get_score(adoption_center)
scoreboard.append((adopter,score))
elif isinstance(adopter,FlexibleAdopter):
score=adopter.get_score(adoption_center)
scoreboard.append((adopter,score))
elif isinstance(adopter,FearfulAdopter):
score=adopter.get_score(adoption_center)
scoreboard.append((adopter,score))
elif isinstance(adopter,AllergicAdopter):
score=adopter.get_score(adoption_center)
scoreboard.append((adopter,score))
elif isinstance(adopter,MedicatedAllergicAdopter):
score=adopter.get_score(adoption_center)
scoreboard.append((adopter,score))
elif isinstance(adopter,SluggishAdopter):
score=adopter.get_score(adoption_center)
scoreboard.append((adopter,score))
#sort first by score then by name
scoreboard.sort(key=lambda item:(-item[1],item[0].get_name()))
# a list of n-ordered adopters objects
liste_adopter=[]
i=0
if n > len(scoreboard):
n=len(scoreboard)
while i<n:
liste_adopter.append(scoreboard[i][0])
i+=1
else:
while i<n:
liste_adopter.append(scoreboard[i][0])
i+=1
return liste_adopter
<file_sep>/6.00.1x/finalExam/getSubLists.py
#!/usr/bin/python
def getSublists(L, n):
"""
This function returns a list of all possible sublists in L of length n without skipping elements in L.
The sublists in the returned list should be ordered in the way they appear in L, with those sublists
starting from a smaller index being at the front of the list.
"""
ListeOfSub=[]
#ListeOfSub.append([x for x in L for y in range(n)])
#use index + range with its 3 args!!
#ListeOfSub.append([L[i:i+n] for i in range(x,len(L),n)])
x=0
while x < len(L):
ListeOfSub.append(L[x:x+n])
x+=1
if x+n>len(L):break
print(ListeOfSub)
#getSublists([1,2,3,4],2)
getSublists([10, 4, 6, 8, 3, 4, 5, 7, 7, 2],4)
<file_sep>/6.00.1x/quizz/dictInterdiff.py
#!/usr/bin/python
def f(a,b):
return a+b
def dict_interdiff(d1, d2):
'''
d1, d2: dicts whose keys and values are integers
Returns a tuple of dictionaries according to the instructions above
'''
#two dict: one for intersect, one for diff. So write to func which returns one dict?
d3={}
d4={}
#intersect
for key in list(d1.keys()):
for key2 in list(d2.keys()):
if key==key2:
d3[key]=f(d1[key],d2[key])
#diff
for key in list(d1.keys()):
if key not in list(d2.keys()):
d4[key]=d1[key]
else: continue
for key2 in list(d2.keys()):
if key2 not in list(d1.keys()):
d4[key2]=d2[key2]
else:continue
# return (d4)
return (d3,d4)
d1 = {1:30, 2:20, 3:30, 5:80}
d2 = {1:40, 2:50, 3:60, 4:70, 6:90}
d=dict_interdiff(d1,d2)
print(d)
<file_sep>/6.00.1x/pset7/test_ps7.py
#!/usr/bin/python
from ps7_skeleton import *
#PART 1
#adoption_center=AdoptionCenter("SPA",{"Dog": 10, "Cat": 5, "Lizard":3,"Camel":1},(5.0,6.1))
#species_dico=adoption_center.get_species_count()
#print(species_dico)
#PART 2
#Oki: name, desired spec, list of allergic spec and a dict of med effectiveness
#adopter=MedicatedAllergicAdopter("joe","Cat", ("Horse", "Camel", "Dog"), {"Dog":0.5,"Camel":0.0,"Horse":0.98})
#adopter=AllergicAdopter("joe","Cat", ("Horse", "Cat", "Dog"))
#score=adopter.get_score(adoption_center)
#print(score)
#adopter=SluggishAdopter("joe","Horse Cat Dog",(5.0,6.1))
#d=adopter.get_linear_distance(adoption_center.get_location())
#s=adopter.get_score(adoption_center)
#print(d,s)
#PART 3
adopter = MedicatedAllergicAdopter("One", "Cat", ['Dog', 'Horse'],{"Dog": .5, "Horse": 0.2})
adopter2 = Adopter("Two", "Cat")
adopter3 = FlexibleAdopter("Three", "Horse", ["Lizard", "Cat"])
adopter4 = FearfulAdopter("Four","Cat","Dog")
adopter5 = SluggishAdopter("Five","Cat", (1,2))
adopter6 = AllergicAdopter("Six", "Cat", "Dog")
ac = AdoptionCenter("Place1", {"Mouse": 12, "Dog": 2}, (1,1))
ac2 = AdoptionCenter("Place2", {"Cat": 12, "Lizard": 2}, (3,5))
ac3 = AdoptionCenter("Place3", {"Horse": 25, "Dog": 9}, (-2,10))
ac4 = AdoptionCenter("Place4", {"Cat": 33, "Horse": 5}, (-3,0))
ac5 = AdoptionCenter("Place5", {"Cat": 45, "Lizard": 2}, (8,-2))
ac6 = AdoptionCenter("Place6", {"Cat": 23, "Dog": 7, "Horse": 5}, (-10,10))
#3.1
# how to test get_ordered_adoption_center_list
#get_ordered_adoption_center_list(adopter4, [ac,ac2,ac3,ac4,ac5,ac6])
# you can print the name and score of each item in the list returned
#print(isinstance(adopter,FearfulAdopter)) # ==> yield False!!
# how to test get_adopters_for_advertisement
get_adopters_for_advertisement(ac2, [adopter, adopter2, adopter3, adopter4, adopter5, adopter6], 10)
# you can print the name and score of each item in the list returned
<file_sep>/6.00.1x/pset1/item_order.py
#!/usr/bin/python
def item_order(order):
"""
This must be written as a function which must return sth
here a well-formatted string
"""
items=list(order.split())
count_items={'salad':0,'hamburger':0,'water':0}
count=0
y=0
while y <= len(items)-1:
prev=items[y]
for i in items:
if i==prev:
count +=1
count_items[i]=count
count=0
y+=1
#string formatting cf 7.1.1 Python Tut
result='salad:{salad:d} hamburger:{hamburger:d} water:{water:d}'.format(**count_items)
return result
<file_sep>/6.00.1x/pset6/mk_dict.py
#!/usr/bin/python
import string
#am lazy cant write the 26 letters etc by hand
#could reuse that: in a func + python -c?? Argv??
#The last comma is not a problem...ouf...
def mk_dict(L):
'''
Take an iterable
Return a dict numbered from 0
'''
count=0
print('{',end='')
for i in L:
print("\'{0}\':{1},".format(i,str(count)),end='')
count+=1
if count==14: print("\n",end='')
print('}')
### TESTING ###
mk_dict(string.ascii_uppercase)
#mk_dict(['a','b','c'])
<file_sep>/6.00.1x/pset2/balance.py
#!/usr/bin/python
"""
Those 3 values shouldn't be specified
Here for test purposes only
"""
balance=3568
annualInterestRate=0.18
monthlyPaymentRate=0.05
monthlyInterestRate=annualInterestRate/12.0
paid=[]
def balanceAfterInterest(balance,monthlyInterestRate):
unpaid_balance= balance - miniMonthlyPayment
interest=unpaid_balance + (monthlyInterestRate*unpaid_balance)
return round(interest,2)
for i in range(1,13):
miniMonthlyPayment=round(balance*monthlyPaymentRate,2)
paid.append(miniMonthlyPayment)
if i < 12:
print("Month:",i)
print("Minimum Monthly Payment:",miniMonthlyPayment)
print("Remaining balance:",balanceAfterInterest(balance,monthlyInterestRate))
if i==12:
print("Month:",i)
print("Minimum Monthly Payment:",miniMonthlyPayment)
print("Remaining balance:",balanceAfterInterest(balance,monthlyInterestRate))
print("Total paid:",round(sum(paid),2))
print("Remaining balance:",balanceAfterInterest(balance,monthlyInterestRate))
balance=balanceAfterInterest(balance,monthlyInterestRate)
| 22d2059d5959216ab898aa483f0191d7df3ff31f | [
"Python"
] | 22 | Python | mayweed/6.00x | 4e0f7ceafd02d752407c5714ad7478908b453c1d | 3126aaea3a0a88caf31aac41129bb446911d7b3e |
refs/heads/master | <file_sep>class Branch:
def __init__(self,Number):
self.number = Number
self.left = self.right = None
class binaryTree:
def __init__(self):
self.Tree = None
#recursive to insert branch (value) to binary tree. If value below current branch value then go to left else go to right.
def recInsert(self,Tree,Number):
if Number < Tree.number:
if Tree.left == None:
Tree.left = Branch(Number)
else:
self.recInsert(Tree.left,Number)
else:
if Tree.right == None:
Tree.right = Branch(Number)
else:
self.recInsert(Tree.right,Number)
#insert branch (value) to binary tree.
def insertBinTree(self,Number):
if self.Tree == None:
self.Tree = Branch(Number)
return
self.recInsert(self.Tree,Number)
#insert branch (value) to binary tree from current list.
def insertFromList(self,List):
if len(List) == 0:
return
self.insertBinTree(List[0])
self.insertFromList(List[1:])
#recursive to print binary tree from root, left, and right position until branch become None.
def recPrint(self,Tree):
if Tree == None:
print('()',end='')
return
print('(',end='')
print(Tree.number,end='')
self.recPrint(Tree.left)
self.recPrint(Tree.right)
print(')',end='')
#print binary tree.
def printTree(self):
self.recPrint(self.Tree)
print()
<file_sep># Python-Module
Python module.
<file_sep>class List:
def __init__(self,Number):
self.number = Number
self.next = None
class linkedList:
def __init__(self):
self.LinkedList = None
#insert element to the first position of list
def insertFirst(self,Number):
if self.LinkedList == None:
self.LinkedList = List(Number)
return
temp = List(Number)
temp.next = self.LinkedList
self.LinkedList = temp
#delete first element of linked list and return it.
def delFirst(self):
Number = self.LinkedList
if Number != None:
self.LinkedList = self.LinkedList.next
Number.next = None
return Number
#delete first element of linked list.
def deleteFirst(self):
Number = self.delFirst()
del(Number)
#recursive until (After) found and insert number after (After) or return if (After) didn't exist in linked list.
def recAfter(self,LinkedList,Number,After):
if LinkedList == None:
print('Empty List or cannot find %d'%After)
print('Insert Fail')
return
elif LinkedList.number == After:
temp = List(Number)
temp.next = LinkedList.next
LinkedList.next = temp
return
self.recAfter(LinkedList.next,Number,After)
#insert number after (After)
def insertAfter(self,Number,After):
self.recAfter(self.LinkedList,Number,After)
#delete number after (After) if (After) exist or return None if list empty or (After) didn't exist.
def delAfter(self,LinkedList,After):
if LinkedList == None:
return None
elif LinkedList.number == After and LinkedList.next != None:
temp = LinkedList.next
LinkedList.next = temp.next
temp.next = None
return temp
self.delAfter(LinkedList.next,After)
#delete number after (After)
def deleteAfter(self,After):
Number = self.delAfter(self.LinkedList,After)
del(Number)
#recursive until the last element of list.
def recLast(self,LinkedList,Number):
if LinkedList.next == None:
LinkedList.next = List(Number)
return
self.recLast(LinkedList.next,Number)
#insert element to the list at last position.
def insertLast(self,Number):
if self.LinkedList == None:
self.insertFirst(Number)
return
self.recLast(LinkedList,Number)
#delete element of the list at last position and return it or return none if list empty.
def delLast(self,LinkedList):
if LinkedList == None:
return None
elif LinkedList.next == None:
return self.delFirst()
elif LinkedList.next.next == None:
temp = LinkedList.next
LinkedList.next = temp.next
return temp
self.delLast(LinkedList.next)
#delete last element of list.
def deleteLast(self):
Number = self.delLast(self.LinkedList)
del(Number)
#recursive and print number in list element until list element become None.
def recPrint(self,LinkedList):
if LinkedList == None:
return
print(LinkedList.number,end='')
if LinkedList.next != None:
print(' -> ',end='')
self.recPrint(LinkedList.next)
#print list
def printList(self):
self.recPrint(self.LinkedList)
print()
| 19d225b539fa47999ef52ef75519f4ed45489625 | [
"Markdown",
"Python"
] | 3 | Python | masamunekenji/Python-Module | f4943b1d9420b9ec7a6014fb27b9d596ebe3dcea | 4102f9aa8ad3568fbc681c54704336df5181ea41 |
refs/heads/master | <repo_name>Dmenk123/Carwash<file_sep>/application/modules/kunci_lap/views/modal_kunci_lap.php
<?php
$obj_date = new DateTime();
$timestamp = $obj_date->format('Y-m-d H:i:s');
$bln_now = (int)$obj_date->format('m');
$thn_now = (int)$obj_date->format('Y');
$thn_awal = $thn_now - 20;
$thn_akhir = $thn_now + 20;
?>
<div class="modal fade modal_add_form" tabindex="-1" role="dialog" aria-labelledby="add_menu" aria-hidden="true" id="modal_kunci_form">
<div class="modal-dialog modal-md" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modal_title"></h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
</button>
</div>
<div class="modal-body">
<form id="form-user" name="form-user">
<div class="form-group">
<input type="hidden" class="form-control" id="id" name="id">
<label for="lbl_username" class="form-control-label">Bulan:</label>
<select name="bulan" id="bulan" class="select2 form-control" style="width: 100%;">
<option value="">Silahkan Pilih Bulan</option>
<?php
for ($i=1; $i <= 12; $i++) {
if($i == $bln_now) {
echo '<option value="'.$i.'" selected>'.bulan_indo($i).'</option>';
}else{
echo '<option value="'.$i.'">'.bulan_indo($i).'</option>';
}
}
?>
</select>
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="lbl_username" class="form-control-label">Tahun:</label>
<select name="tahun" id="tahun" class="form-control select2" style="width: 100%;">
<option value="">Silahkan Pilih Tahun</option>
<?php
for ($i=$thn_awal; $i <= $thn_akhir; $i++) {
if($i == $thn_now) {
echo '<option value="'.$i.'" selected>'.$i.'</option>';
}else{
echo '<option value="'.$i.'">'.$i.'</option>';
}
}
?>
</select>
<span class="help-block"></span>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn_outline" data-dismiss="modal">Batal</button>
<button type="button" class="btn btn_1" id="btnSave" onclick="save()">Simpan</button>
</div>
</div>
</div>
</div>
<file_sep>/t_role_menu.sql
/*
Navicat Premium Data Transfer
Source Server : local-mysql
Source Server Type : MySQL
Source Server Version : 100413
Source Host : localhost:3306
Source Schema : db_carwash
Target Server Type : MySQL
Target Server Version : 100413
File Encoding : 65001
Date: 11/06/2021 02:49:21
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for t_role_menu
-- ----------------------------
DROP TABLE IF EXISTS `t_role_menu`;
CREATE TABLE `t_role_menu` (
`id_menu` int(11) NOT NULL,
`id_role` int(11) NOT NULL,
`add_button` int(1) NULL DEFAULT 0,
`edit_button` int(1) NULL DEFAULT 0,
`delete_button` int(1) NULL DEFAULT 0,
INDEX `f_level_user`(`id_role`) USING BTREE,
INDEX `id_menu`(`id_menu`) USING BTREE,
CONSTRAINT `t_role_menu_ibfk_1` FOREIGN KEY (`id_role`) REFERENCES `m_role` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT,
CONSTRAINT `t_role_menu_ibfk_2` FOREIGN KEY (`id_menu`) REFERENCES `m_menu` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = COMPACT;
-- ----------------------------
-- Records of t_role_menu
-- ----------------------------
INSERT INTO `t_role_menu` VALUES (1, 3, 0, 0, 0);
INSERT INTO `t_role_menu` VALUES (8, 3, 0, 0, 0);
INSERT INTO `t_role_menu` VALUES (9, 3, 1, 1, 1);
INSERT INTO `t_role_menu` VALUES (13, 3, 1, 1, 1);
INSERT INTO `t_role_menu` VALUES (1, 1, 0, 0, 0);
INSERT INTO `t_role_menu` VALUES (6, 1, 0, 0, 0);
INSERT INTO `t_role_menu` VALUES (7, 1, 1, 1, 1);
INSERT INTO `t_role_menu` VALUES (10, 1, 1, 1, 1);
INSERT INTO `t_role_menu` VALUES (11, 1, 1, 1, 1);
INSERT INTO `t_role_menu` VALUES (12, 1, 1, 1, 1);
INSERT INTO `t_role_menu` VALUES (19, 1, 1, 1, 1);
INSERT INTO `t_role_menu` VALUES (8, 1, 0, 0, 0);
INSERT INTO `t_role_menu` VALUES (9, 1, 1, 1, 1);
INSERT INTO `t_role_menu` VALUES (13, 1, 1, 1, 1);
INSERT INTO `t_role_menu` VALUES (14, 1, 1, 1, 1);
INSERT INTO `t_role_menu` VALUES (15, 1, 1, 1, 0);
INSERT INTO `t_role_menu` VALUES (16, 1, 0, 0, 0);
INSERT INTO `t_role_menu` VALUES (20, 1, 1, 1, 1);
INSERT INTO `t_role_menu` VALUES (17, 1, 1, 1, 1);
INSERT INTO `t_role_menu` VALUES (18, 1, 1, 1, 1);
INSERT INTO `t_role_menu` VALUES (2, 1, 0, 0, 0);
INSERT INTO `t_role_menu` VALUES (4, 1, 1, 1, 1);
INSERT INTO `t_role_menu` VALUES (3, 1, 1, 1, 1);
INSERT INTO `t_role_menu` VALUES (21, 1, 0, 0, 0);
INSERT INTO `t_role_menu` VALUES (22, 1, 1, 1, 1);
SET FOREIGN_KEY_CHECKS = 1;
<file_sep>/application/modules/dashboard/views/view_dashboard.php
<style>
.select2-selection__clear {
top: 26%!important;
}
</style>
<!-- begin:: Content -->
<div class="kt-content kt-grid__item kt-grid__item--fluid kt-grid kt-grid--hor" id="kt_content">
<!-- begin:: Content Head -->
<div class="kt-subheader kt-grid__item" id="kt_subheader">
<div class="kt-container kt-container--fluid ">
<div class="kt-subheader__main">
<h3 class="kt-subheader__title">
<?= $title ?>
</h3>
</div>
</div>
</div>
<!-- end:: Content Head -->
<!-- begin:: Content -->
<div class="kt-container kt-container--fluid kt-grid__item kt-grid__item--fluid">
<div class="kt-portlet kt-portlet--mobile">
<div class="kt-portlet__head kt-portlet__head--lg">
<div class="kt-portlet__head-label">
<span class="kt-portlet__head-icon">
<i class="kt-font-brand flaticon2-line-chart"></i>
</span>
<h3 class="kt-portlet__head-title">
<?= $title; ?>
</h3>
</div>
<div class="kt-portlet__head-toolbar">
<div class="kt-portlet__head-wrapper">
<div class="kt-portlet__head-actions">
</div>
</div>
</div>
</div>
<div class="kt-portlet__body">
<!-- body -->
<div class="serach-navbar d-none d-lg-block d-xl-block" data-select2-id="14">
<form id="form-pegawai">
<div class="row no-gutters custom-search-input-3">
<div class="col-lg-7">
<div class="form-group">
<select class="form-control select2" id="selReg" name="jenis_penjualan" id="jenis_penjualan" style="width: 100%;border-radius: 0px;">
<!-- <select class="wide select2 " multiple="" name="mediaCtg" data-select2-id="liveSrchMedia" tabindex="-1" aria-hidden="true"> -->
<?php foreach($penjualan as $row) { ?>
<option value="<?=$row->id?>" ><?=$row->nama?></option>
<?php } ?>
</select>
<div class="clearfix"></div>
</div>
</div>
<div class="col-lg-3" data-select2-id="38">
<div class="form-group" data-select2-id="37">
<select id="liveSrchCity" class="wide select2-hidden-accessible select2" name="tahun" id="tahun" style="width: 100%;border-radius: 0px;" data-select2-id="liveSrchCity" tabindex="-1" aria-hidden="true">
<?php for ($i=2020;$i<=date("Y");$i++) { ?>
<option value="<?=$i?>" <?php if ($i == date('Y')) {
echo "selected"; } ?> ><?=$i?></option>
<?php } ?>
</select>
<div class="clearfix"></div>
</div>
</div>
<div class="col-lg-2 col-md-2">
<input type="submit" class="btn_search" onclick="search()" value="seacrh">
</div>
</div>
</form>
</div>
<br>
<br>
<div class="col-lg-12">
<canvas id="line-chart" width="800" height="450"></canvas>
</div>
<!-- body -->
</div>
</div>
</div>
</div>
<file_sep>/t_log_laporan.sql
/*
Navicat Premium Data Transfer
Source Server : local-mysql
Source Server Type : MySQL
Source Server Version : 100413
Source Host : localhost:3306
Source Schema : db_carwash
Target Server Type : MySQL
Target Server Version : 100413
File Encoding : 65001
Date: 10/06/2021 02:19:26
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for t_log_laporan
-- ----------------------------
DROP TABLE IF EXISTS `t_log_laporan`;
CREATE TABLE `t_log_laporan` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_user` int(64) NULL DEFAULT NULL,
`bulan` int(2) NULL DEFAULT NULL,
`tahun` int(4) NULL DEFAULT NULL,
`id_log_kunci` int(64) NULL DEFAULT NULL,
`saldo_awal` float(20, 2) NULL DEFAULT NULL,
`saldo_akhir` float(20, 2) NULL DEFAULT NULL,
`created_at` datetime(0) NULL DEFAULT NULL,
`updated_at` datetime(0) NULL DEFAULT NULL,
`deleted_at` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 2 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
<file_sep>/t_log_laporan_det.sql
/*
Navicat Premium Data Transfer
Source Server : local-mysql
Source Server Type : MySQL
Source Server Version : 100413
Source Host : localhost:3306
Source Schema : db_carwash
Target Server Type : MySQL
Target Server Version : 100413
File Encoding : 65001
Date: 10/06/2021 02:19:37
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for t_log_laporan_det
-- ----------------------------
DROP TABLE IF EXISTS `t_log_laporan_det`;
CREATE TABLE `t_log_laporan_det` (
`id` int(64) NOT NULL,
`id_log_laporan` int(64) NULL DEFAULT NULL,
`harga_total` float(20, 2) NULL DEFAULT NULL,
`id_jenis_trans` int(4) NULL DEFAULT NULL,
`kode_trans` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`urut` int(4) NULL DEFAULT NULL,
`penerimaan` float(20, 2) NULL DEFAULT NULL,
`pengeluaran` float(20, 2) NULL DEFAULT NULL,
`saldo_akhir` float(20, 2) NULL DEFAULT NULL,
`created_at` datetime(0) NULL DEFAULT NULL,
`updated_at` datetime(0) NULL DEFAULT NULL,
`deleted_at` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
<file_sep>/m_role.sql
/*
Navicat Premium Data Transfer
Source Server : local-mysql
Source Server Type : MySQL
Source Server Version : 100413
Source Host : localhost:3306
Source Schema : db_carwash
Target Server Type : MySQL
Target Server Version : 100413
File Encoding : 65001
Date: 11/06/2021 02:49:40
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for m_role
-- ----------------------------
DROP TABLE IF EXISTS `m_role`;
CREATE TABLE `m_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nama` varchar(20) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
`keterangan` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT '',
`aktif` int(1) NULL DEFAULT 1,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = COMPACT;
-- ----------------------------
-- Records of m_role
-- ----------------------------
INSERT INTO `m_role` VALUES (1, 'Superadmin', 'Level Super Admin', 1);
INSERT INTO `m_role` VALUES (2, 'Owner', 'Owner', 1);
INSERT INTO `m_role` VALUES (3, 'admin', 'admin', 1);
SET FOREIGN_KEY_CHECKS = 1;
<file_sep>/application/modules/kunci_lap/controllers/Kunci_lap.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Kunci_lap extends CI_Controller {
public function __construct()
{
parent::__construct();
if($this->session->userdata('logged_in') === false) {
return redirect('login');
}
$this->load->model('t_log_kunci');
$this->load->model('m_user');
$this->load->model('m_global');
$this->load->model('t_transaksi');
$this->load->model('t_transaksi_det');
$this->load->model('set_role/m_set_role', 'm_role');
}
public function index()
{
$id_user = $this->session->userdata('id_user');
$data_user = $this->m_user->get_detail_user($id_user);
$data_role = $this->m_role->get_data_all(['aktif' => '1'], 'm_role');
/**
* data passing ke halaman view content
*/
$data = array(
'title' => 'Kunci Laporan',
'data_user' => $data_user,
'data_role' => $data_role
);
/**
* content data untuk template
* param (css : link css pada direktori assets/css_module)
* param (modal : modal komponen pada modules/nama_modul/views/nama_modal)
* param (js : link js pada direktori assets/js_module)
*/
$content = [
'css' => null,
'modal' => 'modal_kunci_lap',
'js' => 'kunci_lap.js',
'view' => 'view_kunci_lap'
];
$this->template_view->load_view($content, $data);
}
public function list_kunci_laporan()
{
$list = $this->t_log_kunci->get_datatable_log_kunci();
$data = array();
$no =$_POST['start'];
foreach ($list as $val) {
$no++;
$row = array();
//loop value tabel db
$row[] = $no;
$row[] = $val->bulan;
$row[] = $val->tahun;
$row[] = $val->nama;
$row[] = $val->created_at;
$str_aksi = '
<button class="btn btn-sm btn-danger" onclick="delete_kuncian(\''.$val->id.'\')">
<i class="la la-trash"></i> Hapus
</button>
';
$str_aksi .= '</div></div>';
$row[] = $str_aksi;
$data[] = $row;
}//end loop
$output = [
"draw" => $_POST['draw'],
"recordsTotal" => $this->t_log_kunci->count_all(),
"recordsFiltered" => $this->t_log_kunci->count_filtered(),
"data" => $data
];
echo json_encode($output);
}
public function add_kunci_lap()
{
$this->load->library('Enkripsi');
$obj_date = new DateTime();
$timestamp = $obj_date->format('Y-m-d H:i:s');
$arr_valid = $this->rule_validasi();
$bulan = (int)$this->input->post('bulan');
$tahun = (int)$this->input->post('tahun');
$id_user = $this->session->userdata('id_user');
$cek = $this->m_global->single_row('*', ['bulan' => $bulan, 'tahun' => $tahun, 'deleted_at' => null], 't_log_kunci');
if($cek) {
$retval['status'] = false;
$retval['pesan'] = 'Bulan dan Tahun sudah terkunci !!!';
$retval['is_exist'] = true;
echo json_encode($retval);
return;
}
if ($arr_valid['status'] == FALSE) {
echo json_encode($arr_valid);
return;
}
$data_ins = [
'bulan' => $bulan,
'tahun' => $tahun,
'id_user' => $id_user,
'created_at' => $timestamp
];
$insert_id = $this->t_log_kunci->save($data_ins);
$simpan_log = $this->simpan_log_laporan($bulan, $tahun, $insert_id);
if($simpan_log) {
$data_log = json_encode($data_ins);
$this->lib_fungsi->catat_log_aktifitas('CREATE', null, $data_log);
$retval['status'] = true;
$retval['pesan'] = 'Sukses menambahkan Kunci Laporan';
}else{
$retval['status'] = false;
$retval['pesan'] = 'Gagal menambahkan Kunci Laporan';
}
echo json_encode($retval);
}
private function simpan_log_laporan($bulan, $tahun, $id_log_kunci) {
$obj_date = new DateTime();
$timestamp = $obj_date->format('Y-m-d H:i:s');
$this->db->trans_begin();
### cek log bulan_terpilih, jika ada set deleted_at
$cek_exist = $this->m_global->single_row('*', ['bulan' => $bulan, 'tahun' => $tahun, 'deleted_at' => null], 't_log_laporan');
if($cek_exist) {
$id_exist = $cek_exist->id;
// update t_log_laporan
$this->m_global->update('t_log_laporan', ['deleted_at' => $timestamp], ['id' => $id_exist]);
// update t_log_laporan_det
$this->m_global->update('t_log_laporan_det', ['deleted_at' => $timestamp], ['id_log_laporan' => $id_exist]);
}
$arr_periode = $this->ambil_periode_sebelum($bulan, $tahun);
// cek saldo bulan sebelumnya untuk di olah
$cek_saldo = $this->m_global->single_row('*', ['bulan' => $arr_periode['bulan'], 'tahun' => $arr_periode['tahun'], 'deleted_at' => null], 't_log_laporan');
if($cek_saldo) {
// set saldo awal dari saldo akhir periode sebelumnya
$saldo_fix = $cek_saldo->saldo_akhir;
}else{
//jika tidak ada terpaksa dihitung semua transaksi hingga sebelum bulan laporan terpilih
$q_saldo = $this->t_transaksi->cari_saldo_by_hitung($bulan, $tahun);
if($q_saldo->saldo && (float)$q_saldo->saldo > 0) {
$saldo_fix = (float)$q_saldo->saldo;
}else{
$saldo_fix = 'kosong';
}
}
$data_laporan = $this->t_transaksi->get_laporan_keuangan($bulan, $tahun);
// insert header
$id_header = $this->m_global->last_id('id', 't_log_laporan');
$data_ins = [
'id' => $id_header,
'id_user' => $this->session->userdata('id_user'),
'bulan' => $bulan,
'tahun' => $tahun,
'id_log_kunci' => $id_log_kunci,
'saldo_awal' => (float)$saldo_fix,
'saldo_akhir' => 0,
'created_at' => $timestamp
];
$this->m_global->store($data_ins, 't_log_laporan');
// loop data_detail
$tot_penerimaan = 0;
$tot_pengeluaran = 0;
if($saldo_fix == 'kosong') {
// hasil hitungan
$saldonya = 0;
}else{
// hasil hitungan
$saldonya = (float)$saldo_fix;
}
$data_ins_det_row_1 = [
'id' => $this->m_global->last_id('id', 't_log_laporan_det'),
'id_log_laporan' => $id_header,
'harga_total' => null,
'id_jenis_trans' => null,
'kode_trans' => null,
'urut' => 0,
'penerimaan' => 0,
'pengeluaran' => 0,
'saldo_akhir' => $saldonya,
'created_at' => $timestamp
];
$this->m_global->store($data_ins_det_row_1, 't_log_laporan_det');
foreach ($data_laporan as $key => $value) {
$penerimaan = 0;
$pengeluaran = 0;
if($value->cashflow == 'in') {
$saldonya += $value->total_harga;
$penerimaan = $value->total_harga;
$tot_penerimaan += $value->total_harga;
}else{
$saldonya -= $value->total_harga;
$pengeluaran = $value->total_harga;
$tot_pengeluaran += $value->total_harga;
}
$data_ins_det = [
'id' => $this->m_global->last_id('id', 't_log_laporan_det'),
'id_log_laporan' => $id_header,
'harga_total' => $value->total_harga,
'id_jenis_trans' => $value->id_jenis_trans,
'kode_trans' => $value->kode_jenis,
'urut' => $key+1,
'penerimaan' => (float)$penerimaan,
'pengeluaran' => (float)$pengeluaran,
'saldo_akhir' => (float)$saldonya,
'created_at' => $timestamp
];
$this->m_global->store($data_ins_det, 't_log_laporan_det');
}
// saldo akhir untuk diupdate pada tabel header
$saldo_akhir_fix = $saldo_fix + $tot_penerimaan - $tot_pengeluaran;
$this->m_global->update('t_log_laporan', ['saldo_akhir' => (float)$saldo_akhir_fix], ['id' => $id_header]);
if ($this->db->trans_status() === FALSE){
$this->db->trans_rollback();
return false;
}else{
$this->db->trans_commit();
return true;
}
}
private function ambil_periode_sebelum($bulan, $tahun)
{
$objDate = new DateTime($tahun.'-'.$bulan.'-01');
$tgl_fix = $objDate->modify('-1 month')->format('Y-m-d');
$bulan = $objDate->createFromFormat('Y-m-d', $tgl_fix)->format('m');
$tahun = $objDate->createFromFormat('Y-m-d', $tgl_fix)->format('Y');
return [
'bulan' => (int)$bulan,
'tahun' => (int)$tahun
];
}
/**
* Hanya melakukan softdelete saja
* isi kolom updated_at dengan datetime now()
*/
public function delete_kunci_lap()
{
$id = $this->input->post('id');
$old_data = $this->m_global->single_row_array('*', ['id' => $id], 't_log_kunci');
$del = $this->t_log_kunci->softdelete_by_id($id);
$data_log_old = json_encode($old_data);
$this->lib_fungsi->catat_log_aktifitas('DELETE', $data_log_old, null);
if($del) {
$retval['status'] = TRUE;
$retval['pesan'] = 'Data Kuncian dihapus';
}else{
$retval['status'] = FALSE;
$retval['pesan'] = 'Data Kuncian dihapus';
}
echo json_encode($retval);
}
// ===============================================
private function rule_validasi()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
if ($this->input->post('tahun') == '') {
$data['inputerror'][] = 'tahun';
$data['error_string'][] = 'Wajib mengisi tahun';
$data['status'] = FALSE;
}
if ($this->input->post('bulan') == '') {
$data['inputerror'][] = 'bulan';
$data['error_string'][] = 'Wajib mengisi bulan';
$data['status'] = FALSE;
}
return $data;
}
private function seoUrl($string) {
//Lower case everything
$string = strtolower($string);
//Make alphanumeric (removes all other characters)
$string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
//Clean up multiple dashes or whitespaces
$string = preg_replace("/[\s-]+/", " ", $string);
//Convert whitespaces and underscore to dash
$string = preg_replace("/[\s_]/", "-", $string);
return $string;
}
}
<file_sep>/m_menu.sql
/*
Navicat Premium Data Transfer
Source Server : local-mysql
Source Server Type : MySQL
Source Server Version : 100413
Source Host : localhost:3306
Source Schema : db_carwash
Target Server Type : MySQL
Target Server Version : 100413
File Encoding : 65001
Date: 11/06/2021 02:49:58
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for m_menu
-- ----------------------------
DROP TABLE IF EXISTS `m_menu`;
CREATE TABLE `m_menu` (
`id` int(11) NOT NULL,
`id_parent` int(11) NOT NULL,
`nama` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
`judul` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
`link` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
`icon` varchar(255) CHARACTER SET latin1 COLLATE latin1_swedish_ci NULL DEFAULT NULL,
`aktif` int(1) NULL DEFAULT NULL,
`tingkat` int(11) NULL DEFAULT NULL,
`urutan` int(11) NULL DEFAULT NULL,
`add_button` int(1) NULL DEFAULT NULL,
`edit_button` int(1) NULL DEFAULT NULL,
`delete_button` int(1) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = latin1 COLLATE = latin1_swedish_ci ROW_FORMAT = COMPACT;
-- ----------------------------
-- Records of m_menu
-- ----------------------------
INSERT INTO `m_menu` VALUES (1, 0, 'Dashboard', 'Dashboard', 'home', 'flaticon2-architecture-and-city', 1, 1, 1, 0, 0, 0);
INSERT INTO `m_menu` VALUES (2, 0, 'Setting (Administrator)', 'Setting', '', 'flaticon2-gear', 1, 1, 100, 0, 0, 0);
INSERT INTO `m_menu` VALUES (3, 2, 'Setting Menu', 'Setting Menu', 'set_menu', 'flaticon-grid-menu', 1, 2, 2, 1, 1, 1);
INSERT INTO `m_menu` VALUES (4, 2, 'Setting Role', 'Setting Role', 'set_role', 'flaticon-network', 1, 2, 1, 1, 1, 1);
INSERT INTO `m_menu` VALUES (6, 0, 'Master', 'Master', '', 'flaticon-folder-1', 1, 1, 2, 0, 0, 0);
INSERT INTO `m_menu` VALUES (7, 6, 'Data User', 'Data User', 'master_user', 'flaticon-users', 1, 2, 1, 1, 1, 1);
INSERT INTO `m_menu` VALUES (8, 0, 'Transaksi', 'Transaksi', '', 'flaticon2-shopping-cart', 1, 1, 3, 0, 0, 0);
INSERT INTO `m_menu` VALUES (9, 8, 'Penjualan', 'Penjualan', 'penjualan', 'flaticon2-shopping-cart-1', 1, 2, 1, 1, 1, 1);
INSERT INTO `m_menu` VALUES (10, 6, 'Jenis Transaksi', 'Jenis Transaksi', 'master_jenis_trans', 'flaticon-folder-1', 1, 2, 1, 1, 1, 1);
INSERT INTO `m_menu` VALUES (11, 6, 'Item Transaksi', 'Item Transaksi', 'master_item_trans', 'flaticon-folder-1', 1, 2, 3, 1, 1, 1);
INSERT INTO `m_menu` VALUES (12, 6, 'Profil', 'Master Profil', 'master_profil', 'flaticon-profile', 1, 2, 5, 1, 1, 1);
INSERT INTO `m_menu` VALUES (13, 8, 'Daftar Penjualan', 'Daftar Penjualan', 'daftar_penjualan', 'flaticon-list', 1, 2, 2, 1, 1, 1);
INSERT INTO `m_menu` VALUES (14, 8, 'Transaksi Lain Lain', 'Form Transaksi Non Penjualan', 'trans_lain', 'flaticon-open-box', 1, 2, 3, 1, 1, 1);
INSERT INTO `m_menu` VALUES (15, 8, 'Daftar Transaksi Lain-Lain', 'Pengelolaan Transaksi Non Penjualan', 'daftar_transaksi_lain', 'flaticon-list-2', 1, 2, 4, 1, 1, 1);
INSERT INTO `m_menu` VALUES (16, 0, 'Laporan', 'Laporan', '', 'flaticon-line-graph', 1, 1, 4, 0, 0, 0);
INSERT INTO `m_menu` VALUES (17, 16, 'Laporan Transaksi', 'Laporan Transaksi', 'lap_transaksi', 'flaticon-graph', 1, 2, 2, 1, 1, 1);
INSERT INTO `m_menu` VALUES (18, 16, 'Laporan Keuangan', 'Laporan Keuangan', 'lap_keuangan', 'flaticon-coins', 1, 2, 3, 1, 1, 1);
INSERT INTO `m_menu` VALUES (19, 6, 'Master Supplier', 'Master Supplier', 'master_supplier', 'flaticon-support', 1, 2, 5, 1, 1, 1);
INSERT INTO `m_menu` VALUES (20, 16, 'Kunci Laporan', 'Kunci Laporan', 'kunci_lap', 'flaticon-lock', 1, 2, 1, 1, 1, 1);
INSERT INTO `m_menu` VALUES (21, 0, 'Log', 'Log', '', 'flaticon-calendar-with-a-clock-time-tools', 1, 1, 5, 0, 0, 0);
INSERT INTO `m_menu` VALUES (22, 21, 'Log Aktivitas', 'Log Aktivitas User', 'log_aktivitas', 'flaticon2-calendar-3', 1, 2, 1, 1, 1, 1);
SET FOREIGN_KEY_CHECKS = 1;
| 24936c4687a222b21186e97365fb19e331a6518b | [
"SQL",
"PHP"
] | 8 | PHP | Dmenk123/Carwash | 100d1cd22990adc5f6ed1b5af6347bd99813c662 | 51700e56b35391da4161f213a0a09269ecfce486 |
refs/heads/master | <repo_name>ngttt/nguyenthithuytien-c4ejs<file_sep>/session4/index.js
// let movie = {
// name: 'hotel transylvana',
// year: 2012,
// type: 'animation'
// }
// console.log(movie.name, movie.type);
// let key = name;
// console.log(movie[key]);
// //read all
// movie.actor = 'bat';
// let a = prompt('enter the key');
// let a1 = prompt('enter the value');
// movie.a=a1;
// for (let k in movie)
// {
// console.log(k, movie[k]);
// }
// movie.name = 've nha di con';
// movie.type = 'series';
// console.log(movie);
// //delete
// delete movie.type;
// console.log(movie);
let quiz = [
{
question: 'con nhen co may chan?',
choices: ['1 chan',
'2 chan',
'3 chan',
'6 chan'],
answer: 3
},
{
question: 'con ga co may chan?',
choices: ['1 chan',
'2 chan',
'3 chan',
'6 chan'],
answer: 1
}
]
for (let i = 0; i< quiz.length ; i++)
{
console.log(quiz[i].question);
for (let j = 0 ; j < quiz[i].choices.length; j++ )
{
console.log(`${j+1}: ${ quiz[i].choices [j] }`);
}
let your = prompt('Your answer 1 or 2 or 3 or 4');
if (your -1 == quiz[i].answer)
{
console.log('yayyyyyyy!');
}
else
console.log('ohno');
}
// console.log(quiz.question);
// for (let i =0; i< quiz.choices.length; i+1)
// {
// console.log(i+1, quiz.choices[i]);
// }
// let your = prompt('Choose your answer');
// if(your -1 == quiz.answer)
// {
// console.log('You are right');
// }
// else {
// console.log('Hope you lucky in another time');
// }
<file_sep>/session3/btpart1/index.js
let list1 = [5, 1, 8, 92, 7,30];
console.log('All event numbers: ');
for(let i=0; i<list1.length; i++){
if (list1[i] % 2==0){
console.log(list1[i]);
}
}
let list2 = prompt('nhap so cach nhau boi dau phay');
console.log(`Enter a list of numbers, separated by ',': `, list2);
console.log('All event numbers from entered list: ');
let numberlist = list2.split(',');
for(let i=0; i<numberlist.length; i++){
if (numberlist[i] % 2==0)
console.log(numberlist[i]);
}<file_sep>/session6/functionhomework3/index.js
//3 calculate properties of a circle
let r1 = prompt('Enter a radius');
function calcCircumfrence (radius)
{
let circumfrence = 2 * radius * 3.14;
return circumfrence;
}
let circumfrence = calcCircumfrence(r1);
console.log('The circumference is',circumfrence);
let r2 = prompt('Enter a radius');
function calcArea (radius)
{
let area = (radius**2)*3.14;
return area;
}
let area = calcArea(r2);
console.log('The area is ', area);<file_sep>/session6/functionhomework4/index.js
//4 a converter
let numberC1 = prompt('Enter the number of celsius temperature for changing to fahrenheit temperature')
function celsiusToFahrenheit (number)
{
let numberF =number*1.8 +32 ;
return numberF;
}
let numberF1=celsiusToFahrenheit(numberC1);
console.log(`${numberC1}°C is ${numberF1}°F`);
let numberF2 = prompt('Enter the number of fahrenheit temperature for changing to celsius temperature')
function celsiusToFahrenheit (number)
{
let numberC =number*1.8 +32 ;
return numberC;
}
let numberC2=celsiusToFahrenheit(numberF2);
console.log(`${numberF1}°F is ${numberC1}°C`);
<file_sep>/session6/index.js
// function calc(input, number1, number2){
// let result = 0;
// if(input == '+')
// {
// result = number1+number2;
// }
// else
// if(input == '-')
// {
// result = number1-number2;
// }
// else
// if(input == '*')
// {
// result = number1*number2;
// }
// else
// if(input == '/')
// {
// if(Number(number2)==0)
// {
// console.log('Khong hop le');
// }
// else
// {
// result = number1/number2;
// }
// }
// return result;
// }
// function genaratequiz()
// {
// let a = Math.random(0,10);
// let number1 = Math.floor(a*10);
// let b = Math.random(0,10);
// let number2 = Math.floor(b*10);
// let c = Math.floor((Math.random(0,2))*10);
// let sum = number1+number2+c;
// console.log(`${number1} + ${number2} = ${sum}`);
// let final = plus (number1,number2,sum);
// return final;
// }
// function plus (number1,number2,sum)
// {
// if(number1+number2==sum)
// return 1;
// else return 2;
// }
// let score = 0;
// function total(){
// let choose= prompt('1.True or 2.False')
// let final=genaratequiz();
// return final;
// }
// for(let i =0; i<11; i++)
// {
// let final = total();
// if(final==choose)
// {
// score ++;
// }
// else score--;
// }
function filterodd(array)
{
let newarray = [];
for(let i=0; i<array.length; i++)
{
if(array[i]%2==0)
{
newarray.push(array[i]);
}
}
return newarray;
}
let res = filterodd([1,2,3,6,5,9,7]);
console.log(res);<file_sep>/session7PromiseCallback/index.js
// function generateList(text)
// {
// let array = text.split(' ');
// return array;
// }
// let listNumbers = generateList("2 34 64 245 4");
// console.log(listNumbers);
// PROMISE
// function diCho(tacDuong) {
// return new Promise ( function (resolve, reject) {
// console.log('Dang di cho');
// if(tacDuong==true){
// reject('khong di duoc');
// }
// else {
// resolve("rau");
// }
// })
// }
// let result = diCho(true).then(function(item){
// console.log(item);
// }).catch(function(reason){
// console.log(reason);
// });
//C1 get
const res = fetch("http://5dc6a9cb317717001434f796.mockapi.io/api/members").then(function(respone){
respone.json().then(function(data){
console.log("cach dung promise ",data);
})
})
console.log(res);
//C2 dung async : bat dong bo va await
async function getData()
{
try
{
const respone = await fetch("http://5dc6a9cb317717001434f796.mockapi.io/api/members");
const data = await respone.json();
console.log("cach dung await", data);
}
catch (err)
{
console.log(err);
}
}
getData();
//Post Data
async function postData(data)
{
const url = "http://5dc6a9cb317717001434f796.mockapi.io/api/members"
await fetch (url, {
method: "post",
body: JSON.stringify(data),
headers:
{
"Content-type": "application/json"
}
});
}
const data = {
name : "<NAME>",
gender : 2,
role : "students"
}
//Put
// async function updateData(id,data)
// {
// const url = `http://5dc6a9cb317717001434f796.mockapi.io/api/members/${id}`;
// await fetch (url, {
// method: "put",
// body: JSON.stringify(data),
// headers:
// {
// "Content-type": "application/json"
// }
// });
// }
//
//Delete
async function deleteData(id,data)
{
const url = `http://5dc6a9cb317717001434f796.mockapi.io/api/members/${id}`;
await fetch (url, {
method: "delete"
});
}
// muon chay tuan tu
async function main ()
{
await postData(data);
await updateData(8,data);
await deleteData(19,data);
await getData();
console.log ("Done");
}<file_sep>/session1/index.js
let n = prompt('Nhap thang');
if (n==1 || n==2 || n==3) {
console.log('Mua Xuan');
}
else if (n==4 || n==5 || n==6) {
console.log('Mua Ha');
}
else if (n==7 || n==8 || n==9) {
console.log ('Mua Thu');
}
else {
console.log('Mua Dong');
}<file_sep>/session4/homework1/index.js
// 1
let store = {
HP : 20,
DELL : 50,
MACBOOK: 12,
ASUS:30
}
//2
console.log(store.MACBOOK);
//3
let a = prompt('nhap hang can tim');
console.log(store[a]);
//4
store.TOSHIBA =10;
console.log(store['TOSHIBA']);
//5
let your1 = prompt('nhap hang can them');
let your2 = prompt('nhap so luong');
store[your1] = Number(your2);
console.log(store);
//6
store.DELL +=10;
store.MACBOOK -= 2;
console.log(store);
//7
for (let k in store)
{
console.log(k,store[k]);
console.log(':');
}
//8
let sum = 0;
for (let k in store)
{
sum += store[k];
}
console.log('tong cong la: ',sum);
//9
store.FUJITSU =15;
store.ALIENWARE=5;
console.log(store);
//10
for (let k in store)
{
console.log(k,store[k]);
console.log(':');
}
//PART 4
//1
let price = {
HP: 600,
DELL: 650,
MACBOOK: 12000,
ASUS: 400,
ACER: 350,
TOSHIBA: 600,
FUJITSU: 900,
ALIENWARE: 1000
}
price[your1] = 100; // them gia cua hang duoc nguoi dung nhap
//2
console.log('gia cua 1 may ASUS: ',price.ASUS);
//3
console.log(price);
let n = prompt('Nhap hang can tra gia')
console.log(n,' gia tien: ', price[n]);
//PART 5
//4
let math = price.ASUS * 5;
console.log('tong gia tri don hang cua 5 may asus: ', math );
//5
let cus = prompt('Nhap hang can mua');
let num = prompt('Nhap so luong may can mua');
let math1 = price[cus] * Number(num);
console.log('tong gia tri don hang ',cus, ' voi so luong la ', num, ' la: ',math1);
//6
console.log('ton kho');
store.ASUS -= 5;
store[cus] -= num ;
//7
for (let k in store)
{
console.log(k, store[k]);
console.log(':');
}
//PART 6
//8
for ( let k in store)
{
console.log('tong gia tri cua may ', k, price[k]*store[k]);
}
//9
let sumstore = 0;
for (let k in store)
{
sumstore = sumstore + (price[k]*store[k]);
}
console.log('tong gia tri cua kho', sumstore);<file_sep>/session5/index.js
//PART 7
//10
let character = {
name: 'Light',
age: 17,
strength: 8,
defense: 10,
HP: 100,
backpack: ['Shield', 'Bread Loaf'],
gold: 100,
level: 2
}
//11
character.gold += 50;
//12
character.backpack += 'FlintStone';
//13
character.pocket = ['MonsterDex', 'Flashlight'];
console.log(character);
//PART 8
//14
let skill = [
{
name: 'Tackle',
minium_level: 1,
damage: 5,
hit_rate: 0.3
},
{
name: 'Quick attack',
minium_level: 2,
damage: 3,
hit_rate: 0.5
},
{
name: 'Strong Kick',
minium_level: 4,
damage: 9,
hit_rate: 0.2
}
]
//15
for (let k in skill)
{
console.log(k, skill[k]);
}
//16
for ( let i = 0; i < skill.length; i++)
{
console.log(`${i+1}: ${skill[i].name}`);
}
//PART 9
//17,18
let e1 = prompt('Chon skill thu 1');
if ( Number(skill[ Number(e1) - 1 ].minium_level) > Number(character.level))
{
console.log('khong cho phep');
}
else
{
let random = Math.random(0,1);
console.log(random);
if(random > skill[Number(e1)].hit_rate )
{
console.log('skill da khong trung muc tieu');
}
else
{
console.log(`Damage: ${skill[e1-1].damage}`);
}
}
let e2 = prompt('Chon skill thu 2');
if ( Number(skill[ Number(e2) - 1 ].minium_level) > Number(character.level))
{
console.log('khong cho phep');
}
else
{
let random = Math.random(0,1);
console.log(random);
if(random > skill[Number(e2)].hit_rate )
{
console.log('skill da khong trung muc tieu');
}
else
{
console.log(`Damage: ${skill[e2-1].damage}`);
}
}
let e3 = prompt('Chon skill thu 3');
if ( Number(skill[ Number(e3) - 1 ].minium_level) > Number(character.level))
{
console.log('khong cho phep');
}
else
{
let random = Math.random(0,1);
if(random > skill[Number(e3)].hit_rate )
{
console.log('skill da khong trung muc tieu');
}
else
{
console.log(`Damage: ${skill[e3-1].damage}`);
}
}
<file_sep>/session6/functionhomework1/index.js
//1 dog years
function caculateDogAge(age)
{
age = age *7;
return age;
}
for (let i=0; i<3; i++) {
let dogage = prompt('Your age of dog?');
let age = caculateDogAge(dogage);
console.log(`Your doggie is ${age} years old in dog years`);
}
<file_sep>/session11DOM/Quote/index.js
async function getData ()
{
try {
const respone = await fetch('https://raw.githubusercontent.com/edtechkidsvn/quotes/master/data.json');
const data = await respone.json();
return data;
}
catch (err)
{
console.log(err);
}
}
async function handleSubmit ()
{
let dataResult = await getData();
let number = Math.floor(Math.random() * dataResult.length );
const container = document.getElementById('container');
container.innerHTML = `<p> ${dataResult[number].quoteText} </p>
<a> ${dataResult[number].quoteAuthor} </a>`;
}
function click ()
{
const click = document.getElementById('click');
click.addEventListener( 'click', handleSubmit);
}
click();<file_sep>/session6/functionhomework2/index.js
let maxage = 100;
function caculateSupply(age,amountperday)
{
let amount = (maxage - age) * amountperday;
return amount;
}
for (let i = 0; i< 3; i++)
{
let age = prompt ('How old are you?');
let amountperday = prompt('How many snack do you eat for one day?');
let amount = caculateSupply(age,amountperday);
console.log(`You will need ${amount} you last to until the ripe old age of ${maxage}`);
}<file_sep>/session6/homework.js
// Đoạn code dưới đây mô phỏng 1 chương trình gồm 2 phần:
// Phần 1:
// - Cho người dùng nhập vào một chuỗi các số, ngăn cách nhau bởi dấu cách (space)
// - In ra màn hình số lớn nhất trong dãy số người dùng vừa nhập
// Phần 2:
// - Cho người dùng nhập vào một đoạn text có chứa dấu cách
// - In ra màn hình đoạn text người dùng vừa nhập, đã được loại bỏ hết dấu cách (space)
// Yêu cầu:
// - Tối ưu đoạn code phía dưới bằng cách tìm ra chức năng chung của 2 phần, gộp lại thành một function,
// sau đó sử dụng chung function đó cho cả 2 phần
// Lưu ý:
// - Đoạn code phía dưới chưa bao gồm việc kiểm tra input của người dùng. Mục đích chính của bài này
// không phải là kiểm tra input của người dùng, vậy nên bạn hãy tạm công nhận input của người dùng luôn đúng.
// Part 1
let listNumbers = [];
let number = "";
let inputNumbers = prompt("Enter your list number, separated by space:");
let bbb = add(listNumbers);
console.log(bbb);
// for (let index = 0; index < inputNumbers.length; index++) {
// if (inputNumbers[index] !== " ") {
// number += inputNumbers[index];
// } else {
// number = "";
// }
// if (number !== "") {
// listNumbers.push(parseInt(number));
// }
// }
// Phần code tìm giá trị lớn nhất
let maxNumber = -999999;
for (let index = 0; index < listNumbers.length; index++) {
if (listNumbers[index] > maxNumber) {
maxNumber = listNumbers[index];
}
}
console.log(maxNumber);
// Part 2
let sentence = prompt("Enter your sentence, separated by space:");
let sentenceNoSpace = "";
let aaa = add(sentence);
console.log(aaa);
function add(array)
{
let newarray = [];
for(let index=0; index<array.length; index++)
{
if(array[index]!==" ")
{
newarray += array[index];
}
}
return newarray;
}
// Gợi ý:
// - Viết một function nhận vào một parameter là một string bất kỳ
// - Return ra một string không chứa dấu cách<file_sep>/session11DOM/index.js
// const title = document.getElementById('title');
// console.dir(title); // trả về object
// title.innerText = 'DOM'; // update 1 cai key trong object => treen trang web chỉ hiện chữ DOM nhưng bên phần cosole vẫn là dom intro
// // const contentElement = document.getElementsByClassName('content'); //luôn trả về 1 array vì class có thể xuất hiện nhiều lần
// // console.log(contentElement);
// // for (let i=0; i<contentElement.length; i++)
// // {
// // contentElement[i].innerText = 'DOM content';
// // }
// // const tagname = document.getElementsByTagName('p');
// // console.log (tagname); // trả về 1 object
// // đổi màu qua lại mỗi lần click vào thì dùng DOM click, moúeover là rê chuột qua
// title.addEventListener('mouseover',function(){
// // title.style.color = 'red'; //viết css trên javascrip
// if (title.style.color === 'red')
// {
// title.style.color = 'green';
// }
// else {
// title.style.color = 'red';
// }
// })
// key: nextElementSibling sẽ trỏ tới thằng tiếp thep của nó trong html, mún in ra thì là key: innerText
function action (event)
{
const number = Number(event.target.innerText);
event.target.innerText = number +1;
}
const numberElement = document.getElementsByClassName('content');
for (let i=0; i<numberElement.length; i++)
{
numberElement[i].addEventListener('click',action);
}
//tạo ra thẻ html
// khi bấm nút sẽ hiện ra những con số theo lần nhấn chuột
let count = 0;
const button = document.getElementById('button');
button.addEventListener('click',function(event)
{
const container = document.getElementById('container');
container.innerHTML += `<p>` + count +`</p>`;
count +=1;
}); | 9136f578aebcf232055743bca50b85325b0845ea | [
"JavaScript"
] | 14 | JavaScript | ngttt/nguyenthithuytien-c4ejs | fb9dfc286a2ea1fb93bb2a79158c28a613034983 | 4420197619f8840574aece3d68754f89d738a8cf |
refs/heads/master | <repo_name>PadillaTom/SpringBoot-Polotic-TPFinal<file_sep>/src/main/java/com/padillatomas/tpfinal/controller/ReservaController.java
package com.padillatomas.tpfinal.controller;
import java.util.List;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.padillatomas.tpfinal.model.Reserva;
import com.padillatomas.tpfinal.service.ReservaService;
@CrossOrigin(origins = {"http://localhost:3000","https://tpfinal-polotic.netlify.app"}, allowedHeaders = "*")
@RestController
@RequestMapping("/api/reservas")
public class ReservaController {
// Service
private ReservaService reservaService;
// Constructor:
public ReservaController(ReservaService reservaService) {
super();
this.reservaService = reservaService;
}
// ::: POST Reservas :::
@PostMapping
public ResponseEntity<Reserva> altaRes(@RequestBody Reserva reserva){
String myResultado = reservaService.verifReserva(reserva);
if(myResultado.equals("no")) {
return null;
} else if (myResultado.equals("yes")) {
return new ResponseEntity<Reserva> (reservaService.altaReserva(reserva), HttpStatus.CREATED);
}
else return null;
}
/// ::: GET Reservas :::
@GetMapping
public List<Reserva> fetchAllReservas(){
return reservaService.traerAllReservas();
}
}
<file_sep>/src/main/java/com/padillatomas/tpfinal/repository/HabitacionRepository.java
package com.padillatomas.tpfinal.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.padillatomas.tpfinal.model.Habitacion;
public interface HabitacionRepository extends JpaRepository<Habitacion, Long> {
Habitacion findByTipoHabitacion(String tipoHabitacion);
}
<file_sep>/src/main/java/com/padillatomas/tpfinal/repository/ReservaRepository.java
package com.padillatomas.tpfinal.repository;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.padillatomas.tpfinal.model.Reserva;
public interface ReservaRepository extends JpaRepository<Reserva, Long> {
// Last Reserva:
@Query(value ="select * from reservas ORDER BY reserva_id DESC LIMIT 1", nativeQuery = true)
Reserva lastItem();
// Por Dni:
List<Reserva> findByResUsuarioUsuEmpleadoDniEmpleado(String dni);
List<Reserva> findByResHuespedDniHuesped(String dni);
// Por Tipo Habitacion:
List<Reserva> findByResHabitacionTipoHabitacion(String tipo);
// Por Fecha de Carga:
List<Reserva> findByFechaDeCarga(Date fecha);
}
<file_sep>/src/main/java/com/padillatomas/tpfinal/service/ReservaService.java
package com.padillatomas.tpfinal.service;
import java.util.List;
import com.padillatomas.tpfinal.model.Reserva;
public interface ReservaService {
// Post :
String verifReserva(Reserva reserva);
Reserva altaReserva(Reserva reserva);
// Fetch All:
List<Reserva> traerAllReservas();
// Fetch Last:
Reserva traerLastReserva();
}
<file_sep>/src/main/java/com/padillatomas/tpfinal/model/Empleado.java
package com.padillatomas.tpfinal.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name="empleados")
public class Empleado {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long empleadoId;
@Column(name = "dni_empleado")
private String dniEmpleado;
@Column(name = "nombre_empleado")
private String nombreEmpleado;
@Column(name = "apellido_empleado")
private String apellidoEmpleado;
@Column(name = "fecha_nac_empleado")
@Temporal(TemporalType.DATE)
private Date fechaNacEmpleado;
@Column(name = "direccion_empleado")
private String direccionEmpleado;
@Column(name = "cargo_empleado")
private String cargoEmpleado;
public Empleado() {};
public Empleado(String dniEmpleado, String apellidoEmpleado, Date fechaNacEmpleado, String direccionEmpleado,
String cargoEmpleado) {
super();
this.dniEmpleado = dniEmpleado;
this.apellidoEmpleado = apellidoEmpleado;
this.fechaNacEmpleado = fechaNacEmpleado;
this.direccionEmpleado = direccionEmpleado;
this.cargoEmpleado = cargoEmpleado;
}
public Long getEmpleadoId() {
return empleadoId;
}
public void setEmpleadoId(Long empleadoId) {
this.empleadoId = empleadoId;
}
public String getDniEmpleado() {
return dniEmpleado;
}
public void setDniEmpleado(String dniEmpleado) {
this.dniEmpleado = dniEmpleado;
}
public String getNombreEmpleado() {
return nombreEmpleado;
}
public void setNombreEmpleado(String nombreEmpleado) {
this.nombreEmpleado = nombreEmpleado;
}
public String getApellidoEmpleado() {
return apellidoEmpleado;
}
public void setApellidoEmpleado(String apellidoEmpleado) {
this.apellidoEmpleado = apellidoEmpleado;
}
public Date getFechaNacEmpleado() {
return fechaNacEmpleado;
}
public void setFechaNacEmpleado(Date fechaNacEmpleado) {
this.fechaNacEmpleado = fechaNacEmpleado;
}
public String getDireccionEmpleado() {
return direccionEmpleado;
}
public void setDireccionEmpleado(String direccionEmpleado) {
this.direccionEmpleado = direccionEmpleado;
}
public String getCargoEmpleado() {
return cargoEmpleado;
}
public void setCargoEmpleado(String cargoEmpleado) {
this.cargoEmpleado = cargoEmpleado;
}
}
<file_sep>/src/main/java/com/padillatomas/tpfinal/model/Habitacion.java
package com.padillatomas.tpfinal.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="habitaciones")
public class Habitacion {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long habitacionId;
@Column(name="piso_habitacion")
private int pisoHabitacion;
@Column(name="nombre_habitacion")
private String nombreHabitacion;
@Column(name="tipo_habitacion")
private String tipoHabitacion;
@Column(name="precio_noche_habitacion")
private double precioNocheHabitacion;
@OneToMany(cascade = CascadeType.ALL)
private List<Reserva> habReserva = new ArrayList<>();
public Habitacion() {
}
public Habitacion(int pisoHabitacion, String nombreHabitacion, String tipoHabitacion,
double precioNocheHabitacion) {
super();
this.pisoHabitacion = pisoHabitacion;
this.nombreHabitacion = nombreHabitacion;
this.tipoHabitacion = tipoHabitacion;
this.precioNocheHabitacion = precioNocheHabitacion;
}
public Long getHabitacionId() {
return habitacionId;
}
public void setHabitacionId(Long habitacionId) {
this.habitacionId = habitacionId;
}
public int getPisoHabitacion() {
return pisoHabitacion;
}
public void setPisoHabitacion(int pisoHabitacion) {
this.pisoHabitacion = pisoHabitacion;
}
public String getNombreHabitacion() {
return nombreHabitacion;
}
public void setNombreHabitacion(String nombreHabitacion) {
this.nombreHabitacion = nombreHabitacion;
}
public String getTipoHabitacion() {
return tipoHabitacion;
}
public void setTipoHabitacion(String tipoHabitacion) {
this.tipoHabitacion = tipoHabitacion;
}
public double getPrecioNocheHabitacion() {
return precioNocheHabitacion;
}
public void setPrecioNocheHabitacion(double precioNocheHabitacion) {
this.precioNocheHabitacion = precioNocheHabitacion;
}
public List<Reserva> getHabReserva() {
return habReserva;
}
public void setHabReserva(List<Reserva> habReserva) {
this.habReserva = habReserva;
}
}
<file_sep>/src/main/java/com/padillatomas/tpfinal/controller/ConsultaHuespedesYresEmp.java
package com.padillatomas.tpfinal.controller;
import java.util.List;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.padillatomas.tpfinal.model.Empleado;
import com.padillatomas.tpfinal.model.Huesped;
import com.padillatomas.tpfinal.model.Reserva;
import com.padillatomas.tpfinal.service.ConsultasService;
@CrossOrigin(origins = {"http://localhost:3000","https://tpfinal-polotic.netlify.app"}, allowedHeaders = "*")
@RestController
@RequestMapping("/api/consultaResPorDni")
public class ConsultaHuespedesYresEmp {
private ConsultasService consServ;
public ConsultaHuespedesYresEmp(ConsultasService consServ) {
super();
this.consServ = consServ;
}
// ::: GET Reservas :::
@PostMapping
public List<Reserva> traerResPorEmp(@RequestBody Empleado emple){
return consServ.traerResPorEmp(emple);
}
@GetMapping
public List<Huesped> traerHuespedes(){
return consServ.traerAllHuesped();
}
}
<file_sep>/src/main/java/com/padillatomas/tpfinal/service/UsuarioService.java
package com.padillatomas.tpfinal.service;
import java.util.List;
import com.padillatomas.tpfinal.model.Usuario;
public interface UsuarioService {
// Create USUARIO:
Usuario saveUsuario(Usuario usuario);
// Fetch by Id:
Usuario fetchById(Long id);
// Fetch ALL USUARIOS:
List<Usuario> fetchUsuarios();
//Borrar Usuario:
void eliminarUsu(Usuario usu);
// Edit Usuario:
Usuario editUsuario(Usuario usu, Long id );
}<file_sep>/src/main/java/com/padillatomas/tpfinal/model/Huesped.java
package com.padillatomas.tpfinal.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name = "huespedes")
public class Huesped {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long huespedId;
@Column(name="dni_huesped")
private String dniHuesped;
@Column(name="nombre_huesped")
private String nombreHuesped;
@Column(name="apellido_huesped")
private String apellidoHuesped;
@Column(name="fecha_nac_huesped")
@Temporal(TemporalType.DATE)
private Date fechaNacHuesped;
@Column(name="direccion_huesped")
private String direccionHuesped;
@Column(name="profesion_huesped")
private String profesionHuesped;
@OneToMany(cascade = CascadeType.ALL)
private List<Reserva> huesReserva = new ArrayList<>();
public Huesped() {}
public Huesped(String dniHuesped, String nombreHuesped, String apellidoHuesped, Date fechaNacHuesped,
String direccionHuesped, String profesionHuesped) {
super();
this.dniHuesped = dniHuesped;
this.nombreHuesped = nombreHuesped;
this.apellidoHuesped = apellidoHuesped;
this.fechaNacHuesped = fechaNacHuesped;
this.direccionHuesped = direccionHuesped;
this.profesionHuesped = profesionHuesped;
}
public Long getHuespedId() {
return huespedId;
}
public void setHuespedId(Long huespedId) {
this.huespedId = huespedId;
}
public String getDniHuesped() {
return dniHuesped;
}
public void setDniHuesped(String dniHuesped) {
this.dniHuesped = dniHuesped;
}
public String getNombreHuesped() {
return nombreHuesped;
}
public void setNombreHuesped(String nombreHuesped) {
this.nombreHuesped = nombreHuesped;
}
public String getApellidoHuesped() {
return apellidoHuesped;
}
public void setApellidoHuesped(String apellidoHuesped) {
this.apellidoHuesped = apellidoHuesped;
}
public Date getFechaNacHuesped() {
return fechaNacHuesped;
}
public void setFechaNacHuesped(Date fechaNacHuesped) {
this.fechaNacHuesped = fechaNacHuesped;
}
public String getDireccionHuesped() {
return direccionHuesped;
}
public void setDireccionHuesped(String direccionHuesped) {
this.direccionHuesped = direccionHuesped;
}
public String getProfesionHuesped() {
return profesionHuesped;
}
public void setProfesionHuesped(String profesionHuesped) {
this.profesionHuesped = profesionHuesped;
}
public List<Reserva> getHuesReserva() {
return huesReserva;
}
public void setHuesReserva(List<Reserva> huesReserva) {
this.huesReserva = huesReserva;
}
}
<file_sep>/src/main/java/com/padillatomas/tpfinal/repository/HuespedRepository.java
package com.padillatomas.tpfinal.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.padillatomas.tpfinal.model.Huesped;
public interface HuespedRepository extends JpaRepository<Huesped, Long> {
Huesped findByDniHuesped(String dniHuesped);
}
| 2237d2dea2ea72f1cc3b2235323c6ec70f821d6b | [
"Java"
] | 10 | Java | PadillaTom/SpringBoot-Polotic-TPFinal | 39b7987539667ef500b25edd5b55ac23e7f8c0ef | e947589fe823637f2f8d5b1934caaa0aad722283 |
refs/heads/master | <repo_name>zavsc/eschool<file_sep>/application/views/errorview.php
<div class="container">
<?php if(isset($error)) {?>
<div class="alert alert-danger" role="alert"><?php echo $error; ?></div>
<?php }?>
<span id="show-timetable" onclick="location.href='<?php echo base_url();?>';" class="a-block"
title="На главную">На главную страницу</span>
</div><file_sep>/application/models/apimodel.php
<?php
class Apimodel extends CI_Model {
function getTimetable($class_id, $day) {
$query = $this->db->query("SELECT sc.SUBJECTS_CLASS_ID, r.ROOM_NAME, s.SUBJECT_NAME, tm.TIME_START, tm.TIME_FINISH, t.TIME_ID
FROM TIMETABLE t JOIN SUBJECTS_CLASS sc ON t.SUBJECTS_CLASS_ID = sc.SUBJECTS_CLASS_ID
JOIN SUBJECT s ON s.SUBJECT_ID = sc.SUBJECT_ID
JOIN ROOM r ON r.ROOM_ID = t.ROOM_ID
JOIN TIME tm ON tm.TIME_ID = t.TIME_ID
WHERE t.DAYOFWEEK_ID = '".$day."' AND sc.CLASS_ID = '".$class_id."'
UNION
SELECT sc.SUBJECTS_CLASS_ID, ROOM_ID, s.SUBJECT_NAME, tm.TIME_START, tm.TIME_FINISH, t.TIME_ID
FROM TIMETABLE t JOIN SUBJECTS_CLASS sc ON t.SUBJECTS_CLASS_ID = sc.SUBJECTS_CLASS_ID
JOIN SUBJECT s ON s.SUBJECT_ID = sc.SUBJECT_ID
JOIN TIME tm ON tm.TIME_ID = t.TIME_ID
WHERE t.DAYOFWEEK_ID = '".$day."' AND sc.CLASS_ID = '".$class_id."' AND ROOM_ID IS NULL
ORDER BY 4");
return $query->result_array();
}
function getMarks($subject, $current, $id, $time) {
$query = $this->db->query("SELECT ACHIEVEMENT_MARK
FROM ACHIEVEMENT a JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID
WHERE LESSON_DATE = '$current' AND PUPIL_ID = '$id' AND SUBJECTS_CLASS_ID = '$subject' AND TIME_ID = '$time'");
return $query->result_array();
}
function getBorders($class_id, $current) {
$query = $this->db->query("SELECT * FROM PERIOD
WHERE YEAR_ID = (SELECT c.YEAR_ID
FROM YEAR y JOIN CLASS c ON c.YEAR_ID = y.YEAR_ID
WHERE CLASS_ID = '$class_id') AND '$current' >= PERIOD_START AND '$current' <= PERIOD_FINISH");
return $query->row_array();
}
function getAverageMark($start, $current, $class_id, $pupil, $subject) {
$query = $this->db->query("SELECT AVG(ACHIEVEMENT_MARK) AS MARK
FROM ACHIEVEMENT a JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID JOIN SUBJECTS_CLASS sc
ON sc.SUBJECTS_CLASS_ID = l.SUBJECTS_CLASS_ID
WHERE l.SUBJECTS_CLASS_ID = '$subject' AND LESSON_DATE >= '$start'
AND LESSON_DATE <= '$current' AND CLASS_ID = '$class_id' AND PUPIL_ID = '$pupil'
GROUP BY PUPIL_ID");
return $query->row_array();
}
function getPupils($class_id) {
$query = $this->db->query("SELECT p.PUPIL_ID, PUPIL_NAME
FROM PUPIL p JOIN PUPILS_CLASS pc ON p.PUPIL_ID = pc.PUPIL_ID
WHERE CLASS_ID = '$class_id' ORDER BY PUPIL_NAME");
return $query->result_array();
}
function getPasses($pupil_id, $subject, $period, $pass) {
$query = $this->db->query("SELECT COUNT(ATTENDANCE_PASS) AS COUNT
FROM ATTENDANCE a JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID
WHERE PUPIL_ID = '$pupil_id' AND SUBJECTS_CLASS_ID = '$subject' AND ATTENDANCE_PASS = '$pass' AND
LESSON_DATE >= (SELECT PERIOD_START FROM PERIOD WHERE PERIOD_ID = '$period') AND
LESSON_DATE <= (SELECT PERIOD_FINISH FROM PERIOD WHERE PERIOD_ID = '$period')");
return $query->row_array();
}
function getAllPasses($pupil_id, $period, $pass) {
$query = $this->db->query("SELECT COUNT(ATTENDANCE_PASS) AS COUNT
FROM ATTENDANCE a JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID
WHERE PUPIL_ID = '$pupil_id' AND ATTENDANCE_PASS = '$pass' AND
LESSON_DATE >= (SELECT PERIOD_START FROM PERIOD WHERE PERIOD_ID = '$period') AND
LESSON_DATE <= (SELECT PERIOD_FINISH FROM PERIOD WHERE PERIOD_ID = '$period')");
return $query->row_array();
}
}
?><file_sep>/application/views/authview.php
<!DOCTYPE html>
<html lang = "ru">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="shortcut icon" href="images/school-new2.png">
<title>Электронный дневник учащегося</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="bootstrap/js/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<link href="css/singin.css" rel="stylesheet">
</head>
<body>
<div class="bs-docs-header">
<div class="container">
<h1 style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif;"><strong>Электронный дневник учащегося</strong></h1>
<p>Электронный дневник учащегося — это уникальная разработка, создающая единое информационное пространство, которое объединяет всех участников образовательного процесса</p>
<form class="form-signin" method="POST" action="auth">
<input name="login" type="login" class="form-control" placeholder="Логин" required autofocus>
<input name="password" type="<PASSWORD>" class="form-control" placeholder="Пароль" required>
<?php
if (isset($error)) {?>
<!--alert-->
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong>Ошибка!</strong> <?php echo $error;?>
</div>
<!--alert-->
<?php }?>
<button name="singin" class="btn btn-lg btn-block btn-sample" type="submit">Авторизоваться</button>
</form>
</div>
</div>
</body>
</html><file_sep>/application/views/pupil/marksview.php
<?php
function setColor($mark, $tooltip) {
switch ($mark) {
case 5: echo '<span data-toggle="tooltip" data-placement="top" title="'.$tooltip.'" class="label label-success">'.$mark.'</span>'; break;
case 4: echo '<span data-toggle="tooltip" data-placement="top" title="'.$tooltip.'" class="label label-warning">'.$mark.'</span>'; break;
case 3: echo '<span data-toggle="tooltip" data-placement="top" title="'.$tooltip.'" class="label label-primary">'.$mark.'</span>'; break;
case 2: echo '<span data-toggle="tooltip" data-placement="top" title="'.$tooltip.'" class="label label-danger">'.$mark.'</span>'; break;
}
}
?>
<div class="container">
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-4">
<form method="post">
<label for="class" class="control-label"><i class="fa fa-clock-o"></i> Год</label>
<select id="class" name="class" onchange="this.form.submit();" style="width: 70%;">
<?php
foreach ($classes as $class) {
?>
<option value="<?php echo $class['CLASS_ID'];?>"><?php echo $class['YEAR_START']." - ".$class['YEAR_FINISH']." гг."; ?></option><?php
}
?>
</select>
</form>
</div>
<div class="col-md-8">
<form method="post">
<label for="period" class="control-label"><i class="fa fa-calendar"></i> Период</label>
<select id="period" name="period" onchange="this.form.submit();" style="width: 30%;" >
<?php
foreach ($periods as $period) {
?>
<option value="<?php echo $period['PERIOD_ID'];?>"><?php echo $period['PERIOD_NAME']; ?></option><?php
}
?>
</select>
</form>
</div>
</div>
<div class="row">
<div class="col-md-8">
<h3 class="sidebar-header">Оценки и пропуски</h3>
</div>
<div class="col-md-4" >
<h5><span onclick="print();" class="a-block pull-right" title="Печать"><i class="fa fa-print"></i> Печать</span></h5>
</div>
</div>
<div class="panel panel-default">
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered numeric">
<thead>
<tr>
<th rowspan="2">#</th>
<th class="col-md-2" rowspan="2">Предмет</th>
<th rowspan="2">Оценки</th>
<th colspan="3" style=" text-align: center;">Пропуски</th>
</tr>
<tr>
<th style="width: 10%; border-bottom-width: 1px;">по болезни</th>
<th style="width: 10%; border-bottom-width: 1px;">по неуваж.</br>причине</th>
<th style="width: 10%; border-bottom-width: 1px;">по уваж.</br>причине</th>
</tr>
</thead>
<tbody>
<?php
for($i = 0; $i < count($progress); $i++) {
?>
<tr>
<td><?php echo $i+1; ?></td>
<td><?php echo $progress[$i]["subject"]; ?></td>
<td>
<?php
for ($y =0; $y < count($progress[$i]["marks"]); $y++) {
setColor($progress[$i]["marks"][$y]["mark"], $progress[$i]["marks"][$y]["type"]);
echo " ";
}
?>
</td>
<td><?php if(isset($progress[$i]["pass"]['б'])) echo "<strong>".$progress[$i]["pass"]['б']."</strong>"; else echo "<span class='grey'>н/д</span>"; ?></td>
<td><?php if(isset($progress[$i]["pass"]['н'])) echo "<strong>".$progress[$i]["pass"]['н']."</strong>"; else echo "<span class='grey'>н/д</span>"; ?></td>
<td><?php if(isset($progress[$i]["pass"]['у'])) echo "<strong>".$progress[$i]["pass"]['у']."</strong>"; else echo "<span class='grey'>н/д</span>"; ?></td>
</tr>
<?php
} ?>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
document.getElementById('class').value = "<?php echo $this->uri->segment(3);?>";
$("#class").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
document.getElementById('period').value = "<?php echo $this->uri->segment(4);?>";
$("#period").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
</script><file_sep>/application/views/pupil/sidebarview.php
<?php
function showDate($date) {
$day = date('d', strtotime($date));
$mounth = date('m', strtotime($date));
$year = date('Y', strtotime($date));
$data = array('01'=>'Январь','02'=>'Февраль','03'=>'Март','04'=>'Апрель','05'=>'Май','06'=>'Июнь',
'07'=>'Июль', '08'=>'Август','09'=>'Сентябрь','10'=>'Октябрь','11'=>'Ноябрь','12'=>'Декабрь');
foreach ($data as $key=>$value) {
if ($key==$mounth) echo "$value ".ltrim($day, '0').", $year";
}
}
?>
<div class="container">
<div class="row">
<div class="col-md-4">
<h3 class="sidebar-header"><i class="fa fa-clock-o"></i> <?php showDate(date('Y-m-d'));?></h3>
<div class="panel panel-default">
<div class="table-responsive">
<table name="timetable" class="table table-striped">
<thead>
<tr>
<th>Время</th>
<th>Предмет</th>
<th>Каб.</th>
</tr>
</thead>
<tbody>
<?php
for ($k=0; $k < count($timetable); $k++) {
?>
<tr>
<td id="time"><?php echo date("H:i", strtotime($timetable[$k]["start"]));?></td>
<td><?php echo $timetable[$k]["name"];?></td>
<td id="room"><?php echo $timetable[$k]["room"]; }?></td>
</tr>
</tbody>
</table>
</div>
<div class="panel-body">
<span id="show-timetable" onclick="location.href='<?php echo base_url();?>pupil/timetable';" class="a-block"
title="Показать расписание">Смотреть расписание на всю неделю</span>
</div>
</div>
<h3 class="sidebar-header"><i class="fa fa-bar-chart"></i> Средний балл по предметами на сегодня</h3>
<div class="panel panel-default" id="todayaverages">
<div class="panel-body">
<div><canvas id="myChart1" hidden="true" style="width: 200px; height: 200px;" ></canvas></div>
<span id="no-data1" style="display: block; text-align: center;"></span>
<span onclick="location.href='<?php echo base_url();?>pupil/statistics';" class="a-block" title="Перейти в статистику">Перейти в статистику</a>
</div>
</div>
<h3 class="sidebar-header"><i class="fa fa-pie-chart"></i> Полученные сегодня оценки</h3>
<div class="panel panel-default" id="todaymarks">
<div class="panel-body">
<div><canvas id="myChart" hidden="true" ></canvas></div>
<span id="no-data" style="display: block; text-align: center;"></span>
<span onclick="location.href='<?php echo base_url();?>pupil/diary';" class="a-block" title="Перейти в дневник">Перейти в дневник</span>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
var marks = document.getElementById("myChart").getContext("2d");
var base_url = '<?php echo base_url();?>';
$.ajax({
type: "POST",
url: base_url + "api/todaymarks" ,
cache: false,
success: function(data){
//alert(data);
if(JSON.parse(data) == null || JSON.parse(data) == 'error') {
$('#myChart').attr('hidden', true);
$('#no-data').text("Нет данных");
} else {
$('#myChart').attr('hidden', false);
$('#no-data').text("");
var data = JSON.parse(data);
var data = [
{
value: data[5],
color:"#5cb85c",
label: "Кол-во пятерок"
},
{
value: data[4],
color: "#ec971f",
label: "Кол-во четверок"
},
{
value: data[3],
color: "#337ab7",
label: "Кол-во троек"
},
{
value: data[2],
color: "#d9534f",
label: "Кол-во двоек"
}
];
var options = {
animation: false,
responsive: true,
maintainAspectRatio: true
};
new Chart(marks).Pie(data, options);
}
}
});
var averages = document.getElementById("myChart1").getContext("2d");
$.ajax({
type: "POST",
url: base_url + "api/todayaverages" ,
cache: false,
success: function(data){
if(JSON.parse(data) == null || JSON.parse(data) == 'error') {
$('#myChart1').attr('hidden', true);
$('#no-data1').text("Нет данных");
} else {
$('#myChart1').attr('hidden', false);
$('#no-data1').text("");
var data = JSON.parse(data);
var description = new Array();
var myvalues = new Array();
for (i = 1; i <= Object.keys(data).length; i++) {
//alert(Object.keys(data).length);
//alert(data[i].subject);
description.push(data[i].subject);
myvalues.push(data[i].mark);
//alert(data[i].mark);
}
var step = 1;
var max = 5;
var start = 0;
var options = {
animation: false,
responsive: true,
maintainAspectRatio: true/*,
scaleOverride: true,
scaleSteps: Math.ceil((max-start)/step),
scaleStepWidth: step,
scaleStartValue: start*/
};
var data = {
labels: description,
datasets: [
{
label: "Средние баллы",
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
data: myvalues
},
]};
window.myObjBar = new Chart(averages).Bar(data, options);
for(i = 0; i < myvalues.length; i++) {
if (myvalues[i] >= 4.5) {
myObjBar.datasets[0].bars[i].fillColor = "#5cb85c";
}
if (myvalues[i] < 4.5 && myvalues[i] >= 3.5){
myObjBar.datasets[0].bars[i].fillColor = "#ec971f";
}
if(myvalues[i] < 3.5 && myvalues[i] >= 2.5) {
myObjBar.datasets[0].bars[i].fillColor = "#337ab7";
}
if(myvalues[i] < 2.5 && myvalues[i] > 0) {
myObjBar.datasets[0].bars[i].fillColor = "#d9534f";
}
if (myvalues[i] = 0) {
myObjBar.datasets[0].bars[i].fillColor = "grey";
}
}
myObjBar.update();
}
}
});
});
</script>
<file_sep>/application/views/blankview/blankpupilview.php
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><?php echo $title; ?></div>
<div class="panel-body">
<form method="post">
<div hidden="true" id="id"><?php if(isset($id)) echo $id;?></div>
<div class="form-horizontal">
<div class="form-group">
<label for="inputName" class="col-sm-2 col-md-2 control-label">ФИО учащегося <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<input type="text" class="form-control" id="inputName" name="inputName" placeholder="ФИО учащегося" required="true" maxlength="100" autofocus value="<?php if(isset($name)) echo $name;?>">
</div>
</div>
<div class="form-group">
<label for="inputLogin" class="col-sm-2 col-md-2 control-label">Логин <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<input type="text" class="form-control" id="inputLogin" name="inputLogin" placeholder="Логин" required="true" maxlength="20" value="<?php if(isset($login)) echo $login;?>">
<div class="red" id="responseLoginError"></div>
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-sm-2 col-md-2 control-label">Пароль <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<span class="passEye"><input type="<PASSWORD>" class="form-control" id="inputPassword" name="inputPassword" placeholder="<PASSWORD>" required="true" maxlength="20" value="<?php if(isset($password)) echo $password;?>">
</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-md-2 control-label">Статус <span class="star">*</span></label>
<div class="col-sm-offset-2 col-sm-10" style="margin-top: -27.5px;">
<label class="radio-inline">
<input type="radio" name="inputStatus" value="1" <?php if(isset($status) && $status == 1) { echo "checked='checked'";} else echo "checked='checked'"; ?> >Активен
</label>
<label class="radio-inline">
<input type="radio" name="inputStatus" value="0" <?php if(isset($status) && $status == 0) { echo "checked='checked'";}?>>Не активен
</label>
</div>
</div>
<!--<label>Статус *</label>
<div class="radio" style="margin-top: 0px;">
<input type="radio" name="inputStatus" value="1" <?php if(isset($status) && $status == 1) { echo "checked='checked'";} else echo "checked='checked'"; ?> >Активен<br/>
<input type="radio" name="inputStatus" value="0" <?php if(isset($status) && $status == 0) { echo "checked='checked'";}?>>Не активен
</div>-->
<div class="form-group">
<label for="inputPhone" class="col-sm-2 col-md-2 control-label">Телефон</label>
<div class="col-sm-10 col-md-10">
<input type="tel" class="form-control" id="inputPhone" name="inputPhone" placeholder="8 (###) ###-##-##" name="inputPhone" maxlength="20" value="<?php if(isset($phone)) echo $phone;?>">
</div>
</div>
<div class="form-group">
<label for="inputBirthday" class="col-sm-2 col-md-2 control-label">Дата рождения</label>
<div class="col-sm-10 col-md-10">
<input type="text" class="form-control" id="inputBirthday" name="inputBirthday" placeholder="гггг-мм-дд" value="<?php if(isset($birthday)) echo $birthday;?>">
</div>
</div>
<div class="form-group">
<label for="inputAddress" class="col-sm-2 col-md-2 control-label">Домашний адрес</label>
<div class="col-sm-10 col-md-10">
<textarea style="resize: vertical;" class="form-control" rows="2" maxlength="200" id ="inputAddress" name="inputAddress" placeholder="Домашний адрес"><?php if(isset($address)) echo $address;?></textarea>
<div class="textareaFeedback"></div>
</div>
</div>
</div>
<div class="grey">* - Обязательные поля</div>
<div id="error" class="red"></div>
<div class="modal-footer" style="margin-bottom: -15px; padding-right: 0px;">
<button type="button" class="btn btn-default" onclick="javascript:history.back();" title="Отменить">Отменить</button>
<button type="submit" class="btn btn-sample" name="save" id="save" title="Сохранить">Сохранить</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#inputPhone").mask("8 (999) 999-99-99");
$("#inputBirthday").mask("9999-99-99");
$('#inputBirthday').datepicker({
format: 'yyyy-mm-dd',
startDate: "1980-01-01",
language: "ru",
todayBtn: "linked",
autoclose: true,
todayHighlight: true,
clearBtn: true,
immediateUpdates: true
});
$('#save').click(function() {
var base_url = '<?php echo base_url();?>';
var s = 0;
var error = 0;
var name = $.trim($('#inputName').val());
var password = $.trim($('#inputPassword').val());
var login = $.trim($('#inputLogin').val());
var status = $("input[name='inputStatus']:checked").val();
var phone = $("#inputPhone").val();
var address = $.trim($("#inputAddress").val());
var birthday = $("#inputBirthday").val();
var id = $('#id').text();
if (name.length == 0) {
$('#inputName').parent().addClass("has-error");
s++;
} else {
$('#inputName').parent().removeClass("has-error");
}
if (password.length == 0) {
$('#inputPassword').parent().addClass("has-error");
s++;
} else {
$('#inputPassword').parent().removeClass("has-error");
}
if (login.length == 0) {
$('#inputLogin').parent().addClass("has-error");
$("#responseLoginError").text('');
s++;
} else {
$('#inputLogin').parent().removeClass("has-error");
$.ajax({
type: "POST",
url: base_url + "table/responsepupillogin",
data: "login=" + login + "&id=" + id,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
if (response == true) {
$("#responseLoginError").text('Логин должен быть уникальным');
$('#inputLogin').parent().addClass("has-error");
error++;
}
if (response == false) {
$("#responseLoginError").text('');
$('#inputLogin').parent().removeClass("has-error");
}
}
});
}
if (s != 0) {
$("#error").text('Не все обязательные поля заполнены');
}
else {
$("#error").text('');
}
//alert(s + " " + error);
if (s == 0 && error == 0) {
/*if (id == "") {
$.ajax({
type: "POST",
url: base_url + "table/addpupil",
data: "name=" + name + "&login=" + login + "&password=" + <PASSWORD> + "&status=" + status + "&phone=" + phone + "&birthday=" + birthday + "&address=" + address,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
document.location.href = base_url + 'teacher/pupils';
}
});
}
else {
$.ajax({
type: "POST",
url: base_url + "table/updatepupil",
data: "name=" + name + "&login=" + login + "&password=" + <PASSWORD> + "&status=" + status + "&phone=" + phone + "&address=" + address + "&birthday=" + birthday + "&id=" + id ,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
document.location.href = base_url + 'teacher/pupils';
}
});
}*/
} else return false;
});
});
</script>
<file_sep>/application/views/message/conversationsview.php
<?php
function showDate($date) {
$day = date('d', strtotime($date));
$mounth = date('m', strtotime($date));
$year = date('Y', strtotime($date));
$hours = date('H', strtotime($date));
$minutes = date('i', strtotime($date));
$data = array('01'=>'января','02'=>'февраля','03'=>'марта','04'=>'апреля','05'=>'мая','06'=>'июня',
'07'=>'июля', '08'=>'августа','09'=>'сентября','10'=>'октября','11'=>'ноября','12'=>'декабря');
$today_year = date('Y');
$today_day = date('d');
foreach ($data as $key=>$value) {
if ($key==$mounth) {
if ($year < $today_year) {
echo ltrim($day, '0')." $value $year года";
} else {
if ($day != $today_day) {
echo ltrim($day, '0')." $value"." в ".$hours.":".$minutes;
}
else {
echo "в ".$hours.":".$minutes;
}
}
}
}
}
?>
<div class="container">
<h3 class="sidebar-header"><i class="fa fa-envelope-o"></i> Общение</h3>
<div class="panel panel-default panel-table">
<div class="panel-body">
<button type="button" class="btn btn-menu" id="writeButton" title="Написать сообщение"><i class="fa fa-plus fa-2x"></i></i>
</br><span class="menu-item">Написать</span>
</button>
<button type="button" class="btn btn-menu disabled" id="readButton" title="Отметить прочитано"><i class="fa fa-check-square-o fa-2x"></i>
</br><span class="menu-item">Прочитано</span>
</button>
<button type="button" class="btn btn-menu disabled" id="deleteButton" data-toggle="modal" data-target="#myModal" title="Удалить переписку"><i class="fa fa-trash-o fa-2x"></i>
</br><span class="menu-item">Удалить</span>
</button>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<form method="get">
<div class="input-group">
<input type="text" class="form-control" placeholder="Поиск по собеседникам" id="search" name="search" value="<?php if(isset($search)) echo $search;?>" >
<span class="input-group-btn">
<button class="btn btn-default" type="submit" name="submit" id="searchButton" title="Поиск"><i class="fa fa-search"></i></button>
</span>
</div><!-- /input-group -->
</form>
</div>
<div class="table-responsive">
<table name="timetable" class="table table-striped table-hover numeric">
<thead>
<tr>
<th><input type="checkbox" id="all"></th>
<th>Собеседник</th>
<th style="text-align: center; width: 20%;">Сообщений</th>
<th style="text-align: center; width: 20%;">Новых</th>
</tr>
</thead>
<tbody>
<?php if(is_array($messages) && count($messages) ) {
$i = 0;
foreach($messages as $message){ ?>
<tr style="cursor: pointer; cursor: hand;">
<td><input type="checkbox" name="users[]" value="<?php echo $message['USER_ID']; ?>"</td>
<td><?php echo $message['USER_NAME']; ?></br>
<span style="font-size: 12px; color: grey; font-style: italic;">Последнее сообщение
<?php showDate($message['MAX']); ?></span></td>
<td style="vertical-align: middle; text-align: center;"><?php echo $message['COUNT']; ?></td>
<td style="vertical-align: middle; text-align: center;"><?php if(isset($result[$i]["new"])) {?><span class="green"><?php echo $result[$i]["new"];?></span><?php } else echo "-"; ?></td>
</tr>
<?php $i++; }
} ?>
</tbody>
</table>
</div>
</div>
<?php echo $this->pagination->create_links(); ?>
<?php
if(count($messages) == 0 && isset($search) && $search != "") {
?>
<div class="alert alert-info" role="alert">Поиск не дал результатов. Попробуйте другой запрос</div>
<?php } ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#all").change(function(){
$("input[name='users[]']").prop('checked', this.checked);
if(this.checked == true) {
$('#deleteButton').removeClass('disabled');
$('#readButton').removeClass('disabled');
} else {
$('#deleteButton').addClass('disabled');
$('#readButton').addClass('disabled');
}
});
$('#writeButton').click(function() {
document.location.href = '<?php echo base_url(); ?>messages/message';
});
$('table tbody td input[type=checkbox]').click( function (e) {
var s = 0;
$("input[name='users[]']:checked").each(function () {
s++;
});
if(s != 0) {
$('#deleteButton').removeClass('disabled');
$('#readButton').removeClass('disabled');
} else {
$('#deleteButton').addClass('disabled');
$('#readButton').addClass('disabled');
}
e.stopPropagation();
});
$('#buttonDeleteMessageModal').click(function() {
var base_url = '<?php echo base_url();?>';
var checked = [];
$("input[name='users[]']:checked").each(function () {
checked.push($(this).val());
});
for(var i = 0; i < checked.length; i++ ) {
$.ajax({
type: "POST",
url: base_url + "table/del/conversation/" + checked[i],
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(a) {
//alert(a);
}
});
}
location.reload();
});
$('#readButton').click(function() {
var base_url = '<?php echo base_url();?>';
var checked = [];
$("input[name='users[]']:checked").each(function () {
checked.push($(this).val());
});
for(var i = 0; i < checked.length; i++ ) {
$.ajax({
type: "POST",
url: base_url + "table/readconversation/" + checked[i],
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(a) {
//alert(a);
}
});
}
location.reload();
});
$("tr:not(:first)").click(function(e) {
var base_url = '<?php echo base_url();?>';
var id = $(this).children("td").find("input[name='users[]']").val();
/*$.ajax({
type: "POST",
url: base_url + "table/readconversation/" + id,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(a) {
//alert(a);
}
});*/
window.location.href = '<?php echo base_url(); ?>messages/conversation/'+ id;
});
});
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Удаление переписок</h4>
</div>
<div class="modal-body">
<p>Вы уверены, что хотите удалить эти переписки?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-sample" id="buttonDeleteMessageModal">Удалить</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal --><file_sep>/README.md
# ESCHOOL
Информационная система "Электронный дневник и журнал"
## Установка
1. Создать базу MySQL eschool
2. Выполнить скрипт (script.sql)
3. Добавить в таблицу role роли
```
INSERT INTO `role` VALUES (1,'Классный руководитель'),(2,'Администратор'),(3,'Учитель'),(4,'Учащийся');
```
4. Добавить в таблицу teacher администратора
```
INSERT INTO `teacher` VALUES (1,'admin','<PASSWORD>','<PASSWORD>',2,'Администратор',1);
```
5. Добавить в таблицу dayofweek дни недели
```
INSERT INTO `dayofweek` VALUES (1,'Понедельник'),(2,'Вторник'),(3,'Среда'),(4,'Четверг'),(5,'Пятница'),(6,'Суббота');
```
6. Добавить в таблицу time расписание звонков
```
INSERT INTO `time` VALUES (1,'08:30:00','09:15:00'),(2,'09:30:00','10:15:00'),(3,'10:25:00','11:10:00'),(4,'11:25:00','12:10:00'),(5,'12:30:00','13:15:00'),(6,'13:25:00','14:10:00'),(7,'14:15:00','15:00:00'),(8,'15:05:00','15:50:00');
```
7. Разместить проект на сервере
8. В файле application/config/database.php прописать подключение к базе данных
9. В файле application/config/config.php настроить $config['base_url']
<file_sep>/application/views/blankview/blanktimetableview.php
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><?php echo $title; ?></div>
<div class="panel-body">
<form method="post">
<div hidden="true" id="id"><?php if(isset($id)) echo $id;?></div>
<div class="form-horizontal">
<div class="form-group">
<label for="inputTime" class="col-sm-2 col-md-2 control-label">Время <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<select id="inputTime" name="inputTime" class="width-select">
<?php
if(isset($times)) {
if($time_id == null && isset($id)) echo "<option value=''></option>";
foreach($times as $time) {
if ($time_id != "") {
if($time['TIME_ID'] == $time_id) {
echo "<option selected='selected' value='".$time['TIME_ID']."'>".date("H:i", strtotime($time["TIME_START"])).' - '
.date("H:i",strtotime($time["TIME_FINISH"]))."</option>";
} else {
echo "<option value='".$time['TIME_ID']."'>".date("H:i", strtotime($time["TIME_START"])).' - '
.date("H:i",strtotime($time["TIME_FINISH"]))."</option>";
}
} else {
echo "<option value='".$time['TIME_ID']."'>".date("H:i", strtotime($time["TIME_START"])).' - '
.date("H:i",strtotime($time["TIME_FINISH"]))."</option>";
}
}
}
?>
</select>
<div class="red" id="responseTimeError"></div>
</div>
</div>
<div class="form-group">
<label for="inputSubject" class="col-sm-2 col-md-2 control-label">Предмет в</br>классе <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<select id="inputSubject" name="inputSubject" class="width-select">
<?php
if(isset($subjects)) {
if($subject_id == null && isset($id)) echo "<option value=''></option>";
foreach($subjects as $subject) {
if ($subject_id != "") {
if($subject['SUBJECTS_CLASS_ID'] == $subject_id) {
echo "<option selected='selected' value='".$subject['SUBJECTS_CLASS_ID']."'>".$subject['SUBJECT_NAME']."</option>";
} else {
echo "<option value='".$subject['SUBJECTS_CLASS_ID']."'>".$subject['SUBJECT_NAME']."</option>";
}
} else {
echo "<option value='".$subject['SUBJECTS_CLASS_ID']."'>".$subject['SUBJECT_NAME']."</option>";
}
}
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="inputRoom" class="col-sm-2 col-md-2 control-label">Кабинет</label>
<div class="col-sm-10 col-md-10">
<select id="inputRoom" name="inputRoom" class="width-select">
<option value=""></option>
<?php
if(isset($rooms)) {
foreach($rooms as $room) {
if ($room_id != "") {
if($room['ROOM_ID'] == $room_id) {
echo "<option selected='selected' value='".$room['ROOM_ID']."'>".$room['ROOM_NAME']."</option>";
} else {
echo "<option value='".$room['ROOM_ID']."'>".$room['ROOM_NAME']."</option>";
}
} else {
echo "<option value='".$room['ROOM_ID']."'>".$room['ROOM_NAME']."</option>";
}
}
}
?>
</select>
</div>
</div>
</div>
<div class="grey">* - Обязательные поля</div>
<div id="error" class="red"></div>
<div class="modal-footer" style="margin-bottom: -15px; padding-right: 0px;">
<button type="button" class="btn btn-default" onclick="javascript:history.back();" title="Отменить">Отменить</button>
<button type="submit" class="btn btn-sample" name="save" id="save" title="Сохранить">Сохранить</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#inputSubject").select2({
language: "ru"
});
$("#inputTime").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
$("#inputRoom").select2({
language: "ru"
});
$('#save').click(function() {
var base_url = '<?php echo base_url();?>';
var s = 0;
var error = 0;
var day = '<?php echo $this->uri->segment(3);?>';
var room = $('#inputRoom').find("option:selected").val();
var subject = $('#inputSubject').find("option:selected").val();
var time = $('#inputTime').find("option:selected").val();
var id = $('#id').text();
if (time == "") {
s++;
}
if(subject == "") {
s++;
}
$("#responseTimeError").text('');
if(time != "" && subject != "") {
$.ajax({
type: "POST",
url: base_url + "table/responsetimetable",
data: "time=" + time + "&day=" + day + "&id=" + id,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
//alert(response);
if (response == true) {
$("#responseTimeError").text('В расписании уже занято это время на этот день');
error++;
}
if (response == false) {
$("#responseTimeError").text('');
}
}
});
}
if (s != 0) {
$("#error").text('Не все обязательные поля заполнены');
}
else {
$("#error").text('');
}
//alert(s + " " + error);
if (s == 0 && error == 0) {
/*if (id == "") {
$.ajax({
type: "POST",
url: base_url + "table/addtimetable",
data: "subject=" + subject + "&time=" + time + "&day=" + day + "&room=" + room,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
document.location.href = base_url + 'teacher/timetable/1';
}
});
}
else {
$.ajax({
type: "POST",
url: base_url + "table/updatetimetable",
data: "subject=" + subject + "&time=" + time + "&day=" + day + "&room=" + room + "&id=" + id,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
//alert(response);
document.location.href = base_url + 'teacher/timetable/1';
}
});
}*/
} else return false;
});
});
</script>
<file_sep>/js/charRemaining.js
function declOfNum(number, titles)
{
cases = [2, 0, 1, 1, 1, 2];
return titles[ (number%100>4 && number%100<20)? 2 : cases[(number%10<5)?number%10:5] ];
}
$(function()
{
$('textarea').keyup(function()
{
var maxLength = $(this).attr('maxlength');
var curLength = $(this).val().length;
$(this).val($(this).val().substr(0, maxLength));
var remaning = maxLength - curLength;
if (remaning < 0) remaning = 0;
try {
var textareaFeedback = $(this).closest("div").find($('.textareaFeedback'));
if(remaning == maxLength) {
textareaFeedback.html('');
} else {
textareaFeedback.html('Осталось ' + remaning + ' ' + declOfNum(remaning, ['символ', 'символа', 'символов']));
}
}
catch (e) {
}
})
})<file_sep>/application/views/blankview/blanklessonview.php
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><?php echo $title; ?></div>
<div class="panel-body">
<form method="post" enctype="multipart/form-data">
<div hidden="true" id="id"><?php if(isset($id)) echo $id;?></div>
<div class="form-horizontal">
<div class="form-group">
<label for="inputTheme" class="col-sm-2 col-md-2 control-label">Тема урока <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<textarea style="resize: vertical;" class="form-control" rows="2" maxlength="1000" name="inputTheme" id="inputTheme" placeholder="Тема урока" autofocus required="true"><?php if(isset($theme)) echo $theme;?></textarea>
<div class="textareaFeedback"></div>
</div>
</div>
<div class="form-group">
<label for="inputDate" class="col-sm-2 col-md-2 control-label">Дата урока <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<input type="text" class="form-control" id="inputDate" name="inputDate" required="true" placeholder="гггг-мм-дд" value="<?php if(isset($date)) { echo $date; } else echo date('Y-m-d');?>" >
<div id="responseDateError" class="red"></div>
</div>
</div>
<div class="form-group" hidden="true">
<label for="inputURL" class="col-sm-2 col-md-2 control-label">Предыдущая страница</label>
<div class="col-sm-10 col-md-10">
<input type="text" class="form-control" id="inputURL" name="inputURL" value="<?php if(isset($back)) { echo $back; }?>">
</div>
</div>
<div class="form-group">
<label for="inputTime" class="col-sm-2 col-md-2 control-label">Время урока <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<select id="inputTime" name="inputTime" style="width: 100%;">
<?php
if(isset($times)) {
if($time_id == null && isset($id)) echo "<option value=''></option>";
foreach($times as $time) {
if ($time_id != "") {
if($time['TIME_ID'] == $time_id) {
echo "<option selected='selected' value='".$time['TIME_ID']."'>".date("H:i", strtotime($time["TIME_START"])).' - '
.date("H:i",strtotime($time["TIME_FINISH"]))."</option>";
} else {
echo "<option value='".$time['TIME_ID']."'>".date("H:i", strtotime($time["TIME_START"])).' - '
.date("H:i",strtotime($time["TIME_FINISH"]))."</option>";
}
} else {
echo "<option value='".$time['TIME_ID']."'>".date("H:i", strtotime($time["TIME_START"])).' - '
.date("H:i",strtotime($time["TIME_FINISH"]))."</option>";
}
}
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-md-2 control-label">Статус <span class="star">*</span></label>
<div class="col-sm-offset-2 col-sm-10" style="margin-top: -27.5px;">
<label class="radio-inline">
<input type="radio" name="inputStatus" value="0" <?php if(isset($status) && $status == 0) { echo "checked='checked'";} else echo "checked='checked'";?>>Не проведен
</label>
<label class="radio-inline">
<input type="radio" name="inputStatus" value="1" <?php if(isset($status) && $status == 1) { echo "checked='checked'";} ?> >Проведен
</label>
</div>
</div>
<div class="form-group">
<label for="inputHomework" class="col-sm-2 col-md-2 control-label">Домашнее задание</label>
<div class="col-sm-10 col-md-10">
<textarea style="resize: vertical;" class="form-control" rows="10" maxlength="8000" id="inputHomework" name="inputHomework" placeholder="Текст домашнего задания"><?php if(isset($homework)) echo $homework; ?></textarea>
<div class="textareaFeedback"></div>
</div>
</div>
<!--<div class="form-group">
<label for="inputFile" class="col-sm-2 col-md-2 control-label">Вложения (размер файла не более 10 Мб)</label>
<div class="col-sm-10 col-md-10">
<input type="file" id="inputFile1" name="inputFile1" style="padding-top: 15px;">
<input type="file" id="inputFile2" name="inputFile2">
<input type="file" id="inputFile3" name="inputFile3">
</div>
</div>-->
</div>
<div class="grey">* - Обязательные поля</div>
<div id="error" class="red"></div>
<div class="modal-footer" style="margin-bottom: -15px; padding-right: 0px;">
<button type="button" class="btn btn-default" onclick="javascript:history.back();" title="Отменить">Отменить</button>
<button type="submit" class="btn btn-sample" name="save" id="save" title="Сохранить">Сохранить</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#inputTime").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
$("#inputDate").mask("9999-99-99");
$('#inputDate').datepicker({
format: 'yyyy-mm-dd',
startDate: "1993-01-01",
endDate: "2100-01-01",
language: "ru",
todayBtn: "linked",
autoclose: true,
todayHighlight: true,
});
$('#save').click(function() {
var base_url = '<?php echo base_url();?>';
var s = 0;
var error = 0;
var theme = $.trim($('#inputTheme').val());
var date = $('#inputDate').val();
var time = $('#inputTime').find("option:selected").val();
var text = $.trim($('#inputHomework').val());
var id = $('#id').text();
if (theme.length == 0) {
$('#inputTheme').parent().addClass("has-error");
s++;
} else {
$('#inputTheme').parent().removeClass("has-error");
}
if (date.length == 0) {
$('#inputDate').parent().addClass("has-error");
s++;
} else {
$('#inputDate').parent().removeClass("has-error");
$("#responseDateError").text('');
$.ajax({
type: "POST",
url: base_url + "table/responselesson",
data: "date=" + date + "&time=" + time+ "&id=" + id + "&subject=" + "<?php echo $this->uri->segment(3);?>",
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
if (response == 1) {
$("#responseDateError").text('В списке уже есть такой урок на выбранное время');
$('#inputDate').parent().addClass("has-error");
error++;
}
if (response == 2) {
$("#responseDateError").text('В расписании нет такого занятия');
$('#inputDate').parent().addClass("has-error");
error++;
}
if (response == 0) {
$("#responseDateError").text('');
$('#inputDate').parent().removeClass("has-error");
}
}
});
}
if (s != 0) {
$("#error").text('Не все обязательные поля заполнены');
}
else {
$("#error").text('');
}
/*alert(s + " " + error);*/
if (s == 0 && error == 0) {} else return false;
});
});
</script>
<file_sep>/application/views/message/messageview.php
<?php
function showDate($date) {
$day = date('d', strtotime($date));
$mounth = date('m', strtotime($date));
$year = date('Y', strtotime($date));
$hours = date('H', strtotime($date));
$minutes = date('i', strtotime($date));
$data = array('01'=>'января','02'=>'февраля','03'=>'марта','04'=>'апреля','05'=>'мая','06'=>'июня',
'07'=>'июля', '08'=>'августа','09'=>'сентября','10'=>'октября','11'=>'ноября','12'=>'декабря');
$today_year = date('Y');
$today_day = date('d');
foreach ($data as $key=>$value) {
if ($key==$mounth) {
if ($year < $today_year) {
echo ltrim($day, '0')." $value $year года";
} else {
if ($day != $today_day) {
echo ltrim($day, '0')." $value";
}
else {
echo $hours.":".$minutes;
}
}
}
}
}
?>
<!--<div class="container">
<div class="row">
<div class="col-md-3">
<div class="list-group">
<a href="<?php echo base_url();?>messages/inbox" class="list-group-item <?php if ($active == 1) echo 'active'; ?>">Входящие <?php if ($badge != 0) {?> <span class="badge"><?php echo $badge;?></span> <?php } ?></a>
<a href="<?php echo base_url();?>messages/sent" class="list-group-item <?php if ($active == 2) echo 'active'; ?>">Исходящие</a>
</div>
</div>-->
<div class="col-md-9">
<div class="panel panel-default">
<div class="panel-heading">
<button type="button" class="btn btn-menu" id="writeButton" >
<span class="glyphicon glyphicon-edit" aria-hidden="true"></span></br>Написать
</button>
<button type="button" class="btn btn-menu disabled" id="readButton" >
<span class="glyphicon glyphicon-check" aria-hidden="true"></span></br>Прочитано
</button>
<button type="button" class="btn btn-menu disabled" id="deleteButton" data-toggle="modal" data-target="#myModal" title="Удалить сообщение">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span></br>Удалить
</button>
</div>
<div class="panel-body">
<form method="get">
<div class="input-group">
<input type="text" class="form-control" placeholder="Поиск..." id="search" name="search" value="<?php if(isset($search)) echo $search;?>" >
<span class="input-group-btn">
<button class="btn btn-default" type="submit" name="submit" id="searchButton" title="Поиск"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
</span>
</div><!-- /input-group -->
</form>
</div>
<div class="table-responsive">
<table name="timetable" class="table table-striped table-bordered table-hover numeric">
<thead>
<tr>
<th><input type="checkbox" id="all"></th>
<th><?php if ($active == 'inbox') echo 'От кого'; else echo 'Кому'; ?></th>
<th>Текст сообщения</th>
<th>Дата</th>
</tr>
</thead>
<tbody>
<?php if(is_array($messages) && count($messages) ) {
foreach($messages as $message){ ?>
<?php if($active == 'inbox' && $message['MESSAGE_READ'] == 0) { ?><tr class="info"><?php } else { ?><tr><?php }?>
<td><input type="checkbox" name="messages[]" value="<?php echo $message['USER_MESSAGE_ID']; ?>"></td>
<td class="col-md-5"><?php echo $message['USER_NAME'];?></td>
<td class="col-md-5"><?php echo $message['MESSAGE_TEXT']; ?></td>
<td class="col-md-2"><?php showDate($message['MESSAGE_DATE']);?></td>
</tr>
<?php }}?>
</tbody>
</table>
</div>
</div>
<?php echo $this->pagination->create_links(); ?>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#all").change(function(){
$("input[name='messages[]']").prop('checked', this.checked);
if(this.checked == true) {
$('#deleteButton').removeClass('disabled');
$('#readButton').removeClass('disabled');
} else {
$('#deleteButton').addClass('disabled');
$('#readButton').addClass('disabled');
}
});
$('#writeButton').click(function() {
document.location.href = '<?php echo base_url(); ?>messages/message';
});
$("table tbody td input[name='messages[]']").click(function(e){
var s = 0;
$("input[name='messages[]']:checked").each(function () {
s++;
});
if(s != 0) {
$('#deleteButton').removeClass('disabled');
$('#readButton').removeClass('disabled');
} else {
$('#deleteButton').addClass('disabled');
$('#readButton').addClass('disabled');
}
e.stopPropagation();
});
$('#buttonDeleteMessageModal').click(function() {
var base_url = '<?php echo base_url();?>';
var checked = [];
$("input[name='messages[]']:checked").each(function () {
checked.push($(this).val());
});
for(var i = 0; i < checked.length; i++ ) {
$.ajax({
type: "POST",
url: base_url + "table/del/message/" + checked[i],
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(a) {
//alert(a);
}
});
}
location.reload();
});
$('#readButton').click(function() {
var base_url = '<?php echo base_url();?>';
var checked = [];
$("input[name='messages[]']:checked").each(function () {
checked.push($(this).val());
});
for(var i = 0; i < checked.length; i++ ) {
$.ajax({
type: "POST",
url: base_url + "table/readmessage/" + checked[i],
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(a) {
//alert(a);
}
});
}
location.reload();
});
$("tr:not(:first)").click(function() {
if ($(this).children("td").find("input[name='messages[]']").is(":checked")) {
var attr = false;
} else {
var attr = true;
}
$(this).children("td").find("input[name='messages[]']").prop('checked', attr).change();
});
});
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Удаление сообщений</h4>
</div>
<div class="modal-body">
<p>Вы уверены, что хотите удалить эти сообщения?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-sample" id="buttonDeleteMessageModal">Удалить</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<file_sep>/application/controllers/Messages.php
<?php
class Messages extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('messagemodel', 'message');
}
var $from = null;
var $to = null;
function _remap($method, $params = array())
{
$login = $this->session->userdata('login');
$role = $this->session->userdata('role');
if(isset($login)) {
switch($method) {
/*case 'inbox': {
$data['title'] = "Входящие";
break;
}
case 'sent': {
$data['title'] = "Исходящие";
break;
}*/
case 'conversations': {
$data['title'] = "Переписки";
break;
}
case 'conversation': {
$data['title'] = "Общение";
break;
}
case 'message': {
$data['title'] = "Сообщение";
break;
}
}
switch($role) {
case 4: {
$this->from = "PUPIL";
$this->to = "TEACHER";
break;
}
case 1: case 3: {
$this->to = "PUPIL";
$this->from = "TEACHER";
break;
}
}
$data['role'] = $role;
$data['mainlogin'] = $login;
$this->load->view('header', $data);
//$this->load->view('message/messagemenuview');
if (method_exists($this, $method))
{
call_user_func_array(array($this, $method), $params);
}
else {
redirect(base_url()."messages/conversations");
}
$this->load->view('footer');
}
else {
redirect('auth/logout');
}
}
/*private function _getMessages($type, $offset) {
if($type == "1") {
$folder = "inbox";
} else $folder = "sent";
$search = "";
$id = $this->session->userdata('id');
$num = 10;
$config['total_rows'] = $this->message->totalFolderMessages($id, $type, $search, $this->from, $this->to);
$config['base_url'] = base_url()."message/".$folder;
$config['per_page'] = $num;
if (count($_GET) > 0) { $config['suffix'] = '?' . http_build_query($_GET, '', "&");
$config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
}
$query = $this->message->getFolderMessages($num, $offset * $num - $num, $id, $type, $search, $this->from, $this->to);
$this->pagination->initialize($config);
$data['messages'] = null;
if($query) {
$data['messages'] = $query;
}
$data['active'] = $folder;
//$data['badge'] = $this->message->totalUnreadPupilMessages($id, 1);
$this->load->view('message/messageview', $data);
}
function inbox($offset = 1) {
$role = $this->session->userdata('role');
switch($role) {
case 4: {
$this->_getMessages(1, $offset);
break;
}
case 1: case 3: {
$this->_getMessages(1, $offset);
break;
}
}
}
function sent($offset = 1) {
$role = $this->session->userdata('role');
switch($role) {
case 4: {
$this->_getMessages(2, $offset);
break;
}
case 1: case 3: {
$this->_getMessages(2, $offset);
break;
}
}
}*/
function message() {
if(isset($_POST['send'])) {
$id = $this->session->userdata('id');
$user = $_POST['contact'];
$text = $_POST['inputText'];
date_default_timezone_set('Europe/Moscow');
$date = date('Y-m-d H:i:s');
$this->load->model('tablemodel', 'table');
//добавдение сообщения
$this->table->addMessage($id, $user, $text, $date, $this->from, $this->to);
redirect(base_url()."messages/conversations");
} else {
$data['title'] = 'Новое сообщение';
$this->load->view('blankview/blankmessageview', $data);
}
}
function conversations($offset = 1) {
$search = "";
if(isset($_GET['submit'])) {
if(isset($_GET['search'])) {
$search = urldecode($_GET['search']);
$data['search'] = $search;
if ($search == "") {
redirect(base_url()."messages/conversations");
} else redirect(base_url()."messages/conversations?search=".$search);
}
}
if(isset($_GET['search'])) {
$search = $_GET['search'];
$data['search'] = $search;
}
$id = $this->session->userdata('id');
$num = 15;
$config['total_rows'] = $this->message->totalMessages($id, $this->from, $this->to, $search);
$config['base_url'] = base_url()."messages/conversations";
$config['per_page'] = $num;
$this->pagination->initialize($config);
if (count($_GET) > 0) { $config['suffix'] = '?' . http_build_query($_GET, '', "&");
$config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
}
$query = $this->message->getMessages($num, $offset * $num - $num, $id, $this->from, $this->to, $search);
$data['result'] = null;
$data['messages'] = array();
if($query) {
$result = array();
$i = 0;
foreach($query as $row) {
$user_id = $row['USER_ID'];
$newmessages = $this->message->getNewMessages($user_id, $id, $this->from, $this->to);
if(count($newmessages) > 0) {
$result[$i]["new"] = count($newmessages);
} else {
$result[$i]["new"] = null;
}
$i++;
}
$data['result'] = $result;
$data['messages'] = $query;
}
$this->load->view('message/conversationsview', $data);
}
function conversation($user, $offset = 1) {
$search = "";
if(isset($_GET['submit'])) {
if(isset($_GET['search'])) {
$search = urldecode($_GET['search']);
$data['search'] = $search;
if ($search == "") {
redirect(base_url()."messages/conversation/".$user);
} else redirect(base_url()."messages/conversation/".$user."?search=".$search);
}
}
if(isset($_GET['search'])) {
$search = $_GET['search'];
$data['search'] = $search;
}
$id = $this->session->userdata('id');
$num = 15;
$config['total_rows'] = $this->message->totalConversationMessages($id, $user, $search, $this->from, $this->to);
$config['base_url'] = base_url()."messages/conversation/".$user;
$config['per_page'] = $num;
$config['uri_segment'] = 2;
$data['user'] = $this->message->getUserById($user, $this->from, $this->to)['USER_NAME'];
if (count($_GET) > 0) { $config['suffix'] = '?' . http_build_query($_GET, '', "&");
$config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
}
$this->pagination->initialize($config);
$query = $this->message->getConversationMessages($num, $offset * $num - $num, $id, $user, $search, $this->from, $this->to);
$data['messages'] = null;
if($query) {
$data['messages'] = $query;
}
$this->load->view('message/conversationview', $data);
}
}
?><file_sep>/application/views/admin/statisticsview.php
<?php
function setColor($mark, $tooltip) {
switch ($mark) {
case 5: echo '<span data-toggle="tooltip" data-placement="top" title="'.$tooltip.'" class="label label-success">'.$mark.'</span>'; break;
case 4: echo '<span data-toggle="tooltip" data-placement="top" title="'.$tooltip.'" class="label label-warning">'.$mark.'</span>'; break;
case 3: echo '<span data-toggle="tooltip" data-placement="top" title="'.$tooltip.'" class="label label-primary">'.$mark.'</span>'; break;
case 2: echo '<span data-toggle="tooltip" data-placement="top" title="'.$tooltip.'" class="label label-danger">'.$mark.'</span>'; break;
}
}
?>
<div class="container">
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-4">
<form method="post">
<label for="year" class="control-label"><i class="fa fa-clock-o"></i> Год</label>
<select id="year" name="year" onchange="this.form.submit();" style="width: 70%;">
<?php
foreach ($years as $year) {
?>
<option value="<?php echo $year['YEAR_ID'];?>"><?php echo date("Y", strtotime($year['YEAR_START'])).' - '.date("Y", strtotime($year['YEAR_FINISH']))." гг."; ?></option><?php
}
?>
</select>
</form>
</div>
<div class="col-md-8">
<form method="post">
<label for="period" class="control-label"><i class="fa fa-calendar"></i> Период</label>
<select id="period" name="period" onchange="this.form.submit();" style="width: 30%;">
<?php
foreach ($periods as $period) {
?>
<option value="<?php echo $period['PERIOD_ID'];?>"><?php echo $period['PERIOD_NAME']; ?></option><?php
}
?>
</select>
</form>
</div>
</div>
<div class="row">
<div class="col-md-8">
<h3 class="sidebar-header">Успеваемость <strong><?php if(isset($name)) echo $name;?></strong></h3>
</div>
<div class="col-md-4" >
<h5><span onclick="print();" class="a-block pull-right" title="Печать"><i class="fa fa-print"></i> Печать</span></h5>
</div>
</div>
<div class="panel panel-default">
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered numeric">
<thead>
<tr>
<th rowspan="2">#</th>
<th rowspan="2">Класс</th>
<th rowspan="2">Всего</th>
<th colspan="2" style=" text-align: center;"><span class="green">Отличники</span></th>
<th colspan="2" style=" text-align: center;"><span class="yellow">Хорошисты</span></th>
<th colspan="2" style=" text-align: center;"><span class="blue">Троечники</span></th>
<th colspan="2" style=" text-align: center;"><span class="red">Неуспевающие</span></th>
</tr>
<tr>
<th style="width: 10%; border-bottom-width: 1px;">Всего</th>
<th style="width: 10%; border-bottom-width: 1px;">%</th>
<th style="width: 10%; border-bottom-width: 1px;">Всего</th>
<th style="width: 10%; border-bottom-width: 1px;">%</th>
<th style="width: 10%; border-bottom-width: 1px;">Всего</th>
<th style="width: 10%; border-bottom-width: 1px;">%</th>
<th style="width: 10%; border-bottom-width: 1px;">Всего</th>
<th style="width: 10%; border-bottom-width: 1px;">%</th>
</tr>
</thead>
<tbody>
<?php
for($i = 0; $i < count($result); $i++) {
?>
<tr style="cursor: pointer; cursor: hand;" onclick="location.href='<?php echo base_url();?>admin/progress/<?php echo $result[$i]["class_id"]; ?>'">
<td><?php echo $i+1; ?></td>
<td><?php echo $result[$i]["class_name"]; ?></td>
<td><strong><?php echo $result[$i]["count"]; ?></strong></td>
<?php for($y = 5; $y >= 2; $y--) { ?>
<td>
<?php echo $result[$i][$y]['mark']; ?></td>
<td><?php if ($result[$i]["count"] != 0) echo round($result[$i][$y]['mark'] / $result[$i]["count"] * 100); else echo "0"; ?></td>
<?php } ?>
</tr>
<?php
} ?>
</tbody>
</table>
</div>
</div>
<?php if(isset($pass1)) { ?><span>Самый болеющий класс <?php echo $pass1; ?></span><?php } ?>
</div>
<script type="text/javascript">
document.getElementById('year').value = "<?php echo $this->uri->segment(3);?>";
document.getElementById('period').value = "<?php echo $this->uri->segment(4);?>";
$("#year").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
$("#period").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
</script><file_sep>/application/views/pupil/newsview.php
<?php
function crop_str($string, $limit){
if (strlen($string) >= $limit ) {
$substring_limited = substr($string,0, $limit);
return substr($substring_limited, 0, strrpos($substring_limited, ' ' ));
} else {
//Если количество символов строки меньше чем задано, то просто возращаем оригинал
return $string;
}
}
?>
<div class="col-md-8">
<?php
if(is_array($news) && count($news) ) {
foreach($news as $row){ ?>
<div class="blog_grid">
<h2 class="post_title"><a href="<?php echo base_url(); ?>pupil/post/<?php echo $row['NEWS_ID']; ?>"><?php echo $row['NEWS_THEME'] ?></a></h2>
<ul class="links">
<li><i class="fa fa-calendar"></i> <?php echo showDate($row['NEWS_TIME']); ?></li>
<li><i class="fa fa-user"></i> <?php echo $row['TEACHER_NAME']; ?></li>
</ul>
<p><?php $str = crop_str($row['NEWS_TEXT'], 1000);
if($str != $row['NEWS_TEXT']) {
echo $str." ...";
}
else echo $str;
?></p>
<?php if($str != $row['NEWS_TEXT']) { ?> <button onclick="location.href='<?php echo base_url();?>pupil/post/<?php echo $row['NEWS_ID']; ?>';" class="btn btn-sample" title="Подробнее">Подробнее</button><?php } ?>
</div>
<?php }} ?>
<?php echo $this->pagination->create_links(); ?>
</div>
</div>
</div>
<file_sep>/application/views/teacher/lessonpageview.php
<div class="container">
<div class="row">
<div class="col-md-9">
<div class="panel panel-default">
<div class="panel-heading">Учебное занятие по предмету <strong><?php if(isset($subject)) echo $subject; ?></strong></div>
<div class="table-responsive">
<table class="table table-striped table-hover ">
<tbody>
<tr>
<td class="col-md-4">Дата</td>
<td><?php if(isset($date)) echo $date;?></td>
</tr>
<tr>
<td class="col-md-4">Время</td>
<td><?php if(isset($time)) echo $time;?></td>
</tr>
<tr>
<td class="col-md-4">Тема</td>
<td><?php if(isset($theme)) echo $theme;?></td>
</tr>
<tr>
<td class="col-md-4">Домашнее задание</td>
<td><?php if(isset($homework) && $homework != "") { ?>
<button class="btn btn-sample btn-xs" title="Показать домашнее задание" type="button" data-toggle="modal" data-target="#myModal<?php echo $id ?>"><i class="fa fa-home"></i> Домашнее задание
</button>
<div class="modal fade" id="myModal<?php echo $id ?>" 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" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Домашнее задание</h4>
</div>
<div class="modal-body">
<?php echo $homework ?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Закрыть</button>
</div>
</div>
</div>
</div>
<?php } ?>
</td>
</tr>
<tr>
<td class="col-md-4">Урок проведен</td>
<td><input type="checkbox" name="my-checkbox" <?php if(isset($status) && $status == 1) echo "checked"; ?>></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="col-md-3">
<span onclick="location.href='<?php echo base_url();?>teacher/lesson/<?php echo $this->uri->segment(3);?>/<?php echo $this->uri->segment(4);?>';" class="a-block pull-right" title="Редактировать учебное занятие"><i class="fa fa-pencil"></i> Редактировать занятие</span>
</div>
</div>
<div class="row">
<div class="col-md-8">
<h3 class="sidebar-header"><i class="fa fa-users"></i> Список <strong><?php if(isset($class)) echo $class; ?></strong></h3>
</div>
<div class="col-md-4" >
<h5><span onclick="print();" class="a-block pull-right" title="Печать"><i class="fa fa-print"></i> Печать</span></h5>
</div>
</div>
<div class="panel panel-default">
<div class="table-responsive">
<table id="lesson" class="table table-striped table-hover table-bordered numeric">
<thead>
<tr>
<th>#</th>
<th hidden="true">ID учащегося</th>
<th style="width: 30%;">ФИО учащегося</th>
<th hidden="true">Пропуск</th>
<th style="width: 10%;">Пропуск</th>
<th>Замечания</th>
<th>Оценки</th>
<th>Добавить</th>
</tr>
</thead>
<tbody>
<?php
for($i = 0; $i < count($info); $i++) {
?>
<tr>
<td data-editable='false'><?php echo $i+1; ?></td>
<td data-editable='false' hidden="true" id="pupil_id"><?php echo $info[$i]['pupil_id'];?></td>
<td data-editable='false' id="pupil_name"><?php echo $info[$i]['pupil_name'];?></td>
<td data-editable='false' hidden="true" id="attendance_id"><?php if(isset($info[$i]['pass_id'])) echo $info[$i]['pass_id'];
?></td>
<td class="pass <?php if(isset($info[$i]['pass'])) {
switch($info[$i]['pass']) {
case 'н': {
echo "warning";
break;
}
case 'б': {
echo "success";
break;
}
case 'у': {
echo "info";
break;
}
}
}
?>">
<?php if(isset($info[$i]['pass'])) echo $info[$i]['pass'];?></td>
<td class="note" data-id="<?php echo $info[$i]['note_id']; ?>"><?php echo $info[$i]['note']; ?></td>
<td data-editable='false'><?php
for($y = 0; $y < count($info[$i]['marks']); $y++) {
?><span data-target="#context-menu" style="cursor: pointer; cursor: hand;"
data-toggle="tooltip" data-placement="top" title="<?php echo $info[$i]['marks'][$y]['type']; ?>"
data-type="<?php echo $info[$i]['marks'][$y]['type_id']; ?>"
data-mark ="<?php echo $info[$i]['marks'][$y]['mark']; ?>"
data-id="<?php echo $info[$i]['marks'][$y]['achievement']; ?>" class="btnMark
<?php
switch($info[$i]['marks'][$y]['mark']) {
case '2': {
?> label label-danger <?php
break;
}
case '3': {
?> label label-primary <?php
break;
}
case '4': {
?> label label-warning <?php
break;
}
case '5': {
?> label label-success<?php
break;
}
}
?>"
><?php echo $info[$i]['marks'][$y]['mark']; ?></span>
<?php
}
?></td>
<td data-editable='false'><button type="button" data-toggle="modal" class="btn btn-sample addMark btn-xs">
<span class="glyphicon glyphicon-plus" aria-hidden="true"></span></button>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<table style="margin-bottom: 20px;">
<tr>
<td><div class="color-swatch brand-success"></div></td>
<td>Пропуск по болезни (б)</td>
</tr>
<tr>
<td><div class="color-swatch brand-info"></div></td>
<td>Пропуск по уважительной причине (у)</td>
</tr>
<tr>
<td><div class="color-swatch brand-warning"></div></td>
<td>Пропуск по неуважительной причине (н)</td>
</tr>
</table>
</div>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Выставление оценки</h4>
</div>
<div class="modal-body">
<input type="text" id="id" hidden="true">
<input type="text" id="pupil" hidden="true">
<div class="form-horizontal">
<div class="form-group">
<label for="mark" class="col-sm-3 col-md-3 control-label">Оценка <span class="star">*</span></label>
<div class="col-sm-9 col-md-9">
<select id="mark" class="width-select">
<option value="5">5</option>
<option value="4">4</option>
<option value="3">3</option>
<option value="2">2</option>
</select>
</div>
</div>
<div class="form-group">
<label for="type" class="col-sm-3 col-md-3 control-label">Тип оценки <span class="star">*</span></label>
<div class="col-sm-9 col-md-9">
<select id="type" class="width-select">
<?php foreach($types as $type) {?>
<option value="<?php echo $type['TYPE_ID']; ?>"><?php echo $type['TYPE_NAME']; ?></option>
<?php }?>
</select>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-sample" id="buttonAddMarkModal">Сохранить</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div id="context-menu">
<ul class="dropdown-menu" role="menu">
<li id="editMark"><a tabindex="-1">Редактировать</a></li>
<li id="deleteMark"><a tabindex="-1">Удалить</a></li>
</ul>
</div>
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Удаление оценки</h4>
</div>
<div class="modal-body">
<p>Вы уверены, что хотите удалить эту оценку?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-sample" id="buttonDeleteMarkModal">Удалить</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<script type="text/javascript">
$(document).ready(function() {
$('#lesson').editableTableWidget();
$('#lesson td.pass').focus(function(){
$(this).data('oldValue',$(this).text());
});
$('#lesson td.pass').on('change', function(evt, newValue) {
var base_url = '<?php echo base_url();?>';
//старое значение
var oldValue = $(this).data('oldValue');
newValue = $.trim(newValue);
if (!(newValue == 'н' || newValue == 'у' || newValue == 'б' || newValue == "")) {
return false; // reject change
} else {
$(this).removeClass();
//можем редактировать
if(newValue == 'н') {
$(this).addClass("warning");
}
if(newValue == 'б') {
$(this).addClass("success");
}
if(newValue == 'у') {
$(this).addClass("info");
}
var pupil_id = $(this).parent().find('#pupil_id').html();
var lesson_id = "<?php echo $this->uri->segment(4);?>";
var attendance_id = $(this).parent().find('#attendance_id').html();
if (newValue != oldValue) {
$.ajax({
type: "POST",
url: base_url + "table/changeattendance",
data: "pupil_id=" + pupil_id + "&lesson_id=" +lesson_id + "&attendance=" + attendance_id + "&pass=" + newValue,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
}
});
}
}
});
$('#lesson td.note').focus(function(){
$(this).data('oldValue',$(this).text());
});
$('#lesson td.note').on('change', function(evt, newValue) {
newValue = $.trim(newValue);
var base_url = '<?php echo base_url();?>';
//старое значение
var oldValue = $(this).data('oldValue');
var pupil_id = $(this).parent().find('#pupil_id').html();
var lesson_id = "<?php echo $this->uri->segment(4);?>";
var note_id = $(this).attr("data-id");
if (newValue != oldValue) {
$.ajax({
type: "POST",
url: base_url + "table/changenote",
data: "pupil_id=" + pupil_id + "&lesson_id=" +lesson_id + "¬e_id=" + note_id + "¬e=" + newValue,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
}
});
}
});
$("[name='my-checkbox']").bootstrapSwitch();
$('input[name="my-checkbox"]').on('switchChange.bootstrapSwitch', function(event, state) {
var base_url = '<?php echo base_url();?>';
var lesson_id = "<?php echo $this->uri->segment(4);?>";
if(state == true) {
var flag = 1;
} else {
var flag = 0;
}
$.ajax({
type: "POST",
url: base_url + "table/changelessonstatus",
data: "lesson_id=" +lesson_id + "&status=" + flag,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
}
});
});
$('.addMark').click(function() {
var pupil_name = $(this).parent().parent().find('#pupil_name').html();
var pupil_id = $(this).parent().parent().find('#pupil_id').html();
$("#pupil").val(pupil_id);
$('#myModal .modal-title').text("Новая оценка для " + pupil_name );
$('#myModal').modal('show');
});
//кнопка редактирования или добавления оценки
$("#buttonAddMarkModal" ).on('click',function() {
var lesson_id = "<?php echo $this->uri->segment(4);?>";
var base_url = '<?php echo base_url();?>';
var mark = $("#mark").find("option:selected").val();
var type = $("#type").find("option:selected").val();
var id = $("#id").val();
var pupil_id = $("#pupil").val();
$.ajax({
type: "POST",
url: base_url + "table/changemark",
data: "pupil_id=" + pupil_id + "&lesson_id=" +lesson_id + "&achievement=" + id + "&mark=" + mark + "&type=" + type,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(a) {
//alert(a);
location.reload();
}
});
$('#myModal').modal('hide');
});
//закрытие формы
$('#myModal').on('hide.bs.modal', function() {
$("#mark").val($("#mark option:first").val()).trigger('change');
$("#type").val($("#type option:first").val()).trigger('change');
$("#pupil").val("");
$("#id").val("");
});
var achievement = null;
var type = null;
var mark = null;
$('.btnMark').on( 'click', function( e ) {
e.stopPropagation();
$(this).contextmenu( 'show', e );
achievement = $(this).attr("data-id");
mark = $(this).attr("data-mark");
type = $(this).attr("data-type");
} )
.contextmenu();
//кнопка удаления контекстного меню
$('#deleteMark').click(function() {
$('#deleteModal').modal('show');
});
//кнопка редактирования контекстного меню
$('#editMark').click(function() {
$("#id").val(achievement);
$("#mark option[value='" + mark + "']").prop("selected", true).trigger('change');
$("#type option[value='" + type + "']").prop("selected", true).trigger('change');
$('#myModal .modal-title').text("Редактирование оценки");
$('#myModal').modal('show');
});
//кнопка удаления на модальном окне
$('#buttonDeleteMarkModal').click(function() {
var base_url = '<?php echo base_url();?>';
$.ajax({
type: "POST",
url: base_url + "table/del/mark/" + achievement,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(a) {
location.reload();
}
});
});
$("#type").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
$("#mark").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
});
</script>
<file_sep>/application/views/teacher/classtableview.php
<div class="container">
<?php
function setColor($mark) {
if ($mark >= 4.5) {
echo '<span class="green">'.$mark.'</span>';
}
if ($mark < 4.5 && $mark >=3.5) {
echo '<span class="yellow">'.$mark.'</span>';
}
if ($mark < 3.5 && $mark >= 2.5) {
echo '<span class="blue">'.$mark.'</span>';
}
if ($mark < 2.5 && $mark > 0) {
echo '<span class="red">'.$mark.'</span>';
}
if ($mark == 0) {
echo '<span class="grey">'.$mark.'</span>';
}
}
function setGreyColor($mark) {
if ($mark == 0) {
echo '<span class="grey">'.$mark.'</span>';
}
else {
echo '<span><strong>'.$mark.'</strong></span>';
}
}
?>
<div class="panel panel-default">
<div class="panel-heading">
<form action="" method="POST">
Учебный год
<select id="year" name="year" onchange="this.form.submit();" >
<?php
foreach ($years as $key => $value) { ?>
<option value="<?php echo $key?>"><?php echo $years[$key]; ?> гг.</option>
<?php
}
?>
</select>
</form>
<form action="" method="POST">
Период
<select id="period" name="period" onchange="this.form.submit();">
<?php
foreach ($periods as $key => $value) {
?>
<option value="<?php echo $key?>"><?php echo $periods[$key]['name']; ?></option>
<?php
}
?>
</select>
</form>
</div>
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered numeric">
<thead>
<tr>
<th rowspan="2">#</th>
<th rowspan="2">Предмет</th>
<th colspan="2" style=" text-align: center;">Пропуски</th>
<th colspan="3" style=" text-align: center;">Средний балл по классу</th>
<th colspan="3" style=" text-align: center;">Число обучающихся класса,</br>имеющих показатели</th>
</tr>
<tr >
<th style="border-bottom-width: 1px;">Всего</th>
<th style="border-bottom-width: 1px;">Из них по</br>болезни</th>
<th style="border-bottom-width: 1px;">мин. по</br>классу</th>
<th style="border-bottom-width: 1px;">учащегося</th>
<th style="border-bottom-width: 1px;">макс. по</br>классу</th>
<th style="border-bottom-width: 1px;">ниже</th>
<th style="border-bottom-width: 1px;">такие же</th>
<th style="border-bottom-width: 1px;">выше</th>
</tr>
</thead>
<tbody>
<?php
if(isset($stat)) {
$i = 1;
foreach ($stat as $key => $value) {
?>
<tr>
<td><?php echo $i;?></td>
<td><?php echo $stat[$key]["subject"];?></td>
<td><?php setGreyColor($stat[$key]["pass"]);?></td>
<td><?php setGreyColor($stat[$key]["ill"]);?></td>
<td><?php setColor($stat[$key]["min"]);?></td>
<td><?php setColor($stat[$key]["average"]);?></td>
<td><?php setColor($stat[$key]["max"]);?></td>
<td><?php setGreyColor($stat[$key]["min_count"]);?></td>
<td><?php setGreyColor($stat[$key]["same_count"]);?></td>
<td><?php setGreyColor($stat[$key]["max_count"]);?></td>
</tr>
<?php
$i++; } }?>
</tbody>
</table>
</div>
</div>
<?php
if(!isset($stat)) {
?>
<div class="alert alert-info" role="alert">Данных нет</div>
<?php } ?>
</div>
<script type="text/javascript">
document.getElementById('year').value = "<?php echo $this->uri->segment(3);?>";
document.getElementById('period').value = "<?php echo $this->uri->segment(4);?>";
</script><file_sep>/application/views/admin/classreportview.php
<?php
function setColor($mark) {
switch ($mark) {
case 5: echo '<span class="green">'.$mark.'</span>'; break;
case 4: echo '<span class="yellow">'.$mark.'</span>'; break;
case 3: echo '<span class="blue">'.$mark.'</span>'; break;
case 2: echo '<span class="red">'.$mark.'</span>'; break;
default: echo '<span class="grey">'.$mark.'</span>'; break;
}
}
?>
<div class="container">
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-4">
<form method="post">
<label for="period" class="control-label"><i class="fa fa-calendar"></i> Период</label>
<select id="period" name="period" onchange="this.form.submit();" style="width: 70%;" >
<?php
foreach ($periods as $period) {?>
<option value="<?php echo $period['PERIOD_ID'];?>"><?php echo $period['PERIOD_NAME']; ?></option><?php
}?>
</select>
</form>
</div>
<div class="col-md-8">
</div>
</div>
<div class="row">
<div class="col-md-8">
<h3 class="sidebar-header">Итоговый отчет <strong><?php echo $class_name;?></strong></h3>
</div>
<div class="col-md-4" >
<h5><span onclick="print();" class="a-block pull-right" title="Печать"><i class="fa fa-print"></i> Печать</span></h5>
</div>
</div>
<div class="panel panel-default">
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered numeric">
<thead >
<tr>
<th>#</th>
<th>ФИО учащегося</th>
<?php
foreach($subjects as $subject) {
?>
<th class="rotate"><div><span><?php echo $subject['SUBJECT_NAME']; ?></span></div></th>
<?php
}
?>
<th class="rotate"><div><span>Средний балл</span></div></th>
</tr>
</thead>
<tbody>
<?php
for ($i = 0; $i < count($progress); $i++) {
?>
<tr>
<td><?php echo $i+1; ?></td>
<td><?php echo $progress[$i]["pupil"]; ?></td>
<?php
$s = 0;
$k = 0;
if(isset($progress[$i]["mark"])) {
for($y = 0; $y < count($progress[$i]["mark"]); $y++) {
?>
<td><?php if(isset($progress[$i]["mark"][$y])) {
setColor($progress[$i]["mark"][$y]);
$s = $s + $progress[$i]["mark"][$y];
$k++;
}
else setColor("н/д");
?></td>
<?php
}
}
?>
<td><?php if($k != 0) { ?><strong><?php echo number_format($s / $k, 1); ?></strong><?php } else echo "<span class='grey'>н/д</span>"; ?></td>
</tr>
<?php }?>
<tr>
<td></td>
<td><strong>Средний балл по предмету</strong></td>
<?php if(isset($average)) {
for ($i = 0; $i < count($average); $i++) { ?>
<td><?php if(isset($average[$i]) && $average[$i] != 0) echo "<strong>".$average[$i]."</strong>"; else echo "<span class='grey'>н/д</span>"; ?></td>
<?php } }?>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
document.getElementById('period').value = "<?php echo $this->uri->segment(4);?>";
$("#period").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
</script><file_sep>/application/views/teacher/statisticsview.php
<div class="container">
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-4">
<form method="post">
<label for="class" class="control-label"><i class="fa fa-users"></i> Класс</label>
<select id="class" name="class" onchange="this.form.submit();" style="width: 70%">
<?php
foreach ($classes as $class) {
if(isset($class['YEAR_ID'])) $year_border = " (".date("Y",strtotime($class['YEAR_START']))." - ".date("Y",strtotime($class['YEAR_FINISH']))." гг.)"; else $year_border = '';
?>
<option value="<?php echo $class['CLASS_ID']?>"><?php echo $class['CLASS_NUMBER']." ".$class['CLASS_LETTER'].$year_border; ?></option>
<?php
}
?>
</select>
</form>
</div>
<div class="col-md-8">
<form method="post">
<label for="subject" class="control-label"><i class="fa fa-book"></i> Предмет</label>
<select id="subject" name="subject" onchange="this.form.submit();" style="width: 50%">
<?php
foreach ($subjects as $subject) {
?>
<option value="<?php echo $subject['SUBJECTS_CLASS_ID']?>"><?php echo $subject['SUBJECT_NAME']; ?></option>
<?php
}
?>
</select>
</form>
</div>
</div>
<h3 class="sidebar-header">Статистика</h3>
<div class="panel panel-default">
<div class="table-responsive">
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>Период</th>
<th>На "5"</th>
<th>На "4"</th>
<th>На "3"</th>
<th>На "2"</th>
<th>Усп. %</th>
<th>Кач. %</th>
</tr>
</thead>
<tbody>
<?php if(isset($stat)) {
for($i = 0; $i < count($stat); $i++) { ?>
<tr>
<td><strong><?php echo $stat[$i]["period"]; ?></strong></td>
<td><?php if(isset($stat[$i]["5"])) echo $stat[$i]["5"]; ?></td>
<td><?php if(isset($stat[$i]["4"])) echo $stat[$i]["4"]; ?></td>
<td><?php if(isset($stat[$i]["3"])) echo $stat[$i]["3"]; ?></td>
<td><?php if(isset($stat[$i]["2"])) echo $stat[$i]["2"]; ?></td>
<td><?php if(isset($stat[$i]["ach"])) echo $stat[$i]["ach"]; ?></td>
<td><?php if(isset($stat[$i]["quality"])) echo $stat[$i]["quality"]; ?></td>
</tr>
<?php }} ?>
</tbody>
</table>
</div>
</div>
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-4">
<label for="period" class="control-label"><i class="fa fa-calendar"></i> Период</label>
<select id="period" style="width: 60%;">
<?php
foreach ($periods as $period) {
?>
<option value="<?php echo $period['PERIOD_ID']?>"><?php echo $period['PERIOD_NAME']; ?></option>
<?php
}
?>
</select>
</div>
<div class="col-md-8"></div>
</div>
<h3 class="sidebar-header">Гистограмма посещаемости</h3>
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-12">
<div style="background:white;"><canvas id="myChart"></canvas></div>
</div>
</div>
<table class="brand-table">
<tr>
<td><div class="color-swatch brand-warning"></div></td>
<td>Пропуски по неуважительной причине</td>
</tr>
<tr>
<td><div class="color-swatch brand-info"></div></td>
<td>Пропуски по уважительной причине</td>
</tr>
<tr>
<td><div class="color-swatch brand-success"></div></td>
<td>Пропуски по болезни</td>
</tr>
</table>
</div>
<script type="text/javascript">
$(document).ready(function() {
document.getElementById('class').value = "<?php echo $this->uri->segment(3);?>";
document.getElementById('subject').value = "<?php echo $this->uri->segment(4);?>";
$("#class").select2({
language: "ru"
});
$("#subject").select2({
language: "ru"
});
var passes = document.getElementById("myChart").getContext("2d");
$('#period').change(function(){
// alert("wefef");
var base_url = '<?php echo base_url();?>';
var period = $(this).find("option:selected").val();
var subject = $("#subject").find("option:selected").val();
var class_id = $("#class").find("option:selected").val();
$.ajax({
type: "POST",
url: base_url + "api/getpasses/" + period+ "/" + subject + "/" + class_id,
cache: false,
success: function(data){
// $('#answer').html(data);
var json_obj = JSON.parse(data);
var description = new Array();
var myvalues1 = new Array();
var myvalues2 = new Array();
var myvalues3 = new Array();
for (var i in json_obj) {
description.push(json_obj[i].name);
myvalues1.push(json_obj[i].pass[1]);
myvalues2.push(json_obj[i].pass[2]);
myvalues3.push(json_obj[i].pass[3]);
}
var data = {
labels: description,
datasets: [
{
label: "Пропуски по неуважительной причине",
fillColor: "#fcf8e3",
strokeColor: "#8a6d3b",
data: myvalues1
},
{
label: "Пропуски по уважительной причине",
fillColor: "#d9edf7",
strokeColor: "#31708f",
data: myvalues2
},
{
label: "Пропуски по болезни",
fillColor: "#dff0d8",
strokeColor: "#3c763d",
data: myvalues3
}
]};
var options = {
animation: false,
responsive: true,
maintainAspectRatio: true
};
new Chart(passes).Bar(data, options);
//legend(document.getElementById('placeholder'), data);
}
});
}).change();
});
$("#period").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
</script><file_sep>/application/views/pupil/statisticsview.php
<?php
function setColor($mark) {
if ($mark >= 4.5) {
echo '<span class="green">'.$mark.'</span>';
}
if ($mark < 4.5 && $mark >=3.5) {
echo '<span class="yellow">'.$mark.'</span>';
}
if ($mark < 3.5 && $mark >= 2.5) {
echo '<span class="blue">'.$mark.'</span>';
}
if ($mark < 2.5 && $mark > 0) {
echo '<span class="red">'.$mark.'</span>';
}
if ($mark == 0) {
echo '<span class="grey">'.$mark.'</span>';
}
}
function setGreyColor($mark) {
if ($mark == 0) {
echo '<span class="grey">'.$mark.'</span>';
}
else {
echo '<span><strong>'.$mark.'</strong></span>';
}
}
?>
<div class="container">
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-4">
<form method="post">
<label for="period" class="control-label"><i class="fa fa-clock-o"></i> Год</label>
<select id="year" name="year" onchange="this.form.submit();" style="width: 60%;">
<?php
foreach ($years as $key => $value) {
?>
<option value="<?php echo $key?>"><?php echo $years[$key]; ?> гг.</option>
<?php
}
?>
</select>
</form>
</div>
<div class="col-md-8">
<form method="post">
<label for="period" class="control-label"><i class="fa fa-calendar"></i> Период</label>
<select id="period" name="period" onchange="this.form.submit();" style="width: 30%;">
<?php
foreach ($periods as $key => $value) {
?>
<option value="<?php echo $key;?>"><?php echo $periods[$key]["name"]; ?></option>
<?php
}
?>
</select>
</form>
</div>
</div>
<div class="row">
<div class="col-md-8">
<h3 class="sidebar-header">Статистика</h3>
</div>
<div class="col-md-4" >
<h5><span onclick="print();" class="a-block pull-right" title="Печать"><i class="fa fa-print"></i> Печать</span></h5>
</div>
</div>
<div class="panel panel-default">
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered numeric">
<thead>
<tr>
<th rowspan="2">#</th>
<th rowspan="2">Предмет</th>
<!--<th colspan="2" style=" text-align: center;">Пропуски</th>-->
<th colspan="3" style=" text-align: center;">Средний балл</th>
<th colspan="3" style=" text-align: center;">Число обучающихся класса,</br>имеющих показатели</th>
</tr>
<tr >
<!--<th style="border-bottom-width: 1px;">Всего</th>
<th style="border-bottom-width: 1px;">Из них по</br>болезни</th>-->
<th style="border-bottom-width: 1px;">мин. по</br>классу</th>
<th style="border-bottom-width: 1px;">учащегося</th>
<th style="border-bottom-width: 1px;">макс. по</br>классу</th>
<th style="border-bottom-width: 1px;">ниже</th>
<th style="border-bottom-width: 1px;">такие же</th>
<th style="border-bottom-width: 1px;">выше</th>
</tr>
</thead>
<tbody>
<?php
if(isset($stat)) {
$i = 1;
foreach ($stat as $key => $value) {
?>
<tr>
<td><?php echo $i;?></td>
<td><?php echo $stat[$key]["subject"];?></td>
<!--<td><?php setGreyColor($stat[$key]["pass"]);?></td>-->
<!--<td><?php setGreyColor($stat[$key]["ill"]);?></td>-->
<td><?php setColor($stat[$key]["min"]);?></td>
<td><?php setColor($stat[$key]["average"]);?></td>
<td><?php setColor($stat[$key]["max"]);?></td>
<td><?php setGreyColor($stat[$key]["min_count"]);?></td>
<td><?php setGreyColor($stat[$key]["same_count"]);?></td>
<td><?php setGreyColor($stat[$key]["max_count"]);?></td>
</tr>
<?php
$i++; } }?>
</tbody>
</table>
</div>
</div>
<?php
if(!isset($stat)) {
?>
<div class="alert alert-info" role="alert">Данных нет</div>
<?php } ?>
</div>
<script type="text/javascript">
document.getElementById('year').value = "<?php echo $this->uri->segment(3);?>";
document.getElementById('period').value = "<?php echo $this->uri->segment(4);?>";
$("#period").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
$("#year").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
</script><file_sep>/application/views/pupil/timetableview.php
<div class="container">
<div class="row">
<?php
for ($i = 1; $i <= 6; $i++) {
?>
<div class="col-xs-12 col-md-4">
<h3 class="sidebar-header"><i class="fa fa-calendar"></i> <?php echo $days[$i-1]?></h3>
<div class="panel panel-default">
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th style="width: 30%">Время</th>
<th style="width: 50%">Предмет</th>
<th style="width: 20%">Каб.</th>
</tr>
</thead>
<tbody>
<?php
for ($k = 0; $k < count($timetable[$i-1]); $k++) {
?>
<tr>
<td id="time" class="timetable-time" style="vertical-align: middle;"><?php echo date("H:i", strtotime($timetable[$i-1][$k]["start"])).' - '
.date("H:i",strtotime($timetable[$i-1][$k]["finish"]));?></td>
<td><?php echo $timetable[$i-1][$k]["name"];?></td>
<td id="room"><?php echo $timetable[$i-1][$k]["room"]; }?></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<?php if ($i==3) {?>
<div class="clearfix visible-md visible-xs visible-lg"></div>
<?php } ?>
<?php }?>
</div>
</div><file_sep>/application/views/blankview/blanktypeview.php
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><?php echo $title; ?></div>
<div class="panel-body">
<form method="post">
<div hidden="true" id="id"><?php if(isset($id)) echo $id;?></div>
<div class="form-horizontal">
<div class="form-group">
<label for="inputType" class="col-sm-2 col-md-2 control-label">Тип оценки <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<input type="text" class="form-control" id="inputType" name="inputType" placeholder="Наименование типа оценки" required="true" maxlength="100" autofocus value="<?php if(isset($type)) echo $type;?>">
<div class="red" id="responseTypeError"></div>
</div>
</div>
</div>
<div class="grey">* - Обязательные поля</div>
<div id="error" class="red"></div>
<div class="modal-footer" style="margin-bottom: -15px; padding-right: 0px;">
<button type="button" class="btn btn-default" onclick="javascript:history.back();" title="Отменить">Отменить</button>
<button type="submit" class="btn btn-sample" name="save" id="save" title="Сохранить">Сохранить</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#save').click(function() {
var base_url = '<?php echo base_url();?>';
var s = 0;
var error = 0;
var type_name = $.trim($('#inputType').val());
var id = $('#id').text();
if (type_name.length == 0) {
$('#inputType').parent().addClass("has-error");
$("#responseTypeError").text('');
s++;
} else {
$('#inputType').parent().removeClass("has-error");
$.ajax({
type: "POST",
url: base_url + "table/responsetype",
data: "name=" + type_name + "&id=" + id,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
if (response == true) {
$("#responseTypeError").text('В списке уже есть такой тип оценки');
$('#inputType').parent().addClass("has-error");
error++;
}
if (response == false) {
$("#responseTypeError").text('');
$('#inputType').parent().removeClass("has-error");
}
}
});
}
if (s != 0) {
$("#error").text('Не все обязательные поля заполнены');
}
else {
$("#error").text('');
}
//alert(s + " " + error);
if (s == 0 && error == 0) {
} else {
return false;
}
});
});
</script>
<file_sep>/application/models/tablemodel.php
<?php
class Tablemodel extends CI_Model {
function deleteRoom($id) {
$this->db->where('ROOM_ID', $id);
$this->db->delete('ROOM');
}
function deleteSubject($id) {
$this->db->where('SUBJECT_ID', $id);
$this->db->delete('SUBJECT');
}
function deleteType($id) {
$this->db->where('TYPE_ID', $id);
$this->db->delete('TYPE');
}
function deleteLesson($id) {
$this->db->where('LESSON_ID', $id);
$this->db->delete('LESSON');
}
function deleteMark($id) {
$this->db->where('ACHIEVEMENT_ID', $id);
$this->db->delete('ACHIEVEMENT');
}
function deleteYear($id) {
$this->db->where('YEAR_ID', $id);
$this->db->delete('YEAR');
}
function deleteNews($id) {
$this->db->where('NEWS_ID', $id);
$this->db->delete('NEWS');
}
function deleteClass($id) {
$this->db->where('CLASS_ID', $id);
$this->db->delete('CLASS');
}
function deletePupil($id) {
$this->db->where('PUPIL_ID', $id);
$this->db->delete('PUPIL');
}
function deleteTeacher($id) {
$this->db->where('TEACHER_ID', $id);
$this->db->delete('TEACHER');
}
function deleteTimetable($id) {
$this->db->where('TIMETABLE_ID', $id);
$this->db->delete('TIMETABLE');
}
function deleteSubjectsClass($id) {
$this->db->where('SUBJECTS_CLASS_ID', $id);
$this->db->delete('SUBJECTS_CLASS');
}
function deleteMessage($id, $from, $to) {
$query = $this->db->query("SELECT MESSAGE_ID FROM ".$from."S_MESSAGE WHERE ".$from."S_MESSAGE_ID = '$id'");
$message_id = $query->row_array()['MESSAGE_ID'];
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM ".$to."S_MESSAGE WHERE MESSAGE_ID = '$message_id'");
$count = $query->row_array()['COUNT'];
if($count == 0) {
$this->db->where('MESSAGE_ID', $message_id);
$this->db->delete('MESSAGE');
}
$this->db->where($from."S_MESSAGE_ID", $id);
$this->db->delete($from."S_MESSAGE");
}
function deleteConversation($user, $id, $from, $to) {
$query = $this->db->query("SELECT ".$from."S_MESSAGE_ID
AS USER_MESSAGE_ID FROM ".$from."S_MESSAGE WHERE ".$from."_ID = '$user' AND ".$to."_ID = '$id'");
$messages = $query->result_array();
foreach($messages as $message) {
$message_id = $message['USER_MESSAGE_ID'];
$this->deleteMessage($message_id, $from, $to);
}
}
function deleteTeacherMessage($id) {
$query = $this->db->query("SELECT MESSAGE_ID FROM TEACHERS_MESSAGE WHERE TEACHERS_MESSAGE_ID = '$id'");
$message_id = $query->row_array()['MESSAGE_ID'];
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM PUPILS_MESSAGE WHERE MESSAGE_ID = '$message_id'");
$count = $query->row_array()['COUNT'];
if($count == 0) {
$this->db->where('MESSAGE_ID', $message_id);
$this->db->delete('MESSAGE');
}
$this->db->where('TEACHERS_MESSAGE_ID', $id);
$this->db->delete('TEACHERS_MESSAGE');
}
function responseSubjectName($subject, $id) {
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM SUBJECT
WHERE SUBJECT_NAME = '$subject' AND SUBJECT_ID != '$id'");
return $query->row_array();
}
function addSubject($subject) {
$this->db->set('SUBJECT_NAME', $subject);
$this->db->insert('SUBJECT');
}
function updateSubject($subject, $id) {
$this->db->set('SUBJECT_NAME', $subject);
$this->db->where('SUBJECT_ID', $id);
$this->db->update('SUBJECT');
}
function responseRoomName($room, $id) {
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM ROOM
WHERE ROOM_NAME = '$room' AND ROOM_ID != '$id'");
return $query->row_array();
}
function addRoom($room) {
$this->db->set('ROOM_NAME', $room);
$this->db->insert('ROOM');
}
function updateRoom($room, $id) {
$this->db->set('ROOM_NAME', $room);
$this->db->where('ROOM_ID', $id);
$this->db->update('ROOM');
}
function responseTypeName($name, $id) {
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM TYPE
WHERE TYPE_NAME = '$name' AND TYPE_ID != '$id'");
return $query->row_array();
}
function addType($name) {
$this->db->set('TYPE_NAME', $name);
$this->db->insert('TYPE');
}
function updateType($name, $id) {
$this->db->set('TYPE_NAME', $name);
$this->db->where('TYPE_ID', $id);
$this->db->update('TYPE');
}
function addNews($theme, $date, $text, $user) {
$this->db->set('NEWS_THEME', $theme);
$this->db->set('NEWS_TIME', $date);
$this->db->set('NEWS_TEXT', $text);
$this->db->set('TEACHER_ID', $user);
$this->db->insert('NEWS');
}
function updateNews($id, $theme, $date, $text, $user) {
$this->db->set('NEWS_THEME', $theme);
$this->db->set('NEWS_TIME', $date);
$this->db->set('NEWS_TEXT', $text);
$this->db->set('TEACHER_ID', $user);
$this->db->where('NEWS_ID', $id);
$this->db->update('NEWS');
}
function responseClass($id, $number, $letter, $year, $status) {
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM CLASS
WHERE CLASS_NUMBER = '$number' AND CLASS_LETTER = '$letter' AND CLASS_STATUS = '$status' AND YEAR_ID = '$year' AND CLASS_ID != '$id'");
return $query->row_array();
}
function addClass($number, $letter, $year, $status, $teacher, $previous) {
$this->db->set('CLASS_NUMBER', $number);
$this->db->set('CLASS_LETTER', $letter);
if($year != "") {
$this->db->set('YEAR_ID', $year);
}
if($status !="") {
$this->db->set('CLASS_STATUS', $status);
}
$this->db->set('TEACHER_ID', $teacher);
if($previous == "") {
$this->db->insert('CLASS');
} else {
$this->db->set('CLASS_PREVIOUS', $previous);
$this->db->insert('CLASS');
$id = $this->db->insert_id();
$query = $this->db->query("SELECT PUPIL_ID FROM PUPILS_CLASS WHERE CLASS_ID = '$previous'");
$pupils = $query->result_array();
foreach($pupils as $pupil) {
$pupil_id = $pupil['PUPIL_ID'];
$this->db->set('PUPIL_ID', $pupil_id);
$this->db->set('CLASS_ID', $id);
$this->db->insert('PUPILS_CLASS');
}
$this->db->set('CLASS_STATUS', 0);
$this->db->where('CLASS_ID', $previous);
$this->db->update('CLASS');
}
}
function updateClass($id, $number, $letter, $year, $status, $teacher, $previous) {
$this->db->set('CLASS_NUMBER', $number);
$this->db->set('CLASS_LETTER', $letter);
if($year != "") {
$this->db->set('YEAR_ID', $year);
}
if($status !="") {
$this->db->set('CLASS_STATUS', $status);
}
$this->db->set('TEACHER_ID', $teacher);
if($previous == "") {
$this->db->where('CLASS_ID', $id);
$this->db->update('CLASS');
} else {
$this->db->set('CLASS_PREVIOUS', $previous);
$this->db->where('CLASS_ID', $id);
$this->db->update('CLASS');
$query = $this->db->query("SELECT PUPIL_ID FROM PUPILS_CLASS WHERE CLASS_ID = '$previous'");
$pupils = $query->result_array();
foreach($pupils as $pupil) {
$pupil_id = $pupil['PUPIL_ID'];
$this->db->set('PUPIL_ID', $pupil_id);
$this->db->set('CLASS_ID', $id);
$this->db->insert('PUPILS_CLASS');
}
$this->db->set('CLASS_STATUS', 0);
$this->db->where('CLASS_ID', $previous);
$this->db->update('CLASS');
}
}
function responseTeacherLogin($id, $login) {
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM TEACHER
WHERE TEACHER_LOGIN = '$login' AND TEACHER_ID != '$id'");
return $query->row_array();
}
function responsePupilLogin($id, $login) {
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM PUPIL
WHERE PUPIL_LOGIN = '$login' AND PUPIL_ID != '$id'");
return $query->row_array();
}
function addTeacher($name, $password, $login, $status, $hash) {
$this->db->set('TEACHER_NAME', $name);
$this->db->set('TEACHER_PASSWORD', $password);
$this->db->set('TEACHER_LOGIN', $login);
$this->db->set('TEACHER_STATUS', $status);
$this->db->set('TEACHER_HASH', $hash);
$this->db->set('ROLE_ID', 3);
$this->db->insert('TEACHER');
}
function updateTeacher($id, $name, $password, $login, $status, $hash) {
$this->db->set('TEACHER_NAME', $name);
$this->db->set('TEACHER_PASSWORD', $password);
$this->db->set('TEACHER_LOGIN', $login);
$this->db->set('TEACHER_STATUS', $status);
$this->db->set('TEACHER_HASH', $hash);
$this->db->set('ROLE_ID', 3);
$this->db->where('TEACHER_ID', $id);
$this->db->update('TEACHER');
}
function responseClassTeacher($id, $year, $teacher) {
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM CLASS
WHERE TEACHER_ID = '$teacher' AND CLASS_ID != '$id' AND YEAR_ID = '$year'");
return $query->row_array();
}
function addYearAndPeriods($year_start, $year_finish, $first_start, $first_finish, $second_start, $second_finish, $third_start,$third_finish, $forth_start, $forth_finish) {
$this->db->set('YEAR_START', $year_start);
$this->db->set('YEAR_FINISH', $year_finish);
$this->db->insert('YEAR');
$id = $this->db->insert_id();
$this->db->set('PERIOD_START', $first_start);
$this->db->set('PERIOD_FINISH', $first_finish);
$this->db->set('PERIOD_NAME', 'I четверть');
$this->db->set('YEAR_ID', $id);
$this->db->insert('PERIOD');
$this->db->set('PERIOD_START', $second_start);
$this->db->set('PERIOD_FINISH', $second_finish);
$this->db->set('PERIOD_NAME', 'II четверть');
$this->db->set('YEAR_ID', $id);
$this->db->insert('PERIOD');
$this->db->set('PERIOD_START', $third_start);
$this->db->set('PERIOD_FINISH', $third_finish);
$this->db->set('PERIOD_NAME', 'III четверть');
$this->db->set('YEAR_ID', $id);
$this->db->insert('PERIOD');
$this->db->set('PERIOD_START', $forth_start);
$this->db->set('PERIOD_FINISH', $forth_finish);
$this->db->set('PERIOD_NAME', 'IV четверть');
$this->db->set('YEAR_ID', $id);
$this->db->insert('PERIOD');
$this->db->set('PERIOD_START', $year_start);
$this->db->set('PERIOD_FINISH', $year_finish);
$this->db->set('PERIOD_NAME', 'Итоговая');
$this->db->set('YEAR_ID', $id);
$this->db->insert('PERIOD');
}
function updateYearAndPeriods($id, $year_start, $year_finish, $first_start, $first_finish, $second_start, $second_finish, $third_start,$third_finish, $forth_start, $forth_finish) {
$this->db->set('YEAR_START', $year_start);
$this->db->set('YEAR_FINISH', $year_finish);
$this->db->where('YEAR_ID', $id);
$this->db->update('YEAR');
$this->db->set('PERIOD_START', $first_start);
$this->db->set('PERIOD_FINISH', $first_finish);
$this->db->where('PERIOD_NAME', 'I четверть');
$this->db->where('YEAR_ID', $id);
$this->db->update('PERIOD');
$this->db->set('PERIOD_START', $second_start);
$this->db->set('PERIOD_FINISH', $second_finish);
$this->db->where('PERIOD_NAME', 'II четверть');
$this->db->where('YEAR_ID', $id);
$this->db->update('PERIOD');
$this->db->set('PERIOD_START', $third_start);
$this->db->set('PERIOD_FINISH', $third_finish);
$this->db->where('PERIOD_NAME', 'III четверть');
$this->db->where('YEAR_ID', $id);
$this->db->update('PERIOD');
$this->db->set('PERIOD_START', $forth_start);
$this->db->set('PERIOD_FINISH', $forth_finish);
$this->db->where('PERIOD_NAME', 'IV четверть');
$this->db->where('YEAR_ID', $id);
$this->db->update('PERIOD');
$this->db->set('PERIOD_START', $year_start);
$this->db->set('PERIOD_FINISH', $year_finish);
$this->db->where('PERIOD_NAME', 'Итоговая');
$this->db->where('YEAR_ID', $id);
$this->db->update('PERIOD');
}
//$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM PUPILS_CLASS
//WHERE CLASS_ID = '$previous'");
//SELECT COUNT(*) AS COUNT FROM CLASS
//WHERE CLASS_PREVIOUS = '$previous'
function responseClassPrevious($previous) {
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM CLASS
WHERE CLASS_PREVIOUS = '$previous'");
return $query->row_array();
}
function addPupil($name, $password, $login, $status, $hash, $address, $phone, $birthday, $class_id) {
$this->db->set('PUPIL_NAME', $name);
$this->db->set('PUPIL_PASSWORD', $password);
$this->db->set('PUPIL_LOGIN', $login);
$this->db->set('PUPIL_STATUS', $status);
$this->db->set('PUPIL_HASH', $hash);
$this->db->set('ROLE_ID', 4);
$this->db->set('PUPIL_ADDRESS', $address);
if($birthday == "") {
$this->db->set('PUPIL_BIRTHDAY', NULL);
} else {
$this->db->set('PUPIL_BIRTHDAY', $birthday);
}
$this->db->set('PUPIL_PHONE', $phone);
$this->db->insert('PUPIL');
$id = $this->db->insert_id();
$this->db->set('PUPIL_ID', $id);
$this->db->set('CLASS_ID', $class_id);
$this->db->insert('PUPILS_CLASS');
}
function updatePupil($id, $name, $password, $login, $status, $hash, $address, $phone, $birthday) {
$this->db->set('PUPIL_NAME', $name);
$this->db->set('PUPIL_PASSWORD', $password);
$this->db->set('PUPIL_LOGIN', $login);
$this->db->set('PUPIL_STATUS', $status);
$this->db->set('PUPIL_HASH', $hash);
$this->db->set('ROLE_ID', 4);
$this->db->set('PUPIL_ADDRESS', $address);
if($birthday == "") {
$this->db->set('PUPIL_BIRTHDAY', NULL);
} else {
$this->db->set('PUPIL_BIRTHDAY', $birthday);
}
$this->db->set('PUPIL_PHONE', $phone);
$this->db->where('PUPIL_ID', $id);
$this->db->update('PUPIL');
}
function responseSubjectsClass($id, $teacher, $subject, $class_id) {
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM SUBJECTS_CLASS
WHERE SUBJECTS_CLASS_ID != '$id' AND TEACHER_ID = '$teacher' AND SUBJECT_ID = '$subject' AND CLASS_ID = '$class_id'");
return $query->row_array();
}
function addSubjectsClass($teacher, $subject, $class_id) {
$this->db->set('TEACHER_ID', $teacher);
$this->db->set('SUBJECT_ID', $subject);
$this->db->set('CLASS_ID', $class_id);
$this->db->insert('SUBJECTS_CLASS');
}
function updateSubjectsClass($id, $teacher, $subject, $class_id) {
$this->db->set('TEACHER_ID', $teacher);
$this->db->set('SUBJECT_ID', $subject);
$this->db->set('CLASS_ID', $class_id);
$this->db->where('SUBJECTS_CLASS_ID', $id);
$this->db->update('SUBJECTS_CLASS');
}
function responseTimetable($id, $time, $day, $class_id) {
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM TIMETABLE t JOIN SUBJECTS_CLASS sc ON t.SUBJECTS_CLASS_ID = sc.SUBJECTS_CLASS_ID
WHERE t.TIMETABLE_ID != '$id' AND TIME_ID = '$time' AND DAYOFWEEK_ID = '$day' AND CLASS_ID = '$class_id'");
return $query->row_array();
}
function addTimetable($time, $subject, $day, $room) {
$this->db->set('TIME_ID', $time);
$this->db->set('SUBJECTS_CLASS_ID', $subject);
$this->db->set('DAYOFWEEK_ID', $day);
if($room == "") {
$this->db->set('ROOM_ID', NULL);
} else {
$this->db->set('ROOM_ID', $room);
}
$this->db->insert('TIMETABLE');
}
function updateTimetable($id, $time, $subject, $day, $room) {
$this->db->set('TIME_ID', $time);
$this->db->set('SUBJECTS_CLASS_ID', $subject);
$this->db->set('DAYOFWEEK_ID', $day);
if($room == "") {
$this->db->set('ROOM_ID', NULL);
} else {
$this->db->set('ROOM_ID', $room);
}
$this->db->where('TIMETABLE_ID', $id);
$this->db->update('TIMETABLE');
}
function responseYear($id, $start, $finish) {
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM YEAR
WHERE YEAR_ID != '$id' AND YEAR(YEAR_START) = '$start' AND YEAR(YEAR_FINISH) = '$finish'");
return $query->row_array();
}
function getSearchTeachers($search) {
$query = $this->db->query("SELECT TEACHER_ID AS ID, TEACHER_NAME AS NAME
FROM TEACHER
WHERE TEACHER_ID != '13' AND IFNULL(TEACHER_NAME, '') LIKE '%$search%'
ORDER BY TEACHER_NAME");
return $query->result_array();
}
function getSearchPupils($search) {
$query = $this->db->query("SELECT PUPIL_ID AS ID, PUPIL_NAME AS NAME
FROM PUPIL
WHERE IFNULL(PUPIL_NAME, '') LIKE '%$search%'
ORDER BY PUPIL_NAME");
return $query->result_array();
}
/*function addPupilMessage($from, $to, $text, $date) {
$this->db->set('MESSAGE_TEXT', $text);
$this->db->set('MESSAGE_DATE', $date);
$this->db->insert('MESSAGE');
$message_id = $this->db->insert_id();
$this->db->set('MESSAGE_FOLDER', 2);
$this->db->set('MESSAGE_ID', $message_id);
$this->db->set('TEACHER_ID', $to);
$this->db->set('PUPIL_ID', $from);
$this->db->set('MESSAGE_READ', 0);
$this->db->insert('PUPILS_MESSAGE');
$this->db->set('MESSAGE_FOLDER', 1);
$this->db->set('MESSAGE_ID', $message_id);
$this->db->set('TEACHER_ID', $to);
$this->db->set('PUPIL_ID', $from);
$this->db->set('MESSAGE_READ', 0);
$this->db->insert('TEACHERS_MESSAGE');
}
function addTeacherMessage($from, $to, $text, $date) {
$this->db->set('MESSAGE_TEXT', $text);
$this->db->set('MESSAGE_DATE', $date);
$this->db->insert('MESSAGE');
$message_id = $this->db->insert_id();
$this->db->set('MESSAGE_FOLDER', 2);
$this->db->set('MESSAGE_ID', $message_id);
$this->db->set('PUPIL_ID', $to);
$this->db->set('TEACHER_ID', $from);
$this->db->set('MESSAGE_READ', 0);
$this->db->insert('TEACHERS_MESSAGE');
$this->db->set('MESSAGE_FOLDER', 1);
$this->db->set('MESSAGE_ID', $message_id);
$this->db->set('PUPIL_ID', $to);
$this->db->set('TEACHER_ID', $from);
$this->db->set('MESSAGE_READ', 0);
$this->db->insert('PUPILS_MESSAGE');
}*/
function readMessage($id, $from, $to) {
$this->db->set('MESSAGE_READ', 1);
$this->db->where($from."S_MESSAGE_ID", $id);
$this->db->update($from."S_MESSAGE");
}
function changeLessonStatus($lesson, $status) {
$this->db->set('LESSON_STATUS', $status);
$this->db->where("LESSON_ID", $lesson);
$this->db->update("LESSON");
}
function changeProgress($pupil_id, $subject_id, $period, $class_id, $mark) {
$query = $this->db->query("SELECT PROGRESS_ID, PROGRESS_MARK
FROM PROGRESS p JOIN PERIOD pe ON p.PERIOD_ID = pe.PERIOD_ID
WHERE PUPIL_ID = '$pupil_id' AND SUBJECTS_CLASS_ID = '$subject_id' AND PERIOD_NAME = '$period'
AND YEAR_ID = (SELECT YEAR_ID FROM CLASS WHERE CLASS_ID = '$class_id')");
$progress = $query->row_array();
if(isset($progress)) {
if($mark == "") {
//удаление
$this->db->where('PROGRESS_ID', $progress['PROGRESS_ID']);
$this->db->delete('PROGRESS');
} else {
//обновление
$this->db->set('PROGRESS_MARK', $mark);
$this->db->where('PROGRESS_ID', $progress['PROGRESS_ID']);
$this->db->update('PROGRESS');
}
} else {
//добавление
$query = $this->db->query("SELECT PERIOD_ID FROM PERIOD
WHERE YEAR_ID = (SELECT YEAR_ID FROM CLASS WHERE CLASS_ID = '$class_id') AND PERIOD_NAME = '$period'");
$this->db->set('PUPIL_ID', $pupil_id);
$this->db->set('PROGRESS_MARK', $mark);
$this->db->set('SUBJECTS_CLASS_ID', $subject_id);
$this->db->set('PERIOD_ID', $query->row_array()['PERIOD_ID']);
$this->db->insert('PROGRESS');
}
}
function changeAttendance($pupil_id, $lesson_id, $attendance_id, $pass) {
if($attendance_id != "") {
if ($pass == "") {
//удаление
$this->db->where('ATTENDANCE_ID', $attendance_id);
$this->db->delete('ATTENDANCE');
} else {
//обновление
$this->db->set('ATTENDANCE_PASS', $pass);
$this->db->where('ATTENDANCE_ID', $attendance_id);
$this->db->update('ATTENDANCE');
}
} else {
//добавление
$this->db->set('PUPIL_ID', $pupil_id);
$this->db->set('ATTENDANCE_PASS', $pass);
$this->db->set('LESSON_ID', $lesson_id);
$this->db->insert('ATTENDANCE');
}
}
function readConversation($user, $id, $from, $to) {
$this->db->set('MESSAGE_READ', 1);
$this->db->where($from."_ID", $user);
$this->db->where($to."_ID", $id);
$this->db->update($from."S_MESSAGE");
}
function addMessage($id, $user, $text, $date, $from, $to) {
$this->db->set('MESSAGE_TEXT', $text);
$this->db->set('MESSAGE_DATE', $date);
$this->db->insert('MESSAGE');
$message_id = $this->db->insert_id();
$this->db->set('MESSAGE_FOLDER', 2);
$this->db->set('MESSAGE_ID', $message_id);
$this->db->set($to."_ID", $user);
$this->db->set($from."_ID", $id);
$this->db->set('MESSAGE_READ', 0);
$this->db->insert($from."S_MESSAGE");
$this->db->set('MESSAGE_FOLDER', 1);
$this->db->set('MESSAGE_ID', $message_id);
$this->db->set($to."_ID", $user);
$this->db->set($from."_ID", $id);
$this->db->set('MESSAGE_READ', 0);
$this->db->insert($to."S_MESSAGE");
$message_id = $this->db->insert_id();
return $message_id;
}
/*function responseLesson($id, $date, $time, $subject) {
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM LESSON
WHERE LESSON_ID != '$id' AND SUBJECTS_CLASS_ID = '$subject' AND LESSON_DATE = '$date' AND TIME_ID = '$time'");
return $query->row_array();
}*/
function responseLesson($id, $date, $time, $subject) {
$day = date("w", strtotime($date));
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM LESSON
WHERE LESSON_ID != '$id' AND SUBJECTS_CLASS_ID = '$subject' AND LESSON_DATE = '$date' AND TIME_ID = '$time'");
$arr = $query->row_array();
if($arr['COUNT'] == 0) {
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM TIMETABLE
WHERE SUBJECTS_CLASS_ID = '$subject' AND DAYOFWEEK_ID = '$day' AND TIME_ID = '$time'");
$arr = $query->row_array();
if($arr['COUNT'] == 0) {
return 2;
} else {
return 0;
}
} else {
return 1;
}
}
function addLesson($subject, $theme, $date, $time, $homework, $status) {
$this->db->set('LESSON_THEME', $theme);
$this->db->set('LESSON_DATE', $date);
$this->db->set('LESSON_HOMEWORK', $homework);
$this->db->set('TIME_ID', $time);
$this->db->set('SUBJECTS_CLASS_ID', $subject);
$this->db->set('LESSON_STATUS', $status);
$this->db->insert('LESSON');
return $this->db->insert_id();
}
function updateLesson($id, $subject, $theme, $date, $time, $homework, $status) {
$this->db->set('LESSON_THEME', $theme);
$this->db->set('LESSON_DATE', $date);
$this->db->set('LESSON_HOMEWORK', $homework);
$this->db->set('TIME_ID', $time);
$this->db->set('SUBJECTS_CLASS_ID', $subject);
$this->db->set('LESSON_STATUS', $status);
$this->db->where('LESSON_ID', $id);
$this->db->update('LESSON');
}
function addFile($size, $ext, $name, $id) {
$this->db->set('FILE_NAME', $name);
$this->db->set('FILE_SIZE', $size);
$this->db->set('FILE_EXTENSION', $ext);
$this->db->set('LESSON_ID', $id);
$this->db->insert('FILE');
return $this->db->insert_id();
}
function changeAchievement($pupil_id, $lesson_id, $achievement_id, $mark, $type) {
if(isset($achievement_id) && $achievement_id != "") {
//обновление
$this->db->set('ACHIEVEMENT_MARK', $mark);
$this->db->set('TYPE_ID', $type);
$this->db->where('ACHIEVEMENT_ID', $achievement_id);
$this->db->update('ACHIEVEMENT');
} else {
//добавление
$this->db->set('PUPIL_ID', $pupil_id);
$this->db->set('ACHIEVEMENT_MARK', $mark);
$this->db->set('LESSON_ID', $lesson_id);
$this->db->set('TYPE_ID', $type);
$this->db->insert('ACHIEVEMENT');
}
}
function changeNote($pupil_id, $lesson_id, $note_id, $note) {
if($note_id != "") {
if ($note == "") {
//удаление
$this->db->where('NOTE_ID', $note_id);
$this->db->delete('NOTE');
} else {
//обновление
$this->db->set('NOTE_TEXT', $note);
$this->db->where('NOTE_ID', $note_id);
$this->db->update('NOTE');
}
} else {
//добавление
$this->db->set('PUPIL_ID', $pupil_id);
$this->db->set('NOTE_TEXT', $note);
$this->db->set('LESSON_ID', $lesson_id);
$this->db->insert('NOTE');
}
}
function getGCMIDs($pupil_id) {
$query = $this->db->query("SELECT * FROM GCM_USERS WHERE PUPIL_ID = '$pupil_id'");
return $query->result_array();
}
function getSubjectNameByLessonId($lesson_id) {
$query = $this->db->query("SELECT SUBJECT_NAME FROM SUBJECT s JOIN SUBJECTS_CLASS sc ON s.SUBJECT_ID = sc.SUBJECT_ID
JOIN LESSON l ON l.SUBJECTS_CLASS_ID = sc.SUBJECTS_CLASS_ID WHERE LESSON_ID = '$lesson_id'");
return $query->row_array();
}
function getTypeById($type_id) {
$query = $this->db->query("SELECT TYPE_NAME FROM TYPE WHERE TYPE_ID = '$type_id'");
return $query->row_array();
}
function getLessonById($lesson_id) {
$query = $this->db->query("SELECT * FROM LESSON WHERE LESSON_ID = '$lesson_id'");
return $query->row_array();
}
function getPupilProgressMark($pupil_id, $subject_id, $period, $class_id, $mark) {
$query = $this->db->query("SELECT PROGRESS_ID, p.PERIOD_ID
FROM PROGRESS p JOIN PERIOD pe ON p.PERIOD_ID = pe.PERIOD_ID
WHERE PUPIL_ID = '$pupil_id' AND SUBJECTS_CLASS_ID = '$subject_id' AND PERIOD_NAME = '$period'
AND YEAR_ID = (SELECT YEAR_ID FROM CLASS WHERE CLASS_ID = '$class_id')");
return $query->row_array();
}
}
<file_sep>/application/views/blankview/blankyearview.php
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><?php echo $title; ?></div>
<div class="panel-body">
<form method="post">
<div hidden="true" id="id"><?php if(isset($id)) echo $id;?></div>
<div class="form-horizontal">
<div class="form-group">
<label for="inputYearStart" class="col-sm-2 col-md-2 control-label">Начало учебного года <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<input type="text" class="form-control" id="inputYearStart" name="inputYearStart" placeholder="гггг-мм-дд" required="true" value="<?php if(isset($info["fifth"]["start"])) echo $info["fifth"]["start"]; ?>">
</div>
</div>
<div class="form-group">
<label for="inputYearFinish" class="col-sm-2 col-md-2 control-label">Окончание учебного года <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<input type="text" class="form-control" id="inputYearFinish" name="inputYearFinish" placeholder="гггг-мм-дд" required="true" value="<?php if(isset($info["fifth"]["finish"])) echo $info["fifth"]["finish"]; ?>">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="inputFirstStart">Начало I четверти <span class="star">*</span></label>
<input readonly="true" type="text" class="form-control" id="inputFirstStart" name="inputFirstStart" placeholder="гггг-мм-дд" required="true" value="<?php if(isset($info["first"]["start"])) echo $info["first"]["start"]; ?>">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="inputFirstFinish">Конец I четверти <span class="star">*</span></label>
<input type="text" class="form-control" id="inputFirstFinish" name="inputFirstFinish" placeholder="гггг-мм-дд" required="true" value="<?php if(isset($info["first"]["finish"])) echo $info["first"]["finish"]; ?>">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="inputSecondStart">Начало II четверти <span class="star">*</span></label>
<input type="text" class="form-control" id="inputSecondStart" name="inputSecondStart" placeholder="гггг-мм-дд" required="true" value="<?php if(isset($info["second"]["start"])) echo $info["second"]["start"]; ?>">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="inputSecondFinish">Конец II четверти <span class="star">*</span></label>
<input type="text" class="form-control" id="inputSecondFinish" name="inputSecondFinish" placeholder="гггг-мм-дд" required="true" value="<?php if(isset($info["second"]["finish"])) echo $info["second"]["finish"]; ?>">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="inputThirdStart">Начало III четверти <span class="star">*</span></label>
<input type="text" class="form-control" id="inputThirdStart" name="inputThirdStart" placeholder="гггг-мм-дд" required="true" value="<?php if(isset($info["third"]["start"])) echo $info["third"]["start"]; ?>">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="inputThirdFinish">Конец III четверти <span class="star">*</span></label>
<input type="text" class="form-control" id="inputThirdFinish" name="inputThirdFinish" placeholder="гггг-мм-дд" required="true" value="<?php if(isset($info["third"]["finish"])) echo $info["third"]["finish"]; ?>">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="inputForthStart">Начало IV четверти <span class="star">*</span></label>
<input type="text" class="form-control" id="inputForthStart" name="inputForthStart" placeholder="гггг-мм-дд" required="true" value="<?php if(isset($info["forth"]["start"])) echo $info["forth"]["start"]; ?>">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="inputForthFinish">Конец IV четверти <span class="star">*</span></label>
<input readonly="true" type="text" class="form-control" id="inputForthFinish" name="inputForthFinish" placeholder="гггг-мм-дд" required="true" value="<?php if(isset($info["forth"]["finish"])) echo $info["forth"]["finish"]; ?>">
</div>
</div>
</div>
<div class="red" id="responseDateError"></div>
<div class="grey">* - Обязательные поля</div>
<div id="error" class="red"></div>
<div class="modal-footer" style="margin-bottom: -15px; padding-right: 0px;">
<button type="button" class="btn btn-default" onclick="javascript:history.back();" title="Отменить">Отменить</button>
<button type="submit" class="btn btn-sample" name="save" id="save" title="Сохранить">Сохранить</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#inputYearStart').datepicker({
format: 'yyyy-mm-dd',
startDate: "1993-01-01",
language: "ru",
todayBtn: "linked",
autoclose: true,
todayHighlight: true
});
$('#inputYearFinish').datepicker({
format: 'yyyy-mm-dd',
startDate: "1993-01-01",
language: "ru",
todayBtn: "linked",
autoclose: true,
todayHighlight: true
});
$('#inputFirstFinish').datepicker({
format: 'yyyy-mm-dd',
startDate: "1993-01-01",
language: "ru",
todayBtn: "linked",
autoclose: true,
todayHighlight: true
});
$('#inputSecondStart').datepicker({
format: 'yyyy-mm-dd',
startDate: "1993-01-01",
language: "ru",
todayBtn: "linked",
autoclose: true,
todayHighlight: true
});
$('#inputSecondFinish').datepicker({
format: 'yyyy-mm-dd',
startDate: "1993-01-01",
language: "ru",
todayBtn: "linked",
autoclose: true,
todayHighlight: true
});
$('#inputThirdStart').datepicker({
format: 'yyyy-mm-dd',
startDate: "1993-01-01",
language: "ru",
todayBtn: "linked",
autoclose: true,
todayHighlight: true
});
$('#inputThirdFinish').datepicker({
format: 'yyyy-mm-dd',
startDate: "1993-01-01",
language: "ru",
todayBtn: "linked",
autoclose: true,
todayHighlight: true
});
$('#inputForthStart').datepicker({
format: 'yyyy-mm-dd',
startDate: "1993-01-01",
language: "ru",
todayBtn: "linked",
autoclose: true,
todayHighlight: true
});
$('#inputForthFinish').datepicker({
format: 'yyyy-mm-dd',
startDate: "1993-01-01",
language: "ru",
todayBtn: "linked",
autoclose: true,
todayHighlight: true
});
$("#inputYearStart").mask("9999-99-99");
$("#inputYearFinish").mask("9999-99-99");
$("#inputFirstStart").mask("9999-99-99");
$("#inputFirstFinish").mask("9999-99-99");
$("#inputSecondStart").mask("9999-99-99");
$("#inputSecondFinish").mask("9999-99-99");
$("#inputThirdStart").mask("9999-99-99");
$("#inputThirdFinish").mask("9999-99-99");
$("#inputForthStart").mask("9999-99-99");
$("#inputForthFinish").mask("9999-99-99");
/*$('#inputYearStart').focus(function() {
$(this).data('oldValue',$(this).val());
});*/
$('#inputYearStart').change(function(){
/*var date = $(this).val();
var oldValue = $(this).data('oldValue');
if(isValidDate($.trim(date)) && date.length == 10) {
//trigger focus to set new oldValue
$(this).trigger('focus');
$('#inputFirstStart').val(date);
} else {
$('#inputFirstStart').val(oldValue);
$(this).val(oldValue);
$(this).trigger('focus');
}*/
$('#inputFirstStart').val($(this).val());
});
$('#inputYearFinish').change(function(){
/*var date = $(this).val();
var oldValue = $(this).data('oldValue');
if(isValidDate($.trim(date)) && date.length == 10) {
//trigger focus to set new oldValue
$(this).trigger('focus');
$('#inputForthFinish').val(date);
} else {
$('#inputForthFinish').val(oldValue);
$(this).val(oldValue);
$(this).trigger('focus');
}*/
$('#inputForthFinish').val($(this).val());
});
$('#save').click(function() {
var base_url = '<?php echo base_url();?>';
var s = 0;
var error = 0;
var year_start = $('#inputYearStart').val();
var year_finish = $('#inputYearFinish').val();
var first_start = $('#inputFirstStart').val();
var first_finish = $('#inputFirstFinish').val();
var second_start = $('#inputSecondStart').val();
var second_finish = $('#inputSecondFinish').val();
var third_start = $('#inputThirdStart').val();
var third_finish = $('#inputThirdFinish').val();
var forth_start = $('#inputForthStart').val();
var forth_finish = $('#inputForthFinish').val();
var id = $('#id').text();
if (year_start.length == 0) {
$('#inputYearStart').parent().addClass("has-error");
$('#inputFirstStart').parent().addClass("has-error");
s++;
} else {
$('#inputYearStart').parent().removeClass("has-error");
$('#inputFirstStart').parent().removeClass("has-error");
}
if (year_finish.length == 0) {
$('#inputYearFinish').parent().addClass("has-error");
$('#inputForthFinish').parent().addClass("has-error");
s++;
} else {
$('#inputForthFinish').parent().removeClass("has-error");
$('#inputYearFinish').parent().removeClass("has-error");
}
if (first_finish.length == 0) {
$('#inputFirstFinish').parent().addClass("has-error");
s++;
} else {
$('#inputFirstFinish').parent().removeClass("has-error");
}
if (second_finish.length == 0) {
$('#inputSecondFinish').parent().addClass("has-error");
s++;
} else {
$('#inputSecondFinish').parent().removeClass("has-error");
}
if (second_start.length == 0) {
$('#inputSecondStart').parent().addClass("has-error");
s++;
} else {
$('#inputSecondStart').parent().removeClass("has-error");
}
if (third_start.length == 0) {
$('#inputThirdStart').parent().addClass("has-error");
s++;
} else {
$('#inputThirdStart').parent().removeClass("has-error");
}
if (third_finish.length == 0) {
$('#inputThirdFinish').parent().addClass("has-error");
s++;
} else {
$('#inputThirdFinish').parent().removeClass("has-error");
}
if (forth_start.length == 0) {
$('#inputForthStart').parent().addClass("has-error");
s++;
} else {
$('#inputForthStart').parent().removeClass("has-error");
}
if (forth_finish.length == 0) {
$('#inputForthFinish').parent().addClass("has-error");
s++;
} else {
$('#inputForthFinish').parent().removeClass("has-error");
}
$("#responseDateError").text('');
if (s != 0) {
$("#error").text('Не все обязательные поля заполнены');
}
else {
$("#error").text('');
if((year_start < year_finish) && (first_start < first_finish) && (second_start >= first_finish) &&
(second_start < second_finish) && (second_finish <= third_start) && (third_start < third_finish) &&
(third_finish <= forth_start) && (forth_start< forth_finish)) {
$("#responseDateError").text('');
$.ajax({
type: "POST",
url: base_url + "table/responseyear",
data: "id=" + id + "&yearstart=" + year_start + "&yearfinish=" + year_finish,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
if (response == true) {
$("#responseDateError").text('В списке уже есть учебный период с указанными годами');
error++;
}
if (response == false) {
$("#responseDateError").text('');
}
}
});
}
else {
error++;
$("#responseDateError").text('Есть ошибки в заполнении границ периодов. Проверьте правильность заполнения');
}
}
//alert(s + " " + error);
if (s == 0 && error == 0) {
/*if (id == "") {
$.ajax({
type: "POST",
url: base_url + "table/addyear",
data: "year_start=" + year_start + "&year_finish=" + year_finish +
"&first_start=" + first_start + "&first_finish=" + first_finish +
"&second_start=" + second_start + "&second_finish=" + second_finish +
"&third_start=" + third_start + "&third_finish=" + third_finish +
"&forth_start=" + forth_start + "&forth_finish=" + forth_finish,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
document.location.href = base_url + 'admin/years';
}
});
}
else {
$.ajax({
type: "POST",
url: base_url + "table/updateyear",
data: "year_start=" + year_start + "&year_finish=" + year_finish +
"&first_start=" + first_start + "&first_finish=" + first_finish +
"&second_start=" + second_start + "&second_finish=" + second_finish +
"&third_start=" + third_start + "&third_finish=" + third_finish +
"&forth_start=" + forth_start + "&forth_finish=" + forth_finish + "&id=" + id,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
document.location.href = base_url + 'admin/years';
}
});
}*/
} else return false;
});
});
</script>
<file_sep>/application/views/blankview/blankteacherview.php
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><?php echo $title; ?></div>
<div class="panel-body">
<form method="post">
<div hidden="true" id="id"><?php if(isset($id)) echo $id;?></div>
<div class="form-horizontal">
<div class="form-group">
<label for="inputName" class="col-sm-2 col-md-2 control-label">ФИО учителя <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<input type="text" class="form-control" id="inputName" name="inputName" placeholder="ФИО учителя" required="true" maxlength="100" autofocus value="<?php if(isset($name)) echo $name;?>">
</div>
</div>
<div class="form-group">
<label for="inputLogin" class="col-sm-2 col-md-2 control-label">Логин <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<input type="text" class="form-control" id="inputLogin" name="inputLogin" placeholder="Логин" required="true" maxlength="20" value="<?php if(isset($login)) echo $login;?>">
<div class="red" id="responseLoginError"></div>
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-sm-2 col-md-2 control-label">Пароль <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<span class="passEye"><input type="<PASSWORD>" class="form-control" id="inputPassword" name="inputPassword" placeholder="<PASSWORD>" required="true" maxlength="20" value="<?php if(isset($password)) echo $password;?>">
</span>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-md-2 control-label">Статус <span class="star">*</span></label>
<div class="col-sm-offset-2 col-sm-10" style="margin-top: -27.5px;">
<label class="radio-inline">
<input type="radio" name="inputStatus" value="1" <?php if(isset($status) && $status == 1) { echo "checked='checked'";} else echo "checked='checked'"; ?> >Активен
</label>
<label class="radio-inline">
<input type="radio" name="inputStatus" value="0" <?php if(isset($status) && $status == 0) { echo "checked='checked'";}?>>Не активен
</label>
</div>
</div>
<!--<label class="col-sm-2 control-label">Статус *</label>
<div class="col-sm-offset-2 col-sm-10">
<div class="radio">
<input type="radio" name="inputStatus" value="1" <?php if(isset($status) && $status == 1) { echo "checked='checked'";} else echo "checked='checked'"; ?> >Активен<br/>
<input type="radio" name="inputStatus" value="0" <?php if(isset($status) && $status == 0) { echo "checked='checked'";}?>>Не активен
</div>
</div>-->
</div>
<div class="grey">* - Обязательные поля</div>
<div id="error" class="red"></div>
<div class="modal-footer" style="margin-bottom: -15px; padding-right: 0px;">
<button type="button" class="btn btn-default" onclick="javascript:history.back();" title="Отменить">Отменить</button>
<button type="submit" class="btn btn-sample" name="save" id="save" title="Сохранить">Сохранить</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#save').click(function() {
var base_url = '<?php echo base_url();?>';
var s = 0;
var error = 0;
var name = $.trim($('#inputName').val());
var password = $.trim($('#inputPassword').val());
var login = $.trim($('#inputLogin').val());
var status = $("input[name='inputStatus']:checked").val();
var id = $('#id').text();
if (name.length == 0) {
$('#inputName').parent().addClass("has-error");
s++;
} else {
$('#inputName').parent().removeClass("has-error");
}
if (password.length == 0) {
$('#inputPassword').parent().addClass("has-error");
s++;
} else {
$('#inputPassword').parent().removeClass("has-error");
}
if (login.length == 0) {
$('#inputLogin').parent().addClass("has-error");
$("#responseLoginError").text('');
s++;
} else {
$('#inputLogin').parent().removeClass("has-error");
$.ajax({
type: "POST",
url: base_url + "table/responseteacherlogin",
data: "login=" + login + "&id=" + id,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
if (response == true) {
$("#responseLoginError").text('Логин должен быть уникальным');
$('#inputLogin').parent().addClass("has-error");
error++;
}
if (response == false) {
$("#responseLoginError").text('');
$('#inputLogin').parent().removeClass("has-error");
}
}
});
}
if (s != 0) {
$("#error").text('Не все обязательные поля заполнены');
}
else {
$("#error").text('');
}
//alert(s + " " + error);
if (s == 0 && error == 0) {
/*if (id == "") {
$.ajax({
type: "POST",
url: base_url + "table/addteacher",
data: "name=" + name + "&login=" + login + "&password=" + <PASSWORD> + "&status=" + status,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
document.location.href = base_url + 'admin/teachers';
}
});
}
else {
$.ajax({
type: "POST",
url: base_url + "table/updateteacher",
data: "name=" + name + "&login=" + login + "&password=" + <PASSWORD> + "&status=" + status + "&id=" + id,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
document.location.href = base_url + 'admin/teachers';
}
});
}*/
} else {
return false;
}
});
});
</script>
<file_sep>/script.sql
-- MySQL dump 10.13 Distrib 5.6.24, for osx10.8 (x86_64)
--
-- Host: us-cdbr-azure-east-a.cloudapp.net Database: acsm_b1db89b5cc641ae
-- ------------------------------------------------------
-- Server version 5.5.56-log
/*!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 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 `achievement`
--
DROP TABLE IF EXISTS `achievement`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `achievement` (
`ACHIEVEMENT_ID` int(11) NOT NULL AUTO_INCREMENT,
`ACHIEVEMENT_MARK` int(11) DEFAULT NULL,
`PUPIL_ID` int(11) DEFAULT NULL,
`TYPE_ID` int(11) DEFAULT NULL,
`LESSON_ID` int(11) DEFAULT NULL,
PRIMARY KEY (`ACHIEVEMENT_ID`),
KEY `PUPIL_ID_5_idx` (`PUPIL_ID`),
KEY `TYPE_ID_idx` (`TYPE_ID`),
KEY `LESSON_ID_3_idx` (`LESSON_ID`),
CONSTRAINT `LESSON_ID_1` FOREIGN KEY (`LESSON_ID`) REFERENCES `lesson` (`LESSON_ID`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `PUPIL_ID_1` FOREIGN KEY (`PUPIL_ID`) REFERENCES `pupil` (`PUPIL_ID`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `TYPE_ID` FOREIGN KEY (`TYPE_ID`) REFERENCES `type` (`TYPE_ID`) ON DELETE SET NULL ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=2005 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `attendance`
--
DROP TABLE IF EXISTS `attendance`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `attendance` (
`ATTENDANCE_ID` int(11) NOT NULL AUTO_INCREMENT,
`LESSON_ID` int(11) DEFAULT NULL,
`PUPIL_ID` int(11) DEFAULT NULL,
`ATTENDANCE_PASS` varchar(1) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`ATTENDANCE_ID`),
KEY `LESSON_ID_idx` (`LESSON_ID`),
KEY `PUPIL_ID_1_idx` (`PUPIL_ID`),
CONSTRAINT `LESSON_ID_2` FOREIGN KEY (`LESSON_ID`) REFERENCES `lesson` (`LESSON_ID`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `PUPIL_ID_2` FOREIGN KEY (`PUPIL_ID`) REFERENCES `pupil` (`PUPIL_ID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=265 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `class`
--
DROP TABLE IF EXISTS `class`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `class` (
`CLASS_ID` int(11) NOT NULL AUTO_INCREMENT,
`CLASS_NUMBER` int(11) DEFAULT NULL,
`CLASS_LETTER` varchar(10) CHARACTER SET utf8 DEFAULT NULL,
`YEAR_ID` int(11) DEFAULT NULL,
`CLASS_STATUS` int(11) DEFAULT NULL,
`TEACHER_ID` int(11) DEFAULT NULL,
`CLASS_PREVIOUS` int(11) DEFAULT NULL,
PRIMARY KEY (`CLASS_ID`),
KEY `YEAR_ID_idx` (`YEAR_ID`),
KEY `TEACHER_ID_4_idx` (`TEACHER_ID`),
KEY `CLASS_ID_5_idx` (`CLASS_PREVIOUS`),
CONSTRAINT `CLASS_ID_5` FOREIGN KEY (`CLASS_PREVIOUS`) REFERENCES `class` (`CLASS_ID`) ON DELETE SET NULL ON UPDATE NO ACTION,
CONSTRAINT `TEACHER_ID_1` FOREIGN KEY (`TEACHER_ID`) REFERENCES `teacher` (`TEACHER_ID`) ON DELETE SET NULL ON UPDATE NO ACTION,
CONSTRAINT `YEAR_ID_1` FOREIGN KEY (`YEAR_ID`) REFERENCES `year` (`YEAR_ID`) ON DELETE SET NULL ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `dayofweek`
--
DROP TABLE IF EXISTS `dayofweek`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dayofweek` (
`DAYOFWEEK_ID` int(11) NOT NULL AUTO_INCREMENT,
`DAYOFWEEK_NAME` varchar(25) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`DAYOFWEEK_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `file`
--
DROP TABLE IF EXISTS `file`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `file` (
`FILE_ID` int(11) NOT NULL AUTO_INCREMENT,
`FILE_NAME` varchar(500) DEFAULT NULL,
`FILE_SIZE` varchar(45) DEFAULT NULL,
`FILE_EXTENSION` varchar(10) DEFAULT NULL,
`LESSON_ID` int(11) DEFAULT NULL,
PRIMARY KEY (`FILE_ID`),
KEY `LESSON_ID_3_idx` (`LESSON_ID`),
KEY `LESSON_ID_4_idx` (`LESSON_ID`),
CONSTRAINT `LESSON_ID_3` FOREIGN KEY (`LESSON_ID`) REFERENCES `lesson` (`LESSON_ID`) ON DELETE SET NULL ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `gcm_users`
--
DROP TABLE IF EXISTS `gcm_users`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `gcm_users` (
`GCM_USERS_ID` int(11) NOT NULL AUTO_INCREMENT,
`GCM_USERS_REGID` varchar(200) DEFAULT NULL,
`PUPIL_ID` int(11) DEFAULT NULL,
PRIMARY KEY (`GCM_USERS_ID`),
KEY `PUPIL_ID_12_idx` (`PUPIL_ID`),
CONSTRAINT `PUPIL_ID_12` FOREIGN KEY (`PUPIL_ID`) REFERENCES `pupil` (`PUPIL_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=465 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `lesson`
--
DROP TABLE IF EXISTS `lesson`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `lesson` (
`LESSON_ID` int(11) NOT NULL AUTO_INCREMENT,
`LESSON_DATE` date DEFAULT NULL,
`LESSON_THEME` varchar(300) CHARACTER SET utf8 DEFAULT NULL,
`SUBJECTS_CLASS_ID` int(11) DEFAULT NULL,
`LESSON_HOMEWORK` varchar(10000) CHARACTER SET utf8 DEFAULT NULL,
`TIME_ID` int(11) DEFAULT NULL,
`LESSON_STATUS` int(11) DEFAULT NULL,
PRIMARY KEY (`LESSON_ID`),
KEY `SUBJECTS_CLASS_ID_1_idx` (`SUBJECTS_CLASS_ID`),
KEY `TIME_ID_2_idx` (`TIME_ID`),
CONSTRAINT `SUBJECTS_CLASS_ID_1` FOREIGN KEY (`SUBJECTS_CLASS_ID`) REFERENCES `subjects_class` (`SUBJECTS_CLASS_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `TIME_ID_2` FOREIGN KEY (`TIME_ID`) REFERENCES `time` (`TIME_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=925 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `message`
--
DROP TABLE IF EXISTS `message`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `message` (
`MESSAGE_ID` int(11) NOT NULL AUTO_INCREMENT,
`MESSAGE_DATE` datetime DEFAULT NULL,
`MESSAGE_TEXT` varchar(1000) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`MESSAGE_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3225 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `news`
--
DROP TABLE IF EXISTS `news`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `news` (
`NEWS_ID` int(11) NOT NULL AUTO_INCREMENT,
`NEWS_TIME` date NOT NULL,
`TEACHER_ID` int(11) NOT NULL,
`NEWS_TEXT` longtext CHARACTER SET utf8mb4 NOT NULL,
`NEWS_THEME` varchar(200) CHARACTER SET utf8mb4 DEFAULT NULL,
PRIMARY KEY (`NEWS_ID`),
KEY `TEACHER_ID_6_idx` (`TEACHER_ID`),
CONSTRAINT `TEACHER_ID_2` FOREIGN KEY (`TEACHER_ID`) REFERENCES `teacher` (`TEACHER_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=65 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `note`
--
DROP TABLE IF EXISTS `note`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `note` (
`NOTE_ID` int(11) NOT NULL AUTO_INCREMENT,
`NOTE_TEXT` varchar(200) DEFAULT NULL,
`PUPIL_ID` int(11) DEFAULT NULL,
`LESSON_ID` int(11) DEFAULT NULL,
PRIMARY KEY (`NOTE_ID`),
KEY `LESSON_ID_4_idx` (`LESSON_ID`),
KEY `PUPIL_ID_8_idx` (`PUPIL_ID`),
CONSTRAINT `LESSON_ID_4` FOREIGN KEY (`LESSON_ID`) REFERENCES `lesson` (`LESSON_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `PUPIL_ID_8` FOREIGN KEY (`PUPIL_ID`) REFERENCES `pupil` (`PUPIL_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=95 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `period`
--
DROP TABLE IF EXISTS `period`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `period` (
`PERIOD_ID` int(11) NOT NULL AUTO_INCREMENT,
`PERIOD_NAME` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
`PERIOD_START` date DEFAULT NULL,
`PERIOD_FINISH` date DEFAULT NULL,
`YEAR_ID` int(11) DEFAULT NULL,
PRIMARY KEY (`PERIOD_ID`),
KEY `YEAR_ID_1_idx` (`YEAR_ID`),
CONSTRAINT `YEAR_ID_2` FOREIGN KEY (`YEAR_ID`) REFERENCES `year` (`YEAR_ID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=125 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `progress`
--
DROP TABLE IF EXISTS `progress`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `progress` (
`PROGRESS_ID` int(11) NOT NULL AUTO_INCREMENT,
`PERIOD_ID` int(11) DEFAULT NULL,
`SUBJECTS_CLASS_ID` int(11) DEFAULT NULL,
`PROGRESS_MARK` int(11) DEFAULT NULL,
`PUPIL_ID` int(11) DEFAULT NULL,
PRIMARY KEY (`PROGRESS_ID`),
KEY `SUBJECTS_CLASS_ID_idx` (`SUBJECTS_CLASS_ID`),
KEY `PUPIL_ID_2_idx` (`PUPIL_ID`),
KEY `PERIOD_ID_idx` (`PERIOD_ID`),
CONSTRAINT `PERIOD_ID` FOREIGN KEY (`PERIOD_ID`) REFERENCES `period` (`PERIOD_ID`) ON DELETE SET NULL ON UPDATE NO ACTION,
CONSTRAINT `PUPIL_ID_3` FOREIGN KEY (`PUPIL_ID`) REFERENCES `pupil` (`PUPIL_ID`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `SUBJECTS_CLASS_ID_2` FOREIGN KEY (`SUBJECTS_CLASS_ID`) REFERENCES `subjects_class` (`SUBJECTS_CLASS_ID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=1375 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `pupil`
--
DROP TABLE IF EXISTS `pupil`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pupil` (
`PUPIL_ID` int(11) NOT NULL AUTO_INCREMENT,
`PUPIL_NAME` varchar(200) CHARACTER SET utf8 DEFAULT NULL,
`PUPIL_LOGIN` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
`PUPIL_PASSWORD` varchar(32) CHARACTER SET utf8 DEFAULT NULL,
`PUPIL_HASH` varchar(32) CHARACTER SET utf8 DEFAULT NULL,
`PUPIL_ADDRESS` varchar(400) CHARACTER SET utf8 DEFAULT NULL,
`PUPIL_BIRTHDAY` date DEFAULT NULL,
`PUPIL_STATUS` int(11) DEFAULT NULL,
`ROLE_ID` int(11) DEFAULT NULL,
`PUPIL_PHONE` varchar(45) DEFAULT NULL,
PRIMARY KEY (`PUPIL_ID`),
KEY `ROLE_ID_2_idx` (`ROLE_ID`),
CONSTRAINT `ROLE_ID_1` FOREIGN KEY (`ROLE_ID`) REFERENCES `role` (`ROLE_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `pupils_class`
--
DROP TABLE IF EXISTS `pupils_class`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pupils_class` (
`PUPILS_CLASS_ID` int(11) NOT NULL AUTO_INCREMENT,
`CLASS_ID` int(11) DEFAULT NULL,
`PUPIL_ID` int(11) DEFAULT NULL,
PRIMARY KEY (`PUPILS_CLASS_ID`),
KEY `CLASS_ID_5_idx` (`CLASS_ID`),
KEY `PUPIL_ID_4_idx` (`PUPIL_ID`),
CONSTRAINT `CLASS_ID_1` FOREIGN KEY (`CLASS_ID`) REFERENCES `class` (`CLASS_ID`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `PUPIL_ID_4` FOREIGN KEY (`PUPIL_ID`) REFERENCES `pupil` (`PUPIL_ID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=85 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `pupils_message`
--
DROP TABLE IF EXISTS `pupils_message`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pupils_message` (
`PUPILS_MESSAGE_ID` int(11) NOT NULL AUTO_INCREMENT,
`PUPIL_ID` int(11) DEFAULT NULL,
`MESSAGE_ID` int(11) DEFAULT NULL,
`MESSAGE_READ` int(11) DEFAULT NULL,
`MESSAGE_FOLDER` int(11) DEFAULT NULL,
`TEACHER_ID` int(11) DEFAULT NULL,
PRIMARY KEY (`PUPILS_MESSAGE_ID`),
KEY `MESSAGE_ID_1_idx` (`MESSAGE_ID`),
KEY `PUPIL_ID_6_idx` (`PUPIL_ID`),
KEY `TEACHER_ID_5_idx` (`TEACHER_ID`),
CONSTRAINT `MESSAGE_ID_1` FOREIGN KEY (`MESSAGE_ID`) REFERENCES `message` (`MESSAGE_ID`) ON DELETE SET NULL ON UPDATE NO ACTION,
CONSTRAINT `PUPIL_ID_6` FOREIGN KEY (`PUPIL_ID`) REFERENCES `pupil` (`PUPIL_ID`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `TEACHER_ID_5` FOREIGN KEY (`TEACHER_ID`) REFERENCES `teacher` (`TEACHER_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3215 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `role`
--
DROP TABLE IF EXISTS `role`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `role` (
`ROLE_ID` int(11) NOT NULL AUTO_INCREMENT,
`ROLE_NAME` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`ROLE_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `room`
--
DROP TABLE IF EXISTS `room`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `room` (
`ROOM_ID` int(11) NOT NULL AUTO_INCREMENT,
`ROOM_NAME` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
`ROOMcol` varchar(45) DEFAULT NULL,
PRIMARY KEY (`ROOM_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `subject`
--
DROP TABLE IF EXISTS `subject`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `subject` (
`SUBJECT_ID` int(11) NOT NULL AUTO_INCREMENT,
`SUBJECT_NAME` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`SUBJECT_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `subjects_class`
--
DROP TABLE IF EXISTS `subjects_class`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `subjects_class` (
`SUBJECTS_CLASS_ID` int(11) NOT NULL AUTO_INCREMENT,
`SUBJECT_ID` int(11) DEFAULT NULL,
`CLASS_ID` int(11) DEFAULT NULL,
`TEACHER_ID` int(11) DEFAULT NULL,
PRIMARY KEY (`SUBJECTS_CLASS_ID`),
KEY `SUBJECT_ID_idx` (`SUBJECT_ID`),
KEY `CLASS_ID_idx` (`CLASS_ID`),
KEY `TEACHER_ID_3_idx` (`TEACHER_ID`),
CONSTRAINT `CLASS_ID_2` FOREIGN KEY (`CLASS_ID`) REFERENCES `class` (`CLASS_ID`) ON DELETE SET NULL ON UPDATE NO ACTION,
CONSTRAINT `SUBJECT_ID_1` FOREIGN KEY (`SUBJECT_ID`) REFERENCES `subject` (`SUBJECT_ID`) ON DELETE SET NULL ON UPDATE NO ACTION,
CONSTRAINT `TEACHER_ID_3` FOREIGN KEY (`TEACHER_ID`) REFERENCES `teacher` (`TEACHER_ID`) ON DELETE SET NULL ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=355 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `teacher`
--
DROP TABLE IF EXISTS `teacher`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `teacher` (
`TEACHER_ID` int(11) NOT NULL AUTO_INCREMENT,
`TEACHER_LOGIN` varchar(30) CHARACTER SET utf8 DEFAULT NULL,
`TEACHER_PASSWORD` varchar(32) CHARACTER SET utf8 DEFAULT NULL,
`TEACHER_HASH` varchar(32) CHARACTER SET utf8 DEFAULT NULL,
`ROLE_ID` int(11) DEFAULT NULL,
`TEACHER_NAME` varchar(200) CHARACTER SET utf8 DEFAULT NULL,
`TEACHER_STATUS` int(11) DEFAULT NULL,
PRIMARY KEY (`TEACHER_ID`),
KEY `ROLE_ID_1_idx` (`ROLE_ID`),
CONSTRAINT `ROLE_ID_2` FOREIGN KEY (`ROLE_ID`) REFERENCES `role` (`ROLE_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `teachers_message`
--
DROP TABLE IF EXISTS `teachers_message`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `teachers_message` (
`TEACHERS_MESSAGE_ID` int(11) NOT NULL AUTO_INCREMENT,
`TEACHER_ID` int(11) DEFAULT NULL,
`MESSAGE_ID` int(11) DEFAULT NULL,
`MESSAGE_READ` int(11) DEFAULT NULL,
`MESSAGE_FOLDER` int(11) DEFAULT NULL,
`PUPIL_ID` int(11) DEFAULT NULL,
PRIMARY KEY (`TEACHERS_MESSAGE_ID`),
KEY `TEACHER_ID_4_idx` (`TEACHER_ID`),
KEY `MESSAGE_ID_idx` (`MESSAGE_ID`),
KEY `PUPIL_ID_7_idx` (`PUPIL_ID`),
CONSTRAINT `MESSAGE_ID_2` FOREIGN KEY (`MESSAGE_ID`) REFERENCES `message` (`MESSAGE_ID`) ON DELETE SET NULL ON UPDATE NO ACTION,
CONSTRAINT `PUPIL_ID_7` FOREIGN KEY (`PUPIL_ID`) REFERENCES `pupil` (`PUPIL_ID`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `TEACHER_ID_4` FOREIGN KEY (`TEACHER_ID`) REFERENCES `teacher` (`TEACHER_ID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3225 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `time`
--
DROP TABLE IF EXISTS `time`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `time` (
`TIME_ID` int(11) NOT NULL AUTO_INCREMENT,
`TIME_START` time DEFAULT NULL,
`TIME_FINISH` time DEFAULT NULL,
PRIMARY KEY (`TIME_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `timetable`
--
DROP TABLE IF EXISTS `timetable`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `timetable` (
`TIMETABLE_ID` int(11) NOT NULL AUTO_INCREMENT,
`TIME_ID` int(11) DEFAULT NULL,
`ROOM_ID` int(11) DEFAULT NULL,
`DAYOFWEEK_ID` int(11) DEFAULT NULL,
`SUBJECTS_CLASS_ID` int(11) DEFAULT NULL,
PRIMARY KEY (`TIMETABLE_ID`),
KEY `TIME_ID_idx` (`TIME_ID`),
KEY `ROOM_ID_idx` (`ROOM_ID`),
KEY `DAYOFWEEK_ID_idx` (`DAYOFWEEK_ID`),
KEY `SUBJECTS_CLASS_ID_2_idx` (`SUBJECTS_CLASS_ID`),
CONSTRAINT `DAYOFWEEK_ID_1` FOREIGN KEY (`DAYOFWEEK_ID`) REFERENCES `dayofweek` (`DAYOFWEEK_ID`) ON DELETE SET NULL ON UPDATE NO ACTION,
CONSTRAINT `ROOM_ID_1` FOREIGN KEY (`ROOM_ID`) REFERENCES `room` (`ROOM_ID`) ON DELETE SET NULL ON UPDATE NO ACTION,
CONSTRAINT `SUBJECTS_CLASS_ID_3` FOREIGN KEY (`SUBJECTS_CLASS_ID`) REFERENCES `subjects_class` (`SUBJECTS_CLASS_ID`) ON DELETE SET NULL ON UPDATE NO ACTION,
CONSTRAINT `TIME_ID_1` FOREIGN KEY (`TIME_ID`) REFERENCES `time` (`TIME_ID`) ON DELETE SET NULL ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=765 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `type`
--
DROP TABLE IF EXISTS `type`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `type` (
`TYPE_ID` int(11) NOT NULL AUTO_INCREMENT,
`TYPE_NAME` varchar(150) CHARACTER SET utf8 DEFAULT NULL,
PRIMARY KEY (`TYPE_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Table structure for table `year`
--
DROP TABLE IF EXISTS `year`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `year` (
`YEAR_ID` int(11) NOT NULL AUTO_INCREMENT,
`YEAR_START` date NOT NULL,
`YEAR_FINISH` date NOT NULL,
PRIMARY KEY (`YEAR_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!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 2018-04-09 21:46:12
<file_sep>/application/views/blankview/blankclassview.php
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><?php echo $title; ?></div>
<div class="panel-body">
<form method="post">
<div hidden="true" id="id"><?php if(isset($id)) echo $id;?></div>
<div class="form-horizontal">
<div class="form-group">
<label for="inputNumber" class="col-sm-2 col-md-2 control-label">Параллель <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<input type="number" class="form-control" title="Значение задается в диапазоне от 1 до 11" id="inputNumber" name="inputNumber" required="true" autofocus min="1" max="11" value = "<?php if(isset($number)) { echo $number; } else echo "1";?>">
</div>
</div>
<div class="form-group">
<label for="inputLetter" class="col-sm-2 col-md-2 control-label">Буква <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<input type="text" class="form-control" id="inputLetter" name="inputLetter" placeholder="Буква" required="true" maxlength="50" value="<?php if(isset($letter)) echo $letter;?>">
<div class="red" id="responseClassError"></div>
</div>
</div>
<div class="form-group">
<label for="inputYear" class="col-sm-2 col-md-2 control-label">Учебный год <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<select id="inputYear" name="inputYear" class="width-select" <?php if(isset($status_allow) && $status_allow == true) echo 'disabled';?>>
<?php
if(isset($years)) {
if($year_id == null && isset($id)) echo "<option value=''></option>";
foreach($years as $year) {
if ($year_id != "") {
if($year['YEAR_ID'] == $year_id) {
echo "<option selected='selected' value='".$year['YEAR_ID']."'>".date("Y", strtotime($year['YEAR_START'])).' - '.date("Y", strtotime($year['YEAR_FINISH']))." гг."."</option>";
} else {
echo "<option value='".$year['YEAR_ID']."'>".date("Y", strtotime($year['YEAR_START'])).' - '.date("Y", strtotime($year['YEAR_FINISH']))." гг."."</option>";
}
} else {
echo "<option value='".$year['YEAR_ID']."'>".date("Y", strtotime($year['YEAR_START'])).' - '.date("Y", strtotime($year['YEAR_FINISH']))." гг."."</option>";
}
}
}
?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 col-md-2 control-label">Текущий <span class="star">*</span></label>
<div class="col-sm-offset-2 col-sm-10" style="margin-top: -27.5px;">
<label class="radio-inline">
<input type="radio" name="inputStatus" <?php if(isset($status_allow) && $status_allow == true) echo 'disabled';?>
value="1" <?php if(isset($status) && $status == 1) { echo "checked='checked'";} else echo "checked='checked'"; ?> >Да
</label>
<label class="radio-inline">
<input type="radio" name="inputStatus" <?php if(isset($status_allow) && $status_allow == true) echo 'disabled';?>
value="0" <?php if(isset($status) && $status == 0) { echo "checked='checked'";}?>>Нет
</label>
</div>
</div>
<!--<label>Текущий *</label>
<div class="radio" style="margin-top: 0px;">
<input type="radio" name="inputStatus" <?php if(isset($status_allow) && $status_allow == true) echo 'disabled';?>
value="1" <?php if(isset($status) && $status == 1) { echo "checked='checked'";} else echo "checked='checked'"; ?> >Да<br/>
<input type="radio" name="inputStatus" <?php if(isset($status_allow) && $status_allow == true) echo 'disabled';?>
value="0" <?php if(isset($status) && $status == 0) { echo "checked='checked'";}?>>Нет
</div>-->
<div class="form-group">
<label for="inputTeacher" class="col-sm-2 col-md-2 control-label">Классный руководитель <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<select id="inputTeacher" name="inputTeacher" class="width-select">
<?php
if(isset($teachers)) {
if($teacher_id == null && isset($id)) echo "<option value=''></option>";
foreach($teachers as $teacher) {
if ($teacher_id != "") {
if($teacher['TEACHER_ID'] == $teacher_id) {
echo "<option selected='selected' value='".$teacher['TEACHER_ID']."'>".$teacher['TEACHER_NAME']."</option>";
} else {
echo "<option value='".$teacher['TEACHER_ID']."'>".$teacher['TEACHER_NAME']."</option>";
}
} else {
echo "<option value='".$teacher['TEACHER_ID']."'>".$teacher['TEACHER_NAME']."</option>";
}
}
}
?>
</select>
<div class="red" id="responseTeacherError"></div>
</div>
</div>
<div class="form-group">
<label for="inputPrevious" class="col-sm-2 col-md-2 control-label"><?php if(isset($previous)) echo "Переведен из класса"; else echo "Перевести из класса";?></label>
<div class="col-sm-10 col-md-10">
<select id="inputPrevious" name="inputPrevious" class="width-select" <?php if(isset($previous)) echo "disabled"; ?>>
<option value=""></option>
<?php
foreach($classes as $class) {
if(isset($class['YEAR_ID'])) $year_border = " (".date("Y",strtotime($class['YEAR_START']))." - ".date("Y",strtotime($class['YEAR_FINISH']))." гг.)"; else $year_border = '';
if ($previous != "") {
if($class['CLASS_ID'] == $previous) {
echo "<option selected='selected' value='".$class['CLASS_ID']."'>".$class['CLASS_NUMBER']." ".$class['CLASS_LETTER'].$year_border."</option>";
} else {
echo "<option value='".$class['CLASS_ID']."'>".$class['CLASS_NUMBER']." ".$class['CLASS_LETTER'].$year_border."</option>";
}
} else {
if(isset($id) && $class['CLASS_ID'] == $id) {
} else
echo "<option value='".$class['CLASS_ID']."'>".$class['CLASS_NUMBER']." ".$class['CLASS_LETTER'].$year_border."</option>";
}
}
?>
</select>
<div class="red" id="responsePreviousError"></div>
</div>
</div>
<div class="alert alert-warning" role="alert"><strong>Примечание:</strong> перевод класса осуществляется только один раз - отменить это действие уже будет нельзя. Проверяйте внимательно выбранный класс
</div>
</div>
<div class="grey">* - Обязательные поля</div>
<div id="error" class="red"></div>
<div class="modal-footer" style="margin-bottom: -15px; padding-right: 0px;">
<button type="button" class="btn btn-default" onclick="javascript:history.back();" title="Отменить">Отменить</button>
<button type="submit" class="btn btn-sample" name="save" id="save" title="Сохранить">Сохранить</button>
</div>
</form>
</div>
<!--<div class="panel-footer clearfix">
<div class="pull-right">
<button type="button" class="btn btn-default" onclick="javascript:history.back();">Отменить</button>
<button type="button" class="btn btn-sample" name="save" id="save">Сохранить</button>
</div>
</div>-->
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#inputYear").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
$("#inputTeacher").select2({
language: "ru"
});
$("#inputPrevious").select2({
language: "ru"
});
$("input[type='number']").change("input", function() {
var number = $('#inputNumber').val();
if (number > 11 || number < 1) {
$('#inputNumber').val(1);
}
});
$('#save').click(function() {
var base_url = '<?php echo base_url();?>';
var s = 0;
var error = 0;
var number = $.trim($('#inputNumber').val());
var letter = $.trim($('#inputLetter').val());
var year = $('#inputYear').find("option:selected").val();
var teacher = $('#inputTeacher').find("option:selected").val();
var status = $("input[name='inputStatus']:checked").val();
var previous = $('#inputPrevious').find("option:selected").val();
if ($('#inputPrevious').is(':disabled')) {
previous = "";
}
$("#responsePreviousError").text('');
try {
var years1 = $('#inputYear').find("option:selected").text();
var years2 = $('#inputPrevious').find("option:selected").text().split("(")[1].split(")")[0];
if (years1 == years2) {
error++;
$("#responsePreviousError").text('Нельзя делать перевод в класс этого же года');
} else {
$("#responsePreviousError").text('');
}
}
catch (e) {
}
if(error == 0) {
$("#responsePreviousError").text('');
$.ajax({
type: "POST",
url: base_url + "table/responseclassprevious",
data: "previous=" + previous,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
if (response == true) {
$("#responsePreviousError").text('Из выбранного класса уже был сделан перевод');
error++;
}
if (response == false) {
$("#responsePreviousError").text('');
}
}
});
}
var id = $('#id').text();
if (letter.length == 0) {
$('#inputLetter').parent().addClass("has-error");
s++;
} else {
$('#inputLetter').parent().removeClass("has-error");
$.ajax({
type: "POST",
url: base_url + "table/responseclass",
data: "number=" + number + "&letter=" + letter + "&year=" + year + "&status=" + status + "&id=" + id,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
if (response == true) {
$("#responseClassError").text('В списке уже есть такой класс в выбранном году');
$('#inputLetter').parent().addClass("has-error");
$('#inputNumber').parent().addClass("has-error");
error++;
}
if (response == false) {
$("#responseClassError").text('');
$('#inputLetter').parent().removeClass("has-error");
$('#inputNumber').parent().removeClass("has-error");
}
}
});
}
if (year == "") {
s++;
}
//alert(teacher + year + id);
if (teacher == "") {
$("#responseTeacherError").text('');
s++;
} else {
$("#responseTeacherError").text('');
$.ajax({
type: "POST",
url: base_url + "table/responseclassteacher",
data: "teacher=" + teacher + "&year=" + year + "&id=" + id,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
//alert(response);
if (response == true) {
$("#responseTeacherError").text('Выбранный учитель уже является классным руководителем в выбранном году');
error++;
}
if (response == false) {
$("#responseTeacherError").text('');
}
}
});
}
if (s != 0) {
$("#error").text('Не все обязательные поля заполнены');
}
else {
$("#error").text('');
}
//alert(s + " " + error);
if (s == 0 && error == 0) {
/*if (id == "") {
$.ajax({
type: "POST",
url: base_url + "table/addclass",
data: "number=" + number + "&letter=" + letter + "&year=" + year + "&status=" + status + "&teacher=" + teacher + "&previous=" + previous,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
document.location.href = base_url + 'admin/classes';
}
});
}
else {
$.ajax({
type: "POST",
url: base_url + "table/updateclass",
data: "number=" + number + "&letter=" + letter + "&year=" + year + "&status=" + status + "&teacher=" + teacher + "&id=" + id + "&previous=" + previous,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
//alert(response);
document.location.href = base_url + 'admin/classes';
}
});
}*/
} else return false;
});
});
</script>
<file_sep>/application/views/admin/teachersview.php
<?php
function hidePassword($password) {
$s = "";
for($i = 0; $i < strlen($password); $i++) {
$s = $s."*";
}
echo $s;
}
?>
<div class="container">
<h3 class="sidebar-header"><i class="fa fa-user"></i> Список учителей</h3>
<div class="panel panel-default panel-table">
<div class="panel-body">
<button type="button" class="btn btn-menu" id="createButton" title="Добавить учителя"><i class="fa fa-plus fa-2x"></i>
</br><span class="menu-item">Создать</span>
</button>
<button href="" type="button" class="btn btn-menu disabled" id="editButton" title="Редактировать учителя"><i class="fa fa-pencil fa-2x"></i>
</br><span class="menu-item">Редактировать</span>
</button>
<button type="button" class="btn btn-menu disabled" id="deleteButton" data-toggle="modal" data-target="#myModal" title="Удалить учителя"><i class="fa fa-trash-o fa-2x"></i>
</br><span class="menu-item">Удалить</span>
</button>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<form method="get">
<div class="input-group">
<input type="text" class="form-control" placeholder="Поиск по ФИО и логину" id="search" name="search" value="<?php if(isset($search)) echo $search;?>" >
<span class="input-group-btn">
<button class="btn btn-default" type="submit" name="submit" id="searchButton" title="Поиск"><i class="fa fa-search"></i></button>
</span>
</div><!-- /input-group -->
</form>
</div>
<div class="table-responsive">
<table name="timetable" class="table table-striped table-hover table-bordered numeric">
<thead>
<tr>
<th></th>
<th data-sortable="true">ФИО учителя</th> <!--1-->
<th>Логин</th> <!--2-->
<th>Пароль</th> <!--3-->
<th>Статус</th> <!--5-->
</tr>
</thead>
<tbody>
<?php
if(is_array($teachers) && count($teachers) ) {
foreach($teachers as $teacher) {
?>
<tr>
<td><input type="radio" name="teacher_id" value="<?php echo $teacher['TEACHER_ID'];?>"></td>
<td ><?php echo $teacher['TEACHER_NAME'];?></td>
<td><?php echo $teacher['TEACHER_LOGIN'];?></td>
<td><span data-toggle="tooltip" data-placement="top" title="<?php echo $teacher['TEACHER_PASSWORD']; ?>">
<?php hidePassword($teacher['TEACHER_PASSWORD']);?></span></td>
<td><?php if($teacher['TEACHER_STATUS'] == 0) echo "Не активен"; else echo "Активен";?></td>
</tr>
<?php }} ?>
</tbody>
</table>
</div>
</div>
<?php echo $this->pagination->create_links(); ?>
<?php
if(count($teachers) == 0 && isset($search) && $search != "") {
?>
<div class="alert alert-info" role="alert">Поиск не дал результатов. Попробуйте другой запрос</div>
<?php } ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
if($(":radio[name=teacher_id]").is(':checked')) {
$('#editButton').removeClass('disabled');
$('#deleteButton').removeClass('disabled');
} else {
$('#editButton').addClass('disabled');
$('#deleteButton').addClass('disabled');
}
$(":radio[name=teacher_id]").change(function() {
$('#editButton').removeClass('disabled');
$('#deleteButton').removeClass('disabled');
});
$('#createButton').click(function() {
document.location.href = '<?php echo base_url(); ?>admin/teacher';
});
$('#editButton').click(function() {
var value = $(":radio[name=teacher_id]").filter(":checked").val();
document.location.href = '<?php echo base_url(); ?>admin/teacher/' + value;
});
$('#buttonDeleteTeacherModal').click(function() {
var value = $(":radio[name=teacher_id]").filter(":checked").val();
var base_url = '<?php echo base_url();?>';
$.ajax({
type: "POST",
url: base_url + "table/del/teacher/" + value,
//data: "id=" + value + "&from=subjects",
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(a) {
location.reload();
}
});
});
$("tr:not(:first)").click(function() {
$(this).children("td").find('input[type=radio]').prop('checked', true).change();
});
});
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Удаление пользователя</h4>
</div>
<div class="modal-body">
<p>Вы уверены, что хотите удалить этого пользователя?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-sample" id="buttonDeleteTeacherModal">Удалить</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<file_sep>/application/views/teacher/timetableview.php
<?php
$days = array("Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота");
?>
<div class="container">
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-6">
<label for="day" class="control-label"><i class="fa fa-clock-o"></i> Расписание на</label>
<select id="day" style="width: 50%;">
<?php for ($i = 0; $i < count($days); $i++) {?>
<option value="<?php echo $i+1; ?>" <?php if($this->uri->segment(3) == $i+1) echo "selected"; ?> ><?php echo $days[$i]; ?></option>
<?php } ?>
</select>
</div>
<div class="col-md-6"></div>
</div>
<div class="panel panel-default panel-table">
<div class="panel-body">
<button type="button" class="btn btn-menu" id="createButton" title="Добавить предмет в расписание"><i class="fa fa-plus fa-2x"></i>
</br><span class="menu-item">Создать</span>
</button>
<button href="" type="button" class="btn btn-menu disabled" id="editButton" title="Редактировать предмет в расписании"><i class="fa fa-pencil fa-2x"></i>
</br><span class="menu-item">Редактировать</span>
</button>
<button type="button" class="btn btn-menu disabled" id="deleteButton" data-toggle="modal" data-target="#myModal" title="Удалить предмет из расписания"><i class="fa fa-trash-o fa-2x"></i>
</br><span class="menu-item">Удалить</span>
</button>
</div>
</div>
<!--<select id="day">
<option value="1">Понедельник</option>
<option value="2">Вторник</option>
<option value="3">Среда</option>
<option value="4">Четверг</option>
<option value="5">Пятница</option>
<option value="6">Суббота</option>
</select>-->
<div class="panel panel-default">
<div class="table-responsive">
<table name="timetable" class="table table-striped table-hover table-bordered numeric">
<thead>
<tr>
<th></th>
<th>Время</th>
<th>Предмет</th>
<th>Кабинет</th>
</tr>
</thead>
<tbody>
<?php
if(is_array($timetable) && count($timetable) ) {
foreach($timetable as $row) {
?>
<tr>
<td><input type="radio" name="timetable_id" value="<?php echo $row['TIMETABLE_ID'];?>"></td>
<td id="time"><?php echo date("H:i", strtotime($row["TIME_START"])).' - '
.date("H:i",strtotime($row["TIME_FINISH"]));?></td>
<td><?php if(isset($row['SUBJECT_NAME'])) echo $row['SUBJECT_NAME'];?></td>
<td><?php if(isset($row['ROOM_NAME'])) echo $row['ROOM_NAME'];?></td>
</tr>
<?php } }?>
</tbody>
</table>
</div>
</div>
<?php echo $this->pagination->create_links(); ?>
<?php
if(count($timetable) == 0) {
?>
<div class="alert alert-info" role="alert">Расписание на выбранный день пусто. Начните заполнять его</div>
<?php } ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#day").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
if($(":radio[name=timetable_id]").is(':checked')) {
var value = $(this).filter(":checked").val();
if(value == "") {
$('#editButton').removeClass('disabled');
$('#deleteButton').addClass('disabled');
} else {
$('#editButton').removeClass('disabled');
$('#deleteButton').removeClass('disabled');
}
} else {
$('#editButton').addClass('disabled');
$('#deleteButton').addClass('disabled');
}
$(":radio[name=timetable_id]").change(function() {
var value = $(this).filter(":checked").val();
if(value == "") {
$('#editButton').removeClass('disabled');
$('#deleteButton').addClass('disabled');
} else {
$('#editButton').removeClass('disabled');
$('#deleteButton').removeClass('disabled');
}
});
$('#createButton').click(function() {
var day = $('#day').find("option:selected").val();
document.location.href = '<?php echo base_url(); ?>teacher/timetableitem/' + day;
});
$('#editButton').click(function() {
var day = $('#day').find("option:selected").val();
var value = $(":radio[name=timetable_id]").filter(":checked").val();
document.location.href = '<?php echo base_url(); ?>teacher/timetableitem/' + day + "/" + value;
});
$('#buttonDeleteTimetableModal').click(function() {
var value = $(":radio[name=timetable_id]").filter(":checked").val();
var base_url = '<?php echo base_url();?>';
$.ajax({
type: "POST",
url: base_url + "table/del/timetable/" + value,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(a) {
location.reload();
}
});
});
$("tr:not(:first)").click(function() {
$(this).children("td").find('input[type=radio]').prop('checked', true).change();
});
$("#day").change(function() {
var val = $(this).find("option:selected").val();
document.location.href = '<?php echo base_url(); ?>teacher/timetable/' + val;
});
});
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Удаление предмета из расписания</h4>
</div>
<div class="modal-body">
<p>Вы уверены, что хотите удалить этот предмет из расписания?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-sample" id="buttonDeleteTimetableModal">Удалить</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<file_sep>/application/libraries/GCM.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class GCM {
function send($pupil_id, $message, $collapse_key) {
$apiKey = "<KEY>";
$CI =& get_instance();
$CI->load->model('tablemodel', 'table');
$regIds = $CI->table->getGCMIDs($pupil_id);
$regIdsArray = array();
foreach($regIds as $id) {
$regIdsArray[] = $id['GCM_USERS_REGID'];
}
// Replace with the real client registration IDs
$registrationIDs = $regIdsArray;
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'collapse_key' => $collapse_key,
'data' => array("message" => json_encode($message, JSON_UNESCAPED_UNICODE)),
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the URL, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url);
curl_setopt( $ch, CURLOPT_POST, true);
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields));
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
//echo $result;
}
}
<file_sep>/application/views/teacher/journalview.php
<style type="text/css">
td {
cursor: pointer; cursor: hand;
}
td:first-child, td:nth-child(2) {
cursor: default;
}
.highlighted {
background-color: #f5f5f5 !important;
}
</style>
<?php
function setColor($mark, $tooltip) {
switch ($mark) {
case 5: echo '<span data-toggle="tooltip" data-placement="top" title="'.$tooltip.'" class="label label-success">'.$mark.'</span>'; break;
case 4: echo '<span data-toggle="tooltip" data-placement="top" title="'.$tooltip.'" class="label label-warning">'.$mark.'</span>'; break;
case 3: echo '<span data-toggle="tooltip" data-placement="top" title="'.$tooltip.'" class="label label-primary">'.$mark.'</span>'; break;
case 2: echo '<span data-toggle="tooltip" data-placement="top" title="'.$tooltip.'" class="label label-danger">'.$mark.'</span>'; break;
}
}
?>
<div class="container">
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-4">
<form method="post">
<label for="class" class="control-label"><i class="fa fa-users"></i> Класс</label>
<select id="class" name="class" onchange="this.form.submit();" style="width: 70%">
<?php
foreach ($classes as $class) {
if(isset($class['YEAR_ID'])) $year_border = " (".date("Y",strtotime($class['YEAR_START']))." - ".date("Y",strtotime($class['YEAR_FINISH']))." гг.)"; else $year_border = '';
?>
<option value="<?php echo $class['CLASS_ID']?>"><?php echo $class['CLASS_NUMBER']." ".$class['CLASS_LETTER'].$year_border; ?></option>
<?php
}
?>
</select>
</form>
</div>
<div class="col-md-4">
<form method="post">
<label for="subject" class="control-label"><i class="fa fa-book"></i> Предмет</label>
<select id="subject" name="subject" onchange="this.form.submit();" style="width: 70%">
<?php
foreach ($subjects as $subject) {
?>
<option value="<?php echo $subject['SUBJECTS_CLASS_ID']?>"><?php echo $subject['SUBJECT_NAME']; ?></option>
<?php
}
?>
</select>
</form>
</div>
<div class="col-md-4">
<button onclick="location.href='<?php echo base_url();?>teacher/lessons/<?php echo $this->uri->segment(4); ?>';" class="btn btn-sample btn-large btn-block"
title="Список учебных занятий" style="margin-bottom: 20px;"><i class="fa fa-list"></i> Список учебных занятий</button>
</div>
</div>
<?php echo $this->pagination->create_links(); ?>
<div class="row">
<div class="col-md-8">
<h3 class="sidebar-header"><i class="fa fa-bookmark"></i> Журнальная страница</h3>
</div>
<div class="col-md-4" >
<h5><span onclick="location.href='<?php echo base_url();?>teacher/lesson/<?php echo $this->uri->segment(4);?>';" class="a-block pull-right" title="Добавить учебное занятие"><i class="fa fa-plus"></i> Добавить занятие</span></h5>
</div>
</div>
<div class="panel panel-default">
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered numeric">
<thead>
<tr>
<th>#</th>
<th>ФИО учащегося</th>
<?php foreach($lessons as $lesson) { ?>
<th data-toggle="tooltip" data-placement="top" data-container="body" title="<?php echo $lesson['LESSON_THEME']; ?>" style="cursor: pointer; cursor: hand;" onclick="document.location.href = '<?php echo base_url(); ?>teacher/lessonpage/<?php echo $this->uri->segment(4);?>/<?php echo $lesson['LESSON_ID']; ?>'"><?php echo date('d.m', strtotime($lesson['LESSON_DATE']))."</br>".date('H:i', strtotime($lesson['TIME_START']));?>
</th>
<?php }?>
</tr>
</thead>
<tbody>
<?php
for($i = 0; $i <count($result); $i++){
?>
<tr>
<td><?php echo $i+1; ?></td>
<td><?php echo $result[$i]["pupil_name"];?></td>
<?php if(isset($result[$i]["lessons"])) {
for($y = 0; $y < count($result[$i]["lessons"]); $y++) { ?>
<td <?php if(isset($result[$i]["lessons"][$y]["pass"])) {
switch($result[$i]["lessons"][$y]["pass"]) {
case 'н': {
?>class="warning"<?php
break;
}
case 'б': {
?>class="success"<?php
break;
}
case 'у': {
?>class="info"<?php
break;
}
} } ?>><?php
for($z = 0; $z < count($result[$i]["lessons"][$y]["marks"]); $z++) {
//echo $result[$i]["lessons"][$y]["marks"][$z]["mark"];
setColor($result[$i]["lessons"][$y]["marks"][$z]["mark"], $result[$i]["lessons"][$y]["marks"][$z]["type"]);
echo " ";
}
?>
</td>
<?php }?>
</tr>
<?php
}}
?>
</tbody>
</table>
</div>
</div>
<table style="margin-bottom: 20px;">
<tr>
<td><div class="color-swatch brand-success"></div></td>
<td>Пропуск по болезни</td>
</tr>
<tr>
<td><div class="color-swatch brand-info"></div></td>
<td>Пропуск по уважительной причине</td>
</tr>
<tr>
<td><div class="color-swatch brand-warning"></div></td>
<td>Пропуск по неуважительной причине</td>
</tr>
</table>
<!--Календарь
<div id="datepicker" data-date="12/03/2012"></div>
<input type="hidden" id="my_hidden_input" />-->
</div>
<script type="text/javascript">
$(document).ready(function() {
document.getElementById('class').value = "<?php echo $this->uri->segment(3);?>";
document.getElementById('subject').value = "<?php echo $this->uri->segment(4);?>";
/*$('#datepicker').datepicker({
format: 'yyyy-mm-dd',
startDate: "1993-01-01",
language: "ru",
todayBtn: "linked",
calendarWeeks: true,
todayHighlight: true
});*/
/*$("#datepicker").on("changeDate", function(event) {
$("#my_hidden_input").val(
$("#datepicker").datepicker('getFormattedDate'))
});*/
$("#class").select2({
language: "ru"
});
$("#subject").select2({
language: "ru"
});
$('table td:not(:first-child, :nth-child(2))').click(function() {
$('table th').eq($(this).index()).click();
});
//var period = $('table th').eq($(this).index()/2+1).text();
$('td:not(:first-child, :nth-child(2))').hover(function() {
var t = parseInt($(this).index()) + 1;
$(this).parents('table').find('td:nth-child(' + t + ')').addClass('highlighted');
},
function() {
var t = parseInt($(this).index()) + 1;
$(this).parents('table').find('td:nth-child(' + t + ')').removeClass('highlighted');
});
});
</script><file_sep>/application/models/pupilmodel.php
<?php
class Pupilmodel extends CI_Model {
function getNews($limit = null, $offset = null){
$query = $this->db->query("SELECT * FROM NEWS n JOIN TEACHER t ON t.TEACHER_ID = n.TEACHER_ID
ORDER BY NEWS_TIME DESC, NEWS_THEME LIMIT $offset, $limit");
return $query->result_array();
}
function totalNews() {
$this->db->like('TEACHER_ID', '13');
$this->db->from('NEWS');
return $this->db->count_all_results();
}
function getNewsById($id) {
$query = $this->db->query("SELECT * FROM NEWS n JOIN TEACHER t ON t.TEACHER_ID = n.TEACHER_ID
WHERE n.NEWS_ID = '$id'");
return $query->row_array();
}
function getYears() {
$query = $this->db->query("SELECT * FROM YEAR ORDER BY YEAR_START DESC");
return $query->result_array();
}
function getClassInYear($pupil, $year) {
$query = $this->db->query("SELECT c.CLASS_ID
FROM CLASS c JOIN PUPILS_CLASS pc ON pc.CLASS_ID = c.CLASS_ID
WHERE c.YEAR_ID = '$year' AND pc.PUPIL_ID = '$pupil'");
return $query->result_array();
}
function getSubjectsClass($class_id) {
$query = $this->db->query("SELECT s.SUBJECT_NAME, sc.SUBJECTS_CLASS_ID
FROM SUBJECTS_CLASS sc JOIN SUBJECT s ON s.SUBJECT_ID = sc.SUBJECT_ID
WHERE sc.CLASS_ID = '$class_id' ORDER BY 1");
return $query->result_array();
}
function getProgressMarks($subject, $pupil_id) {
$query = $this->db->query("SELECT p.PROGRESS_MARK, p.PERIOD_ID, PERIOD_NAME
FROM PROGRESS p JOIN PERIOD pe ON pe.PERIOD_ID = p.PERIOD_ID
WHERE p.SUBJECTS_CLASS_ID = '$subject' AND p.PUPIL_ID = '$pupil_id'");
return $query->result_array();
}
function getTimetable($class_id, $day)
{
$query = $this->db->query("SELECT sc.SUBJECTS_CLASS_ID, r.ROOM_NAME, s.SUBJECT_NAME, tm.TIME_START, tm.TIME_FINISH, tm.TIME_ID
FROM TIMETABLE t JOIN SUBJECTS_CLASS sc ON t.SUBJECTS_CLASS_ID = sc.SUBJECTS_CLASS_ID
LEFT JOIN SUBJECT s ON s.SUBJECT_ID = sc.SUBJECT_ID
LEFT JOIN ROOM r ON r.ROOM_ID = t.ROOM_ID
JOIN TIME tm ON tm.TIME_ID = t.TIME_ID
WHERE t.DAYOFWEEK_ID = '$day' AND sc.CLASS_ID = '$class_id'
ORDER BY 4");
return $query->result_array();
}
function getPass($lesson, $pupil) {
$query = $this->db->query("SELECT ATTENDANCE_PASS
FROM ATTENDANCE a
WHERE LESSON_ID = '$lesson' AND PUPIL_ID = '$pupil'");
return $query->row_array();
}
function getNote($lesson, $pupil) {
$query = $this->db->query("SELECT NOTE_TEXT
FROM NOTE
WHERE LESSON_ID = '$lesson' AND PUPIL_ID = '$pupil'");
return $query->row_array();
}
function getMarks($lesson, $pupil) {
$query = $this->db->query("SELECT ACHIEVEMENT_MARK, a.ACHIEVEMENT_ID, a.TYPE_ID, t.TYPE_NAME
FROM ACHIEVEMENT a LEFT JOIN TYPE t ON a.TYPE_ID = t.TYPE_ID
WHERE LESSON_ID = '$lesson' AND PUPIL_ID = '$pupil'");
return $query->result_array();
}
function getLessonByDate($subject, $day, $time) {
$query = $this->db->query("SELECT *
FROM LESSON WHERE LESSON_DATE = '$day' AND SUBJECTS_CLASS_ID = '$subject' AND TIME_ID = '$time'");
return $query->row_array();
}
function getPeriods($year) {
$query = $this->db->query("SELECT p.PERIOD_ID, p.PERIOD_FINISH, p.PERIOD_NAME, p.PERIOD_START
FROM PERIOD p JOIN YEAR y ON p.YEAR_ID = y.YEAR_ID
AND PERIOD_NAME != 'Итоговая' AND y.YEAR_ID = '$year' ORDER BY PERIOD_START");
return $query->result_array();
}
function getPeriodById($period) {
$query = $this->db->query("SELECT * FROM PERIOD WHERE PERIOD_ID = '$period'");
return $query->row_array();
}
/*function getAllMarks($pupil, $subject, $start, $end) {
$query = $this->db->query("SELECT ACHIEVEMENT_MARK, TYPE_NAME
FROM ACHIEVEMENT a JOIN TYPE t ON t.TYPE_ID = a.TYPE_ID JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID
WHERE PUPIL_ID = '$pupil' AND SUBJECTS_CLASS_ID = '$subject' AND LESSON_DATE >= '$start'
AND LESSON_DATE <= '$end'");
return $query->result_array();
}*/
function getAllPasses($pupil, $subject, $start, $end) {
$query = $this->db->query("SELECT COUNT(ATTENDANCE_ID) AS 'PASS'
FROM ATTENDANCE a JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID
WHERE PUPIL_ID = '$pupil' AND SUBJECTS_CLASS_ID = '$subject' AND LESSON_DATE >= '$start'
AND LESSON_DATE <= '$end'");
return $query->result_array();
}
function getIllPasses($pupil, $subject, $start, $end) {
$query = $this->db->query("SELECT COUNT(ATTENDANCE_ID) AS 'PASS'
FROM ATTENDANCE a JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID
WHERE PUPIL_ID = '$pupil' AND SUBJECTS_CLASS_ID = '$subject' AND LESSON_DATE >= '$start'
AND LESSON_DATE <= '$end' AND ATTENDANCE_PASS = 'б'");
return $query->result_array();
}
function getAverageMarkForPupil($pupil, $subject, $start, $end) {
$query = $this->db->query("SELECT AVG(ACHIEVEMENT_MARK) AS MARK
FROM ACHIEVEMENT a JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID
WHERE PUPIL_ID = '$pupil' AND SUBJECTS_CLASS_ID = '$subject' AND LESSON_DATE >= '$start'
AND LESSON_DATE <= '$end'");
return $query->result_array();
}
function getAverageMarkForClass($class_id, $subject, $start, $end) {
$query = $this->db->query("SELECT max(MARK) AS MAX,min(MARK) AS MIN FROM(
SELECT AVG(ACHIEVEMENT_MARK) AS MARK, PUPIL_ID
FROM ACHIEVEMENT a JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID JOIN SUBJECTS_CLASS sc
ON sc.SUBJECTS_CLASS_ID = l.SUBJECTS_CLASS_ID
WHERE l.SUBJECTS_CLASS_ID = '$subject' AND LESSON_DATE >= '$start'
AND LESSON_DATE <= '$end' AND CLASS_ID = '$class_id'
GROUP BY PUPIL_ID) t");
return $query->result_array();
}
function getCountPupilInClassByMark($mark, $pupil, $class_id, $subject, $start, $finish) {
$result = array();
$query = $this->db->query("SELECT COUNT(MARK) AS COUNT FROM( SELECT AVG(ACHIEVEMENT_MARK) AS MARK, PUPIL_ID
FROM ACHIEVEMENT a JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID JOIN SUBJECTS_CLASS sc
ON sc.SUBJECTS_CLASS_ID = l.SUBJECTS_CLASS_ID
WHERE l.SUBJECTS_CLASS_ID = '$subject' AND LESSON_DATE >= '$start'
AND LESSON_DATE <= '$finish' AND CLASS_ID = '$class_id' AND PUPIL_ID != '$pupil'
GROUP BY PUPIL_ID
HAVING AVG(ACHIEVEMENT_MARK) < $mark) t");
$arr = $query->row_array();
$result["min"] = $arr['COUNT'];
$query = $this->db->query("SELECT COUNT(MARK) AS COUNT FROM( SELECT AVG(ACHIEVEMENT_MARK) AS MARK, PUPIL_ID
FROM ACHIEVEMENT a JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID JOIN SUBJECTS_CLASS sc
ON sc.SUBJECTS_CLASS_ID = l.SUBJECTS_CLASS_ID
WHERE l.SUBJECTS_CLASS_ID = '$subject' AND LESSON_DATE >= '$start'
AND LESSON_DATE <= '$finish' AND CLASS_ID = '$class_id' AND PUPIL_ID != '$pupil'
GROUP BY PUPIL_ID
HAVING AVG(ACHIEVEMENT_MARK) = $mark) t");
$arr = $query->row_array();
$result["same"] = $arr['COUNT'];
$query = $this->db->query("SELECT COUNT(MARK) AS COUNT FROM( SELECT AVG(ACHIEVEMENT_MARK) AS MARK, PUPIL_ID
FROM ACHIEVEMENT a JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID JOIN SUBJECTS_CLASS sc
ON sc.SUBJECTS_CLASS_ID = l.SUBJECTS_CLASS_ID
WHERE l.SUBJECTS_CLASS_ID = '$subject' AND LESSON_DATE >= '$start'
AND LESSON_DATE <= '$finish' AND CLASS_ID = '$class_id' AND PUPIL_ID != '$pupil'
GROUP BY PUPIL_ID
HAVING AVG(ACHIEVEMENT_MARK) > $mark) t");
$arr = $query->row_array();
$result["max"] = $arr['COUNT'];
return $result;
}
function getClassByDate($pupil_id, $monday){
$query = $this->db->query("SELECT pc.CLASS_ID, YEAR_START, YEAR_FINISH
FROM PUPILS_CLASS pc JOIN CLASS c ON c.CLASS_ID = pc.CLASS_ID
JOIN YEAR y ON y.YEAR_ID = c.YEAR_ID
WHERE PUPIL_ID = '$pupil_id' AND '$monday' BETWEEN YEAR_START AND YEAR_FINISH");
return $query->row_array();
}
function getFilesForHomework($lesson_id) {
$query = $this->db->query("SELECT * FROM FILE WHERE LESSON_ID = '$lesson_id'");
return $query->result_array();
}
function getClasses($pupil_id) {
$query = $this->db->query("SELECT c.CLASS_ID, CLASS_NUMBER, CLASS_LETTER, YEAR(YEAR_START) AS YEAR_START, c.YEAR_ID,
YEAR(YEAR_FINISH) AS YEAR_FINISH
FROM CLASS c JOIN PUPILS_CLASS pc ON pc.CLASS_ID = c.CLASS_ID LEFT JOIN YEAR y ON c.YEAR_ID = y.YEAR_ID
WHERE PUPIL_ID = '$pupil_id'
ORDER BY YEAR_START DESC");
return $query->result_array();
}
function getMarksForSubject($id, $subject_id, $start, $finish) {
$query = $this->db->query("SELECT ACHIEVEMENT_MARK, TYPE_NAME, LESSON_DATE
FROM ACHIEVEMENT a LEFT JOIN TYPE t ON t.TYPE_ID = a.TYPE_ID
JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID
WHERE PUPIL_ID = '$id' AND SUBJECTS_CLASS_ID = '$subject_id' AND
LESSON_DATE >= '$start' AND LESSON_DATE <= '$finish' ORDER BY LESSON_DATE DESC");
return $query->result_array();
}
function getPassForSubject($id, $subject_id, $start, $finish) {
$query = $this->db->query("SELECT ATTENDANCE_PASS, COUNT(*) AS COUNT
FROM ATTENDANCE a JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID
WHERE PUPIL_ID = '$id' AND SUBJECTS_CLASS_ID = '$subject_id' AND LESSON_DATE >= '$start'
AND LESSON_DATE <= '$finish'
GROUP BY ATTENDANCE_PASS");
return $query->result_array();
}
function getBorders($class_id) {
$query = $this->db->query("SELECT * FROM PERIOD
WHERE YEAR_ID = (SELECT YEAR_ID FROM CLASS WHERE CLASS_ID = '$class_id')
ORDER BY PERIOD_NAME");
return $query->result_array();
}
}
?><file_sep>/application/views/faqview.php
<style type="text/css">
body {
background-image: url(../images/bg.png);
background-repeat: repeat;
}
.panel-default {
background: #563d7c;
color: white;
}
</style>
<div class="container">
<div class="row">
<table>
<tr>
<td>
<div class="panel panel-default">
<div class="panel-body">
<div class="page-header">
<h1>Example page header <small>Subtext for header</small></h1>
</div>
</div>
</div>
</td>
<td>
<img src="<?php echo base_url();?>images/img5.png" class="img-responsive" alt="Responsive image">
</td>
</tr>
<tr>
<td>
<img src="<?php echo base_url();?>images/img2.png" class="img-responsive" alt="Responsive image">
</td>
<td>
<div class="panel panel-default">
<div class="panel-body">
Basic panel example
</div>
</div>
</td>
</tr>
<tr>
<td>
<div class="panel panel-default">
<div class="panel-body">
<div class="page-header">
<h1>Example page header <small>Subtext for header</small></h1>
</div>
</div>
</div>
</td>
<td>
<img src="<?php echo base_url();?>images/img1.png" class="img-responsive" alt="Responsive image">
</td>
</tr>
</table>
</div>
</div><file_sep>/application/views/teacher/progressview.php
<?php
function setColor($mark) {
if ($mark >= 4.5) {
echo '<td class="green">'.$mark.'</td>';
}
if ($mark < 4.5 && $mark >=3.5) {
echo '<td class="yellow">'.$mark.'</td>';
}
if ($mark < 3.5 && $mark >= 2.5) {
echo '<td class="blue">'.$mark.'</td>';
}
if ($mark < 2.5 && $mark > 0) {
echo '<td class="red">'.$mark.'</td>';
}
if ($mark == 0) {
echo '<td class="grey">'.$mark.'</td>';
}
}
?>
<div class="container">
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-4">
<form method="post">
<label for="class" class="control-label"><i class="fa fa-users"></i> Класс</label>
<select id="class" name="class" onchange="this.form.submit();" style="width: 70%">
<?php
foreach ($classes as $class) {
if(isset($class['YEAR_ID'])) $year_border = " (".date("Y",strtotime($class['YEAR_START']))." - ".date("Y",strtotime($class['YEAR_FINISH']))." гг.)"; else $year_border = '';
?>
<option value="<?php echo $class['CLASS_ID']?>"><?php echo $class['CLASS_NUMBER']." ".$class['CLASS_LETTER'].$year_border; ?></option>
<?php
}
?>
</select>
</form>
</div>
<div class="col-md-8">
<form method="post">
<label for="subject" class="control-label"><i class="fa fa-book"></i> Предмет</label>
<select id="subject" name="subject" onchange="this.form.submit();" style="width: 50%">
<?php
foreach ($subjects as $subject) {
?>
<option value="<?php echo $subject['SUBJECTS_CLASS_ID']?>"><?php echo $subject['SUBJECT_NAME']; ?></option>
<?php } ?>
</select>
</form>
</div>
</div>
<div class="row">
<div class="col-md-8">
<h3 class="sidebar-header">Итоговые оценки</h3>
</div>
<div class="col-md-4" >
<h5><span onclick="print();" class="a-block pull-right" title="Печать"><i class="fa fa-print"></i> Печать</span></h5>
</div>
</div>
<div class="panel panel-default">
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered numeric" id="progress">
<thead>
<tr>
<th rowspan="2">#</th>
<th rowspan="2" hidden="true"></th>
<th rowspan="2" >ФИО учащегося</th>
<th colspan="2">I четверть</th>
<th colspan="2">II четверть</th>
<th colspan="2">III четверть</th>
<th colspan="2">IV четверть</th>
<th colspan="2">Итоговая</th>
</tr>
<tr>
<th style="border-bottom-width: 1px;">Ср.</br>балл</th>
<th style="border-bottom-width: 1px;">Оценка</th>
<th style="border-bottom-width: 1px;">Ср.</br>балл</th>
<th style="border-bottom-width: 1px;">Оценка</th>
<th style="border-bottom-width: 1px;">Ср.</br>балл</th>
<th style="border-bottom-width: 1px;">Оценка</th>
<th style="border-bottom-width: 1px;">Ср.</br>балл</th>
<th style="border-bottom-width: 1px;">Оценка</th>
<th style="border-bottom-width: 1px;">Ср.</br>балл</th>
<th style="border-bottom-width: 1px;">Оценка</th>
</tr>
</thead>
<tbody>
<?php
if(isset($marks)) {
for($i = 0; $i < count($marks); $i++) {
?>
<tr>
<td data-editable='false'><?php echo $i+1;?></td>
<td hidden="true" data-editable='false' id="pupil_id"><?php echo $marks[$i]["pupil_id"];?></td>
<td data-editable='false'><?php echo $marks[$i]["pupil_name"];?></td>
<td class="grey" data-editable='false'><?php echo $marks[$i]["I четверть"]["average"];?></td>
<?php if(isset($marks[$i]["I четверть"]["mark"])) setColor($marks[$i]["I четверть"]["mark"]); else echo "<td></td>";?>
<td class="grey" data-editable='false'><?php echo $marks[$i]["II четверть"]["average"];?></td>
<?php if(isset($marks[$i]["II четверть"]["mark"])) setColor($marks[$i]["II четверть"]["mark"]); else echo "<td></td>";?>
<td class="grey" data-editable='false'><?php echo $marks[$i]["III четверть"]["average"];?></td>
<?php if(isset($marks[$i]["III четверть"]["mark"])) setColor($marks[$i]["III четверть"]["mark"]); else echo "<td></td>";?>
<td class="grey" data-editable='false'><?php echo $marks[$i]["IV четверть"]["average"];?></td>
<?php if(isset($marks[$i]["IV четверть"]["mark"])) setColor($marks[$i]["IV четверть"]["mark"]); else echo "<td></td>";?>
<td class="grey" data-editable='false'><?php echo $marks[$i]["Итоговая"]["average"];?></td>
<?php if(isset($marks[$i]["Итоговая"]["mark"])) setColor($marks[$i]["Итоговая"]["mark"]); else echo "<td></td>";?>
</tr>
<?php
}}
?>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
document.getElementById('class').value = "<?php echo $this->uri->segment(3);?>";
document.getElementById('subject').value = "<?php echo $this->uri->segment(4);?>";
$("#class").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
$("#subject").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
$('table#progress').editableTableWidget();
$('table td').focus(function(){
$(this).data('oldValue',$(this).text());
});
$('table td').on('change', function(evt, newValue) {
var base_url = '<?php echo base_url();?>';
//старое значение
var oldValue = $(this).data('oldValue');
if (!(newValue == 5 || newValue == 4 || newValue == 3 || newValue == 2 || newValue == "")) {
return false; // reject change
} else {
$(this).removeClass();
//можем редактировать
if(newValue == 5) {
$(this).addClass("green");
}
if(newValue == 4) {
$(this).addClass("yellow");
}
if(newValue == 3) {
$(this).addClass("blue");
}
if(newValue == 2) {
$(this).addClass("red");
}
var class_id = $('#class').find("option:selected").val();
var subject_id = $('#subject').find("option:selected").val();
if (newValue != oldValue) {
var pupil_id = $(this).parent().find('#pupil_id').html();
var period = $('table th').eq($(this).index()/2+1).text();
//alert(period);
$.ajax({
type: "POST",
url: base_url + "table/changeprogress",
data: "pupil_id=" + pupil_id + "&period=" + period + "&class_id=" + class_id + "&subject_id=" +
subject_id + "&mark=" + newValue,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
//location.reload();
}
});
}
}
});
});
</script><file_sep>/application/views/pupil/diaryview.php
<link href="<?php echo base_url()?>css/btn-sample.css" rel="stylesheet">
<?php
function showDate($date) {
$day = date('d', strtotime($date));
$mounth = date('m', strtotime($date));
$year = date('Y', strtotime($date));
$data = array('01'=>'января','02'=>'февраля','03'=>'марта','04'=>'апреля','05'=>'мая','06'=>'июня',
'07'=>'июля', '08'=>'августа','09'=>'сентября','10'=>'октября','11'=>'ноября','12'=>'декабря');
foreach ($data as $key=>$value) {
if ($key==$mounth) echo "<b>".ltrim($day, '0')." $value $year года</b>";
}
}
function setColor($mark, $tooltip) {
switch ($mark) {
case 5: echo '<span data-toggle="tooltip" data-placement="top" title="'.$tooltip.'" class="label label-success">'.$mark.'</span>'; break;
case 4: echo '<span data-toggle="tooltip" data-placement="top" title="'.$tooltip.'" class="label label-warning">'.$mark.'</span>'; break;
case 3: echo '<span data-toggle="tooltip" data-placement="top" title="'.$tooltip.'" class="label label-primary">'.$mark.'</span>'; break;
case 2: echo '<span data-toggle="tooltip" data-placement="top" title="'.$tooltip.'" class="label label-danger">'.$mark.'</span>'; break;
}
}
?>
<div class="container">
<div class="well well-sm"><span>
<i class="fa fa-bookmark"></i>
</span> Учебная неделя с <?php echo showDate($monday);?> по <?php echo showDate(date('Y-m-d', strtotime($monday . ' + 6 day')));?>
</span>
</div>
<ul class="pager" id="diary-navigation">
<li class="previous" title="Назад на одну неделю">
<a href="<?php echo base_url();?>pupil/diary/<?php echo date('Y-m-d', strtotime($monday . ' - 7 day')); ?>"><i class="fa fa-chevron-left"></i> Назад</a>
</li>
<li title="Показать текущую неделю">
<a href="<?php echo base_url();?>pupil/diary/<?php echo date('Y-m-d', strtotime(date('Y-m-d'). " - " . (date('N', strtotime(date('Y-m-d'))) - 1) . " days")); ?>">Текущая неделя</a>
</li>
<li class="next" title="Вперед на одну неделю">
<a href="<?php echo base_url();?>pupil/diary/<?php echo date('Y-m-d', strtotime($monday . ' + 7 day'));?>">Вперед <i class="fa fa-chevron-right"></i></a>
</li>
</ul>
<?php
if (isset($error)) : ?>
<div class="alert alert-info" role="alert"><?php echo $error;?></div>
<?php else : ?>
<?php
$date = $monday;
if(is_array($diary)) :
for($i = 1; $i <= count($diary); $i++) :
?>
<h4 class="sidebar-header">
<?php
echo $days[$i-1]. " ";
echo showDate($date);
$date = date('Y-m-d', strtotime($date . ' + 1 day'));
?>
</h4>
<div class="panel panel-default">
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th style="width: 20%;">Предмет</th>
<th style="width: 25%;">Оценки</th>
<th style="width: 15%;">Домашнее задание</th>
<th style="width: 25%;">Замечания</th>
<th style="width: 15%;">Статус урока</th>
</tr>
</thead>
<tbody>
<?php
foreach ($diary[$i] as $diaryForDay) :
switch ($diaryForDay["pass"]) {
case 'н':?><tr class="warning"><?php break;
case 'б':?><tr class="success"><?php break;
case 'у':?><tr class="info"><?php break;
default:?><tr><?php break;
}
?>
<td><?php echo $diaryForDay["subject"]; ?></td>
<td>
<?php
if(isset($diaryForDay["marks"])) {
foreach($diaryForDay["marks"] as $marks) {
setColor($marks["mark"], $marks["type"]);
echo " ";
}
}
?>
</td>
<td>
<?php if (isset($diaryForDay["homework"]) && ($diaryForDay['homework'] != "" /*|| count($diaryForDay['files']) > 0*/)) : ?>
<button class="btn btn-sample btn-xs" title="Показать домашнее задание" type="button" data-toggle="modal" data-target="#myModal<?php echo $diaryForDay["lesson_id"];?>"><i class="fa fa-home"></i> Домашнее задание
</button>
<div class="modal fade" id="myModal<?php echo $diaryForDay["lesson_id"];?>" 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" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Домашнее задание по предмету <strong><?php echo $diaryForDay["subject"]; ?></strong></h4>
</div>
<div class="modal-body">
<?php echo $diaryForDay['homework']; ?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Закрыть</button>
</div>
</div>
</div>
</div>
<?php endif; ?>
</td>
<td>
<?php echo $diaryForDay["note"]; ?>
</td>
<td>
<?php
if (isset($diaryForDay["lesson_status"]) && $diaryForDay["lesson_status"] == 1)
echo "Проведен";
?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<?php
endfor;
endif;
endif;
?>
<ul class="pager" id="diary-navigation">
<li class="previous" title="Назад на одну неделю">
<a href="<?php echo base_url();?>pupil/diary/<?php echo date('Y-m-d', strtotime($monday . ' - 7 day')); ?>"><i class="fa fa-chevron-left"></i> Назад</a>
</li>
<li title="Показать текущую неделю">
<a href="<?php echo base_url();?>pupil/diary/<?php echo date('Y-m-d', strtotime(date('Y-m-d'). " - " . (date('N', strtotime(date('Y-m-d'))) - 1) . " days")); ?>">Текущая неделя</a>
</li>
<li class="next" title="Вперед на одну неделю">
<a href="<?php echo base_url();?>pupil/diary/<?php echo date('Y-m-d', strtotime($monday . ' + 7 day'));?>">Вперед <i class="fa fa-chevron-right"></i></a>
</li>
</ul>
<table class="brand-table">
<tr>
<td><div class="color-swatch brand-success"></div></td>
<td>Пропуск по болезни</td>
</tr>
<tr>
<td><div class="color-swatch brand-info"></div></td>
<td>Пропуск по уважительной причине</td>
</tr>
<tr>
<td><div class="color-swatch brand-warning"></div></td>
<td>Пропуск по неуважительной причине</td>
</tr>
</table>
</div><file_sep>/application/views/blankview/blanksubjectview.php
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><?php echo $title; ?></div>
<div class="panel-body">
<form method="post">
<div hidden="true" id="id"><?php if(isset($id)) echo $id;?></div>
<div class="form-horizontal">
<div class="form-group">
<label for="inputSubject" class="col-sm-2 col-md-2 control-label">Предмет <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<input type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Наименование общего предмета" required="true" maxlength="100" autofocus value="<?php if(isset($subject)) echo $subject;?>">
<div class="red" id="responseSubjectError"></div>
</div>
</div>
</div>
<div class="grey">* - Обязательные поля</div>
<div id="error" class="red"></div>
<div class="modal-footer" style="margin-bottom: -15px; padding-right: 0px;">
<button type="button" class="btn btn-default" onclick="javascript:history.back();" title="Отменить">Отменить</button>
<button type="submit" class="btn btn-sample" name="save" id="save" title="Сохранить">Сохранить</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#save').click(function() {
var base_url = '<?php echo base_url();?>';
var s = 0;
var error = 0;
var subject_name = $.trim($('#inputSubject').val());
var id = $('#id').text();
if (subject_name.length == 0) {
$('#inputSubject').parent().addClass("has-error");
$("#responseSubjectError").text('');
s++;
} else {
$('#inputSubject').parent().removeClass("has-error");
$.ajax({
type: "POST",
url: base_url + "table/responsesubject",
data: "name=" + subject_name + "&id=" + id,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
if (response == true) {
$("#responseSubjectError").text('В списке уже есть такой общий предмет');
$('#inputSubject').parent().addClass("has-error");
error++;
}
if (response == false) {
$("#responseSubjectError").text('');
$('#inputSubject').parent().removeClass("has-error");
}
}
});
}
if (s != 0) {
$("#error").text('Не все обязательные поля заполнены');
}
else {
$("#error").text('');
}
//alert(s + " " + error);
if (s == 0 && error == 0) {
/*if (id == "") {
$.ajax({
type: "POST",
url: base_url + "table/addsubject",
data: "name=" + subject_name,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
document.location.href = base_url + 'admin/subjects';
}
});
}
else {
$.ajax({
type: "POST",
url: base_url + "table/updatesubject",
data: "name=" + subject_name + "&id=" + id,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
document.location.href = base_url + 'admin/subjects';
}
});
}*/
} else {
return false;
}
});
});
</script>
<file_sep>/application/views/blankview/blanksubjectsclassview.php
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><?php echo $title; ?></div>
<div class="panel-body">
<form method="post">
<div hidden="true" id="id"><?php if(isset($id)) echo $id;?></div>
<div class="form-horizontal">
<div class="form-group">
<label for="inputSubject" class="col-sm-2 col-md-2 control-label">Общий предмет <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<select id="inputSubject" name="inputSubject" class="width-select">
<?php
if(isset($subjects)) {
if($subject_id == null && isset($id)) echo "<option value=''></option>";
foreach($subjects as $subject) {
if ($subject_id != "") {
if($subject['SUBJECT_ID'] == $subject_id) {
echo "<option selected='selected' value='".$subject['SUBJECT_ID']."'>".$subject['SUBJECT_NAME']."</option>";
} else {
echo "<option value='".$subject['SUBJECT_ID']."'>".$subject['SUBJECT_NAME']."</option>";
}
} else {
echo "<option value='".$subject['SUBJECT_ID']."'>".$subject['SUBJECT_NAME']."</option>";
}
}
}
?>
</select>
</div>
</div>
<div class="form-group">
<label for="inputTeacher" class="col-sm-2 col-md-2 control-label">ФИО учителя <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<select id="inputTeacher" name="inputTeacher" class="width-select">
<?php
if(isset($teachers)) {
if($teacher_id == null && isset($id)) echo "<option value=''></option>";
foreach($teachers as $teacher) {
if ($teacher_id != "") {
if($teacher['TEACHER_ID'] == $teacher_id) {
echo "<option selected='selected' value='".$teacher['TEACHER_ID']."'>".$teacher['TEACHER_NAME']."</option>";
} else {
echo "<option value='".$teacher['TEACHER_ID']."'>".$teacher['TEACHER_NAME']."</option>";
}
} else {
echo "<option value='".$teacher['TEACHER_ID']."'>".$teacher['TEACHER_NAME']."</option>";
}
}
}
?>
</select>
<div class="red" id="responseTeacherError"></div>
</div>
</div>
</div>
<div class="grey">* - Обязательные поля</div>
<div id="error" class="red"></div>
<div class="modal-footer" style="margin-bottom: -15px; padding-right: 0px;">
<button type="button" class="btn btn-default" onclick="javascript:history.back();" title="Отменить">Отменить</button>
<button type="submit" class="btn btn-sample" name="save" id="save" title="Сохранить">Сохранить</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#inputTeacher").select2({
language: "ru"
});
$("#inputSubject").select2({
language: "ru"
});
$('#save').click(function() {
var base_url = '<?php echo base_url();?>';
var s = 0;
var error = 0;
var teacher = $('#inputTeacher').find("option:selected").val();
var subject = $('#inputSubject').find("option:selected").val();
var id = $('#id').text();
if (teacher == "") {
s++;
}
if(subject == "") {
s++;
}
$("#responseTeacherError").text('');
if(teacher != "" && subject != "") {
$.ajax({
type: "POST",
url: base_url + "table/responsesubjectsclass",
data: "teacher=" + teacher + "&subject=" + subject + "&id=" + id,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
//alert(response);
if (response == true) {
$("#responseTeacherError").text('В списке уже есть такой предмет в классе');
error++;
}
if (response == false) {
$("#responseTeacherError").text('');
}
}
});
}
if (s != 0) {
$("#error").text('Не все обязательные поля заполнены');
}
else {
$("#error").text('');
}
//alert(s + " " + error);
if (s == 0 && error == 0) {
/*if (id == "") {
$.ajax({
type: "POST",
url: base_url + "table/addsubjectsclass",
data: "teacher=" + teacher + "&subject=" + subject,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
document.location.href = base_url + 'teacher/subjects';
}
});
}
else {
$.ajax({
type: "POST",
url: base_url + "table/updatesubjectsclass",
data: "teacher=" + teacher + "&subject=" + subject + "&id=" + id,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
//alert(response);
document.location.href = base_url + 'teacher/subjects';
}
});
}*/
} else return false;
});
});
</script>
<file_sep>/application/views/admin/yearsview.php
<div class="container">
<h3 class="sidebar-header"><i class="fa fa-calendar"></i> Список учебных годов</h3>
<div class="panel panel-default panel-table">
<div class="panel-body">
<button type="button" class="btn btn-menu" id="createButton" title="Добавить учебный год"><i class="fa fa-plus fa-2x"></i>
</br><span class="menu-item">Создать</span>
</button>
<button href="" type="button" class="btn btn-menu disabled" id="editButton" title="Редактировать учебный год"><i class="fa fa-pencil fa-2x"></i>
</br><span class="menu-item">Редактировать</span>
</button>
<button type="button" class="btn btn-menu disabled" id="deleteButton" data-toggle="modal" data-target="#myModal" title="Удалить учебный год"><i class="fa fa-trash-o fa-2x"></i>
</br><span class="menu-item">Удалить</span>
</button>
</div>
</div>
<div class="panel panel-default">
<div class="table-responsive">
<table name="timetable" class="table table-striped table-hover table-bordered numeric">
<thead>
<tr>
<th></th>
<th colspan="2">Учебный год</th> <!--1-->
<th colspan="2">I четверть</th> <!--1-->
<th colspan="2">II четверть</th> <!--1-->
<th colspan="2">III четверть</th> <!--1-->
<th colspan="2">IV четверть</th> <!--1-->
</tr>
<tr>
<th style="border-bottom-width: 1px;"></th>
<th style="border-bottom-width: 1px;">Начало</th>
<th style="border-bottom-width: 1px;">Конец</th>
<th style="border-bottom-width: 1px;">Начало</th>
<th style="border-bottom-width: 1px;">Конец</th>
<th style="border-bottom-width: 1px;">Начало</th>
<th style="border-bottom-width: 1px;">Конец</th>
<th style="border-bottom-width: 1px;">Начало</th>
<th style="border-bottom-width: 1px;">Конец</th>
<th style="border-bottom-width: 1px;">Начало</th>
<th style="border-bottom-width: 1px;">Конец</th>
</tr>
</thead>
<tbody>
<?php
if(is_array($periods) && count($periods) ) {
for($i =0; $i < count($periods); $i++){
?>
<tr>
<td><input type="radio" name="year_id" value="<?php echo $periods[$i]["id"];?>"></td>
<td><?php echo $periods[$i]["fifth"]["start"];?></td>
<td><?php echo $periods[$i]["fifth"]["finish"];?></td>
<td><?php if(isset($periods[$i]["first"]["start"])) echo $periods[$i]["first"]["start"];?></td>
<td><?php if(isset($periods[$i]["first"]["finish"])) echo $periods[$i]["first"]["finish"];?></td>
<td><?php if(isset($periods[$i]["second"]["start"])) echo $periods[$i]["second"]["start"];?></td>
<td><?php if(isset($periods[$i]["second"]["finish"])) echo $periods[$i]["second"]["finish"];?></td>
<td><?php if(isset($periods[$i]["third"]["start"]))echo $periods[$i]["third"]["start"];?></td>
<td><?php if(isset($periods[$i]["third"]["finish"]))echo $periods[$i]["third"]["finish"];?></td>
<td><?php if(isset($periods[$i]["forth"]["start"])) echo $periods[$i]["forth"]["start"];?></td>
<td><?php if(isset($periods[$i]["forth"]["finish"])) echo $periods[$i]["forth"]["finish"];?></td>
</tr>
<?php }} ?>
</tbody>
</table>
</div>
</div>
<?php echo $this->pagination->create_links(); ?>
<?php
if(is_array($periods) && count($periods) == 0 && isset($search) && $search != "") {
?>
<div class="alert alert-info" role="alert">Поиск не дал результатов. Попробуйте другой запрос</div>
<?php } ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
$(":radio[name=year_id]").change(function() {
$('#editButton').removeClass('disabled');
$('#deleteButton').removeClass('disabled');
});
$('#createButton').click(function() {
document.location.href = '<?php echo base_url(); ?>admin/year';
});
$('#editButton').click(function() {
var value = $(":radio[name=year_id]").filter(":checked").val();
document.location.href = '<?php echo base_url(); ?>admin/year/' + value;
});
$('#searchButton').click(function() {
//$('#search').slideToggle("fast");
});
$('#buttonDeleteYearModal').click(function() {
var value = $(":radio[name=year_id]").filter(":checked").val();
var base_url = '<?php echo base_url();?>';
$.ajax({
type: "POST",
url: base_url + "table/del/year/" + value,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(a) {
location.reload();
}
});
});
$("tr:not(:first)").click(function() {
$(this).children("td").find('input[type=radio]').prop('checked', true).change();
});
});
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Удаление учебного года</h4>
</div>
<div class="modal-body">
<p>Вы уверены, что хотите удалить этот учебный год?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-sample" id="buttonDeleteYearModal">Удалить</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<file_sep>/application/controllers/Pupil.php
<?php
class Pupil extends CI_Controller {
private $pupil_role = null;
var $pupil_id = null;
var $pupil_login = null;
var $pupil_class = null;
public function __construct() {
parent::__construct();
$this->load->model('pupilmodel', 'pupil');
$this->load->library("roleenum");
$this->pupil_role = $this->session->userdata('role');
$this->pupil_login = $this->session->userdata('login');
$this->pupil_id = $this->session->userdata('id');
$this->pupil_class = $this->session->userdata('class_id');
}
function _remap($method, $params = array()) {
$login = $this->pupil_login; //$this->session->userdata('login');
$role = $this->pupil_role; //$this->session->userdata('role');
$roleEnum = $this->roleenum;
if(isset($login) && isset($role) && $role == $roleEnum::Pupil) {
$data['role'] = $role;
$data['mainlogin'] = $login;
switch($method) {
case 'news': {
$data['title'] = "Новости";
break;
}
case 'timetable': {
$data['title'] = "Расписание";
break;
}
case 'diary': {
$data['title'] = "Дневник";
break;
}
case 'progress': {
$data['title'] = "Итоговые оценки";
break;
}
case 'message': {
$data['title'] = "Общение";
break;
}
case 'faq': {
$data['title'] = "Помощь";
break;
}
case 'statistics': {
$data['title'] = "Статистика";
break;
}
case 'marks': {
$data['title'] = "Оценки";
break;
}
}
/*$this->load->view('header', $data);
switch($method) {
case 'news': {
$this->news();
break;
}
case 'timetable': {
$this->timetable();
break;
}
case 'diary': {
$this->diary();
break;
}
case 'progress': {
$this->progress();
break;
}
case 'message': {
$this->message();
break;
}
case 'lesson': {
$this->lesson();
break;
}
case 'faq': {
$this->faq();
break;
}
case 'statistics': {
$this->statistics();
break;
}
default: {
redirect('pupil/news');
break;
}
}
$this->load->view('footer');*/
$this->load->view('header', $data);
if (method_exists($this, $method))
{
call_user_func_array(array($this, $method), $params);
}
else {
redirect("pupil/news");
}
$this->load->view('footer');
}
else {
redirect('auth/logout');
}
}
private function _dayOfWeek() {
$day = date("w");
if ($day == 0) $day = 7;
return $day;
}
private function _getTimetableForDay($class_id, $day) {
$result = $this->pupil->getTimetable($class_id, $day);
$arrResult = array();
foreach ($result as $row) {
$arrResult[] = array("start"=> $row['TIME_START'],"finish"=>$row['TIME_FINISH'],
"name"=>$row['SUBJECT_NAME'], "room" => $row['ROOM_NAME']);
}
return $arrResult;
}
function timetable() {
$login = $this->pupil_login; //$this->session->userdata('login');
$role = $this->pupil_role; //$this->session->userdata('role');
$class_id = $this->pupil_class; //$this->session->userdata('class_id');
$data['role'] = $role;
$days = array('Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота');
$data = array();
$data['days'] = $days;
$arr = array();
for ($i = 0; $i < 6; $i++) {
$arr[$i] = $this->_getTimetableForDay($class_id, $i+1);
}
$data['timetable'] = $arr;
$this->load->view('pupil/timetableview', $data);
}
function news($offset = 1) {
//Новости
// Переменная хранит число сообщений выводимых на станице
$num = 4;
$config['total_rows'] = $this->pupil->totalNews();
$config['base_url'] = base_url()."pupil/news";
$config['per_page'] = $num;
$this->pagination->initialize($config);
$query = $this->pupil->getNews($num, $offset * $num - $num);
$data['news'] = null;
if($query) {
$data['news'] = $query;
}
//Расписание
$class_id = $this->pupil_class; // $this->session->userdata('class_id');
$data['timetable'] = $this->_getTimetableForDay($class_id, $this->_dayOfWeek());
$this->load->view('pupil/sidebarview', $data);
$this->load->view('pupil/newsview', $data);
}
function post($id = null) {
if(isset($id)) {
$post = $this->pupil->getNewsbyId($id);
$data['theme'] = $post['NEWS_THEME'];
$data['time'] = $post['NEWS_TIME'];
$data['text'] = $post['NEWS_TEXT'];
$data['teacher'] = $post['TEACHER_NAME'];
//Расписание
$class_id = $this->pupil_class; //$this->session->userdata('class_id');
$data['timetable'] = $this->_getTimetableForDay($class_id, $this->_dayOfWeek());
$this->load->view('pupil/sidebarview', $data);
$this->load->view('pupil/postview', $data);
} else {
//ошибка
$data['error'] = "Ошибка";
$this->load->view("errorview", $data);
}
}
private function _getDiary($monday, $class_id) {
$pupil_id = $this->pupil_id; // $this->session->userdata('id');
$day = date("Y-m-d", strtotime($monday));
$diary = array();
for ($i = 1; $i <= 6; $i++) {
$result = $this->pupil->getTimetable($class_id, $i);
$diary[$i] = array();
$y = 1;
if (count($result) == 0) {
$diary[$i] = array();
} else {
foreach ($result as $row) {
$diary[$i][$y] = array();
$diary[$i][$y]["subject"] = $row['SUBJECT_NAME'];
$diary[$i][$y]["subject_id"] = $row['SUBJECTS_CLASS_ID'];
$currentday = $day;
$time_id = $row['TIME_ID'];
$lesson = $this->pupil->getLessonByDate($row['SUBJECTS_CLASS_ID'], $currentday, $time_id);
if (!isset($lesson)) {
$diary[$i][$y]["lesson_id"] = 0;
$diary[$i][$y]["lesson_status"] = 0;
$diary[$i][$y]["homework"] = "";
$diary[$i][$y]["files"] = array();
$diary[$i][$y]["marks"] = array();
$diary[$i][$y]["pass"] = "";
$diary[$i][$y]["note"] = "";
} else {
$diary[$i][$y]["lesson_id"] = $lesson['LESSON_ID'];
$diary[$i][$y]["lesson_status"] = $lesson['LESSON_STATUS'];
if (isset($lesson['LESSON_HOMEWORK'])) {
$diary[$i][$y]["homework"] = $lesson['LESSON_HOMEWORK'];
} else $diary[$i][$y]["homework"] = null;
/*$files = $this->pupil->getFilesForHomework($lesson['LESSON_ID']);
$diary[$i][$y]["file"] = count($files);
if (count($files) > 0) {
$diary[$i][$y]["files"] = array();
$f = 1;
foreach($files as $file) {
$diary[$i][$y]["files"][$f]["name"] = $file['FILE_NAME'].".".$file['FILE_EXTENSION'];
$diary[$i][$y]["files"][$f]["path"] = base_url()."files/".$file['FILE_ID'].".".$file['FILE_EXTENSION'];
$f++;
}
} else $diary[$i][$y]["files"] = null;*/
//получаем пропуск
$pass = $this->pupil->getPass($lesson['LESSON_ID'], $pupil_id);
$diary[$i][$y]["pass"] =isset($pass) ? $pass['ATTENDANCE_PASS'] : "";
//получаем замечание
$diary[$i][$y]["note"] = isset($note) ? $note['NOTE_TEXT'] : "";
//получаем оценки
$marks = $this->pupil->getMarks($lesson['LESSON_ID'], $pupil_id);
$diary[$i][$y]["marks"] = array();
$z = 1;
foreach ($marks as $mark) {
$diary[$i][$y]["marks"][$z]["mark"] = $mark['ACHIEVEMENT_MARK'];
$diary[$i][$y]["marks"][$z]["type"] = $mark['TYPE_NAME'];
$z++;
}
}
$y++;
}
}
$day = date('Y-m-d', strtotime($monday. ' + '.$i.' days'));
}
return $diary;
}
function diary($monday = null) {
$pupil_id = $this->pupil_id; //$this->session->userdata('id');
if(!isset($monday)) {
$string_date = date('Y-m-d');
$day_of_week = date('N', strtotime($string_date));
$week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
redirect(base_url()."pupil/diary/".$week_first_day);
} else {
$week_first_day = date('Y-m-d', strtotime($monday . " - " . (date('N', strtotime($monday)) - 1) . " days"));
//является ли дата понедельником
if ($monday == $week_first_day) {
$data['days'] = array('Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота');
$arr = $this->pupil->getClassByDate($pupil_id, $monday);
if (isset($arr)) {
$class_id = $arr['CLASS_ID'];
$diary = $this->_getDiary($monday, $class_id);
if (!$diary) {
$data['error'] = "Учебных занятий нет";
$data['diary'] = array();
}
else {
$data['error'] = null;
$data['diary'] = $diary;
}
} else {
$data['error'] = "Каникулы";
$data['diary'] = null;
}
//print_r($data['diary']);
$data['monday'] = $monday;
$this->load->view('pupil/diaryview', $data);
}
else {
$string_date = date('Y-m-d');
$day_of_week = date('N', strtotime($string_date));
$week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
redirect(base_url()."pupil/diary/".$week_first_day);
}
}
}
private function _getYears() {
$years = $this->pupil->getYears();
$arr = array();
foreach ($years as $row) {
$arr[$row['YEAR_ID']] = date("Y", strtotime($row['YEAR_START'])).' - '.date("Y", strtotime($row['YEAR_FINISH']));
}
return $arr;
}
private function _getTotalMarks($year) {
$pupil_id = $this->pupil_id; //$this->session->userdata('id');
//Получаем класс
$result = $this->pupil->getClassInYear($pupil_id, $year);
foreach ($result as $row) {
$class_id = $row['CLASS_ID'];
}
if (isset($class_id)) {
//Получаем предметы в классе
$result = $this->pupil->getSubjectsClass($class_id);
$arr = array();
foreach ($result as $row) {
$arr[$row['SUBJECTS_CLASS_ID']]["subject"] = $row['SUBJECT_NAME'];
}
while ($subject = current($arr)) {
$result = $this->pupil->getProgressMarks(key($arr), $pupil_id);
foreach ($result as $row) {
$arr[key($arr)][$row['PERIOD_NAME']] = $row['PROGRESS_MARK'];
}
next($arr);
}
foreach ($arr as $key => $value) {
for ($i = 1; $i <= 5; $i++) {
if (!isset($arr[$key][$i])) {
$arr[$key][$i]="н/д";
}
}
}
}
else $arr = null;
return $arr;
}
function progress($year = null) {
$years = $this->_getYears();
if (isset($year)) {
if(isset($_POST['year'])) {
$year = $_POST['year'];
redirect(base_url().'pupil/progress/'.$year);
}
if(in_array($year, array_keys($years))) {
$result = $this->_getTotalMarks($year);
$data['years'] = $years;
$data['result'] = $result;
$this->load->view('pupil/progressview', $data);
} else {
//ошибка
$data['error'] = "Выбранного периода не существует. Вернитесь обратно";
$this->load->view("errorview", $data);
}
}
else {
if(isset(array_keys($years)[0])) {
$year = array_keys($years)[0];
$url = base_url();
$url = $url.'pupil/progress/'.$year;
redirect($url);
} else {
//ошибка
$data['error'] = "В системе отсутствуют учебные года";
$this->load->view("errorview", $data);
}
}
}
private function _getStatistics($year, $period) {
$pupil_id = $this->pupil_id; //$this->session->userdata('id');
//начало и конец периода
$period = $this->pupil->getPeriodById($period);
$start = $period['PERIOD_START'];
$finish = $period['PERIOD_FINISH'];
//Получаем класс
$result = $this->pupil->getClassInYear($pupil_id, $year);
foreach ($result as $row) {
$class_id = $row['CLASS_ID'];
}
if (isset($class_id)) {
$arr = array();
$subjects = $this->pupil->getSubjectsClass($class_id);
foreach($subjects as $subject) {
$arr[$subject['SUBJECTS_CLASS_ID']]["subject"] = $subject['SUBJECT_NAME'];
$marks = $this->pupil->getAverageMarkForPupil($pupil_id, $subject['SUBJECTS_CLASS_ID'], $start, $finish);
if (count($marks) == 0) {
$arr[$subject['SUBJECTS_CLASS_ID']]["average"] = null;
}
else {
foreach($marks as $mark) {
$arr[$subject['SUBJECTS_CLASS_ID']]["average"] = number_format($mark['MARK'],1);
}
}
$marks = $this->pupil->getAverageMarkForClass($class_id, $subject['SUBJECTS_CLASS_ID'], $start, $finish);
if (count($marks) == 0) {
$arr[$subject['SUBJECTS_CLASS_ID']]["min"] = null;
$arr[$subject['SUBJECTS_CLASS_ID']]["max"] = null;
}
else {
foreach($marks as $mark) {
$arr[$subject['SUBJECTS_CLASS_ID']]["min"] = number_format($mark['MIN'],1);
$arr[$subject['SUBJECTS_CLASS_ID']]["max"] = number_format($mark['MAX'],1);
}
}
//всего пропусков
/*$passes = $this->pupil->getAllPasses($pupil_id, $subject['SUBJECTS_CLASS_ID'], $start, $finish);
if (count($passes) == 0) {
$arr[$subject['SUBJECTS_CLASS_ID']]["pass"] = null;
}
else {
foreach($passes as $pass) {
$arr[$subject['SUBJECTS_CLASS_ID']]["pass"] = $pass['PASS'];
}
}
//по болезни
$passes = $this->pupil->getIllPasses($pupil_id, $subject['SUBJECTS_CLASS_ID'], $start, $finish);
if (count($passes) == 0) {
$arr[$subject['SUBJECTS_CLASS_ID']]["ill"] = null;
}
else {
foreach($passes as $pass) {
$arr[$subject['SUBJECTS_CLASS_ID']]["ill"] = $pass['PASS'];
}
}*/
$counts = $this->pupil->getCountPupilInClassByMark($arr[$subject['SUBJECTS_CLASS_ID']]["average"], $pupil_id, $class_id,
$subject['SUBJECTS_CLASS_ID'], $start, $finish);
$arr[$subject['SUBJECTS_CLASS_ID']]["min_count"] = $counts["min"];
$arr[$subject['SUBJECTS_CLASS_ID']]["same_count"] = $counts["same"];
$arr[$subject['SUBJECTS_CLASS_ID']]["max_count"] = $counts["max"];
}
} else $arr = null;
return $arr;
}
private function _getPeriodsForYear($year) {
$periods = $this->pupil->getPeriods($year);
$arr = array();
foreach ($periods as $row) {
$arr[$row['PERIOD_ID']]["start"] = $row['PERIOD_START'];
$arr[$row['PERIOD_ID']]["finish"] = $row['PERIOD_FINISH'];
$arr[$row['PERIOD_ID']]["name"] = $row['PERIOD_NAME'];
}
return $arr;
}
function statistics($year = null, $period = null) {
$years = $this->_getYears();
if (!isset($year) || !isset($period)) {
$year = array_keys($years)[0];
$period = array_keys($this->_getPeriodsForYear($year))[0];
$url = base_url().'pupil/statistics/'.$year."/".$period;
redirect($url);
}
else {
if (isset($_POST['year'])) {
$year = $_POST['year'];
$periods = array_keys($this->_getPeriodsForYear($year));
redirect(base_url().'pupil/statistics/'.$year."/".$periods[0]);
}
if(isset($_POST['period'])) {
$period = $_POST['period'];
redirect(base_url().'pupil/statistics/'.$year."/".$period);
}
$periods = array_keys($this->_getPeriodsForYear($year));
if (in_array($period, $periods)) {
$data['years'] = $years;
$data['periods'] = $this->_getPeriodsForYear($year);
$data['stat'] = $this->_getStatistics($year, $period);
$this->load->view("pupil/statisticsview", $data);
} else {
//ошибка
$data['error'] = "Выбранного периода не существует";
$this->load->view("errorview", $data);
}
}
}
function faq() {
$this->load->view("faqview");
}
private function _getPupilMarks($id, $start, $finish, $class_id) {
$result = array();
$subjects = $this->pupil->getSubjectsClass($class_id);
$i = 0;
foreach($subjects as $subject) {
$result[$i]["subject"] = $subject["SUBJECT_NAME"];
$subject_id = $subject["SUBJECTS_CLASS_ID"];
$marks = $this->pupil->getMarksForSubject($id, $subject_id, $start, $finish);
if(count($marks) == 0) {
$result[$i]["marks"] = array();
} else {
$z = 0;
foreach($marks as $mark) {
$result[$i]["marks"][$z]["mark"] = $mark['ACHIEVEMENT_MARK'];
if(isset($mark['TYPE_NAME'])) {
$result[$i]["marks"][$z]["type"] = $mark['TYPE_NAME']." (".date('d.m', strtotime($mark['LESSON_DATE'])).")";
} else {
$result[$i]["marks"][$z]["type"] = date('d.m', strtotime($mark['LESSON_DATE']));
}
$z++;
}
}
$passes = $this->pupil->getPassForSubject($id, $subject_id, $start, $finish);
if(count($passes) > 0) {
foreach($passes as $pass) {
if($pass['ATTENDANCE_PASS'] == 'н') {
$result[$i]["pass"]['н'] = $pass['COUNT'];
} else {
if($pass['ATTENDANCE_PASS'] == 'б') {
$result[$i]["pass"]['б'] = $pass['COUNT'];
} else {
if($pass['ATTENDANCE_PASS'] == 'у') {
$result[$i]["pass"]['у'] = $pass['COUNT'];
}
}
}
}
} else {
$result[$i]["pass"] = null;
}
$i++;
}
return $result;
}
function marks($class_id = null, $period = null) {
$pupil_id = $this->pupil_id; //$this->session->userdata('id');
$classes = $this->pupil->getClasses($pupil_id);
if(isset($class_id) && isset($period)) {
if(isset($_POST['class'])) {
$class_id = $_POST['class'];
$period = $this->pupil->getBorders($class_id)[0]['PERIOD_ID'];
redirect(base_url()."pupil/marks/".$class_id."/".$period);
}
if(isset($_POST['period'])) {
$period = $_POST['period'];
redirect(base_url()."pupil/marks/".$class_id."/".$period);
}
$row = $this->pupil->getPeriodById($period);
$start = $row['PERIOD_START'];
$finish = $row['PERIOD_FINISH'];
$data['periods'] = $this->pupil->getBorders($class_id);
$data['progress'] = $this->_getPupilMarks($pupil_id, $start, $finish, $class_id);
$data['classes'] = $classes;
$this->load->view("pupil/marksview", $data);
} else {
$class_id = $this->pupil_class; // $this->session->userdata('class_id');
$period = $this->pupil->getBorders($class_id)[0]['PERIOD_ID'];
redirect(base_url()."pupil/marks/".$class_id."/".$period);
}
}
}
?><file_sep>/application/controllers/Auth.php
<?php
class Auth extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('usermodel', 'user');
$this->load->library("roleenum");
}
function index()
{
$roleEnum = $this->roleenum;
$user = $this->session->userdata('login');
//если пользователь уже есть
if(isset($user)) {
$role = $this->session->userdata('role');
if($role == $roleEnum::Pupil) {
redirect('pupil/news');
}
if($role == $roleEnum::Admin) {
redirect('admin/teachers');
}
if ($role == $roleEnum::Teacher) {
redirect('teacher/journal');
}
if ($role == $roleEnum::ClassTeacher) {
redirect('classteacher/journal');
}
}
else {
if(isset($_POST['singin'])) {
$user = $_POST['login'];
$password = $_POST['<PASSWORD>'];
$row = $this->user->getTeacher($user, md5($password));
if (isset($row)) {
if ($row['TEACHER_STATUS'] == 1) {
$class_id = $this->user->getTeacherClass($row['TEACHER_ID'])['CLASS_ID'];
if (isset($class_id) && $row['ROLE_ID'] == $roleEnum::Teacher) {
$role = $roleEnum::ClassTeacher;
} else {
$role = $row['ROLE_ID'];
}
$newdata = array(
'id' => $row['TEACHER_ID'],
'class_id' => $class_id,
'role' => $role,
'login' => $row['TEACHER_LOGIN'],
);
$this->session->set_userdata($newdata);
if ($row['ROLE_ID'] == $roleEnum::Teacher || $row['ROLE_ID'] == $roleEnum::ClassTeacher) {
redirect('teacher/journal');
}
if ($row['ROLE_ID'] == $roleEnum::Admin) {
redirect('admin/teachers');
}
}
else $data['error'] = "У Вас нет доступа к системе. Обратитесь к администратору";
$this->load->view('authview', $data);
}
else {
$row = $this->user->getPupil($user, md5($password));
if (isset($row)) {
if ($row['PUPIL_STATUS'] == $roleEnum::ClassTeacher) {
$newdata = array(
'id' => $row['PUPIL_ID'],
'class_id' => $row['CLASS_ID'],
'role' => $row['ROLE_ID'],
'login' => $row['PUPIL_LOGIN'],
);
$this->session->set_userdata($newdata);
redirect('pupil/news');
}
else $data['error'] = "У Вас нет доступа к системе. Обратитесь к администратору";
$this->load->view('authview', $data);
}
else {
$data['error'] = "Вы ввели неправильный логин или пароль";
$this->load->view('authview', $data);
}
}
} else {
$this->load->view('authview');
}
}
}
function logout() {
$this->session->unset_userdata('login');
$this->session->unset_userdata('id');
$this->session->unset_userdata('class_id');
$this->session->unset_userdata('role');
redirect('auth');
}
}
?><file_sep>/application/controllers/Admin.php
<?php
class Admin extends CI_Controller {
var $admin_role = null;
var $admin_id = null;
var $admin_login = null;
public function __construct() {
parent::__construct();
$this->load->model('adminmodel', 'admin');
$this->load->model('tablemodel', 'table');
$this->load->library("roleenum");
$this->admin_role = $this->session->userdata('role');
$this->admin_login = $this->session->userdata('login');
$this->admin_id = $this->session->userdata('id');
}
function _remap($method, $params = array()) {
$login = $this->admin_login; //$this->session->userdata('login');
$role = $this->admin_role; //$this->session->userdata('role');
$roleEnum = $this->roleenum;
if(isset($login) && isset($role) && $role == $roleEnum::Admin) {
switch($method) {
case 'teachers': {
$data['title'] = "Список учителей";
break;
}
case 'news': {
$data['title'] = "Список новостей";
break;
}
case 'types': {
$data['title'] = "Список типов оценок";
break;
}
case 'classes': {
$data['title'] = "Список классов";
break;
}
case 'rooms': {
$data['title'] = "Список кабинетов";
break;
}
case 'subjects': {
$data['title'] = "Список общих предметов";
break;
}
case 'years': {
$data['title'] = "Список учебных годов";
break;
}
case 'teacher': {
$data['title'] = "Учитель";
break;
}
case 'newsitem': {
$data['title'] = "Новость";
break;
}
case 'subject': {
$data['title'] = "Общий предмет";
break;
}
case 'room': {
$data['title'] = "Кабинет";
break;
}
case 'classitem': {
$data['title'] = "Класс";
break;
}
case 'type': {
$data['title'] = "Тип оценки";
break;
}
case 'year': {
$data['title'] = "Учебный год";
break;
}
case 'statistics': {
$data['title'] = "Анализ";
break;
}
}
$data['role'] = $role;
$data['mainlogin'] = $login;
$this->load->view('header', $data);
if (method_exists($this, $method))
{
call_user_func_array(array($this, $method), $params);
}
else {
redirect(base_url()."admin/teachers");
}
$this->load->view('footer');
}
else {
redirect('auth/logout');
}
}
function teachers($offset = 1) {
$search = "";
if(isset($_GET['submit'])) {
if(isset($_GET['search'])) {
$search = urldecode($_GET['search']);
$data['search'] = $search;
if ($search == "") {
redirect(base_url()."admin/teachers");
} else redirect(base_url()."admin/teachers?search=".$search);
}
}
if(isset($_GET['search'])) {
$search = $_GET['search'];
$data['search'] = $search;
}
$num = 15;
//$teachers = $this->admin->getTeachers($num, $offset * $num - $num, $search);
$config['total_rows'] = $this->admin->totalTeachers($search);
$config['base_url'] = base_url()."admin/teachers";
$config['per_page'] = $num;
if (count($_GET) > 0) { $config['suffix'] = '?' . http_build_query($_GET, '', "&");
$config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
}
$this->pagination->initialize($config);
$query = $this->admin->getTeachers($num, $offset * $num - $num, $search);
$data['teachers'] = array();
if($query) {
$data['teachers'] = $query;
}
$this->load->view("admin/teachersview", $data);
}
function classes($offset = 1) {
$search = "";
if(isset($_GET['submit'])) {
if(isset($_GET['search'])) {
$search = urldecode($_GET['search']);
$data['search'] = $search;
if ($search == "") {
redirect(base_url()."admin/classes");
} else redirect(base_url()."admin/classes?search=".$search);
}
}
if(isset($_GET['search'])) {
$search = $_GET['search'];
$data['search'] = $search;
}
$num = 15;
//$classes = $this->admin->getClasses($num, $offset * $num - $num, $search);
$config['total_rows'] = $this->admin->totalClasses($search);
$config['base_url'] = base_url()."admin/classes";
$config['per_page'] = $num;
if (count($_GET) > 0) { $config['suffix'] = '?' . http_build_query($_GET, '', "&");
$config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
}
$this->pagination->initialize($config);
$query = $this->admin->getClasses($num, $offset * $num - $num, $search);
$data['classes'] = array();
if($query) {
$data['classes'] = $query;
}
$this->load->view("admin/classesview", $data);
}
function subjects($offset = 1) {
$search = "";
if(isset($_GET['submit'])) {
if(isset($_GET['search'])) {
$search = urldecode($_GET['search']);
$data['search'] = $search;
if ($search == "") {
redirect(base_url()."admin/subjects");
} else redirect(base_url()."admin/subjects?search=".$search);
}
}
if(isset($_GET['search'])) {
$search = $_GET['search'];
$data['search'] = $search;
}
$num = 15;
//$subjects_array = $this->admin->getSubjects($num, $offset * $num - $num, $search);
$config['total_rows'] = $this->admin->totalSubjects($search);
$config['base_url'] = base_url()."admin/subjects";
$config['per_page'] = $num;
if (count($_GET) > 0) { $config['suffix'] = '?' . http_build_query($_GET, '', "&");
$config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
}
$this->pagination->initialize($config);
$query = $this->admin->getSubjects($num, $offset * $num - $num, $search);
$data['subjects'] = array();
if($query) {
$data['subjects'] = $query;
}
$this->load->view("admin/subjectsview", $data);
}
function subject($id = null) {
if(isset($_POST['save'])) {
$name = $_POST['inputSubject'];
if(isset($id)) {
$this->table->updateSubject($name, $id);
} else {
$this->table->addSubject($name);
}
redirect(base_url()."admin/subjects");
} else {
if(isset($id)) {
$subject = $this->admin->getSubjectById($id);
if(isset($subject)) {
$data['subject'] = $subject['SUBJECT_NAME'];
$data['id'] = $subject['SUBJECT_ID'];
$data['title'] = 'Редактирование общего предмета';
$this->load->view("blankview/blanksubjectview", $data);
} else {
//ошибка
$data['error'] = "Такого общего предмета не существует. Вернитесь обратно";
$this->load->view("errorview", $data);
}
} else {
$data['title'] = 'Добавление нового общего предмета';
$this->load->view("blankview/blanksubjectview", $data);
}
}
}
function type($id = null) {
if(isset($_POST['save'])) {
$name = $_POST['inputType'];
if(isset($id)) {
$this->table->updateType($name, $id);
} else {
$this->table->addType($name);
}
redirect(base_url()."admin/types");
} else {
if(isset($id)) {
$type = $this->admin->getTypeById($id);
if(isset($type)) {
$data['type'] = $type['TYPE_NAME'];
$data['id'] = $type['TYPE_ID'];
$data['title'] = 'Редактирование типа оценки';
$this->load->view("blankview/blanktypeview", $data);
} else {
//ошибка
$data['error'] = "Такого типа оценки не существует. Вернитесь обратно";
$this->load->view("errorview", $data);
}
} else {
$data['title'] = 'Добавление нового типа оценки';
$this->load->view("blankview/blanktypeview", $data);
}
}
}
function room($id = null) {
if(isset($_POST['save'])) {
$name = $_POST['inputRoom'];
if(isset($id)) {
$this->table->updateRoom($name, $id);
} else {
$this->table->addRoom($name);
}
redirect(base_url()."admin/rooms");
} else {
if(isset($id)) {
$room = $this->admin->getRoomById($id);
if(isset($room)) {
$data['room'] = $room['ROOM_NAME'];
$data['id'] = $room['ROOM_ID'];
$data['title'] = 'Редактирование кабинета';
$this->load->view("blankview/blankroomview", $data);
} else {
//ошибка
$data['error'] = "Такого кабинета не существует. Вернитесь обратно";
$this->load->view("errorview", $data);
}
} else {
$data['title'] = 'Добавление нового кабинета';
$this->load->view("blankview/blankroomview", $data);
}
}
}
function rooms($offset = 1) {
$search = "";
if(isset($_GET['submit'])) {
if(isset($_GET['search'])) {
$search = urldecode($_GET['search']);
$data['search'] = $search;
if ($search == "") {
redirect(base_url()."admin/rooms");
} else redirect(base_url()."admin/rooms?search=".$search);
}
}
if(isset($_GET['search'])) {
$search = $_GET['search'];
$data['search'] = $search;
}
// Переменная хранит число сообщений выводимых на станице
$num = 15;
$config['total_rows'] = $this->admin->totalRooms($search);
$config['base_url'] = base_url()."admin/rooms";
$config['per_page'] = $num;
if (count($_GET) > 0) { $config['suffix'] = '?' . http_build_query($_GET, '', "&");
$config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
}
$this->pagination->initialize($config);
$query = $this->admin->getRooms($num, $offset * $num - $num, $search);
$data['rooms'] = array();
if($query) {
$data['rooms'] = $query;
}
$this->load->view("admin/roomsview", $data);
}
function types($offset = 1) {
$search = "";
if(isset($_GET['submit'])) {
if(isset($_GET['search'])) {
$search = urldecode($_GET['search']);
$data['search'] = $search;
if ($search == "") {
redirect(base_url()."admin/types");
} else redirect(base_url()."admin/types?search=".$search);
}
}
if(isset($_GET['search'])) {
$search = $_GET['search'];
$data['search'] = $search;
}
// Переменная хранит число сообщений выводимых на станице
$num = 15;
$config['total_rows'] = $this->admin->totalTypes($search);
$config['base_url'] = base_url()."admin/types";
$config['per_page'] = $num;
if (count($_GET) > 0) { $config['suffix'] = '?' . http_build_query($_GET, '', "&");
$config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
}
$this->pagination->initialize($config);
$query = $this->admin->getTypes($num, $offset * $num - $num, $search);
$data['types'] = array();
if($query) {
$data['types'] = $query;
}
$this->load->view("admin/typesview", $data);
}
function news($offset = 1) {
$search = "";
if(isset($_GET['submit'])) {
if(isset($_GET['search'])) {
$search = urldecode($_GET['search']);
$data['search'] = $search;
if ($search == "") {
redirect(base_url()."admin/news");
} else redirect(base_url()."admin/news?search=".$search);
}
}
if(isset($_GET['search'])) {
$search = $_GET['search'];
$data['search'] = $search;
}
// Переменная хранит число сообщений выводимых на станице
$num = 15;
$id = $this->admin_id; //$this->session->userdata('id');
$config['total_rows'] = $this->admin->totalNews($id, $search);
$config['base_url'] = base_url()."admin/news";
$config['per_page'] = $num;
if (count($_GET) > 0) { $config['suffix'] = '?' . http_build_query($_GET, '', "&");
$config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
}
$this->pagination->initialize($config);
$query = $this->admin->getNews($num, $offset * $num - $num, $id, $search);
$data['news'] = array();
if($query) {
$data['news'] = $query;
}
$this->load->view("admin/newsview", $data);
}
function newsitem($id = null) {
if(isset($_POST['save'])) {
$admin = $this->admin_id; //$this->session->userdata('id');
$theme = $_POST['inputTheme'];
$text = $_POST['inputText'];
$date = $_POST['inputDate'];
if(isset($id)) {
$this->table->updateNews($id, $theme, $date, $text, $admin);
} else {
$this->table->addNews($theme, $date, $text, $admin);
}
redirect(base_url()."admin/news");
} else {
if(isset($id)) {
$admin = $this->admin_id; //$this->session->userdata('id');
$news = $this->admin->getNewsById($id, $admin);
if(isset($news)) {
$data['date'] = $news['NEWS_TIME'];
$data['id'] = $news['NEWS_ID'];
$data['text'] = $news['NEWS_TEXT'];
$data['theme'] = $news['NEWS_THEME'];
$data['title'] = 'Редактирование новости';
$this->load->view("blankview/blanknewsview", $data);
} else {
//ошибка
$data['error'] = "Такой новости не существует. Вернитесь обратно";
$this->load->view("errorview", $data);
}
} else {
$data['title'] = 'Добавление новой новости';
$this->load->view("blankview/blanknewsview", $data);
}
}
}
function classitem($id = null) {
$data['years'] = $this->admin->getYears();
$data['teachers'] = $this->admin->getAllTeachers();
$data['classes'] = $this->admin->getAllClasses();
if(isset($_POST['save'])) {
$number = $_POST['inputNumber'];
$letter = $_POST['inputLetter'];
if(isset($_POST['inputYear'])) {
$year = $_POST['inputYear'];
} else {
$year = "";
}
if(isset($_POST['inputStatus'])) {
$status = $_POST['inputStatus'];
} else {
$status = "";
}
$teacher = $_POST['inputTeacher'];
if(isset($_POST['inputPrevious'])) {
$previous = $_POST['inputPrevious'];
} else {
$previous = "";
}
if(isset($id)) {
$this->table->updateClass($id, $number, $letter, $year, $status, $teacher, $previous);
} else {
$this->table->addClass($number, $letter, $year, $status, $teacher, $previous);
}
redirect(base_url()."admin/classes");
} else {
if(isset($id)) {
$classitem = $this->admin->getClassById($id);
if(isset($classitem)) {
$data['id'] = $classitem['CLASS_ID'];
$data['number'] = $classitem['CLASS_NUMBER'];
$data['letter'] = $classitem['CLASS_LETTER'];
$data['status'] = $classitem['CLASS_STATUS'];
//$data['previous'] = $classitem['CLASS_PREVIOUS'];
$data['year_id'] = $classitem['YEAR_ID'];
$data['teacher_id'] = $classitem['TEACHER_ID'];
$data['status_allow'] = false;
foreach( $this->admin->getAllClasses() as $class) {
if($class['CLASS_PREVIOUS'] == $classitem['CLASS_ID']) {
$data['status_allow'] = true;
}
}
$data['title'] = 'Редактирование класса';
$this->load->view("blankview/blankclassview", $data);
} else {
//ошибка
$data['error'] = "Такого класса не существует. Вернитесь обратно";
$this->load->view("errorview", $data);
}
} else {
$data['title'] = 'Добавление нового класса';
$this->load->view("blankview/blankclassview", $data);
}
}
}
function teacher($id = null) {
if(isset($_POST['save'])) {
$name = $_POST['inputName'];
$password = $_POST['inputPassword'];
$login = $_POST['inputLogin'];
$status = $_POST['inputStatus'];
if(isset($id)) {
$this->table->updateTeacher($id, $name, $password, $login, $status, md5($password));
} else {
$this->table->addTeacher($name, $password, $login, $status, md5($password));
}
redirect(base_url()."admin/teachers");
} else {
if(isset($id)) {
$teacher = $this->admin->getTeacherById($id);
if(isset($teacher)) {
$data['id'] = $teacher['TEACHER_ID'];
$data['name'] = $teacher['TEACHER_NAME'];
$data['login'] = $teacher['TEACHER_LOGIN'];
$data['password'] = $teacher['TEACHER_PASSWORD'];
$data['status'] = $teacher['TEACHER_STATUS'];
$data['title'] = 'Редактирование учителя';
$this->load->view("blankview/blankteacherview", $data);
} else {
//ошибка
$data['error'] = "Такого учителя не существует. Вернитесь обратно";
$this->load->view("errorview", $data);
}
} else {
$data['title'] = 'Добавление нового учителя';
$this->load->view("blankview/blankteacherview", $data);
}
}
}
function years($offset = 1) {
// Переменная хранит число сообщений выводимых на станице
$num = 15;
$config['total_rows'] = $this->admin->totalYears();
$config['base_url'] = base_url()."admin/periods";
$config['per_page'] = $num;
$this->pagination->initialize($config);
$query = $this->admin->getYearsLimit($num, $offset * $num - $num);
$data['periods'] = array();
if($query) {
$data['periods'] = $query;
}
$this->load->view("admin/yearsview", $data);
}
function year($id = null) {
if(isset($_POST['save'])) {
$year_start = $_POST['inputYearStart'];
$year_finish = $_POST['inputYearFinish'];
$first_start = $_POST['inputFirstStart'];
$first_finish = $_POST['inputFirstFinish'];
$second_start = $_POST['inputSecondStart'];
$second_finish = $_POST['inputSecondFinish'];
$third_start = $_POST['inputThirdStart'];
$third_finish = $_POST['inputThirdFinish'];
$forth_start = $_POST['inputForthStart'];
$forth_finish = $_POST['inputForthFinish'];
if(isset($id)) {
$this->table->updateYearAndPeriods($id, $year_start, $year_finish,
$first_start, $first_finish, $second_start, $second_finish, $third_start,$third_finish, $forth_start, $forth_finish);
} else {
$this->table->addYearAndPeriods($year_start, $year_finish,
$first_start, $first_finish, $second_start, $second_finish, $third_start,$third_finish, $forth_start, $forth_finish);
}
redirect(base_url()."admin/years");
} else {
if(isset($id)) {
$year = $this->admin->getYearById($id);
if(isset($year)) {
$data['info'] = $year;
$data['id'] = $year["id"];
$data['title'] = 'Редактирование учебного года';
$this->load->view("blankview/blankyearview", $data);
} else {
//ошибка
$data['error'] = "Такого учебного года не существует. Вернитесь обратно";
$this->load->view("errorview", $data);
}
} else {
$data['title'] = 'Добавление нового учебного года';
$this->load->view("blankview/blankyearview", $data);
}
}
}
function statistics($year = null, $period = null) {
$years = $this->admin->getYears();
if(count($years) == 0) {
//ошибка
$data['error'] = "Добавьте учебные года";
$this->load->view("errorview", $data);
} else {
if(!isset($year) || !isset($period)) {
$year = $years[0]['YEAR_ID'];
$periods = $this->admin->getPeriodsInYear($year);
$period = $periods[0]['PERIOD_ID'];
redirect(base_url()."admin/statistics/".$year."/".$period);
} else {
if(isset($_POST['year'])) {
$year = $_POST['year'];
$periods = $this->admin->getPeriodsInYear($year);
$period = $periods[0]['PERIOD_ID'];
redirect(base_url()."admin/statistics/".$year."/".$period);
}
if(isset($_POST['period'])) {
$period = $_POST['period'];
redirect(base_url()."admin/statistics/".$year."/".$period);
}
$data['years'] = $years;
$data['periods'] = $this->admin->getPeriodsInYear($year);
$classes = $this->admin->getClassesInYear($year);
$result = array();
$i=0;
foreach($classes as $class) {
$class_id = $class['CLASS_ID'];
$result[$i]["class_id"] = $class_id;
$result[$i]["class_name"] = $class['CLASS_NUMBER']." ".$class['CLASS_LETTER'];
$pupils = $this->admin->getPupilsInClass($class_id);
$result[$i]["count"] = count($pupils);
$result[$i][5]['mark'] = 0;
$result[$i][4]['mark'] = 0;
$result[$i][3]['mark'] = 0;
$result[$i][2]['mark'] = 0;
foreach($pupils as $pupil) {
$pupil_id = $pupil['PUPIL_ID'];
$marks = $this->admin->getPupilProgress($pupil_id, $period);
for($y = 2; $y <=5; $y++) {
$count[$y] = 0;
foreach ($marks as $key=>$value) {
if ($value ['PROGRESS_MARK'] == $y) {
$count[$y]++;
}
}
}
//print_r( $count[5]);
//print_r( count($marks));
if($count[5] == count($marks) && count($marks) !=0) {
//print_r($pupil['PUPIL_NAME']);
$result[$i][5]['mark']++;
} else {
if(($count[5] + $count[4]) == count($marks) && count($marks) !=0) {
$result[$i][4]['mark']++;
} else {
if($count[2] > 0 && count($marks) !=0) {
$result[$i][2]['mark']++;
} else {
if(count($marks) !=0) {
//print_r($pupil['PUPIL_NAME']);
$result[$i][3]['mark']++;
}
}
}
}
}
$i++;
}
/*$arr = $this->admin->getClassPass($year, $period, 'б');
echo count($arr);
if(count($arr) > 0) {
$data['pass1'] = $arr[0]['CLASS_NUMBER']." ".$arr[0]['CLASS_LETTER'];
}*/
/*$data['pass2'] = $this->admin->getClassPass($year, $period, 'у');
$data['pass3'] = $this->admin->getClassPass($year, $period, 'n');*/
$data['result'] = $result;
$this->load->view("admin/statisticsview", $data);
}
}
}
function progress($class_id = null, $period = null) {
$this->load->model('teachermodel', 'teacher');
$borders = $this->teacher->getBorders($class_id);
$data['class_name'] = $this->admin->getClassById($class_id)['CLASS_NUMBER']." ".$this->admin->getClassById($class_id)['CLASS_LETTER'];
if(!isset($period)) {
redirect(base_url()."admin/progress/".$class_id."/".$borders[0]['PERIOD_ID']);
} else {
if(isset($_POST['period'])) {
$period = $_POST['period'];
redirect(base_url()."admin/progress/".$class_id."/".$period);
}
$data['periods'] = $borders;
//успеваемость
$pupils = $this->admin->getPupilsInClass($class_id);
$subjects = $this->teacher->getAllSubjectsClass($class_id);
if(count($pupils) > 0) {
$result = array();
$average = array();
$i = 0;
foreach($pupils as $pupil) {
$pupil_id = $pupil['PUPIL_ID'];
$result[$i]["pupil"] = $pupil['PUPIL_NAME'];
$y = 0;
foreach($subjects as $subject) {
$subject_id = $subject['SUBJECTS_CLASS_ID'];
$result[$i]['mark'][$y] = $this->teacher->getPupilProgressForSubject($pupil_id, $subject_id, $period)['PROGRESS_MARK'];
$average[$y] = number_format($this->teacher->getAverageForSubject($class_id, $subject_id, $period)['MARK'],1);
$y++;
}
$i++;
}
$data['progress'] = $result;
$data['average'] = $average;
} else {
$data['progress'] = null;
}
$data['subjects'] = $subjects;
$this->load->view("admin/classreportview", $data);
}
}
function error () {
$data['error'] = "Такой страницы не существует";
$this->load->view("errorview", $data);
}
}
?><file_sep>/application/libraries/Roleenum.php
<?php
class Roleenum {
const ClassTeacher = 1;
const Admin = 2;
const Teacher = 3;
const Pupil = 4;
}<file_sep>/application/models/usermodel.php
<?php
class Usermodel extends CI_Model {
function getTeacher($login, $hash) {
/* SELECT TEACHER_LOGIN, TEACHER_HASH, ROLE_ID, CLASS_ID, TEACHER_STATUS, TEACHER_ID
FROM TEACHER
WHERE TEACHER_LOGIN collate utf8_bin = '".$login."' AND TEACHER_HASH collate utf8_bin = '".$hash."'
LIMIT 1*/
$query = $this->db->query("SELECT * FROM TEACHER WHERE TEACHER_LOGIN collate utf8_bin = '$login'
AND TEACHER_HASH collate utf8_bin = '$hash'");
return $query->row_array();
}
function getPupil($login, $hash) {
$query = $this->db->query("SELECT p.PUPIL_LOGIN, p.PUPIL_HASH, p.ROLE_ID, p.PUPIL_STATUS, p.PUPIL_ID, pc.CLASS_ID
FROM PUPIL p JOIN PUPILS_CLASS pc ON p.PUPIL_ID = pc.PUPIL_ID JOIN CLASS c ON c.CLASS_ID = pc.CLASS_ID
WHERE PUPIL_LOGIN collate utf8_bin = '$login' AND PUPIL_HASH = '$hash' AND CLASS_STATUS = 1");
return $query->row_array();
}
function getTeacherClass($id) {
$query = $this->db->query("SELECT CLASS_ID FROM CLASS WHERE TEACHER_ID = '$id' AND CLASS_STATUS = 1");
return $query->row_array();
}
}
/* "SELECT ROLE_ID, CLASS.CLASS_ID, TEACHER.TEACHER_ID, TEACHER.TEACHER_LOGIN, TEACHER.TEACHER_STATUS
FROM TEACHER LEFT JOIN CLASS ON CLASS.TEACHER_ID = TEACHER.TEACHER_ID
WHERE TEACHER_LOGIN collate utf8_bin = '$login' AND TEACHER_HASH collate utf8_bin = '$hash'"*/
?><file_sep>/application/controllers/Api.php
<?php
class Api extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('apimodel', 'api');
}
private function _getMarks($day, $date) {
$id = $this->session->userdata('id');
$class_id = $this->session->userdata('class_id');
$arr = array();
$subjects = $this->api->getTimetable($class_id, $day);
for ($i=5; $i>=2; $i--) {
$arr[$i] = 0;
}
if (count($subjects) > 0) {
foreach($subjects as $subject) {
$subjects_class_id = $subject['SUBJECTS_CLASS_ID'];
$time_id = $subject['TIME_ID'];
$current = $date;
$marks = $this->api->getMarks($subjects_class_id, $current, $id, $time_id);
if (count($marks) > 0) {
foreach($marks as $mark) {
$arr[$mark['ACHIEVEMENT_MARK']]++;
}
}
}
$s = 0;
for ($i=5; $i>=2; $i--) {
if ($arr[$i] != 0) {
$s++;
}
}
if ($s == 0) {
return null;
} else return $arr;
} else {
return null;
}
}
function todayMarks($date = null) {
if ($date == null) {
$date = date("Y-m-d");
}
$day = date("w", strtotime($date));
$login = $this->session->userdata('login');
if(isset($login)) {
$id = $this->session->userdata('id');
//$arr = $this->getMarks(1, '2015-04-27');
$arr = $this->_getMarks($day, $date);
echo json_encode($arr, JSON_UNESCAPED_UNICODE);
}
else {
echo 'error';
}
}
private function getAverageMarks($day, $date) {
$id = $this->session->userdata('id');
$class_id = $this->session->userdata('class_id');
$arr = array();
$i = 1;
$borders = $this->api->getBorders($class_id, $date);
if (isset($borders)) {
$subjects = $this->api->getTimetable($class_id, $day);
if (count($subjects) > 0) {
foreach($subjects as $subject) {
$current = $date.' '.$subject['TIME_START'];
$arr[$i]["subject"] = $subject['SUBJECT_NAME'];
$mark = $this->api->getAverageMark($borders['PERIOD_START'], $date, $class_id, $id, $subject['SUBJECTS_CLASS_ID'])['MARK'];
if(isset($mark)) {
$arr[$i]["mark"] = number_format($mark,1);
} else {
$arr[$i]["mark"] = 0;
}
$i++;
}
return $arr;
} else {
return null;
}
} else {
return null;
}
}
function todayAverages($date = null) {
if ($date == null) {
$date = date("Y-m-d");
}
$login = $this->session->userdata('login');
$day = date("w", strtotime($date));
if(isset($login)) {
$id = $this->session->userdata('id');
//$arr = $this->getAverageMarks(1, '2015-04-27');
$arr = $this->getAverageMarks($day, $date);
echo json_encode( $arr, JSON_UNESCAPED_UNICODE);
}
else {
echo 'error';
}
}
function getPasses($period, $subject, $class_id) {
$pupils = $this->api->getPupils($class_id);
$result = array();
$i = 0;
foreach($pupils as $pupil) {
$pupil_id = $pupil['PUPIL_ID'];
$pass[1] = $this->api->getPasses($pupil_id, $subject, $period, "н")['COUNT'];
$pass[2] = $this->api->getPasses($pupil_id, $subject, $period, "у")['COUNT'];
$pass[3] = $this->api->getPasses($pupil_id, $subject, $period, "б")['COUNT'];
$result[$i]["name"] = $pupil["PUPIL_NAME"];
$result[$i]["pass"] = array(1 => $pass[1], 2 => $pass[2], 3=> $pass[3]);
$i++;
}
//$result = array("pupils"=>$result);
/*
$arrayRes = array();
while ($row = mysql_fetch_assoc($result_op) ){
$arrayRes [] = $row;
}*/
echo json_encode($result, JSON_UNESCAPED_UNICODE);
}
function getAllPasses($period) {
$class_id = $this->session->userdata('class_id');
$pupils = $this->api->getPupils($class_id);
$result = array();
$i = 0;
foreach($pupils as $pupil) {
$pupil_id = $pupil['PUPIL_ID'];
$pass[1] = $this->api->getAllPasses($pupil_id, $period, "н")['COUNT'];
$pass[2] = $this->api->getAllPasses($pupil_id, $period, "у")['COUNT'];
$pass[3] = $this->api->getAllPasses($pupil_id, $period, "б")['COUNT'];
$result[$i]["name"] = $pupil["PUPIL_NAME"];
$result[$i]["pass"] = array(1 => $pass[1], 2 => $pass[2], 3=> $pass[3]);
$i++;
}
echo json_encode($result, JSON_UNESCAPED_UNICODE);
//echo $period;
}
}
?><file_sep>/application/views/message/conversationview.php
<?php
function showDate($date) {
$day = date('d', strtotime($date));
$mounth = date('m', strtotime($date));
$year = date('Y', strtotime($date));
$hours = date('H', strtotime($date));
$minutes = date('i', strtotime($date));
$data = array('01'=>'января','02'=>'февраля','03'=>'марта','04'=>'апреля','05'=>'мая','06'=>'июня',
'07'=>'июля', '08'=>'августа','09'=>'сентября','10'=>'октября','11'=>'ноября','12'=>'декабря');
$today_year = date('Y');
$today_day = date('d');
foreach ($data as $key=>$value) {
if ($key==$mounth) {
if ($year < $today_year) {
echo ltrim($day, '0')." $value $year года";
} else {
if ($day != $today_day) {
echo ltrim($day, '0')." $value $year года в ".$hours.":".$minutes;
}
else {
echo "Сегодня в ".$hours.":".$minutes;
}
}
}
}
}
?>
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-body">
<div class="form-group">
<textarea style="resize: vertical;" class="form-control" rows="3" maxlength="500" id="inputText" name="inputText" placeholder="Текст сообщения"></textarea>
</div>
<div class="modal-footer" style="margin-bottom: -15px; padding-right: 0px;">
<button type="button" class="btn btn-sample" name="send" id="send" title="Отправить">Отправить</button>
</div>
</div>
</div>
<h3 class="sidebar-header"><i class="fa fa-comments"></i> Общение с <strong><?php echo $user; ?></strong></h3>
<div class="panel panel-default">
<div class="panel-body">
<form method="get">
<div class="input-group">
<input type="text" class="form-control" placeholder="Поиск по сообщениям" id="search" name="search" value="<?php if(isset($search)) echo $search;?>" >
<span class="input-group-btn">
<button class="btn btn-default" type="submit" name="submit" id="searchButton" title="Поиск"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
</span>
</div><!-- /input-group -->
</form>
</div>
<div class="table-responsive">
<table name="timetable" class="table table-hover table-striped numeric" >
<tbody>
<?php if(is_array($messages) && count($messages) ) {
foreach($messages as $message){ ?>
<?php if($message['MESSAGE_READ'] == 0 && $message['MESSAGE_FOLDER'] == 1) { ?><tr class="info"><?php } else { ?><tr><?php }?>
<td hidden="true"><input type="radio" name="message_id" value="<?php echo $message['USER_MESSAGE_ID'];?>"></td>
<td>
<button hidden="true" type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<strong><?php if($message['MESSAGE_FOLDER'] == 1) echo $message['USER_NAME']; else echo "Я"; ?></strong> <span style="font-size: 12px; font-style: italic;" class="time"><?php showDate($message['MESSAGE_DATE']); ?></span></br>
<span style="display: block; padding-top: 10px;"><?php echo $message['MESSAGE_TEXT']; ?></span>
</td>
</tr>
<?php }
} ?>
</tbody>
</table>
</div>
</div>
<?php echo $this->pagination->create_links(); ?>
<?php
if(count($messages) == 0 && isset($search) && $search != "") {
?>
<div class="alert alert-info" role="alert">Поиск не дал результатов. Попробуйте другой запрос</div>
<?php } ?>
</div></div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('.close').click(function() {
var value = $(this).closest("tr").find(':radio[name=message_id]').val();
var base_url = '<?php echo base_url();?>';
$.ajax({
type: "POST",
url: base_url + "table/del/message/" + value,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(a) {
location.reload();
}
});
});
$('#send').click(function() {
var id = "<?php echo $this->uri->segment(3);?>";
var text = $.trim($('#inputText').val());
var base_url = '<?php echo base_url();?>';
if(text.length != "") {
$.ajax({
type: "POST",
url: base_url + "table/addmessage",
data: "id=" + id + "&text=" + text,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
//alert(response);
location.reload();
}
});
} else {
return false;
}
});
$('#inputText').on('keyup', function(e) {
if (e.which == 13 && ! e.shiftKey) {
$('#send').click();
}
});
$('table tr').mouseover(function() {
var tr = $(this);
var base_url = '<?php echo base_url();?>';
$(this).find('.close').attr('hidden', false);
var value = $(this).find(':radio[name=message_id]').val();
//alert(value);
$.ajax({
type: "POST",
url: base_url + "table/readmessage/" + value,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(a) {
tr.removeClass();
}
});
});
$('table tr').mouseout(function() {
$(this).find('.close').attr('hidden', true);
});
$('#readButton').click(function() {
var base_url = '<?php echo base_url();?>';
var checked = [];
$("input[name='messages[]']:checked").each(function () {
checked.push($(this).val());
});
for(var i = 0; i < checked.length; i++ ) {
$.ajax({
type: "POST",
url: base_url + "table/readmessage/" + checked[i],
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(a) {
//alert(a);
}
});
}
location.reload();
});
});
</script>
<file_sep>/application/views/blankview/blanknewsview.php
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><?php echo $title; ?></div>
<div class="panel-body">
<form method="post">
<div hidden="true" id="id"><?php if(isset($id)) echo $id;?></div>
<div class="form-horizontal">
<div class="form-group">
<label for="inputTheme" class="col-sm-2 col-md-2 control-label">Тема новости <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<textarea style="resize: vertical;" class="form-control" rows="1" maxlength="150" id="inputTheme" name="inputTheme" placeholder="Тема новости" autofocus required="true"><?php if(isset($theme)) echo $theme;?></textarea>
<div class="textareaFeedback"></div>
</div>
</div>
<div class="form-group">
<label for="inputDate" class="col-sm-2 col-md-2 control-label">Дата новости <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<input type="text" class="form-control" id="inputDate" name="inputDate" required="true" placeholder="гггг-мм-дд" value="<?php if(isset($date)) { echo $date; } else echo date('Y-m-d');?>" >
<div id="responseDateError" class="red"></div>
</div>
</div>
<div class="form-group">
<label for="inputText" class="col-sm-2 col-md-2 control-label">Текст новости <span class="star">*</span></label>
<div class="col-sm-10 col-md-10">
<!--<div id="txtEditor"></div>-->
<textarea style="resize: vertical;" class="form-control" rows="10" maxlength="5000" id="inputText" name="inputText" placeholder="<NAME>и" required="true"><?php if(isset($text)) echo $text; ?></textarea>
<div class="textareaFeedback"></div>
</div>
</div>
</div>
<div class="grey">* - Обязательные поля</div>
<div id="error" class="red"></div>
<div class="modal-footer" style="margin-bottom: -15px; padding-right: 0px;">
<button type="button" class="btn btn-default" onclick="javascript:history.back();" title="Отменить">Отменить</button>
<button type="submit" class="btn btn-sample" name="save" id="save" title="Сохранить">Сохранить</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
//$("#txtEditor").Editor({'fonteffects':false, 'print':false, 'status_bar':false, 'togglescreen':false});
$("#inputDate").mask("9999-99-99");
$('#inputDate').datepicker({
format: 'yyyy-mm-dd',
startDate: "1993-01-01",
language: "ru",
todayBtn: "linked",
autoclose: true,
todayHighlight: true,
});
$('#save').click(function() {
var base_url = '<?php echo base_url();?>';
var s = 0;
var error = 0;
var theme = $.trim($('#inputTheme').val());
var date = $('#inputDate').val();
var text = $.trim($('#inputText').val());
var id = $('#id').text();
if (theme.length == 0) {
$('#inputTheme').parent().addClass("has-error");
s++;
} else {
$('#inputTheme').parent().removeClass("has-error");
}
if (text.length == 0) {
$('#inputText').parent().addClass("has-error");
s++;
} else {
$('#inputText').parent().removeClass("has-error");
}
if (date.length == 0) {
$('#inputDate').parent().addClass("has-error");
s++;
} else {
$('#inputDate').parent().removeClass("has-error");
}
if (s != 0) {
$("#error").text('Не все обязательные поля заполнены');
}
else {
$("#error").text('');
}
//alert($("#txtEditor").val());
//alert(s + " " + error);
if (s == 0 && error == 0) {
/*if (id == "") {
$.ajax({
type: "POST",
url: base_url + "table/addnews",
data: "theme=" + theme + "&date=" + date + "&text=" + text,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
document.location.href = base_url + 'admin/news';
}
});
}
else {
$.ajax({
type: "POST",
url: base_url + "table/updatenews",
data: "theme=" + theme + "&date=" + date + "&text=" + text + "&id=" + id,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
document.location.href = base_url + 'admin/news';
}
});
}*/
} else return false;
});
});
</script>
<file_sep>/application/controllers/Classteacher.php
<?php
include('teacher.php');
class Classteacher extends Teacher {
public function __construct()
{
parent::__construct();
}
function test () {
echo "привет";
}
}
?>
<file_sep>/application/views/diaryview2.php
<link href="<?php echo base_url()?>css/btn-sample.css" rel="stylesheet">
<?php
/* $string_date = '08-03-2015';
$day_of_week = date('N', strtotime($string_date));
$week_first_day = date('Y-m-d', strtotime($string_date . " - " . ($day_of_week - 1) . " days"));
//$week_last_day = date('d-m-Y', strtotime($string_date . " + " . (7 - $day_of_week) . " days"));
$nextMonday = date('Y-m-d',strtotime("next Monday"));*/
function showDate($date) {
$day = date('d', strtotime($date));
$mounth = date('m', strtotime($date));
$year = date('Y', strtotime($date));
$data = array('01'=>'января','02'=>'февраля','03'=>'марта','04'=>'апреля','05'=>'мая','06'=>'июня',
'07'=>'июля', '08'=>'августа','09'=>'сентября','10'=>'октября','11'=>'ноября','12'=>'декабря');
foreach ($data as $key=>$value) {
if ($key==$mounth) echo "<b>".ltrim($day, '0')." $value $year года</b>";
}
}
function setColor($mark, $tooltip) {
switch ($mark) {
case 5: echo '<span data-toggle="tooltip" data-placement="left" title="'.$tooltip.'" class="green">'.$mark.'</span>'; break;
case 4: echo '<span data-toggle="tooltip" data-placement="left" title="'.$tooltip.'" class="yellow">'.$mark.'</span>'; break;
case 3: echo '<span data-toggle="tooltip" data-placement="left" title="'.$tooltip.'" class="blue">'.$mark.'</span>'; break;
case 2: echo '<span data-toggle="tooltip" data-placement="left" title="'.$tooltip.'" class="red">'.$mark.'</span>'; break;
}
}
?>
<div class="container">
<div class="well well-sm" style="background: #563d7c;"><span style="color: white;">
<span class="glyphicon glyphicon-bookmark" aria-hidden="true">
</span> Учебная неделя с <?php echo showDate($monday);?> по <?php echo showDate(date('Y-m-d', strtotime($monday . ' + 6 day')));?>
</span>
</div>
<?php
if ($finish == false && $start == false) {
?>
<div class="alert alert-info" role="alert">Каникулы. Учебных занятий нет</div>
<?
} else {
?>
<ul class="pager" id="diary-navigation">
<li class="previous <?php if ($start == false) echo 'disabled' ;?>" data-toggle="tooltip" data-placement="left" title="Назад на одну неделю">
<a class="<?php if ($start == false) {echo 'not-active';}?>" href="<?php echo base_url();?>pupil/diary?monday=<?php echo date('Y-m-d', strtotime($monday . ' - 7 day')); ?>">← Назад</a>
</li>
<li data-toggle="tooltip" data-placement="left" title="Показать текущую неделю">
<a href="<?php echo base_url();?>pupil/diary?monday=<?php echo date('Y-m-d', strtotime(date('Y-m-d'). " - " . (date('N', strtotime(date('Y-m-d'))) - 1) . " days")); ?>">Текущая неделя</a>
</li>
<li class="next <?php if ($finish == false) {echo 'disabled';}?>" data-toggle="tooltip" data-placement="left" title="Вперед на одну неделю">
<a class="<?php if ($finish == false) {echo 'not-active';}?>" href="<?php echo base_url();?>pupil/diary?monday=<?php echo date('Y-m-d', strtotime($monday . ' + 7 day'));?>">Вперед →</a>
</li>
</ul>
<div class="row" id="diary">
<div class="col-md-6">
<?php
$date = $monday;
for($i = 1; $i <= count($diary); $i++) {
?>
<div class="panel panel-default"><div class="panel-heading">
<?php
echo $days[$i-1]. " ";
echo showDate($date);
$date = date('Y-m-d', strtotime($date . ' + 1 day'));
?>
</div> <div class="table-responsive">
<table name="diarytable" class="table table-striped table-hover ">
<thead>
<tr>
<th>Предмет</th>
<th>Оценки</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
for($y = 1; $y <= count($diary[$i]); $y++) {
//echo $diary[$i][$y]["start"] <= date("Y-m-d");
if ($diary[$i][$y]["pass"] == 1) {
?>
<tr class="warning">
<?php
} else {
?>
<tr>
<?php }
?>
<td class="col-xs-4 col-md-4" style="vertical-align:middle"><?php echo $diary[$i][$y]["subject"]; ?></td>
<td class="mark col-xs-4 col-md-5" style="vertical-align:middle">
<?php
if(isset($diary[$i][$y]["marks"])) {
for($z = 1; $z <= count($diary[$i][$y]["marks"]); $z++) {
setColor($diary[$i][$y]["marks"][$z]["mark"], $diary[$i][$y]["marks"][$z]["type"]);
echo " ";
}
}
?>
</td>
<td class="col-xs-4 col-md-3"><a href="<?php echo base_url();?>pupil/lesson?id=<?php echo $diary[$i][$y]["lesson_id"]; ?>" role="button" class="btn btn-sample btn-sm btn-block <?php
if (!isset($diary[$i][$y]["lesson_id"])) { echo "disabled";}
?>" data-toggle="tooltip" data-placement="left" title="Посмотреть учебное занятие">Подробнее</a></td></tr>
<?php
}
for($y = count($diary[$i]); $y < 6; $y++) {
?>
<tr style="height: 47px;"><td></td><td></td><td></td></tr>
<?php
}?>
</tbody>
</table>
</div>
</div>
<?php
if ($i == 3) {
echo '</div><div class="col-md-6">';
}
if ($i == 6) {
echo '</div>';
}
}
?>
</div>
</div>
<?php }?>
</div><file_sep>/application/views/teacher/subjectsview.php
<div class="container">
<h3 class="sidebar-header"><i class="fa fa-book"></i> Список предметов в классе</h3>
<div class="panel panel-default panel-table">
<div class="panel-body">
<button type="button" class="btn btn-menu" id="createButton" title="Добавить предмет в классе"><i class="fa fa-plus fa-2x"></i>
</br><span class="menu-item">Создать</span>
</button>
<button href="" type="button" class="btn btn-menu disabled" id="editButton" title="Редактировать предмет в классе"><i class="fa fa-pencil fa-2x"></i>
</br><span class="menu-item">Редактировать</span>
</button>
<button type="button" class="btn btn-menu disabled" id="deleteButton" data-toggle="modal" data-target="#myModal" title="Удалить предмет в классе"><i class="fa fa-trash-o fa-2x"></i>
</br><span class="menu-item">Удалить</span>
</button>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<form method="get">
<div class="input-group">
<input type="text" class="form-control" placeholder="Поиск по учителю и предмету" id="search" name="search" value="<?php if(isset($search)) echo $search;?>" >
<span class="input-group-btn">
<button class="btn btn-default" type="submit" name="submit" id="searchButton" title="Поиск"><i class="fa fa-search"></i></button>
</span>
</div><!-- /input-group -->
</form>
</div>
<div class="table-responsive">
<table name="timetable" class="table table-striped table-hover table-bordered numeric">
<thead>
<tr>
<th></th>
<th>ФИО учителя</th>
<th>Общий предмет</th>
</tr>
</thead>
<tbody>
<?php
if(is_array($subjects) && count($subjects) ) {
foreach($subjects as $subject) {
?>
<tr>
<td><input type="radio" name="subject_id" value="<?php echo $subject['SUBJECTS_CLASS_ID'];?>"></td>
<td><?php if(isset($subject['TEACHER_NAME'])) echo $subject['TEACHER_NAME'];?></td>
<td><?php if(isset($subject['SUBJECT_NAME'])) echo $subject['SUBJECT_NAME'];?></td>
</tr>
<?php }} ?>
</tbody>
</table>
</div>
</div>
<?php echo $this->pagination->create_links(); ?>
<?php
if(is_array($subjects) && count($subjects) == 0 && isset($search) && $search != "") {
?>
<div class="alert alert-info" role="alert">Поиск не дал результатов. Попробуйте другой запрос</div>
<?php } ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
if($(":radio[name=subject_id]").is(':checked')) {
$('#editButton').removeClass('disabled');
$('#deleteButton').removeClass('disabled');
} else {
$('#editButton').addClass('disabled');
$('#deleteButton').addClass('disabled');
}
$(":radio[name=subject_id]").change(function() {
$('#editButton').removeClass('disabled');
$('#deleteButton').removeClass('disabled');
});
$('#createButton').click(function() {
document.location.href = '<?php echo base_url(); ?>teacher/subject';
});
$('#editButton').click(function() {
var value = $(":radio[name=subject_id]").filter(":checked").val();
document.location.href = '<?php echo base_url(); ?>teacher/subject/' + value;
});
$('#buttonDeleteSubjectModal').click(function() {
var value = $(":radio[name=subject_id]").filter(":checked").val();
var base_url = '<?php echo base_url();?>';
$.ajax({
type: "POST",
url: base_url + "table/del/subjectsclass/" + value,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(a) {
location.reload();
}
});
});
$("tr:not(:first)").click(function() {
$(this).children("td").find('input[type=radio]').prop('checked', true).change();
});
});
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Удаление предмета в классе</h4>
</div>
<div class="modal-body">
<p>Вы уверены, что хотите удалить этот предмет в классе?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-sample" id="buttonDeleteSubjectModal">Удалить</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<file_sep>/application/views/teacher/lessonsview.php
<?php
function showDate($date) {
$day = date('d', strtotime($date));
$mounth = date('m', strtotime($date));
$year = date('Y', strtotime($date));
$data = array('01'=>'января','02'=>'февраля','03'=>'марта','04'=>'апреля','05'=>'мая','06'=>'июня',
'07'=>'июля', '08'=>'августа','09'=>'сентября','10'=>'октября','11'=>'ноября','12'=>'декабря');
foreach ($data as $key=>$value) {
if ($key==$mounth) echo "".ltrim($day, '0')." $value $year года";
}
}
?>
<div class="container">
<h3 class="sidebar-header"><i class="fa fa-list"></i> Список учебных занятий по <strong><?php echo $subject; ?></strong> в <strong><?php echo $class; ?></strong></h3>
<div class="panel panel-default panel-table">
<div class="panel-body">
<button type="button" class="btn btn-menu" id="createButton" title="Добавить учебное занятие"><i class="fa fa-plus fa-2x"></i>
</br><span class="menu-item">Создать</span>
</button>
<button href="" type="button" class="btn btn-menu disabled" id="editButton" title="Редактировать учебное занятие"><i class="fa fa-pencil fa-2x"></i>
</br><span class="menu-item">Редактировать</span>
</button>
<button type="button" class="btn btn-menu disabled" id="deleteButton" data-toggle="modal" data-target="#myModal" title="Удалить учебное заниятие"><i class="fa fa-trash-o fa-2x"></i>
</br><span class="menu-item">Удалить</span>
</button>
<button href="" type="button" class="btn btn-menu disabled" id="showButton" title="Посмотреть учебное занятие"><i class="fa fa-eye fa-2x"></i>
</br><span class="menu-item">Cмотреть</span>
</button>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<form method="get">
<div class="input-group">
<input type="text" class="form-control" placeholder="Поиск по дате, теме урока и домашнему заданию" id="search" name="search" value="<?php if(isset($search)) echo $search;?>" >
<span class="input-group-btn">
<button class="btn btn-default" type="submit" name="submit" id="searchButton" title="Поиск"><i class="fa fa-search"></i></button>
</span>
</div><!-- /input-group -->
</form>
</div>
<div class="table-responsive">
<table name="timetable" class="table table-striped table-hover table-bordered numeric" data-sort-name="name" data-sort-order="desc">
<thead>
<tr>
<th></th>
<th>Дата урока</th> <!--1-->
<th>Время урока</th> <!--1-->
<th>Тема урока</th> <!--2-->
<th>Статус урока</th>
<th>Домашнее задание</th> <!--3-->
<!--<th>Загруженные файлы</th>-->
</tr>
</thead>
<tbody>
<?php
if(is_array($lessons) && count($lessons) ) {
foreach($lessons as $lesson) {
?>
<tr>
<td><input type="radio" name="lesson_id" value="<?php echo $lesson['LESSON_ID'];?>"></td>
<td ><?php echo $lesson['LESSON_DATE'];?></td>
<td ><?php echo date("H:i", strtotime($lesson['TIME_START'])).' - '.date("H:i", strtotime($lesson['TIME_FINISH']));?></td>
<td><?php echo $lesson['LESSON_THEME'];?></td>
<td><?php if($lesson['LESSON_STATUS'] == 1) echo "Проведен"; else echo "Не проведен";?></td>
<td>
<?php if (isset($lesson['LESSON_HOMEWORK']) && $lesson['LESSON_HOMEWORK'] != "") {
?>
<button class="btn btn-sample btn-xs" title="Показать домашнее задание" type="button" data-toggle="modal" data-target="#myModal<?php echo $lesson['LESSON_ID'] ?>"><i class="fa fa-home"></i> Домашнее задание
</button>
<div class="modal fade" id="myModal<?php echo $lesson['LESSON_ID'] ?>" 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" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Домашнее задание по уроку за <?php showDate($lesson['LESSON_DATE']);?></h4>
</div>
<div class="modal-body">
<?php echo $lesson['LESSON_HOMEWORK']; ?>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Закрыть</button>
</div>
</div>
</div>
</div>
<?php
} ?>
</td>
<!--<td>
<?php
foreach($files[$lesson['LESSON_ID']] as $file) {
?>
<a href="<?php echo base_url()."files/".$file['FILE_ID'].".".$file['FILE_EXTENSION']; ?>"><span class="glyphicon glyphicon-file" aria-hidden="true"><?php echo $file['FILE_NAME'].".".$file['FILE_EXTENSION']; ?></a></br>
<?php
}
?>
</td>-->
</tr>
<?php }} ?>
</tbody>
</table>
</div>
</div>
<?php echo $this->pagination->create_links(); ?>
<?php
if(count($lessons) == 0 && isset($search) && $search != "") {
?>
<div class="alert alert-info" role="alert">Поиск не дал результатов. Попробуйте другой запрос</div>
<?php } ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
if($(":radio[name=lesson_id]").is(':checked')) {
$('#editButton').removeClass('disabled');
$('#showButton').removeClass('disabled');
$('#deleteButton').removeClass('disabled');
} else {
$('#editButton').addClass('disabled');
$('#deleteButton').addClass('disabled');
$('#showButton').addClass('disabled');
}
$(":radio[name=lesson_id]").change(function() {
$('#editButton').removeClass('disabled');
$('#showButton').removeClass('disabled');
$('#deleteButton').removeClass('disabled');
});
$('#createButton').click(function() {
document.location.href = '<?php echo base_url(); ?>teacher/lesson/' + '<?php echo $this->uri->segment(3); ?>';
});
$('#editButton').click(function() {
var value = $(":radio[name=lesson_id]").filter(":checked").val();
document.location.href = '<?php echo base_url(); ?>teacher/lesson/' + '<?php echo $this->uri->segment(3); ?>' + '/' + value;
});
$('#buttonDeleteLessonModal').click(function() {
var value = $(":radio[name=lesson_id]").filter(":checked").val();
var base_url = '<?php echo base_url();?>';
$.ajax({
type: "POST",
url: base_url + "table/del/lesson/" + value,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(a) {
location.reload();
}
});
});
$("tr:not(:first)").click(function() {
$(this).children("td").find('input[type=radio]').prop('checked', true).change();
});
$('#showButton').click(function() {
var value = $(":radio[name=lesson_id]").filter(":checked").val();
document.location.href = '<?php echo base_url(); ?>teacher/lessonpage/' + '<?php echo $this->uri->segment(3); ?>' + '/' + value;
});
});
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Удаление учебного занятия</h4>
</div>
<div class="modal-body">
<p>Вы уверены, что хотите удалить это учебное занятие?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-sample" id="buttonDeleteLessonModal">Удалить</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<file_sep>/application/views/header.php
<!DOCTYPE html>
<html lang = "ru">
<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="description" content="Сайт электронного дневника учащегося">
<meta name="keywords" content="diary, school, pupil, дневник, школа, информационная система">
<meta name="author" content="<NAME>.">
<title> <?
if(isset($title)) echo $title." | Электронный дневник учащегося";
else echo "Электронный дневник учащегося";
?></title>
<link rel="shortcut icon" href="<?php echo base_url();?>images/school-new2.png">
<!--Bootstrap-->
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="<KEY> crossorigin="anonymous"></script>
<script src="<?php echo base_url();?>bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="<?php echo base_url();?>js/Chart.min.js" type="text/javascript"></script>
<script src="<?php echo base_url();?>js/tooltip.js" type="text/javascript"></script>
<script src="<?php echo base_url();?>js/passEye.js" type="text/javascript"></script>
<script src="<?php echo base_url();?>js/charRemaining.js" type="text/javascript"></script>
<script src="<?php echo base_url();?>js/jquery.maskedinput.min.js" type="text/javascript"></script>
<script src="<?php echo base_url();?>js/bootstrap-datepicker.min.js" type="text/javascript"></script>
<script src="<?php echo base_url();?>js/bootstrap-datepicker.ru.min.js" type="text/javascript"></script>
<script src="<?php echo base_url();?>js/select2.min.js" type="text/javascript"></script>
<!--<script src="<?php echo base_url();?>js/ru.js" type="text/javascript"></script>-->
<script src="<?php echo base_url();?>js/mindmup-editabletable.js" type="text/javascript"></script>
<!--<script src="<?php echo base_url();?>js/bootstrap-editable.min.js" type="text/javascript"></script>-->
<script type="text/javascript" src="<?php echo base_url();?>js/bootstrap-switch.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/bootstrap-contextmenu.js"></script>
<!--<script type="text/javascript" src="<?php echo base_url();?>js/legend.js"></script>-->
<link rel="stylesheet" href="<?php echo base_url();?>bootstrap/css/bootstrap.min.css">
<link href="<?php echo base_url();?>css/navbar.css" rel="stylesheet">
<!--<link href="<?php echo base_url();?>css/btn-menu.css" rel="stylesheet">-->
<link href="<?php echo base_url();?>css/main-style.css" rel="stylesheet">
<link href="<?php echo base_url();?>css/bootstrap-datepicker3.css" rel="stylesheet">
<link href="<?php echo base_url();?>css/select2.css" rel="stylesheet">
<link href="<?php echo base_url();?>css/select2-bootstrap.css" rel="stylesheet">
<link href="<?php echo base_url();?>css/bootstrap-switch.css" rel="stylesheet">
<link href="<?php echo base_url();?>css/font-awesome.min.css" rel="stylesheet">
<!--<link href="<?php echo base_url();?>css/bootstrap-editable.css" rel="stylesheet">-->
<style media='print' type='text/css'>
body {
padding: 10px;
}
</style>
</head>
<body>
<!--Header-->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<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="<?php echo base_url();?>">
<img alt="Иконка" src="<?php echo base_url();?>images/schoollogo.png" width="40" height="40">
</a>
<?php
/* if ($role != 4) echo '<a class="navbar-brand pull-left" href="teacher"><img src="'.base_url().'images/schoollogo.png" width="35" height="35">Электронный журнал</a>
';
else echo '<a class="navbar-brand pull-left" href="../pupil/news"><img src="'.base_url().'images/schoollogo.png" width="35" height="35">Электронный дневник</a>';*/
?>
</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 ($role == 4) {
?>
<li><a href="<?php echo base_url();?>pupil/news">Новости</a></li>
<li><a href="<?php echo base_url();?>pupil/timetable">Расписание</a></li>
<!--<li><a href="<?php echo base_url();?>pupil/diary">Дневник</a></li>-->
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Дневник <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="<?php echo base_url();?>pupil/diary"><i class="fa fa-graduation-cap"></i> Традиционный</a></li>
<li><a href="<?php echo base_url();?>pupil/marks"><i class="fa fa-book"></i> Оценки</a></li>
</ul>
</li>
<li><a href="<?php echo base_url();?>pupil/progress">Итоговые оценки</a></li>
<li><a href="<?php echo base_url();?>pupil/statistics">Статистика</a></li>
<li><a href="<?php echo base_url();?>messages/conversations">Общение</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><?php echo $mainlogin;?> <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="<?php echo base_url();?>files/guide.pdf"><i class="fa fa-question-circle"></i> Помощь</a></li>
<li><a href="<?php echo base_url();?>auth/logout"><i class="fa fa-sign-out fa-fw"></i> Выйти</a></li>
</ul>
</li>
</ul>
<?php }?>
<?php
if ($role == 2) { ?>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Списки <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="<?php echo base_url();?>admin/teachers"><i class="fa fa-user"></i> Учителя</a></li>
<li><a href="<?php echo base_url();?>admin/classes"><i class="fa fa-users"></i> Классы</a></li>
<li><a href="<?php echo base_url();?>admin/subjects"><i class="fa fa-book"></i> Общие предметы</a></li>
<li><a href="<?php echo base_url();?>admin/rooms"><i class="fa fa-building"></i> Кабинеты</a></li>
<li><a href="<?php echo base_url();?>admin/types"><i class="fa fa-paperclip"></i> Типы оценок</a></li>
<li><a href="<?php echo base_url();?>admin/years"><i class="fa fa-calendar"></i> Учебные годы</a></li>
</ul>
</li>
<li><a href="<?php echo base_url();?>admin/news">Новости</a></li>
<li><a href="<?php echo base_url();?>admin/statistics">Анализ</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><?php echo $mainlogin;?> <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="<?php echo base_url();?>files/guide.pdf"><i class="fa fa-question-circle"></i> Помощь</a></li>
<li><a href="<?php echo base_url();?>auth/logout"><i class="fa fa-sign-out fa-fw"></i> Выйти</a></li>
</ul>
</li>
</ul>
<?php
}
if ($role == 3) { ?>
<li><a href="<?php echo base_url();?>teacher/journal">Журнал</a></li>
<li><a href="<?php echo base_url();?>teacher/progress">Итоговые оценки</a></li>
<li><a href="<?php echo base_url();?>messages/conversations">Общение</a></li>
<li><a href="<?php echo base_url();?>teacher/statistics">Анализ</a></li>
<li><a href="<?php echo base_url();?>teacher/news">Новости</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><?php echo $mainlogin;?> <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="<?php echo base_url();?>files/guide.pdf"><i class="fa fa-question-circle"></i> Помощь</a></li>
<li><a href="<?php echo base_url();?>auth/logout"><i class="fa fa-sign-out fa-fw"></i> Выйти</a></li>
</ul>
</li>
</ul> <?php
}
if ($role == 1) { ?>
<li><a href="<?php echo base_url();?>teacher/journal">Журнал</a></li>
<li><a href="<?php echo base_url();?>teacher/progress">Итоговые оценки</a></li>
<li><a href="<?php echo base_url();?>messages/conversations">Общение</a></li>
<li><a href="<?php echo base_url();?>teacher/statistics">Анализ</a></li>
<li><a href="<?php echo base_url();?>teacher/news">Новости</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Класс <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="<?php echo base_url();?>teacher/pupils"><i class="fa fa-user"></i> Учащиеся</a></li>
<li><a href="<?php echo base_url();?>teacher/subjects"><i class="fa fa-book"></i> Предметы</a></li>
<li><a href="<?php echo base_url();?>teacher/timetable/1"><i class="fa fa-clock-o"></i> Расписание</a></li>
<li><a href="<?php echo base_url();?>teacher/classreport"><span class="glyphicon glyphicon-stats" aria-hidden="true"></span> Итоговый отчет</a></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><?php echo $mainlogin;?> <span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li><a href="<?php echo base_url();?>files/guide.pdf"><i class="fa fa-question-circle"></i> Помощь</a></li>
<li><a href="<?php echo base_url();?>auth/logout"><i class="fa fa-sign-out fa-fw"></i> Выйти</a></li>
</ul>
</li>
</ul> <?php
}
?>
</div>
</div>
</nav>
<!--Header-->
<script>
/*$(document).ready(function () {
//var url = window.location;
var myParam = (window.location.search.split('page=')[1]||'').split('&')[0];
var url = window.location.href.split('?')[0];
url = url + '?page=' + myParam;
//alert(myParam);
$('ul.nav a[href="' + url + '"]').parent().addClass('active');
$('ul.nav a').filter(function () {
return this.href == url;
}).parent().addClass('active').parent().parent().addClass('active');
});*/
$(document).ready(function() {
var splits = location.href.split('/');
var url = splits[0] +"/"+ splits[1]+"/"+splits[2]+"/"+splits[3]+"/"+splits[4]+"/"+splits[5].split('?')[0];
// alert(url);
$('ul.nav a[href="' + url + '"]').parent().addClass('active');
$('ul.nav a').filter(function () {
return this.href == url;
}).parent().addClass('active').parent().parent().addClass('active');
});
</script>
<file_sep>/application/views/admin/classesview.php
<div class="container">
<h3 class="sidebar-header"><i class="fa fa-users"></i> Список классов</h3>
<div class="panel panel-default panel-table">
<div class="panel-body">
<button type="button" class="btn btn-menu" id="createButton" title="Добавить класс"><i class="fa fa-plus fa-2x"></i>
</br><span class="menu-item">Создать</span>
</button>
<button href="" type="button" class="btn btn-menu disabled" id="editButton" title="Редактировать класс"><i class="fa fa-pencil fa-2x"></i>
</br><span class="menu-item">Редактировать</span>
</button>
<button type="button" class="btn btn-menu disabled" id="deleteButton" data-toggle="modal" data-target="#myModal" title="Удалить класс"><i class="fa fa-trash-o fa-2x"></i>
</br><span class="menu-item">Удалить</span>
</button>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<form method="get">
<div class="input-group">
<input type="text" class="form-control" placeholder="Поиск по параллели, номеру класса и классному руководителю" id="search" name="search" value="<?php if(isset($search)) echo $search;?>" >
<span class="input-group-btn">
<button class="btn btn-default" type="submit" name="submit" id="searchButton" title="Поиск"><i class="fa fa-search"></i></button>
</span>
</div><!-- /input-group -->
</form>
</div>
<div class="table-responsive">
<table name="timetable" class="table table-striped table-hover table-bordered numeric">
<thead>
<tr>
<th></th>
<th>Параллель</th>
<th>Буква</th>
<th>Учебный год</th>
<th>Текущий</th>
<th>Классный руководитель</th>
<!-- <th>Переведен из</br>другого класса</th>-->
</tr>
</thead>
<tbody>
<tr id="search" hidden="true">
<td></td>
<td>
<div class="form-group" style="margin-bottom: 0px;">
<input type="text" class="form-control" maxlength="100" >
</div>
</td>
</tr>
<?php
if(is_array($classes) && count($classes) ) {
foreach($classes as $class) {
?>
<tr>
<td><input type="radio" name="class_id" value="<?php echo $class['CLASS_ID'];?>"></td>
<td><?php echo $class['CLASS_NUMBER'];?></td>
<td><?php echo $class['CLASS_LETTER'];?></td>
<td><?php if(isset($class['YEAR_ID'])) echo date("Y",strtotime($class['YEAR_START']))." - ".date("Y",strtotime($class['YEAR_FINISH']))." гг.";?></td>
<td><?php if($class['CLASS_STATUS'] == 0) {echo "Нет";} else echo "Да";?></td>
<td><?php if(isset($class['TEACHER_ID'])) echo $class['TEACHER_NAME'];?></td>
<!--<td><?php if(isset($class['CLASS_PREVIOUS'])) echo "Да"; else echo "Нет";?></td>-->
</tr>
<?php }} ?>
</tbody>
</table>
</div>
</div>
<?php echo $this->pagination->create_links(); ?>
<?php
if(is_array($classes) && count($classes) == 0 && isset($search) && $search != "") {
?>
<div class="alert alert-info" role="alert">Поиск не дал результатов. Попробуйте другой запрос</div>
<?php } ?>
</div>
<script type="text/javascript">
$(document).ready(function() {
if($(":radio[name=class_id]").is(':checked')) {
$('#editButton').removeClass('disabled');
$('#deleteButton').removeClass('disabled');
} else {
$('#editButton').addClass('disabled');
$('#deleteButton').addClass('disabled');
}
$(":radio[name=class_id]").change(function() {
$('#editButton').removeClass('disabled');
$('#deleteButton').removeClass('disabled');
});
$('#createButton').click(function() {
document.location.href = '<?php echo base_url(); ?>admin/classitem';
});
$('#editButton').click(function() {
var value = $(":radio[name=class_id]").filter(":checked").val();
document.location.href = '<?php echo base_url(); ?>admin/classitem/' + value;
});
$('#buttonDeleteClassModal').click(function() {
var value = $(":radio[name=class_id]").filter(":checked").val();
var base_url = '<?php echo base_url();?>';
$.ajax({
type: "POST",
url: base_url + "table/del/class/" + value,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(a) {
location.reload();
}
});
});
$("tr:not(:first)").click(function() {
$(this).children("td").find('input[type=radio]').prop('checked', true).change();
});
});
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Удаление класса</h4>
</div>
<div class="modal-body">
<p>Вы уверены, что хотите удалить этот класс?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Отмена</button>
<button type="button" class="btn btn-sample" id="buttonDeleteClassModal">Удалить</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<file_sep>/application/views/teacher/classreportview.php
<?php
function setColor($mark) {
switch ($mark) {
case 5: echo '<span class="green">'.$mark.'</span>'; break;
case 4: echo '<span class="yellow">'.$mark.'</span>'; break;
case 3: echo '<span class="blue">'.$mark.'</span>'; break;
case 2: echo '<span class="red">'.$mark.'</span>'; break;
default: echo '<span class="grey">'.$mark.'</span>'; break;
}
}
?>
<div class="container">
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-4">
<form method="post">
<label for="period" class="control-label"><i class="fa fa-calendar"></i> Период</label>
<select id="period" name="period" onchange="this.form.submit();" style="width: 70%;" >
<?php
foreach ($periods as $period) {?>
<option value="<?php echo $period['PERIOD_ID'];?>"><?php echo $period['PERIOD_NAME']; ?></option><?php
}?>
</select>
</form>
</div>
<div class="col-md-8">
</div>
</div>
<div class="row">
<div class="col-md-8">
<h3 class="sidebar-header">Итоговый отчет</h3>
</div>
<div class="col-md-4" >
<h5><span onclick="print();" class="a-block pull-right" title="Печать"><i class="fa fa-print"></i> Печать</span></h5>
</div>
</div>
<div class="panel panel-default">
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered numeric">
<thead >
<tr>
<th>#</th>
<th>ФИО учащегося</th>
<?php
foreach($subjects as $subject) {
?>
<th class="rotate"><div><span><?php echo $subject['SUBJECT_NAME']; ?></span></div></th>
<?php
}
?>
<th class="rotate"><div><span>Средний балл</span></div></th>
</tr>
</thead>
<tbody>
<?php
for ($i = 0; $i < count($progress); $i++) {
?>
<tr>
<td><?php echo $i+1; ?></td>
<td><?php echo $progress[$i]["pupil"]; ?></td>
<?php
$s = 0;
$k = 0;
if(isset($progress[$i]["mark"])) {
for($y = 0; $y < count($progress[$i]["mark"]); $y++) {
?>
<td><?php if(isset($progress[$i]["mark"][$y])) {
setColor($progress[$i]["mark"][$y]);
$s = $s + $progress[$i]["mark"][$y];
$k++;
}
else setColor("н/д");
?></td>
<?php
}
}
?>
<td><?php if($k != 0) { ?><strong><?php echo number_format($s / $k, 1); ?></strong><?php } else echo "<span class='grey'>н/д</span>"; ?></td>
</tr>
<?php }?>
<tr>
<td></td>
<td><strong>Средний балл по предмету</strong></td>
<?php if(isset($average)) {
for ($i = 0; $i < count($average); $i++) { ?>
<td><?php if(isset($average[$i]) && $average[$i] != 0) echo "<strong>".$average[$i]."</strong>"; else echo "<span class='grey'>н/д</span>"; ?></td>
<?php } }?>
<td></td>
</tr>
</tbody>
</table>
</div>
</div>
<h3 class="sidebar-header">Гистограмма посещаемости</h3>
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-12">
<div style="background:white;"><canvas id="myChart"></canvas></div>
</div>
</div>
<table class="brand-table">
<tr>
<td><div class="color-swatch brand-warning"></div></td>
<td>Пропуски по неуважительной причине</td>
</tr>
<tr>
<td><div class="color-swatch brand-info"></div></td>
<td>Пропуски по уважительной причине</td>
</tr>
<tr>
<td><div class="color-swatch brand-success"></div></td>
<td>Пропуски по болезни</td>
</tr>
</table>
</div>
<script type="text/javascript">
document.getElementById('period').value = "<?php echo $this->uri->segment(3);?>";
$("#period").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
var passes = document.getElementById("myChart").getContext("2d");
// alert("wefef");
var base_url = '<?php echo base_url();?>';
var period = $('#period').find("option:selected").val();
//alert(period);
$.ajax({
type: "POST",
url: base_url + "api/getallpasses/" + period,
cache: false,
success: function(data){
//alert(data);
//$('#answer').html(data);
var json_obj = JSON.parse(data);
var description = new Array();
var myvalues1 = new Array();
var myvalues2 = new Array();
var myvalues3 = new Array();
for (var i in json_obj) {
description.push(json_obj[i].name);
myvalues1.push(json_obj[i].pass[1]);
myvalues2.push(json_obj[i].pass[2]);
myvalues3.push(json_obj[i].pass[3]);
}
var data = {
labels: description,
datasets: [
{
label: "Пропуски по неуважительной причине",
fillColor: "#fcf8e3",
strokeColor: "#8a6d3b",
data: myvalues1
},
{
label: "Пропуски по уважительной причине",
fillColor: "#d9edf7",
strokeColor: "#31708f",
data: myvalues2
},
{
label: "Пропуски по болезни",
fillColor: "#dff0d8",
strokeColor: "#3c763d",
data: myvalues3
}
]};
var options = {
animation: false,
responsive: true,
maintainAspectRatio: true
};
new Chart(passes).Bar(data, options);
//legend(document.getElementById('placeholder'), data);
}
});
</script><file_sep>/application/views/pupil/postview.php
<div class="col-md-8">
<div class="blog_grid">
<h2 class="post_title"><?php if(isset($theme)) echo $theme; ?></h2>
<ul class="links">
<li><i class="fa fa-calendar"></i> <?php echo showDate($time); ?></li>
<li><i class="fa fa-user"></i> <?php echo $teacher; ?></li>
</ul>
<p><?php echo $text; ?></p>
</div>
</div>
</div>
</div><file_sep>/application/controllers/Teacher.php
<?php
class Teacher extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('teachermodel', 'teacher');
$this->load->model('tablemodel', 'tablemodel');
$this->load->library("roleenum");
}
function _remap($method, $params = array()) {
$login = $this->session->userdata('login');
$role = $this->session->userdata('role');
$roleEnum = $this->roleenum;
if(isset($login) && isset($role) && ($role == $roleEnum::ClassTeacher || $role == $roleEnum::Teacher)) {
$data['role'] = $role;
$data['mainlogin'] = $login;
switch($method) {
case 'pupils': {
$data['title'] = "Список учащихся";
break;
}
case 'subjects': {
$data['title'] = "Список предметов в классе";
break;
}
case 'journal': {
$data['title'] = "Журнал";
break;
}
case 'progress': {
$data['title'] = "Итоговые оценки";
break;
}
case 'timetable': {
$data['title'] = "Расписание";
break;
}
case 'lessons': {
$data['title'] = "Список учебных занятий";
break;
}
case 'statistics': {
$data['title'] = "Статистика";
break;
}
case 'pupil': {
$data['title'] = "Учащийся";
break;
}
case 'subject': {
$data['title'] = "Предмет в классе";
break;
}
case 'timetableitem': {
$data['title'] = "Предмет в расписании";
break;
}
case 'lesson': case 'lessonpage': {
$data['title'] = "Учебное занятие";
break;
}
}
$this->load->view('header', $data);
if (method_exists($this, $method))
{
call_user_func_array(array($this, $method), $params);
}
else {
redirect(base_url()."teacher/journal");
}
$this->load->view('footer');
}
else {
redirect('auth/logout');
}
}
function pupils($offset = 1) {
$search = "";
if(isset($_GET['submit'])) {
if(isset($_GET['search'])) {
$search = urldecode($_GET['search']);
$data['search'] = $search;
if ($search == "") {
redirect(base_url()."teacher/pupils");
} else redirect(base_url()."teacher/pupils?search=".$search);
}
}
if(isset($_GET['search'])) {
$search = $_GET['search'];
$data['search'] = $search;
}
$class_id = $login = $this->session->userdata('class_id');
$num = 10;
$config['total_rows'] = $this->teacher->totalPupils($class_id, $search);
$config['base_url'] = base_url()."teacher/pupils";
$config['per_page'] = $num;
if (count($_GET) > 0) { $config['suffix'] = '?' . http_build_query($_GET, '', "&");
$config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
}
$this->pagination->initialize($config);
$query = $this->teacher->getPupils($num, $offset * $num - $num, $class_id, $search);
$data['pupils'] = array();
if($query) {
$data['pupils'] = $query;
}
$this->load->view("teacher/pupilsview", $data);
}
private function _getPupilProgress($id, $start, $finish) {
$result = array();
$class_id = $login = $this->session->userdata('class_id');
$subjects = $this->teacher->getAllSubjectsClass($class_id);
$i = 0;
foreach($subjects as $subject) {
$result[$i]["subject"] = $subject["SUBJECT_NAME"];
$subject_id = $subject["SUBJECTS_CLASS_ID"];
$marks = $this->teacher->getPupilMarksForSubject($id, $subject_id, $start, $finish);
if(count($marks) == 0) {
$result[$i]["marks"] = array();
} else {
$z = 0;
foreach($marks as $mark) {
$result[$i]["marks"][$z]["mark"] = $mark['ACHIEVEMENT_MARK'];
if(isset($mark['TYPE_NAME'])) {
$result[$i]["marks"][$z]["type"] = $mark['TYPE_NAME']." (".date('d.m', strtotime($mark['LESSON_DATE'])).")";
} else {
$result[$i]["marks"][$z]["type"] = date('d.m', strtotime($mark['LESSON_DATE']));
}
$z++;
}
}
$passes = $this->teacher->getPupilPassForSubject($id, $subject_id, $start, $finish);
if(count($passes) > 0) {
foreach($passes as $pass) {
if($pass['ATTENDANCE_PASS'] == 'н') {
$result[$i]["pass"]['н'] = $pass['COUNT'];
}
if($pass['ATTENDANCE_PASS'] == 'б') {
$result[$i]["pass"]['б'] = $pass['COUNT'];
}
if($pass['ATTENDANCE_PASS'] == 'у') {
$result[$i]["pass"]['у'] = $pass['COUNT'];
}
}
} else {
$result[$i]["pass"] = null;
}
$i++;
}
return $result;
}
function pupil($id = null, $progress = null, $period = null) {
if(isset($_POST['save'])) {
$name = $_POST['inputName'];
$password = $_POST['input<PASSWORD>'];
$login = $_POST['inputLogin'];
$status = $_POST['inputStatus'];
$address = $_POST['inputAddress'];
$phone = $_POST['inputPhone'];
$birthday = $_POST['inputBirthday'];
$class_id = $this->session->userdata('class_id');
if(isset($id)) {
$this->tablemodel->updatePupil($id, $name, $password, $login, $status, md5($password), $address, $phone, $birthday);
} else {
$this->tablemodel->addPupil($name, $password, $login, $status, md5($password), $address, $phone, $birthday, $class_id);
}
redirect(base_url()."teacher/pupils");
} else {
if(isset($id)) {
$class_id = $login = $this->session->userdata('class_id');
$pupil = $this->teacher->getPupilById($id, $class_id);
if(isset($pupil)) {
if(isset($progress)) {
$borders = $this->teacher->getBorders($class_id);
if(!isset($period)) {
redirect(base_url()."teacher/pupil/".$id."/progress/".$borders[0]['PERIOD_ID']);
} else {
if(isset($_POST['period'])) {
$period = $_POST['period'];
redirect(base_url()."teacher/pupil/".$id."/progress/".$period);
}
foreach ($borders as $border) {
if($period == $border['PERIOD_ID']) {
$start = $border['PERIOD_START'];
$finish = $border['PERIOD_FINISH'];
}
}
//успеваемость учащегося
$data['periods'] = $borders;
$data['progress'] = $this->_getPupilProgress($id, $start, $finish);
$data['name'] = $pupil['PUPIL_NAME'];
$this->load->view("teacher/pupilprogressview", $data);
}
} else {
//редактирование учащегося
$data['name'] = $pupil['PUPIL_NAME'];
$data['login'] = $pupil['PUPIL_LOGIN'];
$data['password'] = $<PASSWORD>['<PASSWORD>'];
$data['address'] = $pupil['PUPIL_ADDRESS'];
$data['phone'] = $pupil['PUPIL_PHONE'];
$data['birthday'] = $pupil['PUPIL_BIRTHDAY'];
$data['status'] = $pupil['PUPIL_STATUS'];
$data['id'] = $pupil['PUPIL_ID'];
$data['title'] = 'Редактирование учащегося';
$this->load->view("blankview/blankpupilview", $data);
}
} else {
//ошибка
$data['error'] = "Такого учащегося не существует. Вернитесь обратно";
$this->load->view("errorview", $data);
}
} else {
//добавление учащегося
$data['title'] = 'Добавление нового учащегося';
$this->load->view("blankview/blankpupilview", $data);
}
}
}
function subjects($offset = 1) {
$search = "";
if(isset($_GET['submit'])) {
if(isset($_GET['search'])) {
$search = urldecode($_GET['search']);
$data['search'] = $search;
if ($search == "") {
redirect(base_url()."teacher/subjects");
} else redirect(base_url()."teacher/subjects?search=".$search);
}
}
if(isset($_GET['search'])) {
$search = $_GET['search'];
$data['search'] = $search;
}
$class_id = $login = $this->session->userdata('class_id');
$num = 10;
$config['total_rows'] = $this->teacher->totalSubjectsClass($class_id, $search);
$config['base_url'] = base_url()."teacher/subjects";
$config['per_page'] = $num;
if (count($_GET) > 0) { $config['suffix'] = '?' . http_build_query($_GET, '', "&");
$config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
}
$this->pagination->initialize($config);
$query = $this->teacher->getSubjectsClass($num, $offset * $num - $num, $class_id, $search);
$data['subjects'] = array();
if($query) {
$data['subjects'] = $query;
}
$this->load->view("teacher/subjectsview", $data);
}
function subject($id = null) {
$data['teachers'] = $this->teacher->getTeachers();
$data['subjects'] = $this->teacher->getSubjects();
if(isset($_POST['save'])) {
$teacher = $_POST['inputTeacher'];
$subject = $_POST['inputSubject'];
$class_id = $login = $this->session->userdata('class_id');
if(isset($id)) {
$this->tablemodel->updateSubjectsClass($id, $teacher, $subject, $class_id);
} else {
$this->tablemodel->addSubjectsClass($teacher, $subject, $class_id);
}
redirect(base_url()."teacher/subjects");
} else {
if(isset($id)) {
$class_id = $login = $this->session->userdata('class_id');
$subject = $this->teacher->getSubjectById($id, $class_id);
if(isset($subject)) {
$data['teacher_name'] = $subject['TEACHER_NAME'];
$data['teacher_id'] = $subject['TEACHER_ID'];
$data['subject_name'] = $subject['SUBJECT_NAME'];
$data['subject_id'] = $subject['SUBJECT_ID'];
$data['id'] = $subject['SUBJECTS_CLASS_ID'];
$data['title'] = 'Редактирование предмета в классе';
$this->load->view("blankview/blanksubjectsclassview", $data);
} else {
//ошибка
$data['error'] = "Такого предмета в классе не существует. Вернитесь обратно";
$this->load->view("errorview", $data);
}
} else {
$data['title'] = 'Добавление нового предмета в классе';
$this->load->view("blankview/blanksubjectsclassview", $data);
}
}
}
function timetable($day = null) {
if($day != null && ($day == 1 || $day == 2 || $day == 3 || $day == 4 || $day == 5 || $day == 6)) {
$class_id = $login = $this->session->userdata('class_id');
$data['timetable'] = $this->teacher->getTimetable($class_id, $day);
$this->load->view("teacher/timetableview", $data);
}
else {
//ошибка
$data['error'] = "Расписания не существует. Вернитесь обратно";
$this->load->view("errorview", $data);
}
}
function timetableitem($day = null, $id = null) {
if(isset($_POST['save'])) {
$time = $_POST['inputTime'];
$subject = $_POST['inputSubject'];
$room = $_POST['inputRoom'];
if(isset($id)) {
$this->tablemodel->updateTimetable($id, $time, $subject, $day, $room);
} else {
$this->tablemodel->addTimetable($time, $subject, $day, $room);
}
redirect(base_url()."teacher/timetable/".$day);
} else {
$dayName = "";
switch($day) {
case '1': $dayName = '<strong>понедельник</strong>'; break;
case '2': $dayName = '<strong>вторник</strong>'; break;
case '3': $dayName = '<strong>среду</strong>'; break;
case '4': $dayName = '<strong>четверг</strong>'; break;
case '5': $dayName = '<strong>пятницу</strong>'; break;
case '6': $dayName = '<strong>субботу</strong>'; break;
}
$class_id = $login = $this->session->userdata('class_id');
$data['times'] = $this->teacher->getTimes();
$data['subjects'] = $this->teacher->getAllSubjectsClass($class_id);
$data['rooms'] = $this->teacher->getRooms();
if(isset($id) && isset($day)) {
$timetable = $this->teacher->getTimetableById($id, $class_id);
if(isset($timetable)) {
$data['time_id'] = $timetable['TIME_ID'];
$data['subject_id'] = $timetable['SUBJECTS_CLASS_ID'];
$data['room_id'] = $timetable['ROOM_ID'];
$data['id'] = $timetable['TIMETABLE_ID'];
$data['title'] = 'Редактирование предмета в расписании на '.$dayName;
$this->load->view("blankview/blanktimetableview", $data);
} else {
//ошибка
$data['error'] = "Такого предмета в расписании не существует. Вернитесь обратно";
$this->load->view("errorview", $data);
}
} else {
if(isset($day)) {
$data['title'] = 'Добавление нового предмета в расписание на '.$dayName;
$this->load->view("blankview/blanktimetableview", $data);
} else {
//ошибка
$data['error'] = "Расписание на день не выбрано. Вернитесь обратно";
$this->load->view("errorview", $data);
}
}
}
}
function progress($class_id = null, $subject_id = null) {
$id = $login = $this->session->userdata('id');
$classes = $this->teacher->getClasses($id);
if($class_id == null || $subject_id == null) {
if(count($classes) > 0) {
$class_id = $classes[0]['CLASS_ID'];
$subjects = $this->teacher->getSubjectsForClass($class_id, $id);
if(count($subjects) > 0) {
$subject_id = $subjects[0]['SUBJECTS_CLASS_ID'];
redirect(base_url()."teacher/progress/".$class_id."/".$subject_id);
} else {
//ошибка
$data['error'] = "Ошибка";
$this->load->view("errorview", $data);
}
} else {
//ошибка
$data['error'] = "Вы не преподаете ни в одном классе";
$this->load->view("errorview", $data);
}
} else {
if(isset($_POST["class"])) {
$class_id = $_POST['class'];
$subjects = $this->teacher->getSubjectsForClass($class_id, $id);
if(count($subjects) > 0) {
$subject_id = $subjects[0]['SUBJECTS_CLASS_ID'];
redirect(base_url()."teacher/progress/".$class_id."/".$subject_id);
} else {
//ошибка
$data['error'] = "Ошибка";
$this->load->view("errorview", $data);
}
}
if(isset($_POST["subject"])) {
$subject_id = $_POST['subject'];
redirect(base_url()."teacher/progress/".$class_id."/".$subject_id);
}
$data['classes'] = $classes;
$data['subjects'] = $this->teacher->getSubjectsForClass($class_id, $id);
$pupils = $this->teacher->getPupilsForClass($class_id);
$resultArr = array();
$i = 0;
$borders = $this->teacher->getBorders($class_id);
foreach($pupils as $pupil) {
$pupil_id = $pupil['PUPIL_ID'];
$resultArr[$i]["pupil_id"] = $pupil_id;
$resultArr[$i]["pupil_name"] = $pupil['PUPIL_NAME'];
//$marks = $this->teacher->getPupilMarks($pupil_id, $class_id, $subject_id);
foreach($borders as $border) {
$period_id = $border['PERIOD_ID'];
$start = $border["PERIOD_START"];
$finish = $border["PERIOD_FINISH"];
$resultArr[$i][$border['PERIOD_NAME']]["mark"] =
$this->teacher->getPupilProgressMark($pupil_id, $subject_id, $period_id)['MARK'];
$average = $this->teacher->getAverageMarkForPupil($pupil_id, $subject_id, $start, $finish);
$resultArr[$i][$border['PERIOD_NAME']]["average"] = number_format($average['MARK'],1);
}
/*foreach($marks as $mark) {
$resultArr[$i][$mark['PERIOD_NAME']]["mark"] = $mark['PROGRESS_MARK'];
$start = $mark["PERIOD_START"];
$finish = $mark["PERIOD_FINISH"];
$average = $this->teacher->getAverageMarkForPupil($pupil_id, $subject_id, $start, $finish);
$resultArr[$i][$mark['PERIOD_NAME']]["average"] = number_format($average['MARK'],1);
}*/
$i++;
}
$data['marks'] = $resultArr;
//$data['stat'] = $this->_getProgressStatistics($class_id, $subject_id, $borders);
$this->load->view("teacher/progressview", $data);
}
}
private function _getProgressStatistics($class_id, $subject_id, $borders) {
$result = array();
$i = 0;
foreach($borders as $border) {
$period_id = $border['PERIOD_ID'];
$period_name = $border['PERIOD_NAME'];
$result[$i]["period"] = $period_name;
for ($y = 2; $y <=5; $y++) {
$result[$i][$y] = $this->teacher->getCountProgressMark($subject_id, $period_id, $y)['COUNT'];
}
if($result[$i]["5"] + $result[$i]["4"] + $result[$i]["3"]+ $result[$i]["2"] != 0) {
$result[$i]["ach"] = round(($result[$i]["5"] + $result[$i]["4"] + $result[$i]["3"]) /
($result[$i]["5"] + $result[$i]["4"] + $result[$i]["3"]+ $result[$i]["2"]) *100);
} else {
$result[$i]["ach"] = 0;
}
if( $result[$i]["5"] + $result[$i]["4"] + $result[$i]["3"]+ $result[$i]["2"] != 0) {
$result[$i]["quality"] = round(($result[$i]["5"] + $result[$i]["4"]) /
($result[$i]["5"] + $result[$i]["4"] + $result[$i]["3"]+ $result[$i]["2"]) *100);
} else {
$result[$i]["quality"] = 0;
}
$i++;
}
return $result;
}
function lessons($subject = null, $offset = 1) {
$this->schedule();
$id = $login = $this->session->userdata('id');
$info = $this->teacher->getSubjectInfo($subject, $id);
if(!isset($info)) {
//ошибка
$data['error'] = "У вас нет доступа к этой странице. Вернитесь обратно";
$this->load->view("errorview", $data);
}
else {
$search = "";
if(isset($_GET['submit'])) {
if(isset($_GET['search'])) {
$search = urldecode($_GET['search']);
$data['search'] = $search;
if ($search == "") {
redirect(base_url()."teacher/lessons/".$subject);
} else redirect(base_url()."teacher/lessons/".$subject."?search=".$search);
}
}
if(isset($_GET['search'])) {
$search = $_GET['search'];
$data['search'] = $search;
}
$data['subject'] = $info['SUBJECT_NAME'];
$data['class'] = $info['CLASS_NUMBER']." ".$info['CLASS_LETTER']." (".$info['YEAR_START']." - ".$info['YEAR_FINISH']." гг.)";
/*$id = $login = $this->session->userdata('id');
$lesson = $this->teacher->checkLessonsForTeacher($subject, $id);
if(isset($lesson) && $lesson['COUNT'] > 0) {*/
$num = 10;
$config['total_rows'] = $this->teacher->totalLessons($subject, $search);
$config['base_url'] = base_url()."teacher/lessons/".$subject;
$config['per_page'] = $num;
$config['uri_segment'] = 4;
if (count($_GET) > 0) { $config['suffix'] = '?' . http_build_query($_GET, '', "&");
$config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
}
$this->pagination->initialize($config);
$query = $this->teacher->getLessons($num, $offset * $num - $num, $subject, $search);
$data['lessons'] = array();
$data['files'] = array();
$arrFiles = array();
if($query) {
$data['lessons'] = $query;
foreach($query as $lesson) {
$lesson_id = $lesson['LESSON_ID'];
//$files = $this->teacher->getFiles($lesson_id);
//$arrFiles[$lesson_id] = $files;
}
//$data['files'] = $arrFiles;
}
$this->load->view("teacher/lessonsview", $data);
}
}
function upload($file, $id) {
//создаем папку для пользователя
//$user = $login = $this->session->userdata('id');
$dir = "/Applications/MAMP/htdocs/ischool/files/";
/*if(!is_dir($dir)) {
mkdir($dir, 0700);
}*/
$filename = $file['name'];
$ext = substr($file['name'], 1 + strrpos($file['name'], "."));
$size = $file['size'];
$name = preg_replace("/\.[^.]+$/", "", $filename);
$file_id = $this->tablemodel->addFile($size, $ext, $name, $id);
if(move_uploaded_file($file['tmp_name'], $dir.$file_id.".".$ext)) {
return $file_id;
} else {
return null;
}
/*$filename = $file['tmp_name'];
$ext = substr($file['name'], 1 + strrpos($file['name'], "."));
if (filesize($filename) > $max_image_size) {
$error = 'Error: File size > 64K.';
} elseif (!in_array($ext, $valid_types)) {
$error = 'Error: Invalid file type.';
} else {
&& ($size[1] < $max_image_height)) {
if (@move_uploaded_file($filename, "/www/htdocs/upload/")) {
echo 'File successful uploaded.';
} else {
echo 'Error: moving fie failed.';
}
} else {
echo 'Error: invalid image properties.';
}
}*/
}
function lesson($subject = null, $id = null) {
if(isset($_POST['save'])){
/*echo "<pre>";
print_r($_FILES);
echo "</pre>";*/
$theme = $_POST['inputTheme'];
$date = $_POST['inputDate'];
$time = $_POST['inputTime'];
$homework = $_POST['inputHomework'];
$status = $_POST['inputStatus'];
if(isset($id)) {
$this->tablemodel->updateLesson($id, $subject, $theme, $date, $time, $homework, $status);
} else {
$id = $this->tablemodel->addLesson($subject, $theme, $date, $time, $homework, $status);
}
//$this->load->library('../controllers/table');
//загружаем файлы
/*if(isset($_FILES['inputFile1']) && $_FILES['inputFile1']['error'] == 0) {
$file1 = $this->upload($_FILES['inputFile1'], $id);
}
if(isset($_FILES['inputFile2']) && $_FILES['inputFile2']['error'] == 0) {
$file2 = $this->upload($_FILES['inputFile2'], $id);
}
if(isset($_FILES['inputFile3']) && $_FILES['inputFile3']['error'] == 0) {
$file3 = $this->upload($_FILES['inputFile3'], $id);
}*/
$back = $_POST['inputURL'];
if(isset($back)) {
redirect($back);
} else
redirect(base_url()."teacher/lessons/".$subject);
} else {
$this->schedule();
$data['times'] = $this->teacher->getTimes();
if(isset($subject)) {
if(isset($id)) {
$user = $login = $this->session->userdata('id');
$lesson = $this->teacher->getLessonById($id, $subject, $user);
if(isset($lesson)) {
$data['theme'] = $lesson['LESSON_THEME'];
$data['date'] = $lesson['LESSON_DATE'];
$data['time_id'] = $lesson['TIME_ID'];
$data['homework'] = $lesson['LESSON_HOMEWORK'];
$data['status'] = $lesson['LESSON_STATUS'];
$data['id'] = $lesson['LESSON_ID'];
$data['title'] = 'Редактирование учебного занятия';
if (!empty($_SERVER['HTTP_REFERER'])) {
$data['back'] = $_SERVER['HTTP_REFERER'];
}
$this->load->view("blankview/blanklessonview", $data);
} else {
//ошибка
$data['error'] = "Такого урока не существует. Вернитесь обратно";
$this->load->view("errorview", $data);
}
} else {
$data['title'] = 'Добавление нового учебного занятия';
if (!empty($_SERVER['HTTP_REFERER'])) {
$data['back'] = $_SERVER['HTTP_REFERER'];
}
$this->load->view("blankview/blanklessonview", $data);
}
} else {
//ошибка
$data['error'] = "Ошибка";
$this->load->view("errorview", $data);
}
}
}
function classreport($period = null) {
$class_id = $this->session->userdata('class_id');
$borders = $this->teacher->getBorders($class_id);
if(!isset($period)) {
redirect(base_url()."teacher/classreport/".$borders[0]['PERIOD_ID']);
} else {
if(isset($_POST['period'])) {
$period = $_POST['period'];
redirect(base_url()."teacher/classreport/".$period);
}
$data['periods'] = $borders;
//успеваемость
$pupils = $this->teacher->getAllPupils($class_id);
$subjects = $this->teacher->getAllSubjectsClass($class_id);
if(count($pupils) > 0) {
$result = array();
$average = array();
$i = 0;
foreach($pupils as $pupil) {
$pupil_id = $pupil['PUPIL_ID'];
$result[$i]["pupil"] = $pupil['PUPIL_NAME'];
$y = 0;
foreach($subjects as $subject) {
$subject_id = $subject['SUBJECTS_CLASS_ID'];
$result[$i]['mark'][$y] = $this->teacher->getPupilProgressForSubject($pupil_id, $subject_id, $period)['PROGRESS_MARK'];
$average[$y] = number_format($this->teacher->getAverageForSubject($class_id, $subject_id, $period)['MARK'],1);
$y++;
}
$i++;
}
$data['progress'] = $result;
$data['average'] = $average;
} else {
$data['progress'] = array();
}
$data['subjects'] = $subjects;
$this->load->view("teacher/classreportview", $data);
}
}
function _getJournal($class_id, $lessons) {
$pupils = $this->teacher->getPupilsForClass($class_id);
//$lessons = $this->teacher->getLessons($num, $offset * $num - $num, $subject_id);
$result = array();
$i = 0;
foreach($pupils as $pupil) {
$pupil_id = $pupil['PUPIL_ID'];
$result[$i]["pupil_id"] = $pupil_id;
$result[$i]["pupil_name"] = $pupil['PUPIL_NAME'];
$y = 0;
foreach($lessons as $lesson) {
$lesson_id = $lesson['LESSON_ID'];
$marks = $this->teacher->getPupilMarksForLesson($pupil_id, $lesson_id);
$z = 0;
if(count($marks) > 0) {
foreach($marks as $mark) {
$result[$i]["lessons"][$y]["marks"][$z]["mark"] = $mark['ACHIEVEMENT_MARK'];
$result[$i]["lessons"][$y]["marks"][$z]["type"] = $mark['TYPE_NAME'];
$z++;
}
} else {
$result[$i]["lessons"][$y]["marks"] = array();
}
$pass = $this->teacher->getPupilPassForLesson($pupil_id, $lesson_id);
if(isset($pass)) {
$result[$i]["lessons"][$y]['pass'] = $pass['ATTENDANCE_PASS'];
} else {
$result[$i]["lessons"][$y]['pass'] = null;
}
$y++;
}
$i++;
}
return $result;
}
function journal($class_id = null, $subject_id = null, $offset = 1) {
$this->schedule();
$num = 12;
$id = $login = $this->session->userdata('id');
$classes = $this->teacher->getClasses($id);
if($class_id == null || $subject_id == null) {
if(count($classes) > 0) {
$class_id = $classes[0]['CLASS_ID'];
$subjects = $this->teacher->getSubjectsForClass($class_id, $id);
if(count($subjects) > 0) {
$subject_id = $subjects[0]['SUBJECTS_CLASS_ID'];
redirect(base_url()."teacher/journal/".$class_id."/".$subject_id);
} else {
//ошибка
$data['error'] = "Вы не преподаете ни одного предмета в классе";
$this->load->view("errorview", $data);
}
} else {
//ошибка
$data['error'] = "Вы не преподаете ни в одном классе";
$this->load->view("errorview", $data);
}
} else {
if(isset($_POST["class"])) {
$class_id = $_POST['class'];
$subjects = $this->teacher->getSubjectsForClass($class_id, $id);
if(count($subjects) > 0) {
$subject_id = $subjects[0]['SUBJECTS_CLASS_ID'];
redirect(base_url()."teacher/journal/".$class_id."/".$subject_id);
} else {
//ошибка
$data['error'] = "Ошибка";
$this->load->view("errorview", $data);
}
}
if(isset($_POST["subject"])) {
$subject_id = $_POST['subject'];
redirect(base_url()."teacher/journal/".$class_id."/".$subject_id);
}
$data['classes'] = $classes;
$data['subjects'] = $this->teacher->getSubjectsForClass($class_id, $id);
$lessons = $this->teacher->getLessons($num, $offset * $num - $num, $subject_id, "");
$data['lessons'] = $lessons;
$config['total_rows'] = $this->teacher->totalLessons($subject_id, "");
$config['base_url'] = base_url()."teacher/journal/".$class_id."/".$subject_id;
$config['per_page'] = $num;
$config['uri_segment'] = 5;
$this->pagination->initialize($config);
$data['result'] = $this->_getJournal($class_id, $lessons);
$this->load->view("teacher/journalview", $data);
}
}
function attendance() {
$class_id = $login = $this->session->userdata('class_id');
}
private function _getLessonPage($lesson, $subject) {
$result = array();
$pupils = $this->teacher->getPupilsForClass($this->teacher->getClassBySubject($subject)['CLASS_ID']);
$i = 0;
foreach ($pupils as $pupil) {
$pupil_id = $pupil['PUPIL_ID'];
$result[$i]['pupil_id'] = $pupil_id;
$result[$i]['pupil_name'] = $pupil['PUPIL_NAME'];
$marks = $this->teacher->getPupilMarksForLesson($pupil_id, $lesson);
if(count($marks) == 0) {
$result[$i]['marks'] = array();
} else {
$y = 0;
foreach($marks as $mark) {
$result[$i]['marks'][$y]['mark'] = $mark['ACHIEVEMENT_MARK'];
$result[$i]['marks'][$y]['type'] = $mark['TYPE_NAME'];
$result[$i]['marks'][$y]['type_id'] = $mark['TYPE_ID'];
$result[$i]['marks'][$y]['achievement'] = $mark['ACHIEVEMENT_ID'];
$y++;
}
}
$pass = $this->teacher->getPupilPassForLesson($pupil_id, $lesson);
if(isset($pass)) {
$result[$i]['pass_id'] = $pass['ATTENDANCE_ID'];
$result[$i]['pass'] = $pass['ATTENDANCE_PASS'];
} else {
$result[$i]['pass_id'] = null;
$result[$i]['pass'] = null;
}
$note = $this->teacher->getPupilNoteForLesson($pupil_id, $lesson);
if(isset($note)) {
$result[$i]['note_id'] = $note['NOTE_ID'];
$result[$i]['note'] = $note['NOTE_TEXT'];
} else {
$result[$i]['note_id'] = null;
$result[$i]['note'] = null;
}
$i++;
}
return $result;
}
function lessonpage($subject = null, $id = null) {
if(isset($id) && isset($subject)) {
$user = $login = $this->session->userdata('id');
$lesson = $this->teacher->getLessonById($id, $subject, $user);
if(isset($lesson)) {
$data['theme'] = $lesson['LESSON_THEME'];
$data['id'] = $lesson['LESSON_ID'];
$data['date'] = $lesson['LESSON_DATE'];
$data['time'] = date('H:i', strtotime($lesson['TIME_START']))." - ".date('H:i', strtotime($lesson['TIME_FINISH']));
$data['homework'] = $lesson['LESSON_HOMEWORK'];
$data['status'] = $lesson['LESSON_STATUS'];
$data['class'] = $lesson['CLASS_NUMBER']." ".$lesson['CLASS_LETTER'];
$data['subject'] = $lesson['SUBJECT_NAME'];
//$data['files'] = $this->teacher->getFiles($id);
$data['info'] = $this->_getLessonPage($id, $subject);
$data['types'] = $this->teacher->getTypes();
//$data['pupils'] = $this->teacher->getPupilsForClass($this->teacher->getClassBySubject($subject)['CLASS_ID']);
$this->load->view("teacher/lessonpageview", $data);
} else {
//ошибка
$data['error'] = "Такого урока не существует. Вернитесь обратно";
$this->load->view("errorview", $data);
}
} else {
//ошибка
$data['error'] = "Ошибка";
$this->load->view("errorview", $data);
}
}
function statistics($class_id = null, $subject_id = null) {
$id = $login = $this->session->userdata('id');
$classes = $this->teacher->getClasses($id);
if($class_id == null || $subject_id == null) {
if(count($classes) > 0) {
$class_id = $classes[0]['CLASS_ID'];
$subjects = $this->teacher->getSubjectsForClass($class_id, $id);
if(count($subjects) > 0) {
$subject_id = $subjects[0]['SUBJECTS_CLASS_ID'];
redirect(base_url()."teacher/statistics/".$class_id."/".$subject_id);
} else {
//ошибка
$data['error'] = "Ошибка";
$this->load->view("errorview", $data);
}
} else {
//ошибка
$data['error'] = "Вы не преподаете ни в одном классе";
$this->load->view("errorview", $data);
}
} else {
if(isset($_POST["class"])) {
$class_id = $_POST['class'];
$subjects = $this->teacher->getSubjectsForClass($class_id, $id);
if(count($subjects) > 0) {
$subject_id = $subjects[0]['SUBJECTS_CLASS_ID'];
redirect(base_url()."teacher/statistics/".$class_id."/".$subject_id);
} else {
//ошибка
$data['error'] = "Ошибка";
$this->load->view("errorview", $data);
}
}
if(isset($_POST["subject"])) {
$subject_id = $_POST['subject'];
redirect(base_url()."teacher/statistics/".$class_id."/".$subject_id);
}
$data['classes'] = $classes;
$data['subjects'] = $this->teacher->getSubjectsForClass($class_id, $id);
$borders = $this->teacher->getBorders($class_id);
$data['stat'] = $this->_getProgressStatistics($class_id, $subject_id, $borders);
$data['periods'] = $borders;
$this->load->view("teacher/statisticsview", $data);
}
}
function schedule() {
$id = $login = $this->session->userdata('id');
$today = date("Y-m-d");
$classes = $this->teacher->getClassesByDate($today, $id);
$result = array();
foreach($classes as $class) {
$class_id = $class['CLASS_ID'];
$subjects = $this->teacher->getSubjectsForClass($class_id, $id);
foreach($subjects as $subject) {
$subject_id = $subject['SUBJECTS_CLASS_ID'];
$timetable = $this->teacher->getTimetableForSubject($subject_id);
foreach($timetable as $row) {
$result[$row['DAYOFWEEK_ID']][$row['TIME_ID']]['subject'] = $subject['SUBJECT_NAME']." (".$class['CLASS_NUMBER']." ".$class['CLASS_LETTER'].")";
$result[$row['DAYOFWEEK_ID']][$row['TIME_ID']]['time'] = date('H:i', strtotime($row['TIME_START']));
$result[$row['DAYOFWEEK_ID']][$row['TIME_ID']]['class_id'] = $class['CLASS_ID'];
$result[$row['DAYOFWEEK_ID']][$row['TIME_ID']]['subject_id'] = $subject_id;
}
}
}
$data['timetable'] = $result;
$this->load->view("teacher/scheduleview", $data);
}
function news($offset = 1) {
$search = "";
if(isset($_GET['submit'])) {
if(isset($_GET['search'])) {
$search = urldecode($_GET['search']);
$data['search'] = $search;
if ($search == "") {
redirect(base_url()."teachers/news");
} else redirect(base_url()."teachers/news?search=".$search);
}
}
if(isset($_GET['search'])) {
$search = $_GET['search'];
$data['search'] = $search;
}
// Переменная хранит число сообщений выводимых на станице
$num = 15;
$id = $this->session->userdata('id');
$config['total_rows'] = $this->teacher->totalNews($id, $search);
$config['base_url'] = base_url()."teachers/news";
$config['per_page'] = $num;
if (count($_GET) > 0) { $config['suffix'] = '?' . http_build_query($_GET, '', "&");
$config['first_url'] = $config['base_url'].'?'.http_build_query($_GET);
}
$this->pagination->initialize($config);
$query = $this->teacher->getNews($num, $offset * $num - $num, $id, $search);
$data['news'] = array();
if($query) {
$data['news'] = $query;
}
$this->load->view("teacher/newsview", $data);
}
function newsitem($id = null) {
if(isset($_POST['save'])) {
$teacher = $this->session->userdata('id');
$theme = $_POST['inputTheme'];
$text = $_POST['inputText'];
$date = $_POST['inputDate'];
if(isset($id)) {
$this->tablemodel->updateNews($id, $theme, $date, $text, $teacher);
} else {
$this->tablemodel->addNews($theme, $date, $text, $teacher);
//news push
$this->load->library('gcm');
$json = array("Тема" => $theme);
$pupils = $this->teacher->getPupilsFromAllClasses();
foreach($pupils as $pupil) {
$this->gcm->send($pupil['PUPIL_ID'], $json, "news");
}
//-----
}
redirect(base_url()."teacher/news");
} else {
if(isset($id)) {
$teacher = $this->session->userdata('id');
$news = $this->teacher->getNewsById($id, $teacher);
if(isset($news)) {
$data['date'] = $news['NEWS_TIME'];
$data['id'] = $news['NEWS_ID'];
$data['text'] = $news['NEWS_TEXT'];
$data['theme'] = $news['NEWS_THEME'];
$data['title'] = 'Редактирование новости';
$this->load->view("blankview/blanknewsview", $data);
} else {
//ошибка
$data['error'] = "Такой новости не существует. Вернитесь обратно";
$this->load->view("errorview", $data);
}
} else {
$data['title'] = 'Добавление новой новости';
$this->load->view("blankview/blanknewsview", $data);
}
}
}
function test1() {
$this->load->library('unit_test');
$test = array();
$expected_result = $this->_getJournal(null, array());
$test_name = 'Нулевой класс и пустой список учебных занятий';
$this->unit->run($test, $expected_result, $test_name);
echo $this->unit->report();
}
function test2() {
$this->load->library('unit_test');
$test = array(0 => array("pupil_id" => 26, "pupil_name" => "<NAME>", "lessons" => array (0 => array ("marks" => null, "pass" => "н"))), 1 => array ("pupil_id" => 28, "pupil_name" => "<NAME>", "lessons" => array(0 => array("marks" => array(0 => array("mark" => 5, "type" => "Сочинение")), "pass" => null))), 2 => array("pupil_id" => 2, "pupil_name" => "<NAME>", "lessons" => array(0 => array("marks" => null, "pass" => null))), 3 => array("pupil_id" => 27, "pupil_name" => "<NAME>", "lessons" => array(0 => array("marks" => null, "pass" => null))));
$expected_result = $this->_getJournal(3, $this->teacher->getLessons(1, 1, 26, ""));
$test_name = 'Входные параметры заданы верно, при этом у каждого учащегося выставлены пропуски и поставлено не более одной оценки';
$this->unit->run($test, $expected_result, $test_name);
echo $this->unit->report();
}
function test3() {
$this->load->library('unit_test');
$test = array(0 => array("pupil_id" => 26, "pupil_name" => "<NAME>"), 1 => array ("pupil_id" => 28, "pupil_name" => "<NAME>"), 2 => array("pupil_id" => 2, "pupil_name" => "<NAME>"), 3 => array("pupil_id" => 27, "pupil_name" => "<NAME>"));
$expected_result = $this->_getJournal(3, array());
$test_name = 'Задан правильный идентификатор класса, но список учебных занятий пуст';
$this->unit->run($test, $expected_result, $test_name);
echo $this->unit->report();
}
function test4() {
$this->load->library('unit_test');
$test = array();
$expected_result = $this->_getJournal(200, $this->teacher->getLessons(10, 0, 26, ""));
$test_name = 'Неправильный идентификатор класса, при этом задан список учебных занятий';
$this->unit->run($test, $expected_result, $test_name);
echo $this->unit->report();
}
function test5() {
$this->load->library('unit_test');
$test = array(0 => array("pupil_id" => 26, "pupil_name" => "<NAME>", "lessons" => array (0 => array ("marks" => null, "pass" => null))), 1 => array ("pupil_id" => 28, "pupil_name" => "<NAME>", "lessons" => array(0 => array("marks" => null, "pass" => null))), 2 => array("pupil_id" => 2, "pupil_name" => "<NAME>", "lessons" => array(0 => array("marks" => null, "pass" => null))), 3 => array("pupil_id" => 27, "pupil_name" => "<NAME>", "lessons" => array(0 => array("marks" => null, "pass" => null))));
$expected_result = $this->_getJournal(3, $this->teacher->getLessons(10, 0, 27, ""));
$test_name = 'Входные параметры заданы верно, но у учащихся отсутствуют оценки и пропуски';
$this->unit->run($test, $expected_result, $test_name);
echo $this->unit->report();
}
function test6() {
$this->load->library('unit_test');
$test = array(0 => array("pupil_id" => 26, "pupil_name" => "<NAME>", "lessons" => array (0 => array ("marks" => array (0 => array ("mark" => 5, "type" => "Изложение"), 1 => array ("mark" => 4, "type" => "Тест")), "pass" => null ) )), 1 => array ("pupil_id" => 28, "pupil_name" => "<NAME>", "lessons" => array (0 => array ("marks" => array (0 => array ("mark" => 5, "type" => "Ответ на уроке" )), "pass" => null))), 2 => array("pupil_id" => 2, "pupil_name" => "<NAME>", "lessons" => array (0 => array ("marks" => null, "pass" => "б" ))), 3 => array("pupil_id" => 27, "pupil_name" => "<NAME>", "lessons" => array(0 => array("marks" => null, "pass" => null))));
$expected_result = $this->_getJournal(3, $this->teacher->getLessons(1, 0, 26, ""));
$test_name = 'Входные параметры заданы верно, при этом у учащихся может быть несколько оценок за один урок';
$this->unit->run($test, $expected_result, $test_name);
echo $this->unit->report();
}
}
?><file_sep>/application/views/blankview/blankmessageview.php
<div class="container">
<div class="row">
<!--Написать сообщение-->
<div class="panel panel-default">
<div class="panel-heading"><?php echo $title; ?></div>
<div class="panel-body">
<form method="post">
<div class="form-horizontal">
<div class="form-group">
<label for="inputСontact" class="col-sm-1 col-md-1 control-label">Кому</label>
<div class="col-sm-11 col-md-11">
<input type="text" class="form-control" id="inputСontact" required="true" placeholder="Получатель">
<div id="responseContactError" class="red"></div>
<div id="contacts" style="margin-top: 5px; margin-left: 15px;"></div>
<div hidden="true" id="id"></div>
<input hidden="true" type="text" id="contact" name="contact"></input>
</div>
</div>
</div>
<div class="form-group">
<textarea style="resize: vertical;" class="form-control" rows="10" name ="inputText"
maxlength="1000" id ="inputText" placeholder="Текст сообщения" required="true"></textarea>
<div class="textareaFeedback"></div>
<div id="responseTextError" class="red"></div>
</div>
<div class="modal-footer" style="margin-bottom: -15px; padding-right: 0px;">
<button type="button" class="btn btn-default" onclick="javascript:history.back();" title="Отменить">Отменить</button>
<button type="submit" class="btn btn-sample" name="send" id="send" title="Отправить">Отправить</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
// $('#inputText').autoResize();
$("#inputСontact").focus(function() {
$('#inputСontact').parent().removeClass("has-error");
$("#responseContactError").text('');
$("#contacts").html('Начните вводить запрос');
});
$("#inputСontact").focusout(function() {
if($(this).val() == "") {
$("#contacts").html('');
}
if($("#contacts").html() == "Поиск не дал результатов"){
$("#contacts").html('');
$(this).val('');
}
});
$("#inputСontact").keyup(function() {
var search = $(this).val();
if(search == "") {
$("#contacts").html('Начните вводить запрос');
} else {
var base_url = '<?php echo base_url();?>';
$.ajax({
type: "POST",
url: base_url + "table/search",
data: {"search": search},
cache: false,
success: function(response){
//alert(response);
$("#contacts").html(response);
}
});
}
});
$(document).on('click', "a", function(){
$("#inputСontact").val($(this).find("#name").text());
$("#contact").val($(this).find("#id").text());
$('#contact').hide();
$("#contacts").html('');
});
$('#send').click(function() {
var base_url = '<?php echo base_url();?>';
var error = 0;
var contact = $('#inputСontact').val();
var text = $.trim($('#inputText').val());
var id = $('#contact').val();
if (contact.length == 0 || id.length == 0) {
$('#inputСontact').parent().addClass("has-error");
$("#responseContactError").text('Выберите кому написать письмо');
error++;
} else {
$('#inputСontact').parent().removeClass("has-error");
$("#responseContactError").text('');
if(text.length == 0) {
$('#inputText').parent().addClass("has-error");
$("#responseTextError").text('Начните писать сообщение');
error++;
} else {
$('#inputText').parent().removeClass("has-error");
$("#responseTextError").text('');
}
}
if (error == 0) {
/*$.ajax({
type: "POST",
url: base_url + "table/addmessage",
data: "id=" + id + "&text=" + text,
timeout: 30000,
async: false,
error: function(xhr) {
console.log('Ошибка!' + xhr.status + ' ' + xhr.statusText);
},
success: function(response) {
document.location.href = base_url + 'messages/sent';
}
});*/
} else {
return false;
}
});
});
</script>
<file_sep>/application/views/pupil/progressview.php
<?php
function setColor($mark) {
switch ($mark) {
case 5: echo '<span class="green">'.$mark.'</span>'; break;
case 4: echo '<span class="yellow">'.$mark.'</span>'; break;
case 3: echo '<span class="blue">'.$mark.'</span>'; break;
case 2: echo '<span class="red">'.$mark.'</span>'; break;
default: echo '<span class="grey">'.$mark.'</span>'; break;
}
}
?>
<div class="container">
<div class="row" style="margin-bottom: 20px;">
<div class="col-md-4">
<form method="post">
<label for="year" class="control-label"><i class="fa fa-calendar"></i> Год</label>
<select id="year" name="year" onchange="this.form.submit();" style="width: 60%;">
<?php
foreach ($years as $key => $value) {
?>
<option value="<?php echo $key?>"><?php echo $years[$key]; ?> гг.</option><?php
}
?>
</select>
</form>
</div>
<div class="col-md-8"></div>
</div>
<div class="row">
<div class="col-md-8">
<h3 class="sidebar-header">Итоговые оценки</h3>
</div>
<div class="col-md-4" >
<h5><span onclick="print();" class="a-block pull-right" title="Печать"><i class="fa fa-print"></i> Печать</span></h5>
</div>
</div>
<div class="panel panel-default">
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered numeric">
<thead>
<tr>
<th >#</th>
<th >Предметы</th>
<th >I</th>
<th >II</th>
<th >III</th>
<th>IV</th>
<th >Год</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
if (isset($result)) {
foreach ($result as $key => $value) {?>
<tr>
<td ><?php echo $i++;?></td>
<td><?php echo $result[$key]["subject"];?></td>
<!-- <td><?php echo $result[$key][1];?></td>-->
<td><?php if(isset($result[$key]["I четверть"])) setColor($result[$key]["I четверть"]); else echo "<span class='grey'>н/д</span>"?></td>
<td><?php if(isset($result[$key]["II четверть"])) setColor($result[$key]["II четверть"]); else echo "<span class='grey'>н/д</span>" ?></td>
<td><?php if(isset($result[$key]["III четверть"])) setColor($result[$key]["III четверть"]); else echo "<span class='grey'>н/д</span>" ?></td>
<td><?php if(isset($result[$key]["IV четверть"])) setColor($result[$key]["IV четверть"]); else echo "<span class='grey'>н/д</span>" ?></td>
<td><?php if(isset($result[$key]["Итоговая"])) setColor($result[$key]["Итоговая"]); else echo "<span class='grey'>н/д</span>" ?></td>
</tr>
<?php }}
?>
</tbody>
</table>
</div>
</div>
<?php
if(!isset($result)) {
?>
<div class="alert alert-info" role="alert">Данных нет</div>
<?php } ?>
</div>
<script type="text/javascript">
document.getElementById('year').value = "<?php echo $this->uri->segment(3);?>";
$("#year").select2({
minimumResultsForSearch: Infinity,
language: "ru"
});
</script>
<file_sep>/application/models/adminmodel.php
<?php
class Adminmodel extends CI_Model {
function getTeachers($limit = null, $offset = null, $search) {
$query = $this->db->query("SELECT *
FROM TEACHER
WHERE TEACHER_ID != 13 AND (IFNULL(TEACHER_NAME, '') LIKE '%$search%' OR IFNULL(TEACHER_LOGIN, '') LIKE '%$search%' )
ORDER BY TEACHER_NAME
LIMIT $offset, $limit");
return $query->result_array();
}
function totalTeachers($search) {
$query = $this->db->query("SELECT *
FROM TEACHER
WHERE TEACHER_ID != 13 AND (IFNULL(TEACHER_NAME, '') LIKE '%$search%' OR IFNULL(TEACHER_LOGIN, '') LIKE '%$search%' )");
return $query->num_rows();
}
function getSubjects($limit = null, $offset = null, $search) {
$query = $this->db->query("SELECT * FROM SUBJECT WHERE IFNULL(SUBJECT_NAME, '') LIKE '%$search%' ORDER BY SUBJECT_NAME
LIMIT $offset, $limit");
return $query->result_array();
}
function totalSubjects($search) {
$this->db->like('SUBJECT_NAME', $search);
$this->db->from('SUBJECT');
return $this->db->count_all_results();
}
function getRooms($limit = null, $offset = null, $search) {
$query = $this->db->query("SELECT * FROM ROOM WHERE IFNULL(ROOM_NAME, '') LIKE '%$search%' ORDER BY ROOM_NAME
LIMIT $offset, $limit");
return $query->result_array();
}
function totalRooms($search) {
$this->db->like('ROOM_NAME', $search);
$this->db->from('ROOM');
return $this->db->count_all_results();
}
function getAllTeachers() {
$query = $this->db->query("SELECT *
FROM TEACHER
WHERE TEACHER_ID != 13
ORDER BY TEACHER_NAME");
return $query->result_array();
}
function getTypes($limit = null, $offset = null, $search) {
$query = $this->db->query("SELECT * FROM TYPE WHERE IFNULL(TYPE_NAME, '') LIKE '%$search%' ORDER BY TYPE_NAME
LIMIT $offset, $limit");
return $query->result_array();
}
function totalTypes($search) {
$this->db->like('TYPE_NAME', $search);
$this->db->from('TYPE');
return $this->db->count_all_results();
}
function responseSubjectName($subject) {
$query = $this->db->query("SELECT COUNT(*) AS COUNT FROM SUBJECT
WHERE SUBJECT_NAME = '$subject'");
return $query->row_array();
}
function addSubject($subject) {
$this->db->set('SUBJECT_NAME', $subject);
$this->db->insert('SUBJECT');
return $this->db->insert_id();
}
function getSubjectById($id) {
$query = $this->db->query("SELECT * FROM SUBJECT
WHERE SUBJECT_ID = '$id'");
return $query->row_array();
}
function getRoomById($id) {
$query = $this->db->query("SELECT * FROM ROOM
WHERE ROOM_ID = '$id'");
return $query->row_array();
}
function getTypeById($id) {
$query = $this->db->query("SELECT * FROM TYPE
WHERE TYPE_ID = '$id'");
return $query->row_array();
}
function getNews($limit = null, $offset = null, $id, $search) {
$query = $this->db->query("SELECT *
FROM NEWS
WHERE TEACHER_ID = '$id' AND
(IFNULL(NEWS_THEME, '') LIKE '%$search%' OR IFNULL(NEWS_TEXT, '') LIKE '%$search%' OR IFNULL(NEWS_TIME, '') LIKE '%$search%')
ORDER BY NEWS_TIME DESC
LIMIT $offset, $limit");
return $query->result_array();
}
function totalNews($id, $search) {
$query = $this->db->query("SELECT * FROM NEWS WHERE TEACHER_ID = '$id' AND
(IFNULL(NEWS_THEME, '') LIKE '%$search%' OR IFNULL(NEWS_TEXT, '') LIKE '%$search%' OR IFNULL(NEWS_TIME, '') LIKE '%$search%')");
return $query->num_rows();
}
function getNewsById($id, $user) {
$query = $this->db->query("SELECT * FROM NEWS
WHERE NEWS_ID = '$id' AND TEACHER_ID = '$user'");
return $query->row_array();
}
function getClasses($limit = null, $offset = null, $search) {
$query = $this->db->query("SELECT c.CLASS_ID, c.YEAR_ID, YEAR_FINISH, YEAR_START, t.TEACHER_ID, TEACHER_NAME, CLASS_LETTER, CLASS_NUMBER,
CLASS_STATUS
FROM CLASS c LEFT JOIN YEAR y ON y.YEAR_ID = c.YEAR_ID LEFT JOIN TEACHER t ON c.TEACHER_ID = t.TEACHER_ID
WHERE CLASS_STATUS = 1 AND (IFNULL(CLASS_NUMBER, '') LIKE '%$search%' OR IFNULL(CLASS_LETTER, '') LIKE '%$search%' OR IFNULL(TEACHER_NAME, '') LIKE '%$search%'
OR IFNULL(YEAR(YEAR_START), '') LIKE '%$search%' OR IFNULL(YEAR(YEAR_FINISH), '') LIKE '%$search%')
ORDER BY CLASS_STATUS DESC, YEAR_START DESC, CLASS_NUMBER DESC, CLASS_LETTER
LIMIT $offset, $limit");
return $query->result_array();
}
function getAllClasses() {
$query = $this->db->query("SELECT * FROM CLASS c LEFT JOIN YEAR y ON y.YEAR_ID = c.YEAR_ID ORDER BY YEAR_START DESC, CLASS_NUMBER DESC, CLASS_LETTER");
return $query->result_array();
}
function totalClasses($search) {
$query = $this->db->query("SELECT *
FROM CLASS c LEFT JOIN YEAR y ON y.YEAR_ID = c.YEAR_ID LEFT JOIN TEACHER t ON c.TEACHER_ID = t.TEACHER_ID
WHERE IFNULL(CLASS_NUMBER, '') LIKE '%$search%' OR IFNULL(CLASS_LETTER, '') LIKE '%$search%' OR IFNULL(TEACHER_NAME, '') LIKE '%$search%'
OR IFNULL(YEAR(YEAR_START), '') LIKE '%$search%' OR IFNULL(YEAR(YEAR_FINISH), '') LIKE '%$search%'");
return $query->num_rows();
}
function getClassById($id) {
$query = $this->db->query("SELECT c.CLASS_ID, c.YEAR_ID, YEAR_FINISH, YEAR_START, t.TEACHER_ID, TEACHER_NAME, CLASS_LETTER, CLASS_NUMBER,
CLASS_STATUS FROM CLASS c LEFT JOIN YEAR y ON y.YEAR_ID = c.YEAR_ID LEFT JOIN TEACHER t ON c.TEACHER_ID = t.TEACHER_ID
WHERE c.CLASS_ID = '$id'");
return $query->row_array();
}
function getTeacherById($id) {
$query = $this->db->query("SELECT * FROM TEACHER
WHERE TEACHER_ID = '$id'");
return $query->row_array();
}
function getYears() {
$query = $this->db->query("SELECT * FROM YEAR ORDER BY YEAR_START DESC");
return $query->result_array();
}
function getPeriods($id) {
$query = $this->db->query("SELECT * FROM PERIOD WHERE YEAR_ID ='$id'");
return $query->result_array();
}
private function _showDate($date) {
$day = date('d', strtotime($date));
$mounth = date('m', strtotime($date));
$year = date('Y', strtotime($date));
$data = array('01'=>'января','02'=>'февраля','03'=>'марта','04'=>'апреля','05'=>'мая','06'=>'июня',
'07'=>'июля', '08'=>'августа','09'=>'сентября','10'=>'октября','11'=>'ноября','12'=>'декабря');
foreach ($data as $key=>$value) {
if ($key==$mounth) return ltrim($day, '0')." $value $year года";
}
}
function getYearsLimit($limit = null, $offset = null) {
$query = $this->db->query("SELECT * FROM YEAR ORDER BY YEAR_START DESC
LIMIT $offset, $limit");
$arr = $query->result_array();
$result = array();
$i = 0;
foreach($arr as $year) {
$year_id = $year['YEAR_ID'];
$result[$i]["id"] = $year_id;
$result[$i]["fifth"]["start"] = $this->_showDate($year['YEAR_START']);
$result[$i]["fifth"]["finish"] = $this->_showDate($year['YEAR_FINISH']);
$periods = $this->getPeriods($year_id);
foreach($periods as $period) {
if($period['PERIOD_NAME'] =="I четверть") {
$result[$i]["first"]["start"] = $this->_showDate($period['PERIOD_START']);
$result[$i]["first"]["finish"] = $this->_showDate($period['PERIOD_FINISH']);
}
if($period['PERIOD_NAME'] =="II четверть") {
$result[$i]["second"]["start"] = $this->_showDate($period['PERIOD_START']);
$result[$i]["second"]["finish"]= $this->_showDate($period['PERIOD_FINISH']);
}
if($period['PERIOD_NAME'] =="III четверть") {
$result[$i]["third"]["start"] = $this->_showDate($period['PERIOD_START']);
$result[$i]["third"]["finish"] = $this->_showDate($period['PERIOD_FINISH']);
}
if($period['PERIOD_NAME'] =="IV четверть") {
$result[$i]["forth"]["start"] = $this->_showDate($period['PERIOD_START']);
$result[$i]["forth"]["finish"] = $this->_showDate($period['PERIOD_FINISH']);
}
}
$i++;
}
return $result;
}
function totalYears() {
$this->db->from('YEAR');
return $this->db->count_all_results();
}
function getYearById($id) {
$query = $this->db->query("SELECT * FROM YEAR WHERE YEAR_ID = '$id'");
$year = $query->row_array();
if (isset($year)) {
$result = array();
$result["id"] = $year['YEAR_ID'];
$result["fifth"]["start"] = $year['YEAR_START'];
$result["fifth"]["finish"] = $year['YEAR_FINISH'];
$periods = $this->getPeriods($year['YEAR_ID']);
foreach($periods as $period) {
if($period['PERIOD_NAME'] =="I четверть") {
$result["first"]["start"] = $period['PERIOD_START'];
$result["first"]["finish"] = $period['PERIOD_FINISH'];
}
if($period['PERIOD_NAME'] =="II четверть") {
$result["second"]["start"] = $period['PERIOD_START'];
$result["second"]["finish"]= $period['PERIOD_FINISH'];
}
if($period['PERIOD_NAME'] =="III четверть") {
$result["third"]["start"] = $period['PERIOD_START'];
$result["third"]["finish"] = $period['PERIOD_FINISH'];
}
if($period['PERIOD_NAME'] =="IV четверть") {
$result["forth"]["start"] = $period['PERIOD_START'];
$result["forth"]["finish"] = $period['PERIOD_FINISH'];
}
}
return $result;
} else {
return null;
}
}
function getClassesInYear($year) {
$query = $this->db->query("SELECT * FROM CLASS WHERE YEAR_ID ='$year' ORDER BY CLASS_NUMBER, CLASS_LETTER");
return $query->result_array();
}
function getPupilsInClass($class_id) {
$query = $this->db->query("SELECT * FROM PUPILS_CLASS pc JOIN PUPIL p ON p.PUPIL_ID = pc.PUPIL_ID WHERE CLASS_ID = '$class_id' ORDER BY PUPIL_NAME");
return $query->result_array();
}
function getPeriodsInYear($year) {
$query = $this->db->query("SELECT * FROM PERIOD WHERE YEAR_ID = '$year'
ORDER BY PERIOD_NAME");
return $query->result_array();
}
function getProgressMark($class_id, $mark, $period) {
$query = $this->db->query("SELECT PROGRESS_ID, p.PUPIL_ID, PUPIL_NAME, PROGRESS_MARK, SUBJECT_NAME
FROM PROGRESS p JOIN PUPIL pu ON pu.PUPIL_ID = p.PUPIL_ID
JOIN PUPILS_CLASS pc ON pc.PUPIL_ID = pu.PUPIL_ID
JOIN SUBJECTS_CLASS sc ON p.SUBJECTS_CLASS_ID = sc.SUBJECTS_CLASS_ID
LEFT JOIN SUBJECT s ON sc.SUBJECT_ID = s.SUBJECT_ID
WHERE pc.CLASS_ID = '$class_id' AND PERIOD_ID = '$period' AND PROGRESS_MARK = '$mark'
ORDER BY PUPIL_NAME, SUBJECT_NAME");
return $query->result_array();
}
function getCountProgressMark($class_id, $period) {
$query = $this->db->query("SELECT COUNT(*) AS COUNT
FROM PROGRESS p JOIN PUPIL pu ON pu.PUPIL_ID = p.PUPIL_ID
JOIN PUPILS_CLASS pc ON pc.PUPIL_ID = pu.PUPIL_ID
WHERE CLASS_ID = '$class_id' AND PERIOD_ID = '$period'");
return $query->row_array();
}
function getPupilProgress($pupil_id, $period) {
$query = $this->db->query("SELECT PROGRESS_MARK
FROM PROGRESS
WHERE PERIOD_ID = '$period' AND PUPIL_ID = '$pupil_id'
ORDER BY PROGRESS_MARK");
return $query->result_array();
}
/*function getClassPass($year, $period, $pass) {
$query = $this->db->query("SELECT COUNT(ATTENDANCE_ID) AS PASS, pc.CLASS_ID, CLASS_NUMBER, CLASS_LETTER
FROM ATTENDANCE a JOIN PUPIL p ON p.PUPIL_ID = a.PUPIL_ID
JOIN PUPILS_CLASS pc ON pc.PUPIL_ID = p.PUPIL_ID JOIN CLASS c ON c.CLASS_ID = pc.CLASS_ID
JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID
WHERE ATTENDANCE_PASS = '$pass' AND YEAR_ID ='$year' AND
LESSON_DATE >= (SELECT PERIOD_START FROM PERIOD WHERE PERIOD_ID = '$period') AND
LESSON_DATE <= (SELECT PERIOD_FINISH FROM PERIOD WHERE PERIOD_ID = '$period')
GROUP BY pc.CLASS_ID
ORDER BY 1 DESC");
return $query->result_array();
}*/
}
?><file_sep>/application/views/teacher/scheduleview.php
<div class="container">
<h3 class="sidebar-header"><i class="fa fa-calendar"></i> Расписание</h3>
<div class="well">
<div class="row">
<?php
$days = array("Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота");
for($i = 1; $i <= count($days); $i++) :
?>
<div class="col-md-2">
<?php echo "<strong>".$days[$i-1]."</strong></br>";?>
<?php if(!array_key_exists($i, $timetable)) : ?>
<span style="font-size: 10px; "><?php echo "Занятий нет"; ?></span>
<?php else: ?>
<?php foreach ($timetable[$i] as $timetableforDay) : ?>
<span style="font-size: 10px;"><?php echo $timetableforDay['time']; ?></span>
<?php echo " "; ?>
<span style="font-size: 10px;"><?php echo $timetableforDay['subject']."</br>"; ?></span>
<?php endforeach; ?>
<?php endif; ?>
</div>
<?php endfor; ?>
</div>
</div>
</div><file_sep>/application/models/teachermodel.php
<?php
class Teachermodel extends CI_Model {
function getPupils($limit = null, $offset = null, $class, $search) {
$query = $this->db->query("SELECT *
FROM PUPIL p JOIN PUPILS_CLASS pc ON p.PUPIL_ID = pc.PUPIL_ID
WHERE CLASS_ID = '$class' AND (IFNULL(PUPIL_NAME, '') LIKE '%$search%' OR IFNULL(PUPIL_LOGIN, '') LIKE '%$search%' OR IFNULL(PUPIL_ADDRESS, '') LIKE '%$search%' OR IFNULL(PUPIL_BIRTHDAY, '') LIKE '%$search%' OR IFNULL(PUPIL_PHONE, '') LIKE '%$search%')
LIMIT $offset, $limit");
return $query->result_array();
}
function getAllPupils($class_id) {
$query = $this->db->query("SELECT *
FROM PUPIL p JOIN PUPILS_CLASS pc ON p.PUPIL_ID = pc.PUPIL_ID
WHERE CLASS_ID = '$class_id' ORDER BY PUPIL_NAME");
return $query->result_array();
}
function getPupilsFromAllClasses() {
$query = $this->db->query("SELECT *
FROM PUPIL");
return $query->result_array();
}
function totalPupils($class, $search) {
$query = $this->db->query("SELECT *
FROM PUPIL p JOIN PUPILS_CLASS pc ON p.PUPIL_ID = pc.PUPIL_ID
WHERE CLASS_ID = '$class' AND (IFNULL(PUPIL_NAME, '') LIKE '%$search%' OR IFNULL(PUPIL_LOGIN, '') LIKE '%$search%' OR IFNULL(PUPIL_ADDRESS, '') LIKE '%$search%' OR IFNULL(PUPIL_BIRTHDAY, '') LIKE '%$search%' OR IFNULL(PUPIL_PHONE, '') LIKE '%$search%')");
return $query->num_rows();
}
function getPupilById($id, $class_id) {
$query = $this->db->query("SELECT * FROM PUPIL p JOIN PUPILS_CLASS pc ON p.PUPIL_ID = pc.PUPIL_ID
WHERE p.PUPIL_ID = '$id' AND CLASS_ID = '$class_id'");
return $query->row_array();
}
function getSubjectsClass($limit = null, $offset = null, $class, $search) {
$query = $this->db->query("SELECT sc.SUBJECTS_CLASS_ID, s.SUBJECT_ID, s.SUBJECT_NAME, sc.TEACHER_ID, t.TEACHER_NAME
FROM SUBJECTS_CLASS sc LEFT JOIN SUBJECT s ON s.SUBJECT_ID = sc.SUBJECT_ID
LEFT JOIN TEACHER t ON t.TEACHER_ID = sc.TEACHER_ID
WHERE CLASS_ID = '$class' AND (IFNULL(TEACHER_NAME, '') LIKE '%$search%' OR IFNULL(SUBJECT_NAME, '') LIKE '%$search%' )
ORDER BY 5, 3
LIMIT $offset, $limit");
return $query->result_array();
}
function totalSubjectsClass($class, $search) {
$query = $this->db->query("SELECT *
FROM SUBJECTS_CLASS sc LEFT JOIN SUBJECT s ON s.SUBJECT_ID = sc.SUBJECT_ID
LEFT JOIN TEACHER t ON t.TEACHER_ID = sc.TEACHER_ID
WHERE CLASS_ID = '$class' AND (IFNULL(TEACHER_NAME, '') LIKE '%$search%' OR IFNULL(SUBJECT_NAME, '') LIKE '%$search%' )");
return $query->num_rows();
}
function getSubjectById($id, $class_id) {
$query = $this->db->query("SELECT sc.SUBJECTS_CLASS_ID, s.SUBJECT_ID, s.SUBJECT_NAME, sc.TEACHER_ID, t.TEACHER_NAME
FROM SUBJECTS_CLASS sc LEFT JOIN SUBJECT s ON s.SUBJECT_ID = sc.SUBJECT_ID
LEFT JOIN TEACHER t ON t.TEACHER_ID = sc.TEACHER_ID
WHERE sc.SUBJECTS_CLASS_ID = '$id' AND CLASS_ID = '$class_id'");
return $query->row_array();
}
function getTeachers() {
$query = $this->db->query("SELECT TEACHER_ID, TEACHER_NAME
FROM TEACHER WHERE TEACHER_ID != 13 ORDER BY TEACHER_NAME");
return $query->result_array();
}
function getSubjects() {
$query = $this->db->query("SELECT SUBJECT_NAME, SUBJECT_ID
FROM SUBJECT ORDER BY SUBJECT_NAME");
return $query->result_array();
}
function getTimetable($class_id, $day) {
$query = $this->db->query("SELECT t.TIMETABLE_ID, sc.SUBJECTS_CLASS_ID, r.ROOM_NAME, s.SUBJECT_NAME, tm.TIME_START, tm.TIME_FINISH
FROM TIMETABLE t JOIN SUBJECTS_CLASS sc ON t.SUBJECTS_CLASS_ID = sc.SUBJECTS_CLASS_ID
LEFT JOIN SUBJECT s ON s.SUBJECT_ID = sc.SUBJECT_ID
LEFT JOIN ROOM r ON r.ROOM_ID = t.ROOM_ID
JOIN TIME tm ON tm.TIME_ID = t.TIME_ID
WHERE t.DAYOFWEEK_ID = '$day' AND sc.CLASS_ID = '$class_id'
ORDER BY 5");
return $query->result_array();
}
function getTimes()
{
$query = $this->db->query("SELECT * FROM TIME ORDER BY TIME_START");
return $query->result_array();
}
function getRooms() {
$query = $this->db->query("SELECT * FROM ROOM ORDER BY ROOM_NAME");
return $query->result_array();
}
function getAllSubjectsClass($class_id) {
$query = $this->db->query("SELECT sc.SUBJECTS_CLASS_ID, s.SUBJECT_NAME
FROM SUBJECTS_CLASS sc LEFT JOIN SUBJECT s ON s.SUBJECT_ID = sc.SUBJECT_ID
WHERE CLASS_ID = '$class_id' ORDER BY 2");
return $query->result_array();
}
function getTimetableById($id, $class_id) {
$query = $this->db->query("SELECT * FROM TIMETABLE t JOIN SUBJECTS_CLASS sc ON t.SUBJECTS_CLASS_ID = sc.SUBJECTS_CLASS_ID
WHERE TIMETABLE_ID = '$id' AND CLASS_ID = '$class_id'");
return $query->row_array();
}
function getClasses($teacher) {
$query = $this->db->query("SELECT distinct sc.CLASS_ID , c.CLASS_LETTER, c.CLASS_NUMBER, c.YEAR_ID, y.YEAR_START, y.YEAR_FINISH
FROM SUBJECTS_CLASS sc JOIN CLASS c ON c.CLASS_ID = sc.CLASS_ID LEFT JOIN YEAR y ON y.YEAR_ID = c.YEAR_ID
WHERE sc.TEACHER_ID = '$teacher' ORDER BY 5 DESC, 3, 2 ");
return $query->result_array();
}
function getSubjectsForClass($class_id, $teacher) {
$query = $this->db->query("SELECT sc.SUBJECTS_CLASS_ID, s.SUBJECT_NAME
FROM SUBJECTS_CLASS sc JOIN SUBJECT s ON s.SUBJECT_ID = sc.SUBJECT_ID
WHERE CLASS_ID = '$class_id' AND TEACHER_ID = '$teacher' ORDER BY 2");
return $query->result_array();
}
function getPupilsForClass($class_id) {
$query = $this->db->query("SELECT p.PUPIL_ID, PUPIL_NAME
FROM PUPIL p JOIN PUPILS_CLASS pc ON p.PUPIL_ID = pc.PUPIL_ID
WHERE CLASS_ID = '$class_id' ORDER BY 2");
return $query->result_array();
}
/*function getPupilMarks($pupil_id, $class_id, $subject_id) {
$query = $this->db->query("SELECT PROGRESS_MARK, p.PROGRESS_ID, p.PERIOD_ID, pe.PERIOD_NAME, PERIOD_START, PERIOD_FINISH
FROM PROGRESS p JOIN PERIOD pe ON pe.PERIOD_ID = p.PERIOD_ID
WHERE p.PUPIL_ID = '$pupil_id' AND SUBJECTS_CLASS_ID = '$subject_id'
AND YEAR_ID = (SELECT YEAR_ID FROM CLASS WHERE CLASS_ID = '$class_id') ORDER BY PERIOD_NAME");
return $query->result_array();
}*/
function getPupilProgressMark($pupil_id, $subject_id, $period_id) {
$query = $this->db->query("SELECT PROGRESS_MARK AS MARK
FROM PROGRESS
WHERE PUPIL_ID = '$pupil_id' AND SUBJECTS_CLASS_ID = '$subject_id' AND PERIOD_ID = '$period_id'");
return $query->row_array();
}
function getAverageMarkForPupil($pupil, $subject, $start, $end) {
$query = $this->db->query("SELECT AVG(ACHIEVEMENT_MARK) AS MARK
FROM ACHIEVEMENT a JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID
WHERE PUPIL_ID = '$pupil' AND SUBJECTS_CLASS_ID = '$subject' AND LESSON_DATE >= '$start'
AND LESSON_DATE <= '$end'");
return $query->row_array();
}
function getLessons($limit = null, $offset = null, $subject, $search) {
$query = $this->db->query("SELECT *
FROM LESSON l JOIN TIME t ON t.TIME_ID = l.TIME_ID
WHERE SUBJECTS_CLASS_ID = '$subject' AND (IFNULL(LESSON_THEME, '') LIKE '%$search%' OR IFNULL(LESSON_HOMEWORK, '') LIKE '%$search%' OR
IFNULL(LESSON_DATE, '') LIKE '%$search%')
ORDER BY LESSON_DATE DESC, TIME_START
LIMIT $offset, $limit");
return $query->result_array();
}
function totalLessons($subject, $search) {
$query = $this->db->query("SELECT *
FROM LESSON
WHERE SUBJECTS_CLASS_ID = '$subject' AND (IFNULL(LESSON_THEME, '') LIKE '%$search%' OR IFNULL(LESSON_HOMEWORK, '') LIKE '%$search%' OR
IFNULL(LESSON_DATE, '') LIKE '%$search%')");
return $query->num_rows();
}
function getPupilMarksForLesson($pupil_id, $lesson_id) {
$query = $this->db->query("SELECT *
FROM ACHIEVEMENT a LEFT JOIN TYPE t ON t.TYPE_ID = a.TYPE_ID
WHERE LESSON_ID = '$lesson_id' AND PUPIL_ID = '$pupil_id'");
return $query->result_array();
}
function getPupilPassForLesson($pupil_id, $lesson_id) {
$query = $this->db->query("SELECT *
FROM ATTENDANCE
WHERE LESSON_ID = '$lesson_id' AND PUPIL_ID = '$pupil_id'");
return $query->row_array();
}
function checkLessonsForTeacher($subject, $id) {
$query = $this->db->query("SELECT COUNT(*) AS COUNT
FROM LESSON l JOIN SUBJECTS_CLASS sc ON sc.SUBJECTS_CLASS_ID = l.SUBJECTS_CLASS_ID
WHERE TEACHER_ID = '$id' AND l.SUBJECTS_CLASS_ID ='$subject'");
return $query->row_array();
}
/*function getFiles($lesson) {
$query = $this->db->query("SELECT *
FROM FILE
WHERE LESSON_ID = '$lesson'");
return $query->result_array();
}*/
function getLessonById($id, $subject, $user) {
$query = $this->db->query("SELECT *
FROM LESSON l JOIN SUBJECTS_CLASS sc ON l.SUBJECTS_CLASS_ID = sc.SUBJECTS_CLASS_ID
JOIN CLASS c ON c.CLASS_ID = sc.CLASS_ID JOIN TIME t ON t.TIME_ID = l.TIME_ID LEFT JOIN SUBJECT s ON s.SUBJECT_ID = sc.SUBJECTS_CLASS_ID
WHERE sc.TEACHER_ID = '$user' AND l.SUBJECTS_CLASS_ID = '$subject' AND LESSON_ID = '$id'");
return $query->row_array();
}
function getPupilMarksForSubject($pupil_id, $subject_id, $start, $finish) {
$query = $this->db->query("SELECT ACHIEVEMENT_MARK, TYPE_NAME, LESSON_DATE
FROM ACHIEVEMENT a LEFT JOIN TYPE t ON t.TYPE_ID = a.TYPE_ID
JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID
WHERE PUPIL_ID = '$pupil_id' AND SUBJECTS_CLASS_ID = '$subject_id' AND
LESSON_DATE >= '$start' AND LESSON_DATE <= '$finish' ORDER BY LESSON_DATE DESC");
return $query->result_array();
}
function getPupilPassForSubject($pupil_id, $subject_id, $start, $finish) {
$query = $this->db->query("SELECT ATTENDANCE_PASS, COUNT(*) AS COUNT
FROM ATTENDANCE a JOIN LESSON l ON l.LESSON_ID = a.LESSON_ID
WHERE PUPIL_ID = '$pupil_id' AND SUBJECTS_CLASS_ID = '$subject_id' AND LESSON_DATE >= '$start'
AND LESSON_DATE <= '$finish'
GROUP BY ATTENDANCE_PASS");
return $query->result_array();
}
function getBorders($class_id) {
$query = $this->db->query("SELECT * FROM PERIOD
WHERE YEAR_ID = (SELECT YEAR_ID FROM CLASS WHERE CLASS_ID = '$class_id')
ORDER BY PERIOD_NAME");
return $query->result_array();
}
function getPupilProgressForSubject($pupil_id, $subject_id, $period) {
$query = $this->db->query("SELECT PROGRESS_MARK FROM PROGRESS
WHERE PUPIL_ID = '$pupil_id' AND SUBJECTS_CLASS_ID = '$subject_id' AND PERIOD_ID = '$period'");
return $query->row_array();
}
function getAverageForSubject($class_id, $subject_id, $period) {
$query = $this->db->query("SELECT AVG(PROGRESS_MARK) AS MARK
FROM PROGRESS pr JOIN PUPIL p ON p.PUPIL_ID = pr.PUPIL_ID JOIN PUPILS_CLASS pc ON pc.PUPIL_ID = p.PUPIL_ID
WHERE SUBJECTS_CLASS_ID = '$subject_id' AND PERIOD_ID = '$period' AND CLASS_ID = '$class_id'");
return $query->row_array();
}
function getClassBySubject($subject) {
$query = $this->db->query("SELECT CLASS_ID FROM SUBJECTS_CLASS WHERE SUBJECTS_CLASS_ID = '$subject'");
return $query->row_array();
}
function getTypes() {
$query = $this->db->query("SELECT * FROM TYPE ORDER BY TYPE_NAME");
return $query->result_array();
}
function getCountProgressMark($subject_id, $period_id, $mark) {
$query = $this->db->query("SELECT COUNT(PROGRESS_MARK) AS COUNT FROM PROGRESS
WHERE PERIOD_ID = '$period_id' AND PROGRESS_MARK = '$mark' AND SUBJECTS_CLASS_ID = '$subject_id'");
return $query->row_array();
}
function getSubjectInfo($subject, $id) {
$query = $this->db->query("SELECT SUBJECT_NAME, sc.SUBJECT_ID, sc.CLASS_ID, CLASS_LETTER, CLASS_NUMBER,
YEAR(YEAR_START) AS YEAR_START, YEAR(YEAR_FINISH) AS YEAR_FINISH
FROM SUBJECTS_CLASS sc LEFT JOIN SUBJECT s ON s.SUBJECT_ID = sc.SUBJECT_ID JOIN CLASS c ON c.CLASS_ID = sc.CLASS_ID
JOIN YEAR y ON y.YEAR_ID = c.YEAR_ID
WHERE SUBJECTS_CLASS_ID = '$subject' AND sc.TEACHER_ID = '$id'");
return $query->row_array();
}
function getClassesByDate($date, $id) {
$query = $this->db->query("SELECT distinct c.CLASS_ID, CLASS_NUMBER, CLASS_LETTER
FROM CLASS c JOIN YEAR y ON c.YEAR_ID = y.YEAR_ID JOIN SUBJECTS_CLASS sc ON sc.CLASS_ID =c.CLASS_ID
WHERE '$date' >= YEAR_START AND '$date' <= YEAR_FINISH AND sc.TEACHER_ID = '$id'");
return $query->result_array();
}
function getTimetableForSubject($subject) {
$query = $this->db->query("SELECT *
FROM TIMETABLE t JOIN TIME tm ON t.TIME_ID = tm.TIME_ID
WHERE SUBJECTS_CLASS_ID = '$subject'");
return $query->result_array();
}
function getNews($limit = null, $offset = null, $id, $search) {
$query = $this->db->query("SELECT *
FROM NEWS
WHERE TEACHER_ID = '$id' AND
(IFNULL(NEWS_THEME, '') LIKE '%$search%' OR IFNULL(NEWS_TEXT, '') LIKE '%$search%' OR IFNULL(NEWS_TIME, '') LIKE '%$search%')
ORDER BY NEWS_TIME DESC
LIMIT $offset, $limit");
return $query->result_array();
}
function totalNews($id, $search) {
$query = $this->db->query("SELECT * FROM NEWS WHERE TEACHER_ID = '$id' AND
(IFNULL(NEWS_THEME, '') LIKE '%$search%' OR IFNULL(NEWS_TEXT, '') LIKE '%$search%' OR IFNULL(NEWS_TIME, '') LIKE '%$search%')");
return $query->num_rows();
}
function getNewsById($id, $user) {
$query = $this->db->query("SELECT * FROM NEWS
WHERE NEWS_ID = '$id' AND TEACHER_ID = '$user'");
return $query->row_array();
}
function getPupilNoteForLesson($pupil_id, $lesson_id) {
$query = $this->db->query("SELECT *
FROM NOTE
WHERE LESSON_ID = '$lesson_id' AND PUPIL_ID = '$pupil_id'");
return $query->row_array();
}
}
?><file_sep>/application/controllers/Table.php
<?php
class Table extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('tablemodel', 'table');
}
//$table - из какой таблицы удаляем, $id - id записи
function del($table, $id) {
switch($table) {
case 'subject': {
$this->table->deleteSubject($id);
break;
}
case 'room': {
$this->table->deleteRoom($id);
break;
}
case 'type': {
$this->table->deleteType($id);
break;
}
case 'news': {
$this->table->deleteNews($id);
break;
}
case 'class': {
$this->table->deleteClass($id);
break;
}
case 'teacher': {
$this->table->deleteTeacher($id);
break;
}
case 'year': {
$this->table->deleteYear($id);
break;
}
case 'pupil': {
$this->table->deletePupil($id);
break;
}
case 'subjectsclass': {
$this->table->deleteSubjectsClass($id);
break;
}
case 'timetable': {
$this->table->deleteTimetable($id);
break;
}
case 'message': {
$role = $this->session->userdata('role');
switch($role) {
case 4: {
$this->table->deleteMessage($id, 'PUPIL', 'TEACHER');
break;
}
case 1: case 3: {
$this->table->deleteMessage($id, 'TEACHER', 'PUPIL');
break;
}
}
break;
}
case 'lesson': {
$this->table->deleteLesson($id);
break;
}
case 'mark': {
$this->table->deleteMark($id);
break;
}
case 'conversation': {
$user = $this->session->userdata('id');
$role = $this->session->userdata('role');
switch($role) {
case 4: {
$this->table->deleteConversation($user, $id, 'PUPIL', 'TEACHER');
break;
}
case 1: case 3: {
$this->table->deleteConversation($user, $id, 'TEACHER', 'PUPIL');
break;
}
}
break;
}
}
}
//проверяет, есть ли уже такой общий предмет
function responsesubject() {
$answer = $this->table->responseSubjectName($_POST['name'], $_POST['id'])['COUNT'];
if($answer > 0) {
echo true;
}
else echo false;
}
/*//добавлем новый общий предмет
function addsubject() {
$name = $_POST['name'];
$this->table->addSubject($name);
}
//обновляем общий предмет
function updatesubject() {
$name = $_POST['name'];
$id = $_POST['id'];
$this->table->updateSubject($name, $id);
}*/
//проверяет, есть ли уже такой кабинет
function responseroom() {
$answer = $this->table->responseRoomName($_POST['name'], $_POST['id'])['COUNT'];
if($answer > 0) {
echo true;
}
else echo false;
}
/*//добавлем новый кабинет
function addroom() {
$name = $_POST['name'];
$this->table->addRoom($name);
}
//обновляем кабинет
function updateroom() {
$name = $_POST['name'];
$id = $_POST['id'];
$this->table->updateRoom($name, $id);
}*/
//проверяет, есть ли уже такой тип оценки
function responsetype() {
$answer = $this->table->responseTypeName($_POST['name'], $_POST['id'])['COUNT'];
if($answer > 0) {
echo true;
}
else echo false;
}
/*//добавлем новый тип оценки
function addtype() {
$name = $_POST['name'];
$this->table->addType($name);
}
//обновляем тип оценки
function updatetype() {
$name = $_POST['name'];
$id = $_POST['id'];
$this->table->updateType($name, $id);
}*/
/*//добавлем новость
function addnews() {
$admin = $this->session->userdata('id');
$theme = $_POST['theme'];
$text = $_POST['text'];
$date = $_POST['date'];
$this->table->addNews($theme, $date, $text, $admin);
}
//обновляем новость
function updatenews() {
$admin = $this->session->userdata('id');
$theme = $_POST['theme'];
$text = $_POST['text'];
$date = $_POST['date'];
$id = $_POST['id'];
$this->table->updateNews($id, $theme, $date, $text, $admin);
}*/
//проверяет, есть ли уже такой класс
function responseclass() {
$answer = $this->table->responseClass($_POST['id'], $_POST['number'], $_POST['letter'], $_POST['year'], $_POST['status'])['COUNT'];
if($answer > 0) {
echo true;
}
else echo false;
}
/*//добавлем класс
function addclass() {
$number = $_POST['number'];
$letter = $_POST['letter'];
$year = $_POST['year'];
$status = $_POST['status'];
$teacher = $_POST['teacher'];
$previous = $_POST['previous'];
$this->table->addClass($number, $letter, $year, $status, $teacher, $previous);
}
//обновляем класс
function updateclass() {
$number = $_POST['number'];
$letter = $_POST['letter'];
$year = $_POST['year'];
$status = $_POST['status'];
$teacher = $_POST['teacher'];
$id = $_POST['id'];
$previous = $_POST['previous'];
$this->table->updateClass($id, $number, $letter, $year, $status, $teacher, $previous);
}*/
//проверяет, есть ли уже такой логин
function responseteacherlogin() {
$answer = $this->table->responseTeacherLogin($_POST['id'], $_POST['login'])['COUNT'];
if($answer > 0) {
echo true;
}
else echo false;
}
/*//добавлем учителя
function addteacher() {
$name = $_POST['name'];
$password = $_POST['<PASSWORD>'];
$login = $_POST['login'];
$status = $_POST['status'];
$this->table->addTeacher($name, $password, $login, $status, md5($password));
}
//обновляем учителя
function updateteacher() {
$name = $_POST['name'];
$password = $_POST['<PASSWORD>'];
$login = $_POST['login'];
$status = $_POST['status'];
$id = $_POST['id'];
$this->table->updateTeacher($id, $name, $password, $login, $status, md5($password));
}*/
function responseclassteacher() {
$year = $_POST['year'];
$teacher = $_POST['teacher'];
$id = $_POST['id'];
$answer = $this->table->responseClassTeacher($id, $year, $teacher)['COUNT'];
if($answer > 0) {
echo true;
}
else echo false;
}
/*function addyear() {
$year_start = $_POST['year_start'];
$year_finish = $_POST['year_finish'];
$first_start = $_POST['first_start'];
$first_finish = $_POST['first_finish'];
$second_start = $_POST['second_start'];
$second_finish = $_POST['second_finish'];
$third_start = $_POST['third_start'];
$third_finish = $_POST['third_finish'];
$forth_start = $_POST['forth_start'];
$forth_finish = $_POST['forth_finish'];
$this->table->addYearAndPeriods($year_start, $year_finish,
$first_start, $first_finish, $second_start, $second_finish, $third_start,$third_finish, $forth_start, $forth_finish);
}
function updateyear() {
$year_start = $_POST['year_start'];
$year_finish = $_POST['year_finish'];
$first_start = $_POST['first_start'];
$first_finish = $_POST['first_finish'];
$second_start = $_POST['second_start'];
$second_finish = $_POST['second_finish'];
$third_start = $_POST['third_start'];
$third_finish = $_POST['third_finish'];
$forth_start = $_POST['forth_start'];
$forth_finish = $_POST['forth_finish'];
$id = $_POST['id'];
$this->table->updateYearAndPeriods($id, $year_start, $year_finish,
$first_start, $first_finish, $second_start, $second_finish, $third_start,$third_finish, $forth_start, $forth_finish);
}*/
function responseclassprevious() {
$previous = $_POST['previous'];
$answer = $this->table->responseClassPrevious($previous)['COUNT'];
if($answer > 0) {
echo true;
}
else echo false;
}
//проверяет, есть ли уже такой логин
function responsepupillogin() {
$answer = $this->table->responsePupilLogin($_POST['id'], $_POST['login'])['COUNT'];
if($answer > 0) {
echo true;
}
else echo false;
}
/*//добавлем учащегося
function addpupil() {
$name = $_POST['name'];
$password = $_POST['<PASSWORD>'];
$login = $_POST['login'];
$status = $_POST['status'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$birthday = $_POST['birthday'];
$class_id = $this->session->userdata('class_id');
$this->table->addPupil($name, $password, $login, $status, md5($password), $address, $phone, $birthday, $class_id);
}
//обновляем учащегося
function updatepupil() {
$name = $_POST['name'];
$password = $_POST['<PASSWORD>'];
$login = $_POST['login'];
$status = $_POST['status'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$id = $_POST['id'];
$birthday = $_POST['birthday'];
$this->table->updatePupil($id, $name, $password, $login, $status, md5($password), $address, $phone, $birthday);
}*/
function responsesubjectsclass() {
$class_id = $this->session->userdata('class_id');
$answer = $this->table->responseSubjectsClass($_POST['id'], $_POST['teacher'], $_POST['subject'], $class_id)['COUNT'];
if($answer > 0) {
echo true;
}
else echo false;
}
/*function addsubjectsclass() {
$teacher = $_POST['teacher'];
$subject = $_POST['subject'];
$class_id = $this->session->userdata('class_id');
$this->table->addSubjectsClass($teacher, $subject, $class_id);
}
function updatesubjectsclass() {
$teacher = $_POST['teacher'];
$subject = $_POST['subject'];
$id = $_POST['id'];
$class_id = $this->session->userdata('class_id');
$this->table->updateSubjectsClass($id, $teacher, $subject, $class_id);
}*/
function responsetimetable() {
$class_id = $this->session->userdata('class_id');
$answer = $this->table->responseTimetable($_POST['id'], $_POST['time'], $_POST['day'], $class_id)['COUNT'];
if($answer > 0) {
echo true;
}
else echo false;
}
/*function addtimetable() {
$time = $_POST['time'];
$subject = $_POST['subject'];
$day = $_POST['day'];
$room = $_POST['room'];
$this->table->addTimetable($time, $subject, $day, $room);
}
function updatetimetable() {
$time = $_POST['time'];
$subject = $_POST['subject'];
$day = $_POST['day'];
$room = $_POST['room'];
$id = $_POST['id'];
$this->table->updateTimetable($id, $time, $subject, $day, $room);
}*/
function responseyear() {
$answer = $this->table->responseYear($_POST['id'], date('Y', strtotime($_POST['yearstart'])), date('Y', strtotime($_POST['yearfinish'])))['COUNT'];
if($answer > 0) {
echo true;
}
else echo false;
}
function search() {
$search = $_POST['search'];
$role = $this->session->userdata('role');
switch($role) {
case 4: {
$contacts = $this->table->getSearchTeachers($search);
break;
}
case 1: case 3: {
$contacts = $this->table->getSearchPupils($search);
break;
}
}
if(count($contacts) == 0) {
echo "Поиск не дал результатов";
} else {
foreach($contacts as $row) {
echo "<a href='#'><span id='name'>".$row['NAME']."</span><span hidden id='id'>".$row['ID']."</span></a></br>";
}
}
}
function addmessage() {
$role = $this->session->userdata('role');
$user = $this->session->userdata('id');
$text = $_POST['text'];
$id = $_POST['id'];
date_default_timezone_set('Europe/Moscow');
$date = date('Y-m-d H:i:s');
switch($role) {
case 4: {
$this->table->addMessage($user, $id, $text, $date, 'PUPIL', 'TEACHER');
break;
}
case 1: case 3: {
$message_id = $this->table->addMessage($user, $id, $text, $date, 'TEACHER', 'PUPIL');
$json = array("ТекстСообщения" => $text, "ДатаСообщения" => $date, "УчительИд" => $user, "Ид" => $message_id, "ТипСообщения" => 1, "Прочтено" => 0);
$this->load->library('gcm');
$this->gcm->send($id, $json, "message");
break;
}
}
/*$subject = $this->table->getSubjectNameByLessonId($lesson_id)['SUBJECT_NAME'];
$type = $this->table->getTypeById($type)['TYPE_NAME'];
$message = "Новая оценка ".$mark." "."(".$type.")"." по предмету ".$subject;
$result = $this->table->getLessonById($lesson_id);
$lesson_date = $result['LESSON_DATE'];
$time_id = $result['TIME_ID'];
$day_of_week = date('N', strtotime($lesson_date));
$json = array("Текст" => $message, "День" => $lesson_date, "ВремяИд" => $time_id, "ДеньНедели" => $day_of_week);*/
}
function readmessage($id) {
$role = $this->session->userdata('role');
switch($role) {
case 4: {
$this->table->readMessage($id, 'PUPIL', 'TEACHER');
break;
}
case 1: case 3: {
$this->table->readMessage($id, 'TEACHER', 'PUPIL');
break;
}
}
}
function readconversation($id) {
$user = $this->session->userdata('id');
$role = $this->session->userdata('role');
switch($role) {
case 4: {
$this->table->readConversation($user, $id, 'PUPIL', 'TEACHER');
break;
}
case 1: case 3: {
$this->table->readConversation($user, $id, 'TEACHER', 'PUPIL');
break;
}
}
}
function changeprogress() {
$mark = $_POST['mark'];
$pupil_id = $_POST['pupil_id'];
$subject_id = $_POST['subject_id'];
$period = $_POST['period'];
$class_id = $_POST['class_id'];
$this->table->changeProgress($pupil_id, $subject_id, $period, $class_id, $mark);
$this->load->library('gcm');
if($mark != "") {
$progress = $this->table->getPupilProgressMark($pupil_id, $subject_id, $period, $class_id, $mark);
$json = array("ПредметИд" => $subject_id, "Оценка" => $mark, "ПериодИд" => $progress['PERIOD_ID'], "Ид" => $progress['PROGRESS_ID']);
$this->gcm->send($pupil_id, $json, "progress");
} else {
}
}
function responselesson() {
/*$answer = $this->table->responseLesson($_POST['id'], $_POST['date'], $_POST['time'], $_POST['subject'])['COUNT'];
if($answer > 0) {
echo true;
}
else echo false;*/
$id = $_POST['id'];
$date = $_POST['date'];
$subject = $_POST['subject'];
$time = $_POST['time'];
echo $this->table->responseLesson($id, $date, $time, $subject);
}
function changeattendance() {
$pass = $_POST['pass'];
$pupil_id = $_POST['pupil_id'];
$lesson_id = $_POST['lesson_id'];
$attendance_id = $_POST['attendance'];
$this->table->changeAttendance($pupil_id, $lesson_id, $attendance_id, $pass);
}
function changelessonstatus() {
$lesson_id = $_POST['lesson_id'];
$status = $_POST['status'];
$this->table->changeLessonStatus($lesson_id, $status);
}
function changemark() {
$mark = $_POST['mark'];
$pupil_id = $_POST['pupil_id'];
$lesson_id = $_POST['lesson_id'];
$achievement_id = $_POST['achievement'];
$type = $_POST['type'];
$this->table->changeAchievement($pupil_id, $lesson_id, $achievement_id, $mark, $type);
if(!(isset($achievement_id) && $achievement_id != "")) {
$subject = $this->table->getSubjectNameByLessonId($lesson_id)['SUBJECT_NAME'];
$type = $this->table->getTypeById($type)['TYPE_NAME'];
$message = "Новая оценка ".$mark." "."(".$type.")"." по предмету ".$subject;
$result = $this->table->getLessonById($lesson_id);
$lesson_date = $result['LESSON_DATE'];
$time_id = $result['TIME_ID'];
$day_of_week = date('N', strtotime($lesson_date));
$json = array("Текст" => $message, "День" => $lesson_date, "ВремяИд" => $time_id, "ДеньНедели" => $day_of_week);
$this->load->library('gcm');
$this->gcm->send($pupil_id, $json, "lesson");
}
}
function changenote() {
$note = $_POST['note'];
$pupil_id = $_POST['pupil_id'];
$lesson_id = $_POST['lesson_id'];
$note_id = $_POST['note_id'];
$this->table->changeNote($pupil_id, $lesson_id, $note_id, $note);
}
}
?><file_sep>/application/models/messagemodel.php
<?php
class Messagemodel extends CI_Model {
function getFolderMessages($limit = null, $offset = null, $id, $type, $search, $from, $to) {
$query = $this->db->query("SELECT ".$from."S_MESSAGE_ID AS USER_MESSAGE_ID, pm.MESSAGE_ID, MESSAGE_DATE, MESSAGE_TEXT, MESSAGE_READ, ".$to."_NAME AS USER_NAME
FROM ".$from."S_MESSAGE pm JOIN MESSAGE m ON m.MESSAGE_ID = pm.MESSAGE_ID LEFT JOIN ".$to." t ON t.".$to."_ID = pm.".$to."_ID
WHERE ".$from."_ID = '$id' AND MESSAGE_FOLDER = '$type' AND (IFNULL(MESSAGE_TEXT, '') LIKE '%$search%' OR IFNULL(".$to."_NAME, '') LIKE '%$search%' )
ORDER BY MESSAGE_DATE DESC LIMIT $offset, $limit");
return $query->result_array();
}
function totalFolderMessages($id, $type, $search, $from, $to) {
$query = $this->db->query("SELECT *
FROM ".$from."S_MESSAGE pm JOIN MESSAGE m ON m.MESSAGE_ID = pm.MESSAGE_ID LEFT JOIN ".$to." t ON t.".$to."_ID = pm.".$to."_ID
WHERE ".$from."_ID = '$id' AND MESSAGE_FOLDER = '$type' AND (IFNULL(MESSAGE_TEXT, '') LIKE '%$search%' OR IFNULL(".$to."_NAME, '') LIKE '%$search%' )");
return $query->num_rows();
}
function totalUnreadPupilMessages($id, $type) {
$query = $this->db->query("SELECT COUNT(PUPILS_MESSAGE_ID) AS COUNT FROM PUPILS_MESSAGE
WHERE PUPIL_ID = '$id' AND MESSAGE_READ = 0 AND MESSAGE_FOLDER = '$type'");
$arr = $query->row_array();
$count = $arr['COUNT'];
return $count;
}
function totalUnreadTeacherMessages($id, $type) {
$query = $this->db->query("SELECT COUNT(TEACHERS_MESSAGE_ID) AS COUNT FROM TEACHERS_MESSAGE
WHERE TEACHER_ID = '$id' AND MESSAGE_READ = 0 AND MESSAGE_FOLDER = '$type'");
$arr = $query->row_array();
$count = $arr['COUNT'];
return $count;
}
function totalMessages($id, $from, $to, $search) {
$query = $this->db->query("SELECT COUNT(*)
FROM ".$from."S_MESSAGE pm JOIN MESSAGE m ON m.MESSAGE_ID = pm.MESSAGE_ID LEFT JOIN ".$to." t ON t.".$to."_ID = pm.".$to."_ID
WHERE ".$from."_ID = '$id' AND IFNULL(".$to."_NAME, '') LIKE '%$search%'");
return $query->num_rows();
}
function getMessages($limit = null, $offset = null, $id, $from, $to, $search) {
$query = $this->db->query("SELECT ".$to."_NAME AS USER_NAME, COUNT(pm.MESSAGE_ID) AS COUNT, pm.".$to."_ID AS USER_ID,
MAX(MESSAGE_DATE) AS MAX
FROM ".$from."S_MESSAGE pm JOIN MESSAGE m ON m.MESSAGE_ID = pm.MESSAGE_ID LEFT JOIN ".$to." t ON t.".$to."_ID = pm.".$to."_ID
WHERE ".$from."_ID = '$id' AND IFNULL(".$to."_NAME, '') LIKE '%$search%'
GROUP BY pm.".$to."_ID ORDER BY MAX(MESSAGE_DATE) DESC
LIMIT $offset, $limit");
return $query->result_array();
}
function getNewMessages($user, $id, $from, $to) {
$query = $this->db->query("SELECT *
FROM ".$from."S_MESSAGE
WHERE ".$from."_ID = '$id' AND ".$to."_ID = '$user' AND MESSAGE_READ = 0 AND MESSAGE_FOLDER = 1");
return $query->result_array();
}
function getConversationMessages($limit = null, $offset = null, $id, $user, $search, $from, $to) {
$query = $this->db->query("SELECT ".$from."S_MESSAGE_ID AS USER_MESSAGE_ID, pm.MESSAGE_ID, MESSAGE_DATE, MESSAGE_TEXT,
MESSAGE_READ, ".$to."_NAME AS USER_NAME, MESSAGE_FOLDER, pm.".$to."_ID AS USER_ID
FROM ".$from."S_MESSAGE pm JOIN MESSAGE m ON m.MESSAGE_ID = pm.MESSAGE_ID LEFT JOIN ".$to." t ON t.".$to."_ID = pm.".$to."_ID
WHERE ".$from."_ID = '$id' AND IFNULL(MESSAGE_TEXT, '') LIKE '%$search%' AND pm.".$to."_ID = '$user'
ORDER BY MESSAGE_DATE DESC LIMIT $offset, $limit");
return $query->result_array();
}
function totalConversationMessages($id, $user, $search, $from, $to) {
$query = $this->db->query("SELECT *
FROM ".$from."S_MESSAGE pm JOIN MESSAGE m ON m.MESSAGE_ID = pm.MESSAGE_ID
WHERE ".$from."_ID = '$id' AND IFNULL(MESSAGE_TEXT, '') LIKE '%$search%' AND pm.".$to."_ID = '$user'");
return $query->num_rows();
}
function getUserById($id, $from, $to) {
$query = $this->db->query("SELECT ".$to."_NAME AS USER_NAME
FROM ".$from."S_MESSAGE pm JOIN ".$to." p ON p.".$to."_ID = pm.".$to."_ID
WHERE pm.".$to."_ID = '$id'");
return $query->row_array();
}
}
?> | 9638117705cd395ced14b21f6f985092950bf42b | [
"Markdown",
"SQL",
"JavaScript",
"PHP"
] | 62 | PHP | zavsc/eschool | e1c81aa44c4fe7a819cfb2919d8f53e1bc9a9143 | fede0a49983b4f6c8ce1fb869a67036622811a16 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faHeart, faUser } from '@fortawesome/free-solid-svg-icons';
import './Post.scss';
import TagList from './TagList/TagList';
import config from '../../config';
class Post extends Component {
formatDate(dateStr) {
const date = new Date(dateStr);
const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
return months[date.getMonth()] + ' ' + date.getDate();
}
render() {
return (
<div className="col-sm-12 col-md-4">
<article className="Post">
<header>
<div className="Post-date">
{this.formatDate(this.props.created)}
</div>
<div className="Post-user">
<FontAwesomeIcon icon={faUser} />
</div>
</header>
<div className="Post-image">
<img src={config.apiUrl + '/' + this.props.image} title={this.props.title} />
</div>
<div className="Post-actions">
<div>{this.props.likes} <FontAwesomeIcon icon={faHeart} /></div>
</div>
<div className="Post-content">
<h1 className="Post-title">{this.props.title}</h1>
<TagList tags={this.props.tags} />
</div>
</article>
</div>
);
}
}
export default Post; | acb7558240c94e497964309326746ada299ba794 | [
"JavaScript"
] | 1 | JavaScript | zingeryuval/instagram-ui-1 | 670254c0729e1b1ff00d311c5138c61e50b856e8 | c3b6ef43f3f50457cdff684ad8ffc56c9003fa10 |
refs/heads/master | <file_sep>import math
import pandas_datareader as web
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
# get quote
df = web.DataReader('AAPL', data_source='yahoo', start='2012-01-01', end='2020-12-04')
# show the data
df
# get the count of rows and columns in data set
df.shape
# visualize the closing price history
plt.figure(figsize=(16, 8))
plt.title('Closing Price History')
plt.plot(df['Close'])
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
plt.show()
# new df w/only close column
data = df.filter(['Close'])
# convert df to a numpy array
ds = data.values
# get or compute the # of rows to train LSTM model
training_data_length = math.ceil(len(ds) * .8)
training_data_length
# scale the data (its good practice)
scaler = MinMaxScaler(feature_range=(0, 1))
scale_data = scaler.fit_transform(ds)
# scaler.fit_transform = computes min/max values to be used for sclaing and transforms data based on the values
# range 0-1 inclusive (could be 0 -> could be 1)
scale_data
# Create the training dataset
# create the scaled training dataset
# scale_data[0:training_data_length] where 0 is the index
train_data = scale_data[0:training_data_length, :]
# split the data into X_train and y_train datasets
X_train = [] # independent training features
y_train = [] # dependent or target variable
for i in range(60, len(train_data)):
X_train.append(train_data[i - 60:i, 0])
y_train.append(train_data[i, 0])
if i <= 61:
print(X_train)
print(y_train)
print()
# convert x_train and y_train to numpy arrays
# to use for training lstm model
X_train, y_train = np.array(X_train), np.array(y_train)
# reshape the x_train dataset
# lstm expects 3d and x_train is only 2d right now
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
# build the LSTM model
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
model.add(LSTM(50, return_sequences=False))
model.add(Dense(25))
model.add(Dense(1))
# compile the model
# epochs # of iterations in deep learning
model.compile(optimizer='adam', loss='mean_squared_error')
# train the model
model.fit(X_train, y_train, batch_size=1, epochs=3)
# create the testing dataset
# create a new array containing scaled values from index 1543 to end
# this will be the scaled testing dataset
test_data = scale_data[training_data_length - 60:, :]
# create the datasets x_test and y_test
X_test = []
y_test = ds[training_data_length:, :] # contains 60 first values not scaled
# create test set
for i in range(60, len(test_data)):
X_test.append(test_data[i - 60:i, 0])
# convert data into a numpy array
X_test = np.array(X_test)
# reshape the data, we need it 3d
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
# get model predicted prive values
predictions = model.predict(X_test)
predictions = scaler.inverse_transform(predictions)
# evaluate model = RMSE get the root mean squared error RMSE(how accurate model predicts res, lower indicates better fit)
rmse = np.sqrt(np.mean(predictions - y_test) ** 2)
rmse
# plot the data
training_data = data[0:training_data_length]
validation = data[training_data_length:]
validation['Predictions'] = predictions
# visualize the data
plt.figure(figsize=(18, 8))
plt.title('Model')
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
plt.plot(training_data['Close'])
plt.plot(validation[['Close', 'Predictions']])
plt.legend(['Training', 'Validation', 'Predictions'], loc='lower right')
plt.show()
# show the valid or actual prices and predicted prices (compared)
validation
# Finally, lets try and predict the Apple stock price for a given (date)
apple_quote = web.DataReader('AAPL', data_source='yahoo', start='2012-01-01', end='2020-12-03')
# create new df
new_df = apple_quote.filter(['Close'])
# get last 60 day closing price values and convert df to array
last_60_days = new_df[-60:].values
# scale between 0 & 1
last_60_days_scaled = scaler.transform(last_60_days)
# create an empty list
X_test = []
# append last_60_days_scaled to test
X_test.append(last_60_days_scaled)
# convert _X_test to numpy array
X_test = np.array(X_test) # to use in lstm model
# reshape to 3d
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
predicted_price = model.predict(X_test)
# undo scaling
predicted_price = scaler.inverse_transform(predicted_price)
"""
Print the prediction. This is for one(1) day after the above(apple_quote) end date
eg. if predicting a stock price for 12/04/2020 the date above would end on 12/03/2020
Once that date passed, you would then compare, if possible, to 12/04/2020 to check the prediction against actual closing stock price
"""
print(predicted_price)
# Check actual price (if available)
apple_quote_2 = web.DataReader('AAPL', data_source='yahoo', start='2020-12-04', end='2020-12-04')
# print actual price
print(apple_quote_2['Close'])
| 4089b4a6b056842c523b138612aa06b0a12dab02 | [
"Python"
] | 1 | Python | alexandercarson/StockPricePrediction_ML_AI_Python | 9367d62e92b644f04b8d054e26df2321e0a2cd4a | 8b7b097c0d7088c8be145c9a36e95735c71ffbdc |
refs/heads/master | <repo_name>Junaid522/Nitrx<file_sep>/stories/admin.py
from django.contrib import admin
from stories import models
# Register your models here.
admin.site.register(models.Story)
admin.site.register(models.StoryView)
admin.site.register(models.StoryRating)
<file_sep>/posts/serializers.py
import urllib.parse
from django.db.models import Avg, Sum
from django.template.loader import render_to_string
from rest_framework import serializers
from accounts.models import User, FollowUser
from accounts.serializers import UserSerializer, FollowUserSerializer, FollowingUserSerializer
from accounts.services import UserManagement
from common.commmon_services import convert_time
from common.qrcode_generator import Qrcode
from notifications.models import Notification
from posts.models import (Post, PostComment, PostRating, PostLike, BlacklistPost, PostView, PostMaterial, PostSave,
CommentRating)
class PathFileField(serializers.FileField):
# TODO: Make django/nginx respect HOST header and get rid of this class
def to_representation(self, value):
if not value:
return None
if not getattr(value, 'url', None):
# If the file has not been saved it may not have a URL.
return None
return urllib.parse.unquote(value.url)
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
exclude = ('is_valid', 'media_files',)
# def to_internal_value(self, data):
# image = data['image']
# format, imgstr = image.split(';base64,')
# ext = format.split('/')[-1]
# data['image'] = ContentFile(base64.b64decode(imgstr),
# name='{}.{}'.format(''.join(random.choices(string.ascii_uppercase +
# string.digits, k=6)), ext))
# return super().to_internal_value(data)
def create(self, validated_data):
post = Post.objects.create(**validated_data)
post.save()
return Qrcode().save_post_qrcode(post)
class PostMaterialSerializer(serializers.ModelSerializer):
class Meta:
model = PostMaterial
exclude = ('is_valid',)
class PostViewSerializer(serializers.ModelSerializer):
class Meta:
model = PostView
exclude = ('is_valid',)
def create(self, data):
return PostView.objects.update_or_create(post=data['post'], user_view=data['user_view'])
class PostDetailSerializer(serializers.ModelSerializer):
comments = serializers.SerializerMethodField()
likes = serializers.SerializerMethodField()
rates = serializers.SerializerMethodField()
views = serializers.SerializerMethodField()
materials = serializers.SerializerMethodField()
creator_details = serializers.SerializerMethodField()
liked = serializers.SerializerMethodField()
follow = serializers.SerializerMethodField()
rated = serializers.SerializerMethodField()
rated_value = serializers.SerializerMethodField()
is_post_saved = serializers.SerializerMethodField()
comments_rating_average = serializers.SerializerMethodField()
rating_count = serializers.SerializerMethodField()
class Meta:
model = Post
exclude = ('is_valid',)
def get_rating_count(self, obj):
post_rating = PostRating.objects.filter(post=obj)
if post_rating:
average = post_rating.aggregate(Sum('rating'))
if average.get('rating__sum'):
return average.get('rating__sum')
return None
def get_comments(self, obj):
if self.context.get('user_id'):
return PostCommentSerializer(PostComment.objects.filter(is_valid=True, post=obj, parent__isnull=True),
context={'user_id': self.context.get('user_id')}, many=True).data
return PostCommentSerializer(PostComment.objects.filter(is_valid=True, post=obj), many=True).data
def get_comments_rating_average(self, obj):
comment_rating = CommentRating.objects.filter(comment__post=obj)
if comment_rating:
average = comment_rating.aggregate(Avg('rating'))
if average.get('rating__avg'):
return average.get('rating__avg')
return None
def get_likes(self, obj):
return PostLikeSerializer(PostLike.objects.filter(is_valid=True, post=obj), many=True).data
def get_rates(self, obj):
return PostRateSerializer(PostRating.objects.filter(is_valid=True, post=obj), many=True).data
def get_views(self, obj):
return PostViewSerializer(PostView.objects.filter(is_valid=True, post=obj), many=True).data
def get_materials(self, obj):
return PostMaterialSerializer(obj.media_files.all(), many=True).data
def get_creator_details(self, obj):
return UserSerializer(User.objects.filter(id=obj.creator.id).first()).data
def get_liked(self, obj):
if self.context.get('user_id'):
is_liked = PostLike.objects.filter(is_valid=True, post=obj,
user_liked__id=self.context.get('user_id')).first()
if is_liked:
return True
return False
def get_rated(self, obj):
if self.context.get('user_id'):
is_rated = PostRating.objects.filter(is_valid=True, post=obj,
user_rated__id=self.context.get('user_id')).first()
if is_rated:
return True
return False
def get_rated_value(self, obj):
if self.context.get('user_id'):
is_rated = PostRating.objects.filter(is_valid=True, post=obj,
user_rated__id=self.context.get('user_id')).first()
if is_rated:
return is_rated.rating
return 0
def get_follow(self, obj):
if self.context.get('user_id'):
is_followed = FollowUser.objects.filter(is_valid=True, user__id=self.context.get('user_id'),
follow__id=obj.creator.id).first()
if is_followed:
return True
return False
def get_is_post_saved(self, obj):
if self.context.get('user_id'):
is_saved = PostSave.objects.filter(is_valid=True, user__id=self.context.get('user_id'),
post__id=obj.id).first()
if is_saved:
return True
return False
class OtherUserProfileSerializer(serializers.ModelSerializer):
posts = serializers.SerializerMethodField()
followings = serializers.SerializerMethodField()
followers = serializers.SerializerMethodField()
follow = serializers.SerializerMethodField()
class Meta:
model = User
fields = ('id', 'username', 'first_name', 'last_name', 'email', 'image_url', 'bio', 'gender', 'phone_number',
'date_of_birth', 'country', 'search_privacy', 'posts', 'followings', 'followers', 'follow',
'profile_qr')
def get_posts(self, obj):
return PostDetailSerializer(Post.objects.filter(is_valid=True, creator__id=obj.id), many=True).data
def get_followings(self, obj):
if self.context.get('user_id'):
return FollowingUserSerializer((UserManagement().get_followings(obj)),
context={'user_id': self.context.get('user_id')}, many=True).data
return FollowingUserSerializer((UserManagement().get_followings(obj)), many=True).data
def get_followers(self, obj):
if self.context.get('user_id'):
return FollowUserSerializer(UserManagement().get_followers(obj),
context={'user_id': self.context.get('user_id')}, many=True).data
return FollowUserSerializer(UserManagement().get_followers(obj), many=True).data
def get_follow(self, obj):
if self.context.get('user_id'):
is_followed = FollowUser.objects.filter(is_valid=True, user__id=self.context.get('user_id'),
follow__id=obj.id).first()
if is_followed:
return True
return False
class PostCommentSerializer(serializers.ModelSerializer):
content = serializers.SerializerMethodField()
profile_image = serializers.SerializerMethodField()
user_detail = serializers.SerializerMethodField()
created_at = serializers.SerializerMethodField()
child_comments = serializers.SerializerMethodField()
rates = serializers.SerializerMethodField()
rated = serializers.SerializerMethodField()
rating_count = serializers.SerializerMethodField()
class Meta:
model = PostComment
fields = (
'id', 'post', 'user_commented', 'comment', 'content', 'profile_image', 'user_detail', 'created_at',
'child_comments', 'rates', 'rated', 'rating_count', 'parent')
def get_rated(self, obj):
if self.context.get('user_id'):
is_rated = CommentRating.objects.filter(is_valid=True, comment=obj,
user_rated__id=self.context.get('user_id')).first()
if is_rated:
return True
return False
def get_rates(self, obj):
return CommentRateSerializer(CommentRating.objects.filter(is_valid=True, comment=obj), many=True).data
def get_rating_count(self, obj):
commment_rating = CommentRating.objects.filter(is_valid=True, comment=obj)
if commment_rating:
average = commment_rating.aggregate(Sum('rating'))
if average.get('rating__sum'):
return average.get('rating__sum')
return None
def get_content(self, obj):
type = self.context.get('type')
if type:
if type == Notification.REPLY_COMMENT:
return render_to_string('post_comment_reply.html', {'instance': obj})
elif type == Notification.MENTION_COMMENT:
return render_to_string('post_comment_mention.html', {'instance': obj})
return render_to_string('post_comment.html', {'instance': obj})
def get_child_comments(self, obj):
if self.context.get('user_id'):
return PostCommentChildSerializer(PostComment.objects.filter(parent=obj),
context={'user_id': self.context.get('user_id')},
many=True).data
return PostCommentChildSerializer(PostComment.objects.filter(parent=obj), many=True).data
def get_profile_image(self, obj):
return obj.user_commented.image_url
def get_user_detail(self, obj):
return UserSerializer(User.objects.filter(id=obj.user_commented.id).first()).data
def get_created_at(self, obj):
return convert_time(obj.created_at)
class PostCommentChildSerializer(serializers.ModelSerializer):
content = serializers.SerializerMethodField()
profile_image = serializers.SerializerMethodField()
user_detail = serializers.SerializerMethodField()
created_at = serializers.SerializerMethodField()
rates = serializers.SerializerMethodField()
rated = serializers.SerializerMethodField()
rating_count = serializers.SerializerMethodField()
class Meta:
model = PostComment
fields = (
'id', 'post', 'user_commented', 'comment', 'content', 'profile_image', 'user_detail', 'created_at', 'rates',
'rated', 'rating_count')
def get_rating_count(self, obj):
commment_rating = CommentRating.objects.filter(is_valid=True, comment=obj)
if commment_rating:
average = commment_rating.aggregate(Sum('rating'))
if average.get('rating__sum'):
return average.get('rating__sum')
return None
def get_content(self, obj):
return render_to_string('post_comment.html', {'instance': obj})
def get_profile_image(self, obj):
return obj.user_commented.image_url
def get_user_detail(self, obj):
return UserSerializer(User.objects.filter(id=obj.user_commented.id).first()).data
def get_created_at(self, obj):
return convert_time(obj.created_at)
def get_rated(self, obj):
if self.context.get('user_id'):
is_rated = CommentRating.objects.filter(is_valid=True, comment=obj,
user_rated__id=self.context.get('user_id')).first()
if is_rated:
return True
return False
def get_rates(self, obj):
return CommentRateSerializer(CommentRating.objects.filter(is_valid=True, comment=obj), many=True).data
class PostRateSerializer(serializers.ModelSerializer):
profile_image = serializers.SerializerMethodField()
user_detail = serializers.SerializerMethodField()
created_at = serializers.SerializerMethodField()
content = serializers.SerializerMethodField()
class Meta:
model = PostRating
exclude = ('is_valid', 'updated_at',)
def get_profile_image(self, obj):
return obj.user_rated.image_url
def get_content(self, obj):
return render_to_string('post_rate.html', {'instance': obj})
def get_user_detail(self, obj):
return UserSerializer(User.objects.filter(id=obj.user_rated.id).first()).data
def get_created_at(self, obj):
return convert_time(obj.created_at)
class CommentRateSerializer(serializers.ModelSerializer):
profile_image = serializers.SerializerMethodField()
user_detail = serializers.SerializerMethodField()
created_at = serializers.SerializerMethodField()
content = serializers.SerializerMethodField()
post = serializers.SerializerMethodField()
class Meta:
model = CommentRating
exclude = ('is_valid', 'updated_at',)
def get_profile_image(self, obj):
return obj.user_rated.image_url
def get_post(self, obj):
return obj.comment.post.id
def get_content(self, obj):
return render_to_string('comment_rate.html', {'instance': obj})
def get_user_detail(self, obj):
return UserSerializer(User.objects.filter(id=obj.user_rated.id).first()).data
def get_created_at(self, obj):
return convert_time(obj.created_at)
class PostLikeSerializer(serializers.ModelSerializer):
content = serializers.SerializerMethodField()
profile_image = serializers.SerializerMethodField()
class Meta:
model = PostLike
fields = ('post', 'user_liked', 'content', 'profile_image')
def get_content(self, obj):
return render_to_string('post_like.html', {'instance': obj})
def get_profile_image(self, obj):
return obj.user_liked.image_url
class BlackListPostSerializer(serializers.ModelSerializer):
class Meta:
model = BlacklistPost
exclude = ('is_valid',)
class PostSaveSerializer(serializers.ModelSerializer):
class Meta:
model = PostSave
exclude = ('is_valid',)
post_detail = serializers.SerializerMethodField()
def get_post_detail(self, obj):
return PostDetailSerializer(Post.objects.filter(id=obj.post.id).first(), context={'user_id': obj.user.id}).data
<file_sep>/requirements.txt
aioredis==1.3.1
amqp==5.0.5
asgi-redis==1.4.3
asgiref==3.3.1
async-timeout==3.0.1
attrs==20.3.0
autobahn==20.12.3
Automat==20.2.0
Babel==2.8.0
billiard==3.6.3.0
celery==5.0.5
certifi==2020.6.20
cffi==1.14.3
channels==3.0.2
channels-redis==3.2.0
chardet==3.0.4
click==7.1.2
click-didyoumean==0.0.3
click-plugins==1.1.1
click-repl==0.1.6
constantly==15.1.0
coreapi==2.3.3
coreschema==0.0.4
cryptography==3.2.1
daphne==3.0.1
Django==3.1.1
django-cors-headers==3.5.0
django-countries==6.1.3
django-group-by==0.3.1
django-phonenumber-field==3.0.1
django-phonenumbers==1.0.1
django-rest-passwordreset==1.1.0
djangorestframework==3.11.1
djangorestframework-jwt==1.11.0
drf-jwt-2fa==0.3.0
drf-yasg==1.20.0
hiredis==1.1.0
hyperlink==20.0.1
idna==2.10
image==1.5.33
importlib-metadata==3.7.3
incremental==17.5.0
inflection==0.5.1
itypes==1.2.0
Jinja2==2.11.2
kombu==5.0.2
MarkupSafe==1.1.1
msgpack==1.0.2
msgpack-python==0.5.6
ndg-httpsclient==0.5.1
packaging==20.4
phonenumbers==8.12.8
Pillow==8.0.1
prompt-toolkit==3.0.18
pusher==3.0.0
pyasn1==0.4.8
pyasn1-modules==0.2.8
pycparser==2.20
PyHamcrest==2.0.2
PyJWT==1.7.1
PyNaCl==1.4.0
pyOpenSSL==19.1.0
pyparsing==2.4.7
pypng==0.0.20
PyQRCode==1.2.1
python-dotenv==0.14.0
pytz==2020.1
qrcode==6.1
redis==3.2.0
requests==2.24.0
ruamel.yaml==0.16.12
ruamel.yaml.clib==0.2.2
service-identity==18.1.0
six==1.15.0
sqlparse==0.3.1
Twisted==20.3.0
txaio==20.12.1
typing-extensions==3.7.4.3
uritemplate==3.0.1
urllib3==1.25.11
vine==5.0.0
wcwidth==0.2.5
zipp==3.4.1
zope.interface==5.2.0
<file_sep>/RestProject/channels_middleware.py
from urllib.parse import parse_qs
from rest_framework_jwt.utils import jwt_decode_handler
from asgiref.sync import sync_to_async, async_to_sync
from accounts.models import User
class TokenAuthMiddleware:
"""
Custom token auth middleware
"""
def __init__(self, inner):
# Store the ASGI application we were passed
self.inner = inner
async def __call__(self, scope, receive, send):
# Close old database connections to prevent usage of timed out connections
# close_old_connections()
# Get the token
token = parse_qs(scope["query_string"].decode("utf8"))["token"][0]
other_username = parse_qs(scope["query_string"].decode("utf8"))["user"][0]
# Try to authenticate the user
# try:
# This will automatically validate the token and raise an error if token is invalid
# UntypedToken(token)
# except (InvalidToken, TokenError) as e:
# Token is invalid
# print(e)
# return None
# else:
# Then token is valid, decode it
decoded_data = await sync_to_async(jwt_decode_handler)(token)
print(decoded_data)
# Will return a dictionary like -
# {
# "token_type": "access",
# "exp": 1568770772,
# "jti": "5c15e80d65b04c20ad34d77b6703251b",
# "user_id": 6
# }
# Get the user using ID
# user = await sync_to_async(get_user_model().objects.get(id=decoded_data["user_id"]))
# scope['user'] = user
# Return the inner application directly and let it run everything else
scope['user_id'] = decoded_data['user_id']
get_user = await sync_to_async(_get_user)(other_username)
scope['other_user'] = get_user.id
return await self.inner(scope, receive, send)
def _get_user(username):
return User.objects.filter(username=username)[0]
<file_sep>/stories/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('api/story/create', views.StoryCreateView.as_view(), name='story-create'),
path('api/story/view', views.ViewStoryView.as_view(), name='story-view'),
path('api/story/details', views.StoryDetailView.as_view(), name='story-detail'),
path('api/story/delete', views.StoryDeleteView.as_view(), name='story-delete'),
path('api/story/all', views.AllStoriesView.as_view(), name='all-stories'),
path('api/story/rate', views.StoryRateView.as_view(), name='story-rate'),
]
<file_sep>/chat_app/migrations/0006_auto_20210130_1655.py
# Generated by Django 3.1.1 on 2021-01-30 16:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('chat_app', '0005_messagemodel_read_receipt'),
]
operations = [
migrations.AlterField(
model_name='messagemodel',
name='read_receipt',
field=models.BooleanField(default=False),
),
]
<file_sep>/categories/migrations/0001_initial.py
# Generated by Django 3.1.1 on 2020-09-10 06:02
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_valid', models.BooleanField(default=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=255)),
('image', models.FileField(max_length=254, upload_to='static/categories_images')),
],
options={
'abstract': False,
},
),
]
<file_sep>/RestProject/urls.py
"""RestProject URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth.decorators import login_required
from django.urls import path
from rest_framework.routers import DefaultRouter
from rest_framework_jwt.views import obtain_jwt_token
from rest_framework_jwt.views import refresh_jwt_token
from rest_framework_jwt.views import verify_jwt_token
from rest_framework import permissions
from drf_yasg.views import get_schema_view
from drf_yasg import openapi
from chat_app.api import MessageModelViewSet, UserModelViewSet, MessageModelPostViewSet
schema_view = get_schema_view(
openapi.Info(
title="NITRX API",
default_version='v1',
description="",
terms_of_service="https://www.google.com/policies/terms/",
contact=openapi.Contact(email="<EMAIL>"),
license=openapi.License(name="BSD License"),
),
public=True,
permission_classes=(permissions.AllowAny,),
)
router = DefaultRouter()
router.register(r'message', MessageModelViewSet)
router.register(r'send_message', MessageModelPostViewSet)
router.register(r'user', UserModelViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('auth-jwt/', obtain_jwt_token),
path('auth-jwt-refresh/', refresh_jwt_token),
path('auth-jwt-verify/', verify_jwt_token),
path('', include('accounts.urls')),
path('', include('categories.urls')),
path('', include('posts.urls')),
path('', include('stories.urls')),
path('', include('notifications.urls')),
path('dashboard/', include('dashboard.urls')),
url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'),
url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
url(r'^redoc/$', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'),
# path('chat/api/v1/', include(router.urls)),
path('api/v1/', include(router.urls)),
# path('chat/', include('chat_app.urls')),
]
<file_sep>/posts/migrations/0001_initial.py
# Generated by Django 3.1.1 on 2020-09-10 06:02
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('categories', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_valid', models.BooleanField(default=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('title', models.CharField(max_length=255)),
('keywords', models.CharField(blank=True, max_length=20, null=True)),
('image', models.FileField(max_length=254, upload_to='static/post_images')),
('description', models.CharField(blank=True, max_length=255, null=True)),
('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='categories.category')),
('creator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='PostRating',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_valid', models.BooleanField(default=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('rating', models.CharField(choices=[('ONE', '1 Nitrx'), ('TWO', '2 Nitrx'), ('THREE', '3 Nitrx'), ('THREE', '4 Nitrx'), ('THREE', '5 Nitrx')], max_length=255)),
('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='posts.post')),
('user_rated', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='PostLike',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_valid', models.BooleanField(default=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='posts.post')),
('user_liked', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='PostComment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_valid', models.BooleanField(default=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('comment', models.CharField(max_length=255)),
('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='posts.post')),
('user_commented', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
<file_sep>/notifications/models.py
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
# Create your models here.
from accounts.models import User
from common.models import BaseModel
class Notification(BaseModel):
MENTION_COMMENT = 'mention_comment'
FOLLOWING = 'following'
LIKE_POST = 'like_post'
COMMENT_POST = 'comment_post'
RATE_COMMENT = 'rate_comment'
REPLY_COMMENT = 'reply_comment'
RATE_POST = 'rate_post'
RATE_STORY = 'rate_story'
CHAT_STARTED = 'chat_started'
GROUP_CHAT_ADD = 'group_chat_add'
NOTIFICATION_TYPE = (
(MENTION_COMMENT, 'Mention Comment'),
(FOLLOWING, 'Following'),
(LIKE_POST, 'Like Post'),
(COMMENT_POST, 'Comment Post'),
(RATE_STORY, 'Rate Story'),
(RATE_POST, 'Rate Post'),
(RATE_COMMENT, 'Rate Comment'),
(REPLY_COMMENT, 'Reply Comment'),
(CHAT_STARTED, 'Chat Started'),
(GROUP_CHAT_ADD, 'Group Chat Add'),
)
actor = models.ForeignKey(User, on_delete=models.CASCADE, )
notification_type = models.CharField(max_length=250, choices=NOTIFICATION_TYPE)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, blank=True, null=True)
object_id = models.PositiveIntegerField(blank=True, null=True)
content_object = GenericForeignKey('content_type', 'object_id')
read = models.BooleanField(default=False)
def __str__(self):
return '%s %s' % (self.actor.username, self.read)
class Meta:
ordering = ['-id', ]
<file_sep>/dashboard/services.py
from django.contrib.sessions.models import Session
from django.utils import timezone
from accounts.models import User
class DashboardService(object):
def get_logged_in_users(self):
active_sessions = Session.objects.filter(expire_date__gte=timezone.now())
user_id_list = []
for session in active_sessions:
data = session.get_decoded()
user_id_list.append(data.get('_auth_user_id', None))
return User.objects.filter(id__in=user_id_list).count()
<file_sep>/chat_app/migrations/0003_auto_20201230_1411.py
# Generated by Django 3.1.1 on 2020-12-30 14:11
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('chat_app', '0002_auto_20201230_1348'),
]
operations = [
migrations.AddField(
model_name='thread',
name='recipient',
field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, related_name='thread_to_user', to='accounts.user', verbose_name='recipient'),
preserve_default=False,
),
migrations.AddField(
model_name='thread',
name='user',
field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, related_name='thread_from_user', to='accounts.user', verbose_name='user'),
preserve_default=False,
),
]
<file_sep>/common/migrations/0003_auto_20201222_1332.py
# Generated by Django 3.1.1 on 2020-12-22 13:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('common', '0002_auto_20201222_1121'),
]
operations = [
migrations.RenameField(
model_name='appname',
old_name='name',
new_name='host_name',
),
migrations.AlterField(
model_name='appname',
name='type',
field=models.CharField(choices=[('DEVELOPMENT', 'DEVELOPMENT'), ('PRODUCTION', 'PRODUCTION')], default='DEVELOPMENT', max_length=255, unique=True),
),
]
<file_sep>/posts/migrations/0007_blacklistpost_report.py
# Generated by Django 3.1.1 on 2020-12-02 11:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0006_postsave'),
]
operations = [
migrations.AddField(
model_name='blacklistpost',
name='report',
field=models.CharField(choices=[('SPAM', 'SPAM'), ('INAPPROPRIATE', 'INAPPROPRIATE')], default='SPAM', max_length=25),
),
]
<file_sep>/common/commmon_services.py
from datetime import datetime
def convert_time(created_at):
time = (datetime.today()).replace(tzinfo=None) - (created_at).replace(tzinfo=None)
if time.days:
if time.days > 365:
return f'{int(time.days / 365)} years ago'
elif time.days > 30:
return f'{int(time.days / 30)} months ago'
elif time.days > 7:
return f'{int(time.days / 7)} months ago'
return f'{time.days} days ago'
else:
new_time = time.seconds % (24 * 3600)
hour = new_time // 3600
if hour:
return f'{int(hour)} hours ago'
new_time %= 3600
minutes = new_time // 60
if minutes:
return f'{int(minutes)} minutes ago'
elif time.seconds:
return f'{int(time.seconds)} seconds ago'
def convert_time_mhr(created_at):
time = (datetime.today()).replace(tzinfo=None) - (created_at).replace(tzinfo=None)
if time.days:
if time.days > 365:
return f'{int(time.days / 365)} years ago'
elif time.days > 30:
return f'{int(time.days / 30)} months ago'
elif time.days > 7:
return f'{int(time.days / 7)} months ago'
return f'{time.days} days ago'
else:
new_time = time.seconds % (24 * 3600)
hour = new_time // 3600
if hour:
return f'{int(hour)}hr ago'
new_time %= 3600
minutes = new_time // 60
if minutes:
return f'{int(minutes)}m ago'
elif time.seconds:
return f'{int(time.seconds)}s ago'
<file_sep>/RestProject/routing.py
from channels.routing import ProtocolTypeRouter, URLRouter
# from channels.auth import AuthMiddlewareStack
from django.urls import path
from RestProject.channels_middleware import TokenAuthMiddleware
from chat_app.consumers import ChatConsumer
application = ProtocolTypeRouter({
"websocket": TokenAuthMiddleware(
URLRouter([
path('ws/', ChatConsumer.as_asgi())
]
)
),
})
<file_sep>/posts/models.py
from django.db import models
from accounts.models import User
from categories.models import Category
from common.models import BaseModel
class PostMaterial(BaseModel):
IMAGE = 'IMAGE'
VIDEO = 'VIDEO'
POST_CHOICES = (
(VIDEO, 'VIDEO'),
(IMAGE, 'IMAGE'),
)
url = models.TextField(null=True, blank=True)
post_type = models.CharField(max_length=20, choices=POST_CHOICES, default=IMAGE)
def __str__(self):
return self.post_type + "-" + self.url
class Post(BaseModel):
title = models.CharField(max_length=255)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
keywords = models.CharField(max_length=20, blank=True, null=True)
image = models.FileField(upload_to='static/post_images', max_length=254, null=True, blank=True)
description = models.CharField(max_length=255, blank=True, null=True)
creator = models.ForeignKey(User, on_delete=models.CASCADE)
media_files = models.ManyToManyField(PostMaterial)
website = models.CharField(max_length=255, null=True, blank=True)
post_qr = models.FileField(upload_to='static/post_qr_codes/', blank=True, null=True)
def __str__(self):
return self.title
class PostLike(BaseModel):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
user_liked = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.post.title
class PostImpressions(BaseModel):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
user_impressed = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.post.title
class PostView(BaseModel):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
user_view = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.post.title
class PostComment(BaseModel):
parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
user_commented = models.ForeignKey(User, on_delete=models.CASCADE)
comment = models.TextField()
mentioned_users = models.ManyToManyField(User, null=True, blank=True, related_name="mentioned_users")
def __str__(self):
return self.post.title
class CommentRating(BaseModel):
ONE = '1'
THREE = '3'
FIVE = '5'
SEVEN = '7'
TEN = '10'
RATE_TYPE = (
(ONE, 1),
(THREE, 3),
(FIVE, 5),
(SEVEN, 7),
(TEN, 10),
)
comment = models.ForeignKey(PostComment, on_delete=models.CASCADE)
user_rated = models.ForeignKey(User, on_delete=models.CASCADE)
rating = models.IntegerField(choices=RATE_TYPE)
def __str__(self):
return self.comment.post.title
class PostSave(BaseModel):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.post.title
class PostRating(BaseModel):
ONE = '1'
THREE = '3'
FIVE = '5'
SEVEN = '7'
TEN = '10'
RATE_TYPE = (
(ONE, 1),
(THREE, 3),
(FIVE, 5),
(SEVEN, 7),
(TEN, 10),
)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
user_rated = models.ForeignKey(User, on_delete=models.CASCADE)
rating = models.IntegerField(choices=RATE_TYPE)
def __str__(self):
return self.post.title
class BlacklistPost(BaseModel):
SPAM = 'SPAM'
INAPPROPRIATE = 'INAPPROPRIATE'
REPORT_TYPE = (
(SPAM, "SPAM"),
(INAPPROPRIATE, "INAPPROPRIATE"),
)
user_reported = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
report = models.CharField(choices=REPORT_TYPE, default=SPAM, max_length=25)
def __str__(self):
return self.post.title
<file_sep>/notifications/services.py
import datetime
from django.core.paginator import Paginator
from django.utils import timezone
from RestProject.constants import NOTIFICATION_CHUNK
from notifications.models import Notification
class Notifications(object):
def create_notification(self, actor, notification_type, instance=None):
notification_instance = Notification(actor=actor, notification_type=notification_type, content_object=instance)
notification_instance.save()
def get_notification(self, actor, notification_type, instance=None):
return Notification.objects.filter(actor=actor, notification_type=notification_type, object_id=instance).first()
def mark_read(self, notification_id, actor_id):
notification = Notification.objects.filter(id=notification_id, actor__id=actor_id).first()
if notification:
notification.read = True
notification.save()
return notification
def mark_all_read(self, actor_id):
return Notification.objects.filter(actor__id=actor_id).update(read=True)
def delete_notification(self, actor_id, notification_id):
return Notification.objects.filter(actor__id=actor_id, id=notification_id).update(is_valid=False)
def get_notifications(self, filter_dict):
notifications = Notification.objects.filter(**filter_dict).exclude(object_id__isnull=True)[:NOTIFICATION_CHUNK]
return [notification for notification in notifications if notification.content_object]
def get_chunk_of_notifications(self, filter_dict, page):
notifications = Notification.objects.filter(**filter_dict).exclude(object_id__isnull=True)
paginator = Paginator(notifications, NOTIFICATION_CHUNK)
notifications = paginator.page(page)
return [notification for notification in notifications if notification.content_object]
def get_notification_time(self, created_at):
time = (timezone.make_aware(datetime.datetime.now())) - created_at
day = time.seconds // (24 * 3600)
time = time.seconds % (24 * 3600)
hour = time // 3600
time %= 3600
minutes = time // 60
time %= 60
seconds = time
if day:
return "{}d ago".format(day)
elif hour:
return "{}h ago".format(hour)
elif minutes:
return "{}m ago".format(minutes)
return "{}s ago".format(seconds)
<file_sep>/common/qrcode_generator.py
from io import BytesIO
import qrcode
from django.conf import settings
from django.core.files.uploadedfile import InMemoryUploadedFile
from common.models import AppName
class Qrcode(object):
def generate_url(self, obj, type):
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=4,
)
app = AppName.objects.filter(type=AppName.PRODUCTION).first()
name = app.host_name
if settings.DEBUG:
app = AppName.objects.filter(type=AppName.DEVELOPMENT).first()
name = app.host_name
data = f"{name}/post_detail?id={obj.id}"
if type == 'user':
data = f"{name}/my_profile?id={obj.id}"
qr.add_data(data)
qr.make(fit=True)
qrcode_img = qr.make_image()
buffer = BytesIO()
qrcode_img.save(buffer, format='PNG')
filename = f'{str(obj.id)}.png'
filebuffer = InMemoryUploadedFile(buffer, None, filename, 'image/png', 100, None)
return filename, filebuffer, qrcode_img
def save_user_qrcode(self, user):
filename, file_buffer, qrcode_img = self.generate_url(user, 'user')
user.profile_qr.save(filename, file_buffer)
user.save()
qrcode_img.close()
return user
def save_post_qrcode(self, post):
filename, file_buffer, qrcode_img = self.generate_url(post, 'post')
post.post_qr.save(filename, file_buffer)
post.save()
qrcode_img.close()
return post
<file_sep>/posts/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('api/post/trending', views.TrendingPostsView.as_view(), name='post-trending'),
path('api/post/create', views.PostCreateView.as_view(), name='post-create'),
path('api/post/view', views.PostViewView.as_view(), name='post-create'),
path('api/post/delete', views.PostDeleteView.as_view(), name='post-delete'),
path('api/post/save', views.PostSaveView.as_view(), name='post-save'),
path('api/post/detail', views.PostDetailView.as_view(), name='post-detail'),
path('api/post/all', views.AllPostsView.as_view(), name='post-all'),
path('api/post/comment', views.PostCommentView.as_view(), name='post-comment'),
path('api/post/comment/rate', views.CommentRateView.as_view(), name='rate-comment'),
path('api/post/rate', views.PostRateView.as_view(), name='post-rate'),
path('api/post/like', views.PostLikeView.as_view(), name='post-like'),
path('api/post/report', views.PostReportView.as_view(), name='post-report'),
path('api/post/by_category', views.PostByCategoryView.as_view(), name='post-by-category'),
path('api/post/my_followings_posts', views.MyFollowingPostsView.as_view(), name='post-report'),
path('api/post/search', views.SearchPostsView.as_view(), name='search-posts'),
path('api/post/all_saved', views.AllSavedPostsView.as_view(), name='saved-posts'),
path('api/post/other_users_detail', views.OtherUserPostsAndProfile.as_view(), name='user-profile-all-details'),
]
<file_sep>/posts/migrations/0004_auto_20201123_0738.py
# Generated by Django 3.1.1 on 2020-11-23 07:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0003_postview'),
]
operations = [
migrations.AlterField(
model_name='postrating',
name='rating',
field=models.IntegerField(choices=[('1', 1), ('3', 3), ('5', 5), ('7', 7), ('10', 10)]),
),
]
<file_sep>/README.md
# Nitrx
Create .env file in root directory of project and add variables like
EMAIL_HOST=smtp.gmail.com
EMAIL_HOST_USER=<email_address>
EMAIL_HOST_PASSWORD=<email_password>
Running server
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
<file_sep>/accounts/serializers.py
from django.template.loader import render_to_string
from django_countries.serializer_fields import CountryField
from django_countries.serializers import CountryFieldMixin
from rest_framework import serializers
from accounts.models import (User, FollowUser, ReportUser, BlockUser, AccountInformation, WebsiteVerification)
from common.qrcode_generator import Qrcode
class UserSerializer(serializers.ModelSerializer):
follow = serializers.SerializerMethodField()
class Meta:
model = User
fields = (
'id', 'username', 'first_name', 'last_name', 'age', 'email', 'bio', 'gender', 'phone_number', 'profile_qr',
'date_of_birth', 'country', 'search_privacy', 'follow', 'email_verified', 'otp_enabled', 'image_url')
# def to_internal_value(self, data):
# if data.get('image'):
# image = data['image']
# format, imgstr = image.split(';base64,')
# ext = format.split('/')[-1]
# data['image'] = ContentFile(base64.b64decode(imgstr),
# name='{}.{}'.format(''.join(random.choices(string.ascii_uppercase +
# string.digits, k=6)), ext))
# return super().to_internal_value(data)
def get_follow(self, obj):
if self.context.get('user_id'):
is_followed = FollowUser.objects.filter(is_valid=True, user__id=self.context.get('user_id'),
follow__id=obj.id).first()
if is_followed:
return True
return False
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
user.save()
return Qrcode().save_user_qrcode(user)
class AccountInformationSerializer(CountryFieldMixin, serializers.ModelSerializer):
country = CountryField(country_dict=True)
gender = serializers.SerializerMethodField()
email_verified = serializers.SerializerMethodField()
otp_enabled = serializers.SerializerMethodField()
class Meta:
model = AccountInformation
fields = (
'country', 'site_visit', 'partner_info', 'search_privacy', 'store_contacts', 'gender', 'email_verified',
'otp_enabled')
def get_gender(self, obj):
return obj.user.gender
def get_email_verified(self, obj):
return obj.user.email_verified
def get_otp_enabled(self, obj):
return obj.user.otp_enabled
class WebsiteVerificationSerializer(serializers.ModelSerializer):
class Meta:
model = WebsiteVerification
exclude = ('is_valid',)
class FollowsUserSerializer(serializers.ModelSerializer):
class Meta:
model = FollowUser
fields = '__all__'
class FollowUserSerializer(serializers.ModelSerializer):
class Meta:
model = FollowUser
fields = (
'user', 'follow', 'content', 'profile_image', 'first_name', 'last_name', 'username', 'follow', 'user_id')
content = serializers.SerializerMethodField()
profile_image = serializers.SerializerMethodField()
first_name = serializers.SerializerMethodField()
last_name = serializers.SerializerMethodField()
follow = serializers.SerializerMethodField()
username = serializers.SerializerMethodField()
user_id = serializers.SerializerMethodField()
def get_content(self, obj):
return render_to_string('follow_user.html', {'instance': obj.user})
def get_profile_image(self, obj):
return obj.user.image_url
def get_first_name(self, obj):
return obj.user.first_name
def get_last_name(self, obj):
return obj.user.last_name
def get_username(self, obj):
return obj.user.username
def get_user_id(self, obj):
return obj.user.id
def get_follow(self, obj):
if self.context.get('user_id'):
is_followed = FollowUser.objects.filter(is_valid=True, user__id=self.context.get('user_id'),
follow__id=obj.user.id).first()
if is_followed:
return True
return False
class FollowingUserSerializer(serializers.ModelSerializer):
class Meta:
model = FollowUser
fields = (
'user', 'follow', 'content', 'profile_image', 'first_name', 'last_name', 'username', 'user_id', 'follow')
content = serializers.SerializerMethodField()
profile_image = serializers.SerializerMethodField()
first_name = serializers.SerializerMethodField()
last_name = serializers.SerializerMethodField()
follow = serializers.SerializerMethodField()
username = serializers.SerializerMethodField()
user_id = serializers.SerializerMethodField()
def get_content(self, obj):
return render_to_string('follow_user.html', {'instance': obj.follow})
def get_profile_image(self, obj):
return obj.follow.image_url
def get_first_name(self, obj):
return obj.follow.first_name
def get_last_name(self, obj):
return obj.follow.last_name
def get_username(self, obj):
return obj.follow.username
def get_user_id(self, obj):
return obj.follow.id
def get_follow(self, obj):
if self.context.get('user_id'):
is_followed = FollowUser.objects.filter(is_valid=True, user__id=self.context.get('user_id'),
follow__id=obj.follow.id).first()
if is_followed:
return True
return False
class ChangePasswordSerializer(serializers.Serializer):
old_password = serializers.CharField(required=True)
new_password = serializers.CharField(required=True)
class Meta:
model = User
fields = ('old_password', 'new_password')
class ReportUserSerializer(serializers.ModelSerializer):
class Meta:
model = ReportUser
fields = ('user', 'reported_user')
class BlockUserSerializer(serializers.ModelSerializer):
class Meta:
model = BlockUser
fields = ('user', 'blocked_user')
class ReportUserListSerializer(serializers.ModelSerializer):
reported_user = serializers.SerializerMethodField()
class Meta:
model = ReportUser
fields = ('reported_user',)
def get_reported_user(self, obj):
return UserSerializer(obj.reported_user).data
class BlockUserListSerializer(serializers.ModelSerializer):
blocked_user = serializers.SerializerMethodField()
class Meta:
model = BlockUser
fields = ('blocked_user',)
def get_blocked_user(self, obj):
return UserSerializer(obj.blocked_user).data
<file_sep>/notifications/migrations/0001_initial.py
# Generated by Django 3.1.1 on 2020-09-17 11:50
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.CreateModel(
name='Notification',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_valid', models.BooleanField(default=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('notification_type', models.CharField(choices=[('mention_comment', 'Mention Comment'), ('following', 'Following'), ('like_photo', 'Like Photo'), ('comment_photo', 'Comment Photo'), ('chat_started', 'Chat Started'), ('group_chat_add', 'Group Chat Add')], max_length=250)),
('object_id', models.PositiveIntegerField(blank=True, null=True)),
('read', models.BooleanField(default=False)),
('actor', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
('content_type', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.contenttype')),
],
options={
'ordering': ['-id'],
},
),
]
<file_sep>/RestProject/constants.py
NOTIFICATION_CHUNK = 10
USER_CREATED_SUCCESS = "User Created Successfully"
PASSWORD_CHANGE_SUCCESS = "Password Updated Successfully"
PASSWORD_CHANGE_ERROR = "Wrong Password"
USER_REPORTED_SUCCESS = "User Reported Successfully"
USER_DEACTIVATE_SUCCESS = "User Deactivate Successfully"
USER_OTP_ENABLED = "OTP Enabled Successfully"
USER_OTP_DISABLED = "OTP Disabled Successfully"
USER_REPORTED_ERROR = "User Already Reported"
USER_BLOCKED_SUCCESS = "User Blocked Successfully"
USER_BLOCKED_ERROR = "User Already Blocked"
USER_UNBLOCKED_SUCCESS = "User UnBlocked Successfully"
USER_UNBLOCKED_ERROR = "User Already UnBlocked"
USER_SEARCH_ERROR = "Username Cannot be Empty and less than 3"
POST_SEARCH_ERROR = "Search field Cannot be Empty and less than 3"
CATEGORY_CREATED_SUCCESS = "Category Created Successfully"
CATEGORY_ADDED_SUCCESS = "Category Added Successfully"
POST_CREATED_SUCCESS = "Post Created Successfully"
POST_DELETED_SUCCESS = "Post Deleted Successfully"
POST_DELETED_ERROR = "Post Not Belongs To You"
POST_COMMENTED_SUCCESS = "Commented Successfully"
COMMENT_RATED_ERROR = "Incorrect Comment RateType"
POST_SAVE_SUCCESS = "Saved Successfully"
POST_VIEWED_SUCCESS = "Viewed Successfully"
POST_LIKED_SUCCESS = "Liked Successfully"
POST_LIKED_REMOVED = "Like Removed Successfully"
POST_RATED_SUCCESS = "Post Rated Successfully"
POST_RATED_ERROR = "Incorrect Post RateType"
STORY_RATED_SUCCESS = "Story Rated Successfully"
STORY_RATED_ERROR = "Incorrect Story RateType"
USER_FOLLOW_SUCCESS = "Follow Successfully"
USER_ALREADY_FOLLOWED = "Already Followed"
POST_REPORT_SUCCESS = "Post Reported Successfully"
POST_REPORTED_ALREADY = "Already Reported"
USER_UNFOLLOW_SUCCESS = "UnFollow Successfully"
USER_UNFOLLOW_ERROR = "Not Following"
STORY_CREATED_SUCCESS = "Story Created Successfully"
STORY_VIEWED_SUCCESS = "Story Viewed Successfully"
STORY_DELETED_SUCCESS = "Story Deleted Successfully"
STORY_DELETED_ERROR = "Story Not Found"
NOTIFICATION_READ_SUCCESS = "Notification Read Successfully"
NOTIFICATION_ALL_READ_SUCCESS = "All Notification Read Successfully"
NOTIFICATION_DELETE_SUCCESS = "Notification Deleted Successfully"
NOTIFICATION_ERROR = "Notification Not Found"
USER_OTP_SEND = "OTP Sent Successfully"
OTP_ERROR = "Otp incorrect"
OTP_TIMEOUT = "Otp timeout"
<file_sep>/chat_app/api.py
from django.db.models import Q
from django.shortcuts import get_object_or_404
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.authentication import SessionAuthentication
from RestProject import settings
from chat_app.serializers import MessageReaderSerializer, MessageModelSerializer, UserModelSerializer
from chat_app.models import MessageModel, Thread
from accounts.models import User
class CsrfExemptSessionAuthentication(SessionAuthentication):
"""
SessionAuthentication scheme used by DRF. DRF's SessionAuthentication uses
Django's session framework for authentication which requires CSRF to be
checked. In this case we are going to disable CSRF tokens for the API.
"""
def enforce_csrf(self, request):
return
class MessagePagination(PageNumberPagination):
"""
Limit message prefetch to one page.
"""
page_size = settings.MESSAGES_TO_LOAD
class MessageModelViewSet(ModelViewSet):
permission_classes = [IsAuthenticated, ]
queryset = MessageModel.objects.all()
serializer_class = MessageReaderSerializer
allowed_methods = ('GET', 'POST', 'HEAD', 'OPTIONS')
pagination_class = MessagePagination
def list(self, request, *args, **kwargs):
self.queryset = self.queryset.filter(Q(recipient=request.user) |
Q(user=request.user))
target = self.request.query_params.get('target', None)
if target is not None:
self.queryset = self.queryset.filter(
Q(recipient=request.user, user__username=target) |
Q(recipient__username=target, user=request.user))
return super(MessageModelViewSet, self).list(request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs):
msg = get_object_or_404(
self.queryset.filter(Q(recipient=request.user) |
Q(user=request.user),
Q(pk=kwargs['pk'])))
serializer = self.get_serializer(msg)
return Response(serializer.data)
class MessageModelPostViewSet(ModelViewSet):
permission_classes = [IsAuthenticated, ]
queryset = MessageModel.objects.all()
serializer_class = MessageModelSerializer
allowed_methods = ('POST',)
pagination_class = MessagePagination
def list(self, request, *args, **kwargs):
self.queryset = self.queryset.filter(Q(recipient=request.user) |
Q(user=request.user))
target = self.request.query_params.get('target', None)
if target is not None:
messages = MessageModel.objects.filter(
Q(recipient=request.user, user__username=target) |
Q(recipient__username=target, user=request.user))
for msg in messages:
msg.read_receipt = True
msg.save()
self.queryset = self.queryset.filter(
Q(recipient=request.user, user__username=target) |
Q(recipient__username=target, user=request.user))
return super(MessageModelPostViewSet, self).list(request, *args, **kwargs)
def retrieve(self, request, *args, **kwargs):
msg = get_object_or_404(
self.queryset.filter(Q(recipient=request.user) |
Q(user=request.user),
Q(pk=kwargs['pk'])))
serializer = self.get_serializer(msg)
return Response(serializer.data)
class UserModelViewSet(ModelViewSet):
permission_classes = [IsAuthenticated, ]
queryset = User.objects.all()
serializer_class = UserModelSerializer
allowed_methods = ('GET', 'HEAD', 'OPTIONS')
pagination_class = None # Get all user
def list(self, request, *args, **kwargs):
# Get all users except yourself
# messaging_users = Thread.objects.filter(Q(user=request.user) | Q(recipient=request.user)).values_list('recipient__id', flat=True)
messaging_us = Thread.objects.filter(Q(user=request.user) | Q(recipient=request.user))
user_list = []
for msg in messaging_us:
if msg.messagemodel_set.all():
user_list.append(msg.recipient.id)
# self.queryset = self.queryset.filter(id__in=messaging_users).exclude(id=request.user.id)
self.queryset = self.queryset.filter(id__in=user_list).exclude(id=request.user.id)
# self.queryset = self.queryset.exclude(id=request.user.id)
return super(UserModelViewSet, self).list(request, *args, **kwargs)
<file_sep>/stories/services.py
from datetime import datetime
from accounts.services import UserManagement
from stories.models import Story, StoryView, StoryRating
class StoryManagement(object):
def get_story_by_id(self, id):
return Story.objects.filter(id=id).first()
def get_self_story_by_id(self, id, user):
return Story.objects.filter(id=id, user=user).first()
def get_story_viewers_by_story_id(self, id):
return StoryView.objects.filter(story__id=id, is_valid=True).values_list('user__id', flat=True).order_by('-id')
def get_all_stories_by_user(self, user):
return Story.objects.filter(user=user, is_valid=True)
def get_story_viewers(self, story):
return StoryView.objects.filter(story=story)
def get_stories_of_following_users(self, user):
blocked_users = UserManagement().get_user_from_blocked_list(user)
following_users = UserManagement().get_followings_users(user).exclude(follow__id__in=blocked_users)
return Story.objects.filter(user__in=following_users, is_valid=True, expire_at__gte=datetime.today()).order_by(
'-id')
def get_stories_by_user_group(self, user_ids):
return Story.objects.filter(user__id__in=user_ids, is_valid=True, expire_at__gte=datetime.today()).order_by(
'-id').group_by('user').distinct().values_list('user', flat=True)
def get_story_rate_by_id(self, id, user_id):
return StoryRating.objects.filter(story__id=id, user_rated__id=user_id).first()
<file_sep>/accounts/views.py
from datetime import timedelta
from django.utils import timezone
from rest_framework import status
from rest_framework.generics import UpdateAPIView
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework.status import HTTP_201_CREATED, HTTP_400_BAD_REQUEST, HTTP_200_OK
from rest_framework.views import APIView
from RestProject.constants import (USER_CREATED_SUCCESS, USER_FOLLOW_SUCCESS, USER_UNFOLLOW_SUCCESS,
USER_UNFOLLOW_ERROR, PASSWORD_CHANGE_SUCCESS,
PASSWORD_CHANGE_ERROR, USER_REPORTED_SUCCESS,
USER_REPORTED_ERROR, USER_BLOCKED_SUCCESS, USER_BLOCKED_ERROR,
USER_UNBLOCKED_SUCCESS, USER_UNBLOCKED_ERROR, USER_SEARCH_ERROR,
USER_DEACTIVATE_SUCCESS, USER_OTP_ENABLED, USER_OTP_DISABLED, USER_OTP_SEND,
OTP_ERROR, OTP_TIMEOUT)
from accounts.models import (User, AccountInformation, WebsiteVerification, Otp)
from accounts.serializers import (UserSerializer, FollowUserSerializer, ChangePasswordSerializer, ReportUserSerializer,
BlockUserSerializer, BlockUserListSerializer, ReportUserListSerializer,
FollowingUserSerializer, FollowsUserSerializer, AccountInformationSerializer,
WebsiteVerificationSerializer)
from accounts.services import UserManagement
from notifications.models import Notification
from notifications.services import Notifications
class UserCreate(APIView):
serializer_class = UserSerializer
permission_classes = ()
authentication_classes = ()
def post(self, request, format='json'):
dict = request.data.copy()
dict['username'] = (request.data.get('username')).lower()
dict['email'] = (request.data.get('email')).lower()
dict['age'] = (request.data.get('age'))
serializer = self.serializer_class(data=dict)
if serializer.is_valid():
user = serializer.save()
user.set_password(request.data.get('password'))
user.is_active = True
user.save()
if user:
UserManagement().send_otp_email(user.id)
return Response({"message": USER_CREATED_SUCCESS}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class UserExistsView(APIView):
serializer_class = UserSerializer
permission_classes = ()
authentication_classes = ()
def post(self, request, format='json'):
message = ""
user_exists = False
if request.data.get('username'):
username = (request.data.get('username')).lower()
user = User.objects.filter(username=username).first()
if user:
user_exists = True
message = "Username not available Try another"
elif request.data.get('email'):
email = (request.data.get('email')).lower()
user = User.objects.filter(email=email).first()
if user:
user_exists = True
message = "Email is already registered please Try another."
return Response({"message": message, 'user_exists': user_exists}, status=status.HTTP_200_OK)
class UserProfileView(UpdateAPIView):
permission_classes = [IsAuthenticated]
serializer_class = UserSerializer
model_class = User
def get_queryset(self):
return User.objects.filter(id=self.request.user.id)
def get_object(self):
return self.request.user
def get(self, request):
serializer = self.serializer_class(self.request.user)
return Response(serializer.data, status=status.HTTP_200_OK)
class AccountInformationView(UpdateAPIView):
permission_classes = [IsAuthenticated]
serializer_class = AccountInformationSerializer
model_class = AccountInformation
def get_queryset(self):
return AccountInformation.objects.filter(user__id=self.request.user.id)
def get_object(self):
return AccountInformation.objects.filter(user__id=self.request.user.id).first()
def get(self, request):
serializer = self.serializer_class(UserManagement().get_account_info_by_user(self.request.user))
return Response(serializer.data, status=status.HTTP_200_OK)
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
dict = request.data.copy()
dict['user'] = self.request.user.id
serializer = self.get_serializer(instance, data=dict, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
UserManagement().update_user_gender(self.request.user.id, self.request.data.get('gender'))
return Response(serializer.data)
class WebsiteVerificationView(UpdateAPIView):
permission_classes = [IsAuthenticated]
serializer_class = WebsiteVerificationSerializer
model_class = WebsiteVerification
def get_queryset(self):
return WebsiteVerification.objects.filter(user__id=self.request.user.id)
def get_object(self):
return WebsiteVerification.objects.filter(user__id=self.request.user.id).first()
def get(self, request):
serializer = self.serializer_class(UserManagement().get_webiste_by_user(self.request.user))
return Response(serializer.data, status=status.HTTP_200_OK)
def update(self, request, *args, **kwargs):
partial = kwargs.pop('partial', False)
instance = self.get_object()
dict = request.data.copy()
dict['user'] = self.request.user.id
serializer = self.get_serializer(instance, data=dict, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
return Response(serializer.data)
class ChangePasswordView(UpdateAPIView):
serializer_class = ChangePasswordSerializer
model = User
permission_classes = (IsAuthenticated,)
def get_object(self, queryset=None):
return self.request.user
def update(self, request, *args, **kwargs):
self.object = self.get_object()
serializer = self.get_serializer(data=request.data)
message = PASSWORD_CHANGE_SUCCESS
status = HTTP_201_CREATED
if serializer.is_valid():
if not self.object.check_password(serializer.data.get("old_password")):
status = HTTP_400_BAD_REQUEST
message = PASSWORD_CHANGE_ERROR
else:
self.object.set_password(serializer.data.get("new_password"))
self.object.save()
else:
message = serializer.errors
status = HTTP_400_BAD_REQUEST
return Response({'message': message}, status=status)
class UserReportView(APIView):
serializer_class = ReportUserSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
message = USER_REPORTED_SUCCESS
status = HTTP_201_CREATED
if not UserManagement().get_user_reported(request.data, self.request.user):
dict = request.data.copy()
dict['user'] = self.request.user.id
serializer = self.serializer_class(data=dict)
if serializer.is_valid():
serializer.save()
else:
message = serializer.errors
status = HTTP_400_BAD_REQUEST
else:
message = USER_REPORTED_ERROR
status = HTTP_400_BAD_REQUEST
return Response({"message": message}, status=status)
class UserBlockView(APIView):
serializer_class = BlockUserSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
message = USER_BLOCKED_SUCCESS
status = HTTP_201_CREATED
block_user = UserManagement().get_blockUser(request.data, self.request.user)
if not block_user:
dict = request.data.copy()
dict['user'] = self.request.user.id
dict['is_valid'] = True
serializer = self.serializer_class(data=dict)
if serializer.is_valid():
serializer.save()
else:
message = serializer.errors
status = HTTP_400_BAD_REQUEST
else:
if block_user.is_valid:
message = USER_BLOCKED_ERROR
status = HTTP_400_BAD_REQUEST
else:
block_user.is_valid = True
block_user.save()
return Response({"message": message}, status=status)
class UserUnBlockView(APIView):
serializer_class = BlockUserSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, *args, **kwargs):
status = HTTP_400_BAD_REQUEST
message = USER_UNBLOCKED_ERROR
block_user = UserManagement().get_blockUser(request.data, self.request.user)
if block_user and block_user.is_valid:
block_user.is_valid = False
block_user.save()
message = USER_UNBLOCKED_SUCCESS
status = HTTP_201_CREATED
return Response({'message': message}, status=status)
class UserFollowView(APIView):
serializer_class = FollowsUserSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
following_user = UserManagement().get_user_follow(request.data, self.request.user)
user = UserManagement().get_user(request.data.get('follow'))
status = HTTP_201_CREATED
message = USER_FOLLOW_SUCCESS
if not following_user:
dict = request.data.copy()
dict['user'] = self.request.user.id
serializer = self.serializer_class(data=dict)
if serializer.is_valid():
follow_user = serializer.save()
Notifications().create_notification(user, Notification.FOLLOWING, follow_user)
else:
message = serializer.errors
status = HTTP_400_BAD_REQUEST
else:
if following_user.is_valid:
following_user.is_valid = False
message = USER_UNFOLLOW_SUCCESS
notification = Notifications().get_notification(user, Notification.FOLLOWING, following_user.id)
if notification:
notification.created_at = timezone.now()
notification.save()
else:
Notifications().create_notification(user, Notification.FOLLOWING, following_user)
else:
following_user.is_valid = True
Notifications().create_notification(user, Notification.FOLLOWING, following_user)
following_user.save()
status = HTTP_200_OK
return Response({"message": message}, status=status)
class UserUnFollowView(APIView):
serializer_class = FollowUserSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
following_user = UserManagement().get_user_follow(request.data, self.request.user)
message = USER_UNFOLLOW_ERROR
status = HTTP_400_BAD_REQUEST
if following_user:
if following_user.is_valid:
following_user.is_valid = False
following_user.save()
message = USER_UNFOLLOW_SUCCESS
status = HTTP_201_CREATED
return Response({"message": message}, status=status)
class FollowingUsersView(APIView):
serializer_class = FollowUserSerializer
permission_classes = (IsAuthenticated,)
def get(self, request):
data = {'following': FollowingUserSerializer(UserManagement().get_followings(self.request.user),
context={'user_id': self.request.user.id}, many=True).data,
'followers': self.serializer_class(UserManagement().get_followers(self.request.user),
context={'user_id': self.request.user.id}, many=True).data}
return Response(data, status=status.HTTP_200_OK)
class BlockedUsersListView(APIView):
serializer_class = BlockUserListSerializer
permission_classes = (IsAuthenticated,)
def get(self, request):
data = self.serializer_class(UserManagement().get_user_blocked_list(self.request.user), many=True).data
return Response(data, status=status.HTTP_200_OK)
class ReportUsersListView(APIView):
serializer_class = ReportUserListSerializer
permission_classes = (IsAuthenticated,)
def get(self, request):
data = self.serializer_class(UserManagement().get_user_reported_list(self.request.user), many=True).data
return Response(data, status=status.HTTP_200_OK)
class SearchUsersListView(APIView):
serializer_class = UserSerializer
permission_classes = (IsAuthenticated,)
def post(self, request):
if request.data.get('username') and len(request.data.get('username')) > 2:
data = self.serializer_class(
UserManagement().search_users_by_username(request.data.get('username'), self.request.user.id),
context={'user_id': self.request.user.id}, many=True).data
return Response(data, status=status.HTTP_200_OK)
return Response({'message': USER_SEARCH_ERROR}, status=status.HTTP_400_BAD_REQUEST)
class UserDeactivateView(APIView):
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
user = UserManagement().get_user(self.request.user.id)
user.is_active = False
user.save()
return Response({"message": USER_DEACTIVATE_SUCCESS}, status=HTTP_200_OK)
class OtpEmailToggleView(APIView):
permission_classes = (IsAuthenticated,)
def get(self, request, format='json'):
user = UserManagement().get_user(self.request.user.id)
if user.otp_enabled:
user.otp_enabled = False
message = USER_OTP_DISABLED
else:
user.otp_enabled = True
message = USER_OTP_ENABLED
user.save()
return Response({"message": message, 'data': UserSerializer(user).data}, status=HTTP_200_OK)
class OtpEmailVerifyView(APIView):
permission_classes = (IsAuthenticated,)
def get(self, request, format='json'):
otp = Otp.objects.filter(user__id=self.request.user.id).first()
if otp:
otp.delete()
UserManagement().send_otp_email(self.request.user.id)
return Response({"message": USER_OTP_SEND}, status=HTTP_200_OK)
def post(self, request, format='json'):
message = OTP_ERROR
now = timezone.now()
otp = Otp.objects.filter(user__id=self.request.user.id, code=request.data.get('code')).first()
user = UserManagement().get_user(self.request.user.id)
if otp:
diff = now - otp.created_at
if diff and diff < timedelta(minutes=1):
message = "Success"
user.email_verified = True
user.save()
else:
message = OTP_TIMEOUT
return Response({"message": message, 'data': UserSerializer(user).data}, status=HTTP_200_OK)
class SignupOtpEmailVerifyView(APIView):
permission_classes = (AllowAny,)
def post(self, request, format='json'):
message = OTP_ERROR
now = timezone.now()
otp = Otp.objects.filter(user__email=request.data.get('user_email'), code=request.data.get('code')).first()
user = UserManagement().get_user_by_email(request.data.get('user_email'))
if otp:
diff = now - otp.created_at
if diff and diff < timedelta(minutes=1):
message = "Success"
user.email_verified = True
user.save()
else:
message = OTP_TIMEOUT
return Response({"message": message}, status=HTTP_200_OK)
<file_sep>/common/migrations/0002_auto_20201222_1121.py
# Generated by Django 3.1.1 on 2020-12-22 11:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('common', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='appname',
name='type',
field=models.CharField(choices=[('DEVELOPMENT', 'DEVELOPMENT'), ('PRODUCTION', 'PRODUCTION')], default='DEVELOPMENT', max_length=255),
),
]
<file_sep>/accounts/migrations/0008_websiteverification.py
# Generated by Django 3.1.1 on 2020-10-29 07:59
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0007_accountinformation'),
]
operations = [
migrations.CreateModel(
name='WebsiteVerification',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_valid', models.BooleanField(default=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('name', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_verified', models.BooleanField(default=False)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
<file_sep>/posts/migrations/0015_post_post_qr.py
# Generated by Django 3.1.1 on 2020-12-22 12:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0014_auto_20201219_0850'),
]
operations = [
migrations.AddField(
model_name='post',
name='post_qr',
field=models.FileField(blank=True, null=True, upload_to='static/post_qr_codes/'),
),
]
<file_sep>/posts/migrations/0009_auto_20201203_0811.py
# Generated by Django 3.1.1 on 2020-12-03 08:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0008_auto_20201203_0810'),
]
operations = [
migrations.AlterField(
model_name='postcomment',
name='child',
field=models.ManyToManyField(blank=True, null=True, related_name='_postcomment_child_+', to='posts.PostComment'),
),
]
<file_sep>/stories/migrations/0001_initial.py
# Generated by Django 3.1.1 on 2020-09-15 12:11
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Story',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_valid', models.BooleanField(default=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('expire_at', models.DateTimeField(blank=True, null=True)),
('file', models.FileField(max_length=254, upload_to='static/story_files')),
('title', models.CharField(blank=True, max_length=255, null=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='StoryView',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_valid', models.BooleanField(default=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('story', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='stories.story')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
<file_sep>/categories/models.py
from django.db import models
from accounts.models import User
from common.models import BaseModel
class Category(BaseModel):
parent = models.ForeignKey("self", on_delete=models.DO_NOTHING, null=True, blank=True)
name = models.CharField(max_length=255)
image = models.FileField(upload_to='static/categories_images', max_length=254)
def __str__(self):
return self.name
class SelectedCategories(BaseModel):
categories = models.ManyToManyField(Category, null=True, blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.user.username
<file_sep>/chat_app/models.py
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from django.db import models
from accounts.models import User
from common.models import BaseModel
class Thread(BaseModel):
title = models.CharField(max_length=5)
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='user',
related_name='thread_from_user', db_index=True)
recipient = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='recipient',
related_name='thread_to_user', db_index=True)
def __str__(self):
return self.title
class MessageModel(models.Model):
"""
This class represents a chat message. It has a owner (user), timestamp and
the message body.
"""
TEXT = 'text'
POST_URL = 'post_url'
STORY_URL = 'story_url'
FILE = 'file'
AUDIO = 'audio'
MESSAGE_TYPE = (
(TEXT, 'Text'),
(FILE, 'File'),
(POST_URL, 'Post URL'),
(STORY_URL, 'Story URL'),
(AUDIO, 'Audio'),
)
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='user',
related_name='from_user', db_index=True)
recipient = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='recipient',
related_name='to_user', db_index=True)
thread = models.ForeignKey(Thread, on_delete=models.CASCADE, null=True, blank=True)
timestamp = models.DateTimeField('timestamp', auto_now_add=True, editable=False,
db_index=True)
body = models.TextField('body')
message_type = models.CharField(max_length=10, choices=MESSAGE_TYPE, default=TEXT)
file_url = models.URLField(null=True, blank=True)
read_receipt = models.BooleanField(default=False)
def __str__(self):
return str(self.id)
def characters(self):
"""
Toy function to count body characters.
:return: body's char number
"""
return len(self.body)
def notify_ws_clients(self):
"""
Inform client there is a new message.
"""
notification = {
'type': 'message',
'message': '{}'.format(self.id)
}
channel_layer = get_channel_layer()
print("user.id {}".format(self.user.id))
print("user.id {}".format(self.recipient.id))
async_to_sync(channel_layer.group_send)("{}".format(self.user.id), notification)
async_to_sync(channel_layer.group_send)("{}".format(self.recipient.id), notification)
def save(self, *args, **kwargs):
"""
Trims white spaces, saves the message and notifies the recipient via WS
if the message is new.
"""
new = self.id
self.body = self.body.strip() # Trimming whitespaces from the body
super(MessageModel, self).save(*args, **kwargs)
if new is None:
self.notify_ws_clients()
# Meta
class Meta:
verbose_name_plural = 'messages'
ordering = ('timestamp',)
<file_sep>/common/admin.py
from django.contrib import admin
# Register your models here.
from .models import AppName
admin.site.register(AppName)
<file_sep>/accounts/migrations/0007_accountinformation.py
# Generated by Django 3.1.1 on 2020-10-29 05:51
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django_countries.fields
class Migration(migrations.Migration):
dependencies = [
('accounts', '0006_blockuser'),
]
operations = [
migrations.CreateModel(
name='AccountInformation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_valid', models.BooleanField(default=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('country', django_countries.fields.CountryField(max_length=2)),
('site_visit', models.BooleanField(default=False)),
('partner_info', models.BooleanField(default=False)),
('search_privacy', models.BooleanField(default=False)),
('store_contacts', models.BooleanField(default=False)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
<file_sep>/dashboard/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.DashBoardView.as_view(), name='dashboard'),
path('login/', views.dashboard_login_view, name='dashboard-login'),
path('logout/', views.dashboard_logout_view, name='dashboard-logout'),
path('users/', views.DashBoardUsersView.as_view(), name='dashboard-users'),
]
<file_sep>/posts/migrations/0011_auto_20201208_0624.py
# Generated by Django 3.1.1 on 2020-12-08 06:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0010_auto_20201203_1044'),
]
operations = [
migrations.AlterField(
model_name='postmaterial',
name='url',
field=models.TextField(blank=True, null=True),
),
]
<file_sep>/chat_app/migrations/0004_auto_20210125_0822.py
# Generated by Django 3.1.1 on 2021-01-25 08:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('chat_app', '0003_auto_20201230_1411'),
]
operations = [
migrations.AlterField(
model_name='messagemodel',
name='message_type',
field=models.CharField(choices=[('text', 'Text'), ('file', 'File'), ('post_url', 'Post URL'), ('story_url', 'Story URL'), ('audio', 'Audio')], default='text', max_length=10),
),
]
<file_sep>/posts/tasks.py
from celery import shared_task
from accounts.models import User
from posts.models import Post, PostImpressions
@shared_task
def save_impressions(post_ids, user_id):
for post in Post.objects.filter(id__in=post_ids):
post_object = Post.objects.filter(id=post.id).first()
user = User.objects.filter(id=user_id).first()
PostImpressions.objects.get_or_create(post=post_object, user_impressed=user)
<file_sep>/notifications/serializers.py
from rest_framework import serializers
from accounts.serializers import FollowUserSerializer
from posts.serializers import PostLikeSerializer, PostCommentSerializer, PostRateSerializer, CommentRateSerializer
from stories.serializers import StoryRateSerializer
from .models import Notification
from .services import Notifications
class NotificationSerializer(serializers.ModelSerializer):
detail = serializers.SerializerMethodField()
time = serializers.SerializerMethodField()
class Meta:
model = Notification
fields = ('id', 'notification_type', 'read', 'content_type', 'detail', 'time',)
def get_detail(self, instance):
serializer = None
if instance.notification_type == Notification.LIKE_POST:
serializer = PostLikeSerializer(instance.content_object).data
elif instance.notification_type == Notification.COMMENT_POST:
serializer = PostCommentSerializer(instance.content_object).data
elif instance.notification_type == Notification.FOLLOWING:
serializer = FollowUserSerializer(instance.content_object,
context={'user_id': self.context.get('user_id')}).data
elif instance.notification_type == Notification.RATE_POST:
serializer = PostRateSerializer(instance.content_object).data
elif instance.notification_type == Notification.RATE_STORY:
serializer = StoryRateSerializer(instance.content_object).data
elif instance.notification_type == Notification.RATE_COMMENT:
serializer = CommentRateSerializer(instance.content_object).data
elif instance.notification_type == Notification.MENTION_COMMENT:
serializer = PostCommentSerializer(instance.content_object,
context={'type': instance.notification_type}).data
elif instance.notification_type == Notification.REPLY_COMMENT:
serializer = PostCommentSerializer(instance.content_object,
context={'type': instance.notification_type}).data
return serializer
def get_time(self, obj):
return Notifications().get_notification_time(obj.created_at)
<file_sep>/common/email_services.py
from django.conf import settings
from django.core.mail import send_mail as main_email_send
from django.template.loader import get_template
class Email(object):
def send_email(self, subject, content, user_email, html_content=None):
# print(subject, content, settings.EMAIL_HOST_USER, [user_email], html_content)
main_email_send(subject, content, settings.EMAIL_HOST_USER, [user_email], fail_silently=False,
html_message=html_content)
def send_otp_email(self, user, otp):
htmly = get_template('otp_email.html')
content = 'Code: {}'.format(otp)
d = {'email_body': content,
"email_type": 'Nitrx OTP', "user": user}
html_content = htmly.render(d)
self.send_email('Nitrx', '', user.email, html_content=html_content)
<file_sep>/posts/migrations/0002_auto_20200910_1024.py
# Generated by Django 3.1.1 on 2020-09-10 10:24
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('posts', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='postrating',
name='rating',
field=models.CharField(choices=[('ONE', '1 Nitrx'), ('TWO', '2 Nitrx'), ('THREE', '3 Nitrx'), ('FOUR', '4 Nitrx'), ('FIVE', '5 Nitrx')], max_length=255),
),
migrations.CreateModel(
name='BlacklistPost',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_valid', models.BooleanField(default=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='posts.post')),
('user_reported', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
<file_sep>/chat_app/migrations/0001_initial.py
# Generated by Django 3.1.1 on 2020-12-24 13:00
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='MessageModel',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('timestamp', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='timestamp')),
('body', models.TextField(verbose_name='body')),
('message_type', models.CharField(choices=[('text', 'Text'), ('file', 'File')], default='text', max_length=10)),
('file_url', models.URLField(blank=True, null=True)),
('recipient', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='to_user', to=settings.AUTH_USER_MODEL, verbose_name='recipient')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='from_user', to=settings.AUTH_USER_MODEL, verbose_name='user')),
],
options={
'verbose_name_plural': 'messages',
},
),
]
<file_sep>/stories/models.py
from django.db import models
# Create your models here.
from django.db.models import QuerySet
from django_group_by import GroupByMixin
from accounts.models import User
from common.models import BaseModel
class StoryQuerySet(QuerySet, GroupByMixin):
pass
class Story(BaseModel):
IMAGE = 'IMAGE'
VIDEO = 'VIDEO'
STORY_CHOICES = (
(VIDEO, 'VIDEO'),
(IMAGE, 'IMAGE'),
)
objects = StoryQuerySet.as_manager()
user = models.ForeignKey(User, on_delete=models.CASCADE)
expire_at = models.DateTimeField(null=True, blank=True)
file = models.FileField(upload_to='static/story_files', max_length=254, null=True, blank=True)
title = models.CharField(max_length=255, blank=True, null=True)
story_url = models.CharField(max_length=255, blank=True, null=True)
url = models.TextField(null=True, blank=True)
story_type = models.CharField(max_length=20, choices=STORY_CHOICES, default=IMAGE)
def __str__(self):
return self.user.username
class StoryView(BaseModel):
user = models.ForeignKey(User, on_delete=models.CASCADE)
story = models.ForeignKey(Story, on_delete=models.CASCADE)
def __str__(self):
return self.user.username
class StoryRating(BaseModel):
ONE = '1'
THREE = '3'
FIVE = '5'
SEVEN = '7'
TEN = '10'
RATE_TYPE = (
(ONE, 1),
(THREE, 3),
(FIVE, 5),
(SEVEN, 7),
(TEN, 10),
)
story = models.ForeignKey(Story, on_delete=models.CASCADE)
user_rated = models.ForeignKey(User, on_delete=models.CASCADE)
rating = models.IntegerField(choices=RATE_TYPE)
<file_sep>/accounts/migrations/0013_auto_20201222_1140.py
# Generated by Django 3.1.1 on 2020-12-22 11:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0012_user_image_url'),
]
operations = [
migrations.AlterField(
model_name='user',
name='profile_qr',
field=models.FileField(null=True, upload_to='static/user_qr_codes/'),
),
]
<file_sep>/posts/views.py
from rest_framework import generics
from rest_framework import status
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST, HTTP_201_CREATED
from rest_framework.views import APIView
from RestProject.constants import (POST_CREATED_SUCCESS, POST_COMMENTED_SUCCESS, POST_RATED_SUCCESS, POST_LIKED_SUCCESS,
POST_REPORT_SUCCESS, POST_REPORTED_ALREADY, POST_DELETED_SUCCESS, POST_DELETED_ERROR,
POST_VIEWED_SUCCESS, POST_SEARCH_ERROR, POST_LIKED_REMOVED, POST_RATED_ERROR,
POST_SAVE_SUCCESS, COMMENT_RATED_ERROR)
from accounts.services import UserManagement
from notifications.models import Notification
from notifications.services import Notifications
from posts.models import BlacklistPost, Post, PostSave
from posts.serializers import (PostSerializer, PostCommentSerializer, PostRateSerializer, PostLikeSerializer,
BlackListPostSerializer, PostDetailSerializer, PostViewSerializer,
OtherUserProfileSerializer, PostMaterialSerializer, PostSaveSerializer,
CommentRateSerializer)
from posts.services import PostManagement
from posts.tasks import save_impressions
class PostCreateView(APIView):
serializer_class = PostSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
dict = self.request.data.copy()
dict['creator'] = self.request.user.id
serializer = self.serializer_class(data=dict)
if serializer.is_valid():
post = serializer.save()
media_list = request.data.get('media_list')
for media in media_list:
dict['url'] = media.get('url')
dict['post_type'] = media.get('post_type')
material_serializer = PostMaterialSerializer(data=dict)
if material_serializer.is_valid():
post_material = material_serializer.save()
post.media_files.add(post_material)
return Response({"message": POST_CREATED_SUCCESS}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class PostDeleteView(APIView):
serializer_class = PostSerializer
permission_classes = (IsAuthenticated,)
def post_exist(self, data):
obj = Post.objects.filter(id=data.get('post'), creator=self.request.user).first()
if obj:
return obj
return None
def post(self, request, format='json'):
post = self.post_exist(request.data)
message = POST_DELETED_SUCCESS
status = HTTP_200_OK
if post:
post.is_valid = False
post.save()
else:
message = POST_DELETED_ERROR
status = HTTP_400_BAD_REQUEST
return Response({"message": message}, status=status)
class PostDetailView(APIView):
serializer_class = PostDetailSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, *args, **kwargs):
posts = PostManagement().get_post_detail(request.data.get('post_id'))
return Response(self.serializer_class(posts, context={'user_id': self.request.user.id}).data,
status=status.HTTP_200_OK)
class PostViewView(APIView):
serializer_class = PostViewSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
dict = self.request.data.copy()
dict['user_view'] = self.request.user.id
serializer = self.serializer_class(data=dict)
if serializer.is_valid():
serializer.save()
return Response({"message": POST_VIEWED_SUCCESS}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class AllPostsView(APIView):
serializer_class = PostDetailSerializer
permission_classes = (IsAuthenticated,)
def get_objects(self, ):
posts = Post.objects.filter(creator=self.request.user, is_valid=True).order_by('-id')
save_impressions.delay(list(posts.values_list('id', flat=True)), self.request.user.id)
return posts
def get(self, request, *args, **kwargs):
posts = self.get_objects()
return Response(self.serializer_class(posts, many=True, context={'user_id': request.user.id}).data,
status=status.HTTP_200_OK)
class PostCommentView(APIView):
serializer_class = PostCommentSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
dict = self.request.data.copy()
dict['user_commented'] = self.request.user.id
serializer = self.serializer_class(data=dict)
if serializer.is_valid():
post_comment = serializer.save()
parent = request.data.get('parent')
if parent:
parent_comment = PostManagement().get_comment_by_id(int(parent))
users_comment = UserManagement().get_user(parent_comment.user_commented.id)
Notifications().create_notification(users_comment, Notification.REPLY_COMMENT, post_comment)
mentioned_users = request.data.get('mentioned_users')
post = PostManagement().get_post_detail(request.data.get('post'))
post_creator = UserManagement().get_user(post.creator.id)
if mentioned_users:
for user_id in eval(mentioned_users):
user = UserManagement().get_user(int(user_id))
if user:
post_comment.mentioned_users.add(user)
Notifications().create_notification(user, Notification.MENTION_COMMENT, post_comment)
if not parent and post.creator.id != self.request.user.id:
Notifications().create_notification(post_creator, Notification.COMMENT_POST, post_comment)
return Response({"message": POST_COMMENTED_SUCCESS}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class CommentRateView(APIView):
serializer_class = CommentRateSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
dict = self.request.data.copy()
dict['user_rated'] = self.request.user.id
comment_rate = PostManagement().get_rate_by_id_user(request.data.get('comment'), self.request.user.id)
message = POST_COMMENTED_SUCCESS
status = HTTP_201_CREATED
if not comment_rate:
serializer = self.serializer_class(data=dict)
if serializer.is_valid():
comment_rate = serializer.save()
comment = PostManagement().get_comment_by_id(request.data.get('comment'))
users_comment = UserManagement().get_user(comment.user_commented.id)
Notifications().create_notification(users_comment, Notification.RATE_COMMENT, comment_rate)
else:
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
elif request.data.get('rating') in ['1', '3', '5', '7', '10']:
comment_rate.rating = request.data.get('rating')
comment_rate.save()
else:
message = COMMENT_RATED_ERROR
status = HTTP_400_BAD_REQUEST
return Response({"message": message}, status=status)
class PostRateView(APIView):
serializer_class = PostRateSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
dict = self.request.data.copy()
dict['user_rated'] = self.request.user.id
post_rate = PostManagement().get_post_rate_by_user(self.request.user.id, request.data.get('post'))
message = POST_RATED_SUCCESS
status = HTTP_201_CREATED
if not post_rate:
serializer = self.serializer_class(data=dict)
if serializer.is_valid():
post_rate = serializer.save()
post = PostManagement().get_post_detail(request.data.get('post'))
post_creator = UserManagement().get_user(post.creator.id)
Notifications().create_notification(post_creator, Notification.RATE_POST, post_rate)
else:
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
elif request.data.get('rating') in ['1', '3', '5', '7', '10']:
post_rate.rating = request.data.get('rating')
post_rate.save()
else:
message = POST_RATED_ERROR
status = HTTP_400_BAD_REQUEST
return Response({"message": message}, status=status)
class PostLikeView(APIView):
serializer_class = PostLikeSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
dict = self.request.data.copy()
dict['user_liked'] = self.request.user.id
post_like = PostManagement().get_postlike_by_user(request.data.get('post'), self.request.user.id)
if not post_like:
serializer = self.serializer_class(data=dict)
if serializer.is_valid():
post_like = serializer.save()
post = PostManagement().get_post_detail(self.request.data.get('post'))
if self.request.user.id != post.creator.id:
user = UserManagement().get_user(post.creator.id)
Notifications().create_notification(user, Notification.LIKE_POST, post_like)
return Response({"message": POST_LIKED_SUCCESS}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
else:
if post_like.is_valid:
post_like.is_valid = False
message = POST_LIKED_REMOVED
else:
post_like.is_valid = True
message = POST_LIKED_SUCCESS
post_like.save()
return Response({"message": message}, status=status.HTTP_200_OK)
class PostReportView(APIView):
serializer_class = BlackListPostSerializer
permission_classes = (IsAuthenticated,)
def is_already_reported(self, data):
return BlacklistPost.objects.filter(id=data.get('post'), user_reported=self.request.user).first()
def post(self, request, format='json'):
if not self.is_already_reported(request.data):
dict = request.data.copy()
dict['user_reported'] = self.request.user.id
serializer = self.serializer_class(data=dict)
if serializer.is_valid():
serializer.save()
return Response({"message": POST_REPORT_SUCCESS}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return Response({"message": POST_REPORTED_ALREADY}, status=status.HTTP_400_BAD_REQUEST)
class MyFollowingPostsView(APIView):
serializer_class = PostDetailSerializer
permission_classes = (IsAuthenticated,)
def get(self, request, format='json'):
following_users = UserManagement().get_followings_users(self.request.user)
posts = PostManagement().get_non_reported_posts(following_users, self.request.user)
save_impressions.delay(list(posts.values_list('id', flat=True)), self.request.user.id)
return Response(self.serializer_class(posts, many=True).data, status=status.HTTP_200_OK)
class PostByCategoryView(APIView):
serializer_class = PostDetailSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
posts = PostManagement().get_post_by_category(request.data.get('category_id'), self.request.user)
save_impressions.delay(list(posts.values_list('id', flat=True)), self.request.user.id)
return Response(self.serializer_class(posts, many=True, context={'user_id': self.request.user.id}).data,
status=status.HTTP_200_OK)
class SearchPostsView(APIView):
serializer_class = PostDetailSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
if request.data.get('data') and len(request.data.get('data')) > 1:
posts = PostManagement().search_posts(request.data.get('data'), self.request.user)
save_impressions.delay(list(posts.values_list('id', flat=True)), self.request.user.id)
return Response(self.serializer_class(posts, many=True).data, status=status.HTTP_200_OK)
return Response({'message': POST_SEARCH_ERROR}, status=status.HTTP_400_BAD_REQUEST)
class OtherUserPostsAndProfile(APIView):
serializer_class = OtherUserProfileSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
return Response(self.serializer_class(UserManagement().get_user(request.data.get('user_id')),
context={'user_id': self.request.user.id}).data,
status=status.HTTP_200_OK)
class PostSaveView(APIView):
serializer_class = PostSaveSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
dict = self.request.data.copy()
dict['user'] = self.request.user.id
serializer = self.serializer_class(data=dict)
if serializer.is_valid():
serializer.save()
return Response({"message": POST_SAVE_SUCCESS}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class AllSavedPostsView(generics.ListAPIView):
serializer_class = PostSaveSerializer
permission_classes = (IsAuthenticated,)
def get_queryset(self):
filter_dict = {'user': self.request.user, 'is_valid': True}
saved_posts = PostSave.objects.filter(**filter_dict)
return saved_posts
class TrendingPostsView(APIView):
serializer_class = PostDetailSerializer
permission_classes = (AllowAny,)
def get_objects(self, ):
posts_ids = []
posts = Post.objects.filter(is_valid=True).order_by('-id')
save_impressions.delay(list(posts.values_list('id', flat=True)), self.request.user.id)
for post in posts:
if post.media_files.all().count() < 3:
posts_ids.append(post.id)
return posts.exclude(id__in=posts_ids)
def get(self, request, *args, **kwargs):
posts = self.get_objects()
return Response(self.serializer_class(posts, many=True).data, status=status.HTTP_200_OK)
<file_sep>/notifications/views.py
import math
# Create your views here.
from rest_framework import generics
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from rest_framework.views import APIView
from RestProject.constants import (NOTIFICATION_CHUNK, NOTIFICATION_READ_SUCCESS, NOTIFICATION_ERROR,
NOTIFICATION_ALL_READ_SUCCESS, NOTIFICATION_DELETE_SUCCESS)
from notifications.models import Notification
from notifications.serializers import NotificationSerializer
from notifications.services import Notifications
class AllNotificationsView(generics.ListAPIView):
serializer_class = NotificationSerializer
permission_classes = (IsAuthenticated,)
pagination_class = PageNumberPagination
def get_queryset(self):
filter_dict = {'actor': self.request.user, 'is_valid': True}
notifications = Notification.objects.filter(**filter_dict).exclude(object_id__isnull=True)
filtered_notifications = [notification for notification in notifications if notification.content_object]
unread = len([notification for notification in filtered_notifications if notification.read == False])
return filtered_notifications, unread
def list(self, request, *args, **kwargs):
filtered_notifications, unread = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(filtered_notifications)
context = {}
context['user_id'] = request.user.id
if page is not None:
serializer = self.serializer_class(page, context=context, many=True)
total_pages = int((int(math.ceil(len(filtered_notifications) / 10.0)) * 10) / NOTIFICATION_CHUNK)
return self.get_paginated_response({
'unread': unread,
'total_notifications': len(filtered_notifications),
'total_pages': total_pages,
'data': serializer.data
})
serializer = self.serializer_class(filtered_notifications, context=context, many=True).data
return Response(serializer)
class ReadNotificationsView(APIView):
serializer_class = NotificationSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, *args, **kwargs):
status = HTTP_400_BAD_REQUEST
message = NOTIFICATION_ERROR
if Notifications().mark_read(request.data.get('notification_id'), self.request.user.id):
status = HTTP_200_OK
message = NOTIFICATION_READ_SUCCESS
return Response({"message": message}, status=status)
class DeleteNotificationsView(APIView):
serializer_class = NotificationSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, *args, **kwargs):
status = HTTP_400_BAD_REQUEST
message = NOTIFICATION_ERROR
if Notifications().delete_notification(request.data.get('notification_id'), self.request.user.id):
status = HTTP_200_OK
message = NOTIFICATION_DELETE_SUCCESS
return Response({"message": message}, status=status)
class MarkAllReadNotificationsView(APIView):
serializer_class = NotificationSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, *args, **kwargs):
status = HTTP_400_BAD_REQUEST
message = NOTIFICATION_ERROR
if Notifications().mark_all_read(self.request.user.id):
status = HTTP_200_OK
message = NOTIFICATION_ALL_READ_SUCCESS
return Response({"message": message}, status=status)
<file_sep>/accounts/models.py
from django.contrib.auth.models import AbstractUser
from django.core.validators import MinValueValidator
from django.db import models
from django.utils.translation import gettext_lazy as _
from django_countries.fields import CountryField
from phonenumber_field.modelfields import PhoneNumberField
from common.models import BaseModel
# Create your models here.
class User(AbstractUser, BaseModel):
MALE = 'male'
FEMALE = 'female'
OTHER = 'other'
GENDER_TYPE = (
(MALE, 'Male'),
(FEMALE, 'Female'),
(OTHER, 'Other'),
)
profile_qr = models.FileField(upload_to='static/user_qr_codes/', blank=True, null=True)
image = models.FileField(upload_to='static/profile_image/', null=True, blank=True)
bio = models.CharField(max_length=200, null=True, blank=True)
gender = models.CharField(max_length=20, choices=GENDER_TYPE, default=OTHER)
phone_number = PhoneNumberField(null=True, blank=True)
age = models.IntegerField(validators=[MinValueValidator(1)], default=1)
verified_account = models.BooleanField(default=False)
email = models.EmailField(_('email address'), unique=True)
date_of_birth = models.DateField(null=True, blank=True)
country = models.CharField(max_length=100, null=True, blank=True)
search_privacy = models.BooleanField(default=False)
email_verified = models.BooleanField(default=False)
otp_enabled = models.BooleanField(default=False)
image_url = models.TextField(null=True, blank=True)
def __str__(self):
return self.username
class AccountInformation(BaseModel):
user = models.ForeignKey(User, on_delete=models.CASCADE)
country = CountryField()
site_visit = models.BooleanField(default=False)
partner_info = models.BooleanField(default=False)
search_privacy = models.BooleanField(default=False)
store_contacts = models.BooleanField(default=False)
def __str__(self):
return self.user.username
class WebsiteVerification(BaseModel):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=255, null=True, blank=True)
is_verified = models.BooleanField(default=False)
def __str__(self):
return self.user.username
class FollowUser(BaseModel):
user = models.ForeignKey(User, on_delete=models.CASCADE)
follow = models.ForeignKey(User, on_delete=models.CASCADE, related_name='follower_user')
def __str__(self):
return self.user.username
class ReportUser(BaseModel):
user = models.ForeignKey(User, on_delete=models.CASCADE)
reported_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='reported_user')
def __str__(self):
return self.user.username
class BlockUser(BaseModel):
user = models.ForeignKey(User, on_delete=models.CASCADE)
blocked_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blocked_user')
def __str__(self):
return self.user.username
class Otp(BaseModel):
EMAIL = 'EMAIL'
NUMBER = 'NUMBER'
LOGIN = 'LOGIN'
VERIFY = 'VERIFY'
OTP_CHOICES = (
(EMAIL, 'EMAIL'),
(NUMBER, 'NUMBER'),
)
OTP_FOR_CHOICES = (
(VERIFY, 'VERIFY'),
(LOGIN, 'LOGIN'),
)
user = models.ForeignKey(User, on_delete=models.CASCADE)
code = models.CharField(max_length=4)
otp_type = models.CharField(max_length=255, choices=OTP_CHOICES, default=EMAIL)
otp_for = models.CharField(max_length=255, choices=OTP_FOR_CHOICES, default=VERIFY)
<file_sep>/posts/migrations/0014_auto_20201219_0850.py
# Generated by Django 3.1.1 on 2020-12-19 08:50
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('posts', '0013_auto_20201218_1309'),
]
operations = [
migrations.AlterField(
model_name='postcomment',
name='parent',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='posts.postcomment'),
),
]
<file_sep>/notifications/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('api/notifications/all', views.AllNotificationsView.as_view(), name='all-notifications.'),
path('api/notifications/read', views.ReadNotificationsView.as_view(), name='read-notifications.'),
path('api/notifications/delete', views.DeleteNotificationsView.as_view(), name='delete-notifications.'),
path('api/notifications/mark_all_read', views.MarkAllReadNotificationsView.as_view(), name='mark-all-read.'),
]
<file_sep>/posts/migrations/0005_auto_20201202_0734.py
# Generated by Django 3.1.1 on 2020-12-02 07:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0004_auto_20201123_0738'),
]
operations = [
migrations.CreateModel(
name='PostMaterial',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_valid', models.BooleanField(default=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('url', models.CharField(blank=True, max_length=150, null=True)),
('post_type', models.CharField(choices=[('VIDEO', 'VIDEO'), ('IMAGE', 'IMAGE')], default='IMAGE', max_length=20)),
],
options={
'abstract': False,
},
),
migrations.AlterField(
model_name='post',
name='image',
field=models.FileField(blank=True, max_length=254, null=True, upload_to='static/post_images'),
),
migrations.AddField(
model_name='post',
name='media_files',
field=models.ManyToManyField(to='posts.PostMaterial'),
),
]
<file_sep>/accounts/migrations/0004_auto_20200911_1103.py
# Generated by Django 3.1.1 on 2020-09-11 11:03
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0003_auto_20200910_1247'),
]
operations = [
migrations.RenameField(
model_name='followuser',
old_name='follower',
new_name='follow',
),
migrations.RenameField(
model_name='followuser',
old_name='folowing',
new_name='user',
),
]
<file_sep>/chat_app/serializers.py
from django.db.models import Q
from accounts.models import User
from django.shortcuts import get_object_or_404
from chat_app.models import MessageModel, Thread
from rest_framework.serializers import ModelSerializer, CharField
from rest_framework import serializers
from common.commmon_services import convert_time_mhr
from posts.models import Post
from posts.serializers import PostDetailSerializer
class MessageModelSerializer(ModelSerializer):
user = CharField(source='user.username', read_only=True)
recipient = CharField(source='recipient.username')
message_type = CharField()
timestamp = serializers.SerializerMethodField()
def get_timestamp(self, obj):
return convert_time_mhr(obj.timestamp)
def create(self, validated_data):
if 'user' not in validated_data.keys():
user = self.context['request'].user
else:
user = User.objects.filter(id=validated_data['user']).first()
recipient = get_object_or_404(
User, username=validated_data['recipient']['username'])
if validated_data.get('thread'):
msg = MessageModel(recipient=recipient,
body=validated_data['body'], thread=validated_data.get('thread'),
user=user, message_type=validated_data['message_type'])
else:
group_name = f'{user.id}-{recipient.id}' if user.id < recipient.id else \
f'{recipient.id}-{user.id}'
is_thread_exist = Thread.objects.filter(title=group_name).exists()
if not is_thread_exist:
Thread.objects.create(user=user, recipient=recipient, title=group_name)
thread_obj = Thread.objects.filter(Q(recipient=recipient, user=user) |
Q(recipient=user, user=recipient)).first()
msg = MessageModel(recipient=recipient,
body=validated_data['body'], thread=thread_obj,
user=user, message_type=validated_data['message_type'])
msg.save()
return msg
class Meta:
model = MessageModel
fields = ('id', 'user', 'recipient', 'timestamp', 'body', 'message_type', 'read_receipt')
class UserModelSerializer(ModelSerializer):
_id = serializers.IntegerField(source='id')
avatar = serializers.URLField(source="image")
name = serializers.SerializerMethodField()
message = serializers.SerializerMethodField()
def get_name(self, obj):
return '{} {}'.format(obj.first_name, obj.last_name)
def get_message(self, obj):
data = {}
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
message = MessageModel.objects.filter(Q(user=obj, recipient=user) | Q(recipient=obj, user=user)).last()
if message:
data['body'] = message.body
data['time'] = convert_time_mhr(message.timestamp)
data['type'] = message.message_type
data['read_receipt'] = message.read_receipt
return data
else:
return ''
class Meta:
model = User
fields = ('username', 'name', '_id', 'avatar', 'username', 'first_name', 'last_name', 'message')
class MessageReaderSerializer(serializers.ModelSerializer):
_id = serializers.IntegerField(source='id')
current_user = UserModelSerializer(source='user')
user = UserModelSerializer(source='recipient')
text = serializers.CharField(source='body')
createdAt = serializers.SerializerMethodField()
post_detail = serializers.SerializerMethodField()
read_receipt = serializers.SerializerMethodField()
def get_createdAt(self, obj):
return convert_time_mhr(obj.timestamp)
def get_post_detail(self, obj):
if obj.message_type == MessageModel.POST_URL:
id = obj.body.split('?id=')[1]
return PostDetailSerializer(Post.objects.filter(id=id).first()).data
else:
return None
def get_read_receipt(self, obj):
if not obj.read_receipt:
obj.read_receipt = True
obj.save()
return obj.read_receipt
class Meta:
model = MessageModel
fields = ('current_user', 'user', '_id', 'text', 'createdAt', 'message_type', 'post_detail', 'read_receipt')
class ThreadSerializer(serializers.ModelSerializer):
class Meta:
model = Thread
fields = '__all__'<file_sep>/chat_app/consumers.py
# chat/consumers.py
from asgiref.sync import sync_to_async
from channels.generic.websocket import AsyncWebsocketConsumer
import json
from accounts.models import User
from chat_app.models import Thread, MessageModel
from chat_app.serializers import MessageModelSerializer, ThreadSerializer
from common.commmon_services import convert_time_mhr
def check_is_thread_exists(group_name):
return Thread.objects.filter(title=group_name).exists()
def create_thread(group_name, user_id, other_user_id):
return Thread.objects.create(title=group_name, user=User.objects.filter(id=user_id).first(),
recipient=User.objects.filter(id=other_user_id).first())
def get_thread_users(title):
thread = Thread.objects.filter(title=title).first()
return {'user': thread.user, 'recipient': thread.recipient}
def get_thread(group_name):
thread = Thread.objects.filter(title=group_name).first()
return {'thread': thread}
def get_user(id):
return User.objects.filter(id=id).first()
class ChatConsumer(AsyncWebsocketConsumer):
async def connect(self):
user_id = self.scope["user_id"]
other_user_id = self.scope["other_user"]
self.group_name = f'{user_id[0]}-{other_user_id}' if user_id[0] < other_user_id else \
f'{other_user_id}-{user_id[0]}'
is_thread_available = await sync_to_async(check_is_thread_exists)(self.group_name)
if not is_thread_available:
await sync_to_async(create_thread)(self.group_name, user_id[0], other_user_id)
await self.channel_layer.group_add(
self.group_name,
self.channel_name
)
await self.accept()
async def disconnect(self, close_code):
# Leave room group
await self.channel_layer.group_discard(
self.group_name,
self.channel_name
)
# Receive message from WebSocket
async def receive(self, text_data=None, bytes_data=None):
text_data_json = json.loads(text_data)
message = text_data_json['message']
type = text_data_json['type']
data = {}
data['body'] = text_data_json['message']
users = await sync_to_async(get_thread_users)(self.group_name)
data['user'] = self.scope['user_id']
rec = await sync_to_async(get_user)(self.scope['other_user'])
data['recipient'] = {'username': rec.username}
data['message_type'] = type
thread = await sync_to_async(get_thread)(self.group_name)
data['thread'] = thread.get('thread')
message_serializer = MessageModelSerializer()
new_message = await sync_to_async(message_serializer.create)(data)
message = {}
message['_id'] = new_message.id
message['current_user'] = {}
message['current_user']['_id'] = new_message.user.id
message['current_user']['username'] = new_message.user.username
message['current_user']['name'] = new_message.user.first_name + ' ' + new_message.user.last_name
message['current_user']['avatar'] = new_message.user.image_url
message['user'] = {}
message['user']['_id'] = new_message.recipient.id
message['user']['username'] = new_message.recipient.username
message['user']['name'] = new_message.recipient.first_name + ' ' + new_message.recipient.last_name
message['user']['avatar'] = new_message.recipient.image_url
# message['recipient'] = new_message.recipient.username
message['text'] = new_message.body
message['message_type'] = new_message.message_type
message['createdAt'] = convert_time_mhr(new_message.timestamp)
message['read_receipt'] = new_message.read_receipt
# Send message to room group
await self.channel_layer.group_send(
self.group_name,
{
'type': 'message',
'message': message
}
)
async def message(self, event):
message = event['message']
await self.send(
text_data=json.dumps({
'message': message
}))
<file_sep>/accounts/urls.py
from django.conf.urls import include, url
from django.urls import path, re_path
from drf_jwt_2fa.views import (obtain_auth_token, obtain_code_token, refresh_auth_token, verify_auth_token)
from rest_framework_jwt.views import refresh_jwt_token, verify_jwt_token, obtain_jwt_token
from . import views
urlpatterns = [
path('api/user/register', views.UserCreate.as_view(), name='account-create'),
path('api/user/get_user', views.UserExistsView.as_view(), name='user-exists'),
path('api/user/profile', views.UserProfileView.as_view(), name='account-profile'),
path('api/user/deactivate', views.UserDeactivateView.as_view(), name='account-deactivate'),
path('api/user/information', views.AccountInformationView.as_view(), name='user-info'),
path('api/user/webitelink', views.WebsiteVerificationView.as_view(), name='user-webiste'),
path('api/user/opt_toggle', views.OtpEmailToggleView.as_view(), name='user-otp-email'),
path('api/user/otp_email_verified', views.OtpEmailVerifyView.as_view(), name='user-otp-email'),
path('api/user/change_password', views.ChangePasswordView.as_view(), name='change-password'),
path('api/user/login', obtain_jwt_token),
path('refresh-token', refresh_jwt_token),
re_path(r'^api-token-refresh/', refresh_jwt_token),
re_path(r'^api-token-verify/', verify_jwt_token),
url(r'^api/user/password_reset/', include('django_rest_passwordreset.urls', namespace='password_reset')),
path('api/user/report', views.UserReportView.as_view(), name='user-report'),
path('api/user/block', views.UserBlockView.as_view(), name='user-block'),
path('api/user/unblock', views.UserUnBlockView.as_view(), name='user-unblock'),
path('api/user/follow', views.UserFollowView.as_view(), name='follow-user'),
path('api/user/unfollow', views.UserUnFollowView.as_view(), name='unfollow-user'),
path('api/user/followings', views.FollowingUsersView.as_view(), name='following-followers-users'),
path('api/user/blocked_list', views.BlockedUsersListView.as_view(), name='blocked-user-list'),
path('api/user/report_list', views.ReportUsersListView.as_view(), name='report-user-list'),
url(r'^api/user/login/2fa/get-code-token/', obtain_code_token),
url(r'^api/user/confirmation/2fa/get-auth-token/', obtain_auth_token),
url(r'^api/user/2fa/refresh/', refresh_auth_token),
url(r'^api/user/2fa/verify/', verify_auth_token),
path('api/user/search', views.SearchUsersListView.as_view(), name='search-users'),
path('api/user/signup_otp_email_verified', views.SignupOtpEmailVerifyView.as_view(), name='signup-otp-email'),
]
<file_sep>/categories/admin.py
from django.contrib import admin
# Register your models here.
from categories import models
admin.site.register(models.Category)
admin.site.register(models.SelectedCategories)
<file_sep>/chat_app/migrations/0002_auto_20201230_1348.py
# Generated by Django 3.1.1 on 2020-12-30 13:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('chat_app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Thread',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_valid', models.BooleanField(default=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('title', models.CharField(max_length=5)),
],
options={
'abstract': False,
},
),
migrations.AlterModelOptions(
name='messagemodel',
options={'ordering': ('timestamp',), 'verbose_name_plural': 'messages'},
),
migrations.AddField(
model_name='messagemodel',
name='thread',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='chat_app.thread'),
),
]
<file_sep>/posts/migrations/0010_auto_20201203_1044.py
# Generated by Django 3.1.1 on 2020-12-03 10:44
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('posts', '0009_auto_20201203_0811'),
]
operations = [
migrations.AddField(
model_name='postcomment',
name='mentioned_users',
field=models.ManyToManyField(blank=True, null=True, related_name='mentioned_users', to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='postcomment',
name='comment',
field=models.TextField(),
),
]
<file_sep>/dashboard/forms.py
from django import forms
class LoginForm(forms.Form):
username = forms.CharField(
widget=forms.TextInput(attrs={'name': "uname", 'class': 'fadeIn second', 'placeholder': '<NAME>'}))
password = forms.CharField(
widget=forms.PasswordInput(attrs={'name': "psw", 'class': 'fadeIn third', 'placeholder': '<PASSWORD>'}))
<file_sep>/chat_app/admin.py
from django.contrib import admin
# Register your models here.
from chat_app.models import MessageModel, Thread
admin.site.register(MessageModel)
admin.site.register(Thread)
<file_sep>/categories/migrations/0003_category_child.py
# Generated by Django 3.1.1 on 2020-12-15 08:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('categories', '0002_selectedcategories'),
]
operations = [
migrations.AddField(
model_name='category',
name='child',
field=models.ManyToManyField(blank=True, null=True, related_name='_category_child_+', to='categories.Category'),
),
]
<file_sep>/categories/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('api/category/create', views.CategoryCreateView.as_view(), name='category-create'),
path('api/category/all', views.AllCategoriesView.as_view(), name='category-all'),
path('api/category/selection', views.SelectCategoriesView.as_view(), name='category-select'),
path('api/category/other', views.OtherCategoriesView.as_view(), name='other-category'),
]
<file_sep>/chat_app/migrations/0005_messagemodel_read_receipt.py
# Generated by Django 3.1.1 on 2021-01-30 15:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('chat_app', '0004_auto_20210125_0822'),
]
operations = [
migrations.AddField(
model_name='messagemodel',
name='read_receipt',
field=models.BooleanField(default=True),
),
]
<file_sep>/stories/migrations/0002_auto_20201202_0715.py
# Generated by Django 3.1.1 on 2020-12-02 07:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stories', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='story',
name='story_type',
field=models.CharField(choices=[('VIDEO', 'VIDEO'), ('IMAGE', 'IMAGE')], default='IMAGE', max_length=20),
),
migrations.AddField(
model_name='story',
name='url',
field=models.CharField(blank=True, max_length=150, null=True),
),
migrations.AlterField(
model_name='story',
name='file',
field=models.FileField(blank=True, max_length=254, null=True, upload_to='static/story_files'),
),
]
<file_sep>/notifications/migrations/0006_auto_20201222_1207.py
# Generated by Django 3.1.1 on 2020-12-22 12:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('notifications', '0005_auto_20201203_0916'),
]
operations = [
migrations.AlterField(
model_name='notification',
name='notification_type',
field=models.CharField(choices=[('mention_comment', 'Mention Comment'), ('following', 'Following'), ('like_post', 'Like Post'), ('comment_post', 'Comment Post'), ('rate_story', 'Rate Story'), ('rate_post', 'Rate Post'), ('rate_comment', 'Rate Comment'), ('reply_comment', 'Reply Comment'), ('chat_started', 'Chat Started'), ('group_chat_add', 'Group Chat Add')], max_length=250),
),
]
<file_sep>/accounts/services.py
import string
from random import choice
from RestProject import settings
from accounts.models import FollowUser, BlockUser, ReportUser, User, AccountInformation, WebsiteVerification, Otp
from accounts.serializers import UserSerializer
from common.email_services import Email
class UserManagement(object):
def get_user_by_email(self, email):
return User.objects.filter(email=email).first()
def get_all_active_users(self):
return User.objects.filter(is_active=True, is_valid=True, is_superuser=False)
def get_user(self, id):
return User.objects.filter(id=id).first()
def get_users_by_user_list(self, user_ids):
return User.objects.filter(id__in=user_ids)
def get_followings_users(self, user):
return FollowUser.objects.filter(user=user, is_valid=True).values_list('follow', flat=True)
def get_followings(self, user):
return FollowUser.objects.filter(user=user, is_valid=True)
def get_followers(self, user):
return FollowUser.objects.filter(follow=user, is_valid=True)
def get_blockUser(self, data, user):
return BlockUser.objects.filter(user=user, blocked_user=data.get('blocked_user')).first()
def get_user_follow(self, data, user):
return FollowUser.objects.filter(user=user, follow=data.get('follow')).first()
def get_user_reported(self, data, user):
return ReportUser.objects.filter(user=user, reported_user=data.get('reported_user')).first()
def get_user_reported_list(self, user):
return ReportUser.objects.filter(user=user, is_valid=True)
def get_user_blocked_list(self, user):
return BlockUser.objects.filter(user=user, is_valid=True)
def get_user_from_blocked_list(self, user):
return BlockUser.objects.filter(user=user, is_valid=True).values_list('blocked_user__id', flat=True)
def search_users_by_username(self, username, current_user):
return User.objects.filter(username__icontains=username, is_valid=True).order_by('-id').exclude(
id=current_user).exclude(is_superuser=True).exclude(id__in=self.get_user_from_blocked_list(current_user))
def get_account_info_by_user(self, user):
account_info = AccountInformation.objects.filter(user__id=user.id).first()
if not account_info:
user = self.get_user(user.id)
account_info = AccountInformation(user=user)
account_info.save()
return account_info
def get_webiste_by_user(self, user):
return WebsiteVerification.objects.filter(user__id=user.id).first()
def update_user_gender(self, user, gender):
user = self.get_user(user)
if gender == User.MALE:
user.gender = User.MALE
elif gender == User.FEMALE:
user.gender = User.FEMALE
elif gender == User.OTHER:
user.gender = User.OTHER
user.save()
def send_otp_email(self, user_id):
user = self.get_user(user_id)
chars = string.digits
code = ''.join(choice(chars) for _ in range(4))
otp = Otp.objects.create(user=user, code=code)
otp.save()
Email().send_otp_email(user, otp.code)
from django.core.mail import EmailMultiAlternatives
from django.dispatch import receiver
from django.template.loader import render_to_string
from django_rest_passwordreset.signals import reset_password_token_created
@receiver(reset_password_token_created)
def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs):
"""
Handles password reset tokens
When a token is created, an e-mail needs to be sent to the user
:param sender: View Class that sent the signal
:param instance: View Instance that sent the signal
:param reset_password_token: Token Model Object
:param args:
:param kwargs:
:return:
"""
# send an e-mail to the user
context = {
'current_user': reset_password_token.user,
'username': reset_password_token.user.username,
'email': reset_password_token.user.email,
# 'reset_password_url': "{}?token={}".format('https://nitrx.com/update_password', reset_password_token.key)
'reset_password_url': "{}?token={}".format('http://localhost:3000/update_password', reset_password_token.key)
}
# render email text
email_html_message = render_to_string('email/user_reset_password.html', context)
email_plaintext_message = render_to_string('email/user_reset_password.txt', context)
msg = EmailMultiAlternatives(
# title:
"Password Reset for {title}".format(title="Nitrx"),
# message:
email_plaintext_message,
# from:
settings.EMAIL_HOST_USER,
# to:
[reset_password_token.user.email]
)
msg.attach_alternative(email_html_message, "text/html")
msg.send()
def jwt_response_payload_handler(token, user=None, request=None):
if user.otp_enabled:
UserManagement().send_otp_email(user.id)
return {
'token': token,
'user': UserSerializer(user, context={'request': request}).data
}
<file_sep>/stories/serializers.py
from datetime import datetime
from django.template.loader import render_to_string
from rest_framework import serializers
from accounts.models import User
from accounts.serializers import UserSerializer
from common.commmon_services import convert_time_mhr, convert_time
from stories.models import Story, StoryView, StoryRating
from stories.services import StoryManagement
class StorySerializer(serializers.ModelSerializer):
class Meta:
model = Story
exclude = ('is_valid', 'expire_at',)
class StoryViewSerializer(serializers.ModelSerializer):
class Meta:
model = StoryView
exclude = ('is_valid',)
def create(self, data):
return StoryView.objects.update_or_create(story=data['story'], user=data['user'])
class StoryDetailSerializer(serializers.ModelSerializer):
viewers = serializers.SerializerMethodField()
created_at = serializers.SerializerMethodField()
rates = serializers.SerializerMethodField()
rated = serializers.SerializerMethodField()
finish = serializers.SerializerMethodField()
class Meta:
model = Story
fields = '__all__'
def get_viewers(self, obj):
users = StoryManagement().get_story_viewers_by_story_id(obj.id)
return UserSerializer(User.objects.filter(id__in=users), many=True).data
def get_created_at(self, obj):
return convert_time_mhr(obj.created_at)
def get_rates(self, obj):
return StoryRateSerializer(StoryRating.objects.filter(is_valid=True, story=obj), many=True).data
def get_rated(self, obj):
if self.context.get('user_id'):
is_rated = StoryRating.objects.filter(is_valid=True, story=obj,
user_rated__id=self.context.get('user_id')).first()
if is_rated:
return True
return False
def get_finish(self, obj):
return 0
class StoryDetailByUserSerializer(serializers.ModelSerializer):
stories = serializers.SerializerMethodField()
class Meta:
model = User
fields = ('id', 'username', 'stories', 'image_url')
def get_stories(self, obj):
return StoryDetailSerializer(
Story.objects.filter(user__id=obj.id, is_valid=True, expire_at__gte=datetime.today()).order_by(
'-id'), context={'user_id': self.context.get('user_id')}, many=True).data
class StoryRateSerializer(serializers.ModelSerializer):
profile_image = serializers.SerializerMethodField()
user_detail = serializers.SerializerMethodField()
created_at = serializers.SerializerMethodField()
content = serializers.SerializerMethodField()
class Meta:
model = StoryRating
exclude = ('is_valid', 'updated_at',)
def get_profile_image(self, obj):
return obj.user_rated.image_url
def get_content(self, obj):
return render_to_string('story_rate.html', {'instance': obj})
def get_user_detail(self, obj):
return UserSerializer(User.objects.filter(id=obj.user_rated.id).first()).data
def get_created_at(self, obj):
return convert_time(obj.created_at)
<file_sep>/accounts/migrations/0011_auto_20201219_0731.py
# Generated by Django 3.1.1 on 2020-12-19 07:31
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0010_auto_20201112_0625'),
]
operations = [
migrations.AddField(
model_name='user',
name='email_verified',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='user',
name='otp_enabled',
field=models.BooleanField(default=False),
),
migrations.CreateModel(
name='Otp',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('is_valid', models.BooleanField(default=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('code', models.CharField(max_length=4)),
('otp_type', models.CharField(choices=[('EMAIL', 'EMAIL'), ('NUMBER', 'NUMBER')], default='EMAIL', max_length=255)),
('otp_for', models.CharField(choices=[('VERIFY', 'VERIFY'), ('LOGIN', 'LOGIN')], default='VERIFY', max_length=255)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
<file_sep>/chat_app/routing.py
from django.conf.urls import url
from django.urls import path
from . import consumers
websocket_urlpatterns = [
path('ws/', consumers.ChatConsumer),
# url(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()),
]
<file_sep>/dashboard/views.py
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render, redirect
# Create your views here.
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView
from RestProject.decorators import staff_required
from accounts.models import User
from accounts.services import UserManagement
from dashboard.forms import LoginForm
from dashboard.services import DashboardService
from posts.models import Post
from posts.services import PostManagement
@method_decorator(staff_required, name='dispatch')
class DashBoardView(LoginRequiredMixin, TemplateView):
template_name = 'dashboard.html'
def get_context_data(self, **kwargs):
total_users = User.objects.filter(is_active=True, is_valid=True)
kwargs.setdefault('view', self)
posts = Post.objects.all()
for post in posts:
post.__setattr__('post_media', post.media_files.first().url)
post.__setattr__('impressions', post.postimpressions_set.count)
post.__setattr__('total_audience', post.postlike_set.count() + post.postrating_set.count() +
post.postview_set.count())
post.__setattr__('engaged_audience', post.postlike_set.count() + post.postrating_set.count() +
post.postview_set.count())
kwargs['posts'] = posts
kwargs['total_users'] = total_users
kwargs['active_users'] = DashboardService().get_logged_in_users()
return kwargs
@method_decorator(staff_required, name='dispatch')
class DashBoardUsersView(LoginRequiredMixin, TemplateView):
template_name = 'users.html'
def get_context_data(self, **kwargs):
user_posts = []
total_users = UserManagement().get_all_active_users()
for user in total_users:
user_posts.append(PostManagement().get_user_posts(user).count())
kwargs.setdefault('view', self)
kwargs['total_users'] = zip(total_users, user_posts)
return kwargs
def dashboard_login_view(request):
form = LoginForm(request.POST or None)
msg = None
if request.user and request.user.is_authenticated:
return redirect('dashboard')
if request.method == "POST":
if form.is_valid():
username = form.cleaned_data.get("username")
password = form.cleaned_data.get("password")
user = authenticate(username=username, password=password)
if user is not None and user.is_superuser:
login(request, user)
return redirect("dashboard")
else:
msg = 'Invalid credentials'
else:
msg = 'Invalid credentials'
return render(request, "login.html", {"form": form, "msg": msg})
def dashboard_logout_view(request):
logout(request)
return redirect(reverse('dashboard-login'))
<file_sep>/common/models.py
from django.db import models
# Create your models here.
class BaseModel(models.Model):
is_valid = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class AppName(models.Model):
PRODUCTION = 'PRODUCTION'
DEVELOPMENT = 'DEVELOPMENT'
name_type_choices = (
(DEVELOPMENT, 'DEVELOPMENT'),
(PRODUCTION, 'PRODUCTION'),
)
host_name = models.CharField(max_length=255)
type = models.CharField(max_length=255, choices=name_type_choices, default=DEVELOPMENT, unique=True)
def __str__(self):
return self.host_name
<file_sep>/stories/views.py
import datetime as deltadays
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST, HTTP_201_CREATED
from rest_framework.views import APIView
from RestProject.constants import (STORY_CREATED_SUCCESS, STORY_VIEWED_SUCCESS, STORY_DELETED_SUCCESS,
STORY_DELETED_ERROR, STORY_RATED_SUCCESS, STORY_RATED_ERROR)
from accounts.services import UserManagement
from notifications.models import Notification
from notifications.services import Notifications
from stories.serializers import (StorySerializer, StoryViewSerializer, StoryDetailSerializer,
StoryDetailByUserSerializer, StoryRateSerializer)
from stories.services import StoryManagement
class StoryCreateView(APIView):
serializer_class = StorySerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
dict = request.data.copy()
dict['user'] = self.request.user.id
media_list = request.data.get('media_list')
for media in media_list:
dict['url'] = media.get('url')
dict['story_type'] = media.get('story_type')
serializer = self.serializer_class(data=dict)
if serializer.is_valid():
story = serializer.save()
story.expire_at = story.created_at + deltadays.timedelta(days=1)
story.save()
return Response({"message": STORY_CREATED_SUCCESS}, status=status.HTTP_201_CREATED)
class ViewStoryView(APIView):
serializer_class = StoryViewSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
dict = request.data.copy()
dict['user'] = self.request.user.id
serializer = self.serializer_class(data=dict)
if serializer.is_valid():
serializer.save()
return Response({"message": STORY_VIEWED_SUCCESS}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class StoryDetailView(APIView):
serializer_class = StoryDetailSerializer
permission_classes = (IsAuthenticated,)
def get(self, request, format='json'):
id = request.data.get('story_id')
return Response(self.serializer_class(StoryManagement().get_story_by_id(id)).data, status=status.HTTP_200_OK)
class StoryDeleteView(APIView):
serializer_class = StorySerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
story = StoryManagement().get_self_story_by_id(request.data.get('story_id'), self.request.user)
message = STORY_DELETED_ERROR
status = HTTP_400_BAD_REQUEST
if story and story.is_valid:
story.is_valid = False
story.save()
message = STORY_DELETED_SUCCESS
status = HTTP_200_OK
return Response({'message': message}, status=status)
class AllStoriesView(APIView):
serializer_class = StoryDetailByUserSerializer
permission_classes = (IsAuthenticated,)
def get(self, request, format='json'):
blocked_users = UserManagement().get_user_from_blocked_list(self.request.user)
following_users = UserManagement().get_followings_users(self.request.user).exclude(follow__id__in=blocked_users)
user_ids = [user_id for user_id in following_users]
user_ids.append(self.request.user.id)
user_ids = StoryManagement().get_stories_by_user_group(user_ids)
users = UserManagement().get_users_by_user_list(user_ids)
return Response(self.serializer_class(users, context={'user_id': request.user.id}, many=True).data,
status=HTTP_200_OK)
class StoryRateView(APIView):
serializer_class = StoryRateSerializer
permission_classes = (IsAuthenticated,)
def post(self, request, format='json'):
dict = self.request.data.copy()
dict['user_rated'] = self.request.user.id
story_rate = StoryManagement().get_story_rate_by_id(request.data.get('story'), self.request.user.id)
message = STORY_RATED_SUCCESS
status = HTTP_201_CREATED
if not story_rate:
serializer = self.serializer_class(data=dict)
if serializer.is_valid():
story_rate = serializer.save()
story = StoryManagement().get_story_by_id(request.data.get('story'))
story_creator = UserManagement().get_user(story.user.id)
Notifications().create_notification(story_creator, Notification.RATE_STORY, story_rate)
else:
return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
elif request.data.get('rating') in ['1', '3', '5', '7', '10']:
story_rate.rating = request.data.get('rating')
story_rate.save()
else:
message = STORY_RATED_ERROR
status = HTTP_400_BAD_REQUEST
return Response({"message": message}, status=status)
<file_sep>/accounts/admin.py
from django.contrib import admin
# Register your models here.
from accounts import models
admin.site.register(models.User)
admin.site.register(models.FollowUser)
admin.site.register(models.ReportUser)
admin.site.register(models.BlockUser)
admin.site.register(models.AccountInformation)
admin.site.register(models.WebsiteVerification)
admin.site.register(models.Otp)
<file_sep>/categories/serializers.py
from rest_framework import serializers
from categories.models import Category, SelectedCategories
class CategorySerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = '__all__'
childs = serializers.SerializerMethodField()
collapsed = serializers.SerializerMethodField()
def get_childs(self, obj):
return CategoryChildSerializer(Category.objects.filter(parent=obj), many=True).data
def get_collapsed(self, obj):
return False
class CategoryChildSerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = '__all__'
class SelectCategorySerializer(serializers.ModelSerializer):
category_details = serializers.SerializerMethodField()
class Meta:
model = SelectedCategories
fields = '__all__'
def get_category_details(self, obj):
return CategorySerializer(obj.categories, many=True).data
<file_sep>/posts/services.py
from django.db.models import Q
from accounts.services import UserManagement
from categories.models import SelectedCategories
from posts.models import Post, BlacklistPost, PostLike, PostRating, PostComment, CommentRating
class PostManagement(object):
def get_user_posts(self, user):
return Post.objects.filter(creator=user, is_valid=True)
def get_reported_posts(self, user):
return BlacklistPost.objects.filter(is_valid=True, user_reported=user).values_list('post__id', flat=True)
def get_non_reported_posts(self, users, self_user):
return Post.objects.filter(is_valid=True, creator__in=users).exclude(id__in=self.get_reported_posts(self_user))
def get_post_detail(self, post_id):
return Post.objects.filter(is_valid=True, id=post_id).first()
def get_post_by_category(self, category_id, self_user):
if category_id:
category_ids = category_id.split(',')
else:
selected_categories = SelectedCategories.objects.filter(user__id=self_user.id).first()
category_ids = selected_categories.categories.all().values_list('id', flat=True)
posts = Post.objects.filter(is_valid=True, category__id__in=category_ids).exclude(
id__in=self.get_reported_posts(self_user))
return posts.exclude(creator__id__in=UserManagement().get_user_from_blocked_list(self_user)).order_by('-id')
def search_posts(self, data, self_user):
return Post.objects.filter(
(Q(title__icontains=data) | Q(description__icontains=data) | (Q(keywords__icontains=data))),
is_valid=True).exclude(id__in=self.get_reported_posts(self_user)).distinct().order_by('-id')
def get_postlike_by_user(self, post_id, user_id):
return PostLike.objects.filter(user_liked__id=user_id, post__id=post_id).first()
def get_post_rate_by_user(self, user_id, post_id):
return PostRating.objects.filter(user_rated__id=user_id, post__id=post_id).first()
def get_comment_by_id(self, id):
return PostComment.objects.filter(id=id).first()
def get_rate_by_id_user(self, id, user_id):
return CommentRating.objects.filter(comment__id=id, user_rated__id=user_id).first()
<file_sep>/posts/admin.py
from django.contrib import admin
# Register your models here.
from posts import models
admin.site.register(models.Post)
admin.site.register(models.PostLike)
admin.site.register(models.PostComment)
admin.site.register(models.PostRating)
admin.site.register(models.BlacklistPost)
admin.site.register(models.PostView)
admin.site.register(models.PostMaterial)
admin.site.register(models.PostSave)
admin.site.register(models.CommentRating)
admin.site.register(models.PostImpressions)
<file_sep>/categories/views.py
from rest_framework import status, generics
from rest_framework.permissions import IsAdminUser, IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from RestProject.constants import (CATEGORY_CREATED_SUCCESS, CATEGORY_ADDED_SUCCESS)
from categories.models import (Category, SelectedCategories)
from categories.serializers import (CategorySerializer, SelectCategorySerializer)
class CategoryCreateView(APIView):
serializer_class = CategorySerializer
permission_classes = (IsAuthenticated, IsAdminUser)
def post(self, request, format='json'):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
serializer.save()
return Response({"message": CATEGORY_CREATED_SUCCESS}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class AllCategoriesView(generics.ListAPIView):
queryset = Category.objects.filter(is_valid=True, parent__isnull=True)
serializer_class = CategorySerializer
permission_classes = [IsAuthenticated, ]
class SelectCategoriesView(APIView):
serializer_class = SelectCategorySerializer
permission_classes = (IsAuthenticated,)
def get_object(self):
return SelectedCategories.objects.filter(user=self.request.user, is_valid=True).first()
def post(self, request, format='json'):
data = self.request.data.copy()
data['user'] = self.request.user.id
serializer = self.serializer_class(data=data)
if serializer.is_valid():
serializer.save()
return Response({"message": CATEGORY_ADDED_SUCCESS}, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request):
serializer = self.serializer_class(self.get_object())
return Response(serializer.data, status=status.HTTP_200_OK)
class OtherCategoriesView(APIView):
serializer_class = CategorySerializer
permission_classes = (IsAuthenticated,)
def get_object(self):
selected_categories = SelectedCategories.objects.filter(user=self.request.user, is_valid=True).first()
return Category.objects.filter(is_valid=True).exclude(
id__in=selected_categories.categories.all().values_list('id', flat=True))
def get(self, request):
serializer = self.serializer_class(self.get_object(), many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
| ecef1113bed9dc9f8d0cb2c38f2842442a816d56 | [
"Markdown",
"Python",
"Text"
] | 79 | Python | Junaid522/Nitrx | 7cf2c5810d5a2e7e2666b2cc53065b6a8b10fa55 | b4c53643023e61a9e92e4c27ce8a500378efa7f9 |
refs/heads/main | <repo_name>fengzi91/livewire-alert<file_sep>/README.md
<h1 align="center"> livewire-alert </h1>
[](https://travis-ci.com/fengzi91/livewire-alert)

<p align="center"> livewire alert 组件.</p>
## Installing
```shell
$ composer require zys/livewire-alert -vvv
```
## Requirements
This package uses Livewire under the hood. Please make sure you include it in your dependencies before using this package.
- PHP 7.2 or higher
- Laravel 8
- Livewire
- tailwindcss
## Usage
Add livewire-alert component
```html
<body>
...
@livewire('livewire-alert')
</body>
```
Show message in livewire component
```php
public function showMessage()
{
...
$this->alert('info', 'Message~', ['content' => 'Message Content', 'timeout' => 3000]);
}
```
Show Message in javascript
```javascript
window.livewire.emitTo('livewire-alert', 'livewireAlert', {
type: 'info',
message: 'Message',
options: {
content: 'Message content~',
timeout: 3000,
}
})
```
## Contributing
You can contribute in one of three ways:
1. File bug reports using the [issue tracker](https://github.com/zys/livewire-alert/issues).
2. Answer questions or fix bugs on the [issue tracker](https://github.com/zys/livewire-alert/issues).
3. Contribute new features or update the wiki.
_The code contribution process is not very formal. You just need to make sure that you follow the PSR-0, PSR-1, and PSR-2 coding guidelines. Any new code contributions must be accompanied by unit tests where applicable._
## License
MIT<file_sep>/tests/AlertTest.php
<?php
namespace Zys\LivewireAlert\Test;
use Illuminate\Support\Str;
use Orchestra\Testbench\TestCase;
use Livewire\Livewire;
class AlertTest extends TestCase
{
protected function getPackageProviders($app)
{
return ['Livewire\LivewireServiceProvider', 'Zys\LivewireAlert\ServiceProvider'];
}
public function testCanShowAMessage()
{
$message = Str::random();
Livewire::test('livewire-alert')
->assertNotSet('message', $message)
->call('livewireAlert', ['type' => 'info', 'message' => $message])
->assertSet('message', $message);
}
}<file_sep>/src/Alert.php
<?php
namespace Zys\LivewireAlert;
use Livewire\Component;
class Alert extends Component
{
public $title = null;
public $message = null;
public $timeout = 3000;
public $isShow = false;
public $type = 'primary';
public $options = [];
protected $listeners = ['livewireAlert'];
public function mount()
{
$this->options = config('livewire-alert');
}
public function livewireAlert($message = [])
{
if (isset($message['options'])) {
$this->options = array_merge($this->options, $message['options']);
}
$this->fill($message);
$this->emitSelf('show');
}
public function show()
{
$this->isShow = true;
}
public function hide()
{
$this->isShow = false;
}
public function render()
{
return view('livewire-alert::alert');
}
}<file_sep>/src/ServiceProvider.php
<?php
namespace Zys\LivewireAlert;
use Illuminate\Support\ServiceProvider as Service;
use Livewire\Livewire;
use Livewire\Component;
class ServiceProvider extends Service
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(__DIR__ . '/../config/config.php', 'livewire-alert');
$this->registerAlertMacro();
}
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$this->loadViewsFrom(__DIR__.'/resources/views', 'livewire-alert');
Livewire::component('livewire-alert', Alert::class);
$this->registerPublishables();
}
public function registerAlertMacro()
{
Component::macro('alert', function ($type = 'success', $message = '', $options = []) {
$options = array_merge(config('livewire-alert'), $options);
$this->emitTo('livewire-alert', 'livewireAlert', [
'type' => $type,
'message' => $message,
'options' => $options
]);
});
}
public function registerPublishables()
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__ . '/../config/config.php' => config_path('livewire-alert.php'),
], 'config');
}
}
}
<file_sep>/config/config.php
<?php
return [
'timeout' => 3000,
]; | aa3974a9651b43f31ed1ce9f50514e94e2607551 | [
"Markdown",
"PHP"
] | 5 | Markdown | fengzi91/livewire-alert | 7612c62820e6dbc08cf283c6ab3d3bc950b639b9 | 56e91ce1f2e3f0bb7d1f93aabb9a7d10c3b7c978 |
refs/heads/master | <file_sep>module.exports = (playerName, score, questionIndex, totalQuestions, questionName, opts) => {
let str = `
<link rel="stylesheet" href="./assets/css/questionPre.css" />
<div class="header">
<div class="headPad">
<div class="quizProgress" id="quizProgress">${questionIndex+1} of ${totalQuestions}</div>
`;
if (questionName == "") {
str += `<div class="currentQuestionType" id="currentQuestionType">Please open the settings and type either a quiz name or an id.</div>`
} else {
str += `<div class="currentQuestionType" id="currentQuestionType">${questionName} (Edit in settings)</div>`
}
if (opts.customText == "NORMAL") {
str += `
</div>
</div>
<div class="main">
<div class="text">Question ${questionIndex+1}</div>
<div class="parent-circle"><div class="loading-circle"></div></div>
<div class="text2">Ready...</div>
</div>
<div class="footer">
<div class="name" id="nickname">${playerName}</div>
<div class="score" id="score">${score}</div>
</div>
`
} else if (opts.customText == "NOT_QUIZ") {
str += `
</div>
</div>
<div class="main">
<div class="text">No need to answer.</div>
<div class="parent-circle"><div class="loading-circle"></div></div>
<div class="text2">Please wait...</div>
</div>
<div class="footer">
<div class="name" id="nickname">${playerName}</div>
<div class="score" id="score">${score}</div>
</div>
`
} else if (opts.customText == "WAITING") {
str += `
</div>
</div>
<div class="main">
<div class="text">You answered this question</div>
<div class="parent-circle"><div class="loading-circle"></div></div>
<div class="text2">Waiting for others to answer...</div>
</div>
<div class="footer">
<div class="name" id="nickname">${playerName}</div>
<div class="score" id="score">${score}</div>
</div>
`
}
return str;
}<file_sep>module.exports = (nickname) => {
return `
<div class="main">
<div class="text">Get Ready!</div>
<div class="parent-circle"><div class="loading-circle"></div></div>
<div class="text2">Loading...</div>
</div>
<div class="footer">
<div class="name" id="nickname">${nickname}</div>
<div class="score" id="score">0</div>
</div>
<style type="text/css">
.score {
overflow: hidden;
min-width: 5rem;
padding: 0px 0.75rem;
background: rgb(51, 51, 51);
border-radius: 0.1875rem;
font-size: 1.25rem;
line-height: 1.875;
text-align: center;
color: rgb(255, 255, 255);
margin: 0px 0.625rem;
}
.text,
.text2 {
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
color: rgb(255, 255, 255);
}
.text {
font-size: 4rem;
}
.text2 {
font-size: 2rem;
}
body {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
text-align: center;
}
.parent-circle {
width: 72px;
height: 72px;
flex: 0 1 auto;
flex-direction: row;
-webkit-box-align: center;
align-items: center;
-webkit-box-pack: center;
justify-content: center;
animation: 0.9s ease-out 0s infinite normal none running fJiXoE; /* 0.6 */
transition: all 0.6s ease;
display: inline-block;
vertical-align: middle;
margin-bottom: 1rem;
}
.loading-circle {
border: 20px solid rgb(255, 255, 255);
width: 72px;
height: 36px;
border-top-left-radius: 100px;
border-top-right-radius: 100px;
border-bottom: 0;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
.name {
margin: 0px 0.625rem;
font-size: 1.25rem;
line-height: 1.875;
margin: 0px 0.625rem;
}
.footer {
display: flex;
align-self: stretch;
left: 0px;
right: 0px;
bottom: 0px;
box-shadow: rgb(0 0 0 / 10%) 0px -2px 10px 0px;
min-height: 60px;
padding: 4px 16px;
font-size: 40px;
flex: 0 1 auto;
flex-direction: row;
-webkit-box-align: center;
align-items: center;
-webkit-box-pack: justify;
justify-content: space-between;
position: absolute;
background-color: rgb(255, 255, 255);
font-family: Montserrat, "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 700;
color: rgb(0, 0, 0);
bottom: 0;
}
</style>
`
}<file_sep>let Kahoot = require('kahoot.js-api');
let client = new Kahoot({
modules: {
extraData: true
}
});
const fetch = require("node-fetch");
class ClientClass {
constructor() {
this.QNF = false;
this.Qid = null;
this.Qname = "";
this.PIN = "";
this.choice = null;
this.joinedBeforeQuizStarts = false;
this.totalScore = 0;
this.playerName = null;
}
returnName() {
return this.playerName;
}
async makeChoice(Obj) {
let Qindex = Obj.index;
let uri = "https://create.kahoot.it/rest/kahoots/" + this.Qid + "/card/?includeKahoot=true";
let json = await (await fetch(uri)).json();
let choice;
let question = json.kahoot.questions[Qindex];
let correctAnswers = question.choices;
if (!question.type.includes("quiz")) return;
if ((question.type).includes("multiple")) choice = [];
for (const ans of correctAnswers) {
if (ans.correct) {
if ((question.type).includes("multiple")) choice.push(correctAnswers.indexOf(ans))
else choice = correctAnswers.indexOf(ans)
}
}
this.choice = choice;
}
getThis() {
return this;
}
returnNumberFromData(formData) {
let data = [];
for (let key of formData.entries()) {
if (key[0] == "red-input") data.push(0);
if (key[0] == "blue-input") data.push(1);
if (key[0] == "yellow-input") data.push(2);
if (key[0] == "green-input") data.push(3);
}
return data;
}
async getAnswer() {}
async getQidFromQname(qname) {
let uri = `https://create.kahoot.it/rest/kahoots/?query=${qname}&limit=20&cursor=0&searchCluster=20`;
let json = await (await fetch(uri)).json()
if (json.totalHits < 1) {
this.QNF = true
return false; //Quiz not found.
} else {
this.Qid = json.entities[0].card.uuid;
this.Qname = qname;
return true;
}
}
async validateQid(Qid) {
// console.log(Qid)
// let regEx = new RegExp('[[:alnum:]]{8}-[[:alnum:]]{4}-[[:alnum:]]{4}-[[:alnum:]]{4}-[[:alnum:]]{12}')
// console.log("why", regEx.test(Qid))
// if (regEx.exec(Qid) == null) return false;
let uri = "https://create.kahoot.it/rest/kahoots/" + Qid + "/card/?includeKahoot=true";
let json = await (await fetch(uri)).json();
if (json.error) return false;
return true;
}
async updateQid(qid) {
this.Qid = qid;
let uri = "https://create.kahoot.it/rest/kahoots/" + qid + "/card/?includeKahoot=true";
await fetch(uri).then(async res => await res.json()).then(json => {
this.Qname = json.card.title;
});
}
async validatePIN(PIN) {
let uri = `https://kahoot.it/reserve/session/${PIN}/`;
let text = await (await fetch(uri)).text();
if (text == "Not found") return false;
return true;
}
async join(PIN, NAME) {
if (client.connected) client = new Kahoot();
this.PIN = PIN;
try {
await client.join(PIN, NAME);
return false;
} catch (e) {
let err = e.description
return err
}
}
answer(question, choice) {
question.answer(choice);
}
ordinal_suffix_of(i) {
var j = i % 10,
k = i % 100;
if (j == 1 && k != 11) {
return i + "st";
}
if (j == 2 && k != 12) {
return i + "nd";
}
if (j == 3 && k != 13) {
return i + "rd";
}
return i + "th";
}
returnClient() {
return client;
}
updateName(newName) {
this.playerName = newName;
}
on(event, callback) {
client.on(event, callback);
}
}
let clientC = new ClientClass()
client.on("Joined", () => {
console.log(`I joined the Game!\n`);
clientC.score = 0;
});
module.exports = clientC;<file_sep># KahootCheat++
Hello there!
## NOTE: THIS ONLY WORKS FOR LIVE QUIZZES, CHALLENGES COMING SOON
---
You need to grab the quiz name quickly, or enter it's exact id. In the start of the quiz, the screen of the teacher WILL show the quiz name for 3 seconds. If you didn't manage to get it, try getting the id from the url: blahBlah/blah?quizId=x8-x4-x4-x4-x12.
To download, goto the tags section and to the releases, download the latest one. (Windows Only)
---
For Linux and MacOS, I cant compile it. You can clone this repo and run npm install, then npm start.
## If you have any issues open an issue, If you found a bug that you can fix, please fix it and open a pr
Help me continue this project! [Donate](https://paypal.me/FlashplaysDonations)
<file_sep>/*let allInput = document.getElementsByTagName('input');
for (var ele of allInput) {
ele.onchange = () => {
var thingy = ele.id.replace('-input', '');
let element = document.getElementsByClassName(thingy)[0];
if (ele.checked == true) {
element.style.width = "calc(50% - 32px)";
element.style.height = "calc(50% - 32px)";
element.style.margin = "16px";
} else if (ele.checked == false) {
element.style.width = "calc(50% - 16px)";
element.style.height = "calc(50% - 16px)";
element.style.margin = "8px";
}
}
}*/<file_sep>// JavaScript.
let inputs = document.getElementsByTagName('input');
for (let inputPin of inputs) {
inputPin.addEventListener('input', () => {
inputPin.classList.remove('error');
});
}<file_sep>let client = require('./classes/kahoot-client.js');
let settingsClass = require('./classes/settings.js');
window.addEventListener('DOMContentLoaded', async () => {
let PIN, NAME;
let settings = document.getElementById('settings');
let settingsWrapper = document.getElementById('settings-wrapper');
let settingsForm = document.getElementById('settings-form')
let QidEle = document.getElementById('Qid');
let QnameEle = document.getElementById('Qname');
document.getElementById('answerCooldown').value = settingsClass.answerDelay;
QidEle.value = client.Qid;
QnameEle.value = client.Qname;
settingsForm.onsubmit = (e) => {
e.preventDefault();
}
document.getElementById('settings-form-submit').onclick = async () => {
let formData = new FormData(settingsForm);
let data = {};
for (let i of formData.entries()) {
data[i[0]] = i[1];
}
if (data.manualMode) settingsClass.autoAnswer = false;
else settingsClass.autoAnswer = true;
if (!isNaN(data.answerCooldown)) settingsClass.answerDelay = data.answerCooldown;
if (isNaN(data.answerCooldown)) return document.getElementById('answerCooldown').classList.add('error')
if (data.Qid) {
let QidValid = await client.validateQid(data.Qid);
if (!QidValid) return document.getElementById('Qid').classList.add('error')
else {
settings.click();
await client.updateQid(data.Qid);
}
} else if (data.Qname) {
let QnameValid = await client.getQidFromQname(data.Qname);
if (!QnameValid) return document.getElementById('Qname').classList.add('error')
else settings.click();
}
}
settings.onclick = () => {
document.getElementById('answerCooldown').value = settingsClass.answerDelay;
QidEle.value = client.Qid;
QnameEle.value = client.Qname;
settingsWrapper.classList.toggle("settings-show");
settingsWrapper.classList.toggle("settings-hide");
settings.classList.toggle('down');
}
// On index page.
if (document.getElementsByClassName('index')[0]) {
var form = document.getElementById('submitGameCode') /*Your Form Element*/ ;
var submitBtnPin = document.getElementById('submitBtnPin');
var ele = document.getElementsByClassName("inputPin")[0];
form.onsubmit = (e) => {
e.preventDefault();
}
submitBtnPin.onclick = async () => {
let formData = new FormData(form);
for (var key of formData.entries()) {
if (key[0] == "code") {
PIN = key[1];
if (PIN == "") return ele.classList.add('error');
if (isNaN(PIN)) {
return ele.classList.add('error');
}
let pinTrue = false;
document.getElementById("loader").classList.add("loading")
pinTrue = await client.validatePIN(PIN);
document.getElementById("loader").classList.remove("loading")
if (!pinTrue) {
ele.classList.add('error');
} else {
submitBtnPin.setAttribute("id", "submitBtnName");
var submitBtnName = document.getElementById('submitBtnName');
ele.setAttribute("name", "name");
ele.setAttribute("maxlength", "15")
ele.setAttribute("placeholder", "Enter A Nickname");
submitBtnName.innerText = "Ok, GO!";
ele.value = "";
}
} else if (key[0] == "name") {
NAME = key[1];
if (NAME == "") {
return ele.classList.add('error');
}
if (NAME.length > 15) return ele.classList.add('error');
document.getElementById("loader").classList.add("loading")
clientJoined = await client.join(PIN, NAME);
document.getElementById("loader").classList.remove("loading")
if (clientJoined == !true) {
// Joined Success
client.on('NameAccept', (Obj) => {
client.updateName(Obj.playerName);
document.getElementById('wrapper').style.display = "none";
let NC = require('./pages/quiz/instructions-page')(Obj.playerName);
document.getElementById('loader').classList.remove('index');
document.getElementById('loader').classList.add('instructions');
document.getElementById('wrapper-2').innerHTML = NC;
client.on('Disconnect', Disconnect);
client.on('QuestionEnd', QuestionEnd);
client.on('QuestionReady', QuestionReady);
client.on('QuestionStart', QuestionStart);
client.on('QuizEnd', QuizEnd);
client.on('QuizStart', QuizStart);
client.on('TimeOver', TimeOver);
// Now this parent if statement will return false.
});
} else {
//console.log(clientJoined)
errorMessage(clientJoined);
}
}
}
}
}
// Events for client.
function QuizStart(quiz) {
client.joinedBeforeQuizStarts = true;
document.getElementById('wrapper').style.display = "none";
let NC = require('./pages/quiz/quizLoading-page')(client.playerName);
document.getElementById('loader').classList.add('game');
document.getElementById('loader').classList.remove('instructions');
document.getElementById('wrapper-2').innerHTML = NC;
}
function TimeOver(Obj) {
// Nothing to do here
}
function QuizEnd(Obj) {
// Things to do here...
NC = require('./pages/quiz/quizEnd-page')(Obj.rank, client)
document.getElementById('wrapper-2').innerHTML = NC;
}
function QuestionStart(Obj) {
// Things to do here...
if (!client.joinedBeforeQuizStarts) {
// This means that things are not initialized properly, so we initialize them.
document.getElementById('wrapper').style.display = "none";
let NC = require('./pages/quiz/quizLoading-page')(client.playerName);
document.getElementById('loader').classList.add('game');
document.getElementById('loader').classList.remove('instructions');
document.getElementById('wrapper-2').innerHTML = NC;
client.joinedBeforeQuizStarts = true;
}
//console.log(Obj.gameBlockLayout)
let NC;
if (Obj.gameBlockType.includes("multiple")) {
if (Obj.gameBlockType.includes("quiz")) {
// Quiz handler Multiple select only 4 possible buttons with the on form submit event.
NC = require('./pages/question/questionMultiple-page')(Obj, client)
document.getElementById('wrapper-2').innerHTML = NC;
let formEle = document.getElementById('formElementMultiQuestion'),
formSubmitButton = document.getElementById('formSubmitButton');
formEle.onsubmit = (e) => {
e.preventDefault();
}
formSubmitButton.onclick = () => {
let data = new FormData(formEle);
let dataArr = client.returnNumberFromData(data);
Obj.answer(dataArr);
}
if (client.choice != null) {
setTimeout(() => {
Obj.answer(client.choice);
client.choice = false;
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "WAITING"
});
document.getElementById('wrapper-2').innerHTML = NC;
}, (settingsClass.answerDelay * 1000));
}
} else if (Obj.gameBlockType.includes("poll")) {
// Poll Handler Multiple select with the on form submit event.
NC = require('./pages/question/questionMultiple-page')(Obj, client)
document.getElementById('wrapper-2').innerHTML = NC;
let formEle = document.getElementById('formElementMultiQuestion'),
formSubmitButton = document.getElementById('formSubmitButton');
formEle.onsubmit = (e) => {
e.preventDefault();
}
formSubmitButton.onclick = () => {
let data = new FormData(formEle);
let dataArr = client.returnNumberFromData(data);
Obj.answer(dataArr);
}
}
} else {
if (Obj.gameBlockType.includes("quiz")) {
// Quiz number of choices functions with the onclick event.
if (Obj.quizQuestionAnswers[Obj.questionIndex] == 2) {
if (Obj.gameBlockLayout == "TRUE_FALSE") {
NC = require('./pages/question/questionSingle-page')(Obj, client, true, true)
} else {
NC = require('./pages/question/questionSingle-page')(Obj, client, true, false)
}
document.getElementById('wrapper-2').innerHTML = NC;
/* onclick s including if is set auto answer and is set quiz id,
automatically call onclick with client.answer.
if (!client.answer) return and make the user himself select the answer. */
let redButton = document.getElementById('red'),
blueButton = document.getElementById('blue');
blueButton.onclick = () => {
Obj.answer((Obj.gameBlockLayout == "TRUE_FALSE") ? 0 : 1);
blueButton.onclick = null;
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "WAITING"
});
document.getElementById('wrapper-2').innerHTML = NC;
}
redButton.onclick = () => {
Obj.answer((Obj.gameBlockLayout == "TRUE_FALSE") ? 1 : 0);
redButton.onclick = null;
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "WAITING"
});
document.getElementById('wrapper-2').innerHTML = NC;
}
if (client.choice != null) {
setTimeout(() => {
Obj.answer(client.choice);
client.choice = false;
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "WAITING"
});
document.getElementById('wrapper-2').innerHTML = NC;
}, (settingsClass.answerDelay * 1000));
}
} else {
NC = require('./pages/question/questionSingle-page')(Obj, client, false)
document.getElementById('wrapper-2').innerHTML = NC;
// onclick s
let redButton = document.getElementById('red'),
blueButton = document.getElementById('blue'),
yellowButton = document.getElementById('yellow'),
greenButton = document.getElementById('green');
redButton.onclick = () => {
Obj.answer(0);
redButton.onclick = null;
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "WAITING"
});
document.getElementById('wrapper-2').innerHTML = NC;
}
blueButton.onclick = () => {
Obj.answer(1);
blueButton.onclick = null;
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "WAITING"
});
document.getElementById('wrapper-2').innerHTML = NC;
}
yellowButton.onclick = () => {
Obj.answer(2);
yellowButton.onclick = null;
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "WAITING"
});
document.getElementById('wrapper-2').innerHTML = NC;
}
greenButton.onclick = () => {
Obj.answer(3);
greenButton.onclick = null;
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "WAITING"
});
document.getElementById('wrapper-2').innerHTML = NC;
}
//* Reaches here
if (client.choice != null) {
setTimeout(() => {
Obj.answer(client.choice);
client.choice = false;
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "WAITING"
});
document.getElementById('wrapper-2').innerHTML = NC;
}, (settingsClass.answerDelay * 1000));
}
}
} else if (Obj.gameBlockType.includes("poll")) {
// Poll Handler with the onclick event.
if (Obj.quizQuestionAnswers[Obj.questionIndex] == 2) {
NC = require('./pages/question/questionSingle-page')(Obj, client, true)
document.getElementById('wrapper-2').innerHTML = NC;
/* onclick s only user can answer this. */
let redButton = document.getElementById('red'),
blueButton = document.getElementById('blue');
redButton.onclick = () => {
Obj.answer(0);
redButton.onclick = null;
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "WAITING"
});
document.getElementById('wrapper-2').innerHTML = NC;
}
blueButton.onclick = () => {
Obj.answer(1);
blueButton.onclick = null;
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "WAITING"
});
document.getElementById('wrapper-2').innerHTML = NC;
}
} else {
NC = require('./pages/question/questionSingle-page')(Obj, client, false)
document.getElementById('wrapper-2').innerHTML = NC;
// onclick s
let redButton = document.getElementById('red'),
blueButton = document.getElementById('blue'),
yellowButton = document.getElementById('yellow'),
greenButton = document.getElementById('green');
redButton.onclick = () => {
Obj.answer(0);
redButton.onclick = null;
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "WAITING"
});
document.getElementById('wrapper-2').innerHTML = NC;
}
blueButton.onclick = () => {
Obj.answer(1);
blueButton.onclick = null;
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "WAITING"
});
document.getElementById('wrapper-2').innerHTML = NC;
}
yellowButton.onclick = () => {
Obj.answer(2);
yellowButton.onclick = null;
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "WAITING"
});
document.getElementById('wrapper-2').innerHTML = NC;
}
greenButton.onclick = () => {
Obj.answer(3);
greenButton.onclick = null;
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "WAITING"
});
document.getElementById('wrapper-2').innerHTML = NC;
}
}
}
}
// let NC = require('./questionSingle-page')(Obj, client, is2)
}
function QuestionEnd(Obj) {
// Things to do here...
if (!client.joinedBeforeQuizStarts) {
// This means that things are not initialized properly, so we initialize them.
document.getElementById('wrapper').style.display = "none";
let NC = require('./pages/quiz/quizLoading-page')(client.playerName);
document.getElementById('loader').classList.add('game');
document.getElementById('loader').classList.remove('instructions');
document.getElementById('wrapper-2').innerHTML = NC;
client.joinedBeforeQuizStarts = true;
}
if (!client.quizQuestionAnswers) return;
client.totalScore = Obj.totalScore;
let NC = require('./pages/question/questionEnd-page')(Obj, client);
document.getElementById('wrapper-2').innerHTML = NC;
}
function QuestionReady(Obj) {
// Things to do here...
if (!client.joinedBeforeQuizStarts) {
// This means that things are not initialized properly, so we initialize them.
document.getElementById('wrapper').style.display = "none";
let NC = require('./pages/quiz/quizLoading-page')(client.playerName);
document.getElementById('loader').classList.add('game');
document.getElementById('loader').classList.remove('instructions');
document.getElementById('wrapper-2').innerHTML = NC;
client.joinedBeforeQuizStarts = true;
}
// Now we are good to go.
if (Obj.gameBlockType.includes("content")) { //*Obj.gameBlockType.includes("quiz") || Obj.gameBlockType.includes("poll")
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "NOT_QUIZ"
});
document.getElementById('wrapper-2').innerHTML = NC;
} else {
client.quizQuestionAnswers = Obj.quizQuestionAnswers;
let NC = require('./pages/question/questionPre-page')(client.playerName, client.totalScore, Obj.questionIndex, Obj.quizQuestionAnswers.length, client.Qname, {
customText: "NORMAL"
});
document.getElementById('wrapper-2').innerHTML = NC;
// if is set auto answer and is set quiz id, set client.answer with the answer.
}
if (settingsClass.autoAnswer) {
client.makeChoice(Obj);
}
}
function Disconnect(reason) {
//Disconnected
var ele = document.getElementsByClassName("inputPin")[0];
document.getElementById('wrapper').style.display = "flex";
document.getElementById('wrapper-2').innerHTML = "";
document.getElementById('loader').classList.add('index');
document.getElementById('loader').classList.remove('instructions');
document.getElementById('loader').classList.remove('game');
for (const e of document.getElementsByTagName('link')) {
if (e.getAttribute('href').includes("instructions.css")) {
e.remove();
}
}
var submitBtnName = document.getElementById('submitBtnName');
submitBtnName.setAttribute("id", "submitBtnPin");
var submitBtnPin = document.getElementById('submitBtnPin');
ele.setAttribute("name", "code");
ele.removeAttribute("maxlength")
ele.setAttribute("placeholder", "Enter Code");
submitBtnPin.innerText = "Enter";
ele.value = "";
errorMessage(`Disconnected: ${reason}`)
}
function errorMessage(error) {
let errorMessageDiv = document.createElement('div');
errorMessageDiv.setAttribute('class', 'errorMessageDiv');
let innerErrorMessage = document.createElement('div');
innerErrorMessage.setAttribute('class', 'innerErrorMessage');
let iconA = document.createElement('i');
iconA.setAttribute('class', 'fa fa-2x fa-exclamation-circle errorMessageIcon')
innerErrorMessage.appendChild(iconA);
let errorMessage = document.createElement('div');
errorMessage.setAttribute('class', 'errorMessage');
errorMessage.innerHTML = error;
errorMessage.style.marginLeft = "0.5rem"
innerErrorMessage.appendChild(errorMessage);
errorMessageDiv.appendChild(innerErrorMessage);
errorMessageDiv.style.transform = "translateY(100%)";
document.body.append(errorMessageDiv);
setTimeout(() => errorMessageDiv.style.transform = "translateY(0)", 500);
setTimeout(() => {
errorMessageDiv.style.transform = "translateY(100%)";
}, 5000);
}
});<file_sep>module.exports = (rank, client) => {
let str = "";
str += `<link rel="stylesheet" type="text/css" href="./assets/css/quizEnd.css">`
if (rank <= 3) {
if (rank == 1) str += `<div class="medal gold"></div>`;
if (rank == 2) str += `<div class="medal silver"></div>`;
if (rank == 3) str += `<div class="medal bronze"></div>`;
str += `<p class="p1">You are the ${client.ordinal_suffix_of(rank)}</p>`
str += `<p class="p2">#${rank}</p>`
} else {
str += `<p class="p1">Awesome Effort!</p>`
str += `<p class="p2">#${rank}</p>`
}
str += `
<div class="footer">
<div class="name" id="nickname">${client.playerName}</div>
<div class="score" id="score">${client.totalScore}</div>
</div>
`
return str;
} | 9ed1b85efbbe8a3c0a3565ae7816e4c768d53340 | [
"JavaScript",
"Markdown"
] | 8 | JavaScript | artifexdevstuff/KahootCheatPlusPlus | 1a2bead90c099214de4e61437eda08e62e0ecec9 | a1bbbbccf8d467204c311c61aee1ca7fd669927c |
refs/heads/master | <file_sep><?php
$content = '
<page>
<table border="0.5" cellpadding="0" cellspacing="0" align="center" style="margin-top:50px;">
<tr>
<th>
<table>
<tr><th style="font-size:24px;"><NAME></th></tr>
<tr><th><EMAIL></th></tr>
<tr><th>+91-8553236639</th></tr>
</table>
</th>
<th style="font-size:24px;padding-left:15px;padding-right:15px;text-align:center;">COMPUTER SCIENCE<br /> AND<br /> ENGINEERING</th>
<th><img src="logo.png" /></th>
</tr>
</table>
<br />
<p style="font-size:14px;"><b>Career Objective :</b></p>
<p style="margin-left:50px;margin-right:40px;">To make a sound position in corporate world and work enthusiastically in team to achieve goal of the
organization with devotion and hard work.To seek challenging assignment and responsibility, with an opportunity for
growth and career advancement as successful achievements.</p>
<p style="font-size:14px;"><b>Academics :</b></p>
<table border="0.5" cellpadding="0" cellspacing="0" align="center">
<tr>
<th style="padding-left:5px;padding-right:5px;">Sl. No.</th>
<th style="padding-left:5px;padding-right:5px;">Qualification</th>
<th style="padding-left:5px;padding-right:5px;">Board</th>
<th style="padding-left:5px;padding-right:5px;">College/School</th>
<th style="padding-left:5px;padding-right:5px;">Year of Passing</th>
<th style="padding-left:5px;padding-right:5px;">Marks Obtained (%)</th>
</tr>
<tr>
<td style="padding-left:5px;padding-right:5px;">1. </td>
<td style="padding-left:5px;padding-right:5px;">B.E</td>
<td style="padding-left:5px;padding-right:5px;">VTU<sup>1</sup></td>
<td style="padding-left:5px;padding-right:5px;">BMS Institute of Technology</td>
<td style="padding-left:5px;padding-right:5px;">2016 (to be completed)</td>
<td style="padding-left:5px;padding-right:5px;">76.92</td>
</tr>
<tr>
<td style="padding-left:5px;padding-right:5px;">2. </td>
<td style="padding-left:5px;padding-right:5px;">Class 12</td>
<td style="padding-left:5px;padding-right:5px;">CBSE<sup>2</sup></td>
<td style="padding-left:5px;padding-right:5px;">Kendriya Vidyalaya No.1, Jalahalli West</td>
<td style="padding-left:5px;padding-right:5px;">2012</td>
<td style="padding-left:5px;padding-right:5px;">89.4</td>
</tr>
<tr>
<td style="padding-left:5px;padding-right:5px;">3. </td>
<td style="padding-left:5px;padding-right:5px;">Claas 10</td>
<td style="padding-left:5px;padding-right:5px;">CBSE<sup>2</sup></td>
<td style="padding-left:5px;padding-right:5px;">Kendriya Vidyalaya No.1, Jalahalli West</td>
<td style="padding-left:5px;padding-right:5px;">2010</td>
<td style="padding-left:5px;padding-right:5px;">87.4</td>
</tr>
</table>
<p style="margin-left:12px;">VTU<sup>1</sup> : Visvesvaraya Technological University</p>
<p style="margin-left:12px;margin-top:0px;">CBSE<sup>2</sup> : Central Board Of Secondary Education</p>
<p style="font-size:14px;"><b>Technical Skills :</b></p>
<ol>
<li><b>Languages :</b> C, C++, Python, UNIX Shell, PHP, JAVA, C#, R, Octave</li>
<li><b>Databases :</b> MySQL, PostgreSQL</li>
<li><b>Platforms :</b> Android</li>
<li><b>Libraries :</b> OpenCV</li>
<li><b>O/S :</b> Debian based Linux, Fedora, Windows</li>
</ol>
<p style="font-size:14px;"><b>Certifications :</b></p>
<ol>
<li>LFS101x: Introduction To Linux from Linux Foundation through edX.</li>
<li>Introduction To Data Analysis Using R from Big Data University, IBM.</li>
<li>Hadoop Fundamentals from Big Data University, IBM.</li>
<li>MAS.S69x: Big Data and Social Physics from MITx through edX.</li>
<li>15.390x: Entreprenuership:Who is your customer? from MITx through edX.</li>
<li>CS1156x: Learning From Data,Machine Learning from Caltechx through edX.</li>
<li>Microsoft Certification in Dot Net Technologies through NIIT.</li>
</ol>
<p style="font-size:14px;"><b>Technical Papers :</b></p>
<ol>
<li><b>“Artificial Intelligence Based Personal Assistance Bot For Automated Task Processing”</b>, presented at
NCECC 2013 (ISBN9 : 78-81-928203-6-1).</li>
<li><b>“Using Improved Laser Spark Plugs To Improve Ignition Temperature Of IC Engines In Cold
Countries”</b>, published in Manthana 2014, BMSIT.</li>
</ol>
<p style="font-size:14px;"><b>Internships :</b></p>
<ol>
<li>Campus Ambassador, National Student Space Challenge</li>
<li>Campus Ambassador, Internshala</li>
</ol>
<p style="font-size:14px;"><b>Achievements/Awards :</b></p>
<ol>
<li>Won NASA Space Apps Challenge 2014 from India in Best Use Of Hardware category.</li>
<li>Qualified for Facebook Hackers Cup 2013 and 2014 till round 2.</li>
</ol>
</page>';
require_once(dirname(__FILE__).'/html2pdf/html2pdf.class.php');
$html2pdf = new HTML2PDF('P','A4','fr');
$html2pdf->WriteHTML($content);
$html2pdf->Output('exemple.pdf');
?> | 3b7854ce8d76f798d630fdf5ed223598d5025281 | [
"PHP"
] | 1 | PHP | surajjana/html2pdf | 4db05056f6a2438168b73b7557d99645c495e7ea | c2daaec63aa61dfc565496f853452e9ad712fd85 |
refs/heads/main | <file_sep>a, b, c = input().split()
a = int(a)
b = int(b)
c = int(c)
num = 0
for i in range(c):
for j in range(b):
for k in range(a):
print("{} {} {}" .format(i, j, k))
num += 1
print(num)
<file_sep>a, b, c = input().split()
a = int(a)
b = int(b)
c = int(c)
d = a + b + c
print(d, format(d / 3, ".2f"))
<file_sep>init = []
for i in range(10):
init.append(list(map(int, input().split())))
x, y = 1, 1
while True:
if init[x][y] == 0:
init[x][y] = 9
elif init[x][y] == 2:
init[x][y] = 9
break
if init[x][y+1] == 1 and init[x+1][y] == 1:
break
if init[x][y+1] != 1:
y = y + 1
elif init[x+1][y] != 1:
x = x + 1
for i in range(10):
for j in range(10):
print(init[i][j], end=' ')
print()
<file_sep>a = int(input())
b = 0
for i in range(1, a + 1):
if i % 2 == 0:
b = b + i
print(b)
<file_sep>a, b, c = map(int, input().split())
i = 0
while True:
i += 1
if i % a == 0 and i % b == 0 and i % c == 0:
print(i)
break
<file_sep>num = int(input())
a = list(map(int, input().split()))
for i in range(num):
a[i] = int(a[i])
small = a[0]
for i in range(num):
if small > a[i]:
small = a[i]
print(small)
<file_sep>a = list(map(int, input().split()))
for i in range(len(a)):
if a[i] % 2 == 0:
print("even")
else:
print("odd")
<file_sep>a, b, c, d = map(int, input().split())
e = a * b * c * d / 8 / 1024 / 1024
print("%.1f MB " % e)
<file_sep>init = []
a, b = map(int, input().split())
num = int(input())
for i in range(a):
init.append([])
for j in range(b):
init[i].append(0)
for i in range(num):
l, d, x, y = map(int, input().split())
for j in range(l):
if d == 0:
init[x-1][y-1+j] = 1
else:
init[x-1+j][y-1] = 1
for i in range(a):
for j in range(b):
print(init[i][j], end=' ')
print()
<file_sep>a, b, c, d = map(int, input().split())
for i in range(1, d):
a = a * b + c
print(a)
<file_sep>a = float(input())
b = float(input())
c = a + b
print(c)
<file_sep>init = []
for i in range(20):
init.append([])
for j in range(20):
init[i].append(0)
for i in range(1, 20):
a = [int(x) for x in input().split()]
for j in range(1, 20):
init[i][j] = a[j - 1]
num = int(input())
for i in range(num):
x, y = map(int, input().split())
for j in range(1, 20):
if init[j][y] == 0:
init[j][y] = 1
else:
init[j][y] = 0
if init[x][j] == 0:
init[x][j] = 1
else:
init[x][j] = 0
for i in range(1, 20):
for j in range(1, 20):
print(init[i][j], end=' ')
print()
<file_sep>a, b, c = input().split()
a = int(a)
b = int(b)
c = int(c)
print((b if a > b else a) if (b if a > b else a) < c else c)
<file_sep>num = int(input())
a = list(map(int, input().split()))
for i in range(num):
a[i] = int(a[i])
b = []
for i in range(24):
b.append(0)
for i in range(num):
b[a[i]] += 1
for i in range(1, 24):
print(b[i], end=' ')
<file_sep>a = str(input())
a = ord(a) + 1
print(chr(a))
<file_sep>a = ord(input())
b = ord("a")
while True:
print(chr(b), end=' ')
b = b + 1
if a < b:
break
<file_sep>a, b, c = map(int, input().split())
e = a * b * c / 8 / 1024 / 1024
print("%.2f MB " % e)
<file_sep>init = []
for i in range(20):
init.append([])
for j in range(20):
init[i].append(0)
num = int(input())
for i in range(num):
x, y = input().split()
init[int(x)][int(y)] = 1
for i in range(1, 20):
for j in range(1, 20):
print(init[i][j], end=' ')
print()
| ad7915b99b67d671a0ea9697c346f0ca77581b2c | [
"Python"
] | 18 | Python | Gungoguma/Python | 79c47e4c46a0ee47d9d71a048eec77a26641cde7 | 7802f29896cebf9007c7e76145b960695f8a4881 |
refs/heads/master | <file_sep>
package util;
/**
*
* @author felip
*/
public class Produto {
private int codigo;
private String descricao;
private double valorCusto;
private double lucro;
private double icms;
private double ipi;
private double outrosImpostos;
private int estoque;
private int estoqueMinimo;
private int estoqueMaximo;
public Produto(int codigo, String descricao, double valorCusto, double lucro, double icms, double ipi, double outrosImpostos, int estoque, int estoqueMinimo, int estoqueMaximo) {
this.codigo = codigo;
this.descricao = descricao;
this.valorCusto = valorCusto;
this.lucro = lucro;
this.icms = icms;
this.ipi = ipi;
this.outrosImpostos = outrosImpostos;
this.estoque = estoque;
this.estoqueMinimo = estoqueMinimo;
this.estoqueMaximo = estoqueMaximo;
}
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
public double getValorCusto() {
return valorCusto;
}
public void setValorCusto(double valorCusto) {
this.valorCusto = valorCusto;
}
public double getLucro() {
return lucro;
}
public void setLucro(double lucro) {
this.lucro = lucro;
}
public double getIcms() {
return icms;
}
public void setIcms(double icms) {
this.icms = icms;
}
public double getIpi() {
return ipi;
}
public void setIpi(double ipi) {
this.ipi = ipi;
}
public double getOutrosImpostos() {
return outrosImpostos;
}
public void setOutrosImpostos(double outrosImpostos) {
this.outrosImpostos = outrosImpostos;
}
public int getEstoque() {
return estoque;
}
public void setEstoque(int estoque) {
this.estoque = estoque;
}
public int getEstoqueMinimo() {
return estoqueMinimo;
}
public void setEstoqueMinimo(int estoqueMinimo) {
this.estoqueMinimo = estoqueMinimo;
}
public int getEstoqueMaximo() {
return estoqueMaximo;
}
public void setEstoqueMaximo(int estoqueMaximo) {
this.estoqueMaximo = estoqueMaximo;
}
public double precoRevenda(){
double precoVenda = valorCusto + valorCusto*(lucro+icms+ipi+outrosImpostos);
return precoVenda;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pkgInterface.Dialogs;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import util.ConexaoBD;
import util.Produto;
/**
*
* @author felip
*/
public class DialogPesquisaProdutos extends JDialog{
private final PesquisaProdutos painel;
private Produto produtoSelecionado;
private final JButton btnConfirmar;
private JTable tabProdutos;
public DialogPesquisaProdutos (javax.swing.JFrame parent){
super(parent);
super.setModal(true);
painel = new PesquisaProdutos();
this.btnConfirmar = painel.getBtnConfirma();
this.tabProdutos = painel.getTabProdutos();
btnConfirmar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(tabProdutos.getSelectedRowCount() == 1){
recupera();
dispose();
}
else if(tabProdutos.getSelectedRowCount() > 1)
JOptionPane.showMessageDialog(painel, "Você deve selecionar apenas 1 produto !","Info",JOptionPane.INFORMATION_MESSAGE);
else
JOptionPane.showMessageDialog(painel, "Você deve selecionar 1 produto !","Info",JOptionPane.INFORMATION_MESSAGE);
}
});
this.setContentPane(painel);
setSize(475, 369);
setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
}
//Recupera todas as informações do produto selecionado
private void recupera(){
String codigo = tabProdutos.getValueAt(tabProdutos.getSelectedRow(),0).toString();
ConexaoBD conexao = new ConexaoBD();
conexao.conectar();
String sql = "SELECT * FROM PRODUTO WHERE codigo = "+codigo;
try {
ResultSet rst = conexao.consultaBD(sql);
rst.next();
int cod = rst.getInt("codigo");
String descricao = rst.getString("descricao");
Double valorCusto = rst.getDouble("valorcusto");
Double lucro = rst.getDouble("lucro")/100;
Double icms = rst.getDouble("icms")/100;
Double ipi = rst.getDouble("ipi")/100;
Double outros = rst.getDouble("outrosimpostos")/100;
Integer estoque = rst.getInt("estoque");
Integer estoqueMin = rst.getInt("estoqueminimo");
Integer estoqueMax = rst.getInt("estoquemaximo");
produtoSelecionado = new Produto(cod, descricao,valorCusto,lucro,icms,ipi,outros,estoque,estoqueMin,estoqueMax);
} catch (SQLException ex) {
Logger.getLogger(DialogPesquisaProdutos.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Produto getProdutoSelecionado() {
return produtoSelecionado;
}
}
<file_sep>
package pkgInterface.Dialogs;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import util.Cliente;
import util.ConexaoBD;
import util.Produto;
/**
*
* @author felip
*/
public class DialogFinalizarVenda extends JDialog{
private final FinalizarVenda painel;
private final JButton btnConfirmar;
private boolean vendaFinalizada;
private final ArrayList<Produto> produtos;
private final String dataDaVenda;
public DialogFinalizarVenda(Frame owner,ArrayList<Produto>produtos,String dataDaVenda,String valorTotal) {
super(owner,true);
this.dataDaVenda = dataDaVenda;
this.produtos = produtos;
this.setSize(473, 305);
painel = new FinalizarVenda();
setContentPane(painel);
btnConfirmar = painel.getBtnConfirma();
vendaFinalizada = false;
painel.getLblValorTotal().setText(valorTotal);
//Configura o botão confirmar venda
btnConfirmar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
vendaFinalizada = true;
ConexaoBD conexao = new ConexaoBD();
Cliente c = painel.getCliente();
if(c == null)
finalizaVendaAvista(conexao);
else
finalizaVendaPrazo(conexao, c);
dispose();
}
});
}
public boolean isVendaFinalizada() {
return vendaFinalizada;
}
public void setVendaFinalizada(boolean vendaFinalizada) {
this.vendaFinalizada = vendaFinalizada;
}
// Cadastra uma venda a prazo no Banco de Dados
private void finalizaVendaPrazo(ConexaoBD conexao,Cliente c){
conexao.conectar();
String sql = "INSERT INTO VENDA_APRAZO(codigocliente,datadavenda) VALUES("+ c.getCodigo()
+",CAST('"+dataDaVenda+"' as DATE))";
try {
conexao.manipulaBD(sql);
//Captura o código da venda gerada
int codigoDaVenda;
sql = "SELECT MAX (codigo) FROM VENDA_APRAZO";
ResultSet res = conexao.consultaBD(sql);
res.next();
codigoDaVenda = res.getInt("max");
//Insere os produtos associados à venda no Banco de dados e atualiza o estoque de cada produto
for(Produto p : produtos){
//Descobre a quantidade comprada do produto
sql = "SELECT P.estoque FROM PRODUTO P WHERE P.codigo = "+p.getCodigo();
res = conexao.consultaBD(sql);
res.next();
int quantidade = res.getInt("estoque") - p.getEstoque();
//Insere a ligação de cada produto com a venda
sql = "INSERT INTO PRODUTOS_VENDA_PRAZO(codigovenda,codigoproduto,quantidade) "
+ "VALUES("+codigoDaVenda+" ,"+p.getCodigo()+" ,"+quantidade+")";
conexao.manipulaBD(sql);
//Atualiza o estoque
sql = "UPDATE PRODUTO SET estoque = "+p.getEstoque()+" WHERE codigo = "+p.getCodigo();
conexao.manipulaBD(sql);
}
conexao.desconectar();
} catch (SQLException ex) {
conexao.desconectar();
Logger.getLogger(DialogFinalizarVenda.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("ACTION QUE CADASTRA VENDA A PRAZO NO BANCO DE DADOS!");
}
// Cadastra uma venda a vista no Banco de Dados
private void finalizaVendaAvista(ConexaoBD conexao){
String modoDePagamento = painel.getCmbFormaDePagamento().getSelectedItem().toString();
String sql = "INSERT INTO VENDA_AVISTA(tipopagamento,datadavenda) VALUES('"+modoDePagamento
+"' CAST('"+dataDaVenda+"' as DATE))";
try {
conexao.manipulaBD(sql);
//Captura o código da venda gerada
int codigoDaVenda;
sql = "SELECT MAX (codigo) FROM VENDA_AVISTA";
ResultSet res = conexao.consultaBD(sql);
res.next();
codigoDaVenda = res.getInt("max");
//Insere os produtos associados à venda no Banco de dados e atualiza o estoque de cada produto
for(Produto p : produtos){
//Descobre a quantidade comprada do produto
sql = "SELECT P.estoque FROM PRODUTO P WHERE P.codigo = "+p.getCodigo();
res = conexao.consultaBD(sql);
res.next();
int quantidade = res.getInt("estoque") - p.getEstoque();
//Insere a ligação de cada produto com a venda
sql = "INSERT INTO PRODUTOS_VENDA_VISTA(codigovenda,codigoproduto,quantidade) "
+ "VALUES("+codigoDaVenda+" ,"+p.getCodigo()+" ,"+quantidade+")";
conexao.manipulaBD(sql);
//Atualiza o estoque
sql = "UPDATE PRODUTO SET estoque = "+p.getEstoque()+" WHERE codigo = "+p.getCodigo();
conexao.manipulaBD(sql);
}
conexao.desconectar();
} catch (SQLException ex) {
conexao.desconectar();
Logger.getLogger(DialogFinalizarVenda.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("ACTION QUE CADASTRA VENDA A VISTA NO BANCO DE DADOS!");
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pkgInterface.Dialogs;
import java.awt.Frame;
import javax.swing.JDialog;
import util.Fornecedor;
import util.Produto;
/**
*
* @author felip
*/
public class DialogComprarMais extends JDialog {
private Produto produto;
private ComprarMais painel;
private Fornecedor fornecedor;
public DialogComprarMais(Produto produto, ComprarMais painel, Fornecedor fornecedor, Frame owner) {
super(owner,true);
this.produto = produto;
this.painel = painel;
this.fornecedor = fornecedor;
setContentPane(painel);
}
private void carregaInformacoes(){
setContentPane(painel);
setSize(393, 132);
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package pkgInterface.Dialogs;
import javax.swing.JButton;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.text.DefaultFormatter;
/**
*
* @author felip
*/
public class ComprarMais extends javax.swing.JPanel {
/**
* Creates new form ComprarMais
*/
public ComprarMais() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
btnFinalizarCompra = new javax.swing.JButton();
edtDescricao = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
spinnerQuantidade = new javax.swing.JSpinner();
edtValorTotal = new javax.swing.JTextField();
edtNomeFornecedor = new javax.swing.JTextField();
jLabel1.setText("Descrição");
btnFinalizarCompra.setText("Finalizar Venda");
btnFinalizarCompra.setEnabled(false);
btnFinalizarCompra.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnFinalizarCompraActionPerformed(evt);
}
});
edtDescricao.setEditable(false);
edtDescricao.setEnabled(false);
jLabel2.setText("Fornecedor");
jLabel3.setText("Valor Total");
jLabel4.setText("Quantidade");
JSpinner.NumberEditor jsEditor = (JSpinner.NumberEditor)spinnerQuantidade.getEditor();
DefaultFormatter formatter = (DefaultFormatter) jsEditor.getTextField().getFormatter();
formatter.setAllowsInvalid(false);
spinnerQuantidade.setEnabled(false);
edtValorTotal.setEditable(false);
edtValorTotal.setEnabled(false);
edtNomeFornecedor.setEditable(false);
edtNomeFornecedor.setEnabled(false);
edtNomeFornecedor.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
edtNomeFornecedorActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(spinnerQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(62, 62, 62)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(edtValorTotal, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnFinalizarCompra, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(13, 13, 13)
.addComponent(edtDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 314, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(edtNomeFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, 314, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(edtDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(edtNomeFornecedor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(spinnerQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(edtValorTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(btnFinalizarCompra, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
}// </editor-fold>//GEN-END:initComponents
private void btnFinalizarCompraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFinalizarCompraActionPerformed
}//GEN-LAST:event_btnFinalizarCompraActionPerformed
private void edtNomeFornecedorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_edtNomeFornecedorActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_edtNomeFornecedorActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnFinalizarCompra;
private javax.swing.JTextField edtDescricao;
private javax.swing.JTextField edtNomeFornecedor;
private javax.swing.JTextField edtValorTotal;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JSpinner spinnerQuantidade;
// End of variables declaration//GEN-END:variables
}
| 7162bc1b791330f03f383d65d509160cbe2512ff | [
"Java"
] | 5 | Java | ronaldoi9/TrabalhoBD | 5aea3107766471ed6e71f8a1d0cd6c3c167c5fd1 | ba20a1dc0590ba8bf9b846980bdc2a44571ed6ee |
refs/heads/master | <file_sep># Docompiler
A Compiler Add-On for Microsoft Word

<file_sep>(function(){
'use strict';
// The initialize function must be run each time a new page is loaded
Office.initialize = function(reason) {
jQuery(document).ready(function() {
app.initialize();
jQuery('#get-data-from-selection').click(getDataFromSelection);
app.socket.on('lang', function(data) {
var html = Prism.highlight(data.text, Prism.languages[data.lang])
jQuery('#code').html(html);
})
app.socket.on('output', function(res) {
if (app.isNotificationClosed()) {
app.showNotification('Output', res.data);
}
else {
app.appendNotification(res.data);
}
});
app.socket.on('compile_error', function(res) {
app.showError('Error', res.data);
});
app.socket.on('end', function(res) {
console.log('end');
});
getDataFromSelection();
});
};
// Reads data from current document selection and displays a notification
function getDataFromSelection(){
// Word.run(function (context) {
// // Create a proxy object for the document body.
// var body = context.document.body;
// // Queue a commmand to get the HTML contents of the body.
// var bodyHTML = body.getHtml();
// // Synchronize the document state by executing the queued commands,
// // and return a promise to indicate task completion.
// return context.sync().then(function () {
// console.log("Body HTML contents: " + bodyHTML.value);
// });
// })
// .catch(function (error) {
// console.log("Error: " + JSON.stringify(error));
// if (error instanceof OfficeExtension.Error) {
// console.log("Debug info: " + JSON.stringify(error.debugInfo));
// }
// });
if (!app.isNotificationClosed()) {
app.closeNotification();
}
Office.context.document.getSelectedDataAsync(Office.CoercionType.Text,
function(result){
if (result.status === Office.AsyncResultStatus.Succeeded) {
if (result.value !== '') {
var data = {
text: result.value
}
app.socket.emit('data', data);
}
// app.showNotification('The selected text is:', '"' + result.value + '"');
} else {
app.showNotification('Error:', result.error.message);
}
}
);
}
})();
<file_sep>var fs = require('fs'),
express = require('express'),
https = require('https'),
bodyParser = require('body-parser'),
lang = require('language-classifier');
const spawn = require('child_process').spawn;
var https_options = {
key: fs.readFileSync('./localhost-key.pem'),
cert: fs.readFileSync('./localhost-cert.pem')
};
var PORT = 8443,
HOST = 'localhost';
var app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// set static routes
app.use('/', express.static(__dirname + '/src'));
app.use('/content', express.static(__dirname + '/content'));
app.use('/images', express.static(__dirname + '/images'));
app.use('/scripts', express.static(__dirname + '/scripts'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
var server = https.createServer(https_options, app)
.listen(PORT, HOST);
var io = require('socket.io')(server);
io.on('connection', function (socket) {
socket.emit('connected', { text: 'connected' });
socket.on('data', function(data) {
fs.writeFile('junk.txt', data.text, function(err) {
if (err) {
return console.log(err);
}
})
//
// console.log(data.text);
var text = data.text.trim().replace(/(?:\r\n|\r|\n)/g, '\n').replace(/[^\x00-\x7F]/g, "");
var language = null;
var extension = null;
if (text.startsWith('```') && text.endsWith('```')) {
var lines = text.split('\n');
var firstLine = lines[0];
var trimmedLines = lines.slice(1, lines.length -1).join('\n');
language = firstLine.substring(firstLine.lastIndexOf(" ")+1)
text = trimmedLines;
extension = get_extension(language);
console.log(firstLine)
}
else {
language = lang(text);
extension = get_extension(language);
}
// if (language === 'html') {
// console.log('HTML')
// var filename = 'test.html'
// fs.writeFile(filename, text, function(err) {
// if (err) {
// return console.log(err);
// }
// })
// }
// else if (language === 'shell') {
// var filename = 'test.sh';
// fs.writeFile(filename, text, function(err) {
// if (err) {
// return console.log(err);
// }
// })
// }
if (extension === null){
// res.send('ERROR: Cannot detect language');
// res.status(500).send('ERROR: Cannot detect language');
console.log(language);
socket.emit('compile_error', {data: 'ERROR: Cannot detect language' });
}
else {
console.log(language);
socket.emit('lang', {lang: language, text: text});
var extension = get_extension(language);
var filename = 'test' + extension;
if (language === 'javascript') {
fs.writeFile(filename, text, function(err) {
if (err) {
return console.log(err);
}
const process = spawn('node', [filename]);
process.stdout.on('data', function(data) {
// console.log(`${data}`);
socket.emit('output', { data: `${data}`});
})
process.stderr.on('data', function(data) {
// console.log(`stderr: ${data}`);
socket.emit('compile_error', {data: `${data}`});
// fs.unlink(filename);
})
process.on('close', function(code) {
console.log(`child process exited with code ${code}`);
socket.emit('end', {data: 'end'})
// fs.unlink(filename);
})
socket.on('exit', function() {
process.kill();
})
});
}
else if (language === 'c') {
fs.writeFile(filename, text, function(err) {
if (err) {
return console.log(err);
}
const process = spawn('gcc', [filename]);
process.stdout.on('data', function(data) {
// console.log(`${data}`);
socket.emit('output', { data: `${data}`});
})
process.stderr.on('data', function(data) {
// console.log(`stderr: ${data}`);
socket.emit('compile_error', {data: `${data}`});
// fs.unlink(filename);
})
process.on('close', function(code) {
console.log(`child process exited with code ${code}`);
// socket.emit('end', {data: 'end'})
// fs.unlink(filename);
const process2 = spawn('./a.out');
process2.stdout.on('data', function(data) {
// console.log(`${data}`);
socket.emit('output', { data: `${data}`});
})
process2.stderr.on('data', function(data) {
// console.log(`stderr: ${data}`);
socket.emit('compile_error', {data: `${data}`});
// fs.unlink(filename);
})
process2.on('close', function(code) {
console.log(`child process exited with code ${code}`);
socket.emit('end', {data: 'end'})
})
socket.on('exit', function() {
process2.kill();
})
})
socket.on('exit', function() {
process.kill();
})
});
}
else if (language === 'python') {
fs.writeFile(filename, text, function(err) {
if (err) {
return console.log(err);
}
const process = spawn('python', [filename]);
process.stdout.on('data', function(data) {
// console.log(`${data}`);
socket.emit('output', { data: `${data}`});
})
process.stderr.on('data', function(data) {
// console.log(`stderr: ${data}`);
socket.emit('compile_error', {data: `${data}`});
// fs.unlink(filename);
})
process.on('close', function(code) {
console.log(`child process exited with code ${code}`);
socket.emit('end', {data: 'end'})
// fs.unlink(filename);
})
socket.on('exit', function() {
process.kill();
})
});
}
else if (language === 'java') {
var classIndex = text.split(' ').findIndex(function(el) {
return el === 'class'
})
var className = text.split(' ')[classIndex + 1];
filename = className + extension;
fs.writeFile(filename, text, function(err) {
if (err) {
return console.log(err);
}
const process = spawn('javac', [filename]);
process.stdout.on('data', function(data) {
// console.log(`${data}`);
socket.emit('output', { data: `${data}`});
})
process.stderr.on('data', function(data) {
// console.log(`stderr: ${data}`);
socket.emit('compile_error', {data: `${data}`});
// fs.unlink(filename);
})
process.on('close', function(code) {
console.log(`child process exited with code ${code}`);
// socket.emit('end', {data: 'end'})
// fs.unlink(filename);
const process2 = spawn('java', [className]);
process2.stdout.on('data', function(data) {
// console.log(`${data}`);
socket.emit('output', { data: `${data}`});
})
process2.stderr.on('data', function(data) {
// console.log(`stderr: ${data}`);
socket.emit('compile_error', {data: `${data}`});
// fs.unlink(filename);
})
process2.on('close', function(code) {
console.log(`child process exited with code ${code}`);
socket.emit('end', {data: 'end'})
});
socket.on('exit', function() {
process2.kill();
})
})
socket.on('exit', function() {
process.kill();
})
});
}
}
})
});
function get_extension(language) {
switch(language) {
case 'javascript':
return '.js';
case 'ruby':
return '.rb'
case 'python':
return '.py'
case 'java':
return '.java'
// case 'objective-c':
// return '.m';
// case 'html':
// return '.html'
// case 'css':
// return '.css';
case 'shell':
return '.sh';
case 'c++':
return '.cpp';
case 'c':
return '.c';
default:
return null;
}
}
console.log('+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+');
console.log('HTTPS Server listening @ https://%s:%s', HOST, PORT);
console.log('+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+');<file_sep>var app = (function(){ // jshint ignore:line
'use strict';
var self = {};
self.socket = io();
// Common initialization function (to be called from each page)
self.initialize = function(){
jQuery('body').append(
'<div id="notification-message">' +
'<div id="notification-message-header">'+
'</div>' +
'<div id="notification-message-close"></div>' +
'<div id="notification-message-body"></div>' +
'</div>');
self.closeNotification = function() {
jQuery('#notification-message').hide();
self.socket.emit('exit');
}
jQuery('#notification-message-close').click(self.closeNotification);
// After initialization, expose a common notification function
self.showNotification = function(header, text){
jQuery('#notification-message-header').text(header);
jQuery('#notification-message-body').html(text.replace(/(?:\r\n|\r|\n)/g, '<br />'));
jQuery('#notification-message-body').append('<br/>');
jQuery('#notification-message').slideDown('fast');
jQuery('#notification-message').css("background-color", "#818285");
interact('#notification-message')
.resizable({
preserveAspectRatio: false,
edges: { top: true }
})
.on('resizemove', function (event) {
var content = document.getElementById('notification-message-body');
var target = event.target,
y = (parseFloat(target.getAttribute('data-y')) || 0);
// update the element's style
target.style.height = event.rect.height + 'px';
content.style.maxHeight = event.rect.height - 70 + 'px';
});
};
self.isNotificationClosed = function() {
return jQuery('#notification-message').css('display') === 'none';
}
self.appendNotification = function(text) {
// console.log(text.replace(/↵/g, "\n").replace(/(?:\r\n|\r|\n)/g, '<br />'));
jQuery('#notification-message-body').append(text.replace(/↵/g, "\n").replace(/(?:\r\n|\r|\n)/g, '<br />'));
// jQuery('.messages').animate({ scrollTop: $(this).height() }, "slow");
jQuery('#notification-message-body').scrollTop(jQuery('#notification-message-body')[0].scrollHeight);
}
self.showError = function(header, text){
jQuery('#notification-message-header').text(header);
jQuery('#notification-message-body').text(text);
jQuery('#notification-message').slideDown('fast');
jQuery('#notification-message-header').css("background-color", "#E81123");
interact('#notification-message')
.resizable({
preserveAspectRatio: false,
edges: { top: true }
})
.on('resizemove', function (event) {
var content = document.getElementById('notification-message-body');
var target = event.target,
y = (parseFloat(target.getAttribute('data-y')) || 0);
// update the element's style
target.style.height = event.rect.height + 'px';
content.style.maxHeight = event.rect.height - 70 + 'px';
});
};
};
return self;
})();
| 3fd50b32587ead0e8195eb8188e3249effdbea51 | [
"Markdown",
"JavaScript"
] | 4 | Markdown | timotius02/Docompiler | f24b68e66397ce82b2b10bd10d2bb63d2c5b6eaf | 76d373f69027d18a5fd18ce9325df6721cff7b62 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.