branch_name
stringclasses
15 values
target
stringlengths
26
10.3M
directory_id
stringlengths
40
40
languages
sequencelengths
1
9
num_files
int64
1
1.47k
repo_language
stringclasses
34 values
repo_name
stringlengths
6
91
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
input
stringclasses
1 value
refs/heads/master
<file_sep>CXX=/usr/bin/clang++ INCLUDE_DIRS=include ../include ./include INCDIR=include TESTDIR=test CXXFLAGS=-I$(INCDIR) -std=c++11 TESTFILES=$(shell find $(TESTDIR) -name '*.cpp') OBJFILES=$(patsubst test/%.cpp,bin/%.o,$(TESTFILES)) EXECS=$(patsubst test/%.cpp,bin/%,$(TESTFILES)) TEST_TARGETS=$(patsubst bin/%,%,$(EXECS)) PREV_BUILD=$(shell find ./.prev 2>/dev/null | xargs cat) .PHONY: Makefile all include src lib README.md bin test tests check-syntax .SUFFIXES: .cpp all: @echo Available targets: @echo - test: build all test targets @echo - [target]: build and run specified target test: $(EXECS) @echo $(EXECS) > ./.prev tests: test bin/%.o: test/%.cpp $(CXX) $(CXXFLAGS) -c $< -o $@ bin/%: bin/%.o $(CXX) $(CXXFLAGS) $< -o $@ $(TEST_TARGETS): $(eval OUTFILE=$(patsubst %,bin/%,$@) ) $(CXX) $(CXXFLAGS) $(patsubst %,test/%.cpp,$@) -o $(OUTFILE) @echo $(OUTFILE) > ./.prev @echo Running $(OUTFILE) @$(OUTFILE) clean: rm -f $(EXECS) rm -f $(OBJFILES) @clean $(INCDIR) $(TESTDIR) redo: clean $(PREV_BUILD) check-syntax: $(CXX) $(CXXFLAGS) -Wall -Wextra -fsyntax-only $(CHK_SOURCES) dumpvars: @echo $(foreach var, ${DUMPVARS}, "\n$(var)=$($(var))") <file_sep>#ifndef _MPH_DOUBLE_LIST_H_ #define _MPH_DOUBLE_LIST_H_ #include <iostream> #include "node.hpp" template <typename T> class DoubleList { public: Node<T> * fwalk(Node<T> * start, int dist) const; Node<T> * rwalk(Node<T> * start, int dist) const; Node<T> * head; Node<T> * tail; public: DoubleList(); DoubleList(T data); DoubleList(T * data, int len); DoubleList(DoubleList<T> * dl); ~DoubleList(); Node<T> * begin() const { return this->head; } Node<T> * end() const { return this->tail; } T insert(int pos, T data) { return this->add(pos, data); } T add(int pos, T data); T remove(int pos); T prepend(T data); T append(T data); void clear(); T at(int pos) const; T get(int pos) const; T set(int pos, T data); int size() const; }; template <typename T> DoubleList<T>::DoubleList(DoubleList<T> * dl) { for (int i = 0; i < dl->size(); i++) { this->append(dl->at(i)); } } template <typename T> Node<T> * DoubleList<T>::fwalk(Node<T> * start, int dist) const { Node<T> * tmp = start; for (int i = 0; i < dist; i++) { tmp = tmp->next; if (tmp->next == NULL) { return tmp; } } return tmp; } template <typename T> Node<T> * DoubleList<T>::rwalk(Node<T> * start, int dist) const { Node<T> * tmp = start; for (int i = 0; i < dist; i++) { tmp = tmp->prev; if (tmp->prev == NULL) { return tmp; } } return tmp; } template <typename T> DoubleList<T>::DoubleList() { this->head = NULL; this->tail = NULL; } template <typename T> DoubleList<T>::DoubleList(T data) { this->head = new Node<T>(data, NULL, NULL); this->tail = this->head; } template <typename T> DoubleList<T>::DoubleList(T * data, int len) { for (int i = 0; i < len; i++) { this->append(*(data + i)); } } template <typename T> DoubleList<T>::~DoubleList() { this->clear(); } template <typename T> T DoubleList<T>::add(int pos, T data) { if (pos > this->size()) { this->append(data); return data; } if (pos < 0) { this->prepend(data); return data; } Node<T> * tmp = fwalk(head, pos); Node<T> * new_node = new Node<T>(data, tmp->prev, tmp); tmp->prev = new_node; new_node->prev->next = new_node; return data; } template <typename T> T DoubleList<T>::remove(int pos) { Node<T> * tmp = fwalk(head, pos); if (tmp != this->head) { tmp->prev->next = tmp->next; } else { this->head = tmp->next; } if (tmp != this->tail) { tmp->next->prev = tmp->prev; } else { this->tail = tmp->prev; } T data = tmp->data; delete tmp; return data; } template <typename T> T DoubleList<T>::append(T data) { Node<T> * tmp = new Node<T>(data, this->tail, NULL); this->tail = tmp; if (this->head == NULL) { this->head = tmp; } else { tmp->prev->next = tmp; } return data; } template <typename T> T DoubleList<T>::prepend(T data) { Node<T> * tmp = new Node<T>(data, NULL, this->head); this->head = tmp; if (this->tail == NULL) { this->tail = tmp; } else { tmp->next->prev = tmp; } return data; } template <typename T> void DoubleList<T>::clear() { Node<T> * tmp; while (head != NULL) { tmp = head; head = tmp->next; delete tmp; } tail = head; } template <typename T> T DoubleList<T>::at(int pos) const { if (pos < 0) { return (T)(NULL); } return fwalk(head, pos)->data; } template <typename T> T DoubleList<T>::get(int pos) const { if (pos < 0) { return (T)(NULL); } return fwalk(head, pos)->data; } template <typename T> T DoubleList<T>::set(int pos, T data) { Node<T> * tmp = fwalk(head, pos); tmp->data = data; return data; } template <typename T> int DoubleList<T>::size() const { if (head == NULL) { return 0; } else if (head == tail) { return 1; } else if (head->next == tail) { return 2; } else { Node<T> * tmp = head; int count = 1; while (tmp->next != NULL) { tmp = tmp->next; count++; } return count; } } template<typename T> std::ostream & operator<<(std::ostream & out, const DoubleList<T> & l) { Node<T> * tmp = l.begin(); if (tmp == NULL) { out << "< empty >"; return out; } while (tmp != l.end()) { out << tmp->data << " <-> "; tmp = tmp->next; } out << l.end()->data; return out; } template<typename T> std::istream & operator>>(std::istream & in, DoubleList<T> & l) { T tmp; in >> tmp; l.append(tmp); return in; } #endif <file_sep>#ifndef _MPH_HASH_H_ #define _MPH_HASH_H_ #include <cmath> #include <vector.hpp> #include <list.hpp> namespace hash_functions { int knuth_div_hash(long k, int n) { return (k * (k + 3) ) % n; } int mod_hash(long k, int n) { return k % n; } int mult_hash(long k, int n) { float A = 0.5 * (sqrt(5) - 1); int s = floor(A * pow(2, 32)); int x = k * s; return x >> (32 - 16); } int knuth_mult_hash(long k, int n) { return (k * 2654435761) >> (32 - (int)floor(log2(n))); } int basic_hash(long k, int n) { return knuth_mult_hash(k, n); } }; template <typename T> class HashTable { private: int blocks; int (*hash_function)(long, int); Vector<List<T> > * contents; public: HashTable(); HashTable(int n); HashTable(int (*func)(int, int)); HashTable(int (*func)(int, int), int n); ~HashTable(); int size() const { return blocks; } int block_length(int block) const { return contents->at(block).size(); } int insert(T data); List<T> * const get_block(int block); T find(T data); }; template <typename T> using Hash = HashTable<T>; template <typename T> HashTable<T>::HashTable() { hash_function = hash_functions::basic_hash; blocks = 100; contents = new Vector<List<T> >(blocks); } template <typename T> HashTable<T>::HashTable(int s) { hash_function = hash_functions::basic_hash; blocks = s; contents = new Vector<List<T> >(blocks); } template <typename T> HashTable<T>::HashTable(int (*func)(int, int)) { hash_function = func; blocks = 100; contents = new Vector<List<T> >(blocks); } template <typename T> HashTable<T>::HashTable(int (*func)(int, int), int n) { hash_function = func; blocks = n; contents = new Vector<List<T> >(blocks); } template <typename T> HashTable<T>::~HashTable() { delete contents; } template <typename T> int HashTable<T>::insert(T data) { int k = hash_function((long)(data), size); contents->at(k).append(data); return k; } template <typename T> List<T> * const HashTable<T>::get_block(int block) { return contents->at(block); } template <typename T> T HashTable<T>::find(T data) { int k = hash_function((long)(data), size); return } #endif <file_sep>#ifndef _MPH_QUEUE_H_ #define _MPH_QUEUE_H_ #include <list.hpp> template <typename T> class Queue { private: List<T> contents; const int size; public: Queue() : size(0) { }; Queue(int s) : size(s) { }; Queue(List<T> data) : size(data.size()) { }; Queue(Queue<T> q) : size(q.size()); { }; Queue(List<T> data, int s) : size(s > data.size() ? s : data.size()) { }; Queue(Queue<T> data, int s) : size(s > data.length() ? s : data.size()) { }; ~Queue() { }; const int size() const { return size; } int length() const { return contents.size() }; bool is_empty() const { return this->length() == 0; } bool is_full() const { size == 0 ? return false : return this->length() == this->size(); } T peek() const { return contents.get(contents.size()); } T pop(); bool push(T data); }; template <typename T> T Queue<T>::pop() { if (is_empty()) { return (T)(0); } T data = contents.at(0); contents.remove(0); return data; } template <typename T> bool Queue<T>::push(T data) { if (is_full()) { return false; } contents.append(data); return true; } #endif <file_sep>#ifndef _MPH_LINKLIST_H_ #define _MPH_LINKLIST_H_ #include <iostream> #include "node.hpp" template <typename T> class LinkList { private: Node<T> * head; Node<T> * tail; Node<T> * walk(Node<T> * start, int pos) const; public: LinkList(); LinkList(T data); LinkList(T * data, int len); LinkList(LinkList<T> * dl); ~LinkList(); Node<T> * begin() const { return head; } Node<T> * end() const { return tail; } T add(int pos, T data); T remove(int pos); T prepend(T data); T append(T data); T at(int pos) const; T get(int pos) const; T set(int pos, T data); void clear(); int size() const; }; template <typename T> LinkList<T>::LinkList(LinkList<T> * dl) { for (int i = 0; i < dl->size(); i++) { this->append(dl->at(i)); } } template <typename T> Node<T> * LinkList<T>::walk(Node<T> * start, int pos) const { Node<T> * tmp = start; for (int i = 0; i < pos; i++) { tmp = tmp->next; if (tmp->next == NULL) { return tmp; } } return tmp; } template <typename T> LinkList<T>::LinkList() { head = NULL; tail = NULL; } template <typename T> LinkList<T>::LinkList(T data) { head = new Node<T>(data, NULL); tail = head; } template <typename T> LinkList<T>::LinkList(T * data, int len) { for (int i = 0; i < len; i++) { this->append(*(data + i)); } } template <typename T> LinkList<T>::~LinkList() { this->clear(); } template <typename T> T LinkList<T>::add(int pos, T data) { Node<T> * tmp = walk(head, pos); Node<T> * new_node = new Node<T>(data, tmp); walk(head, pos - 1)->next = new_node; return data; } template <typename T> T LinkList<T>::remove(int pos) { Node<T> * tmp = walk(head, pos); if (tmp == head) { head = head->next; } else if (tmp == tail) { tail = walk(head, pos - 1); tail->next = NULL; } else { walk(head, pos - 1)->next = walk(tmp, 1); } T data = tmp->data; delete tmp; return data; } template <typename T> T LinkList<T>::prepend(T data) { Node<T> * tmp = new Node<T>(data, NULL); tmp->next = head; head = tmp; return data; } template <typename T> T LinkList<T>::append(T data) { Node<T> * tmp = new Node<T>(data, NULL); tail->next = tmp; tail = tmp; return data; } template <typename T> T LinkList<T>::at(int pos) const { if (pos < 0) { return NULL; } return walk(head, pos)->data; } template <typename T> T LinkList<T>::get(int pos) const { if (pos < 0) { return NULL; } return walk(head, pos)->data; } template <typename T> T LinkList<T>::set(int pos, T data) { Node<T> * tmp = walk(head, pos); tmp->data = data; return data; } template <typename T> void LinkList<T>::clear() { Node<T> * tmp; while (head != NULL) { tmp = head; head = tmp->next; delete tmp; } tail = head; } template <typename T> int LinkList<T>::size() const { if (head == NULL) { return 0; } else if (head == tail) { return 1; } else if (head->next == tail) { return 2; } else { Node<T> * tmp = head; int count = 1; while (tmp->next != NULL) { tmp = tmp->next; count++; } return count; } } template<typename T> std::ostream & operator<<(std::ostream & out, const LinkList<T> & l) { Node<T> * tmp = l.begin(); if (tmp == NULL) { out << "< empty >"; return out; } while (tmp != l.end()) { out << tmp->data << " -> "; tmp = tmp->next; } out << l.end()->data; return out; } template<typename T> std::istream & operator>>(std::istream & in, LinkList<T> & l) { T tmp; in >> tmp; l.append(tmp); return in; } #endif <file_sep>#ifndef _MPH_STATIC_ARRAY_BAG_H_ #define _MPH_STATIC_ARRAY_BAG_H_ #include <iostream> template <typename T> class StaticArrayBag { private: int maxItems; int itemCount; T * contents; public: StaticArrayBag(); StaticArrayBag(int size); StaticArrayBag(int size, T * data, int len); ~StaticArrayBag(); int size() const { return itemCount; } bool isEmpty() const { return itemCount == 0; } bool isFull() const { return itemCount == maxItems; } bool insert(const T & newEntry); bool add(const T & newEntry) { return this->insert(newEntry); } bool remove(const T & toDelete); int contains(const T & data) const; template <typename U> friend std::ostream & operator<<(std::ostream & out, StaticArrayBag<U> & b); template <typename U> friend std::istream & operator>>(std::istream & in, StaticArrayBag<U> & b); }; template <typename T> StaticArrayBag<T>::StaticArrayBag() { maxItems = 10; itemCount = 0; contents = new T[maxItems]; } template <typename T> StaticArrayBag<T>::StaticArrayBag(int size) { itemCount = 0; if (size <= 0) { maxItems = 10; } else { maxItems = size; } contents = new T[maxItems]; } template <typename T> StaticArrayBag<T>::StaticArrayBag(int size, T * data, int len) { itemCount = 0; if (size <= 0) { maxItems = 10; } else { maxItems = size; } contents = new T[maxItems]; for (int i = 0; i < len; i++) { this->insert(data[i]); } } template <typename T> StaticArrayBag<T>::~StaticArrayBag() { delete [] contents; } template <typename T> bool StaticArrayBag<T>::insert(const T & newEntry) { if (itemCount >= maxItems) { return false; } contents[itemCount] = newEntry; itemCount++; return true; } template<typename T> std::istream & operator>>(std::istream & in, StaticArrayBag<T> & b) { T tmp; in >> tmp; b.add(tmp); return in; } template <typename T> std::ostream & operator<<(std::ostream & out, StaticArrayBag<T> & b) { for (int i = 0; i < b.size() - 1; i++) { out << b.contents[i] << ", "; } out << b.contents[b.size() - 1]; return out; } #endif <file_sep>#ifndef _MPH_MAP_H_ #define _MPH_MAP_H_ #endif <file_sep>#include <bag.hpp> #include <iostream> using namespace std; void show_ptrs_fwd(const List<double> * ll) { Node<double> * tmp = ll->begin(); cout << "Forward: "; while (tmp != NULL) { cout << tmp << " "; tmp = tmp->next; } cout << endl; } void show_ptrs_bwd(const List<double> * ll) { Node<double> * tmp = ll->end(); cout << "Backward: "; while (tmp != NULL) { cout << tmp << " "; tmp = tmp->prev; } cout << endl; } int main() { LinkListBag<double> b(5); const List<double> * c = b.get_contents(); b.add(5.5); b.add(3); b.add(4); b.add(3); cout << b << endl; show_ptrs_fwd(c); show_ptrs_bwd(c); cout << *c << endl; b.remove(3); show_ptrs_fwd(c); show_ptrs_bwd(c); cout << *c << endl; b.remove(3); show_ptrs_fwd(c); show_ptrs_bwd(c); cout << *c << endl; b.remove(5.5); show_ptrs_fwd(c); show_ptrs_bwd(c); cout << *c << endl; b.remove(4); show_ptrs_fwd(c); show_ptrs_bwd(c); cout << *c << endl; b.remove(5.5); show_ptrs_fwd(c); show_ptrs_bwd(c); cout << *c << endl; StaticArrayBag<double> dB(4); for (int i = 0; i < 1000; i++) { dB.insert(i); if (dB.isFull()) { cout << "Expanding!" << endl; } } cout << dB << endl; return 0; } <file_sep>/* bag.hpp */ #ifndef _MPH_LL_BAG_H_ #define _MPH_LL_BAG_H_ #include <iostream> using namespace std; #include <list.hpp> // Specification template <typename T> class LinkListBag { private: const int BAG_SIZE; List<T> contents; public: LinkListBag(int size) : BAG_SIZE(size) { } ~LinkListBag() { } const List<T> * get_contents() const { return &contents; } bool isEmpty() const; bool isFull() const; int contains(T data) const; const int size() const { return contents.size(); }; const int capacity() const { return BAG_SIZE; }; bool add(T data); bool remove(T data); template <typename U> friend std::ostream & operator<<(std::ostream & out, LinkListBag<U> & b); template <typename U> friend std::istream & operator>>(std::istream & in, LinkListBag<U> & b); }; // Implementation template <typename T> bool LinkListBag<T>::isEmpty() const { return (size() == 0); } template <typename T> bool LinkListBag<T>::isFull() const { return (size() == capacity()); } template <typename T> int LinkListBag<T>::contains(T data) const { int n = 0; for (int i = 0; i < this->size(); i++) { if (contents.at(i) == data) { n++; } } return n; } template <typename T> bool LinkListBag<T>::add(T data) { if (size() < capacity()) { contents.append(data); return true; } else { return false; } } template <typename T> bool LinkListBag<T>::remove(T data) { for (int i = 0; i < this->size(); i++) { if (contents.at(i) == data) { contents.remove(i); return true; } } return false; } template<typename T> std::istream & operator>>(std::istream & in, LinkListBag<T> & b) { T tmp; in >> tmp; b.add(tmp); return in; } template <typename T> std::ostream & operator<<(std::ostream & out, LinkListBag<T> & b) { if (b.isEmpty()) { out << "< empty >"; return out; } for (int i = 0; i < b.size() - 1; i++) { out << b.contents.at(i) << ", "; } out << b.contents.at(b.size() - 1); return out; } #endif <file_sep>#ifndef _MPH_NODE_H #define _MPH_NODE_H #ifndef NULL #define NULL 0 #endif template <typename T> class Node { public: T data; Node<T> * next; Node<T> * prev; Node(T d, Node<T> * n) { data = d; next = n; prev = NULL; } Node(T d, Node<T> * p, Node<T> * n) { data = d; next = n; prev = p; } }; #endif <file_sep>#ifndef _MPH_WRAPPER_QUEUE_H_ #define _MPH_WRAPPER_QUEUE_H_ #include <queue/queue.hpp> #include <queue/deque.hpp> template <typename T> using DoubleQueue = Deque<T>; #endif <file_sep>#ifndef _MPH_BAG_H_ #define _MPH_BAG_H_ #include <bags/static_array_bag.hpp> #include <bags/dynamic_array_bag.hpp> #include <bags/ll_bag.hpp> template <typename T> using Bag = LinkListBag<T>; #endif <file_sep>#ifndef _MPH_WRAPPER_DEQUE_H_ #define _MPH_WRAPPER_DEQUE_H_ #include <queue.hpp> #endif <file_sep>#include <stack.hpp> #include <iostream> using namespace std; int main() { cout << "Compiles!" << endl; Stack<int> s; s.push(4); s.push(5); s.pop(); cout << s << endl; int data[7] = {1, 4, 5, 8, 6, 5, 10}; s.push(data, 7); cout << s << endl; return 0; } <file_sep>Dacilndak/ds ============ A bunch of data structures made for CSCI2270. Use the Makefile.<file_sep>#include <hash.hpp> int main() { Hash<int> h; return 0; } <file_sep>#ifndef _MPH_LIST_H_ #define _MPH_LIST_H_ #include <list/node.hpp> #include <list/linklist.hpp> #include <list/doublelist.hpp> template <typename T> using List = DoubleList<T>; #endif <file_sep>#ifndef _MPH_STACK_H_ #define _MPH_STACK_H_ #include <list.hpp> #ifndef NULL #define NULL 0 #endif template <typename T> class Stack { private: List<T> contents; public: Stack() : contents() { } Stack(T data) : contents(data) { } Stack(T * data, int len) : contents(data, len) { } T pop(); T push(T data); T * push(T * data, int len); int size() const { return this->contents.size(); } template <typename U> friend std::ostream & operator<<(std::ostream & out, const Stack<U> & s); template <typename U> friend std::istream & operator>>(std::istream & out, Stack<U> & s); }; template <typename T> T Stack<T>::pop() { if (this->contents.size() == 0) { return (T)(NULL); } T temp = this->contents.at(this->contents.size()); this->contents.remove(this->contents.size()); return temp; } template <typename T> T Stack<T>::push(T data) { this->contents.append(data); return data; } template <typename T> T * Stack<T>::push(T * data, int len) { for (int i = 0; i < len; i++) { this->contents.append(data[i]); } return data; } template<typename T> std::ostream & operator<<(std::ostream & out, const Stack<T> & s) { out << s.contents; return out; } template<typename T> std::istream & operator>>(std::istream & in, Stack<T> & s) { T input; in >> input; s.push(input); return in; } #endif <file_sep>#ifndef _MPH_VECTOR_H_ #define _MPH_VECTOR_H_ template <typename T> class Vector { private: int size; T * contents; public: Vector(); Vector(int size); Vector(int size, T * data, int len); ~Vector(); bool insert(const T & newEntry, int index); bool append(const T & data); T & operator[](int index) { return this->at(index); } T & at(int index); int length() const { return size; } }; template <typename T> Vector<T>::Vector() { size = 0; contents = nullptr; } template <typename T> Vector<T>::Vector(int s) { size = s; contents = new T[size]; } template <typename T> Vector<T>::Vector(int s, T * data, int len) { size = s > len ? s : len; contents = new T[size]; for (int i = 0; i < len; i++) { contents[i] = data[i]; } } template <typename T> Vector<T>::~Vector() { if (contents != nullptr) { delete [] contents; } } template <typename T> bool Vector<T>::insert(const T & newEntry, int index) { size += 1; T * tmp = realloc(contents, size); if (tmp == nullptr) { return false; } contents = tmp; for (int i = size - 1; i > index; i--) { contents[i] = contents[i - 1]; } contents[index] = newEntry; return true; } template <typename T> bool Vector<T>::append(const T & data) { size += 1; T * tmp = realloc(contents, size); if (tmp == nullptr) { return false; } contents = tmp; contents[size - 1] = data; return true; } template <typename T> T & Vector<T>::at(int index) { return contents[index]; } #endif <file_sep>#ifndef _MPH_DEQUE_H_ #define _MPH_DEQUE_H_ template <typename T> class DoubleQueue { private: List<T> contents; const int size; public: DoubleQueue() : size(0) { }; DoubleQueue(int s) : size(s) { }; DoubleQueue(List<T> data) : size(data.size()) { }; DoubleQueue(DoubleQueue<T> q) : size(q.size()) { }; DoubleQueue(List<T> data, int s) : size(s > data.size() ? s : data.size()) { }; DoubleQueue(DoubleQueue<T> data, int s) : size(s > data.length() ? s : data.size()) { }; ~DoubleQueue() { }; const int capacity() const { return size; } const int size() const { return size; } int length() const { return contents.size(); }; bool is_empty() const { return this->length() == 0; } bool is_full() const { size == 0 ? return false : return this->length() >= this->size(); } T peek_front() const { return contents.get(0); } T peek_back() const { return contents.get(contents.size()); } T pop_front(); T pop_back(); bool push_front(T data); bool push_back(T data); }; template <typename T> T DoubleQueue<T>::pop_front() { if (is_empty()) { return (T)(0); } T data = contents.at(0); contents.remove(0); return data; } template <typename T> T DoubleQueue<T>::pop_back() { if (is_empty()) { return (T)(0); } T data = contents.at(contents.size()); contents.remove(contents.size()); return data; } template <typename T> bool DoubleQueue<T>::push_front(T data) { if (is_full()) { return false; } contents.prepend(data); return true; } template <typename T> bool DoubleQueue<T>::push_back(T data) { if (is_full()) { return false; } contents.append(data); return true; } #endif <file_sep>#include <list.hpp> #include <iostream> using namespace std; void show_ptrs(List<int> * ll) { Node<int> * tmp = ll->begin(); while (tmp != NULL) { cout << "Address: " << tmp << endl; tmp = tmp->next; } } int main() { int nums[4] = { 1, 2, 3, 4 }; List<int> x(nums, 4); cout << "Made list" << endl; show_ptrs(&x); x.append(20); cout << endl << "Appended" << endl; show_ptrs(&x); x.prepend(10); cout << endl << "Prepended" << endl; show_ptrs(&x); x.remove(1); cout << endl << "Removed" << endl; show_ptrs(&x); x.add(1, 20); x.add(2, 50); cout << endl << "Added" << endl; show_ptrs(&x); cout << "Size: " << x.size() << endl; cout << x; x.clear(); cout << endl << "Cleared" << endl; show_ptrs(&x); cout << x << endl; cout << "Size: " << x.size() << endl; cout << endl << "Destructor" << endl; return 0; } <file_sep>#ifndef _MPH_ARRAY_BAG_H_ #define _MPH_ARRAY_BAG_H_ #include <iostream> template <typename T> class DynamicArrayBag { private: int maxItems; int itemCount; T * contents; public: DynamicArrayBag(); DynamicArrayBag(int size); DynamicArrayBag(int size, T * data, int len); ~DynamicArrayBag(); bool insert(const T & newEntry); bool add(const T & newEntry) { return this->insert(newEntry); } bool remove(const T & toDelete); int contains(const T & data) const; int size() const { return itemCount; } bool isEmpty() const { return itemCount == 0; } bool isFull() const { return itemCount == maxItems; } template <typename U> friend std::ostream & operator<<(std::ostream & out, DynamicArrayBag<U> & b); template <typename U> friend std::istream & operator>>(std::istream & in, DynamicArrayBag<U> & b); }; template <typename T> DynamicArrayBag<T>::DynamicArrayBag() { maxItems = 10; itemCount = 0; contents = new T[maxItems]; } template <typename T> DynamicArrayBag<T>::DynamicArrayBag(int size) { itemCount = 0; if (size <= 0) { maxItems = 10; } else { maxItems = size; } contents = new T[maxItems]; } template <typename T> DynamicArrayBag<T>::DynamicArrayBag(int size, T * data, int len) { itemCount = 0; if (size <= 0) { maxItems = 10; } else { maxItems = size; } contents = new T[maxItems]; for (int i = 0; i < len; i++) { this->insert(data[i]); } } template <typename T> DynamicArrayBag<T>::~DynamicArrayBag() { delete [] contents; } template <typename T> bool DynamicArrayBag<T>::insert(const T & newEntry) { if (itemCount >= maxItems) { T * oldArray = contents; contents = new T[2 * maxItems]; for (int i = 0; i < maxItems; i++) { contents[i] = oldArray[i]; } delete [] oldArray; maxItems *= 2; } contents[itemCount] = newEntry; itemCount++; return true; } template <typename T> bool DynamicArrayBag<T>::remove(const T & toDelete) { for (int i = 0; i < itemCount; i++) { if (contents[i] == toDelete) { for (int j = i + 1; j < itemCount; j++) { contents[j - 1] = contents[j]; } itemCount--; return true; } } return false; } template <typename T> int DynamicArrayBag<T>::contains(const T & data) const { int n = 0; for (int i = 0; i < itemCount; i++) { if (contents[i] == data) { n++; } } return n; } template<typename T> std::istream & operator>>(std::istream & in, DynamicArrayBag<T> & b) { T tmp; in >> tmp; b.add(tmp); return in; } template <typename T> std::ostream & operator<<(std::ostream & out, DynamicArrayBag<T> & b) { for (int i = 0; i < b.size() - 1; i++) { out << b.contents[i] << ", "; } out << b.contents[b.size() - 1]; return out; } #endif
f7464ff8911bb52a52bec92cb6eb2d35c58584ec
[ "Markdown", "Makefile", "C++" ]
22
Makefile
thewpaney/ds
edae4a057912946329066338bada4deea8d723ab
d12bff662eb64ab25c761305c25e21efd1360a11
refs/heads/main
<repo_name>73nko/secret-santa<file_sep>/src/create-stars.js const $sky = $(".stars"); const skyHeight = $sky.innerHeight(), skyWidth = $sky.innerWidth(); const numberOfStars = (skyWidth * skyHeight) / 10000; for (let i = 0; i < numberOfStars; i++) { const starSize = Math.floor(Math.random() * 8 + 2), starTop = Math.floor(Math.random() * skyHeight), starLeft = Math.floor(Math.random() * skyWidth); $('<div class="star">') .css({ width: starSize, height: starSize, top: starTop, left: starLeft, }) .prependTo($sky); } <file_sep>/README.md # secret-santa A gift ^^ <file_sep>/src/index.js import "plax"; import "./create-snow"; import "./create-stars"; $(".js-plaxify").plaxify({ xRange: 20, yRange: 20 }); $.plax.enable();
88094fc39b6552b0e83883900acc2877c36a4590
[ "JavaScript", "Markdown" ]
3
JavaScript
73nko/secret-santa
c567689f698ffeb981f648624a9978813c5a90d4
3fec90ddd760a3718cfc38bb695efc7b8c29442c
refs/heads/master
<repo_name>Hatsune39/raspberryPi<file_sep>/installations/pi-setup-lirc.sh #! /bin/bash sudo apt update sudo apt install -y lirc sudo sed -i 's/DRIVER="UNCONFIGURED"/DRIVER="default"/g' /etc/lirc/hardware.conf sudo sed -i 's/DEVICE=""/DEVICE="\/dev\/lirc0"/g' /etc/lirc/hardware.conf sudo sed -i 's/MODULES=""/MODULES="lirc-rpi"/g' /etc/lirc/hardware.conf # enable lirc-rpi sudo sed -i 's/#dtoverlay=lirc-rpi/dtoverlay=lirc-rpi,gpio_in_pin=24,gpio_out_pin=10/g' /boot/config.txt # record # irrecord -d /dev/lirc0 ~/lircd.conf cd ~ wget https://github.com/newnius/raspberryPi/raw/master/installations/lircd.conf sudo mv ~/lircd.conf /etc/lirc/lircd.conf # add .lircrc events wget https://github.com/newnius/raspberryPi/raw/master/installations/.lircrc sudo reboot # irexec -d <file_sep>/sensors/distance.py #!/usr/bin/python #-*- coding: utf-8 -*- # HC-SR04超声波传感器 import time import RPi.GPIO as GPIO import os GPIO.setmode(GPIO.BCM) #使用BCM编码方式 #定义引脚 GPIO_ECHO = 22 GPIO_TRIGGER = 23 #设置引脚为输入和输出 GPIO.setwarnings(False) GPIO.setup(GPIO_TRIGGER, GPIO.OUT) GPIO.setup(GPIO_ECHO, GPIO.IN) def detect(): GPIO.output(GPIO_TRIGGER, False) time.sleep(0.5) GPIO.output(GPIO_TRIGGER, True) time.sleep(0.00001) GPIO.output(GPIO_TRIGGER, False) start = time.time() while(GPIO.input(GPIO_ECHO))==0: #当有障碍物时,传感器输出低电平,所以检测低电平 start = time.time() while(GPIO.input(GPIO_ECHO))==1: #当有障碍物时,传感器输出低电平,所以检测低电平 stop = time.time() elapsed = stop-start #计算一共花费多长时间 distance = elapsed * 34300 #计算距离,就是时间乘以声速 distance = distance / 2 #除以2得到一次的距离而不是来回的距离 print "Distance : %.1fcm" % distance while True: detect() time.sleep(1) GPIO.cleanup() <file_sep>/installations/os_install.md # OS install Based on MacOS ## Format SD card download [SD Memory Card Formatter](https://www.sdcard.org/downloads/formatter/) and format the SD card ## Download rasbian img file download from [Raspbian Download Page](https://www.raspberrypi.org/downloads/raspbian/) ## Unmount SD card ```bash # use `diskutil list` to see disk name diskutil unmountDisk /dev/disk2 ``` ## dd img to SD card ```bash sudo dd if=raspbian-stretch-lite.img of=/dev/rdisk2 bs=1m;sync ``` *use rdisk to boost, or it would takes rather a long time to write the image* ## Create ssh dir to enable ssh service Create a dir named `ssh` under the root dir of SD card to enable ssh service ## Eject SD card ```bash diskutil eject /dev/ ``` ## Update mirror (if necessary) A full list of mirrors located at [Raspbian Mirrors](https://www.raspbian.org/RaspbianMirrors) ``` # /etc/apt/sources.list deb https://mirrors.ustc.edu.cn/raspbian/raspbian/ stretch main contrib non-free rpi # /etc/apt/sources.list.d/raspi.list deb https://archive.raspberrypi.org/debian/ stretch main ui ``` *use ssl to get rid of `Hash Sum mismatch`. I hate the ICPs!* ## How to find the ip address ### By a monitor which supports HDMI ### Scan the network with nmap ### In the router management panel ## Ref [MacOS下树莓派烧录img/iso文件到SD卡](https://www.jianshu.com/p/e95c406badaa) [解决macOS使用dd指令写入/读取速度过慢的问题](https://zhuanlan.zhihu.com/p/34603784) [系列 - 树莓派装机(二)](https://www.barretlee.com/blog/2018/06/14/rasyberry-pi-os/) <file_sep>/cloudflared/install.sh #!/bin/bash # setup DoH # install 32bit architecture # see https://forum.armbian.com/topic/4764-running-32-bit-applications-on-aarch64/ dpkg --add-architecture armhf apt-get update apt-get install libc6:armhf libstdc++6:armhf wget -O cloudflared.tgz https://bin.equinox.io/c/VdrWdbjqyF/cloudflared-stable-linux-arm.tgz \ && tar -xzvf cloudflared.tgz \ && rm cloudflared.tgz ./cloudflared <file_sep>/sensors/climbing.py #!/usr/bin/python #-*- coding: utf-8 -*- # 倾斜传感器模块 import time import RPi.GPIO as GPIO import os GPIO.setmode(GPIO.BCM) #使用BCM编码方式 #定义引脚 GPIO_1 = 1 GPIO_2 = 2 GPIO_3 = 3 GPIO_4 = 4 GPIO_16 = 16 GPIO_21 = 21 GPIO_22 = 22 GPIO_23 = 23 GPIO_24 = 24 led = 21 #设置引脚为输入和输出 GPIO.setwarnings(False) #设置23针脚为输入,接到红外避障传感器模块的out引脚 #GPIO.setup(GPIO_23,GPIO.IN) GPIO.setup(GPIO_22,GPIO.IN) def warn(): #亮灯来作为有障碍物时发出的警告 # GPIO.output(led,GPIO.HIGH) # time.sleep(0.5) # GPIO.output(led,GPIO.LOW) time.sleep(0.5) print "warn" while True: if(GPIO.input(GPIO_22)==0): #当有障碍物时,传感器输出低电平,所以检测低电平 print "climbing" time.sleep(0.5) GPIO.cleanup() <file_sep>/sensors/16种传感器套件/DS1302实时时钟模块/DS1302 Experiment PIC/DS1302.C /******************************************************** 实验十九: DS1302时钟芯片实验 说明: 因为该型号开发板只有四位数码管, 为了方便看到实验效果只显示分与秒 实验现象: 数码管上显示分与秒 CPU型号: PIC16F877A 时钟: 4MHZ 日期: 2010-12-2 联系方法: CJMCU ********************************************************/ #include <pic.h> //调用头文件 __CONFIG(0x3F32); //芯片配置字 #define uchar unsigned char #define uint unsigned int //联接DS1302的端口定义 #define ds1302_rst RC2 //定义1302的RST接在PC4 #define ds1302_io RC1 //定义1302的IO接在PC3 #define ds1302_sclk RC0 //定义1302的时钟接在PC2 #define set_ds1302_rst_ddr() TRISC2=0 //复位端置为输出 #define set_ds1302_rst() ds1302_rst=1 //复位端置1 #define clr_ds1302_rst() ds1302_rst=0 //复位端清0 #define set_ds1302_io_ddr() TRISC1=0 //数据端置为输出 #define set_ds1302_io() ds1302_io=1 //数据端置1 #define clr_ds1302_io() ds1302_io=0 //数据端清0 #define clr_ds1302_io_ddr() TRISC1=1 //数据端置为输入 #define in_ds1302_io() PORTC&0X02 //数据端输入数据 #define set_ds1302_sclk_ddr() TRISC0=0 //时钟端置为输出 #define set_ds1302_sclk() ds1302_sclk=1 //时钟端置1 #define clr_ds1302_sclk() ds1302_sclk=0 //时钟端清0 #define ds1302_sec_add 0x80 //秒数据地址 #define ds1302_min_add 0x82 //分数据地址 #define ds1302_hr_add 0x84 //时数据地址 #define ds1302_date_add 0x86 //日数据地址 #define ds1302_month_add 0x88 //月数据地址 #define ds1302_day_add 0x8a //星期数据地址 #define ds1302_year_add 0x8c //年数据地址 #define ds1302_control_add 0x8e //控制数据地址 #define ds1302_charger_add 0x90 #define ds1302_clkburst_add 0xbe uchar timer[8]; //时钟数据 //共阴数码管0-F显示代码 uchar Table[]={0xc0,0xf9,0xa4,0xb0,0x99, 0x92,0x82,0xf8,0x80,0x90,0xff}; //转换后的显示数据 uchar s[4]; //定义扫描计数器 uchar sel=0; uchar temp_pa=0xFF; /************************************* * DS1302操作函数组 * *************************************/ //写入1302数据函数: //入口:add为写入地址码,data为写入数据 //返回:无 void ds1302_write(uchar add,uchar data) { uchar i=0; set_ds1302_io_ddr(); //配置IO为输出 NOP();NOP(); clr_ds1302_rst(); //清复位,停止所有操作 NOP();NOP(); clr_ds1302_sclk(); //清时钟,准备操作 NOP();NOP(); set_ds1302_rst(); //置复位,开始操作 NOP();NOP(); for(i=8;i>0;i--) //此循环写入控制码 { if(add&0x01) set_ds1302_io(); //当前位为1,置数据位 else clr_ds1302_io(); //当前位为0,清数据位 NOP();NOP(); set_ds1302_sclk(); //产生时钟脉冲,写入数据 NOP();NOP(); clr_ds1302_sclk(); NOP();NOP(); add>>=1; //移位,准备写入下1位 } for(i=8;i>0;i--) //此循环写入数据码 { if(data&0x01) set_ds1302_io(); else clr_ds1302_io(); NOP();NOP(); set_ds1302_sclk(); NOP();NOP(); clr_ds1302_sclk(); NOP();NOP(); data>>=1; } clr_ds1302_rst(); NOP();NOP(); clr_ds1302_io_ddr(); //清输出状态 NOP();NOP(); } //从1302中读出数据: //入口:add为读数据所在地址 //返回:读出的数据data uchar ds1302_read(uchar add) { uchar data=0; uchar i=0; add+=1; //读标志 set_ds1302_io_ddr(); //端口输出 NOP();NOP(); clr_ds1302_rst(); //清复位 NOP();NOP(); clr_ds1302_sclk(); //清时钟 NOP();NOP(); set_ds1302_rst(); //置复位 NOP();NOP(); for(i=8;i>0;i--) //此循环写入地址码 { if(add&0x01) {set_ds1302_io();} else {clr_ds1302_io();} NOP();NOP(); set_ds1302_sclk(); NOP();NOP(); clr_ds1302_sclk(); NOP();NOP(); add>>=1; } clr_ds1302_io_ddr(); //端口输入 NOP();NOP(); for(i=8;i>0;i--) //此循环读出1302的数据 { data>>=1; if(in_ds1302_io()) {data|=0x80;} NOP();NOP(); set_ds1302_sclk(); NOP();NOP(); clr_ds1302_sclk(); NOP();NOP(); } clr_ds1302_rst(); NOP();NOP(); return(data); } //检查1302状态 uchar check_ds1302(void) { ds1302_write(ds1302_control_add,0x80); if(ds1302_read(ds1302_control_add)==0x80) return 1; return 0; } //向1302中写入时钟数据 void ds1302_write_time(void) { ds1302_write(ds1302_control_add,0x00); //关闭写保护 ds1302_write(ds1302_sec_add,0x80); //暂停 ds1302_write(ds1302_charger_add,0xa9); //涓流充电 ds1302_write(ds1302_year_add,timer[1]); //年 ds1302_write(ds1302_month_add,timer[2]); //月 ds1302_write(ds1302_date_add,timer[3]); //日 ds1302_write(ds1302_day_add,timer[7]); //周 ds1302_write(ds1302_hr_add,timer[4]); //时 ds1302_write(ds1302_min_add,timer[5]); //分 ds1302_write(ds1302_sec_add,timer[6]); //秒 ds1302_write(ds1302_control_add,0x80); //打开写保护 } //从1302中读出当前时钟 void ds1302_read_time(void) { timer[1]=ds1302_read(ds1302_year_add); //年 timer[2]=ds1302_read(ds1302_month_add); //月 timer[3]=ds1302_read(ds1302_date_add); //日 timer[7]=ds1302_read(ds1302_day_add); //周 timer[4]=ds1302_read(ds1302_hr_add); //时 timer[5]=ds1302_read(ds1302_min_add); //分 timer[6]=ds1302_read(ds1302_sec_add); //秒 } //延时函数1 void delay_us(uchar i) { for(;i;i--); } //延时函数2 void delay(uint i) { uchar j; for(;i;i--) for(j=220;j;j--); } void timer0_init(void) { OPTION=0x07; //TMR0----256分频 INTCON=0XA0; //开总中断及TMR0计数溢出断 TMR0=0xE8; //定时器初值 } /* 定时器0中断入口函数 */ void interrupt TMR0INT() { T0IF=0; TMR0=0xE8; PORTD=0xff; //先关显示 PORTA=0XDF; PORTD=s[sel]; switch(sel) { case 0x00: PORTA=0X1D;break; case 0x01: PORTA=0X1B;break; case 0x02: PORTA=0X17;break; case 0x03: PORTA=0X0F;break; } if(++sel>3)sel=0; } //显示数据转换函数 void Process(void)//(uint i) { s[3]=Table[(timer[5]&0xF0)>>4]; s[2]=Table[(timer[5]&0x0F)]&0x7F; //初始化显示数据,并将时分之间加小数点 s[1]=Table[(timer[6]&0xF0)>>4]; s[0]=Table[(timer[6]&0x0F)]; } //主函数 void main(void) { uint n,m=0; TRISA=0x00; //设置按键A口为带上拉输入; PORTA=0xDF; TRISD=0x00; PORTD=0XFF; TRISE=0X03; PORTE=0X05; PORTE=0X00; TRISC=0x00; //定义C口为输出 PORTC=0xff; timer[1]=0x09; //年 timer[2]=0x08; //月 timer[3]=0x20; //日 timer[4]=0x12; //时 timer[5]=0x12; //分 timer[6]=0x00; //秒 timer[7]=0x04; //周 ds1302_write_time(); //写入初始时钟 timer0_init(); //设定定时器0 while(1) { ds1302_read_time(); //读出当前时钟 Process(); //显示数据转换 delay(100); //每100MS读一次 } } <file_sep>/sensors/16种传感器套件/DS1302实时时钟模块/DS1302实时时钟实验(ATMEGA128A)/DS1302.C /******************************************************** 实验十九: DS1302时钟芯片实验 说明: 显示时 分 秒 实验现象: 数码管上显示分与秒 CPU型号: ATMEGA128A 时钟: 8MHZ 日期: 2011-3-17 联系方法: CJMCU ********************************************************/ #include <iom128v.h> #include <macros.h> //联接DS1302的端口定义 #define ds1302_rst PE4 //定义1302的RST接在PC4 #define ds1302_io PE3 //定义1302的IO接在PC3 #define ds1302_sclk PE2 //定义1302的时钟接在PC2 #define set_ds1302_rst_ddr() DDRE|=1<<ds1302_rst //复位端置为输出 #define set_ds1302_rst() PORTE|=1<<ds1302_rst //复位端置1 #define clr_ds1302_rst() PORTE&=~(1<<ds1302_rst) //复位端清0 #define set_ds1302_io_ddr() DDRE|=1<<ds1302_io //数据端置为输出 #define set_ds1302_io() PORTE|=1<<ds1302_io //数据端置1 #define clr_ds1302_io() PORTE&=~(1<<ds1302_io) //数据端清0 #define clr_ds1302_io_ddr() DDRE&=~(1<<ds1302_io) //数据端置为输入 #define in_ds1302_io() PINE&(1<<ds1302_io) //数据端输入数据 #define set_ds1302_sclk_ddr() DDRE|=1<<ds1302_sclk //时钟端置为输出 #define set_ds1302_sclk() PORTE|=1<<ds1302_sclk //时钟端置1 #define clr_ds1302_sclk() PORTE &=~(1<<ds1302_sclk) //时钟端清0 #define ds1302_sec_add 0x80 //秒数据地址 #define ds1302_min_add 0x82 //分数据地址 #define ds1302_hr_add 0x84 //时数据地址 #define ds1302_date_add 0x86 //日数据地址 #define ds1302_month_add 0x88 //月数据地址 #define ds1302_day_add 0x8a //星期数据地址 #define ds1302_year_add 0x8c //年数据地址 #define ds1302_control_add 0x8e //控制数据地址 #define ds1302_charger_add 0x90 #define ds1302_clkburst_add 0xbe //简化宏定义 #define uchar unsigned char #define uint unsigned int //全局变量定义 uchar timer[8]; //时钟数据 //共阴数码管0-F显示代码 uchar Table[]={0xc0,0xf9,0xa4,0xb0,0x99, 0x92,0x82,0xf8,0x80,0x90,0xff}; //转换后的显示数据 uchar s[6]; //定义扫描计数器 uchar sel=0; uchar temp_pa=0xFF; /************************************* * DS1302操作函数组 * *************************************/ //写入1302数据函数: //入口:add为写入地址码,data为写入数据 //返回:无 void ds1302_write(uchar add,uchar data) { uchar i=0; set_ds1302_io_ddr(); //配置IO为输出 delay_us(20); clr_ds1302_rst(); //清复位,停止所有操作 delay_us(20); clr_ds1302_sclk(); //清时钟,准备操作 delay_us(20); set_ds1302_rst(); //置复位,开始操作 delay_us(20); for(i=8;i>0;i--) //此循环写入控制码 { if(add&0x01) set_ds1302_io(); //当前位为1,置数据位 else clr_ds1302_io(); //当前位为0,清数据位 delay_us(20); set_ds1302_sclk(); //产生时钟脉冲,写入数据 NOP();NOP();NOP(); clr_ds1302_sclk(); delay_us(20); add>>=1; //移位,准备写入下1位 } for(i=8;i>0;i--) //此循环写入数据码 { if(data&0x01) set_ds1302_io(); else clr_ds1302_io(); delay_us(20); set_ds1302_sclk(); delay_us(20); clr_ds1302_sclk(); delay_us(20); data>>=1; } clr_ds1302_rst(); delay_us(20); clr_ds1302_io_ddr(); //清输出状态 delay_us(20); } //从1302中读出数据: //入口:add为读数据所在地址 //返回:读出的数据data uchar ds1302_read(uchar add) { uchar data=0; uchar i=0; add+=1; //读标志 set_ds1302_io_ddr(); //端口输出 delay_us(20); clr_ds1302_rst(); //清复位 delay_us(20); clr_ds1302_sclk(); //清时钟 delay_us(20); set_ds1302_rst(); //置复位 delay_us(20); for(i=8;i>0;i--) //此循环写入地址码 { if(add&0x01) {set_ds1302_io();} else {clr_ds1302_io();} delay_us(20); set_ds1302_sclk(); delay_us(20); clr_ds1302_sclk(); delay_us(20); add>>=1; } clr_ds1302_io_ddr(); //端口输入 delay_us(20); for(i=8;i>0;i--) //此循环读出1302的数据 { data>>=1; if(in_ds1302_io()) {data|=0x80;} delay_us(20); set_ds1302_sclk(); delay_us(20); clr_ds1302_sclk(); delay_us(20); } clr_ds1302_rst(); delay_us(20); return(data); } //检查1302状态 uchar check_ds1302(void) { ds1302_write(ds1302_control_add,0x80); if(ds1302_read(ds1302_control_add)==0x80) return 1; return 0; } //向1302中写入时钟数据 void ds1302_write_time(void) { ds1302_write(ds1302_control_add,0x00); //关闭写保护 ds1302_write(ds1302_sec_add,0x80); //暂停 ds1302_write(ds1302_charger_add,0xa9); //涓流充电 ds1302_write(ds1302_year_add,timer[1]); //年 ds1302_write(ds1302_month_add,timer[2]); //月 ds1302_write(ds1302_date_add,timer[3]); //日 ds1302_write(ds1302_day_add,timer[7]); //周 ds1302_write(ds1302_hr_add,timer[4]); //时 ds1302_write(ds1302_min_add,timer[5]); //分 ds1302_write(ds1302_sec_add,timer[6]); //秒 ds1302_write(ds1302_control_add,0x80); //打开写保护 } //从1302中读出当前时钟 void ds1302_read_time(void) { timer[1]=ds1302_read(ds1302_year_add); //年 timer[2]=ds1302_read(ds1302_month_add); //月 timer[3]=ds1302_read(ds1302_date_add); //日 timer[7]=ds1302_read(ds1302_day_add); //周 timer[4]=ds1302_read(ds1302_hr_add); //时 timer[5]=ds1302_read(ds1302_min_add); //分 timer[6]=ds1302_read(ds1302_sec_add); //秒 } /************************************** * 扫描显示函数组 * **************************************/ //延时函数1 void delay_us(uchar i) { for(;i;i--); } //延时函数2 void delay(uint i) //在1M时钟下为i ms { uchar j; for(;i;i--) for(j=220;j;j--); } /* 定时器0中断配置函数 预分频数:256 定时时间: 5mSec 实际时间: 4.864mSec (2.7%) 功能:用于LED数码管显示扫描*/ void timer0_init(void) { TCNT0 = 0xED; //装初值 TCNT0 = 0x00; //装初值 OCR0 = 0x13; //这个是比较值? TCCR0 = 0x04; //启动定时器 } /* 定时器0中断入口函数 */ #pragma interrupt_handler timer0_ovf_isr:17 void timer0_ovf_isr(void) { TCNT0 = 0xED; //重装初值 PORTC=0xff; //先关显示 PORTA=0X00; PORTC=s[sel]; switch(sel) { case 0x00: PORTA=0X80;break; case 0x01: PORTA=0X40;break; case 0x02: PORTA=0X20;break; case 0x03: PORTA=0X10;break; case 0x04: PORTA=0X08;break; case 0x05: PORTA=0X04;break; } if(++sel>5)sel=0; } //显示数据转换函数 void Process(void)//(uint i) { s[5]=Table[(timer[4]&0xf0)>>4]; s[4]=Table[(timer[4]&0x0F)]&0x7F; s[3]=Table[(timer[5]&0xF0)>>4]; s[2]=Table[(timer[5]&0x0F)]&0x7F; //初始化显示数据,并将时分之间加小数点 s[1]=Table[(timer[6]&0xF0)>>4]; s[0]=Table[(timer[6]&0x0F)]; } //主函数 void main(void) { uint n,m=0; DDRA=0xff; //设置按键A口为带上拉输入; PORTA=0xFF; DDRE=0xff; PORTE=0X1C; DDRC=0xff; //定义B口为输出 PORTC=0xff; DDRF|=0X0E; PORTF|=0X0E; PORTF &=~BIT(3); PORTA=0XFF; DDRB |=0X10; //PB4设为输出 PORTB|=0X10; //关闭PB4外接的LED timer[1]=0x11; //年 timer[2]=0x03; //月 timer[3]=0x20; //日 timer[4]=0x12; //时 timer[5]=0x00; //分 timer[6]=0x00; //秒 timer[7]=0x00; //周 delay(200); ds1302_write_time(); //写入初始时钟 delay(100); CLI(); //先关闭所有中断 timer0_init(); //设定定时器0 MCUCR = 0x00; TIMSK = 0x05; //允许定时器0、定时器1中断 SEI(); //开总中断 while(1) { ds1302_read_time(); //读出当前时钟 Process(); //显示数据转换 delay(500); //每100MS读一次 } } <file_sep>/sensors/16种传感器套件/DS1302实时时钟模块/DS1302实时时钟实验(ATMEGA128A)/DS1302.mak CC = iccavr LIB = ilibw CFLAGS = -e -D__ICC_VERSION=722 -DATMega128 -l -g -MLongJump -MHasMul -MEnhanced -Wf-use_elpm ASFLAGS = $(CFLAGS) LFLAGS = -g -e:0x20000 -ucrtatmega.o -bfunc_lit:0x8c.0x20000 -dram_end:0x10ff -bdata:0x100.0x10ff -dhwstk_size:30 -beeprom:0.4096 -fihx_coff -S2 FILES = DS1302.o DS1302: $(FILES) $(CC) -o DS1302 $(LFLAGS) @DS1302.lk -lcatm128 DS1302.o: C:\iccv7avr\include\iom128v.h C:\iccv7avr\include\macros.h C:\iccv7avr\include\AVRdef.h DS1302.o: ..\..\..\BK-AVR~1\BK-AVR128配套实验程序\实1C23~1\DS1302.C $(CC) -c $(CFLAGS) ..\..\..\BK-AVR~1\BK-AVR128配套实验程序\实1C23~1\DS1302.C <file_sep>/sensors/obstacle-detect.py #!/usr/bin/python #-*- coding: utf-8 -*- # 避障传感器 壁障小车 黑白线识别 import time import RPi.GPIO as GPIO import os GPIO.setmode(GPIO.BCM) #使用BCM编码方式 #定义引脚 GPIO_1 = 1 GPIO_2 = 2 GPIO_3 = 3 GPIO_4 = 4 GPIO_16 = 16 GPIO_21 = 21 GPIO_23 = 23 GPIO_24 = 24 led = 21 #设置引脚为输入和输出 GPIO.setwarnings(False) #设置23针脚为输入,接到红外避障传感器模块的out引脚 GPIO.setup(GPIO_23,GPIO.IN) #GPIO.setup(led,GPIO.OUT) def warn(): #亮灯来作为有障碍物时发出的警告 # GPIO.output(led,GPIO.HIGH) # time.sleep(0.5) # GPIO.output(led,GPIO.LOW) time.sleep(0.5) print "warn" while True: #GPIO.input(GPIO_23)==0: #当有障碍物时,传感器输出低电平,所以检测低电平 print GPIO.input(GPIO_23) #当有障碍物时,传感器输出低电平,所以检测低电平 GPIO.cleanup() <file_sep>/installations/pi-setup-player.sh #! /bin/bash # sudo apt-get update # install mplyer sudo apt install -y mplayer2 # level up USB audio card # this conf file is in /etc/modprobe.d/alsa-base.conf if not Raspbian Jessie # http://5aimiku.com/archives/400.html sudo sed -i "s/options snd-usb-audio index=-2/options snd-usb-audio index=0/g" /lib/modprobe.d/aliases.conf echo "need reboot" <file_sep>/usr/local/services.sh #! /bin/bash # login to p.nju.edu.cn nohup python /usr/local/pnju.py & # run fan control nohup python /usr/local/fan.py & # start frp nohup /usr/local/frp/frpc -c /usr/local/frp/frpc.ini & # start DoH to fuck GFW nohup /usr/local/cloudflared proxy-dns --port 15353 & # start global vpn service nohup bash /usr/local/global_vpn.sh & <file_sep>/sensors/test.py #!/usr/bin/python #-*- coding: utf-8 -*- import time import RPi.GPIO as GPIO import os GPIO.setmode(GPIO.BCM) #使用BCM编码方式 #定义引脚 GPIO_OUT = 5 led = 4 #设置引脚为输入和输出 GPIO.setwarnings(False) #设置23针脚为输入,接到红外避障传感器模块的out引脚 GPIO.setup(GPIO_OUT,GPIO.IN) GPIO.setup(led,GPIO.OUT) GPIO.output(led,GPIO.LOW) time.sleep(5) def warn(): #亮灯来作为有障碍物时发出的警告 GPIO.output(led,GPIO.HIGH) time.sleep(0.5) GPIO.output(led,GPIO.LOW) time.sleep(0.5) #while True: # if GPIO.input(GPIO_OUT)==0: #当有障碍物时,传感器输出低电平,所以检测低电平 # warn() GPIO.cleanup() <file_sep>/etc/rc.local #!/bin/sh -e # # rc.local # # This script is executed at the end of each multiuser runlevel. # Make sure that the script will "" on success or any other # value on error. # # In order to enable or disable this script just change the execution # bits. # # By default this script does nothing. # Print the IP address _IP=$(hostname -I) || true if [ "$_IP" ]; then printf "My IP address is %s\n" "$_IP" fi ifconfig wlan0 down ifconfig wlan0 192.168.68.1 netmask 255.255.255.0 up iwconfig wlan0 power off service dnsmasq restart hostapd -B /etc/hostapd/hostapd.conf & > /dev/null 2>&1 sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE sudo iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT sudo iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT bash /usr/local/services.sh exit 0 <file_sep>/usr/local/global_vpn.sh #!/bin/bash # restore Chineses IPs ipset restore < /etc/chnroute.ipset # add iptables chain iptables -t nat -N SHADOWSOCKS # exclude your own vps IPs # exclude CloudFlare IPs iptables -t nat -A SHADOWSOCKS -d 192.168.3.11/20 -j RETURN iptables -t nat -A SHADOWSOCKS -d 192.168.3.11/22 -j RETURN iptables -t nat -A SHADOWSOCKS -d 192.168.3.11/22 -j RETURN iptables -t nat -A SHADOWSOCKS -d 172.16.31.10/22 -j RETURN iptables -t nat -A SHADOWSOCKS -d 172.16.31.10/18 -j RETURN iptables -t nat -A SHADOWSOCKS -d 172.16.17.32/18 -j RETURN iptables -t nat -A SHADOWSOCKS -d 172.16.58.3/20 -j RETURN iptables -t nat -A SHADOWSOCKS -d 192.168.3.11/20 -j RETURN iptables -t nat -A SHADOWSOCKS -d 192.168.127.12/22 -j RETURN iptables -t nat -A SHADOWSOCKS -d 172.16.58.3/17 -j RETURN iptables -t nat -A SHADOWSOCKS -d 192.168.3.11/15 -j RETURN iptables -t nat -A SHADOWSOCKS -d 192.168.3.11/12 -j RETURN iptables -t nat -A SHADOWSOCKS -d 172.16.31.10/13 -j RETURN iptables -t nat -A SHADOWSOCKS -d 131.0.72.0/22 -j RETURN # excluce intranet ips & Chinese IPs iptables -t nat -A SHADOWSOCKS -d 0.0.0.0/8 -j RETURN iptables -t nat -A SHADOWSOCKS -d 10.0.0.0/8 -j RETURN iptables -t nat -A SHADOWSOCKS -d 127.0.0.0/8 -j RETURN iptables -t nat -A SHADOWSOCKS -d 169.254.0.0/16 -j RETURN iptables -t nat -A SHADOWSOCKS -d 172.16.0.0/12 -j RETURN iptables -t nat -A SHADOWSOCKS -d 192.168.0.0/16 -j RETURN iptables -t nat -A SHADOWSOCKS -d 192.168.127.12/4 -j RETURN iptables -t nat -A SHADOWSOCKS -d 240.0.0.0/4 -j RETURN iptables -t nat -A SHADOWSOCKS -m set --match-set chnroute dst -j RETURN # redirect traffic to redsocks iptables -t nat -A SHADOWSOCKS -p tcp -j REDIRECT --to-ports 12345 # redirect traffic to SHADOWSOCKS iptables -t nat -A OUTPUT -p tcp -j SHADOWSOCKS iptables -t nat -A PREROUTING -p tcp -j SHADOWSOCKS # overide default dns ns of devices iptables -t nat -A PREROUTING -p udp --dport 53 -j REDIRECT --to-ports 53 iptables -t nat -A PREROUTING -p tcp --dport 53 -j REDIRECT --to-ports 53 exit 0 <file_sep>/installations/apt_install.sh #!/bin/bash ```bash sudo apt install -y git vim curl wget httpie tree ``` <file_sep>/installations/pi-setup-LCD5.sh #! /bin/bash git clone https://github.com/goodtft/LCD-show.git chmod -R 755 LCD-show cd LCD-show/ sudo ./LCD5-show <file_sep>/sensors/16种传感器套件/DS1302实时时钟模块/DS1302时钟实验(51单片机)/DS1302时钟芯片实验2.C /*************************************************************************** 实验十九: DS1302时钟芯片实验 CPU型号: AT89S52或兼容型号 系统时钟: 11.0592MHZ 编译环境: keil uVision4 日期: 2009-8-2 联系方法: CJMCU ****************************************************************************/ /*********************************包含头文件********************************/ #include <reg52.h> #include <intrins.h> #define uchar unsigned char /*********************************端口定义**********************************/ sbit DS1302_CLK = P1^0; sbit DS1302_IO = P1^1; sbit DS1302_RST = P1^2; /*******************************共阳LED段码表*******************************/ uchar code LED_TAB[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90}; /******************************定义全局变量*********************************/ uchar second,minute,hour,week,day,month,year; uchar time[]={0x09,0x08,0x15,0x03,0x12,0x12,0x00}; //初始时间数组 /**************************************************************************** 函数功能:数码管扫描延时子程序 入口参数: 出口参数: ****************************************************************************/ void delay1(void) { int k; for(k=0;k<400;k++); } /**************************************************************************** 函数功能:数码管显示子程序 入口参数:k 出口参数: ****************************************************************************/ void display(void) { P2=0x01; P0=LED_TAB[minute/16]; delay1(); P2=0x02; P0=LED_TAB[minute%16] & 0X7F; delay1(); P2=0x04; P0=LED_TAB[second/16]; delay1(); P2=0x08; P0=LED_TAB[second%16]; delay1(); } /***************************************************************************** 函数功能:向DS1302送一字节数据子程序 入口参数: 出口参数: *****************************************************************************/ void InputByte(uchar byte1) { char i; for(i=8;i>0;i--) { DS1302_IO=(bit)(byte1&0x01); DS1302_CLK=1; _nop_(); DS1302_CLK=0; byte1>>=1; } return; } /***************************************************************************** 函数功能:读DS1302一个字节子程序 入口参数: 出口参数: *****************************************************************************/ uchar outputbyte(void) { uchar i; uchar ucdat=0; for(i=8;i>0;i--) { DS1302_IO=1; ucdat>>=1; if(DS1302_IO)ucdat|=0x80; DS1302_CLK=1; _nop_(); DS1302_CLK=0; } return(ucdat); } /***************************************************************************** 函数功能:向DS1302某地址写一字节数据子程序 入口参数:addr,TDat 出口参数: *****************************************************************************/ void write_ds1302(uchar addr,uchar TDat) { DS1302_RST=0; _nop_(); DS1302_CLK=0; _nop_(); DS1302_RST=1; InputByte(addr); _nop_(); InputByte(TDat); DS1302_CLK=1; _nop_(); DS1302_RST=0; } /***************************************************************************** 函数功能:读DS1302地址子程序 入口参数:add 出口参数:timedata *****************************************************************************/ uchar read_ds1302(uchar addr) { uchar timedata; DS1302_RST=0; _nop_(); DS1302_CLK=0; _nop_(); DS1302_RST=1; InputByte(addr); timedata=OutputByte(); DS1302_CLK=1; _nop_(); DS1302_RST=0; return(timedata); } /***************************************************************************** 函数功能:初始化DS1302子程序 入口参数:time[](全局变量) 出口参数: *****************************************************************************/ void initial_ds1302() { write_ds1302(0x8e,0x00); //写保护寄存器,在对时钟或RAM写前WP一定要为0 write_ds1302(0x8c,time[0]); //年 write_ds1302(0x88,time[1]); //月 write_ds1302(0x86,time[2]); //日 write_ds1302(0x8A,time[3]); //星期 write_ds1302(0x84,time[4]); //时 write_ds1302(0x82,time[5]); //分 write_ds1302(0x80,time[6]); //秒 write_ds1302(0x8e,0x80); //写保护寄存器 } /***************************************************************************** 函数功能:读DS1302时间子程序 入口参数: 出口参数:全局变量(second,minute,hour,week,day,month,year) *****************************************************************************/ void read_time() { second=read_ds1302(0x81); //秒寄存器 minute=read_ds1302(0x83); //分 hour=read_ds1302(0x85); //时 week=read_ds1302(0x8B); //星期 day=read_ds1302(0x87); //日 month=read_ds1302(0x89); //月 year=read_ds1302(0x8d); //年 } /***************************************************************************** 函数功能:主程序 入口参数: 出口参数: *****************************************************************************/ void main(void) { initial_ds1302(); //初始化DS1302 while(1) { read_time(); //读取时间 display(); //显示时间 } } <file_sep>/installations/pi-setup-wifi.sh #! /bin/bash sudo apt update sudo apt install -y hostapd dnsmasq sudo bash -c "cat >>/etc/dnsmasq.conf <<EOF #this line existes to make sure below starts in a new line interface=wlan0 dhcp-range=192.168.68.24,192.168.68.200,255.255.255.0,12h EOF" sudo bash -c "cat >/etc/hostapd/hostapd.conf <<EOF interface=wlan0 hw_mode=g channel=10 auth_algs=1 wpa=2 wpa_key_mgmt=WPA-PSK wpa_pairwise=CCMP rsn_pairwise=CCMP wpa_passphrase=<PASSWORD> ssid=SSID EOF" # enable ip_forward sudo sed -i "s/#net.ipv4.ip_forward=[01]/net.ipv4.ip_forward=1/g" /etc/sysctl.conf # open wifi on startup sudo sed -i "s/exit 0//g" /etc/rc.local sudo bash -c "cat >>/etc/rc.local <<EOF ifconfig wlan0 down ifconfig wlan0 192.168.68.1 netmask 255.255.255.0 up iwconfig wlan0 power off service dnsmasq restart hostapd -B /etc/hostapd/hostapd.conf & > /dev/null 2>&1 sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE sudo iptables -A FORWARD -i eth0 -o wlan0 -m state --state RELATED,ESTABLISHED -j ACCEPT sudo iptables -A FORWARD -i wlan0 -o eth0 -j ACCEPT exit 0 EOF" # sudo reboot echo -e "now reboot to take effect" <file_sep>/sensors/1.py #!/usr/bin/python #-*- coding: utf-8 -*- import time import RPi.GPIO as GPIO import os GPIO.setmode(GPIO.BCM) #使用BCM编码方式 #定义引脚 GPIO_1 = 1 GPIO_2 = 2 GPIO_3 = 4 GPIO_4 = 4 GPIO_14 = 14 GPIO_16 = 16 GPIO_21 = 21 GPIO_22 = 22 GPIO_23 = 23 GPIO_24 = 24 led = 21 #设置引脚为输入和输出 GPIO.setwarnings(False) #设置23针脚为输入,接到红外避障传感器模块的out引脚 #GPIO.setup(GPIO_23,GPIO.IN) GPIO.setup(GPIO_14,GPIO.OUT) #GPIO.setup(GPIO_24,GPIO.IN) def warn(): #亮灯来作为有障碍物时发出的警告 # GPIO.output(led,GPIO.HIGH) # time.sleep(0.5) # GPIO.output(led, GPIO.LOW) time.sleep(0.5) print "warn" while True: print "low" GPIO.output(GPIO_14, GPIO.LOW) #当有障碍物时,传感器输出低电平,所以检测低电平 time.sleep(15) print "high" GPIO.output(GPIO_14, GPIO.HIGH) #当有障碍物时,传感器输出低电平,所以检测低电平 time.sleep(15) GPIO.cleanup() <file_sep>/fan.py #!/usr/bin/python #-*- coding: utf-8 -*- import time, os, datetime import RPi.GPIO as GPIO GPIO_OUT = 14 LOG_PATH = '/var/log/fan_control.log' IS_DEBUG=False def read_cpu_temperature(): with open("/sys/class/thermal/thermal_zone0/temp", 'r') as f: temperature = float(f.read()) / 1000 log('DEBUG', 'Current CPU temperature is %s' % temperature) return temperature def start_fan(): log('INFO', 'power on.') GPIO.output(GPIO_OUT, GPIO.HIGH) def stop_fan(): log('INFO', 'power off.') GPIO.output(GPIO_OUT, GPIO.LOW) def setup_GPIO(): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(GPIO_OUT, GPIO.OUT) def control_fan(): is_close = True try: while True: temp = read_cpu_temperature() if is_close: if temp>=50: start_fan() is_close = False else: if temp<=45: stop_fan() is_close = True time.sleep(10) except Exception, e: GPIO.cleanup() log('WARN', e) def log(level, msg): log_msg = '[%s]: %s (%s)' % (level, msg, datetime.datetime.now() ) if IS_DEBUG: print log_msg return if level == 'DEBUG': return try: with open(LOG_PATH, 'a') as f: f.write(log_msg+'\n') except Exception as e: print "Unable to log, %s" % e if __name__ == '__main__': os.environ["TZ"] = 'Asia/Shanghai' time.tzset() log('INFO', 'started.') setup_GPIO() control_fan() log('INFO', 'quit.') <file_sep>/README.md # raspberryPi raspberryPi related works #### Note All of these works are based on pi3 & Raspbian Jessie -> stretch <file_sep>/sensors/README.md ## sensors detect & control scripts ### Pin of sensors ![Pin of sensors](sensors_list.jpg "Pin of sensors")
d0b015070cc65a43c54a0d45c3f273c0cd6024d9
[ "Markdown", "Makefile", "Python", "C", "Shell" ]
22
Shell
Hatsune39/raspberryPi
886a677a0f6501eee8df0e889fd4f11ecfa12220
32931421c9f95e2ad0d084f6a539e7a8b8f106f4
refs/heads/master
<repo_name>zhi-lu/MasterLearning<file_sep>/src/com/luzhi/miniTomcat/watcher/WarFileWatcher.java package com.luzhi.miniTomcat.watcher; import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.watch.WatchMonitor; import cn.hutool.core.io.watch.WatchUtil; import cn.hutool.core.io.watch.Watcher; import com.luzhi.miniTomcat.catalina.Host; import com.luzhi.miniTomcat.util.ConstantTomcat; import java.io.File; import java.nio.file.Path; import java.nio.file.WatchEvent; import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; /** * @author apple * @version jdk1.8 * // TODO : 2021/7/2 * 监控webapps下的文件,如果存在新创建的.war文件.则由{@link com.luzhi.miniTomcat.catalina.Host#loadWar(File)}方法进行处理. */ @SuppressWarnings("unused") public class WarFileWatcher { /** * 创建监听器 * * @see #watchMonitor */ private final WatchMonitor watchMonitor; /** * war文件的扩展名: * * @see #WAR_EXTENSION */ private static final String WAR_EXTENSION = ".war"; public WarFileWatcher(Host host) { this.watchMonitor = WatchUtil.createAll(ConstantTomcat.WEBAPPS_FOLDER, 1, new Watcher() { private void dealWith(WatchEvent<?> event, Path currentPath) { synchronized (WarFileWatcher.class) { String fileName = event.context().toString(); if (fileName.toLowerCase().endsWith(WAR_EXTENSION) && ENTRY_CREATE.equals(event.kind())) { File warFile = FileUtil.file(ConstantTomcat.WEBAPPS_FOLDER, fileName); host.loadWar(warFile); } } } @Override public void onCreate(WatchEvent<?> event, Path currentPath) { dealWith(event, currentPath); } @Override public void onModify(WatchEvent<?> event, Path currentPath) { dealWith(event, currentPath); } @Override public void onDelete(WatchEvent<?> event, Path currentPath) { dealWith(event, currentPath); } @Override public void onOverflow(WatchEvent<?> event, Path currentPath) { dealWith(event, currentPath); } }); } public void start() { watchMonitor.start(); } public void stop() { watchMonitor.interrupt(); } } <file_sep>/startup.sh #!/usr/bin/env zsh # shellcheck disable=SC2164 # shellcheck disable=SC2035 # shellcheck disable=SC2103 # 详细参数解释请看站长. hello="你好吖,[]~( ̄▽ ̄)~*.正在开启tomcat,<( ̄︶ ̄)>." echo "${hello}" rm -rf bootstrap.jar jar cvf0 bootstrap.jar -C out/production/MasterLearning com/luzhi/miniTomcat/Bootstrap.class -C out/production/MasterLearning com/luzhi/miniTomcat/classloader/CommonClassLoader.class # 删除 lib 目录下的miniTomcat.jar rm -rf lib/miniTomcat.jar cd out cd production cd MasterLearning jar cvf0 ../../../lib/miniTomcat.jar * cd .. cd .. cd .. java -cp bootstrap.jar com/luzhi/miniTomcat/Bootstrap<file_sep>/src/com/luzhi/miniTomcat/pratice/DemoThread.java package com.luzhi.miniTomcat.pratice; import java.util.concurrent.atomic.AtomicInteger; /** * @author apple * @version jdk1.8 * // TODO : 2021/5/21 * 对多线程的探索,关于synchronized的四种修饰方式 * 在Java中 synchronized: * 对于接口方法不能使用synchronized进行修饰,构造方法不可以使用synchronized进行修饰,但它的synchronized代码块可以进行同步. * 《1》对于synchronized(this) 一个线程访问一个对象的同步代码块时,会使其他访问该对象的代码块线程出现阻塞状态。 * 《2》对方法进行修饰,一个线程访问一个对象被synchronized修饰的方法时,会使其他访问该对象synchronized的方法线程进行堵塞. */ @SuppressWarnings("AlibabaAvoidManuallyCreateThread") public class DemoThread { public static void main(String[] args) throws InterruptedException { runSyncThread(); // 睡上2秒.便于查看. Thread.sleep(2000); runSynThread(); Thread.sleep(2000); Child child = new Child(); child.methods(); Thread.sleep(2000); runSynchroThread(); Thread.sleep(2000); runSynchronizedThread(); } private static void runSyncThread() { SyncThread syncThread = new SyncThread(); // 创建 A 线程. Thread thread = new Thread(syncThread, "SynchronizeOne"); // 创建 B 线程. Thread thread1 = new Thread(syncThread, "SynchronizedTwo"); thread.start(); thread1.start(); } private static void runSynThread() { SynThread synThread = new SynThread(); // 创建 A 线程. Thread thread = new Thread(synThread, "SynThread-One"); // 创建 B 线程. Thread thread1 = new Thread(synThread, "SynThread-Two"); thread.start(); thread1.start(); } private static void runSynchroThread() { SynchroThread synchroThread = new SynchroThread(); // 创建 A 线程. Thread thread = new Thread(synchroThread, "SynchroThread-One"); // 创建 B 线程. Thread thread1 = new Thread(synchroThread, "SynchroThread-Two"); thread.start(); thread1.start(); } private static void runSynchronizedThread() { SynchronizedThread synchronizedThread = new SynchronizedThread(); // 创建 A 线程. Thread thread = new Thread(synchronizedThread, "synchronizedThread-One"); // 创建 B 线程. Thread thread1 = new Thread(synchronizedThread, "synchronizedThread-Two"); thread.start(); thread1.start(); } } @SuppressWarnings("unused") class SyncThread implements Runnable { private static volatile int count; private static final int NUMBER = 5; public SyncThread() { count = 0; } /** * @see #run() * 对run进行重新.使用synchronized(this) */ @Override public void run() { synchronized (this) { for (int i = 0; i < NUMBER; i++) { try { System.out.println("打印当前线程名:" + Thread.currentThread().getName() + ":" + (count++)); Thread.sleep(100); } catch (InterruptedException exception) { exception.printStackTrace(); } } } } public static int getCount() { return count; } } @SuppressWarnings("unused") class SynThread implements Runnable { private static volatile int count; private static final int NUMBER = 5; public SynThread() { count = 0; } @Override public synchronized void run() { for (int i = 0; i < NUMBER; i++) { // 不使用 synchronized(this) try { System.out.println("打印线程名:" + Thread.currentThread().getName() + ":" + (count++)); Thread.sleep(100); } catch (InterruptedException exception) { exception.printStackTrace(); } } } public static int getCount() { return count; } } /** * {@link Parent} 对synchronized方法进行修饰和继承. */ class Parent { public synchronized void methods() { System.out.println("Hello,World,类对象为:" + this.getClass().getName()); } } class Child extends Parent { /** * @see #methods() * 第一种重新方式. */ @Override public synchronized void methods() { // 打印的是子类的对象名 super.methods(); } } /** * {@link SynchroThread} 修饰静态方法 */ class SynchroThread implements Runnable { private static final int NUMBER = 6; private static AtomicInteger atomicInteger; public SynchroThread() { atomicInteger = new AtomicInteger(-1); } public static synchronized void methods() { for (int i = 0; i < NUMBER; i++) { try { System.out.println("打印线程名(原子性操作):" + Thread.currentThread().getName() + ":" + (atomicInteger.incrementAndGet())); Thread.sleep(100); } catch (InterruptedException exception) { exception.printStackTrace(); } } } @Override public synchronized void run() { methods(); } } /** * {@link SynchronizedThread} 修饰类 */ class SynchronizedThread implements Runnable { private static int count; private static final int NUMBER = 6; public SynchronizedThread() { count = 0; } @Override public void run() { synchronized (SynchronizedThread.class) { for (int i = 0; i < NUMBER; i++) { try { System.out.println("打印线程名:" + Thread.currentThread().getName() + ":" + (count++)); Thread.sleep(100); } catch (InterruptedException exception) { exception.printStackTrace(); } } } } }<file_sep>/src/com/luzhi/miniTomcat/test/TomcatTest.java package com.luzhi.miniTomcat.test; import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.TimeInterval; import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.NetUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.ZipUtil; import com.luzhi.miniTomcat.util.MiniBrowser; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CountDownLatch; /** * @author apple * @version jdk1.8 * // TODO : 2021/5/11 * 为自动测试类 */ public class TomcatTest { /** * @see #PORT * <p> * 测试端口 */ private static final int PORT = 9091; /** * @see #HOST * <p> * 本地主机地址 */ private static final String HOST = "127.0.0.1"; /** * @see #POOL_SIZE * <p> * 测试的线程数为3 */ private static final int POOL_SIZE = 3; /** * @see #beforeClass() * 该类为测试类,所有的测试之前Jvm执行该方法一次并使用{@link BeforeClass}注解,注解的方法必须为 public static void 所修饰 * 它和{@link org.junit.Before} 的区别是每个测试都执行一遍. 注解的方法必须为 public static void 所修饰 */ @BeforeClass public static void beforeClass() { if (NetUtil.isUsableLocalPort(PORT)) { System.err.println("miniTomcat服务还没有启动,请检查端口是否启动该服务.谢谢"); // 终止当前的Java虚拟机,非零表示为异常终止. System.exit(1); } else { System.out.println("miniTomcat服务已经启动啦, 下面进行单元测试哦!"); } } /** * @see #testTomcat() * 对字符文本进行操作 */ @Test public void testTomcat() { String content = getContentString("/"); Assert.assertEquals(content, "<h1 align='center' style='color:pink;'> Hello, I't is new simplify tomcat</h1>"); } /** * @see #testHtml() * 对h5进行文本进行操作 */ @Test public void testHtml() { String content = getContentString("/login.html"); Assert.assertEquals(content, "<h1 align='center' style='color:pink;'> Hello, I't is new simplify tomcat</h1>"); } /** * @see #textHtmlCrossXml() * 对多应用配置(使用xml)进行配置进行测试 */ @Test public void textHtmlCrossXml() { String content = getContentString("/resource/manyConf.html"); Assert.assertEquals(content, "<h1 style='color:pink; align-content: center'> Hello, I't is new simplify tomcat</h1>"); } @Test public void testServletText() { String content = getContentString("/hello"); Assert.assertEquals(content, "<h1 align=center style='color:pink'>Hello, It's really easy servlet</h1>"); } /** * @see #testOtherHtml() * 对webapps的多应用文件进行测试 */ @Test public void testOtherHtml() { String content = getContentString("/a/start.html"); Assert.assertEquals(content, "<h1 style='color:pink; align-content: center'> Hello, I't is new simplify tomcat</h1>"); } /** * @see #testPage404() * 对"404"页面进行测试 */ @Test public void testPage404() { String response = getHttpString("/not_exist.html"); containAssert(response, "HTTP/1.1 404 NOT FOUND"); } /** * @see #testPage500() * 对"500"页面进行测试. */ @Test public void testPage500() { String response = getHttpString("/500.html"); containAssert(response, "HTTP/1.1 500 Internal Server Error"); } @Test public void testJ2eeHello() { String content = getContentString("/j2ee/hello"); Assert.assertEquals(content, "<h1 align=center style='color:pink'>Hello, It's really easy servlet</h1>"); } @Test public void testJavaWebHello() { String content = getContentString("/javaweb/hello"); String contentTest = getContentString("/javaweb/hello"); Assert.assertEquals(content, contentTest); } /** * @see #testLoginHtml() * 创建3个线程对页面login.html进行访问.由于BootStrap现在是多线程处理. */ @Test public void testLoginHtml() throws InterruptedException { // 创建倒数锁存器并初始化为3 CountDownLatch countDownLatch = new CountDownLatch(3); // 使用计数器.统计下面线程运行的时间。默认初始 (isNano 为 false). TimeInterval timeInterval = DateUtil.timer(); for (int i = 0; i < POOL_SIZE; i++) { //noinspection AlibabaAvoidManuallyCreateThread new Thread(() -> { getContentString("/login.html"); // 将倒数锁存器初始化倒数逐级递减. countDownLatch.countDown(); }, "Thread" + i).start(); } // 将当前线程进行挂起.直到倒数锁存器的倒数递减为零.释放当前挂起的线程. countDownLatch.await(); // 统计时间,从开始到当前所用的时间.默认为毫秒. long duration = timeInterval.intervalMs(); // 因为是线程池进行处理.自然 duration 小于3000毫秒. Assert.assertTrue(duration < 3000); } /** * @see #testJpgFile() 对图片文件读取进行测试 * 测试手段,比较文件长度大小. */ @Test public void testJpgFile() { byte[] bytes = getContentBytes("/lastPic.jpg"); final int fileLength = 505797; Assert.assertEquals(fileLength, bytes.length); } /** * @see #testPdfFile() 对pdf文件进行读取测试 * 测试手段,上同. */ @Test public void testPdfFile() { byte[] bytes = getContentBytes("/healthBook.pdf"); final int pdfFileLength = 262524; Assert.assertEquals(pdfFileLength, bytes.length); } @Test public void testGetParam() { String uri = "/javaweb/param"; //noinspection HttpUrlsUsage String url = StrUtil.format("http://{}:{}{}", HOST, PORT, uri); //noinspection MismatchedQueryAndUpdateOfCollection Map<String, Object> params = new HashMap<>(64); params.put("name", "鲁滍"); // 测试GET方法 String result = MiniBrowser.getContentString(url, params, true); Assert.assertEquals(result, "get的name属性为:鲁滍"); } @Test public void testPostParam() { String uri = "/javaweb/param"; //noinspection HttpUrlsUsage String url = StrUtil.format("http://{}:{}{}", HOST, PORT, uri); //noinspection MismatchedQueryAndUpdateOfCollection Map<String, Object> params = new HashMap<>(64); params.put("name", "白上吹雪"); // 对POST请求体处理 String result = MiniBrowser.getContentString(url, params, false); Assert.assertEquals(result, "post的name属性为:白上吹雪"); } @Test public void testHeader() { String result = getContentString("/javaweb/header"); Assert.assertEquals(result, "mini browser / java1.8"); } @Test public void testCookie() { String html = getHttpString("/javaweb/setCookie"); containAssert(html, "Set-Cookie:name=luzhi;Expires="); } @Test public void testGetCookie() throws IOException { @SuppressWarnings("HttpUrlsUsage") String url = StrUtil.format("http://{}:{}{}", HOST, PORT, "/javaweb/getCookie"); URL u = new URL(url); HttpURLConnection httpUrlConnection = (HttpURLConnection) u.openConnection(); httpUrlConnection.setRequestProperty("Cookie", "name=luzhi"); httpUrlConnection.connect(); InputStream inputStream = httpUrlConnection.getInputStream(); String html = IoUtil.read(inputStream, StandardCharsets.UTF_8); containAssert(html, "name:luzhi"); } @Test public void testSession() throws IOException { String jSessionId = getContentString("/javaweb/setSession"); if (null != jSessionId) { jSessionId = jSessionId.trim(); } //noinspection HttpUrlsUsage String url = StrUtil.format("http://{}:{}{}", HOST, PORT, "/javaweb/getSession"); URL u = new URL(url); HttpURLConnection httpUrlConnection = (HttpURLConnection) u.openConnection(); httpUrlConnection.setRequestProperty("Cookie", "JSESSIONID=" + jSessionId); httpUrlConnection.connect(); InputStream inputStream = httpUrlConnection.getInputStream(); String html = IoUtil.read(inputStream, StandardCharsets.UTF_8); containAssert(html, "luzhi"); } @Test public void testGzip() { byte[] gzipContent = getContentBytes("/", true); byte[] unGzipContent = ZipUtil.unGzip(gzipContent); String content = new String(unGzipContent); containAssert(content, "<h1 align=\"center\" style=\"color: pink; align-content: center\">Welcome miniTomcat! miniTomcat already start.</h1>"); } @Test public void testJavaWeb0Hello() { String html = getContentString("/javaweb0/hello.jsp"); System.out.println(html); containAssert(html,"Hello"); } @Test public void testJsp() { String html = getContentString("/javaweb/"); Assert.assertEquals(html, "hello jsp@This is javaweb"); } /** * @see #getContentString(String) * 该私有静态方法获取浏览器的内容,通过{@link MiniBrowser#getContentString(String)}方法进行获取. */ private static String getContentString(String uri) { //noinspection HttpUrlsUsage String url = StrUtil.format("http://{}:{}{}", HOST, PORT, uri); return MiniBrowser.getContentString(url); } /** * @see #getHttpString(String) * 模拟资源不存在 */ private String getHttpString(String uri) { //noinspection HttpUrlsUsage String url = StrUtil.format("http://{}:{}{}", HOST, PORT, uri); return MiniBrowser.getHttpString(url); } /** * @see #containAssert(String, String) * 当资源不存在则设置断言. */ private void containAssert(String html, String string) { boolean match = StrUtil.containsAny(html, string); Assert.assertTrue(match); } /** * @see #getContentString(String) 将路径资源文件读取为字节流. * 详情请看{@link #getContentBytes(String, boolean)} */ private byte[] getContentBytes(@SuppressWarnings("SameParameterValue") String uri) { return getContentBytes(uri, false); } /** * @see #getContentBytes(String, boolean) 默认无压缩模式 * 详细操作请看 {@link MiniBrowser#getContentString(String, boolean)}; */ private byte[] getContentBytes(String uri, @SuppressWarnings("SameParameterValue") boolean gzip) { //noinspection HttpUrlsUsage String url = StrUtil.format("http://{}:{}{}", HOST, PORT, uri); return MiniBrowser.getContentBytes(url, gzip); } } <file_sep>/src/com/luzhi/miniTomcat/catalina/Context.java package com.luzhi.miniTomcat.catalina; import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.TimeInterval; import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.IORuntimeException; import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.log.LogFactory; import com.luzhi.miniTomcat.classloader.WebAppClassLoader; import com.luzhi.miniTomcat.exception.WebConfigDuplicatedException; import com.luzhi.miniTomcat.http.ApplicationServlet; import com.luzhi.miniTomcat.http.StandardServletConfig; import com.luzhi.miniTomcat.util.ContextXmlUtil; import com.luzhi.miniTomcat.watcher.ContextFileChangeWatcher; import org.apache.jasper.JspC; import org.apache.jasper.compiler.JspRuntimeContext; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import javax.servlet.*; import javax.servlet.http.HttpServlet; import java.io.File; import java.util.*; /** * @author apple * @version jdk1.8 * // TODO : 2021/5/21 * 创建方法文件的地址和在系统文件的位置. */ @SuppressWarnings({"unused", "MismatchedQueryAndUpdateOfCollection"}) public class Context { /** * 匹配"/* * * @see #START_STAR */ private static final String START_STAR = "/*"; /** * 匹配"/*.jsp"文件 * * @see #START_STAR_DOT */ private static final String START_STAR_DOT = "/*."; /** * servletEvent初始化方法,对应的比较值 * * @see #INIT_VALUE */ private static final String INIT_VALUE = "init"; /** * servletEvent销毁方法,对应的比较值. */ private static final String DESTROYED_VALUE = "destroyed"; /** * 获取映射的资源文件夹地址 * * @see #path */ private String path; /** * 获取资源地址的在系统的绝对路径. * * @see #docBase */ private String docBase; /** * 创建host对象 * * @see Host */ private final Host host; /** * 是否进行重载 * * @see #reloadable */ private boolean reloadable; /** * 获取'*'/WEB-INF/xml文件 * * @see #contextWebXmlFile */ private final File contextWebXmlFile; /** * 设置自定义的ContextFile的监听器 * * @see #contextFileChangeWatcher */ private ContextFileChangeWatcher contextFileChangeWatcher; /** * 地址映射servlet类名 * * @see #urlToServletClassName */ private final Map<String, String> urlToServletClassName; /** * 地址映射servlet名 * * @see #urlToServletName */ private final Map<String, String> urlToServletName; /** * servlet类名映射servlet名. * * @see #servletClassNameToServletName */ private final Map<String, String> servletClassNameToServletName; /** * servlet名映射servlet类名. * * @see #servletNameToServletClassName */ private final Map<String, String> servletNameToServletClassName; /** * 存放初始化信息 * * @see #servlet_className_init_params */ private final Map<String, Map<String, String>> servlet_className_init_params; /** * 创建一个存放servlet对象池. * * @see #servletPool */ private final Map<Class<?>, HttpServlet> servletPool; /** * 设置类的加载器为自定义的{@link WebAppClassLoader}加载器 * * @see #webAppClassLoader */ private final WebAppClassLoader webAppClassLoader; /** * 处理定义的Servlet的上下文. * * @see #servletContext */ private final ServletContext servletContext; /** * 定义那些是需要自定义初始化的Servlet在Context启动之后. * * @see #loadOnStartupServletClassNames */ private final List<String> loadOnStartupServletClassNames; /** * 创建webContext监听器列表. */ private final List<ServletContextListener> servletContextListenerList; /** * url对应着筛选器的相应的类名 * * @see #urlToFilterClassName */ private final Map<String, List<String>> urlToFilterClassName; /** * url对应着筛选器 * * @see #urlToFilterNames */ private final Map<String, List<String>> urlToFilterNames; /** * 筛选器类对应的筛选器名 * * @see #filterClassNameToFilterName */ private final Map<String, String> filterClassNameToFilterName; /** * 筛选器名对应的筛选器 * * @see #filterNameToFilterClassName */ private final Map<String, String> filterNameToFilterClassName; /** * 创建筛选器池. * * @see #filterPool */ private final Map<String, Filter> filterPool; /** * 筛选器类对应的相关的初始化的参数. * * @see #filterClassNameToInitParameters */ private final Map<String, Map<String, String>> filterClassNameToInitParameters; /** * 详细解释通过{@code Thread.currentThread().getContextClassLoader()}获取{@link com.luzhi.miniTomcat.Bootstrap} * 中的{@link com.luzhi.miniTomcat.classloader.CommonClassLoader}公共类加载器.根据tomcat将此公共加载器设置为{@link WebAppClassLoader} * 的父类加载器。由它获取类和资源. * * @see #Context(String, String, Host, boolean) */ public Context(String path, String docBase, Host host, boolean reloadable) { this.path = path; this.docBase = docBase; this.host = host; this.reloadable = reloadable; this.contextWebXmlFile = new File(docBase, ContextXmlUtil.getWatchedResource()); this.loadOnStartupServletClassNames = new ArrayList<>(); this.servletContextListenerList = new ArrayList<>(); this.urlToServletClassName = new HashMap<>(512); this.urlToServletName = new HashMap<>(512); this.urlToFilterClassName = new HashMap<>(512); this.urlToFilterNames = new HashMap<>(512); this.filterPool = new HashMap<>(512); this.filterNameToFilterClassName = new HashMap<>(512); this.filterClassNameToInitParameters = new HashMap<>(512); this.filterClassNameToFilterName = new HashMap<>(512); this.servletClassNameToServletName = new HashMap<>(512); this.servletNameToServletClassName = new HashMap<>(512); this.servletPool = new HashMap<>(512); this.servlet_className_init_params = new HashMap<>(512); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); this.webAppClassLoader = new WebAppClassLoader(this.docBase, classLoader); this.servletContext = new ApplicationServlet(this); deploy(); } private void deploy() { TimeInterval timeInterval = DateUtil.timer(); LogFactory.get().info("Deploying web application directory {}", this.getPath()); parseLoadListeners(); init(); if (this.reloadable) { this.contextFileChangeWatcher = new ContextFileChangeWatcher(this); this.contextFileChangeWatcher.start(); } JspC jspC = new JspC(); // 进行JspRuntimeContext初始化。 new JspRuntimeContext(servletContext, jspC); LogFactory.get().info("Deploying of application directory {} has finished in {}", this.getDocBase(), timeInterval.intervalMs()); } private void init() { if (!contextWebXmlFile.exists()) { return; } try { checkDuplicated(); } catch (WebConfigDuplicatedException exception) { System.out.println("打印异常原因:" + exception.getMessage()); exception.printStackTrace(); return; } String xml = FileUtil.readUtf8String(this.contextWebXmlFile); Document document = Jsoup.parse(xml); parseServletMapping(document); parseFilterMapping(document); parseServletInitName(document); parseFilterInitParameters(document); initFilter(); parseLoadOnStartup(document); handleLoadOnStartup(); fireEvent("init"); } private void initFilter() { Set<String> filterClassNames = filterClassNameToFilterName.keySet(); for (String filterClassName : filterClassNames) { try { Class<?> clazz = this.getWebAppClassLoader().loadClass(filterClassName); Map<String, String> initParameters = filterClassNameToInitParameters.get(filterClassName); String filterName = filterClassNameToFilterName.get(filterClassName); FilterConfig filterConfig = new StandardFilterConfig(servletContext, initParameters, filterName); @SuppressWarnings("SuspiciousMethodCalls") Filter filter = filterPool.get(clazz); if (null == filter) { filter = (Filter) ReflectUtil.newInstance(clazz); filter.init(filterConfig); filterPool.put(filterClassName, filter); } } catch (Exception exception) { throw new RuntimeException("异常原因:" + exception); } } } /** * 具体的映射解析. * * @param document 需要解析web.xml */ private void parseServletMapping(Document document) { // 地址对servletName的映射 Elements elementsUrlToServletName = document.select("servlet-mapping url-pattern"); for (Element elementOne : elementsUrlToServletName) { String urlPattern = elementOne.text(); String servletName = elementOne.parent().select("servlet-name").first().text(); urlToServletName.put(urlPattern, servletName); } // servlet-name 和 servlet-className 之间的相互映射 Elements elementServletClassNameToServletName = document.select("servlet servlet-name"); for (Element elementTwo : elementServletClassNameToServletName) { String servletName = elementTwo.text(); String servletClassName = elementTwo.parent().select("servlet-class").first().text(); servletNameToServletClassName.put(servletName, servletClassName); servletClassNameToServletName.put(servletClassName, servletName); } // url地址对servlet-className的映射. Set<String> urls = urlToServletName.keySet(); for (String url : urls) { String servletName = urlToServletName.get(url); String servletClass = servletNameToServletClassName.get(servletName); urlToServletClassName.put(url, servletClass); } } @SuppressWarnings("DuplicatedCode") private void parseFilterInitParameters(Document document) { Elements elements = document.select("filter-class"); for (Element element : elements) { String filterClassName = element.text(); Elements elementsInitParam = elements.parents().select("init-param"); if (elementsInitParam.isEmpty()) { continue; } Map<String, String> initParam = new HashMap<>(512); for (Element elementInitParam : elementsInitParam) { String name = elementInitParam.select("init-name").get(0).text(); String value = elementInitParam.select("init-value").get(0).text(); initParam.put(name, value); } filterClassNameToInitParameters.put(filterClassName, initParam); } } /** * 解析配置的筛选器相关的表 * * @param document 获取需要解析的web.xml文件 * @see #parseFilterMapping(Document) */ public void parseFilterMapping(Document document) { // url对应相关定义的筛选器的名称。 Elements elements = document.select("filter-mapping url-pattern"); for (Element element : elements) { String urlName = element.text(); String filterName = element.parent().select("filter-name").first().text(); List<String> filterNames = urlToFilterNames.computeIfAbsent(urlName, k -> new ArrayList<>()); filterNames.add(filterName); } // filterName 和 filterClassName 表的解析 Elements elementsTwo = document.select("filter filter-name"); for (Element element : elementsTwo) { String filterName = element.text(); String filterClassName = element.parent().select("filter-class").first().text(); filterNameToFilterClassName.put(filterName, filterClassName); filterClassNameToFilterName.put(filterClassName, filterName); } // url对应的筛选器类. Set<String> urls = urlToFilterNames.keySet(); for (String url : urls) { List<String> filterNames = urlToFilterNames.computeIfAbsent(url, k -> new ArrayList<>()); for (String filterName : filterNames) { String filterClassName = filterNameToFilterClassName.get(filterName); List<String> filterClassNames = urlToFilterClassName.computeIfAbsent(url, k -> new ArrayList<>()); filterClassNames.add(filterClassName); } } } /** * 使用{@link #checkDuplicated(Document, String, String)} 具体检查和配置相关的参数. * * @see #checkDuplicated() */ private void checkDuplicated() throws WebConfigDuplicatedException { String xml = FileUtil.readUtf8String(this.contextWebXmlFile); Document document = Jsoup.parse(xml); checkDuplicated(document, "servlet servlet-name", "在servlet中出现相同的servlet-name:{},请检查WEB-INF/web.xml."); checkDuplicated(document, "servlet servlet-class", "在servlet中出现相同的servlet-class:{},请检查WEB-INF/web.xml"); checkDuplicated(document, "servlet-mapping url-pattern", "在servlet-mapping中出现相同的url-pattern:{},请检查WEB-INF/web.xml"); } /** * 检查xml中是否出现出现同样的配置出现的异常为{@link WebConfigDuplicatedException} * * @param document 获取{@link Document} 将xml转化的对象。 * @param mapping 在xml中的结点对象. * @param desc 对异常处理的描述. * @see #checkDuplicated(Document, String, String) */ private void checkDuplicated(Document document, String mapping, String desc) throws WebConfigDuplicatedException { Elements elements = document.select(mapping); List<String> contentList = new ArrayList<>(); for (Element element : elements) { contentList.add(element.text()); } // 进行排序,查看是否出现相同的配置 Collections.sort(contentList); for (int i = 0; i < contentList.size() - 1; i++) { String preContent = contentList.get(i); String lastContent = contentList.get(i + 1); if (preContent.equals(lastContent)) { throw new WebConfigDuplicatedException(StrUtil.format(desc, preContent)); } } } public String getPath() { return path; } public String getDocBase() { return docBase; } public void setDocBase(String docBase) { this.docBase = docBase; } public void setPath(String path) { this.path = path; } public WebAppClassLoader getWebAppClassLoader() { return webAppClassLoader; } public String getServletClassName(String uri) { return urlToServletClassName.get(uri); } public boolean isReloadable() { return reloadable; } public void setReloadable(boolean reloadable) { this.reloadable = reloadable; } /** * 添加监听器 * * @param listener 监听器 * @see #addListener(ServletContextListener) */ public void addListener(ServletContextListener listener) { this.servletContextListenerList.add(listener); } /** * 停止并销毁 * * @see #stop() */ public void stop() { webAppClassLoader.stop(); contextFileChangeWatcher.stop(); destroyServlets(); fireEvent("destroyed"); } /** * 加载父类对象{@link Host}去重载{@code Context.this}。 * * @see #reload() */ public void reload() { host.reload(this); } /** * 获取servlet类名 * * @param uri 通过uri进行获取。 * @see #useUrlToServletClassName(String) */ public String useUrlToServletClassName(String uri) { return urlToServletClassName.get(uri); } /** * 通过{@link #servletPool} 获取servlet对象,如果在哈希表中不存在,则利用{@link Class#newInstance()}构造一个servlet对象。 * * @param clazz 获取类{@code Class<?> clazz} servlet对象. * @see #getServlet(Class) */ public synchronized HttpServlet getServlet(Class<?> clazz) throws InstantiationException, IllegalAccessException, ServletException { HttpServlet servlet = servletPool.get(clazz); if (servlet == null) { servlet = (HttpServlet) clazz.newInstance(); ServletContext servletContextOne = this.getServletContext(); String clazzName = clazz.getName(); String servletName = servletClassNameToServletName.get(clazzName); Map<String, String> initParameters = servlet_className_init_params.get(clazzName); StandardServletConfig standardServletConfig = new StandardServletConfig(servletContext, initParameters, servletName); servlet.init(standardServletConfig); servletPool.put(clazz, servlet); } return servlet; } /** * 将web.xml进行解析,获取servletClassName属性,初始化名和初始化值的属性。存储到{@link #servlet_className_init_params}中. * * @param document 获取{@link Document}对象 * @see #parseServletInitName(Document) */ @SuppressWarnings("DuplicatedCode") private void parseServletInitName(Document document) { Elements servletClassNameElements = document.select("servlet-class"); for (Element servletClassNameElement : servletClassNameElements) { String servletClassName = servletClassNameElement.text(); Elements initElements = servletClassNameElement.parent().select("init-param"); if (initElements.isEmpty()) { continue; } Map<String, String> initParams = new HashMap<>(512); for (Element element : initElements) { String name = element.select("init-name").get(0).text(); String value = element.select("init-value").get(0).text(); initParams.put(name, value); } servlet_className_init_params.put(servletClassName, initParams); } } /** * 解析相关到web.xml文件.获取web中定义到监听器。 * * @see #parseLoadListeners() */ private void parseLoadListeners() { try { if (!contextWebXmlFile.exists()) { return; } String xml = FileUtil.readUtf8String(contextWebXmlFile); Document document = Jsoup.parse(xml); Elements elements = document.select("listener listener-class"); for (Element element : elements) { String listenerClassName = element.text(); Class<?> clazz = this.getWebAppClassLoader().loadClass(listenerClassName); ServletContextListener listener = (ServletContextListener) clazz.newInstance(); addListener(listener); } } catch (ClassNotFoundException | IORuntimeException | InstantiationException | IllegalAccessException exception) { throw new RuntimeException("异常原因:"); } } private void fireEvent(String type) { ServletContextEvent event = new ServletContextEvent(servletContext); for (ServletContextListener servletContextListener : servletContextListenerList) { if (INIT_VALUE.equals(type)) { servletContextListener.contextInitialized(event); } else if (DESTROYED_VALUE.equals(type)) { servletContextListener.contextDestroyed(event); } else { System.out.println("请输入正确的type值."); } } } /** * 此方法获取那些Servlet对象是需要进行"自启动"操作的. * * @param document 获取xml文件转化为{@link Document}的对象 * @see #parseLoadOnStartup(Document) */ private void parseLoadOnStartup(Document document) { Elements loadOnStartupElements = document.select("load-on-startup"); for (Element loadOnStartupElement : loadOnStartupElements) { String loadOnStartupServletClassName = loadOnStartupElement.parent().select("servlet-class").text(); loadOnStartupServletClassNames.add(loadOnStartupServletClassName); } } /** * 设置getter方法. * * @see #getServletContext() */ public ServletContext getServletContext() { return servletContext; } /** * 准备这个方法删除所有的Servlet对象. * * @see #destroyServlets() */ private void destroyServlets() { Collection<HttpServlet> servlets = servletPool.values(); for (HttpServlet servlet : servlets) { servlet.destroy(); } } /** * 对这些类进行自启动. * * @see #handleLoadOnStartup() */ public void handleLoadOnStartup() { for (String loadOnStartupServletClassName : loadOnStartupServletClassNames) { try { Class<?> clazz = webAppClassLoader.loadClass(loadOnStartupServletClassName); getServlet(clazz); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | ServletException e) { LogFactory.get().info("异常原因:" + e.getMessage()); e.printStackTrace(); } } } /** * 三种匹配模式 * * @param uri 需要匹配的资源路径 * @see #getMatchedFilters(String) */ public List<Filter> getMatchedFilters(String uri) { List<Filter> filters = new ArrayList<>(); Set<String> patterns = urlToFilterClassName.keySet(); Set<String> matchedPatterns = new HashSet<>(); Set<String> matchedFilterClassNames = new HashSet<>(); for (String pattern : patterns) { if (match(pattern, uri)) { matchedPatterns.add(pattern); } List<String> filterClassName = urlToFilterClassName.get(pattern); matchedFilterClassNames.addAll(filterClassName); } for (String filterClassName : matchedFilterClassNames) { Filter filter = filterPool.get(filterClassName); filters.add(filter); } return filters; } /** * 匹配方式 * * @param pattern 匹配的模式 * @param uri 需要匹配的资源字段 * @see #match(String, String) */ private boolean match(String pattern, String uri) { // 完全匹配; if (StrUtil.equals(pattern, uri)) { return true; } if (StrUtil.equals(pattern, START_STAR)) { return true; } if (StrUtil.startWith(pattern, START_STAR_DOT)) { String patternExtension = StrUtil.subAfter(pattern, ".", false); String uriExtension = StrUtil.subAfter(pattern, ".", false); return patternExtension.equals(uriExtension); } return false; } } <file_sep>/src/com/luzhi/miniTomcat/util/WebXmlUtil.java package com.luzhi.miniTomcat.util; import cn.hutool.core.io.FileUtil; import com.luzhi.miniTomcat.catalina.Context; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.util.HashMap; import java.util.Map; import java.io.File; /** * @author apple * @version jdk1.8 * // TODO : 2021/5/21 * 生成对conf下的web.xml进行解析. */ public abstract class WebXmlUtil { /** * @see #MIME_MAPPING_TYPE * 此Map对象存放Extension(文件扩展名)和Mime-Type(浏览器所识别对类型)。 */ private static final Map<String, String> MIME_MAPPING_TYPE = new HashMap<>(1024); /** * @see #isInitMime * 是否进行初始化对于hashMap表来说。 */ private static volatile boolean isInitMime = false; /** * @see #getMimeName(String) * 使用 valotile 避免出现两次出现化哈希表{@link #MIME_MAPPING_TYPE}; * 双重锁机制,保证线程中的数据的可见性和互斥性. */ public static String getMimeName(String extensionName) { if (!isInitMime) { // 不允许其他线程对该类进行访问.直到在local memory执行完毕,把操作好的数据数据刷入main memory为止. synchronized (WebXmlUtil.class) { if (!isInitMime) { initMimeMapping(); isInitMime = true; } } } String mineName = MIME_MAPPING_TYPE.get(extensionName); if (null == mineName) { return "text/html"; } return mineName; } /** * @see #initMimeMapping() * 对{@link #MIME_MAPPING_TYPE} HashMap进行初始化. * 填充文件扩展名,和文件mime-type(被浏览器所识别.) */ private static void initMimeMapping() { String xml = FileUtil.readUtf8String(ConstantTomcat.SERVER_WEB_XML); // 进行解析 Document document = Jsoup.parse(xml); Elements elements = document.select("mime-mapping"); for (Element element : elements) { String extensionName = element.select("extension").text(); String mimeType = element.select("mime-type").text(); MIME_MAPPING_TYPE.put(extensionName, mimeType); } } /** * @param context 获取一个{@link Context} 对象获取"欢迎文件"的地址 * 对web.xml进行解析.获取欢迎文件。 * @see #getWelcomeFile(Context) */ public static String getWelcomeFile(Context context) { String webXml = FileUtil.readUtf8String(ConstantTomcat.SERVER_WEB_XML); // 进行解析 Document document = Jsoup.parse(webXml); // 获取元素标签 Elements elements = document.select("welcome-file"); for (Element element : elements) { // 对解析的标签获取其中的文本. String welcomeFileName = element.text(); // 根据地址和文件名,获取文件对象. File file = new File(context.getDocBase(), welcomeFileName); // 是否存在该文件. if (file.exists()) { return file.getName(); } } return "index.html"; } } <file_sep>/src/com/luzhi/miniTomcat/catalina/Connector.java package com.luzhi.miniTomcat.catalina; import cn.hutool.log.LogFactory; import com.luzhi.miniTomcat.http.Request; import com.luzhi.miniTomcat.http.Response; import com.luzhi.miniTomcat.util.ThreadPoolUtil; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * @author apple * @version jdk1.8 * // TODO : 2021/5/21 * 生成对server.xml"中连接器解析". */ @SuppressWarnings("unused") public class Connector implements Runnable { /** * 服务端口 * * @see #port */ private int port; /** * 获取Service对象. * * @see #service */ private final Service service; /** * 创建compression属性值(是否进行压缩) * * @see #compression */ private String compression; /** * 创建compressionMinSize(超过多少字节数进行压缩) * * @see #compressionMinSize */ private int compressionMinSize; /** * 创建onCompressionUserAgents(那些浏览器不需要压缩) * * @see #onCompressionUserAgents */ private String onCompressionUserAgents; /** * 创建compressionMimeType(那些文件需要进行压缩.) * * @see #compressibleMimeType */ private String compressibleMimeType; @Override public void run() { try { ServerSocket serverSocket = new ServerSocket(port); //noinspection InfiniteLoopStatement while (true) { // 收到一个浏览器服务器的请求. Socket socket = serverSocket.accept(); Runnable runnable = () -> { try { Request request = new Request(socket, Connector.this); System.out.println("浏览器读取的信息为: \r\n" + request.getRequestString()); System.out.println("Uri信息为: \r\n" + request.getUri()); Response response = new Response(); HttpProcessor processor = new HttpProcessor(); processor.execute(socket, request, response); } catch (IOException exception) { // 日志打印输出异常. LogFactory.get().error(exception); } }; // 把当前定义的 runnable 丢入定义的线程池中. ThreadPoolUtil.run(runnable); } } catch (Exception exception) { LogFactory.get().error(exception); System.out.println("异常的原因:" + exception.getMessage()); } } public void init() { LogFactory.get().info("Init ProtocolHandler [http-bio-{}]", port); } @SuppressWarnings("AlibabaAvoidManuallyCreateThread") public void start() { LogFactory.get().info("Start ProtocolHandler [http-bio-{}]", port); new Thread(this).start(); } public Connector(Service service) { this.service = service; } public void setPort(int port) { this.port = port; } public Service getService() { return service; } public int getCompressionMinSize() { return compressionMinSize; } public int getPort() { return port; } public String getCompressibleMimeType() { return compressibleMimeType; } public String getCompression() { return compression; } public void setCompression(String compression) { this.compression = compression; } public String getOnCompressionUserAgents() { return onCompressionUserAgents; } public void setCompressibleMimeType(String compressibleMimeType) { this.compressibleMimeType = compressibleMimeType; } public void setCompressionMinSize(int compressionMinSize) { this.compressionMinSize = compressionMinSize; } public void setOnCompressionUserAgents(String onCompressionUserAgents) { this.onCompressionUserAgents = onCompressionUserAgents; } } <file_sep>/webapps/javaweb1/web/WEB-INF/classes/com/luzhi/test.js // noinspection JSUnusedGlobalSymbols /** * @author apple * @version javaScript11 * @since 1.0 * // TODO : 2021/5/21 */ import(document) /** * 设置cookie值 * @see #setCookie * @param paramName 设置参数名 * @param paramValue 设置参数值 * @param exDays 设置cookie多少天过期 */ function setCookie(paramName, paramValue, exDays) { let date = new Date(); date.setTime(date.getTime() + (exDays * 24 * 60 * 60 * 1000)); let expires = "expires=" + date.toUTCString(); document.cookie = paramName + "=" + paramValue + ";" + expires; } /** * 获取cookie值 * @see getCookie * @param paramName 获取cookie键值 */ function getCookie(paramName) { let name = paramName + "="; let cookieSet = document.cookie.split(";"); for (let i = 0; i < cookieSet.length; i++) { let result = cookieSet[i].trim(); if (result.indexOf(name) === 0) { return result.substring(name.length, result.length); } } } /** * 检查cookie值 * @see checkCookie * @param paramName 需要检查的cookie值 */ function checkCookie(paramName) { let name = getCookie(paramName); if (name !== "" && name != null) { window.alert("cookie值存在" + name + "呀"); } else { name = window.prompt("输出键值:", ""); if (name !== "" && name != null) { setCookie(paramName, name, 1); } } }<file_sep>/src/com/luzhi/miniTomcat/catalina/Engine.java package com.luzhi.miniTomcat.catalina; import com.luzhi.miniTomcat.util.ServerXmlUtil; import java.util.List; /** * @author apple * @version jdk1.8 * // TODO : 2021/5/21 * 对miniTomcat的内置对象Engine进行处理. */ @SuppressWarnings("unused") public class Engine { private final String defaultName; private final List<Host> hosts; private final Service service; public Engine(Service service) { this.defaultName = ServerXmlUtil.getEngineName(); this.hosts = ServerXmlUtil.getHosts(this); this.service = service; checkDefaultHost(); } /** * 检查{@link #getDefaultHost()}返回是否为空。 * * @throws RuntimeException 如果Host为空抛出为运行异常. * @see #checkDefaultHost() */ private void checkDefaultHost() { if (null == getDefaultHost()) { throw new RuntimeException("the defaultHost: " + this.defaultName + " not exist"); } } /** * 遍历Engine的Host标签是否存在defaultHost。 * 理论上可以处理多个Host,但事实上只处理一个Host.本地主机. * * @see #getDefaultHost() */ public Host getDefaultHost() { for (Host host : hosts) { if (this.defaultName.equals(host.getName())) { return host; } } return null; } public Service getService() { return service; } } <file_sep>/src/com/luzhi/miniTomcat/catalina/Server.java package com.luzhi.miniTomcat.catalina; import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.TimeInterval; import cn.hutool.log.LogFactory; import cn.hutool.system.SystemUtil; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; /** * @author apple * @version jdk1.8 * // TODO : 2021/5/21 * Server是最外层的元素,代表服务器本身. */ public class Server { private final Service service; public Server() { this.service = new Service(this); } public void start() { TimeInterval timeInterval = DateUtil.timer(); logJvm(); init(); LogFactory.get().info("服务器启动使用{}毫秒", timeInterval.intervalMs()); } /** * 由Server(服务器)进行处理. * * @see #init() 对请求和访问进行初始化. */ private void init() { service.init(); } /** * 此方法用作设置相关的输出日志. * 在该方法中使用 {@link LinkedHashMap} 而不用 {@link java.util.HashMap} 是因为前者存放是由序的Hash键值 * 后者为无序存放Hash的键值. * * @see #logJvm() */ private static void logJvm() { // 定义存放相关信息的Map.(Server 版本, System 相关信息, Jvm的一些相关信息.) Map<String, String> mapInfo = new LinkedHashMap<>(512); mapInfo.put("Server version", "Luzhi miniTomcat/1.0.1"); mapInfo.put("Server built", "2021-5-21, 21:31:22"); mapInfo.put("Server name", "1.0.1"); mapInfo.put("OS Name \t", SystemUtil.get("os.name")); mapInfo.put("OS Version", SystemUtil.get("os.version")); mapInfo.put("System Architecture", SystemUtil.get("os.arch")); mapInfo.put("Java Home", SystemUtil.get("java.home")); mapInfo.put("Jvm Version", SystemUtil.get("java.runtime.version")); mapInfo.put("Jvm Vendor", SystemUtil.get("java.vm.specification.vendor")); Set<String> keySet = mapInfo.keySet(); for (String key : keySet) { // 创建日志工厂设置info类型日志. LogFactory.get().info(key + ":\t\t" + mapInfo.get(key)); } } } <file_sep>/src/com/luzhi/miniTomcat/classloader/WebAppClassLoader.java package com.luzhi.miniTomcat.classloader; import cn.hutool.core.io.FileUtil; import com.luzhi.miniTomcat.catalina.Context; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.List; /** * @author apple * @version jdk1.8 * // TODO : 2021/5/6 * 生成web应用的类的加载器. */ public class WebAppClassLoader extends URLClassLoader { /** * 该构成方法创建一个Web应用的类加载器. * * @param docBase 扫描{@link Context#getDocBase()}获取classes和jar资源 * @param commonClassLoader 获取父类加载器 * @see #WebAppClassLoader(String, ClassLoader) */ public WebAppClassLoader(String docBase, ClassLoader commonClassLoader) { super(new URL[]{}, commonClassLoader); try { // 扫描路径 File webInfFolder = new File(docBase, "WEB-INF"); File classesFolder = new File(webInfFolder, "classes"); File jarFolder = new File(webInfFolder, "lib"); URL url; // 将classes目录扫入URL中添加后缀"/",如此这样才会把WEB-INF下的classes当做目录来处理.不然的话会将资源当作(.jar)文件进行处理 url = new URL("file:" + classesFolder.getAbsolutePath() + "/"); this.addURL(url); // 遍历WEB-INF下的lib中的(.jar)文件.{@code FileUtil.loopFiles(jarFolder)}将结果打包成一个List List<File> jarLists = FileUtil.loopFiles(jarFolder); for (File file : jarLists) { url = new URL("file:" + file.getAbsolutePath()); this.addURL(url); } } catch (Exception exception) { System.out.println("打印异常原因:" + exception.getMessage()); exception.printStackTrace(); } } /** * 关闭该加载器. * * @see #stop() */ public void stop() { try { close(); } catch (IOException exception) { System.out.println("打印异常原因:" + exception.getMessage()); exception.printStackTrace(); } } } <file_sep>/shutdown.sh #!/usr/bin/env zsh # 结束由 startup.sh 启动的tomcat进程 # shellcheck disable=SC2006 # shellcheck disable=SC2009 echo "正在关闭 tomcat (╮(╯▽╰)╭ )" # 查找启动进程PID号 Tomcat_Id=$(ps -ef | grep java | grep -v "grep" | awk '{print $2}') # 判断$Tomcat_Id不为空 if [ "$Tomcat_Id" ]; then for id in $Tomcat_Id; do # 结束进程 kill -9 "$id" echo "有关Tomcat_Id进程${id}已经结束,谢谢." done echo "tomcat 关闭完成(>﹏<)" else echo "tomcat 进程不存在.请稍后尝试.(( ̄3 ̄)a)" fi <file_sep>/src/com/luzhi/miniTomcat/http/Response.java package com.luzhi.miniTomcat.http; import cn.hutool.core.date.DateField; import cn.hutool.core.date.DateUtil; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; /** * @author apple * @version jdk1.8 * // TODO:2021/5/20 * 生成miniTomcat的Response,同理Response需要实现{@link HttpServletResponse} */ public class Response extends BaseResponse { /** * @see #stringWriter * 字符流将其输出收集到缓存字符串中,将输出的头信息写入缓存字符串中. */ private final StringWriter stringWriter; /** * @see #writer * 因为浏览器返回的是字符流,所以在Java中不使用{@link java.io.PrintStream}, * 而使用 {@link PrintWriter},把数据字符流写入 stringWrite中 */ private final PrintWriter writer; /** * @see #contentType * 保存浏览器的头信息.文本类型为 "text/html". */ private String contentType; /** * @see #redirectPath * 重定向路径. */ private String redirectPath; /** * @see #bytes * 保存二进制文件 */ private byte[] bytes; /** * @see #status * 设置状态值. */ private int status; /** * @see #cookies * 声明一个Cookie列表 */ private final List<Cookie> cookies; /** * @see #Response() * 初始化构造Response()方法对获取对回复的数据进行进行操作. */ public Response() { this.stringWriter = new StringWriter(); this.cookies = new ArrayList<>(); this.writer = new PrintWriter(stringWriter); this.contentType = "text/html"; } @Override public void setContentType(String contentType) { this.contentType = contentType; } @Override public String getContentType() { return contentType; } /** * @see #getBody() * 获取当前stringWrite对象,对缓存的字节流,转化为字节数组. */ public byte[] getBody() { if (null == bytes) { String content = stringWriter.toString(); bytes = content.getBytes(StandardCharsets.UTF_8); } return bytes; } public void setBytes(byte[] bytes) { this.bytes = bytes; } public String getRedirectPath() { return redirectPath; } @Override public PrintWriter getWriter() { return writer; } @Override public int getStatus() { return status; } @Override public void setStatus(int status) { this.status = status; } @Override public void sendRedirect(String redirect){ this.redirectPath = redirect; } @Override public void addCookie(Cookie cookie) { cookies.add(cookie); } public List<Cookie> getCookies() { return cookies; } public String getCookiesHeader() { String pattern = "EEE, d MMM yyyy HH:mm:ss 'GMT'"; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern, Locale.ENGLISH); StringBuilder stringBuffer = new StringBuilder(); for (Cookie cookie : getCookies()) { stringBuffer.append("\r\n"); stringBuffer.append("Set-Cookie:"); stringBuffer.append(cookie.getName()).append("=").append(cookie.getValue()).append(";"); // cookie.getMaxAge()为-1意味着Cookie中Expires is forever 直到浏览器关闭. if (-1 != cookie.getMaxAge()) { stringBuffer.append("Expires="); Date date = new Date(); Date expire = DateUtil.offset(date, DateField.SECOND, cookie.getMaxAge()); stringBuffer.append(simpleDateFormat.format(expire)).append(";"); } if (null != cookie.getPath()) { stringBuffer.append("Path=").append(cookie.getPath()); } } return stringBuffer.toString(); } } <file_sep>/src/com/luzhi/miniTomcat/http/StandardSession.java package com.luzhi.miniTomcat.http; import javax.servlet.ServletContext; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionContext; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; /** * @author apple * @version jdk1.8 * // TODO : 2021/6/16 * 生成自定义标准化Session实现{@link HttpSession} 接口 */ public class StandardSession implements HttpSession { /** * @see #attributeMap * <p> * 在session存放相关的信息 */ private final Map<String, Object> attributeMap; /** * @see #id * <p> * 创建session唯一标识符 */ private final String id; /** * @see #creationTime * <p> * session会话创建的时间 */ private final long creationTime; /** * @see #lastAccessedTime * <p> * 用户结束session最后访问的时间 */ private long lastAccessedTime; /** * @see #servletContext * <p> * 接受当前需要创建session对象的ServletContext */ private final ServletContext servletContext; /** * @see #maxInactiveInterval * <p> * 最大非活动session持续的时间,一般为30分钟,如果不进行登录默认session失效. */ private int maxInactiveInterval; public StandardSession(String jSessionId, ServletContext servletContext) { this.attributeMap = new HashMap<>(512); this.id = jSessionId; this.servletContext = servletContext; this.creationTime = System.currentTimeMillis(); } @Override public long getCreationTime() { return this.creationTime; } @Override public String getId() { return this.id; } @Override public long getLastAccessedTime() { return this.lastAccessedTime; } @SuppressWarnings("unused") public void setLastAccessedTime(long lastAccessedTime) { this.lastAccessedTime = lastAccessedTime; } @Override public ServletContext getServletContext() { return this.servletContext; } @Override public void setMaxInactiveInterval(int interval) { this.maxInactiveInterval = interval; } @Override public int getMaxInactiveInterval() { return this.maxInactiveInterval; } @Override @Deprecated public HttpSessionContext getSessionContext() { return null; } @Override public Object getAttribute(String name) { return attributeMap.get(name); } @Override public Object getValue(String name) { return null; } @Override public Enumeration<String> getAttributeNames() { return Collections.enumeration(attributeMap.keySet()); } @Override public String[] getValueNames() { return new String[0]; } @Override public void setAttribute(String name, Object value) { attributeMap.put(name, value); } @Override public void putValue(String name, Object value) { } @Override public void removeAttribute(String name) { attributeMap.remove(name); } @Override public void removeValue(String name) { } @Override public void invalidate() { attributeMap.clear(); } @Override public boolean isNew() { return creationTime == lastAccessedTime; } } <file_sep>/src/com/luzhi/miniTomcat/http/Request.java package com.luzhi.miniTomcat.http; import cn.hutool.core.convert.Convert; import cn.hutool.core.io.IoUtil; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.URLUtil; import com.luzhi.miniTomcat.catalina.Connector; import com.luzhi.miniTomcat.catalina.Context; import com.luzhi.miniTomcat.catalina.Engine; import com.luzhi.miniTomcat.catalina.Service; import com.luzhi.miniTomcat.util.MiniBrowser; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.*; /** * @author apple * @version jdk1.8 * // TODO : 2021/5/11 * 生成miniTomcat的Request,为了把Request参数传入Servlet中,需要实现 {@link HttpServletRequest} */ public class Request extends BaseRequest { /** * 获取对Http解析的字符串 * * @see #requestString */ private String requestString; /** * 创建Context对象. * * @see #context */ private Context context; /** * 处理的uri请求. * * @see #uri */ private String uri; /** * 返回请求的method。 * * @see #method */ private String method; /** * 准备查询参数. * * @see #queryString */ private String queryString; /** * 当前的请求是否为转发 * * @see #forwarded */ private boolean forwarded; /** * 从Connector获取Service对象,再从Service标签中获取Engine对象,在从获取的Engine获取Host对象 * * @see #connector */ private final Connector connector; /** * 从启动器获取Socket(套接字). * * @see #socket */ private final Socket socket; /** * 创建一个Session对象. * * @see #session */ private HttpSession session; /** * 存放相关参数的Map * * @see #paramMaps */ private final Map<String, String[]> paramMaps; /** * 存放请求的头信息 * * @see #headerMaps */ private final Map<String, String> headerMaps; /** * 存放信息,便于服务器传参数. * * @see #attributesMap */ private final Map<String, Object> attributesMap; /** * 存放Cookie对象的数组 * * @see #cookies */ private Cookie[] cookies; /** * 用于解析指定'?'是否出现被截取对字符串中 * * @see #SEARCH_CHAR */ private static final char SEARCH_CHAR = '?'; /** * 用于分割地址的字符串. ==== "/" * * @see #DIVISION_STRING */ private static final String DIVISION_STRING = "/"; /** * 处理 get 请求 * * @see #GET */ private static final String GET = "GET"; /** * 处理 post 请求 * * @see #POST */ private static final String POST = "POST"; /** * http协议默认端口为:80 * * @see #HTTP_PORT */ private static final int HTTP_PORT = 80; /** * https协议默认端口为:443 * * @see #HTTPS_PORT */ private static final int HTTPS_PORT = 443; /** * http协议 * * @see #HTTP */ private static final String HTTP = "http"; /** * https协议. * * @see #HTTPS */ private static final String HTTPS = "https"; /** * JSESSIONID * * @see #JSESSIONID */ private static final String JSESSIONID = "JSESSIONID"; /** * 初始化构造函数,由{@link Request}直接对http请求和uri进行解析。 * * @see #Request(Socket, Connector) */ public Request(Socket socket, Connector connector) throws IOException { this.socket = socket; this.connector = connector; this.paramMaps = new HashMap<>(512); this.headerMaps = new HashMap<>(512); this.attributesMap = new HashMap<>(512); parseHttpRequest(); // 判断解析的Http请求的"头"和请求内容不为空. if (StrUtil.isEmpty(this.requestString)) { return; } parseUri(); parseMethod(); parseContext(); if (!DIVISION_STRING.equals(context.getPath())) { uri = StrUtil.removePrefix(uri, context.getPath()); // 如果去除context.getPath前缀后返回为空字符串 if (StrUtil.isEmpty(uri)) { // 将uri 设置为"/" uri = "/"; } } parseParameters(); parseHeaderMap(); parseCookie(); } /** * 解析请求中method(Get,Post),获取请求值,并且不从最后开始索引. * * @see #parseMethod() */ private void parseMethod() { method = StrUtil.subBefore(requestString, " ", false); } /** * 该方法对Http请求进行解析.使用{@link MiniBrowser#readBytes(InputStream, boolean)} * 返回一个解析完成的byte[]数组 * * @see #parseHttpRequest() */ private void parseHttpRequest() throws IOException { InputStream inputStream = this.socket.getInputStream(); byte[] bytes = MiniBrowser.readBytes(inputStream, false); // 推荐使用StandardCharsets.UTF_8,因为会自动抛出 "字符不支持异常" this.requestString = new String(bytes, StandardCharsets.UTF_8); } /** * 该方法对Http解析返回的"头"和请求内容进行解析. * * @see #parseUri() */ private void parseUri() { String temp; // 对字符进行截取,获取被两个字符空格截取对部分。 temp = StrUtil.subBetween(this.requestString, " ", " "); // 判断'?' 是否在已经截取对字符串中. if (!StrUtil.contains(temp, SEARCH_CHAR)) { // '?' 不在截取的字符串中. this.uri = temp; return; } // 如果'?' 在截取的字符串中,返回前面的部分.不查找最后的一个分割字符串. temp = StrUtil.subBefore(temp, '?', false); this.uri = temp; } /** * 在Request 中创建解析Context. * * @see #parseContext() */ private void parseContext() { Service service = connector.getService(); Engine engine = service.getEngine(); context = engine.getDefaultHost().getContext(uri); if (null != context) { return; } // 截取字符串 String path = StrUtil.subBetween(this.uri, "/", "/"); if (path == null) { path = "/"; } else { path = "/" + path; } // 通过截取的字符串获取Context对象. context = engine.getDefaultHost().getContext(path); if (context == null) { context = engine.getDefaultHost().getContext("/"); } } private void parseParameters() { System.out.println("打印queryString为:" + this.queryString); if (GET.equals(this.getMethod())) { String url = StrUtil.subBetween(requestString, " ", " "); if (StrUtil.contains(url, SEARCH_CHAR)) { queryString = StrUtil.subAfter(url, SEARCH_CHAR, false); } } if (POST.equals(this.getMethod())) { queryString = StrUtil.subAfter(requestString, "\r\n\r\n", false); } if (null == queryString) { return; } queryString = URLUtil.decode(queryString); String[] parametersValues = queryString.split("&"); for (String parameterValue : parametersValues) { String[] nameValues = parameterValue.split("="); String name = nameValues[0]; String value = nameValues[1]; String[] values = paramMaps.get(name); if (null == values) { values = new String[]{value}; } else { values = ArrayUtil.append(values, value); } paramMaps.put(name, values); } } public void parseHeaderMap() { StringReader stringReader = new StringReader(requestString); List<String> list = new ArrayList<>(); // 把数据从Reader读取Collection集合中 IoUtil.readLines(stringReader, list); for (int i = 1; i < list.size(); i++) { String line = list.get(i); if (line.length() == 0) { break; } String[] speList = line.split(":"); String headerName = speList[0].toLowerCase(); String headerValue = speList[1]; headerMaps.put(headerName, headerValue); } } private void parseCookie() { List<Cookie> cookieList = new ArrayList<>(); String cookieStringList = headerMaps.get("cookie"); if (null != cookieStringList) { // 根据";"分隔获取数组 String[] pairs = StrUtil.split(cookieStringList, ";"); for (String pair : pairs) { if (null == pair) { continue; } // 将获得的每个Cookie(key-value)根据"="进行分隔. String[] speCookie = StrUtil.split(pair, "="); Cookie cookie = new Cookie(speCookie[0].trim(), speCookie[1].trim()); cookieList.add(cookie); } } this.cookies = ArrayUtil.toArray(cookieList, Cookie.class); } /** * 通过Cookie对象获取JSEESIONID * * @see #getJSessionIdFormCookie() */ @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming") public String getJSessionIdFormCookie() { if (null == cookies) { return null; } for (Cookie cookie : cookies) { if (JSESSIONID.equals(cookie.getName())) { return cookie.getValue(); } } return null; } public void setSession(HttpSession session) { this.session = session; } public void setUri(String uri) { this.uri = uri; } public Socket getSocket() { return socket; } public void setForwarded(boolean forwarded) { this.forwarded = forwarded; } public Context getContext() { return context; } public String getUri() { return uri; } public String getRequestString() { return requestString; } public Connector getConnector() { return connector; } public boolean isForwarded() { return forwarded; } @Override public RequestDispatcher getRequestDispatcher(String uri) { return new ApplicationRequestDispatcher(uri); } @Override public HttpSession getSession() { return session; } @Override public Cookie[] getCookies() { return this.cookies; } @Override public String getParameter(String name) { String[] values = paramMaps.get(name); if (null != values && 0 != values.length) { return values[0]; } return null; } @Override public void setAttribute(String name, Object object) { attributesMap.put(name, object); } @Override public void removeAttribute(String name) { attributesMap.remove(name); } @Override public Object getAttribute(String name) { return attributesMap.get(name); } @Override public Enumeration<String> getAttributeNames() { return Collections.enumeration(attributesMap.keySet()); } @Override public HttpSession getSession(boolean b) { return super.getSession(b); } @Override public String getMethod() { return method; } @Override public ServletContext getServletContext() { return context.getServletContext(); } @Override public String getRealPath(String name) { return context.getServletContext().getRealPath(name); } @Override public Map<String, String[]> getParameterMap() { return this.paramMaps; } @Override public Enumeration<String> getParameterNames() { return Collections.enumeration(paramMaps.keySet()); } @Override public String[] getParameterValues(String name) { return paramMaps.get(name); } @Override public Enumeration<String> getHeaderNames() { return Collections.enumeration(headerMaps.keySet()); } @Override public String getHeader(String name) { if (null == name) { return null; } return headerMaps.get(name.toLowerCase()); } @Override public int getIntHeader(String name) { // 将值转换为int值,转换失败默认为0 return Convert.toInt(headerMaps.get(name), 0); } @Override public String getLocalAddr() { return socket.getLocalAddress().getHostAddress(); } @Override public String getLocalName() { return socket.getLocalAddress().getHostName(); } @Override public int getLocalPort() { return socket.getLocalPort(); } @Override public String getProtocol() { return "HTTP:/1.1"; } @Override public String getRemoteAddr() { InetSocketAddress inetSocketAddress = (InetSocketAddress) socket.getRemoteSocketAddress(); String temp = inetSocketAddress.getAddress().toString(); return StrUtil.subAfter(temp, "/", false); } @Override public String getRemoteHost() { InetSocketAddress inetSocketAddress = (InetSocketAddress) socket.getRemoteSocketAddress(); return inetSocketAddress.getHostName(); } @Override public String getScheme() { return "http"; } @Override public String getServerName() { return getHeader("host").trim(); } @Override public int getServerPort() { return getLocalPort(); } @Override public String getContextPath() { String result = this.context.getPath(); if (DIVISION_STRING.equals(result)) { return ""; } return result; } @Override @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming") public String getRequestURI() { return uri; } @Override @SuppressWarnings("AlibabaLowerCamelCaseVariableNaming") public StringBuffer getRequestURL() { StringBuffer url = new StringBuffer(); String scheme = getScheme(); int port = getServerPort(); if (port < 0) { port = 80; } url.append(scheme); url.append("://"); url.append(getServerName()); boolean http = (scheme.equals(HTTP) && port != HTTP_PORT); boolean https = (scheme.equals(HTTPS) && port != HTTPS_PORT); if (http || https) { url.append(":"); url.append(port); } url.append(getRequestURI()); return url; } @Override public String getServletPath() { return uri; } } <file_sep>/src/com/luzhi/miniTomcat/servlets/JspServlet.java package com.luzhi.miniTomcat.servlets; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.StrUtil; import com.luzhi.miniTomcat.catalina.Context; import com.luzhi.miniTomcat.classloader.JspClassLoader; import com.luzhi.miniTomcat.http.Request; import com.luzhi.miniTomcat.http.Response; import com.luzhi.miniTomcat.util.ConstantTomcat; import com.luzhi.miniTomcat.util.JspUtil; import com.luzhi.miniTomcat.util.WebXmlUtil; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; /** * @author apple * @version jdk1.8 * // TODO : 2021/6/11 * 创建该列对Jsp文件解析的Servlet; */ public class JspServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see #STATUES_INIT * <p> * /初始化界面. */ private static final String STATUES_INIT = "/"; private static final JspServlet INSTANCE = new JspServlet(); public static synchronized JspServlet getInstance() { return INSTANCE; } /** * @see #JspServlet() * 禁止任何人对其实例化. */ private JspServlet() { } @Override public void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { try { Request request = (Request) httpServletRequest; Response response = (Response) httpServletResponse; String uri = request.getRequestURI(); if (STATUES_INIT.equals(uri)) { uri = WebXmlUtil.getWelcomeFile(request.getContext()); } String fileName = StrUtil.removePrefix(uri, STATUES_INIT); File file = FileUtil.file(request.getRealPath(fileName)); if (file.exists()) { Context context = request.getContext(); String path = context.getPath(); String subFolder; if (STATUES_INIT.equals(path)) { subFolder = "_"; } else { subFolder = StrUtil.subAfter(path, '/', false); } String servletClassPath = JspUtil.getServletClassPath(uri, subFolder); File jspServletClassFile = new File(servletClassPath); if (!jspServletClassFile.exists()) { JspUtil.compileJsp(context, file); } else if (file.lastModified() > jspServletClassFile.lastModified()) { JspUtil.compileJsp(context, file); JspClassLoader.invalidJspClassLoader(uri, context); } String extensionName = FileUtil.extName(file); String miniType = WebXmlUtil.getMimeName(extensionName); response.setContentType(miniType); JspClassLoader jspClassLoader = JspClassLoader.getJspClassLoader(uri, context); String jspServletClassName = JspUtil.getJspServletClassName(uri, subFolder); Class<?> jspServletClass = jspClassLoader.loadClass(jspServletClassName); HttpServlet servlet = context.getServlet(jspServletClass); servlet.service(request, response); response.setStatus(ConstantTomcat.CODE_200); } else { response.setStatus(ConstantTomcat.CODE_404); } } catch (Exception exception) { throw new RuntimeException(exception); } } } <file_sep>/src/com/luzhi/miniTomcat/catalina/Host.java package com.luzhi.miniTomcat.catalina; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.RuntimeUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.log.LogFactory; import com.luzhi.miniTomcat.util.ConstantTomcat; import com.luzhi.miniTomcat.util.ServerXmlUtil; import com.luzhi.miniTomcat.watcher.WarFileWatcher; import java.io.File; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * @author apple * @version jdk1.8 * // TODO : 2021/5/21 * 对miniTomcat的内置对象的Host进行处理 */ @SuppressWarnings("unused") public class Host { private String name; private final Engine engine; private static final String ROOT = "ROOT"; private static Map<String, Context> contextMap; public Host(String name, Engine engine) { this.engine = engine; this.name = name; contextMap = new LinkedHashMap<>(128); scanContextsOnServerXml(); scanContextsOnWebAppsFolder(); LogFactory.get().info("<====================== HOST ======================>"); scanWarOnWebAppsFolder(); LogFactory.get().info("<====================== HOST END ===================>"); new WarFileWatcher(this).start(); } /** * 遍历webapps文件夹下的文件夹和文件.如果是文件的话直接跳过, * 如果是文件夹交由{@link #loadContext(File)}方法进行处理. * * @see #scanContextsOnWebAppsFolder() */ private void scanContextsOnWebAppsFolder() { File[] folders = ConstantTomcat.WEBAPPS_FOLDER.listFiles(); // 设置断言因为在File类中listFiles()如果被遍历的文件夹下如果为空则该方法返回null. assert folders != null; for (File folder : folders) { if (!folder.isDirectory()) { continue; } loadContext(folder); } } /** * 加载{@link Context}对象 * * @param folder 获取需要处理的文件夹. * @see #loadContext(File) */ private void loadContext(File folder) { String path = folder.getName(); if (ROOT.equals(path)) { path = "/"; } else { path = "/" + path; } String docBase = folder.getAbsolutePath(); Context context = new Context(path, docBase, this, true); // 将获取web下的资源路径和初始化的context对象写入Map中. contextMap.put(context.getPath(), context); } /** * 把文件加加载为{@link Context} 对象; * * @param folder 需要处理的文件 * @see #load(File) */ public void load(File folder) { String path = folder.getName(); if (ROOT.equals(path)) { path = "/"; } else { path = "/" + path; } String docBase = folder.getAbsolutePath(); Context context = new Context(path, docBase, this, false); contextMap.put(context.getPath(), context); } /** * 把war文件进行解析为目录,并把文件加载为相关的Context * * @param warFile 获取相关的war文件 * @see #loadWar(File) */ public void loadWar(File warFile) { String fileName = warFile.getName(); String folderName = StrUtil.subBefore(fileName, ".", true); // 是否存在相应的Context对象 Context context = getContext("/" + folderName); if (null != context) { return; } // 是否存在相应的文件夹对象. File folder = new File(ConstantTomcat.WEBAPPS_FOLDER, folderName); if (folder.exists()) { return; } // 移动war文件,因为jar命令只支持解压当前目录下 File tempWarFile = FileUtil.file(ConstantTomcat.WEBAPPS_FOLDER, folderName, fileName); File contextFolder = tempWarFile.getParentFile(); //noinspection ResultOfMethodCallIgnored contextFolder.mkdir(); FileUtil.copyFile(warFile, tempWarFile); // 进行解压 String command = "jar xvf " + fileName; System.out.println(command); Process process = RuntimeUtil.exec(null, contextFolder, command); try { process.waitFor(); } catch (InterruptedException exception) { System.out.println("打印异常原因:" + exception.getMessage()); } // 解压后删除文件对象 //noinspection ResultOfMethodCallIgnored tempWarFile.delete(); // 创建新的Context; load(contextFolder); } /** * 多应用配置.将{@link ServerXmlUtil#contextList(Host)}解析的{@link Context}进行遍历 * 和保存的ContextMap中. * * @see #scanContextsOnServerXml() */ private void scanContextsOnServerXml() { List<Context> contexts = ServerXmlUtil.contextList(this); for (Context context : contexts) { contextMap.put(context.getPath(), context); } } /** * 扫描webapps下的文件,处理.war文件 * * @see #scanWarOnWebAppsFolder() */ private void scanWarOnWebAppsFolder() { File folder = FileUtil.file(ConstantTomcat.WEBAPPS_FOLDER); File[] files = folder.listFiles(); assert files != null; LogFactory.get().info("<HELLO>" + Arrays.stream(files).count()); for (File file : files) { if (file.getName().toLowerCase().endsWith(".war")) { LogFactory.get().info("文件名:" + file.getName()); loadWar(file); } } } /** * 具体重载操作. * * @param context 获取子类对象{@code Context.this} * @see #reload(Context) */ public void reload(Context context) { LogFactory.get().info("Reloading context with name [{}] has started", context.getPath()); String path = context.getPath(); String docBase = context.getDocBase(); boolean reloadable = context.isReloadable(); // stop context.stop(); // remove contextMap.remove(path); // 重新设置对应关系. Context newContext = new Context(path, docBase, this, reloadable); contextMap.put(newContext.getPath(), newContext); LogFactory.get().info("Reloading Context with name [{}] has completed", context.getPath()); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Context getContext(String path) { return contextMap.get(path); } public Engine getEngine() { return engine; } }
1871b3daf10d7beb7facf391ba224adf623b6284
[ "JavaScript", "Java", "Shell" ]
17
Java
zhi-lu/MasterLearning
8f616248c51e4ee6181b9008b29809ec8f02b86c
7f347c5879ad5e05988fce76e51eaf357427b348
refs/heads/master
<file_sep>const express = require('express'); const exphbs = require('express-handlebars'); const path = require('path'); const bodyParser = require('body-parser'); const methodOverride = require('method-override'); const redis = require('redis'); let unirest = require('unirest'); // Create a redis client let client = redis.createClient(); client.on('connect', function(){ console.log("Connected to redis"); }); const port = 3000; const app = express(); app.engine('handlebars', exphbs({defaultLayout: 'main'})); app.set('view engine', 'handlebars'); // Body parser app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended:false})); // methodOverride app.use(methodOverride('_method')); // Search Page app.get('/search', function(req, res, next){ res.render('searchusers'); }); // Search processing app.post('/user/search', function(req, res, next){ let id = req.body.id; client.hgetall(id, function(err, obj){ if (!obj){ res.render('searchusers', { error: 'User does not exist' }); } else{ obj.id = id; let request = require('request'); let link1 = "http://api.proc.link/oembed?url=http%3A%2F%2F" + obj.link1; let link2 = "http://api.proc.link/oembed?url=http%3A%2F%2F" + obj.link2; let link3 = "http://api.proc.link/oembed?url=http%3A%2F%2F" + obj.link3; let link4 = "http://api.proc.link/oembed?url=http%3A%2F%2F" + obj.link4; var thumb_1 = ""; var thumb_2 = ""; var thumb_3 = ""; var thumb_4 = ""; request(link1, function (error, response, body) { if (!error && response.statusCode == 200) { let info = JSON.parse(body); thumb_1 = info; } request(link2, function (error, response, body) { if (!error && response.statusCode == 200) { let info = JSON.parse(body); thumb_2 = info; } request(link3, function (error, response, body) { if (!error && response.statusCode == 200) { let info = JSON.parse(body); thumb_3 = info; } request(link4, function (error, response, body) { if (!error && response.statusCode == 200) { let info = JSON.parse(body); thumb_4 = info; } res.render('details', { user: obj, thumb1: thumb_1, thumb2: thumb_2, thumb3: thumb_3, thumb4: thumb_4 }); }); }); }); }); } }); }); // Home page app.get('/', function(req, res, next){ client.keys('*', function(err, keys){ if (err){ return console.log(err); } res.render('display', { key: keys }); }); }); // Add board page app.get('/user/add', function(req, res, next){ res.render('adduser'); }); // Process Add board page app.post('/user/add', function(req, res, next){ let id = req.body.id; let link1 = req.body.link1; let link2 = req.body.link2; let link3 = req.body.link3; let link4 = req.body.link4; client.hmset(id, [ 'link1', link1, 'link2', link2, 'link3', link3, 'link4', link4 ], function(err, reply){ if (err){ console.log(err); } res.redirect('/'); }); }); // Delete user app.delete('/user/delete/:id', function(req, res, next){ client.del(req.params.id); res.redirect('/'); }); app.listen(port, function(){ console.log("Server started in port " + port); });
4508f2aea8bf09b2693862d77171a91553e597ba
[ "JavaScript" ]
1
JavaScript
sukeesh/Pinterest-for-Links
ca14acc71ceb22e469f3bc5b1dbe4c0a99a521a6
108d5145632c4f5bd45e26a5cadd06f7c62f987e
refs/heads/master
<file_sep>require 'java' require 'rubygems' require 'rsolr' require 'rsolr-direct' require 'timestools.jar' require 'date' class String def starts_with?(prefix) prefix = prefix.to_s self[0, prefix.length] == prefix end def ends_with?(suffix) suffix = suffix.to_s self[-suffix.length, suffix.length] == suffix end end def untar_dir(dir) tar_files = Dir[File.join(dir, "**", "*")].map{|f| f if File.basename(f).ends_with?(".tgz")}.compact tar_files.each do |file| puts "Untaring #{file}" system("tar -C #{File.dirname(file)} -zxvf #{file}") end end def index_dir(dir, opts={}) solr = nil if opts[:solr_home] != nil RSolr.load_java_libs solr = RSolr.connect :direct, :solr_home => opts[:solr_home] elsif opts[:solr_server_url] != nil solr = RSolr.connect :url=> opts[:solr_server_url] else raise "You must specify a solr_home or solr_server_url" end solr.delete_by_query "*:*" docs = [] xml_files = Dir[File.join(dir, "**", "*")].map{|f| f if File.basename(f).ends_with?(".xml")}.compact xml_files.each_with_index do |file, i| #puts "Processing #{file}" docs << parse_and_create_hash_from_nyt_file(java.io.File.new(file)) #commit every 2000 docs to reduce mem usage if(i % 2000 == 0) solr.add(docs) solr.commit # solr.optimize # causes issues using web api docs = [] end end end def parse_and_create_hash_from_nyt_file(file) parser = com.nytlabs.corpus.NYTCorpusDocumentParser.new nytDoc = parser.parseNYTCorpusDocumentFromFile(file, false) create_hash_from_nyt_doc(nytDoc) end def create_hash_from_nyt_doc(nytDoc) doc = {} #strings doc["id"] = nytDoc.getGuid() doc["alternativeURL"] = nytDoc.getAlternateURL() doc["url"] = nytDoc.getUrl() doc["articleAbstract"] = nytDoc.getArticleAbstract() doc["authorBiography"] = nytDoc.getAuthorBiography() doc["banner"] = nytDoc.getBanner() doc["body"] = nytDoc.getBody() doc["byline"] = nytDoc.getByline() doc["columnName"] = nytDoc.getColumnName() doc["correctionText"] = nytDoc.getCorrectionText() doc["credit"] = nytDoc.getCredit() doc["dateline"] = nytDoc.getDateline() doc["dayOfWeek"] = nytDoc.getDayOfWeek() doc["featurePage"] = nytDoc.getFeaturePage() doc["headline"] = nytDoc.getHeadline() doc["kicker"] = nytDoc.getKicker() doc["leadParagraph"] = nytDoc.getLeadParagraph() doc["newsDesk"] = nytDoc.getNewsDesk() doc["normalizedByline"] = nytDoc.getNormalizedByline() doc["onlineHeadline"] = nytDoc.getOnlineHeadline() doc["onlineLeadParagraph"] = nytDoc.getOnlineLeadParagraph() doc["onlineSection"] = nytDoc.getOnlineSection() doc["section"] = nytDoc.getSection() doc["seriesName"] = nytDoc.getSeriesName() doc["slug"] = nytDoc.getSlug() doc["sourceFile"] = nytDoc.getSourceFile().toString() #numerics doc["columnNumber"] = nytDoc.getColumnNumber() doc["guid"] = nytDoc.getGuid() doc["page"] = nytDoc.getPage() doc["publicationDayOfMonth"] = nytDoc.getPublicationDayOfMonth() doc["publicationMonth"] = nytDoc.getPublicationMonth() doc["publicationYear"] = nytDoc.getPublicationYear() doc["wordCount"] = nytDoc.getWordCount() #dates doc["publicationDate"]= Date.parse(nytDoc.getPublicationDate().to_s).strftime("%Y-%m-%dT00:00:00Z") doc["correctDate"] = Date.parse(nytDoc.getCorrectionDate().to_s).strftime("%Y-%m-%dT00:00:00Z") rescue nil #mulitvalues doc["biographicalCategories"] = nytDoc.getBiographicalCategories().to_a doc["descriptors"] = nytDoc.getDescriptors().to_a doc["generalOnlineDescriptors"] = nytDoc.getGeneralOnlineDescriptors().to_a doc["locations"] = nytDoc.getLocations().to_a doc["names"] = nytDoc.getNames().to_a doc["onlineDescriptors"] = nytDoc.getOnlineDescriptors().to_a doc["onlineLocations"] = nytDoc.getOnlineLocations().to_a doc["onlineOrganizations"] = nytDoc.getOnlineOrganizations().to_a doc["onlinePeople"] = nytDoc.getOnlinePeople().to_a doc["onlineTitles"] = nytDoc.getOnlineTitles().to_a doc["organizations"] = nytDoc.getOrganizations().to_a doc["people"] = nytDoc.getPeople().to_a doc["taxonomicClassifiers"] = nytDoc.getTaxonomicClassifiers().to_a doc["titles"] = nytDoc.getTitles().to_a doc["typesOfMaterial"] = nytDoc.getTypesOfMaterial().to_a doc end puts "Indexing NYTimes Corpus" puts "-----" if(ARGV.size != 2) puts " This script will untar the xml files and index them with Solr" puts " Specify a path the nytimes corpus data folder and solr home" puts "jruby nytimes_solr_indexer.rb \"path/to/nytimes data/data\" \"/path/to/solr/home\"" puts " You can also post a solr server by specifying a solr server in the second parameter" puts "jruby nytimes_solr_indexer.rb \"path/to/nytimes data/data\" \"http://localhost:8983/solr\"" else dir = ARGV[0] #"/Users/wheels/data/tmp_data" server_or_solr_dir = ARGV[1] #"/Users/wheels/src/java/nytimes/solr/solr" or "http://localhost:8983/solr" opts= {} if server_or_solr_dir.starts_with?("http://") opts[:solr_server_url] = server_or_solr_dir else opts[:solr_home] = server_or_solr_dir end puts "Processing #{ARGV[0]}" untar_dir(dir) index_dir(dir, opts) puts "Done!" end
4372e2c0d0e0888f25c0abf075755316c1f56a30
[ "Ruby" ]
1
Ruby
n3wtn9/nytimes-solr-indexer
89bbc12f09d6361a3d36460b310c5e715a5b9057
bd5e76de13a9e47e245df672078ac93ab513c0c0
refs/heads/master
<repo_name>rachelktyjohnson/thevarious_landing<file_sep>/README.md # The Various - Landing The temporary landing page for The Various Directory <file_sep>/index.php <?php $formMessage = "Let me know when The Various Directory launches!"; $email = filter_input(INPUT_POST,"your_email",FILTER_VALIDATE_EMAIL); if ($type==null){ $type="user"; } else { $type = filter_input(INPUT_POST,"type"); } if (!empty($_POST)){ //if something has been posted require('includes/connection.php'); try{ $sql = "INSERT INTO prelaunch_users(email,type) VALUES(?,?)"; $results = $db->prepare($sql); $results->bindParam(1, $email, PDO::PARAM_STR); $results->bindParam(2, $type, PDO::PARAM_STR); $results->execute(); $formMessage = "Thanks for registering your interest! We'll let you know as soon as we're up and running!"; } catch (Exception $e) { echo $e->getMessage(); } } ?> <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>The Various - Coming Soon</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32" /> <link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16" /> <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,600,700&display=swap" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="css/styles.css"> </head> <body> <main> <img class="main-image" src="img/image.png"/> <div class="email-signup"> <h2><?= $formMessage?></h2> <?php if (empty($_POST)){ ?> <form method="POST"> <div class="form-group checkbox-group"> <input type="checkbox" class="largerCheckbox" id="business" name="type" value="business"> <label for="business">I am a business interested in being listed on The Various</label> </div> <div class="form-group form-group-email"> <label for="your_email">Email</label> <input type="email" name="your_email" id="your_email" required/> <input class="submit-button" type="submit" value="GO"> </div> </form> <?php } ?> </div> <div class="social-media"> <a href="https://www.facebook.com/thevarious.com.au/"><img src="img/facebook.svg"/></a> <a href="https://www.instagram.com/thevarious.com.au/"><img src="img/instagram.svg"/></a> </div> </main> </body> </html>
bb7f4fa5b8166a0b86e4dc0cb4112501544dcb76
[ "Markdown", "PHP" ]
2
Markdown
rachelktyjohnson/thevarious_landing
302c97b0f43fedc7fb7aa5ec80ca0cff8409a073
0a08e4512ebb5feccaf0d7700f7ede2cb9c1f76b
refs/heads/master
<repo_name>DiegoKazadi/treinamentospring<file_sep>/src/test/java/com/treinamento/applicacao/ApplicacaoApplicationTests.java package com.treinamento.applicacao; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class ApplicacaoApplicationTests { @Test void contextLoads() { } } <file_sep>/src/main/java/com/treinamento/applicacao/repositories/CategoriaRepository.java /** * */ package com.treinamento.applicacao.repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.treinamento.applicacao.domain.Categoria; /** * @author diego.kazadi * */ @Repository public interface CategoriaRepository extends JpaRepository<Categoria, Integer>{ }
419503d12187183f2b2a0613c76a7215ab230a9f
[ "Java" ]
2
Java
DiegoKazadi/treinamentospring
e7520fa736cd5289a41171c992fccf7890bb93eb
e236b585a50bb2ffe914db62cd9c5858393364db
refs/heads/master
<repo_name>cmilfont/pwa2<file_sep>/src/api/domain/fetch-entities.js import { fromJS, List } from 'immutable'; function getCoords(item) { const { lat, lon } = (item.type === 'experience')? item.destination.location: item.location; return [lat, lon]; } export default (state, action) => { const isArray = action.payload.length; const coords = isArray ? action.payload.map(item => getCoords(item)): [getCoords(action.payload)]; const newState = state.setIn(['map', 'bounds'], List(coords)) .setIn(['entities', action.meta.entity], fromJS(action.payload)) return isArray ? newState: newState.setIn(['map', 'center'], fromJS(getCoords(action.payload))) .setIn(['map', 'zoom'], 16); }<file_sep>/src/api/sagas/index.js import { all, fork } from 'redux-saga/effects'; import watchFetchEntities from './fetch-entities'; function* sagas() { yield all([ fork(watchFetchEntities), ]); } export default sagas;<file_sep>/src/components/places/place/place.js import React from 'react'; import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; const Place = ({ highlights, content, name, slug, cover: { file: { url } }, destination: { name: destinationName } }) => { const highlightedContent = highlights.reduce((resultado, text) => { return resultado.replace(text, `<span class="high">${text}</span>`); }, content); return ( <li> <div> <img src={url} /> <div className="name"> <Link to={`/places/${slug}`}> {name} </Link> </div> <div>{destinationName}</div> <div dangerouslySetInnerHTML={{ __html: highlightedContent }} /> </div> </li> ) }; export default Place; <file_sep>/src/components/map/index.js import React from 'react'; import { connect } from 'react-redux'; import { Map, LayerGroup } from 'react-leaflet'; import { GoogleApiLoader, GoogleMutant } from 'react-leaflet-googlemutant'; import Marker from './markers/marker'; class BeerswarmMap extends React.Component { render() { const {bounds, center, zoom} = this.props; const options = { maxZoom: 18, minZoom: 0, zoomControl: false, doubleClickZoom: true, keyboard: false, }; const viewport = { center, zoom }; if (bounds.length) { options.bounds = bounds; } const places = bounds.map(item => ( <Marker coords={item} /> )); return ( <div> <GoogleApiLoader apiKey="<KEY>"> <Map attributionControl={false} viewport={viewport} {...options} > <GoogleMutant type="roadmap" /> <LayerGroup> {places} </LayerGroup> </Map> </GoogleApiLoader> Mapa </div> ) } } export default connect( state => { const {bounds, center, zoom } = state.get('map').toJS(); return { bounds, center, zoom } } )(BeerswarmMap);<file_sep>/src/components/routes.js import Places from './places'; import Place from './places/place/index.js'; import Experiences from './experiences'; export default [ { path: '/', component: Places, exact: true, }, { path: '/places', component: Places, exact: true, }, { path: '/places/:placeSlug?', component: Place, }, { path: '/experiences', component: Experiences, } ];<file_sep>/src/components/theme/index.js import React from 'react'; import Places from '../places'; import { renderRoutes } from 'react-router-config'; import { Link } from 'react-router-dom'; import routes from '../routes'; import Map from '../map'; export default () => ( <div> <div className="toolbar"> <Link to="/experiences"> Experiences </Link> <Link to="/places"> Places </Link> <Link to="/destinations"> Desetinations </Link> </div> <Map /> <div className="content"> {renderRoutes(routes)} </div> </div> );<file_sep>/src/api/sagas/fetch-entities.js import pluralize from 'pluralize'; import { takeLatest, put } from 'redux-saga/effects'; import { FETCH_ENTITY_ERROR, FETCH_ENTITY_SUCCESS } from '../constants'; import { LOCATION_CHANGE } from 'react-router-redux'; import axios from 'axios'; function* verify(action) { try { const [, entityUrl, slug] = action.payload.pathname.split('/'); const entity = slug ? pluralize.singular(entityUrl) : entityUrl; if (entity) { const res = yield axios(`/api/${action.payload.pathname}`); const payload = slug ? res.data[0] : res.data; yield put({ type: FETCH_ENTITY_SUCCESS, payload, meta: { entity } }) } } catch (error) { put({ type: FETCH_ENTITY_ERROR, payload: error.message, }) } } export default function* watch() { yield takeLatest(LOCATION_CHANGE, verify); }<file_sep>/src/components/highlight/index.js import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; class Highlight extends React.Component { static childContextTypes = { highlight: PropTypes.func, highlights: PropTypes.array, } getChildContext() { return { highlight: this.highlight, highlights: this.props.highlights, } } componentDidMount() { window.onmouseup = this.highlight; } highlight = () => { const selection = window.getSelection(); this.props.addHighlight(selection.toString()); } render() { return this.props.children; } } export default connect( state => { return ({ highlights: state.get('highlights').toJS() }) }, dispatch => ({ addHighlight: payload => dispatch({ type: 'SELECT_TEXT', payload, }) }) )(Highlight);
63810d2032718a9b22fc57d0361ef8116511b24d
[ "JavaScript" ]
8
JavaScript
cmilfont/pwa2
c353ff5dd0c3d9792f7c3fb48d96906143d42cf6
0e83ebcb515fbb8fb0e89bf2fc06d62c87e36802
refs/heads/master
<repo_name>fengyalu/Progress_Bar_Solid<file_sep>/app/src/main/java/cn/com/fyl/learn/progress_bar_solid/MyCircleView.java package cn.com.fyl.learn.progress_bar_solid; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; /** * Created by Administrator on 2019/9/16 0016. */ public class MyCircleView extends View { private Paint paint; private Paint rectPaint; private Paint txtPaint; public int progress; public float getProgress() { return progress; } public void setProgress(int progress) { this.progress = progress; //重新绘制 invalidate(); } public MyCircleView(Context context) { this(context, null); } public MyCircleView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public MyCircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { paint = new Paint(); paint.setStyle(Paint.Style.STROKE); int color = Color.parseColor("#FF14A903"); paint.setColor(color); //抗锯齿 paint.setAntiAlias(true); //设置线宽 paint.setStrokeWidth(2); rectPaint = new Paint(); rectPaint.setStyle(Paint.Style.FILL); int rectColor = Color.parseColor("#FF14A903"); rectPaint.setColor(rectColor); //抗锯齿 rectPaint.setAntiAlias(true); //设置线宽 rectPaint.setStrokeWidth(1); txtPaint = new Paint(); txtPaint.setStyle(Paint.Style.FILL); txtPaint.setTextAlign(Paint.Align.CENTER); txtPaint.setTextSize(100); int txtColor = Color.parseColor("#ff0000"); txtPaint.setColor(txtColor); //抗锯齿 txtPaint.setAntiAlias(true); //设置线宽 txtPaint.setStrokeWidth(5); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //设置宽高,默认200dp int defaultSize = dp2px(getContext(), 200); setMeasuredDimension(measureWidth(widthMeasureSpec, defaultSize), measureHeight(heightMeasureSpec, defaultSize)); } private int dp2px(Context context, int dpVal) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, context.getResources().getDisplayMetrics()); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //算半径 int width = getWidth() - getPaddingLeft() - getPaddingRight(); int height = getHeight() - getPaddingTop() - getPaddingBottom(); //取半径为长和宽中最小的那个的(1/2) int radius = Math.min(width, height) / 2; //计算圆心(横坐标) int cx = getPaddingLeft() + width / 2; //计算圆心(纵坐标) int cy = getPaddingTop() + height / 2; drawCircle(canvas, cx, cy, radius,paint); drawRectCircle(canvas, cx, cy, radius,rectPaint); drawCenterText(canvas, cx, cy, txtPaint); } /** * 画圆 * @param canvas * @param cx * @param cy * @param radius * @param paint */ private void drawCircle(Canvas canvas, int cx, int cy, int radius, Paint paint) { canvas.drawCircle(cx, cy, radius, paint); } /** * 画扇形 * @param canvas * @param cx * @param cy * @param radius * @param paint */ private void drawRectCircle(Canvas canvas, int cx, int cy, int radius, Paint paint) { RectF rectf = new RectF(cx-radius, cy-radius, cx + radius, cy + radius); canvas.drawArc(rectf, 0, 360 * progress / 100, true, paint); } /** * 画文字 * * @param canvas * @param cx * @param cy * @param txtPaint */ private void drawCenterText(Canvas canvas, int cx, int cy, Paint txtPaint) { //计算baseline //距离 = 文字高度的一半 - 基线到文字底部的距离(也就是bottom) //= (fontMetrics.bottom - fontMetrics.top)/2 - fontMetrics.bottom Paint.FontMetrics fontMetrics = txtPaint.getFontMetrics(); float distance = (fontMetrics.bottom - fontMetrics.top) / 2 - fontMetrics.bottom; float baseline = cy + distance; canvas.drawText(progress + "%", cx, baseline, txtPaint); } /** * 测量宽 * 1.精确模式(MeasureSpec.EXACTLY) * <p> * 在这种模式下,尺寸的值是多少,那么这个组件的长或宽就是多少。 * <p> * 2.最大模式(MeasureSpec.AT_MOST) * <p> * 这个也就是父组件,能够给出的最大的空间,当前组件的长或宽最大只能为这么大,当然也可以比这个小。 * <p> * 3.未指定模式(MeasureSpec.UNSPECIFIED) * * @param measureSpec * @param defaultSize * @return */ private int measureWidth(int measureSpec, int defaultSize) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(defaultSize); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { result = defaultSize + getPaddingLeft() + getPaddingRight(); if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } result = Math.max(result, getSuggestedMinimumWidth()); return result; } /** * 测量高 * 1.精确模式(MeasureSpec.EXACTLY) * <p> * 在这种模式下,尺寸的值是多少,那么这个组件的长或宽就是多少。 * <p> * 2.最大模式(MeasureSpec.AT_MOST) * <p> * 这个也就是父组件,能够给出的最大的空间,当前组件的长或宽最大只能为这么大,当然也可以比这个小。 * <p> * 3.未指定模式(MeasureSpec.UNSPECIFIED) * * @param measureSpec * @param defaultSize * @return */ private int measureHeight(int measureSpec, int defaultSize) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(defaultSize); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { result = defaultSize + getPaddingTop() + getPaddingBottom(); if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } result = Math.max(result, getSuggestedMinimumHeight()); return result; } }
758987e597ffc1875327c93a157fb36d113606f0
[ "Java" ]
1
Java
fengyalu/Progress_Bar_Solid
e392b689b4a0fdd6f87e015e616f5be4c8fbc01f
486978560b16bfac606d9fafceb9b51da97f5cf7
refs/heads/master
<repo_name>xSaintBurrito/GymApp<file_sep>/userDBAndAuthentication/src/main/java/com/gymapp/gymapp/UserBO.java package com.gymapp.gymapp; import com.gymapp.gymapp.entity.FitnessClass; import com.gymapp.gymapp.entity.User; import com.gymapp.gymapp.input.UserAddInput; import java.util.Set; public interface UserBO { boolean setRole(long id, Role role); boolean changePassword(long userId, String password); boolean isMatchingPassword(long userId, String password); User addUser(UserAddInput userAddInput); boolean deleteUser(long userId); boolean changeUsername(long userId, String newUsername); boolean addFitnessClass(long userId, FitnessClass fitnessClass); Role getUserRole(long userId); } <file_sep>/userDBAndAuthentication/src/main/java/com/gymapp/gymapp/input/UserAddInput.java package com.gymapp.gymapp.input; import com.gymapp.gymapp.Role; import com.gymapp.gymapp.entity.FitnessClass; import lombok.Builder; import lombok.Getter; import java.util.Collection; import java.util.List; @Getter @Builder public class UserAddInput { private final String username; private final String password; private final Role role; private final List<FitnessClass> fitnessClasses; } <file_sep>/userDBAndAuthentication/src/test/java/com/gymapp/gymapp/bo/UserBOImplTest.java package com.gymapp.gymapp.bo; import com.gymapp.gymapp.Role; import com.gymapp.gymapp.bo.UserBOImpl; import com.gymapp.gymapp.entity.User; import com.gymapp.gymapp.factory.UserFactory; import com.gymapp.gymapp.input.UserAddInput; import com.gymapp.gymapp.repository.UserRepository; import com.gymapp.gymapp.validator.PasswordValidator; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.security.crypto.password.PasswordEncoder; import java.time.LocalDateTime; import java.util.*; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class UserBOImplTest { private UserBOImpl userBOImpl; @Mock private UserRepository userRepository; @Mock private UserFactory userFactory; @Mock private PasswordEncoder passwordEncoder; @Mock private PasswordValidator passwordValidator; private long id; private String username; private String password; private Role role; @Before public void setUp() throws Exception { this.userBOImpl = new UserBOImpl(userRepository, userFactory, passwordEncoder, passwordValidator); this.id = 1L; this.username = "user"; this.password = "<PASSWORD>"; this.role = Role.MANAGER; } @After public void tearDown() throws Exception { this.userBOImpl = null; } @Test public void shouldAddUserWithoutRoles() { //given User user = mock(User.class); UserAddInput userAddInput = UserAddInput.builder() .username(username) .password(<PASSWORD>) .role(Role.MANAGER) .build(); when(userFactory.create(userAddInput)) .thenReturn(user); when(userRepository.save(user)) .thenReturn(user); //when User result = userBOImpl.addUser(userAddInput); //then verify(userFactory) .create(userAddInput); verify(userRepository) .save(user); assertThat(result) .isNotNull(); } @Test public void shouldAddUserWithRoles() { //given User user = mock(User.class); UserAddInput userAddInput = UserAddInput.builder() .username(username) .password(<PASSWORD>) .role(role) .build(); when(userFactory.create(userAddInput)) .thenReturn(user); when(userRepository.save(user)) .thenReturn(user); //when User result = userBOImpl.addUser(userAddInput); //then verify(userFactory) .create(userAddInput); verify(userRepository) .save(user); assertThat(result) .isNotNull(); } @Test public void shouldGrantRoleToUser() { //given Role role = Role.MANAGER; User user = mock(User.class); when(userRepository.getOne(id)) .thenReturn(user); //when userBOImpl.setRole(id, role); //then verify(userRepository) .getOne(id); verify(user) .setRole(role); } @Test public void shouldDelete() { //given //when userBOImpl.deleteUser(1L); //then verify(userRepository) .deleteById(1L); } @Test public void shouldChangePassword() { //given String userName = "user"; String newPassword = "<PASSWORD>"; String newHash = "<PASSWORD>"; User user = mock(User.class); when(userRepository.getOne(id)) .thenReturn(user); when(passwordEncoder.encode(newPassword)) .thenReturn(newHash); //when userBOImpl.changePassword(id, newPassword); //then verify(user) .updatePassword(newHash); } } <file_sep>/userDBAndAuthentication/src/main/java/com/gymapp/gymapp/entity/FitnessClass.java package com.gymapp.gymapp.entity; import com.sun.istack.internal.NotNull; import lombok.Getter; import javax.persistence.*; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; @Entity @Getter public class FitnessClass { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull private long maxPlaces; @NotNull private LocalDateTime date; private long trainerId; //@Transient @ManyToMany(mappedBy = "fitnessClasses") private List<User> signedUsers; protected FitnessClass(){ } public FitnessClass(final long maxPlaces, final LocalDateTime date, final long trainerId) { this.maxPlaces = maxPlaces; this.date = date; this.trainerId = trainerId; this.signedUsers = new ArrayList<>(); } public LocalDateTime checkDate(){ return date; } public boolean checkForPlaces(){ return signedUsers.size() < maxPlaces; } public void signUp(final User user){ signedUsers.add(user); } public void signOff(final User user){ signedUsers.remove(user); } public List<User> getUsers(){ return signedUsers; } } <file_sep>/userDBAndAuthentication/src/test/java/com/gymapp/gymapp/bo/FitnessClassBOImplTest.java package com.gymapp.gymapp.bo; import com.gymapp.gymapp.entity.FitnessClass; import com.gymapp.gymapp.entity.User; import com.gymapp.gymapp.repository.FitnessClassRepository; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.time.LocalDateTime; import java.util.Collections; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class FitnessClassBOImplTest { private FitnessClassBOImpl fitnessClassBOImpl; @Mock private FitnessClassRepository fitnessClassRepository; private Long id; private long maxPlaces; private LocalDateTime date; private long trainerId; private List<User> signedUsers; private String username; private String password; @Before public void setUp() throws Exception { this.fitnessClassBOImpl = new FitnessClassBOImpl(fitnessClassRepository); this.id = 1L; this.username = "user"; this.password = "<PASSWORD>"; this.maxPlaces = 100; this.date = LocalDateTime.of(2010, 10, 10, 10, 10); this.trainerId = 1L; } @After public void tearDown() throws Exception { this.fitnessClassBOImpl = null; } @Test public void shouldAddFitnessClass() { //given FitnessClass fitnessClass = mock(FitnessClass.class); when(fitnessClassRepository.save(fitnessClass)) .thenReturn(fitnessClass); //when boolean result = fitnessClassBOImpl.add(fitnessClass); //then assertThat(result) .isTrue(); } @Test public void shouldRemoveFitnessClass() { //given FitnessClass fitnessClass = new FitnessClass(maxPlaces, date, trainerId); fitnessClassBOImpl.add(fitnessClass); //when boolean result = fitnessClassBOImpl.remove(fitnessClass); //then assertThat(result) .isTrue(); } } <file_sep>/userDBAndAuthentication/src/main/resources/application.properties spring.jpa.hibernate.ddl=org.hibernate.dialect.MySQLInnoDBDialect spring.jpa.hibernate.ddl-auto=update spring.datasource.url=jdbc:mysql://localhost:3306/gymapp?autoReconnect=true&useSSL=false spring.datasource.username=gymapp spring.datasource.password=<PASSWORD> <file_sep>/userDBAndAuthentication/src/main/java/com/gymapp/gymapp/Constants.java package com.gymapp.gymapp; public final class Constants { public static final int MIN_PASSWORD_LENGTH = 5; private Constants() { } } <file_sep>/userDBAndAuthentication/src/main/java/com/gymapp/gymapp/bo/FitnessClassBOImpl.java package com.gymapp.gymapp.bo; import com.gymapp.gymapp.FitnessClassBO; import com.gymapp.gymapp.entity.FitnessClass; import com.gymapp.gymapp.entity.User; import com.gymapp.gymapp.repository.FitnessClassRepository; import org.springframework.stereotype.Service; import javax.transaction.Transactional; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @Service @Transactional public class FitnessClassBOImpl implements FitnessClassBO { private final FitnessClassRepository fitnessClassRepository; FitnessClassBOImpl(final FitnessClassRepository fitnessClassRepository) { this.fitnessClassRepository = fitnessClassRepository; } @Override public boolean isThereFitnessClassAtDate(LocalDateTime date) { List<FitnessClass> fitnessClasses = fitnessClassRepository.findAll().stream() .filter(fitnessClass -> date.isEqual(fitnessClass.checkDate())) .collect(Collectors.toList()); return fitnessClasses.size() > 0; } @Override public List<User> whichUsersHaveClassesAtDate(LocalDateTime date) { List<FitnessClass> fitnessClasses = fitnessClassRepository.findAll().stream() .filter(fitnessClass -> date.isEqual(fitnessClass.checkDate())) .collect(Collectors.toList()); List<User> activeUsers = new ArrayList<>(); fitnessClasses.forEach(fitnessClass -> activeUsers.addAll(fitnessClass.getUsers())); return activeUsers; } @Override public boolean add(FitnessClass fitnessClass) { fitnessClassRepository.save(fitnessClass); return true; } @Override public boolean remove(FitnessClass fitnessClass) { fitnessClassRepository.delete(fitnessClass); return true; } } <file_sep>/worker/src/main/java/worker/Date.java package worker; /** * Defines the concept of Date. * @author <NAME> & <NAME> * */ public class Date { /** * Holds the date in the dd/mm/aaaa format as a String. */ private String date; /** * The Strings day, month and year hold the 3 elements of a date separately. */ private String day, month, year; /** * Contructor for a Date. * @param day * @param month * @param year */ public Date(String day, String month, String year) { this.date = day + "/" + month + "/" + year; this.day = day; this.month = month; this.year = year; } /** * Returns the day of the Date. * @return day */ public String getDay() { return day; } /** * Returns the month of the Date. * @return month */ public String getMonth() { return month; } /** * Returns the year of the Date. * @return year */ public String getYear() { return year; } /** * Returns the full date in the predefined format. * @return date */ public String toString() { return date; } } <file_sep>/worker/src/main/java/worker/ReportManager.java package worker; import java.util.ArrayList; /** * Class that manages all the Reports. * @author <NAME> & <NAME> * */ public class ReportManager { private static ArrayList<Report> reports = new ArrayList<>(); private static ReportManager rm = null; /** * Private ReportManager() constructor so that we can apply the Singleton pattern. * This is because we only need one instance of the ReportManager. */ private ReportManager() {} /** * Implements the Singleton pattern with lazy initialization. * @return The instance of the ReportManager. If it has not been created yet, this method calls the constructor and returns the new instance. */ public ReportManager getReportManagerInstance() { if (rm.equals(null)) { return new ReportManager(); } else return rm; } /** * Returns all the reports the worker has access to. * @return All reports this worker can access. */ public ArrayList<Report> getAllGymsReports() { return reports; } /** * Returns reports of work-outs filtered with some specifications. * Filters by gym, date, client and activity. * * Usage: search only reports from gymX -> getFilteredReports(gymX,null, null, null) * search only reports from a specific date and also a specific client -> getFilteredReports(null, date, client, null) * * @return All the reports that correspond to the filters passed as parameters. */ public ArrayList<Report> getFilteredReports (Gym gym, Date date, Client client, Activity activity) { ArrayList<Report> filtered = reports; for (Report r : reports) { if ((!gym.equals(null) && !gym.equals(r.getGym())) || (!date.equals(null) && !date.equals(r.getDate())) || (!client.equals(null) && !client.equals(r.getClient())) || (!activity.equals(null) && !activity.equals(r.getActivity()))) filtered.remove(r); } return filtered; } /** * Changes the importance of the Reports. * This is completed by removing or adding to the importantReports list of the Worker. * @param report */ public void changeImportanceStatus(Worker w, Report r) { w.changeImportantStatus(r); } /** * Makes the worker follow or unfollow a specific Report. * This is completed by removing or adding to the reportsFollowed list of the Worker */ public void changeFollowStatus(Worker w, Report r) { w.changeFollowStatus(r); } }
0de2726d1667bdff8deb11ae3746ecba9e6856bb
[ "Java", "INI" ]
10
Java
xSaintBurrito/GymApp
0f4a04b55379600906da6d93227c2645edcb6b40
4fd163cbfddc6e1fcb4a0f487d7c3337807d2c88
refs/heads/master
<file_sep>package com.mygdx.game; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Vector2; public class WorldRenderer { }
25f67fb4e133a1372d02113dc7515672c51681bb
[ "Java" ]
1
Java
nongharunana/pacman
11fa5f2b6e46ddb1ad50513a82bccd9a05e04acd
e8a3db82b62763538eb9f43b9c389f7349fcd284
refs/heads/master
<file_sep>import React,{useState,useEffect} from 'react'; import { Auth, Hub } from "aws-amplify"; export const IdentityContext = React.createContext({}); const IdentityProvider = props => { const [user, setUser] = useState(null) useEffect(() => { Hub.listen("auth", ({ payload: { event } }) => { switch (event) { case "signIn": case "cognitoHostedUI": getUser().then(userData => setUser(userData)) break case "signOut": setUser(null) break case "signIn_failure": case "cognitoHostedUI_failure": break default: console.log('something went wrong') } }) getUser().then(userData => { setUser(userData) console.log("Signed In:", userData) }) }, []) function getUser() { return Auth.currentAuthenticatedUser() .then(userData => userData) .catch(() => console.log("Not signed in")) } return ( <IdentityContext.Provider value={{ user }}> {props.children} </IdentityContext.Provider> ) }; export default IdentityProvider;<file_sep>import React, { useContext } from "react"; import { Flex, NavLink } from "theme-ui"; import { Link } from "gatsby"; import { IdentityContext } from "../../Identity-Context"; import { Auth} from "aws-amplify"; const Navbar = () => { const { user } = useContext(IdentityContext); return ( <Flex as="nav"> <NavLink as={Link} to="/" p={2}> Home </NavLink> {user && <NavLink as={Link} to="/app" p={2}>Dashboard</NavLink>} {user && ( <NavLink sx={{ cursor: 'pointer' }} p={2} onClick={() => Auth.signOut()}> Logout {user.signInUserSession.idToken.payload.given_name} </NavLink> )} </Flex> ); }; export default Navbar; <file_sep>import * as cdk from '@aws-cdk/core'; import * as lambda from '@aws-cdk/aws-lambda'; import * as appsync from '@aws-cdk/aws-appsync'; import * as events from '@aws-cdk/aws-events'; import * as eventsTargets from '@aws-cdk/aws-events-targets'; import * as dynamoDB from '@aws-cdk/aws-dynamodb'; import * as cognito from '@aws-cdk/aws-cognito'; import * as cloudfront from "@aws-cdk/aws-cloudfront"; import * as origins from "@aws-cdk/aws-cloudfront-origins"; import * as s3 from "@aws-cdk/aws-s3"; import * as s3deploy from "@aws-cdk/aws-s3-deployment"; import { requestTemplate, responseTemplate, EVENT_SOURCE } from '../utils/appsync-request-response'; export class BackendStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); //Here we define our Authentication via google const userPool = new cognito.UserPool(this, "TodosGoogleUserPool", { selfSignUpEnabled: true, accountRecovery: cognito.AccountRecovery.EMAIL_ONLY, userVerification: { emailStyle: cognito.VerificationEmailStyle.CODE }, autoVerify: { email: true }, standardAttributes: { email: { required: true, mutable: true, }, }, }); const provider = new cognito.UserPoolIdentityProviderGoogle(this, "googleProvider", { userPool: userPool, clientId: "946189751283-qar9hmgh34n2k95g99bj5t21q92u612u.apps.googleusercontent.com", clientSecret: "<KEY>", // Google Client Secret attributeMapping: { email: cognito.ProviderAttribute.GOOGLE_EMAIL, givenName: cognito.ProviderAttribute.GOOGLE_GIVEN_NAME, phoneNumber: cognito.ProviderAttribute.GOOGLE_PHONE_NUMBERS, }, scopes: ["profile", "email", "openid"], } ); userPool.registerIdentityProvider(provider); const userPoolClient = new cognito.UserPoolClient(this, "todoamplifyClient", { userPool, oAuth: { callbackUrls: ["https://dd7ec0n7fuvn7.cloudfront.net/"], // This is what user is allowed to be redirected to with the code upon signin. this can be a list of urls. logoutUrls: ["https://dd7ec0n7fuvn7.cloudfront.net/"], // This is what user is allowed to be redirected to after signout. this can be a list of urls. }, }); const domain = userPool.addDomain("Todosdomain", { cognitoDomain: { domainPrefix: "muhib-todos", // SET YOUR OWN Domain PREFIX HERE }, }); new cdk.CfnOutput(this, "aws_user_pools_web_client_id", { value: userPoolClient.userPoolClientId, }); new cdk.CfnOutput(this, "aws_project_region", { value: this.region, }); new cdk.CfnOutput(this, "aws_user_pools_id", { value: userPool.userPoolId, }); new cdk.CfnOutput(this, "domain", { value: domain.domainName, }); // Appsync API for todo app schema const Todoapi = new appsync.GraphqlApi(this, "ApiForTodo", { name: "appsyncEventbridgeAPITodo", schema: appsync.Schema.fromAsset("utils/schema.gql"), authorizationConfig: { defaultAuthorization: { authorizationType: appsync.AuthorizationType.API_KEY, }, }, xrayEnabled: true, }); // Prints out the AppSync GraphQL endpoint to the terminal new cdk.CfnOutput(this, "todoURL", { value: Todoapi.graphqlUrl }); // Prints out the AppSync GraphQL API key to the terminal new cdk.CfnOutput(this, "TodoApiKey", { value: Todoapi.apiKey || '' }); // Prints out the AppSync Api to the terminal new cdk.CfnOutput(this, "TodoAPI-ID", { value: Todoapi.apiId || '' }); // Create new DynamoDB Table for Todos const TodoAppTable = new dynamoDB.Table(this, 'TodAppTable', { tableName: "TodoTable", partitionKey: { name: 'id', type: dynamoDB.AttributeType.STRING, }, }); // DynamoDB as a Datasource for the Graphql API. const TodoAppDS = Todoapi.addDynamoDbDataSource('TodoAppDataSource', TodoAppTable); ////////////////////////////// Creating Lambda handler ////////////////////// const dynamoHandlerLambda = new lambda.Function(this, 'Dynamo_Handler', { code: lambda.Code.fromAsset('lambda'), runtime: lambda.Runtime.NODEJS_12_X, handler: 'dynamoHandler.handler', environment: { DYNAMO_TABLE_NAME: TodoAppTable.tableName, }, }); // Giving Table access to dynamoHandlerLambda TodoAppTable.grantReadWriteData(dynamoHandlerLambda); TodoAppDS.createResolver({ typeName: "Query", fieldName: 'getTodos', requestMappingTemplate: appsync.MappingTemplate.dynamoDbScanTable(), responseMappingTemplate: appsync.MappingTemplate.dynamoDbResultList(), }); // HTTP as Datasource for the Graphql API const httpEventTriggerDS = Todoapi.addHttpDataSource( "eventTriggerDS", "https://events." + this.region + ".amazonaws.com/", // This is the ENDPOINT for eventbridge. { name: "httpDsWithEventBridge", description: "From Appsync to Eventbridge", authorizationConfig: { signingRegion: this.region, signingServiceName: "events", }, } ); /* Mutation */ const mutations = ["addTodo", "deleteTodo",] mutations.forEach((mut) => { let details = `\\\"todoId\\\": \\\"$ctx.args.todoId\\\"`; if (mut === 'addTodo') { details = `\\\"title\\\":\\\"$ctx.args.todo.title\\\" , \\\"user\\\":\\\"$ctx.args.todo.user\\\"` } else if (mut === "deleteTodo") { details = `\\\"todoId\\\":\\\"$ctx.args.todoId\\\"` } httpEventTriggerDS.createResolver({ typeName: "Mutation", fieldName: mut, requestMappingTemplate: appsync.MappingTemplate.fromString(requestTemplate(details, mut)), responseMappingTemplate: appsync.MappingTemplate.fromString(responseTemplate()), }); }); events.EventBus.grantPutEvents(httpEventTriggerDS); ////////// Creating rule to invoke step function on event /////////////////////// new events.Rule(this, "eventConsumerRule", { eventPattern: { source: [EVENT_SOURCE], }, targets: [new eventsTargets.LambdaFunction(dynamoHandlerLambda)] }); //here I define s3 bucket const todosBucket = new s3.Bucket(this, "todosBucket", { versioned: true, }); todosBucket.grantPublicAccess(); // website visible to all. // create a CDN to deploy your website const distribution = new cloudfront.Distribution(this, "TodosDistribution", { defaultBehavior: { origin: new origins.S3Origin(todosBucket), }, defaultRootObject: "index.html", }); // Prints out the web endpoint to the terminal new cdk.CfnOutput(this, "DistributionDomainName", { value: distribution.domainName, }); // housekeeping for uploading the data in bucket new s3deploy.BucketDeployment(this, "DeployTodoApp", { sources: [s3deploy.Source.asset("../frontend/public")], destinationBucket: todosBucket, distribution, distributionPaths: ["/*"], }); } }<file_sep>import { EventBridgeEvent, Context } from 'aws-lambda'; export declare const handler: (event: EventBridgeEvent<string, any>, context: Context) => Promise<void>; <file_sep>import React, { useState, useRef, useEffect, useContext } from "react"; import { Router } from "@reach/router"; import { addTodo } from "../graphql/mutations"; import { getTodos } from "../graphql/queries"; import { deleteTodo } from "../graphql/mutations"; import { API } from "aws-amplify"; import { IdentityContext } from "../../Identity-Context"; import Navbar from "../components/Navbar"; import { Link } from 'gatsby'; import { Button, Heading, Input, Label, NavLink, Text } from "theme-ui"; const Dash = () => { const { user } = useContext(IdentityContext); const [loading, setLoading] = useState(true) const [todoData, setTodoData] = useState(null) const todoTitleRef = useRef("") const addTodoMutation = async () => { try { const todo = { title: todoTitleRef.current.value, user: user.username } await API.graphql({ query: addTodo, variables: { todo: todo, }, }) todoTitleRef.current.value = "" fetchTodos(); } catch (e) { console.log(e) } } const fetchTodos = async () => { try { const data = await API.graphql({ query: getTodos, }) setTodoData(data); console.log(data); setLoading(false) } catch (e) { console.log(e) } } useEffect(() => { fetchTodos() }, []) return ( <div> {loading ? ( <Heading as="h3" sx={{ textAlign: "center" }}>Loading...</Heading> ) : ( <div> <Navbar /><br /><br /> <Heading as="h3" sx={{ textAlign: "center" }}>Make Schedule Easy</Heading> <Label> <Input ref={todoTitleRef} /> </Label><br /> <Button sx={{ color: "black", textAlign: "center" }} onClick={() => addTodoMutation()}>Create Todo</Button><br /><br /> <Heading as="h2" sx={{ textAlign: "center" }}>Your Todo List</Heading> {todoData.data && todoData.data.getTodos.filter((todo) => todo.user === user.username).map((item, ind) => ( // todoData.data.getTodos.map((item, ind) => ( <div style={{ marginLeft: "1rem", marginTop: "2rem" }} key={ind}> <Text sx={{ fontSize: 4, fontWeight: 'italic', margin: '5px'}}>{item.title}</Text> <div> <Button sx={{ color: "black", textAlign: "center" }} onClick={async e => { e.preventDefault(); await API.graphql({ query: deleteTodo, variables: { todoId: item.id }, }) fetchTodos(); }} >Delete Todo</Button> </div> </div> ))} </div> )} </div> ); }; const App = () => { const { user } = useContext(IdentityContext); return ( <> <Router>{user && <Dash path="/app" />}</Router> {!user && <NavLink as={Link} to="/" p={2}>Home</NavLink>} </>) }; export default App;<file_sep>export declare const EVENT_SOURCE = "todo-app-events"; export declare const requestTemplate: (detail: string, detailType: string) => string; export declare const responseTemplate: () => string; <file_sep>import React, { useContext } from "react"; import { Button, Container, Flex, Heading } from "theme-ui"; import { IdentityContext } from "../../Identity-Context"; import Navbar from "../components/Navbar"; import { Link } from "gatsby"; import { Auth } from "aws-amplify"; const Index = () => { const { user } = useContext(IdentityContext); return ( <Container> <Navbar /> <Flex sx={{ flexDirection: "column", padding: 3, textAlign: "center" }}> <Heading as="h1">Todo App</Heading> {!user && ( <Button sx={{ marginTop: 2, color: 'black', fontFamily: 'monospace', cursor: 'pointer' }} onClick={() => { Auth.federatedSignIn({ provider: "Google"}) }} > Login </Button> )} {user && ( <Button sx={{ marginTop: 2, color: 'black', cursor: 'pointer' }}> <Link to='app/'>Create Todos</Link> </Button> )} </Flex> </Container> ); }; export default Index;
af8ca8624580817a98b000da60457790342bf46c
[ "JavaScript", "TypeScript" ]
7
JavaScript
Muhibullah-09/aws-event-bridge-todo-app
e62c3b0846244d57edcd42d82ca5fa895df6661f
8364e0af8d25024d3f9f6a463403344cb3d068fe
refs/heads/master
<repo_name>hammGJU/alumniservices<file_sep>/src/main/java/daos/ConnectionDAOImpl.java /* * 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 daos; import java.io.Serializable; import java.sql.Connection; import javax.sql.DataSource; /** * * @author hesham */ public class ConnectionDAOImpl implements Serializable, ConnectionDAO { private DataSource dataSource; public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } @Override public Connection getConnection() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void closeConnection() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public Connection openSessionConnection() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } } <file_sep>/src/main/java/beans/LoginBean.java /* * 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 beans; import java.io.Serializable; import java.sql.Connection; import javax.enterprise.context.SessionScoped; import javax.faces.application.NavigationHandler; import javax.faces.context.FacesContext; import javax.inject.Named; /** * * @author hesham */ @SessionScoped @Named(value = "loginBean") public class LoginBean implements Serializable { private String username; private String password; private Connection conn; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public Connection getConn() { return conn; } public void setConn(Connection conn) { this.conn = conn; } public void login() { FacesContext facesContect = FacesContext.getCurrentInstance(); boolean success = true; if (success) { if (facesContect != null) { NavigationHandler navigationHandler = facesContect.getApplication().getNavigationHandler(); navigationHandler.handleNavigation(facesContect, null, "/first_page?faces-redirect=true"); } } } public void logout() throws Exception { try { // Release and close database resources and connections if (conn != null) { if (!conn.getAutoCommit()) { conn.rollback(); conn.setAutoCommit(true); } conn.close(); conn = null; } } catch (Exception e) { throw new Exception(e.getMessage()); } finally { setPassword(null); setUsername(null); FacesContext facesContext = FacesContext.getCurrentInstance(); facesContext.getExternalContext().invalidateSession(); } } }
0c8a87e72b4158e5a597ba6c49036cbdbd6b9dda
[ "Java" ]
2
Java
hammGJU/alumniservices
e266219207f44792f01273424d6b4b417b3e3eaa
17b58a77db533f4645355d05eb8e3b4aec6bbde7
refs/heads/master
<file_sep>This is Raw-G's first attempt at making a blog!<file_sep>json.extract! @micropost, :id, :string, :integer, :created_at, :updated_at <file_sep>class CreateMicroposts < ActiveRecord::Migration def change create_table :microposts do |t| t.content :string t.user_id :integer t.timestamps end end end
2b925e4cc531c18c4d5c216795ce29f7f5ae6188
[ "RDoc", "Ruby" ]
3
RDoc
Raw-G/blog1
bec38511078a6eda99676f8b7085c42df0785239
f2f6b5dfb479c2a8e42ccfe34464b0f832a605ac
refs/heads/master
<repo_name>7odri9o/Lanterna<file_sep>/app/src/main/java/br/com/kimstorm/lanterna/LanternaApplication.java package br.com.kimstorm.lanterna; import android.app.Application; public class LanternaApplication extends Application { private static boolean isActivityVisible; public static boolean isActivityVisible() { return isActivityVisible; } public static void activityResumed() { isActivityVisible = true; } public static void activityPaused() { isActivityVisible = false; } } <file_sep>/app/src/main/java/br/com/kimstorm/lanterna/MainFragment.java package br.com.kimstorm.lanterna; import android.Manifest; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.graphics.SurfaceTexture; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraCaptureSession; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraManager; import android.hardware.camera2.CameraMetadata; import android.hardware.camera2.CaptureRequest; import android.os.BatteryManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.util.Size; import android.view.LayoutInflater; import android.view.Surface; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainFragment extends Fragment { public static final int CAMERA_ACCESS_REQUEST_CODE = 100; public static final float BATTERY_MINIMAL_PERCENTAGE = (float) 0.25; private Activity activity; private BroadcastReceiver mBatteryOkayReceiver; private CaptureRequest.Builder mBuilder; private CameraCaptureSession mSession; private CameraDevice mCameraDevice; private CameraManager mCameraManager; private SurfaceTexture mSurfaceTexture; private ImageButton flashSwitchButton; private boolean isFlashOn; private boolean isShowingLowBatteryMessage; public MainFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); flashSwitchButton = (ImageButton) rootView.findViewById(R.id.flashlight_switch_button); flashSwitchButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isFlashOn) { turnOffFlash(); } else { turnOnFlash(); } } }); return rootView; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); this.activity = getActivity(); } @Override public void onStart() { super.onStart(); startCamera(); } @Override public void onResume() { super.onResume(); verifyLowBattery(); } @Override public void onStop() { super.onStop(); close(); if (mBatteryOkayReceiver != null) { activity.unregisterReceiver(mBatteryOkayReceiver); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case CAMERA_ACCESS_REQUEST_CODE: if (grantResults[0] != PackageManager.PERMISSION_GRANTED) { Toast.makeText(activity, getString(R.string.camera_permission_not_granted_message), Toast.LENGTH_SHORT).show(); } else { startCamera(); } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); break; } } private void startCamera() { mCameraManager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE); String cameraId = getCameraId(); if (!cameraId.isEmpty()) { try { if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions( activity, new String[] { android.Manifest.permission.CAMERA}, CAMERA_ACCESS_REQUEST_CODE); return; } mCameraManager.openCamera(cameraId, new MyCameraDeviceStateCallback(), null); } catch (CameraAccessException e) { Toast.makeText(activity, getString(R.string.follow_problem_ocurr_message) + e.getMessage(), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(activity, getString(R.string.camera_not_found_message), Toast.LENGTH_SHORT).show(); } } @SuppressWarnings("ConstantConditions") @NonNull private String getCameraId() { String cameraId = ""; try { for (String id : mCameraManager.getCameraIdList()) { CameraCharacteristics characteristics = mCameraManager .getCameraCharacteristics(id); if (characteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT) { continue; } if (characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)) { cameraId = id; break; } } } catch (CameraAccessException e) { e.printStackTrace(); } return cameraId; } private void turnOnFlash() { try { mBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH); mSession.capture(mBuilder.build(), null, null); isFlashOn = true; toggleButtonImage(); } catch (CameraAccessException e) { Toast.makeText(activity, getString(R.string.problem_when_starting_flashlight_message), Toast.LENGTH_SHORT).show(); if (isFlashOn) { turnOffFlash(); } } } private void turnOffFlash() { try { mBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF); mSession.capture(mBuilder.build(), null, null); isFlashOn = false; toggleButtonImage(); } catch (CameraAccessException e) { Toast.makeText(activity, getString(R.string.problem_when_finish_flashlight_message), Toast.LENGTH_SHORT).show(); } } private void toggleButtonImage() { if (isFlashOn) { flashSwitchButton.setImageResource(R.drawable.switch_button_on); flashSwitchButton.setContentDescription(getString(R.string.switch_button_turn_on_content_description)); } else { flashSwitchButton.setImageResource(R.drawable.switch_button_off); flashSwitchButton.setContentDescription(getString(R.string.switch_button_turn_off_content_description)); } } @SuppressWarnings("ConstantConditions") private Size getSmallestSize(String cameraId) throws CameraAccessException { Size[] outputSizes = mCameraManager.getCameraCharacteristics(cameraId) .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) .getOutputSizes(SurfaceTexture.class); if (outputSizes == null || outputSizes.length == 0) { throw new IllegalStateException( "Camera " + cameraId + "doesn't support any outputSize."); } Size chosen = outputSizes[0]; for (Size s : outputSizes) { if (chosen.getWidth() >= s.getWidth() && chosen.getHeight() >= s.getHeight()) { chosen = s; } } return chosen; } private void close() { if (mCameraDevice == null || mSession == null) { return; } try { mBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_OFF); mSession.capture(mBuilder.build(), null, null); } catch (CameraAccessException e) { e.printStackTrace(); } mBuilder = null; mSession.close(); mSurfaceTexture.release(); if (mCameraDevice != null) { mCameraDevice.close(); mCameraDevice = null; } if (isFlashOn) { isFlashOn = false; toggleButtonImage(); } mSession = null; } private void verifyLowBattery() { IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); Intent batteryStatus = activity.registerReceiver(null, ifilter); assert batteryStatus != null; int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1); float batteryPct = level / (float)scale; if (batteryPct < BATTERY_MINIMAL_PERCENTAGE) { showLowBatterMessage(true); IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_OKAY); mBatteryOkayReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (LanternaApplication.isActivityVisible()) { if (intent.getAction().equals(Intent.ACTION_BATTERY_OKAY)) { if (isShowingLowBatteryMessage) { showLowBatterMessage(false); } } } } }; activity.registerReceiver(mBatteryOkayReceiver, filter); } } private void showLowBatterMessage(boolean mustShowMessage) { TextView messageTextView = (TextView) activity.findViewById(R.id.low_battery_message_textview); messageTextView.setVisibility(mustShowMessage ? View.VISIBLE : View.GONE); isShowingLowBatteryMessage = mustShowMessage; } private class MyCameraDeviceStateCallback extends CameraDevice.StateCallback { @Override public void onOpened(@NonNull CameraDevice camera) { mCameraDevice = camera; try { mBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE); mBuilder.set(CaptureRequest.CONTROL_AE_MODE, CameraMetadata.CONTROL_AF_MODE_AUTO); mSurfaceTexture = new SurfaceTexture(1); Size size = getSmallestSize(mCameraDevice.getId()); mSurfaceTexture.setDefaultBufferSize(size.getWidth(), size.getHeight()); Surface surface = new Surface(mSurfaceTexture); List<Surface> surfaceList = new ArrayList<>(); surfaceList.add(surface); mBuilder.addTarget(surface); mCameraDevice.createCaptureSession(surfaceList, new MyCameraCaptureSessionStateCallback(), null); } catch (CameraAccessException e) { e.printStackTrace(); } } @Override public void onDisconnected(@NonNull CameraDevice camera) { } @Override public void onError(@NonNull CameraDevice camera, int error) { } } private class MyCameraCaptureSessionStateCallback extends CameraCaptureSession.StateCallback { @Override public void onConfigured(@NonNull CameraCaptureSession session) { mSession = session; } @Override public void onConfigureFailed(@NonNull CameraCaptureSession session) { } } }
cd6e690e9b4f7170a686d1fcdf6b3ec145f0440f
[ "Java" ]
2
Java
7odri9o/Lanterna
077c5c8e32e08b7989642b4a3b5f1b88eabc0c94
d89c0821ca67ac1ae105616324da3b18caab7129
refs/heads/master
<repo_name>pponnuvel/liburing4cpp<file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(liburing-http-demo) find_package(Boost OPTIONAL_COMPONENTS context) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) option(USE_LIBAIO "Use libaio instead of liburing for old kernel support") add_executable(${PROJECT_NAME} "main.cpp" "global.cpp") target_link_libraries(${PROJECT_NAME} LINK_PRIVATE fmt) if(USE_LIBAIO) add_compile_definitions(USE_LIBAIO=1) target_link_libraries(${PROJECT_NAME} LINK_PRIVATE aio) else() target_link_libraries(${PROJECT_NAME} LINK_PRIVATE uring) endif() if(Boost_FOUND) include_directories(${Boost_INCLUDE_DIR}) target_link_libraries(${PROJECT_NAME} LINK_PRIVATE ${Boost_LIBRARIES}) endif() string(APPEND CMAKE_CXX_FLAGS_DEBUG " -fno-omit-frame-pointer -fsanitize=address -D_GLIBCXX_DEBUG") string(APPEND CMAKE_LINKER_FLAGS_DEBUG " -fno-omit-frame-pointer -fsanitize=address") <file_sep>/global.hpp #pragma once #include <unordered_map> #include <string_view> #include <vector> #if !USE_LIBAIO # include <liburing.h> // http://git.kernel.dk/liburing #else # include <libaio.h> // http://git.infradead.org/users/hch/libaio.git #endif extern const std::unordered_map<std::string_view, std::string_view> MimeDicts; #if !USE_LIBAIO extern io_uring ring; #else extern io_context_t context; #endif <file_sep>/coroutine.hpp #pragma once #include <functional> #include <sys/timerfd.h> #if !USE_LIBAIO # include <liburing.h> // http://git.kernel.dk/liburing #else # include <libaio.h> // http://git.infradead.org/users/hch/libaio.git #endif #include <sys/poll.h> #include <fmt/format.h> // https://github.com/fmtlib/fmt #include "yield.hpp" #include "global.hpp" // 填充 iovec 结构体 constexpr inline iovec to_iov(void *buf, size_t size) { return { buf, size }; } constexpr inline iovec to_iov(std::string_view sv) { return to_iov(const_cast<char *>(sv.data()), sv.size()); } template <size_t N> constexpr inline iovec to_iov(std::array<char, N>& array) { return to_iov(array.data(), array.size()); } template <typename Fn> struct on_scope_exit { on_scope_exit(Fn &&fn): _fn(std::move(fn)) {} ~on_scope_exit() { this->_fn(); } private: Fn _fn; }; [[noreturn]] void panic(std::string_view sv, int err = 0) { // 简单起见,把错误直接转化成异常抛出,终止程序 if (err == 0) err = errno; fmt::print(stderr, "errno: {}\n", err); if (err == EPIPE) { throw std::runtime_error("Broken pipe: client socket is closed"); } throw std::system_error(err, std::generic_category(), sv.data()); } class Coroutine: public FiberSpace::Fiber<int, std::function<void ()>> { public: using BaseType = FiberSpace::Fiber<int, std::function<void ()>>; using FuncType = BaseType::FuncType; public: static int runningCoroutines; explicit Coroutine(FuncType f): BaseType(std::move(f)) { ++Coroutine::runningCoroutines; this->next(); // We have to make sure that this->yield() is executed at least once. } explicit Coroutine(FuncType f, std::function<void ()> cleanup): BaseType(std::move(f)) { this->localData = std::move(cleanup); ++Coroutine::runningCoroutines; this->next(); } ~Coroutine() { --Coroutine::runningCoroutines; if (this->localData) this->localData(); } public: // 异步读操作,不使用缓冲区 #if !USE_LIBAIO #define DEFINE_AWAIT_OP(operation) \ template <unsigned int N> \ int await_##operation (int fd, iovec (&&ioves) [N], off_t offset = 0) { \ auto* sqe = io_uring_get_sqe(&ring); \ assert(sqe && "sqe should not be NULL"); \ io_uring_prep_##operation (sqe, fd, ioves, N, offset); \ io_uring_sqe_set_data(sqe, this); \ io_uring_submit(&ring); \ this->yield(); \ int res = this->current().value(); \ if (res < 0) panic(#operation, -res); \ return res; \ } #else #define DEFINE_AWAIT_OP(operation) \ template <unsigned int N> \ int await_##operation (int fd, iovec (&&ioves) [N], off_t offset = 0) { \ iocb ioq, *pioq = &ioq; \ io_prep_p##operation(&ioq, fd, ioves, N, offset); \ ioq.data = this; \ io_submit(context, 1, &pioq); \ this->yield(); \ int res = this->current().value(); \ if (res < 0) panic(#operation, -res); \ return res; \ } #endif DEFINE_AWAIT_OP(readv) DEFINE_AWAIT_OP(writev) #undef DEFINE_AWAIT_OP #if !USE_LIBAIO #define DEFINE_AWAIT_OP(operation) \ template <unsigned int N> \ int await_##operation(int sockfd, iovec (&&ioves) [N], uint32_t flags) { \ msghdr msg = { \ .msg_iov = ioves, \ .msg_iovlen = N, \ }; \ auto* sqe = io_uring_get_sqe(&ring); \ io_uring_prep_##operation(sqe, sockfd, &msg, flags); \ io_uring_sqe_set_data(sqe, this); \ io_uring_submit(&ring); \ this->yield(); \ int res = this->current().value(); \ if (res < 0) panic(#operation, -res); \ return res; \ } DEFINE_AWAIT_OP(recvmsg) DEFINE_AWAIT_OP(sendmsg) #else template <unsigned int N> int await_recvmsg(int sockfd, iovec (&&ioves) [N], uint32_t flags) { return this->await_readv(sockfd, std::move(ioves)); } template <unsigned int N> int await_sendmsg(int sockfd, iovec (&&ioves) [N], uint32_t flags) { return this->await_writev(sockfd, std::move(ioves)); } #endif int await_poll(int fd) { #if !USE_LIBAIO auto* sqe = io_uring_get_sqe(&ring); assert(sqe && "sqe should not be NULL"); io_uring_prep_poll_add(sqe, fd, POLLIN); io_uring_sqe_set_data(sqe, this); io_uring_submit(&ring); #else iocb ioq, *pioq = &ioq; io_prep_poll(&ioq, fd, POLLIN); ioq.data = this; io_submit(context, 1, &pioq); #endif this->yield(); int res = this->current().value(); if (res < 0) panic("poll", -res); return res; } // 把控制权交给其他协程 int yield_execution() { #if !USE_LIBAIO auto* sqe = io_uring_get_sqe(&ring); assert(sqe && "sqe should not be NULL"); io_uring_prep_nop(sqe); io_uring_sqe_set_data(sqe, this); io_uring_submit(&ring); #else iocb ioq, *pioq = &ioq; memset(&ioq, 0, sizeof(ioq)); ioq.aio_lio_opcode = IO_CMD_NOOP; ioq.data = this; io_submit(context, 1, &pioq); #endif this->yield(); return this->current().value(); } int delay(int second) { itimerspec exp = { {}, { second, 0 } }; auto tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK); if (timerfd_settime(tfd, 0, &exp, nullptr)) panic("timerfd"); on_scope_exit closefd([=]() { close(tfd); }); return this->await_poll(tfd); } public: static std::pair<Coroutine *, int> wait_for_event() { // 获取已完成的IO事件 #if !USE_LIBAIO io_uring_cqe* cqe; Coroutine *coro; do { if (io_uring_wait_cqe(&ring, &cqe)) panic("wait_cqe"); io_uring_cqe_seen(&ring, cqe); } while ((coro = static_cast<Coroutine *>(io_uring_cqe_get_data(cqe)))); auto res = cqe->res; #else io_event event; io_getevents(context, 1, 1, &event, nullptr); auto* coro = static_cast<Coroutine *>(event.data); auto res = event.res; #endif return { coro, res }; } static std::optional<std::pair<Coroutine *, int>> peek_a_event() { #if !USE_LIBAIO io_uring_cqe* cqe; while (io_uring_peek_cqe(&ring, &cqe) >= 0 && cqe) { io_uring_cqe_seen(&ring, cqe); if (auto* coro = static_cast<Coroutine *>(io_uring_cqe_get_data(cqe))) { return std::make_pair(coro, cqe->res); } } return std::nullopt; #else return timedwait_for_event({0, 0}); #endif } static std::optional<std::pair<Coroutine *, int>> timedwait_for_event(timespec timeout) { #if !USE_LIBAIO // io_uring doesn't support timed wait (yet), simulate it by polling a timer // First clear all cqes, to make sure there's no timer-poll completion event in queue if (auto result = Coroutine::peek_a_event()) { return result; } itimerspec exp = { {}, timeout }, old; static const int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK); if (timerfd_settime(tfd, 0, &exp, &old)) panic("timerfd"); // See if we can reuse the existing timer-poll request if (old.it_value.tv_sec == 0 && old.it_value.tv_nsec == 0) { // The old timer has expired, restart the poll request auto* sqe = io_uring_get_sqe(&ring); io_uring_prep_poll_add(sqe, tfd, POLLIN); // io_uring_sqe_set_data(sqe, nullptr); if (io_uring_submit_and_wait(&ring, 1) < 0) panic("io_uring_submit_and_wait"); } io_uring_cqe* cqe; if (io_uring_wait_cqe(&ring, &cqe) < 0) panic("io_uring_wait_cqe"); io_uring_cqe_seen(&ring, cqe); if (auto* coro = static_cast<Coroutine *>(io_uring_cqe_get_data(cqe))) { // We don't cancel the running time-poll request, it will be handled in next call return std::make_pair(coro, cqe->res); } else { return std::nullopt; } #else io_event event; if (io_getevents(context, 1, 1, &event, &timeout)) { return std::make_pair(static_cast<Coroutine *>(event.data), event.res); } else { return std::nullopt; } #endif } }; int Coroutine::runningCoroutines = 0; <file_sep>/README.md # liburing-http-demo Simple http server demo using [liburing](http://kernel.dk/io_uring.pdf) and [Cxx-yield](https://github.com/CarterLi/Cxx-yield/) Tested on `Linux Ubuntu 5.3.0-10-generic #11-Ubuntu SMP Mon Sep 9 15:12:17 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux` ## Dependencies * [liburing](http://git.kernel.dk/liburing) ( requires Linux 5.1 or later ) * [libaio](http://git.infradead.org/users/hch/libaio.git) ( fallback, requires Linux 4.18 or later ) * [fmt](https://github.com/fmtlib/fmt) * [boost::context](https://boost.org) ( optional ) * CMake ( build ) * Compiler that supports C++17 ## Introduction ( Chinese ) * https://segmentfault.com/a/1190000019300089 * https://segmentfault.com/a/1190000019361819 ## More info https://github.com/libuv/libuv/issues/1947 ## License Public domain <file_sep>/main.cpp #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <string> #include <string_view> #include <chrono> #include "coroutine.hpp" enum { SERVER_PORT = 8080, BUF_SIZE = 1024, }; using namespace std::literals; // 一些预定义的错误返回体 static constexpr const auto http_404_hdr = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n"sv; static constexpr const auto http_400_hdr = "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n"sv; // 解析到HTTP请求的文件后,发送本地文件系统中的文件 void http_send_file(Coroutine& coro, std::string filename, int clientfd, int dirfd) { if (filename == "./") filename = "./index.html"; // 尝试打开待发送文件 const auto infd = openat(dirfd, filename.c_str(), O_RDONLY); on_scope_exit closefd([=]() { close(infd); }); if (struct stat st; infd < 0 || fstat(infd, &st) || !S_ISREG(st.st_mode)) { // 文件未找到情况下发送404 error响应 fmt::print("{}: file not found!\n", filename); coro.await_sendmsg(clientfd, { to_iov(http_404_hdr) }, MSG_NOSIGNAL); } else { auto contentType = [filename_view = std::string_view(filename)]() { auto extension = filename_view.substr(filename_view.find_last_of('.') + 1); auto iter = MimeDicts.find(extension); if (iter == MimeDicts.end()) return "application/octet-stream"sv; return iter->second; }(); // 发送响应头 coro.await_sendmsg(clientfd, { to_iov(fmt::format("HTTP/1.1 200 OK\r\nContent-type: {}\r\nContent-Length: {}\r\n\r\n", contentType, st.st_size)), }, MSG_NOSIGNAL | MSG_MORE); off_t offset = 0; std::array<char, BUF_SIZE> filebuf; auto iov = to_iov(filebuf); for (; st.st_size - offset > BUF_SIZE; offset += BUF_SIZE) { coro.await_readv(infd, { iov }, offset); coro.await_sendmsg(clientfd, { iov }, MSG_NOSIGNAL | MSG_MORE); // coro.delay(1); // For debugging } if (st.st_size > offset) { iov.iov_len = size_t(st.st_size - offset); coro.await_readv(infd, { iov }, offset); coro.await_sendmsg(clientfd, { iov }, MSG_NOSIGNAL); } } } // HTTP请求解析 void serve(Coroutine& coro, int clientfd, int dirfd) { fmt::print("Serving connection, sockfd {}; number of running coroutines: {}\n", clientfd, Coroutine::runningCoroutines); std::string_view buf_view; std::array<char, BUF_SIZE> buffer; int res = coro.await_recvmsg(clientfd, { to_iov(buffer) }, MSG_NOSIGNAL); buf_view = std::string_view(buffer.data(), size_t(res)); // 这里我们只处理GET请求 if (buf_view.compare(0, 3, "GET") == 0) { // 获取请求的path auto file = "."s += buf_view.substr(4, buf_view.find(' ', 4) - 4); fmt::print("received request {} with sockfd {}\n", file, clientfd); http_send_file(coro, file, clientfd, dirfd); } else { // 其他HTTP请求处理,如POST,HEAD等,返回400错误 fmt::print("unsupported request: {}\n", buf_view); coro.await_sendmsg(clientfd, { to_iov(http_400_hdr) }, MSG_NOSIGNAL); } } void accept_connection(Coroutine& coro, int serverfd, int dirfd) { while (coro.await_poll(serverfd)) { int clientfd = accept(serverfd, nullptr, nullptr); // 新建新协程处理请求 new Coroutine( [=](auto& coro) { serve(static_cast<Coroutine &>(coro), clientfd, dirfd); }, [=, start = std::chrono::high_resolution_clock::now()] () { // 请求结束时清理资源 close(clientfd); fmt::print("sockfd {} is closed, time used {}\n", clientfd, (std::chrono::high_resolution_clock::now() - start).count()); } ); } } int main(int argc, char* argv[]) { if (argc != 2) { fmt::print("Usage: {} <ROOT_DIR>\n", argv[0]); return 1; } int dirfd = open(argv[1], O_DIRECTORY); if (dirfd < 0) panic("open dir"); on_scope_exit closedir([=]() { close(dirfd); }); // 初始化内核支持的原生异步IO操作实现 #if !USE_LIBAIO if (io_uring_queue_init(32, &ring, 0)) panic("queue_init"); on_scope_exit closerg([&]() { io_uring_queue_exit(&ring); }); #else if (io_queue_init(32, &context)) panic("queue_init"); on_scope_exit closerg([&]() { io_queue_release(context); }); #endif // 建立TCP套接字 int sockfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0); if (sockfd < 0) panic("socket creation"); on_scope_exit closesock([=]() { close(sockfd); }); // 设置允许端口重用 if (int on = 1; setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))) panic("SO_REUSEADDR"); if (int on = 1; setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on))) panic("SO_REUSEPORT"); // 绑定端口 if (sockaddr_in addr = { .sin_family = AF_INET, // 这里要注意,端口号一定要使用htons先转化为网络字节序,否则绑定的实际端口可能和你需要的不同 .sin_port = htons(SERVER_PORT), .sin_addr = { INADDR_ANY }, .sin_zero = {}, // 消除编译器警告 }; bind(sockfd, reinterpret_cast<sockaddr *>(&addr), sizeof (sockaddr_in))) panic("socket binding"); // 监听端口 if (listen(sockfd, 128)) panic("listen"); fmt::print("Listening: {}\n", SERVER_PORT); new Coroutine( [=](auto& coro) { accept_connection(static_cast<Coroutine &>(coro), sockfd, dirfd); } ); // 事件循环 while (Coroutine::runningCoroutines) { // 获取已完成的IO事件 if (auto some = Coroutine::timedwait_for_event({1, 0})) { auto [coro, res] = some.value(); // 有已完成的事件,回到协程继续 try { if (!coro->next(res)) delete coro; } catch (std::runtime_error& e) { fmt::print("{}\n", e.what()); delete coro; } } else { fmt::print("PING!\n"); } } }
c86d3b26e71d5f74e61aedf4ac2b73975c825f6c
[ "Markdown", "CMake", "C++" ]
5
CMake
pponnuvel/liburing4cpp
06a8fe8bed43c47a099f18f94cd03445b2483c13
34fdd41be8f72f170e7d7d8792ff3a39da7ce400
refs/heads/main
<file_sep># Reterm (仮) IDE っぽい UI のターミナルエミュレータ。(Electron + React + TypeScript) ステータス: ほとんど未実装 ## 機能 - コマンドの入力・編集を普通のエディタと同様に行える - ジョブごとに独立して入力操作や出力の閲覧を行える - 作業ディレクトリなどをファイラのようにツリーで視覚的にみれる ## UI (予定) イメージ図: ![window image](docs/images/window-image.png) - ファイルツリー - ファイルやディレクトリのツリーが表示される - 作業ディレクトリは強調表示される - ディレクトリをダブルクリックして作業ディレクトリを変更できる - 選択しているファイルのパスをシェルの変数として参照できる - エディタ - monaco-editor の予定 - 構文強調や入力補完が動く (予定) - Ctrl+Enter でジョブを実行する - Ctrl+↑/↓ で履歴にあるコマンドを使う - ジョブリスト - ジョブごとにカードが表示される - カードはヘッダー部分とボディーからなる - ヘッダーをクリックするとボディ部分を折りたんで隠せる - ヘッダーにジョブのコマンドとステータスが表示される (実行中か否か。終了済みなら終了コードも。) - ボディ部分に出力が表示される - ジョブにフォーカスを当てた状態でのキーボード操作は、このジョブに対して処理される - カーソルキーなど - (イメージには描かれていないが、おそらく read line に応答するための入力欄がある) - (イメージには描かれていないが、おそらく SIGINT を送るための ✖ ボタンがある) - (おそらく検索機能とかもあった方がよい) ### その他 - Git との統合 - ファイルの状態や、ブランチやスタッシュの表示など ## 類似プロジェクト? (他に知っていたら教えてください。) - [railsware/upterm\: A terminal emulator for the 21st century.](https://github.com/railsware/upterm) (archived) ## 開発用の資料 - [electron docs](https://www.electronjs.org/docs) Electron のドキュメント - [electron/electron-quick-start-typescript\: Clone to try a simple Electron app (in TypeScript)](https://github.com/electron/electron-quick-start-typescript) リポジトリの土台になっているやつ - [microsoft/node-pty\: Fork pseudoterminals in Node.JS](https://github.com/microsoft/node-pty) プロセスを起動するやつ (`child_process` と違って、起動したプロセスにはターミナルから直接呼ばれたようにみえる) <file_sep>export type JobStatus = { kind: "RUNNING" } | { kind: "EXITED" exitCode: number } export const Running: JobStatus = { kind: "RUNNING" } export const Exited = (exitCode: number): JobStatus => ({ kind: "EXITED", exitCode }) export const ExitedOk = Exited(0) export const ExitedErr = Exited(1) <file_sep>import { app, BrowserWindow, ipcMain } from "electron" import * as path from "path" import { JobStatus, Running, Exited, ExitedOk } from "./shared/job_status" import * as pty from "node-pty" type JobId = string interface JobState { id: JobId cmdline: string proc: pty.IPty | null status: JobStatus } let lastJobId = 0 let workDir = process.cwd() const jobs: JobState[] = [] const doExecute = (cmdline: string, reply: (...args: unknown[]) => void): JobState => { lastJobId++ const jobId = lastJobId.toString() console.log("[TRACE] execute", jobId, cmdline) const [cmd, ...args] = cmdline.trim().split(" ") // 組み込みコマンド switch (cmd) { case "cd": { const [dir] = args console.log("[TRACE] cd", dir) workDir = dir return { id: jobId, cmdline, proc: null, status: ExitedOk } } case "pwd": { console.log("[TRACE] pwd", workDir) return { id: jobId, cmdline, proc: null, status: ExitedOk } } default: break } // 外部コマンド const proc = pty.spawn(cmd, args, { name: "xterm-color", cols: 80, rows: 30, cwd: workDir, env: process.env as Record<string, string>, }) const job: JobState = { id: jobId, cmdline, proc, status: Running, } proc.onData(data => { console.log("[TRACE] process data", jobId, data.length) reply("rt-job-data", jobId, data) }) proc.onExit(({ exitCode, signal }) => { console.log("[TRACE] process exit", jobId, exitCode, signal) job.status = Exited(exitCode) reply("rt-job-exit", jobId, exitCode, signal) }) return job } ipcMain.handle("rt-get-work-dir", () => { console.log("[TRACE] rt-get-work-dir") return workDir }) ipcMain.on("rt-execute", (ev, cmdline) => { const reply = ev.reply.bind(ev) const job = doExecute(cmdline, reply) jobs.push(job) ev.reply("rt-job-created", job.id, job.cmdline, job.status) }) ipcMain.handle("rt-kill", (_ev, jobId, signal) => { console.log("[TRACE] rt-kill", jobId, signal) const job = jobs.find(j => j.id === jobId) if (job == null || job.status.kind === "EXITED" || job.proc == null) { console.log("[WARN] job missing, exited or built-in", job?.status?.kind) return null } job.proc.kill(signal) return true }) ipcMain.handle("rt-write", (_ev, jobId, data) => { console.log("[TRACE] rt-write", jobId, data) const job = jobs.find(j => j.id === jobId) if (job == null || job.status.kind === "EXITED" || job.proc == null) { console.log("[WARN] job missing, exited or built-in?", job?.status) return null } job.proc.write(data) return true }) function createWindow() { // Create the browser window. const mainWindow = new BrowserWindow({ height: 600, webPreferences: { nodeIntegration: true, preload: path.join(__dirname, "preload.js"), }, width: 800, }) // and load the index.html of the app. mainWindow.loadFile(path.join(__dirname, "../dist/index.html")) // Open the DevTools. // mainWindow.webContents.openDevTools() } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on("ready", () => { createWindow() app.on("activate", function () { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) // Quit when all windows are closed, except on macOS. There, it's common // for applications and their menu bar to stay active until the user quits // explicitly with Cmd + Q. app.on("window-all-closed", () => { if (process.platform !== "darwin") { app.quit() } }) // In this file you can include the rest of your app"s specific main process // code. You can also put them in separate files and require them here. <file_sep>#!/bin/sh set -eu npm run tsc-watch & npm run webpack-watch & wait <file_sep>#!/bin/sh set -eu npm run electron-run <file_sep>// This file is required by the index.html file and will // be executed in the renderer process for that window. // No Node.js APIs are available in this process unless // nodeIntegration is set to true in webPreferences. // Use preload.js to selectively enable features // needed in the renderer process. import ReactDOM from "react-dom" import { renderMain } from "./ui_main" document.addEventListener("DOMContentLoaded", () => { const appContainerElement = document.getElementById("app-container") as HTMLDivElement ReactDOM.render(renderMain(), appContainerElement) })
bc922155860db14df12688fed7bdb9ed644fe682
[ "Markdown", "TypeScript", "Shell" ]
6
Markdown
vain0x/reterm
b2d104f85fdc3707bd5bdc6e0837034b32a02515
06247845700a8877c822434ed39e414e3a57f7b6
refs/heads/master
<repo_name>krainet/ps_resources<file_sep>/ps_modules/modules_src/shopimultitabs/classes/ShopimultitabContent.php <?php /** * Shopi Multiple Tabs In Product Module * * @author ShopiTheme; * @copyright Copyright (C) October 2013 prestabrain.com <@emai:<EMAIL>>; * @license GNU General Public License version 2; */ class ShopimultitabContent extends ObjectModel { public $id; public $id_product; public $content; public $id_shopimultitab; public $categories; public $global; public $content_text; /** * @see ObjectModel::$definition */ public static $definition = array( 'table' => 'shopimultitab_content', 'primary' => 'id_shopimultitab_content', 'multilang' => true, 'fields' => array( 'id_product' => array('type' => self::TYPE_INT, 'validate' => 'isunsignedInt', 'required' => true), 'content' => array('type' => self::TYPE_STRING, 'validate' => 'isCleanHtml', 'size' => 255), 'id_shopimultitab' => array('type' => self::TYPE_INT, 'validate' => 'isunsignedInt', 'required' => true), 'categories' => array('type' => self::TYPE_STRING, 'validate' => 'isCleanHtml'), 'global' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool'), 'content_text' => array('type' => self::TYPE_HTML, 'lang' => true), ) ); public function __construct($id = null, $id_lang = null, $id_shop = null, Context $context = null) { parent::__construct($id, $id_lang, $id_shop); } public function add($autodate = true, $null_values = false) { $context = Context::getContext(); $id_shop = $context->shop->id; $res = parent::add($autodate, $null_values); $res &= Db::getInstance()->execute(' INSERT INTO `'._DB_PREFIX_.'shopimultitab_content_shop` (`id_shop`, `id_shopimultitab_content`) VALUES('.(int)$id_shop.', '.(int)$this->id.')' ); return $res; } public function delete() { $res = true; $res &= Db::getInstance()->execute(' DELETE FROM `'._DB_PREFIX_.'shopimultitab_content_shop` WHERE `id_shopimultitab_content` = '.(int)$this->id ); $res &= parent::delete(); return $res; } public static function checkExist($id_shopimultitab, $id_product) { $return = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow(' SELECT * FROM '._DB_PREFIX_.'shopimultitab_content WHERE id_shopimultitab = '.(int)$id_shopimultitab.' AND id_product = '.(int)($id_product) ); return ($return ? true : false); } public static function getContents($id_shopimultitab = null, $id_product = null, $global = null) { $context = Context::getContext(); $id_shop = $context->shop->id; $id_lang = $context->language->id; return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT hs.`id_shopimultitab_content` as id_shopimultitab_content, hss.`content`, hss.`id_product`, hss.`id_shopimultitab`, hssl.`content_text`, hss.categories, hss.global FROM '._DB_PREFIX_.'shopimultitab_content_shop hs LEFT JOIN '._DB_PREFIX_.'shopimultitab_content hss ON (hs.id_shopimultitab_content = hss.id_shopimultitab_content) LEFT JOIN '._DB_PREFIX_.'shopimultitab_content_lang hssl ON (hss.id_shopimultitab_content = hssl.id_shopimultitab_content) WHERE (id_shop = '.(int)$id_shop.') AND hssl.id_lang = '.(int)$id_lang.($id_shopimultitab ? ' AND hss.`id_shopimultitab` = '.(int)$id_shopimultitab : '').($id_product ? ' AND hss.`id_product` = '.(int)$id_product : '') .($global ? ' AND hss.global = 1' : '') ); } public static function getContent($id_shopimultitab, $id_product) { if (!$id_shopimultitab || !$id_product) return array(); $context = Context::getContext(); $id_shop = $context->shop->id; $id_lang = $context->language->id; return Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow(' SELECT hs.`id_shopimultitab_content` as id_shopimultitab_content, hss.`content`, hss.`id_product`, hss.`id_shopimultitab`, hssl.`content_text` FROM '._DB_PREFIX_.'shopimultitab_content_shop hs LEFT JOIN '._DB_PREFIX_.'shopimultitab_content hss ON (hs.id_shopimultitab_content = hss.id_shopimultitab_content) LEFT JOIN '._DB_PREFIX_.'shopimultitab_content_lang hssl ON (hss.id_shopimultitab_content = hssl.id_shopimultitab_content) WHERE (id_shop = '.(int)$id_shop.') AND hssl.id_lang = '.(int)$id_lang.' AND hss.`id_shopimultitab` = '.(int)$id_shopimultitab.($id_product ? ' AND hss.`id_product` = '.(int)$id_product : '') ); } } <file_sep>/ps_modules/modules_src/shopimultitabs/libs/Helper.php <?php /** * Shopi Multiple Tabs In Product Module * * @author ShopiTheme; * @copyright Copyright (C) October 2013 prestabrain.com <@emai:<EMAIL>>; * @license GNU General Public License version 2; */ class HelperShopiMultiTab { public static $hookAssign = array('displayRightColumn','displayLeftColumn','displayHome','displayTop','displayFooter'); public static function getFolderAdmin() { $folders = array('cache','classes','config','controllers','css','docs','download','img','js','localization','log','mails', 'modules','override','themes','tools','translations','upload','webservice','.','..'); $handle = opendir(_PS_ROOT_DIR_); if (!$handle) { return false; } while (false !== ($folder = readdir($handle))) { if (is_dir(_PS_ROOT_DIR_ .'/'. $folder)) { if (!in_array($folder, $folders)) { $folderadmin = opendir(_PS_ROOT_DIR_ .'/'. $folder); if (!$folderadmin) return $folder; while (false !== ($file = readdir($folderadmin))) { if (is_file(_PS_ROOT_DIR_ .'/'. $folder.'/'.$file) && ($file == 'header.inc.php')) { return $folder; } } } } } return $false; } /** * get modules * this */ public static function getModules() { //global $hookAssign; $notModule = array( SHOPI_MULTITAB_MODULE_NAME ); $where = ''; if (count($notModule) == 1) { $where = ' WHERE m.`name` <> \''.$notModule[0].'\' AND active = 1'; } elseif (count($notModule) > 1) { $where = ' WHERE m.`name` NOT IN (\''.implode("','",$notModule).'\') AND active = 1'; } $id_shop = Context::getContext()->shop->id; $modules = Db::getInstance()->ExecuteS(' SELECT m.* FROM `'._DB_PREFIX_.'module` m JOIN `'._DB_PREFIX_.'module_shop` ms ON (m.`id_module` = ms.`id_module` AND ms.`id_shop` = '.(int)($id_shop).') '.$where ); if (!$modules) return array(); $return = array(); foreach ($modules as $module) { $moduleInstance = Module::getInstanceByName($module['name']); $m_module = ''; foreach (self::$hookAssign as $hook) { $retro_hook_name = Hook::getRetroHookName($hook); if (is_callable(array($moduleInstance, 'hook'.ucfirst($hook))) || is_callable(array($moduleInstance, 'hook'.ucfirst($retro_hook_name)))) $m_module = $module; } if ($m_module) $return[] = $m_module; } return $return; } /** * get modules * */ public static function getModuleByName( $name ) { return Db::getInstance()->getRow(' SELECT m.* FROM `'._DB_PREFIX_.'module` m JOIN `'._DB_PREFIX_.'module_shop` ms ON (m.`id_module` = ms.`id_module` AND ms.`id_shop` = '.(int)(Context::getContext()->shop->id).') WHERE m.`name` = \''.$name.'\''); } /** * get Hooks in module * */ public static function getHooksByModuleName( $name ) { //global $hookAssign; if(!$name) return array(); $moduleInstance = Module::getInstanceByName( $name ); //echo "<pre>".print_r($moduleInstance,1); die; $hooks = array(); foreach( self::$hookAssign as $hook) { $retro_hook_name = Hook::getRetroHookName($hook); if (is_callable(array($moduleInstance, 'hook'.ucfirst($hook))) || is_callable(array($moduleInstance, 'hook'.ucfirst($retro_hook_name)))) { $hooks[] = $hook; } } $results = self::getHookByArrName( $hooks ); return $results; } /** * get Hook by Name * */ public static function getHookByName($name) { return Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow(' SELECT * FROM `'._DB_PREFIX_.'hook` WHERE `name` = \''.$name.'\''); } /** * get Hook by name array * */ public static function getHookByArrName($arrName) { $result = Db::getInstance()->ExecuteS(' SELECT `id_hook`, `name` FROM `'._DB_PREFIX_.'hook` WHERE `name` IN (\''.implode("','",$arrName).'\')'); return $result ; } public static function execModule( $values ) { $result = ''; if ($values ) { $arrItems = explode(':',$values); if (count($arrItems) == 2) { $shopimodule = self::getModuleByName( $arrItems[0] ); $shopihook = self::getHookByName( $arrItems[1] ); if ($shopimodule && $shopihook) { $array = array(); $array['id_hook'] = $shopihook['id_hook']; $array['module'] = $shopimodule['name']; $array['id_module'] = $shopimodule['id_module']; if ($array['module'] && $array['id_module'] && $array['id_hook']) $result = self::hookExec( $shopihook['name'], array(), $shopimodule['id_module'], $array); /* delete module hook self::DeleteModuleHook( $shopimodule['id_module'], $shopihook['id_hook'] ); */ } } } return $result; } public static function hookExec($hook_name, $hookArgs = array(), $id_module = NULL, $array = array()) { if ((!empty($id_module) AND !Validate::isUnsignedId($id_module)) OR !Validate::isHookName($hook_name)) die(Tools::displayError()); $context = Context::getContext(); if (!isset($hookArgs['cookie']) || !$hookArgs['cookie']) $hookArgs['cookie'] = $context->cookie; if (!isset($hookArgs['cart']) || !$hookArgs['cart']) $hookArgs['cart'] = $context->cart; if ($id_module && $id_module != $array['id_module']) return ; if (!($moduleInstance = Module::getInstanceByName($array['module'])) || !$moduleInstance->active) return ; $retro_hook_name = Hook::getRetroHookName($hook_name); $hook_callable = is_callable(array($moduleInstance, 'hook'.$hook_name)); $hook_retro_callable = is_callable(array($moduleInstance, 'hook'.$retro_hook_name)); $output = ''; if (($hook_callable || $hook_retro_callable) && Module::preCall($moduleInstance->name)) { if ($hook_callable) $output = $moduleInstance->{'hook'.$hook_name}($hookArgs); else if ($hook_retro_callable) $output = $moduleInstance->{'hook'.$retro_hook_name}($hookArgs); } return $output; } } ?><file_sep>/ps_modules/modules_src/extrainfo/readme.txt Extra Info Module This module adds an extra product information tab among the product tabs in the product page. Data field names are adjusted and modified by a request of book seller and can be change easily by editing extratabContents.tpl Current modifications are presented below: Author field : uses product reference info ISBN field : uses EAN13 info Item code field : uses UPC info Compatible with Prestashop version 1.4.x Contact: <EMAIL> P.S: Module is free of charge, can be distributed or modified without permission of the coder.<file_sep>/ps_modules/modules_src/shopimultitabs/classes/Shopimultitab.php <?php /** * Shopi Multiple Tabs In Product Module * * @author ShopiTheme; * @copyright Copyright (C) October 2013 prestabrain.com <@emai:<EMAIL>>; * @license GNU General Public License version 2; */ class Shopimultitab extends ObjectModel { public $id; public $position; public $active; public $date_add; public $date_upd; public $title; /** * @see ObjectModel::$definition */ public static $definition = array( 'table' => 'shopimultitab', 'primary' => 'id_shopimultitab', 'multilang' => true, 'fields' => array( 'active' => array('type' => self::TYPE_BOOL, 'validate' => 'isBool', 'required' => true), 'position' => array('type' => self::TYPE_INT, 'validate' => 'isunsignedInt'), 'title' => array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isCleanHtml', 'required' => true, 'size' => 255), ) ); public function __construct($id = null, $id_lang = null, $id_shop = null, Context $context = null) { parent::__construct($id, $id_lang, $id_shop); } public function add($autodate = true, $null_values = false) { $context = Context::getContext(); $id_shop = $context->shop->id; $this->position = $this->getLastPosition(); $res = parent::add($autodate, $null_values); $res &= Db::getInstance()->execute(' INSERT INTO `'._DB_PREFIX_.'shopimultitab_shop` (`id_shop`, `id_shopimultitab`) VALUES('.(int)$id_shop.', '.(int)$this->id.')' ); return $res; } public function delete() { $res = true; $res &= $this->reOrderPositions(); $res &= Db::getInstance()->execute(' DELETE FROM `'._DB_PREFIX_.'shopimultitab_shop` WHERE `id_shopimultitab` = '.(int)$this->id ); $contents = ShopimultitabContent::getContents($this->id); if ($contents) foreach ($contents as $content) { $obj = new ShopimultitabContent((int)$content['id_shopimultitab_content']); $res &= $obj->delete(); } $res &= parent::delete(); return $res; } public static function getLastPosition() { return (Db::getInstance()->getValue('SELECT MAX(l.position)+1 FROM `'._DB_PREFIX_.'shopimultitab` l')); } public function reOrderPositions() { $id_shopimultitab = $this->id; $context = Context::getContext(); $id_shop = $context->shop->id; $max = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT MAX(hss.`position`) as position FROM `'._DB_PREFIX_.'shopimultitab` hss, `'._DB_PREFIX_.'shopimultitab_shop` hs WHERE hss.`id_shopimultitab` = hs.`id_shopimultitab` AND hs.`id_shop` = '.(int)$id_shop ); if ((int)$max == (int)$id_shopimultitab) return true; $rows = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT hss.`position` as position, hss.`id_shopimultitab` as id_shopimultitab FROM `'._DB_PREFIX_.'shopimultitab` hss LEFT JOIN `'._DB_PREFIX_.'shopimultitab_shop` hs ON (hss.`id_shopimultitab` = hs.`id_shopimultitab`) WHERE hs.`id_shop` = '.(int)$id_shop.' AND hss.`position` > '.(int)$this->position ); foreach ($rows as $row) { $current_tab = new Shopimultitab($row['id_shopimultitab']); $current_tab->position; $current_tab->update(); unset($current_tab); } return true; } public static function getTabs($active = null) { $context = Context::getContext(); $id_shop = $context->shop->id; $id_lang = $context->language->id; return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' SELECT hs.`id_shopimultitab` as id_shopimultitab, hss.`position`, hss.`active`, hssl.`title` FROM '._DB_PREFIX_.'shopimultitab_shop hs LEFT JOIN '._DB_PREFIX_.'shopimultitab hss ON (hs.id_shopimultitab = hss.id_shopimultitab) LEFT JOIN '._DB_PREFIX_.'shopimultitab_lang hssl ON (hss.id_shopimultitab = hssl.id_shopimultitab) WHERE (id_shop = '.(int)$id_shop.') AND hssl.id_lang = '.(int)$id_lang. ($active ? ' AND hss.`active` = 1' : ' ').' ORDER BY hss.position' ); } } <file_sep>/README.md # ps_resources A set of PS 1.6 resources (modules and themes) <file_sep>/ps_modules/modules_src/shopimultitabs/install/sql.tables.php <?php /** * Shopi Multiple Tabs In Product Module * * @author ShopiTheme; * @copyright Copyright (C) October 2013 prestabrain.com <@emai:<EMAIL>>; * @license GNU General Public License version 2; */ $query = " CREATE TABLE IF NOT EXISTS `_DB_PREFIX_shopimultitab` ( `id_shopimultitab` int(11) NOT NULL AUTO_INCREMENT, `position` int(11) NOT NULL, `active` tinyint(1) NOT NULL, `date_add` datetime NOT NULL, `date_upd` datetime NOT NULL, PRIMARY KEY (`id_shopimultitab`) ) ENGINE=_MYSQL_ENGINE_ DEFAULT CHARSET=utf8 ; CREATE TABLE IF NOT EXISTS `_DB_PREFIX_shopimultitab_lang` ( `id_shopimultitab` int(11) NOT NULL DEFAULT '0', `title` varchar(50) DEFAULT NULL, `id_lang` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`id_shopimultitab`,`id_lang`) ) ENGINE=_MYSQL_ENGINE_ DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `_DB_PREFIX_shopimultitab_shop` ( `id_shopimultitab` int(11) NOT NULL, `id_shop` int(11) NOT NULL, PRIMARY KEY (`id_shopimultitab`,`id_shop`) ) ENGINE=_MYSQL_ENGINE_ DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `_DB_PREFIX_shopimultitab_content` ( `id_shopimultitab_content` int(11) NOT NULL AUTO_INCREMENT, `id_product` int(11) NOT NULL, `content` text NOT NULL, `id_shopimultitab` int(11) NOT NULL, `categories` varchar(255) DEFAULT NULL, `global` tinyint(1) NOT NULL, PRIMARY KEY (`id_shopimultitab_content`) ) ENGINE=_MYSQL_ENGINE_ DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `_DB_PREFIX_shopimultitab_content_lang` ( `id_shopimultitab_content` int(11) NOT NULL, `id_lang` int(11) NOT NULL, `content_text` text NOT NULL, PRIMARY KEY (`id_shopimultitab_content`,`id_lang`) ) ENGINE=_MYSQL_ENGINE_ DEFAULT CHARSET=utf8; CREATE TABLE IF NOT EXISTS `_DB_PREFIX_shopimultitab_content_shop` ( `id_shopimultitab_content` int(11) NOT NULL, `id_shop` int(11) NOT NULL, PRIMARY KEY (`id_shopimultitab_content`,`id_shop`) ) ENGINE=_MYSQL_ENGINE_ DEFAULT CHARSET=utf8; "; <file_sep>/ps_modules/modules_src/extrainfo/extrainfo.php <?php class extrainfo extends Module { function __construct() { $this->name = 'extrainfo'; $this->tab = 'front_office_features'; $this->version = 1.0; $this->author = 'Caglar'; $this->need_instance = 0; parent::__construct(); // The parent construct is required for translations $this->displayName = $this->l('Extra Info'); $this->description = $this->l('Adds an extra product info tab on product page.<br />(www.cepparca.com | by Caglar)'); } function install() { if (parent::install() == false OR $this->registerHook('productTab') == false OR $this->registerHook('productTabContent') == false) return (false); return (true); } /** * Returns module content * * @param array $params Parameters * @return string Content */ function hookProductTab($params) { global $smarty, $cookie; return $this->display(__FILE__, 'extratab.tpl'); } public function hookProductTabContent($params) { global $smarty, $cookie, $link; /* Product informations */ $product = new Product((int)Tools::getValue('id_product'), false, (int)$cookie->id_lang); $smarty->assign(array( 'product' => $product )); return ($this->display(__FILE__, 'extratabContents.tpl')); } } ?><file_sep>/ps_modules/modules_src/shopimultitabs/form.php <?php /** * Shopi Multiple Tabs In Product Module * * @author ShopiTheme; * @copyright Copyright (C) October 2013 prestabrain.com <@emai:<EMAIL>>; * @license GNU General Public License version 2; */ if (!defined('_PS_VERSION_')) exit; $tabs = Shopimultitab::getTabs(); $types = array('html' => 'Html', 'module' => 'Module'); $str = ''; if ($tabs) { $id_product = Tools::getValue('id_product'); foreach ($tabs as $tab) { $tabContent = ShopimultitabContent::getContent($tab['id_shopimultitab'], $id_product); $str .= '<div id="product-tab-content-shopi-tab-'.$tab['id_shopimultitab'].'" class="product-tab-content shopi-product-tab-content panel" style="display:none">'; if ($tabContent) $obj = new ShopimultitabContent($tabContent['id_shopimultitab_content']); else $obj = new ShopimultitabContent(); $str .= ' <div class="form-group"> <label class="control-label col-lg-3">Content Text:</label> <div class="col-lg-9">'; $languages = Language::getLanguages(false); $id_lang_default = (int)Configuration::get('PS_LANG_DEFAULT'); foreach ($languages as $language) { $str .= ' <div class="translatable-field row lang-'.$language['id_lang'].'" style="display: '.($language['id_lang'] == $id_lang_default ? 'block' : 'none').';"> <div class="col-lg-9"> <textarea class="rte" id="shopicontent_text_'.$tab['id_shopimultitab'].'_'.$language['id_lang'].'" name="shopicontent_text_'.$tab['id_shopimultitab'].'_'.$language['id_lang'].'" cols="30" row="5">'.htmlentities((isset($obj->content_text[$language['id_lang']]) ? $obj->content_text[$language['id_lang']] : ''), ENT_COMPAT, 'UTF-8').'</textarea> </div>'; $str .= ' <div class="col-lg-2"> <button type="button" class="btn btn-default dropdown-toggle" tabindex="-1" data-toggle="dropdown"> '.$language['iso_code'].' <i class="icon-caret-down"></i> </button> <ul class="dropdown-menu">'; foreach ($languages as $lang) $str .= '<li><a href="javascript:hideOtherLanguage('.$lang['id_lang'].');" tabindex="-1">'.$lang['name'].'</a></li>'; $str .= ' </ul> </div>'; $str .= ' </div>'; } $str .= '</div>'; $str .= '</div>'; $str .= ' <div class="form-group"> <label class="control-label col-lg-3">Modules:</label> <div class="col-lg-9"> '; /* MODULE */ /* Submenu Modules */ $hookoptions = ''; $shopimodule = ''; $shopihook = ''; if ($obj->content) { $arrmodulehook = explode(':', $obj->content); if (count($arrmodulehook) == 2) { $shopimodule = $arrmodulehook[0]; $shopihook = $arrmodulehook[1]; } $hookAssign = HelperShopiMultiTab::getHooksByModuleName($shopimodule); foreach ($hookAssign as $hook) $hookoptions .= '<option value="'.$hook['name'].'"'.((isset($shopihook) && Tools::strtolower($shopihook) == Tools::strtolower($hook['name'])) ? ' selected="selected"' : '').'>'.$hook['name'].'</option>'; } $modules = HelperShopiMultiTab::getModules(); $options = ''; foreach ($modules as $module) $options .= '<option value="'.$module['name'].'"'.((isset($shopimodule) && $shopimodule == $module['name']) ? ' selected="selected"' : '').'>'.$module['name'].'</option>'; $str .= ' <div class="menu_type_modules"> <div class="shopi-header"> <input type="hidden" value="'.$obj->id.'" name="id_shopimultitab_content_'.$tab['id_shopimultitab'].'" class="id_shopimultitab_content"/> <input type="hidden" value="'.$tab['id_shopimultitab'].'" name="id_shopimultitab_'.$tab['id_shopimultitab'].'" class="id_shopimultitab"/> <div class="shopi-left"> <label class="labelmodule">Modules:</label> <select class="shopimodule" name="shopimodule_'.$tab['id_shopimultitab'].'"> <option value=""> --- Choose module --- </option>'.$options.' </select> </div> <div class="shopi-right"> <label class="labelhook">Override hooks:</label> <select class="shopihook" name="shopihook_'.$tab['id_shopimultitab'].'" id="shopihook-'.$tab['id_shopimultitab'].'"> <option value=""> --- Choose hook --- </option>'.$hookoptions.' </select> </div> </div> </div>'; $str .= '</div>'; $str .= '</div>'; $str .= ' <div class="form-group"> <label class="control-label col-lg-3">Global Block:</label> <div class="col-lg-9">'; $str .= '<input type="checkbox" value="1" name="global_'.$tab['id_shopimultitab'].'" '.($obj->global ? 'checked="checked"' : '').'>'; $str .= '</div>'; $str .= '</div>'; $str .= ' <div class="form-group"> <div class="col-lg-9 col-lg-offset-3"> <div class="alert alert-info"> This option will allow to display this block on other products that are associated with selected categories (you can select categories below) </div> </div> </div> '; $str .= ' <div class="form-group"> <label class="control-label col-lg-3">Categories ID:</label> <div class="col-lg-9">'; $str .= '<input type="text" name="categories_'.$tab['id_shopimultitab'].'" value="'.$obj->categories.'"> <p>Example: 1,2,3</p> '; $str .= '</div>'; $str .= '</div>'; /* END MODULE */ $str .= ' <div class="panel-footer"> <a class="btn btn-default" href="index.php?controller=AdminProducts&amp;token=<PASSWORD>"><i class="process-icon-cancel"></i> Cancel</a> <button class="btn btn-default pull-right" name="submitAddproduct" type="submit"><i class="process-icon-save"></i> Save</button> <button class="btn btn-default pull-right" name="submitAddproductAndStay" type="submit"><i class="process-icon-save"></i> Save and stay</button> </div> '; $str .= '</div>'; } $iso = Language::getIsoById((int)(Context::getContext()->language->id)); $isoTinyMCE = (file_exists(_PS_ROOT_DIR_.'/js/tiny_mce/langs/'.$iso.'.js') ? $iso : 'en'); $adminfolder = HelperShopiMultiTab::getFolderAdmin(); $ad = __PS_BASE_URI__.$adminfolder; $str .= ' <script type="text/javascript"> var iso = \''.$isoTinyMCE.'\' ; var pathCSS = \''._THEME_CSS_DIR_.'\' ; var ad = \''.$ad.'\' ; tinySetup(); </script> <script type="text/javascript"> jQuery(document).ready(function($){ $(\'.shopimodule\').change(function(){ var module_name = $(this).find(\'option:selected\').val(); var id_shopimultitab = $(this).parent().parent().find(\'.id_shopimultitab\').val(); if(module_name){ $.ajax({ type: "POST", url: "'._MODULE_DIR_.'shopimultitabs/ajax.php?secure_key='.Tools::encrypt('shopimultitabs').'", data: "module_name="+module_name+"&task=gethook", success: function(data){ select_innerHTML(document.getElementById("shopihook-" + id_shopimultitab),data); } }); } }); }); function select_innerHTML(objeto,innerHTML){ objeto.innerHTML = "" var selTemp = document.createElement("micoxselect") var opt; selTemp.id="micoxselect1" document.body.appendChild(selTemp) selTemp = document.getElementById("micoxselect1") selTemp.style.display="none" if(innerHTML.toLowerCase().indexOf("<option")<0){//se não é option eu converto innerHTML = "<option>" + innerHTML + "</option>" } innerHTML = innerHTML.toLowerCase().replace(/<option/g,"<span").replace(/<\/option/g,"</span") selTemp.innerHTML = innerHTML for(var i=0;i<selTemp.childNodes.length;i++){ var spantemp = selTemp.childNodes[i]; if(spantemp.tagName){ opt = document.createElement("OPTION") if(document.all){ //IE objeto.add(opt) }else{ objeto.appendChild(opt) } //getting attributes for(var j=0; j<spantemp.attributes.length ; j++){ var attrName = spantemp.attributes[j].nodeName; var attrVal = spantemp.attributes[j].nodeValue; if(attrVal){ try{ opt.setAttribute(attrName,attrVal); opt.setAttributeNode(spantemp.attributes[j].cloneNode(true)); }catch(e){} } } //getting styles /* if(spantemp.style){ for(var y in spantemp.style){ try{opt.style[y] = spantemp.style[y];}catch(e){} } } */ //value and text opt.value = spantemp.getAttribute("value") opt.text = spantemp.innerHTML //IE opt.selected = spantemp.getAttribute(\'selected\'); //opt.className = spantemp.className; } } document.body.removeChild(selTemp) selTemp = null } </script>'; }<file_sep>/ps_modules/modules_src/extrainfo/tr.php <?php global $_MODULE; $_MODULE = array(); $_MODULE['<{extrainfo}prestashop>extrainfo_bfc328668da4835003808cdff4a09f5f'] = 'Ekstra Ürün Bilgi Sekmesi'; $_MODULE['<{extrainfo}prestashop>extrainfo_51ab1a6afddda78a3479c84c42e7ccb4'] = 'Ürün sayfası sekmelerine ekstra bilgi sekmesi ekler (www.cepparca.com | Kodlayan Caglar)'; $_MODULE['<{extrainfo}prestashop>extratab_bfc328668da4835003808cdff4a09f5f'] = 'EKSTRA BİLGİ'; $_MODULE['<{extrainfo}prestashop>extratabcontents_49ee3087348e8d44e1feda1917443987'] = 'Adı'; $_MODULE['<{extrainfo}prestashop>extratabcontents_a517747c3d12f99244ae598910d979c5'] = 'Yazar & Çizer'; $_MODULE['<{extrainfo}prestashop>extratabcontents_bc67a1507258a758c3a31e66d7ceff8f'] = 'Tedarikçi Referansı'; $_MODULE['<{extrainfo}prestashop>extratabcontents_9609dddf3618cff8f67b7829e6fc575e'] = 'ISBN'; $_MODULE['<{extrainfo}prestashop>extratabcontents_7608203603437f0513ba8203a2d39a4f'] = 'Ürün Kodu'; <file_sep>/ps_modules/modules_src/krmodule/display.php <?php /** * Created by Develjitsu.com. * User: <NAME> * Date: 18/08/16 * Time: 17:56 */ class krmoduledisplayModuleFrontController extends ModuleFrontController { public function initContent() { parent::initContent(); $this->setTemplate('display.tpl'); } }<file_sep>/ps_modules/modules_src/shopimultitabs/shopimultitabs.php <?php /** * Shopi Multiple Tabs In Product Module * * @author ShopiTheme; * @copyright Copyright (C) October 2013 prestabrain.com <@emai:<EMAIL>>; * @license GNU General Public License version 2; */ if (!defined('_PS_VERSION_')) exit; include_once(dirname(__FILE__).'/defines.php'); include_once(dirname(__FILE__).'/classes/Shopimultitab.php'); include_once(dirname(__FILE__).'/classes/ShopimultitabContent.php'); include_once(dirname(__FILE__).'/libs/Helper.php'); class ShopiMultiTabs extends Module { private $_html = ''; public $base_config_url; public $tabcontent; public function __construct() { $this->name = 'shopimultitabs'; $this->tab = 'front_office_features'; $this->version = '2.0.0'; $this->author = 'ShopiTheme'; $this->module_key = '<KEY>'; $this->secure_key = Tools::encrypt($this->name); $this->bootstrap = true; parent::__construct(); $this->base_config_url = AdminController::$currentIndex.'&configure='.$this->name.'&token='.Tools::getValue('token'); $this->displayName = $this->l('Shopi Multiple Tabs In Product Module'); $this->description = $this->l('Shopi Multiple Product Tab Module'); } public function install() { /* Adds Module */ if (parent::install() && $this->registerHook('displayBackOfficeFooter') && $this->registerHook('actionProductSave') && $this->registerHook('actionProductDelete') && $this->registerHook('displayBackOfficeHeader') && $this->registerHook('displayProductTab') && $this->registerHook('displayProductTabContent') && $this->_installTradDone()) { $shops = Shop::getContextListShopID(); $shop_groups_list = array(); /* Setup each shop */ foreach ($shops as $shop_id) { $shop_group_id = (int)Shop::getGroupFromShop($shop_id, true); if (!in_array($shop_group_id, $shop_groups_list)) $shop_groups_list[] = $shop_group_id; /* Sets up configuration */ Configuration::updateValue('SHOPITYPE_TAB', '16', false, $shop_group_id, $shop_id); } /* Sets up Shop Group configuration */ if (count($shop_groups_list)) foreach ($shop_groups_list as $shop_group_id) Configuration::updateValue('SHOPITYPE_TAB', '16', false, $shop_group_id); /* Sets up Global configuration */ Configuration::updateValue('SHOPITYPE_TAB', '16'); return true; } return false; } private function _installTradDone() { $query = ''; require_once(dirname(__FILE__).'/install/sql.tables.php'); $error = true; if (isset($query) && !empty($query)) { if (!($data=Db::getInstance()->ExecuteS( "SHOW TABLES LIKE '"._DB_PREFIX_."shopimultitab'" ))) { $query = str_replace( '_DB_PREFIX_', _DB_PREFIX_, $query ); $query = str_replace( '_MYSQL_ENGINE_', _MYSQL_ENGINE_, $query ); $db_data_settings = preg_split("/;\s*[\r\n]+/",$query); foreach ($db_data_settings as $query) { $query = trim($query); if (!empty($query)) if (!Db::getInstance()->Execute($query)) $error = false; } } } return $error; } /** * @see Module::uninstall() */ public function uninstall() { /* Deletes Module */ if (parent::uninstall()) return true; return false; } public function getContent() { $errors = array(); $this->_html .= $this->headerHTML(); $this->_html .= '<h2>'.$this->displayName.'.</h2>'; $shop_context = Shop::getContext(); if (Tools::isSubmit('submitSettings')) { $shop_groups_list = array(); $shops = Shop::getContextListShopID(); foreach ($shops as $shop_id) { $shop_group_id = (int)Shop::getGroupFromShop($shop_id, true); if (!in_array($shop_group_id, $shop_groups_list)) $shop_groups_list[] = $shop_group_id; $res = Configuration::updateValue('SHOPITYPE_TAB', (int)Tools::getValue('SHOPITYPE_TAB'), false, $shop_group_id, $shop_id); } /* Update global shop context if needed*/ switch ($shop_context) { case Shop::CONTEXT_ALL: $res = Configuration::updateValue('SHOPITYPE_TAB', (int)Tools::getValue('SHOPITYPE_TAB')); if (count($shop_groups_list)) { foreach ($shop_groups_list as $shop_group_id) $res = Configuration::updateValue('SHOPITYPE_TAB', (int)Tools::getValue('SHOPITYPE_TAB'), false, $shop_group_id); } break; case Shop::CONTEXT_GROUP: if (count($shop_groups_list)) { foreach ($shop_groups_list as $shop_group_id) $res = Configuration::updateValue('SHOPITYPE_TAB', (int)Tools::getValue('SHOPITYPE_TAB'), false, $shop_group_id); } break; } } if (Tools::isSubmit('submitSaveTab')) { $id_default_language = (int)Configuration::get('PS_LANG_DEFAULT'); $title_default = Tools::getValue('title_'.$id_default_language); if ($title_default) if (Tools::getValue('id_shopimultitab')) { if (Validate::isLoadedObject($obj = new Shopimultitab((int)Tools::getValue('id_shopimultitab')))) { $obj->active = Tools::getValue('active_tab'); $languages = Language::getLanguages(false); foreach ($languages as $language) if (Tools::getValue('title_'.$language['id_lang']) != '') $obj->title[$language['id_lang']] = Tools::getValue('title_'.$language['id_lang']); if (!$obj->update()) $errors[] = $this->l('Tabs could not be updated'); } else $errors[] = $this->l('Tabs could not be updated'); } else { $obj = new Shopimultitab(); $obj->active = Tools::getValue('active_tab'); $languages = Language::getLanguages(false); foreach ($languages as $language) if (Tools::getValue('title_'.$language['id_lang']) != '') $obj->title[$language['id_lang']] = Tools::getValue('title_'.$language['id_lang']); if (!$obj->add()) $errors[] = $this->l('Tabs could not be create'); } else $errors[] = $this->l('You have to enter title for default language'); if (count($errors)) $this->_html .= $this->displayError(implode('<br />', $errors)); else Tools::redirectAdmin($this->base_config_url); } elseif (Tools::getIsset('changeStatus')) { $obj = new Shopimultitab((int)Tools::getValue('id_shopimultitab')); if ($obj->active == 0) $obj->active = 1; else $obj->active = 0; $res = $obj->update(); $this->_html .= ($res ? $this->displayConfirmation($this->l('Status updated')) : $this->displayError($this->l('Status could not be updated'))); } elseif (Tools::getIsset('deleteTab')) { $obj = new Shopimultitab((int)Tools::getValue('id_shopimultitab')); $res = $obj->delete(); if (!$res) $this->_html .= $this->displayError('Could not delete'); else $this->_html .= $this->displayConfirmation($this->l('Tab deleted')); } if (Tools::getIsset('addTab')) $this->_html .= $this->_displayForm(); else { $this->_html .= $this->renderForm(); $this->_html .= $this->_displayList(); } return $this->_html; } public function contentTabs($id_product) { $str = ''; require_once ( dirname(__FILE__).'/form.php' ); return $str; } public function strHook($module_name) { $hooks = HelperShopiMultiTab::getHooksByModuleName( $module_name ); $options = ''; if (!empty($hooks)) foreach ($hooks as $hook) $options .= '<option value="'.$hook['name'].'">'.$hook['name'].'</option>'; return $options; } public function renderForm() { $this->context->controller->addJS( ($this->_path).'views/js/config.js' ); $types = array( 0 => array('value' => '15', 'name' => $this->l('Like default tabs in PrestaShop 1.5')), 1 => array('value' => '16', 'name' => $this->l('Like default tabs in PrestaShop 1.6')), ); $img15 = _MODULE_DIR_.$this->name.'/views/img/15.png'; $img16 = _MODULE_DIR_.$this->name.'/views/img/16.png'; $fields_form = array( 'form' => array( 'legend' => array( 'title' => $this->l('Settings'), 'icon' => 'icon-cogs' ), 'input' => array( array( 'type' => 'select', 'label' => $this->l('Type of tabs:'), 'name' => 'SHOPITYPE_TAB', 'options' => array( 'query' => $types, 'id' => 'value', 'name' => 'name' ), 'desc' => '<br><div class="shopitype shopitype_15"><img src="'.$img15.'" alt="15"/></div> <div class="shopitype shopitype_16"><img src="'.$img16.'" alt="16"/></div>' ) ), 'submit' => array( 'title' => $this->l('Save'), ) ), ); $helper = new HelperForm(); $helper->show_toolbar = false; $helper->table = $this->table; $lang = new Language((int)Configuration::get('PS_LANG_DEFAULT')); $helper->default_form_language = $lang->id; $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0; $this->fields_form = array(); $helper->identifier = $this->identifier; $helper->submit_action = 'submitSettings'; $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name; $helper->token = Tools::getAdminTokenLite('AdminModules'); $helper->tpl_vars = array( 'fields_value' => $this->getConfigFieldsValues(), 'languages' => $this->context->controller->getLanguages(), 'id_language' => $this->context->language->id ); return $helper->generateForm(array($fields_form)); } public function getConfigFieldsValues() { $id_shop_group = Shop::getContextShopGroupID(); $id_shop = Shop::getContextShopID(); return array( 'SHOPITYPE_TAB' => Tools::getValue('SHOPITYPE_TAB', Configuration::get('SHOPITYPE_TAB', null, $id_shop_group, $id_shop)), ); } public function _displayList() { $obj = new Shopimultitab(); $tabs = $obj->getTabs(); foreach ($tabs as $key => $slide) $tabs[$key]['status'] = $this->displayStatus($slide['id_shopimultitab'], $slide['active']); $this->context->smarty->assign( array( 'link' => $this->context->link, 'tabs' => $tabs ) ); return $this->display(__FILE__, 'list.tpl'); } public function _displayForm() { $fields_form = array( 'form' => array( 'legend' => array( 'title' => $this->l('Tab information'), 'icon' => 'icon-cogs' ), 'input' => array( array( 'type' => 'text', 'label' => $this->l('Tab Title'), 'name' => 'title', 'lang' => true, ), array( 'type' => 'switch', 'label' => $this->l('Enabled'), 'name' => 'active_tab', 'is_bool' => true, 'values' => array( array( 'id' => 'active_on', 'value' => 1, 'label' => $this->l('Yes') ), array( 'id' => 'active_off', 'value' => 0, 'label' => $this->l('No') ) ), ), ), 'submit' => array( 'title' => $this->l('Save'), ) ), ); if (Tools::isSubmit('id_shopimultitab') && $this->slideExists((int)Tools::getValue('id_shopimultitab'))) { $slide = new Shopimultitab((int)Tools::getValue('id_shopimultitab')); $fields_form['form']['input'][] = array('type' => 'hidden', 'name' => 'id_shopimultitab'); } $helper = new HelperForm(); $helper->show_toolbar = false; $helper->table = $this->table; $lang = new Language((int)Configuration::get('PS_LANG_DEFAULT')); $helper->default_form_language = $lang->id; $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0; $this->fields_form = array(); $helper->module = $this; $helper->identifier = $this->identifier; $helper->submit_action = 'submitSaveTab'; $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name; $helper->token = Tools::getAdminTokenLite('AdminModules'); $language = new Language((int)Configuration::get('PS_LANG_DEFAULT')); $helper->tpl_vars = array( 'base_url' => $this->context->shop->getBaseURL(), 'language' => array( 'id_lang' => $language->id, 'iso_code' => $language->iso_code ), 'fields_value' => $this->getAddFieldsValues(), 'languages' => $this->context->controller->getLanguages(), 'id_language' => $this->context->language->id ); return $helper->generateForm(array($fields_form)); } public function displayStatus($id_shopimultitab, $active) { $title = ((int)$active == 0 ? $this->l('Disabled') : $this->l('Enabled')); $img = ((int)$active == 0 ? 'disabled.gif' : 'enabled.gif'); $html = '<a href="'.AdminController::$currentIndex. '&configure='.$this->name.' &token='.Tools::getAdminTokenLite('AdminModules').' &changeStatus&id_shopimultitab='.(int)$id_shopimultitab.'" title="'.$title.'"><img src="'._PS_ADMIN_IMG_.''.$img.'" alt="" /></a>'; return $html; } public function getAddFieldsValues() { $fields = array(); if (Tools::isSubmit('id_shopimultitab') && $this->slideExists((int)Tools::getValue('id_shopimultitab'))) { $slide = new Shopimultitab((int)Tools::getValue('id_shopimultitab')); $fields['id_shopimultitab'] = (int)Tools::getValue('id_shopimultitab', $slide->id); } else $slide = new Shopimultitab(); $fields['active_tab'] = Tools::getValue('active_tab', $slide->active); $fields['has_picture'] = true; $languages = Language::getLanguages(false); foreach ($languages as $lang) $fields['title'][$lang['id_lang']] = Tools::getValue('title_'.(int)$lang['id_lang'], $slide->title[$lang['id_lang']]); return $fields; } public function slideExists($id_shopimultitab) { $req = 'SELECT hs.`id_shopimultitab` FROM `'._DB_PREFIX_.'shopimultitab` hs WHERE hs.`id_shopimultitab` = '.(int)$id_shopimultitab; $row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($req); return ($row); } public function headerHTML() { if (Tools::getValue('controller') != 'AdminModules' && Tools::getValue('configure') != $this->name) return; $this->context->controller->addJqueryUI('ui.sortable'); /* Style & js for fieldset 'slides configuration' */ $html = '<script type="text/javascript"> $(function() { var $myTabs = $("#tabs"); $myTabs.sortable({ opacity: 0.6, cursor: "move", update: function() { var order = $(this).sortable("serialize") + "&task=updatePosition"; $.post("'.$this->context->shop->physical_uri.$this->context->shop->virtual_uri.'modules/'.$this->name.'/ajax.php?secure_key='.$this->secure_key.'", order); } }); $myTabs.hover(function() { $(this).css("cursor","move"); }, function() { $(this).css("cursor","auto"); }); }); </script>'; return $html; } public function hookdisplayBackOfficeHeader() { return '<link href="'._MODULE_DIR_.$this->name.'/views/css/admin.css" rel="stylesheet" type="text/css" media="all" />'; } public function hookactionProductSave($params) { $tabs = Shopimultitab::getTabs(); $languages = Language::getLanguages(false); $content = array(); if (!$tabs) return true; foreach ($tabs as $tab) { $content_text = array(); foreach ($languages as $lang) $content_text[$lang['id_lang']] = Tools::getValue('shopicontent_text_'.$tab['id_shopimultitab'].'_'.$lang['id_lang']); if (Tools::getValue('id_shopimultitab_content_'.$tab['id_shopimultitab'])) $obj = new ShopimultitabContent((int)Tools::getValue('id_shopimultitab_content_'.$tab['id_shopimultitab'])); else $obj = new ShopimultitabContent(); $obj->id_shopimultitab = $tab['id_shopimultitab']; $obj->id_product = $params['id_product']; $obj->content_text = $content_text; $obj->categories = Tools::getValue('categories_'.$tab['id_shopimultitab']); $obj->global = (int)Tools::getValue('global_'.$tab['id_shopimultitab']); $shopimodule = Tools::getValue('shopimodule_'.$tab['id_shopimultitab'], ''); $shopihook = Tools::getValue('shopihook_'.$tab['id_shopimultitab'], ''); if ($shopimodule && $shopihook) $obj->content = $shopimodule.':'.$shopihook; if (Tools::getValue('id_shopimultitab_content_'.$tab['id_shopimultitab'])) $obj->update(); else if (!(ShopimultitabContent::checkExist( $tab['id_shopimultitab'], $params['id_product'] ))) $obj->add(); } } public function hookactionProductDelete($params) { if (!$params['id_product']) return ''; $shopicontent = ShopimultitabContent::getContents(null, $params['id_product']); if (!$shopicontent) return ''; foreach ($shopicontent as $content) { $obj = new ShopimultitabContent($content['id_shopimultitab_content']); $obj->delete(); } } public function hookdisplayBackOfficeFooter() { $this->context->smarty->assign(array( 'back_url' => _MODULE_DIR_.$this->name.'/ajax.php?secure_key='.$this->secure_key, 'shopi_id_product' => (int)Tools::getValue('id_product') )); if (Tools::strtolower(Tools::getValue('controller')) == Tools::strtolower('adminproducts')) return $this->display(__FILE__, 'backofficefooter.tpl' ); return ''; } public function getGlobalContent($global_contents, $categories) { if ($global_contents) { foreach ($global_contents as $global_content) { $gcategories = $global_content['categories']; if ($gcategories) { $gcategories = explode(',', $gcategories); foreach ($gcategories as $id_category) if (in_array($id_category, $categories)) return $global_content; } } } return false; } public function hookdisplayProductTab() { if (!$this->tabcontent) { $id_product = (int)(Tools::getValue('id_product')); $tabs = Shopimultitab::getTabs( true ); if (!$tabs) return ''; foreach ($tabs as &$tab) { $categories = Product::getProductCategories($id_product); $global_contents = ShopimultitabContent::getContents($tab['id_shopimultitab'], null, true); $content = $this->getGlobalContent($global_contents, $categories); if (!$content) $content = ShopimultitabContent::getContent($tab['id_shopimultitab'], $id_product); if ($content) { $content['module'] = HelperShopiMultiTab::execModule($content['content']); if ($content['module'] || $content['content_text']) $tab['contenttab'] = $content; } } $this->tabcontent = $tabs; } if (!$this->tabcontent) return ''; $this->context->smarty->assign(array( 'shopimultitabs_tabs' => $this->tabcontent )); if (Configuration::get('SHOPITYPE_TAB') == 15) return $this->display(__FILE__, 'producttabs.tpl'); else return $this->display(__FILE__, 'producttabs16.tpl'); } public function hookdisplayProductTabContent() { $this->context->controller->addCSS( ($this->_path).'views/css/style.css', 'all' ); if (!$this->tabcontent) { $tabs = Shopimultitab::getTabs( true ); if (!$tabs) return ''; $id_product = Tools::getValue('id_product'); foreach ($tabs as &$tab) { $categories = Product::getProductCategories($id_product); $global_contents = ShopimultitabContent::getContents($tab['id_shopimultitab'], null, true); $content = $this->getGlobalContent($global_contents, $categories); if (!$content) $content = ShopimultitabContent::getContent($tab['id_shopimultitab'], $id_product); if ($content) { $content['module'] = HelperShopiMultiTab::execModule($content['content']); if ($content['module'] || $content['content_text']) $tab['contenttab'] = $content; } } $this->tabcontent = $tabs; } if (!$this->tabcontent) return ''; $this->context->smarty->assign(array( 'shopimultitabs_tabs' => $this->tabcontent )); if (Configuration::get('SHOPITYPE_TAB') == 15) return $this->display(__FILE__, 'producttabscontent.tpl'); return ''; } } <file_sep>/ps_modules/modules_src/shopimultitabs/ajax.php <?php /** * Shopi Multiple Tabs In Product Module * * @author ShopiTheme; * @copyright Copyright (C) October 2013 prestabrain.com <@emai:<EMAIL>>; * @license GNU General Public License version 2; */ include_once('../../config/config.inc.php'); include_once('../../init.php'); include_once( dirname(__FILE__).'/shopimultitabs.php' ); $obj = new shopimultitabs(); if (Tools::getValue('secure_key') == $obj->secure_key && Tools::getValue('task') == 'tab') { $tabs = Shopimultitab::getTabs(); $str = ''; if ($tabs) { foreach ($tabs as $tab) $str .= '<a class="list-group-item shopi-tab-row" href="javascript:void(0)" id="link-shopi-tab-'.$tab['id_shopimultitab'].'" rel="shopi-tab-'.$tab['id_shopimultitab'].'">'.$tab['title'].'</a>'; } die($str); } if (Tools::getValue('secure_key') == $obj->secure_key && Tools::getValue('task') == 'content') { $id_product = Tools::getValue('id_product'); $str = $obj->contentTabs($id_product); die('<script type="text/javascript" src="'._MODULE_DIR_.$obj->name.'/views/js/general.js"></script>'.$str); } if (Tools::getValue('secure_key') == $obj->secure_key && Tools::getValue('task') == 'updatePosition') { $tabs = Tools::getValue('tabs'); foreach ($tabs as $position => $id_shopimultitab) { $res = Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.'shopimultitab` SET `position` = '.(int)$position.' WHERE `id_shopimultitab` = '.(int)$id_shopimultitab ); } } if (Tools::getValue('secure_key') == $obj->secure_key && Tools::getValue('task') == 'gethook') { $module_name = Tools::getValue('module_name'); $str = $obj->strHook($module_name); die($str); } <file_sep>/ps_modules/modules_src/shopimultitabs/defines.php <?php /** * Shopi Multiple Tabs In Product Module * * @author ShopiTheme; * @copyright Copyright (C) October 2013 prestabrain.com <@emai:<EMAIL>>; * @license GNU General Public License version 2; */ define('SHOPI_MULTITAB_MODULE_NAME', 'shopimultitabs'); <file_sep>/ps_modules/modules_src/shopimultitabs/Readme.md # Shopi Multiple Product Tab Module ## About Shopi Multiple Product Tab Module, extra tab
e91b3065b037730902c5dc6ab90090e2594b3e21
[ "Markdown", "Text", "PHP" ]
14
PHP
krainet/ps_resources
b8ae716b56c4eb98264bf214bded291a335c646d
66a0d6e4fb2abf093a92c8e2283a0238a018e35d
refs/heads/master
<repo_name>davidfindley19/macOS-Management<file_sep>/README.md # Mac Management Scripts A collection of scripts to manage/install software on Macs # OSX_Test_Menu A script that allows you to select from a menu different administration tasks. At the time of this being written, Office 2016 needed to be manually installed from a local source. # Adobe Install At the time of this being written, there was some confusion around whether or not all Macs deployed needed Adobe. The installs were too big for network installs, so this allows you to install from a local source such as a USB drive. # NFS_Software_Install This was a test script written to see if we could store all software on a centralized repo and have it install. This centralized repo is Windows based and mounts it as such. # JAMF_Update This was written to help with the enrollment process of the Macs in our environment. Some older machines don't check in as quickly as needed. This allows us to keep an always updated install of the JAMF package on a network location and manually install/policy updates. <file_sep>/JAMF_Update_New.sh #!/bin/sh # Purpose: To simplify the DEP enrollment process for Macs. # Author: <NAME> # Date: December 20, 2017 [Updated 04-03-2019] # Version: 1.4 # Change Log: #1.3 - Removed local requirement. Cleaned up code. #1.4 - Updated mount command to mount -t # Verifying that user is running the scrip with elevated permissions. if [ "$USER" != "root" ]; then echo "************************************" echo "You are attempting to execute this process as user $USER" echo "Please execute the script with elevated permissions." exit 1 fi clear #Now we need to authenticate with domain credentials. echo "We need to authenticate with your tech account domain credentials to proceed: " read -p 'Please enter your network username:' domainusername read -s -p 'Please enter your AD password: ' domainpass clear #Install of the Location-Specific Quick Add package function jamf_install() { # We need to check that JAMF is installed. If it is, then it will force a check in. echo "\nChecking that JAMF is installed." if [ ! -f /usr/local/bin/jamf ]; then echo "\nJAMF is not installed. Attempting to install." mkdir /Volumes/MacInstalls echo "\nMounting remote network location." mount -t smbfs //$domainusername:$domainpass@servername/MacInstalls /Volumes/MacInstalls /usr/sbin/installer -pkg /Volumes/MacInstalls/Jamf/QuickAdd.pkg -target "/" echo "\nJAMF has been installed." umount /Volumes/MacInstalls else echo "\nJAMF is installed. Checking in with the JSS server." /usr/local/bin/jamf recon /usr/local/bin/jamf policy fi } ## Used to force the machine to check in with JSS function recon() { echo "\nChecking in with JSS" jamf recon } # Force policy retrieval - like gpupdate, but for Macs. function policy() { echo "\nForcing policy retrieval for machine" jamf policy } function do_all() { jamf_install recon policy clear } # Have this as a hidden feature to remove the JAMF software function remove_jamf() { jamf removeFramework clear } function read_options() { local choice read -p "Choose and option: " number case $number in 1) do_all ;; 2) jamf_install ;; 3) recon ;; 4) policy ;; 5) exit 0 ;; 6) remove_jamf ;; # Was a "hidden" menu option to remove the JAMF Framework. esac } function menu() { echo "*********************************************" echo "1) Install JAMF QuickAdd and update policies " echo "2) Install JAMF QuickAdd Package Only " echo "3) Run Recon Tool for JAMF " echo "4) Update JAMF Policies " echo "5) Exit " } while true do menu read_options done <file_sep>/OSX_Test_Menu.sh !/bin/sh echo echo "Garmin Mac Deployment Script" echo "Authors: <NAME>, <NAME>, <NAME>" #echo "Purpose: Apple laptop deployment " echo "Date: January 17, 2016 " echo "Version: 2.2.4" echo # Version 1.2 - Fixed some issues with spacing and responses are recognized as lower and uppercase. # Version 2.0 - Removed the menu option for installing Adobe CC products. Also introduced the any case answer. # Version 2.2 - Added the option to install Office updates only. Office installers updated to 15.17.0. 15.17.1 for Word and Outlook # due to crashing. # Version 2.2.1 - Added January security updates. Bringing the versions to 15.18.0 # Version 2.2.3 - Cleaned up code. Simplified Office update functions. Rearranged menu to make it more functional. # Version 2.2.3 - Disable Office 2016 for Mac first run prompt # We need to execute as root to get some of this done. # If the executing user is not root, the script will exit with code 1. if [ "$USER" != "root" ]; then echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" echo "You are attempting to execute this process as user $USER" echo "Please execute the script with elevated permissions." exit 1 fi ### Standard parameters # Truncated hardware serial. Collect last 7 characters of serial to match Dell service tag standard. truncserial=`ioreg -c IOPlatformExpertDevice -d 2 | awk -F\" '/IOPlatformSerialNumber/{print substr($(NF-1),1+length($(NF-1))-7)}'` # Regional hostname prefix. regionprefix="OLA-" # Combine $regionprefix and $truncserial for a standard hostname. localhostname=$regionprefix$truncserial-MAC # Fully qualified DNS name of Active Directory domain. domain="enter domain name" # Distinguished name of intended container for this computer. ou="Enter default OU path" # Name of network time server. Used to synchronize clocks. networktimeserver="time server" ### Advanced options # 'enable' or 'disable' automatic multi-domain authentication. alldomains="enable" # 'enable' or 'disable' force home directory to local disk. localhome="enable" # 'afp' or 'smb' change how home is mounted from server. protocol="smb" # 'enable' or 'disable' mobile account support for offline logon. mobile="enable" # 'enable' or 'disable' warn the user that a mobile account will be created. mobileconfirm="disable" # 'enable' or 'disable' use AD SMBHome attribute to determine the home directory. useuncpath="disable" # Configure local shell. e.g., /bin/bash or "none". user_shell="/bin/bash" # Use the specified server for all directory lookups and authentication. # (e.g. "-nopreferred" or "-preferred ad.server.edu") #preferred="-nopreferred" preferred="preferred domain" # Comma-separated AD groups and users to be admins ("" or "DOMAIN\groupname"). admingroups="default admin groups to be used" ### End of configuration function function_menu() { echo "*******************************************" echo "Menu:" echo echo "1. Join a Mac to the domain " echo "2. Disconnect a Mac from the domain " echo "3. Reinstall OS X Yosemite " echo "4. Add User Only " echo "5. Install Office 2016 for Mac " echo "6. Install Office 2016 for Mac Security Updates " echo "7. System Summary " echo "8. Exit " } function read_options() { local choice read -p "Make a selection: " number case $number in 1) ad_bind ;; 2) forceunbind ;; 3) install_osx ;; 4) admin_only ;; 5) office_install ;; 6) office_2016_update ;; 7) summary ;; 8) exit 0 ;; esac } function basic_settings() { ### Basic configuration echo "Prompting for basic details" # Prompt for local hostname - written just after configuration. #localhostname=`/usr/sbin/scutil --get LocalHostName` #read -p "What is this computer's name? " localhostname # Prompt for end-user local admin. echo "Enter the AD usernames of the people who will be local admins" read -p "You MUST separate the usernames with spaces: " localadmins # Authenticate with privileged AD credentials (probably YOURS!). echo "Prompting for *YOUR* AD credentials." # Here we'll ask for a privileged AD username. read -p "Enter *YOUR* AD username: " domainadmin # And here we'll ask for the password of that privileged AD username. read -s -p "Enter *YOUR* AD password: " password echo "" } function ad_bind() { # Running prompt for basic account settings. basic_settings # Set network time server to prevent errors during binding attempts. # We should test for the existence of /etc/ntp.conf before we define the network time server. if [ -f /etc/ntp.conf ]; then echo "Setting network time server." sudo systemsetup setnetworktimeserver $networktimeserver else echo "Creating /etc/ntp.conf" sudo touch /etc/ntp.conf echo "Setting network time server." sudo systemsetup setnetworktimeserver $networktimeserver fi # Activate the AD plugin by updating DirectoryService preferences. echo "Updating DirectoryServices preferences to activate AD plugin." sudo defaults write /Library/Preferences/DirectoryService/DirectoryService "Active Directory" "Active" # Now we wait a few seconds to account for disk write delays and let OS X notice the new configuration. echo "Taking a nap for 5 seconds to let Directory Services to catch up." sleep 5 # Set HostName, LocalHostName, ComputerName, using value assigned in $localhostname. echo "Setting HostName, LocalHostName, and ComputerName as $localhostname." scutil --set HostName $localhostname scutil --set LocalHostName $localhostname scutil --set ComputerName $localhostname # Bind to AD with hostname defined above. echo "Binding computer to $domain as $localhostname." sudo dsconfigad -f -a $localhostname -domain $domain -u $domainadmin -p "$password" -ou "$ou" # Define local admin groups, to be listed in Directory Utility. # If no groups are defined in $admingroups, -nogroups option is used. if [ "$admingroups" = "" ]; then sudo dsconfigad -nogroups else echo "Configuring AD Groups with local admin privileges." sudo dsconfigad -groups "$admingroups" fi echo "Configuring mobile settings." sudo dsconfigad -alldomains $alldomains -localhome $localhome -protocol $protocol -mobile $mobile -mobileconfirm $mobileconfirm -useuncpath $useuncpath -shell $user_shell -preferred $preferred echo "Adding users as admins. " users summary } function users() { # Iterate through each username in @localadmins array to provision each user. for username in ${localadmins[@]} do # Create mobile account for user(s) specified in @localadmins. # Domain groups inherited as expected, i.e., members of SPECIFIC GROUP are admins. # Note: this will pass two odd messages to the CLI, this is a known bug in ManagedClient. echo "Creating mobile account for user $username." echo "Expect two odd messages here. They do not indicate an error." sudo /System/Library/CoreServices/ManagedClient.app/Contents/Resources/createmobileaccount -n "$username" # Add username(s) specified in @localadmins to local admin group - does not add to Directory Utility listing. echo "Adding user $username to local admin group." sudo dscl . -append /Groups/admin GroupMembership "$username" done } function admin_only() { basic_settings users } #Reinstalls OS X Yosemite function install_osx() { echo "This only applies to OS X Yosemite! " read -p "Are you sure you want to reinstall OS X? (Yes/No) " reinstall if [ $reinstall = Yes ] || [ $reinstall = yes ]; then ~/Documents/Test\ Scripts/Install\ OS\ X\ Yosemite.app/Contents/MacOS/InstallAssistant else echo "Returning to the main menu. " fi } function office_install() { read -p "Is Office 2016 okay to install? (Yes/No) " response if [ $response = yes ] || [ $response = Yes ]; then echo "Installing Office 2016 for Mac" echo echo /usr/sbin/installer -pkg ./"Microsoft_Office_2016.pkg" -target "/" office_2016_update echo "Disabling the application first run prompting" defaults write /Library/Preferences/com.microsoft.Excel kSubUIAppCompletedFirstRunSetup1507 -bool true defaults write /Library/Preferences/com.microsoft.onenote.mac kSubUIAppCompletedFirstRunSetup1507 -bool true defaults write /Library/Preferences/com.microsoft.Outlook kSubUIAppCompletedFirstRunSetup1507 -bool true defaults write /Library/Preferences/com.microsoft.Outlook FirstRunExperienceCompletedO15 -bool true defaults write /Library/Preferences/com.microsoft.PowerPoint kSubUIAppCompletedFirstRunSetup1507 -bool true defaults write /Library/Preferences/com.microsoft.Word kSubUIAppCompletedFirstRunSetup1507 -bool true echo echo "Package installation completed." elif [ $response = no ] || [ $response = No ]; then echo "Office 2016 is the only package this script supports. Please manually install Office 2011. " fi } #Obviously old versions of Office. function office_2016_update() { echo "***Installing Office 2016 updates***" echo echo "Installing Microsoft Autoupdate Update " echo /usr/sbin/installer -pkg ./"Microsoft_AutoUpdate_3.4.0_Updater.pkg" -target "/" echo echo "Installing Microsoft Excel 2016 update" echo /usr/sbin/installer -pkg ./"Microsoft_Excel_15.18.0_Updater.pkg" -target "/" echo echo "Installing Microsoft OneNote 2016 update" echo /usr/sbin/installer -pkg ./"Microsoft_OneNote_15.18.0_Updater.pkg" -target "/" echo echo "Installing Microsoft Outlook 2016 update" echo /usr/sbin/installer -pkg ./"Microsoft_Outlook_15.18.0_Updater.pkg" -target "/" echo echo "Installing Microsoft PowerPoint 2016 update" echo /usr/sbin/installer -pkg ./"Microsoft_PowerPoint_15.18.0_Updater.pkg" -target "/" echo echo "Installing Microsoft Word 2016 update" echo /usr/sbin/installer -pkg ./"Microsoft_Word_15.18.0_Updater.pkg" -target "/" echo } function summary() { # Sanity check. Rather than printing from variables, we'll query the system configuration for these values. #This part brought to you by Kyle's amazing knowledge of awk. echo "\n*** SUMMARY ***" echo "Hardware serial number:" ioreg -c IOPlatformExpertDevice -d 2 | awk -F\" '/IOPlatformSerialNumber/{print $(NF-1)}' echo "\nHostname:" scutil --get HostName # Print AD forest. echo "\nActive Directory forest:" dsconfigad -show | awk -F\= '/^Active Directory Forest/{gsub(/ /, ""); print $(NF)}' # Print AD domain, specified in $domain variable. echo "\nActive Directory domain:" dsconfigad -show | awk -F\= '/^Active Directory Domain/{gsub(/ /, ""); print $(NF)}' # Print preferred domain controller, specified in $preferred variable. echo "\nPreferred domain controller:" dsconfigad -show | awk -F\= '/Preferred Domain controller/{gsub(/ /, ""); print $(NF)}' # Print network time server and ntpd status. echo "\nNetwork time server:" sudo systemsetup getnetworktimeserver | awk '{print $(NF)}' echo "\nNetwork time status:" sudo systemsetup getusingnetworktime | awk '{print $(NF)}' # Print members of local "admin" group. echo "\nCurrent members of local \"admin\" group:" dscl . -read /Groups/admin GroupMembership | awk -F ' ' '{for (i=2; i<=NF; i++) print $i}' # Print allowed admin groups, specified in $admingroups variable. echo "\nAllowed admin groups:" dsconfigad -show | grep "Allowed admin groups" | sed -e $'s/.*= //;s/,/\\\n/g' } function forceunbind() { # Force unbind from domain. echo "\nForce unbinding $HOSTNAME from domain." dsconfigad -f -r $HOSTNAME -u $domainadmin -p $password # Sanity check. If "dsconfigad -show" returns nothing, unbinding was successful. if [ "$(dsconfigad -show)" = "" ]; then echo "\nForce unbinding successful." else echo "\nForce unbinding unsuccessful." fi } while true do function_menu read_options done <file_sep>/Adobe_Install.sh #!/bin/sh # We need to execute as root to get some of this done. # If the executing user is not root, the script will exit with code 1. if [ "$USER" != "root" ]; then echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" echo "You are attempting to execute this process as user $USER" echo "Please execute the script with elevated permissions!" exit 1 fi echo echo "Installing Adobe Creative Cloud for Mac" echo read -p "Which version of Adobe CC 2014 do you need installed? (Standard or Premium) " response if [[ $response == Standard ]]; then /usr/sbin/installer -pkg ./"Design Standard OS X_Install.pkg" -target "/" ; elif [[ $response == Premium ]]; then /usr/sbin/installer -pkg ./"Production Premium OS X_Install.pkg" -target "/" ; fi exit <file_sep>/JAMF_Update.sh #!/bin/sh # Purpose: To simplify the DEP enrollment process for Macs. # Author: <NAME> # Date: December 20, 2017 # Version: 1.1 # Removed the local storage requirement. if [ "$USER" != "root" ]; then echo "************************************" echo "You are attempting to execute this process as user $USER" echo "Please execute the script with elevated permissions." exit 1 fi clear # Now we need to authenticate with domain credentials echo "We need to authenticate with your domain credentials to proceed: " read -p 'Please enter your network username:' domainusername read -s -p 'Please enter your AD password: ' domainpass clear ### Begin Functions # Basic function to install the Quick Add pkg for JAMF. function jamf_install() { echo "\nInstalling the Quick Add package. This may take a few moments..." # Now we need to make a mount point for the NFS share. echo "\nMaking mount point directory" mkdir /Volumes/FOLDER echo "\nMounting remote network location" mount_smbfs "//$domainusername:$domainpass@FQDN/Scratch" /Volumes/FOLDER /usr/sbin/installer -pkg /Volumes/PATH/TO/DRIVE/QuickAdd.pkg -target "/" echo "\nThe JAMF Management software has been installed." echo "\nUnmounting network drive." umount /Volumes/scratch clear } # Used to force the machine to check in with JSS function recon() { echo "\nChecking in with JSS" jamf recon clear } # Force policy retrieval - like gpupdate, but for Macs. function policy() { echo "\nForcing policy retrieval for machine" jamf policy clear } function do_all() { jamf_install recon policy clear } # Have this as a hidden feature to remove the JAMF software function remove_jamf() { jamf removeFramework clear } ### Begin Menu Functions function read_options() { local choice read -p "Choose and option: " number case $number in 1) do_all ;; 2) jamf_install ;; 3) recon ;; 4) policy ;; 5) exit 0 ;; 6) remove_jamf ;; esac } function menu() { echo "**********************" echo "1) Install JAMF QuickAdd and update policies " echo "2) Install JAMF QuickAdd Package Only " echo "3) Run Recon Tool for JAMF " echo "4) Update JAMF Policies " echo "5) Exit " } while true do menu read_options done <file_sep>/NFS_Software_Install.sh #!/bin/sh # Purpose: Copy installer from remote, centralized software repo and install. # Author: <NAME> # Version: 1.0 ### As with all scripts, it needs to be ran as root. Checking credentials. if [ "$USER" != "root" ]; then echo "************************************" echo "You are attempting to execute this process as user $USER" echo "Please execute the script with elevated permissions." exit 1 fi # Now we need to authenticate with domain credentials read -p 'Please enter your network username:' domainusername read -s -p 'Please enter your AD password: ' domainpass function setup() { # Now we need to make a mount point for the NFS share. mkdir /Volumes/name of directory you want mounted to mount_smbfs "//$domainusername:$domainpass@FQDN/Share Name" /Volumes/name of directory you created #This was example software used. Really, any software that needs copied over to be installed can be inserted. echo "Copying over Skype For Business..." cp /Volumes/scratch/SCRATCH/Findley/SkypeForBusiness.pkg ~/Desktop echo "Copying over Microsoft Office 2016..." cp /Volumes/scratch/SCRATCH/Findley/Microsoft_Office.pkg ~/Desktop echo "Installing Skype for Business for Mac:" /usr/sbin/installer -pkg ~/Desktop/"SkypeForBusiness.pkg" -target "/" echo echo echo "Skype for Business is now installed." echo echo "Installing Microsoft Office 2016 for Mac:" echo /usr/sbin/installer -pkg ~/Desktop/"Microsoft_Office.pkg" -target "/" echo echo "Microsoft Office 2016 for Mac is now installed." #Trying to be responsible, I have it remove the install files for each package. #This could be simplified, but for testing I wanted to have it remove each one individually. echo "Removing install files. " rm ~/Desktop/Microsoft_Office.pkg rm ~/Desktop/SkypeForBusiness.pkg #The last step, it unmounts the network share you are working from. umount /Volumes/name of directory you created }
eb22d390acb881b8a8499150483b5447dcb9b402
[ "Markdown", "Shell" ]
6
Markdown
davidfindley19/macOS-Management
c7343e04ba4d6639887cc2c856243e91b81fc38e
b78b6974b1be7760ba4d710e2ee4cf265d00828e
refs/heads/master
<repo_name>hilalisa/statictemplate<file_sep>/statictemplate/statictemplate.go // Package statictemplate implements a code generator for converting text or html/template to Go code. package statictemplate
366805383997d8a10b01114aecfeb94ff77a592d
[ "Go" ]
1
Go
hilalisa/statictemplate
0148c1b698ea42cccc8c13cc0fff15556ef493d6
4208b0d807963df4f6de40884adf39b737e7b214
refs/heads/master
<repo_name>smilecool2012/Java-Laba8<file_sep>/Lab 8/src/com/company/Main.java package com.company; import java.lang.String; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.ParseException; import java.util.ArrayList; public class Main { public static void main(String[] args) throws ParseException, IOException { Car car; ArrayList<Machine> machines = new ArrayList<>(); machines.add(new Machine("Shkoda", "Miki", "Gavela", "AI3333", 613, true )); machines.add(new Machine("Audi", "Zago", "Shepeleva", "AB0000", 300, false)); car = new Car(machines); String fileName = "c:\\java2.txt"; car.saveToFile(fileName); ArrayList<Machine> carsFromFile = new ArrayList<>(); Car myCarsFromFile = new Car(carsFromFile); myCarsFromFile.loadFromFile(fileName); System.out.println("Список машин (з файлу):"); myCarsFromFile.printList(); } } <file_sep>/Lab10Mykytiuk/src/main/java/com/ntu/MyLab9/Entity/Parent.java package com.ntu.MyLab9.Entity; public class Parent { } <file_sep>/Lab10Mykytiuk/src/main/java/com/ntu/MyLab/main.java package com.ntu.MyLab; import com.ntu.MyLab.DAO.FlightDAO; import com.ntu.MyLab.DAO.FlightDAOimpl; import com.ntu.MyLab.Entity.AllEntitysParent; import com.ntu.MyLab.Entity.Flight; import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; import javafx.scene.text.Font; import javafx.stage.Stage; public class main extends Application{ private static Flight flightToUpdate; private TextField textFieldFlightFlightnumber; private TextField textFieldFlightOtpravlenie; private TextField textFieldFlightNaznachenie; private TextField textFieldFlightKolichestvoMest; private TextField textFieldFlightKolichestvoProdanuh; private TextField textFieldFlightStoimost; //Сама таблица private static TableView<AllEntitysParent> table; //Лист с данными из бд для таблицы private static ObservableList<AllEntitysParent> list = FXCollections.observableArrayList(); public static void main(String[] args) { launch(args); } public void start(Stage stage) throws Exception { createStartMenu(stage); } private void createStartMenu(Stage stage) { //////сцена////// AnchorPane root = new AnchorPane(); stage.setTitle("Lab 10"); Scene scene = new Scene(root, 500, 250); stage.setScene(scene); stage.show(); Label labelHello = UtilsUI.createLabel(root,"WELCOME!",30,30,550,100); labelHello.setFont(new Font("Arial", 70)); //////кнопка 1////// Button btnSubscribersTable = UtilsUI.createButton("Subscribers Table", 30, 200); btnSubscribersTable.setOnAction(event -> { createDialogMenu(stage); }); //////кнопка 2////// Button btnConversationTable = UtilsUI.createButton("Conversation Table", 330, 200); btnConversationTable.setOnAction(event -> { createDialogMenu(stage); }); //////добавление в root////// root.getChildren().addAll(btnSubscribersTable, btnConversationTable); } private void createDialogMenu(Stage generalStage) { //Создаем маленькое окошко AnchorPane root = createSmallStage(generalStage, "TableMenu"); //Добаляем кнопки menuWithTableAddButtons(root); //Добавляем поля для ввода информации menuWithTableAddInfoPickers(root); //Добаляем саму таблицу со значениями menuWithTableAddTables(root); } //////Штуки для диалогового окна с таблицей////// private void menuWithTableAddButtons(AnchorPane root) { Button btnUpdate = UtilsUI.createButton("Update", 240, 10); Button btnCreate = UtilsUI.createButton("Create", 240, 160); Button btnDelete = UtilsUI.createButton("Delete", 240, 110); Button btnSave = UtilsUI.createButton("Save Update", 240, 60); root.getChildren().addAll(btnCreate, btnUpdate, btnDelete, btnSave); //////setOnAction////// FlightDAO flightDAO = new FlightDAOimpl(); String regex = "[0-9]+"; btnUpdate.setOnAction(event -> { try { int selectedIndex = table.getSelectionModel().getSelectedIndex(); if (selectedIndex != -1) { //if (isItASubscriberTable) { flightToUpdate = (Flight) list.get(selectedIndex); textFieldFlightFlightnumber.setText(String.valueOf(flightToUpdate.getFlightnumber())); textFieldFlightOtpravlenie.setText(String.valueOf(flightToUpdate.getOtpravlenie())); textFieldFlightNaznachenie.setText(String.valueOf(flightToUpdate.getNaznachenie())); textFieldFlightKolichestvoMest.setText(String.valueOf(flightToUpdate.getKolichestvomest())); textFieldFlightKolichestvoProdanuh.setText(String.valueOf(flightToUpdate.getKolichestvoprodanuh())); textFieldFlightStoimost.setText(String.valueOf(flightToUpdate.getStoimost())); } //} else { // conversationToUpdate = (Conversation) list.get(selectedIndex); // // textFieldConversationSubWhoCall.setText(conversationToUpdate.getSubWhoCallId()); // textFielConversatinCalledSub.setText(conversationToUpdate.getCalledSubId()); //} } catch (ArrayIndexOutOfBoundsException e) { } }); btnCreate.setOnAction(event -> { // if (isItASubscriberTable) { Flight flight = new Flight();flight.setFlightnumber(Long.valueOf(textFieldFlightFlightnumber.getText())); flight.setOtpravlenie((textFieldFlightOtpravlenie.getText())); flight.setNaznachenie((textFieldFlightNaznachenie.getText())); flight.setKolichestvomest(Long.valueOf(textFieldFlightKolichestvoMest.getText())); flight.setKolichestvoprodanuh(Long.valueOf(textFieldFlightKolichestvoProdanuh.getText())); flight.setStoimost(Long.valueOf(textFieldFlightStoimost.getText())); flightDAO.insertFlight(flight); list.add(flight); /*} else { String numberSubWhoCall = textFieldConversationSubWhoCall.getText(); String numberCalledSub = textFielConversatinCalledSub.getText(); //validation and add if (numberSubWhoCall.length() == 7 & numberCalledSub.length() == 7) { if (numberSubWhoCall.matches(regex) & numberCalledSub.matches(regex)) { Conversation conversation = new Conversation(); conversation.setSubWhoCallId(numberSubWhoCall); conversation.setCalledSubId(numberCalledSub); //Проверяем существуют ли такие пользователи List<Subscriber> listWirhAllSubscribers = subscriberDAO.getAllSubscriber(); List<String> numbers = new ArrayList<😠); for (Subscriber s:listWirhAllSubscribers) { numbers.add(s.getNumber()); } if(numbers.contains(numberSubWhoCall)&numbers.contains(numberCalledSub)) { conversationDAO.insertConversation(conversation); list.add(conversation); }else { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("Ahtung"); alert.setHeaderText(null); alert.setContentText("Some testfields are not correct" + "\nTheu are real important"); alert.showAndWait(); } } else { System.out.println("в номере должны быть только цыфры"); } } else { System.out.println("неверная длина номера!"); } } */ }); btnDelete.setOnAction(event -> { try { int selectedIndex = table.getSelectionModel().getSelectedIndex(); if (selectedIndex != -1) { //if (isItASubscriberTable) { Flight subscriber = (Flight) list.get(selectedIndex); flightDAO.deleteFlight(subscriber.getId()); list.remove(selectedIndex); //} else { //Conversation conversation = (Conversation) list.get(selectedIndex); //conversationDAO.deleteConversation(conversation.getID()); //list.remove(selectedIndex); //} } } catch (ArrayIndexOutOfBoundsException e) { } }); btnSave.setOnAction(event -> { //if (isItASubscriberTable) { //DODELAT // //String oldSubNumber = subscriberToUpdate.getNumber(); // list.removeAll(subscriberToUpdate); // // subscriberToUpdate.setNumber(number); // if (textFieldSubAvailable.getText().equals("0")) { // subscriberToUpdate.setAvailable(false); // } else { // subscriberToUpdate.setAvailable(true); // } // // System.out.println(subscriberToUpdate.getNumber()); // subscriberDAO.updateSubscriber(subscriberToUpdate, oldSubNumber); // list.addAll(subscriberToUpdate); //} else { // String numberSubWhoCall = textFieldConversationSubWhoCall.getText(); // String numberCalledSub = textFielConversatinCalledSub.getText(); // // //validation and add // if (numberSubWhoCall.length() == 7 & numberCalledSub.length() == 7) { // if (numberSubWhoCall.matches(regex) & numberCalledSub.matches(regex)) { // // list.remove(conversationToUpdate); // // String id1 = conversationToUpdate.getSubWhoCallId(); // String id2 = conversationToUpdate.getCalledSubId(); // // conversationToUpdate.setSubWhoCallId(numberSubWhoCall); // conversationToUpdate.setCalledSubId(numberCalledSub); // // conversationDAO.updateConversation(conversationToUpdate,id1,id2); // list.add(conversationToUpdate); // // } else { // System.out.println("в номере должны быть только цыфры"); // } // } else { // System.out.println("неверная длина номера!"); // } //} }); } //////Штуки для диалогового окна с таблицей////// private void menuWithTableAddInfoPickers(AnchorPane root) { //if (isItASubscriberTable) { Label labelSubNumber = UtilsUI.createLabel(root, "Subscriber number", 50, 10, 150, 30); Label labelSubAvailable = UtilsUI.createLabel(root, "Subscriber Available(0 or 1)", 50, 90, 150, 30); textFieldSubName = UtilsUI.createTextField(50, 50, 150, 30); textFieldSubAvailable = UtilsUI.createTextField(50, 130, 150, 30); root.getChildren().addAll(textFieldSubName, textFieldSubAvailable); // } else { // Label conversationSubWhoCall = UtilsUI.createLabel(root, "Sub who call", 50, 10, 150, 30); // Label conversationCalledSub = UtilsUI.createLabel(root, "Called Sub", 50, 90, 150, 30); // // textFieldConversationSubWhoCall = UtilsUI.createTextField(50, 50, 150, 30); // textFielConversatinCalledSub = UtilsUI.createTextField(50, 130, 150, 30); // // root.getChildren().addAll(textFieldConversationSubWhoCall, textFielConversatinCalledSub); // } } //////Штуки для диалогового окна с таблицей////// private void menuWithTableAddTables(AnchorPane root) { table = new TableView<😠); table.setTranslateX(10); table.setTranslateY(250); list.clear(); table.setItems(readAllForDB()); if (isItASubscriberTable) { createTableColumn(table, "Number"); createTableColumn(table, "Available"); } else { createTableColumn(table, "ID"); createTableColumn(table, "SubWhoCallId"); createTableColumn(table, "CalledSubId"); } root.getChildren().addAll(table); } //////Вспомогательный для menuWithTableAddTables()////// private TableColumn<AllEntitysParent, String> createTableColumn( TableView<AllEntitysParent> table, String name) { TableColumn<AllEntitysParent, String> tmp = new TableColumn<😠name); tmp.setCellValueFactory(new PropertyValueFactory<😠name)); tmp.setPrefWidth(190); tmp.setStyle("-fx-alignment: CENTER;" ); table.getColumns().addAll(tmp); return tmp; } //////Вспомогательный для menuWithTableAddTables()////// private static ObservableList<AllEntitysParent> readAllForDB() { if (isItASubscriberTable) { SubscriberDAO subscriberDAO = new SubscriberDAOImpl(); List<Subscriber> subs = subscriberDAO.getAllSubscriber(); list.addAll(subs); } else { ConversationDAO conversationDAO = new ConversationDAOImpl(); List<Conversation> conversations = conversationDAO.getAllConversation(); list.addAll(conversations); } return list; } //////Диалоговое окно////// private static AnchorPane createSmallStage(Stage owner, String stageName) { Stage createStage = new Stage(); createStage.setTitle(stageName); createStage.initModality(Modality.WINDOW_MODAL); createStage.initOwner(owner); AnchorPane root = new AnchorPane(); Scene scene = new Scene(root, 410, 550); createStage.setScene(scene); createStage.show(); return root; } } <file_sep>/Lab10Mykytiuk/src/main/java/com/ntu/MyLab10/UtilsUI.java package com.ntu.MyLab10; import javafx.scene.control.*; import javafx.scene.layout.AnchorPane; import javafx.util.StringConverter; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class UtilsUI { //Методы создания елементов интерфейса public static CheckBox createCheckBox(String name, double x, double y){ CheckBox checkBox = new CheckBox(name); checkBox.setTranslateX(x); checkBox.setTranslateY(y); return checkBox; } public static Label createLabel(AnchorPane root, String text, double x, double y, double width, double height ){ Label label = new Label(); label.setPrefSize(width,height); AnchorPane.setLeftAnchor(label,x); AnchorPane.setTopAnchor(label,y); label.setText(text); root.getChildren().addAll(label); return label; } public static Button createButton(String name){ Button button = new Button(); button.setText(name); button.setPrefSize(120,50); return button; } public static Button createButton(String name,double x,double y){ Button button = new Button(); button.setText(name); button.setPrefSize(120,30); button.setTranslateX(x); button.setTranslateY(y); return button; } public static TextField createTextField(double x, double y, double width, double height ){ TextField textField = new TextField(); textField.setTranslateX(x); textField.setTranslateY(y); textField.prefHeight(height); textField.prefWidth(width); return textField; } public static SplitMenuButton createSplitMenuButton(String[] menuitems, String name, double x, double y){ MenuItem[] menuItem= new MenuItem[menuitems.length]; for(int i=0;i<menuitems.length;i++){ menuItem[i] = new MenuItem(menuitems[i].toString()); } SplitMenuButton splitMenuButton = new SplitMenuButton(menuItem); for(int i=0;i<menuitems.length;i++){ final int j = i; menuItem[i].setOnAction(event -> { splitMenuButton.setText(menuItem[j].getText()); }); } splitMenuButton.setText(name); splitMenuButton.setTranslateX(x); splitMenuButton.setTranslateY(y); splitMenuButton.setWrapText(true); return splitMenuButton; } public static DatePicker createDatePicker(double x,double y) { DatePicker datePicker = new DatePicker(); datePicker.setTranslateX(x); datePicker.setTranslateY(y); StringConverter<LocalDate> converter = new StringConverter<LocalDate>() { DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy.MM.dd"); @Override public String toString(LocalDate date) { if (date != null) { return dateFormatter.format(date); } else { return ""; } } @Override public LocalDate fromString(String string) { if (string != null && !string.isEmpty()) { return LocalDate.parse(string, dateFormatter); } else { return null; } } }; datePicker.setConverter(converter); datePicker.setPromptText("yyyy.mm.dd"); return datePicker; } }
cc7f7a9d56f48afa8fdbdd164fd515c4935ef6db
[ "Java" ]
4
Java
smilecool2012/Java-Laba8
24bdabe8b856fff5d676adbffb15d4c5bc443b0c
c1bc02f0c5dce74fa854a23f8112bb9ad0b703a4
refs/heads/master
<file_sep>import '../img/icon-34.png'; import '../img/icon-128.png'; // Blocked urls var urls = []; // Handle incoming connections chrome.extension.onConnect.addListener(port => { // Listen for a domain to block port.onMessage.addListener(url => { urls.push("*://*." + url + "/*") updateBlocks(); }); }); function updateBlocks() { if (urls.length > 0) chrome.webRequest.onBeforeRequest.addListener(() => ({cancel: true}), {urls: urls}, ['blocking']); } <file_sep><p align="center"> <img src="src/img/icon-128.png"> <h1 align="center">Blocker</h1> </p> > Website blocking Google Chrome extension - :no_entry_sign: harmful sites - :no_entry_sign: procrastination - :heavy_check_mark: focused - :heavy_check_mark: productivity ## Installation > Install yarn packages ``` yarn install ``` ## Clone - Clone this repo to your local machine using `https://github.com/gurveerdhindsa/blocker.git` ## Development ``` yarn start ``` To load extension in Chrome: - Go to chrome://extensions/ - Check 'Developer mode' - Click 'Load unpacked extension' - Select the build folder of this repo ## Support - Website at <a href="https://gurveerdhindsa.github.io/portfolio/" target="_blank">`gurveerdhindsa.github.io`</a> <file_sep>import "../css/popup.css"; var $ = require('jQuery'); /* Use Chrome background page to store HTML session */ chrome.runtime.getBackgroundPage(bg => { // Get previous session if(bg.sessionDataHTML){ document.body.innerHTML = bg.sessionDataHTML; } // Update the session to include changes setInterval(function(){ bg.sessionDataHTML = document.body.innerHTML },1000); /* Adding a blocked site */ $(".input").change(() => { $('.blocked-list').append('<li class="blocked-item"><p class="blocked-item--website">' + $(".input").val() + '</p></li>') // $('.blocked-list').append('<i class="blocked-item--delete fas fa-times" onclick=""></i></li>') // Validate the domain input is correct // "" // "" // "" // Clear the input field // $(".input").val('') // Establish connection with extension to send messages var port = chrome.extension.connect({ name: "Content script" }) // Pass the blocked domain to extension port.postMessage($(".input").val()); }); /* Removing a blocked site */ $(".blocked-item--delete").click(function() { console.log("item is being deleted...") }) })
c222cd733dce64896d1cd6ac0ad9bf72865130ea
[ "JavaScript", "Markdown" ]
3
JavaScript
gurveerdhindsa/blocker
234b286fc9e9414090e4c6bfe7b207932c03abc6
51ed0fa61b9b53c2330de18b1114fe3511ae9b89
refs/heads/master
<repo_name>Arkanoid01/MUDABlue2<file_sep>/src/main/java/it/univaq/disim/mudablue/matrix/MudaBlueRun2.java package it.univaq.disim.mudablue.matrix; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import org.apache.commons.math3.linear.RealMatrix; public class MudaBlueRun2 { public static void main(String[] args) throws Exception { /* * si crea la matrice dalle occorrenze e si fanno tutte le operazioni */ String path= "C:/repos"; File folder_path = new File(path); ArrayList<String> pathList = new ArrayList<String>(); File[] listOfRepos = folder_path.listFiles(); for(File elem:listOfRepos) { if(elem.listFiles().length<=1) { String[] subRepo = elem.list(); pathList.add(elem+"\\"+subRepo[0]); } else { File[] subListOfRepos = elem.listFiles(); for(File subelem:subListOfRepos) { pathList.add(subelem.toString()); } } } MatrixManager manager = new MatrixManager(); LSA lsa = new LSA(); System.out.println("creating matrix"); RealMatrix m = manager.createMatrix(); System.out.println("Numero di Termini: "+m.getRowDimension()); m = manager.cleanMatrix(m); System.out.println("Numero di Termini dopo pulizia: "+m.getRowDimension()); m = lsa.algorithm(m); /* * Similarity */ System.out.println("cosine similarity"); CosineSimilarity csm = new CosineSimilarity(); m = csm.CS(m); /* * scrittura su file */ File file = new File("results.txt"); FileWriter fileWriter = new FileWriter(file); for(int i=0; i<m.getRowDimension(); i++) { fileWriter.write(pathList.get(i)+" "+m.getRowMatrix(i).toString()+"\n"); } fileWriter.flush(); fileWriter.close(); DataRefinement dr = new DataRefinement(); folder_path = new File("results"); dr.refine(m,folder_path); } }
17971399e4c6620535b3c7e83c8e8332a6105fb1
[ "Java" ]
1
Java
Arkanoid01/MUDABlue2
476c41844acee70bf2b9b47e118075308178f617
9907867dbaf595b2e8566bfd3917b158490dc91f
refs/heads/master
<repo_name>sravi4701/plack<file_sep>/src/controller/Testsql.java package controller; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import getData.GetConnection; /** * Servlet implementation class Testsql */ @WebServlet("/Testsql") public class Testsql extends HttpServlet { private static final long serialVersionUID = 1L; /** * Default constructor. */ public Testsql() { // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); Connection cn = GetConnection.getCn(); String query = "select * from test"; try { Statement st = cn.createStatement(); ResultSet rs = st.executeQuery(query); while(rs.next()){ out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)); } cn.close(); } catch (Exception e) { System.out.println(e); } } }<file_sep>/src/controller/UploadPhoto.java package controller; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import getData.GetConnection; /** * Servlet implementation class UploadPhoto */ @WebServlet("/UploadPhoto") public class UploadPhoto extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public UploadPhoto() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String currentUser = request.getParameter("id"); Connection cn = GetConnection.getCn(); boolean flag = false; try{ String sql = "select image from dashboard where useremail=?"; PreparedStatement ps = cn.prepareStatement(sql); ps.setString(1, currentUser); ResultSet rs = ps.executeQuery(); Blob image = null; byte [] imgData = null; if(rs.next()){ image = rs.getBlob(1); if(image != null){ imgData = image.getBytes(1, (int)image.length()); // InputStream input = rs.getBinaryStream("photo"); OutputStream output = response.getOutputStream(); response.setContentType("image/gif"); output.write(imgData); } else{ flag=true; } } else{ flag=true; } if(flag){ response.setContentType("image/gif"); ServletOutputStream out; out = response.getOutputStream(); FileInputStream fin = new FileInputStream("/home/ravishankar/workspace/plack/WebContent/img/default.png"); BufferedInputStream bin = new BufferedInputStream(fin); BufferedOutputStream bout = new BufferedOutputStream(out); int ch =0; while((ch=bin.read())!=-1) { bout.write(ch); } bin.close(); fin.close(); bout.close(); out.close(); System.out.println("UploadPhoto.java: no record found"); } } catch(Exception e){ e.printStackTrace(); } } } <file_sep>/src/getData/GetConnection.java package getData; import java.sql.*; public class GetConnection{ static String driver = "com.mysql.jdbc.Driver"; static String url = "jdbc:mysql://localhost:3306/plack"; static String user = "root"; static String pass = "<PASSWORD>"; static Connection cn = null; public static Connection getCn(){ try{ Class.forName(driver); cn = DriverManager.getConnection(url, user, pass); } catch(Exception e){ System.out.println(e); } return cn; } }<file_sep>/README.md # plack ### A simple web presence of a person Built with Java web application tools like Servlet, JSP etc. <file_sep>/src/controller/FileUpload.java package controller; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.PreparedStatement; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.Part; import getData.GetConnection; /** * Servlet implementation class FileUpload */ @WebServlet("/FileUpload") @MultipartConfig(maxFileSize = 16177215) public class FileUpload extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public FileUpload() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession s = request.getSession(false); String currentUser = (String)s.getAttribute("email"); InputStream inputStream = null; Part filePart = request.getPart("photo"); System.out.println("FileUpload.java " + currentUser); if(filePart != null){ System.out.println(filePart.getName()); System.out.println(filePart.getSize()); System.out.println(filePart.getContentType()); inputStream = filePart.getInputStream(); } Connection cn = GetConnection.getCn(); try{ String sql = "update dashboard set image=? where useremail=?"; PreparedStatement ps = cn.prepareStatement(sql); if(inputStream != null){ ps.setBlob(1, inputStream); } ps.setString(2, currentUser); int c = ps.executeUpdate(); if(c > 0){ System.out.println("sucess"); response.sendRedirect("Profile.jsp"); } else{ System.out.println("FileUpload.java : " + "no record found"); } } catch(Exception e){ e.printStackTrace(); } } }
cfef0a268ef6ef994a4370beb7ce6ed872b1e5b4
[ "Markdown", "Java" ]
5
Java
sravi4701/plack
880a7fd8f0ad005b13dfc5ffab962d74bec8a6b6
d5a7f2ae88250d33250703f5e1344e6008d5cff3
refs/heads/master
<repo_name>ddana0909/cats<file_sep>/Scripts/pisicute.js var pisica1= [[0,0,0,0,5,0,0,0,2,0], [0,0,0,0,1,1,1,1,1,0], [0,0,0,0,1,6,1,6,1,0], [0,0,0,0,1,1,1,1,1,0], [1,1,3,0,0,1,1,1,0,0], [1,0,0,0,0,0,1,0,0,0], [1,0,0,0,1,1,1,1,1,0], [1,0,0,1,1,1,1,1,1,0], [1,0,-1,1,1,1,1,1,1,0], [1,0,1,1,1,0,0,1,1,0], [4,1,1,1,1,1,0,1,1,1], [0,0,1,1,1,0,0,1,1,0] ]; var pisica2= [[0,2,0,0,0,5,0,0,0,0], [0,1,1,1,1,1,0,0,0,0], [0,1,6,1,6,1,0,0,0,0], [0,1,1,1,1,1,0,0,0,0], [0,0,1,1,1,0,0,5,1,1], [0,0,0,1,0,0,0,0,0,1], [0,1,1,1,1,1,0,0,0,1], [0,1,1,1,1,1,1,0,0,1], [0,1,1,1,1,1,1,1,0,1], [0,1,1,0,0,1,1,1,0,1], [-1,-1,1,0,-1,-1,1,1,1,3], [0,1,1,0,0,1,1,1,0,0] ]; var canvas; const cat1X=0; const cat1Y=390; const cat2X=0; const cat2Y=30; var dimPat=30; window.addEventListener('load', OnLoad, false); function addline(name,i,j,stx,sty) { function addAll(pisica) { if (j == 0 && pisica[i][j] == 1 || ((pisica[i][j] == 1|| pisica[i][j]==2) && (pisica[i][j - 1] == 0 || pisica[i][j - 1] == -1))) canvas.add(makeLine([sty + j * dimPat-4, (i - 1) * dimPat + 0.5 * dimPat-1, sty + j * dimPat-4, i * dimPat + 0.5 * dimPat], 3)); if (j == 9 && pisica[i][j] == 1 || ((pisica[i][j] == 1||pisica[i][j] == 5) && (pisica[i][j + 1] == 0||pisica[i][j + 1] == -1))) canvas.add(makeLine([sty + j * dimPat+dimPat, (i - 1) * dimPat + 0.5 * dimPat-1, sty + j * dimPat+dimPat, i * dimPat + 0.5 * dimPat], 3)); if (i == 0 && pisica[i][j] == 1 || ((pisica[i][j] == 1||pisica[i][j] == 3||pisica[i][j] == 4) && (pisica[i-1][j] == 0||pisica[i-1][j] == -1))) canvas.add(makeLine([sty + (j-1) * dimPat+0.5*dimPat, i* dimPat-3 , sty + j * dimPat+0.5*dimPat, i * dimPat-3 ], 3)); if (i == 11 && pisica[i][j] == 1 || ((pisica[i][j] == 1||pisica[i][j] == 5||pisica[i][j] == 2) && (pisica[i+1][j] == 0 || pisica[i+1][j] == -1))) canvas.add(makeLine([sty + (j-1) * dimPat+0.5*dimPat, (i+1)* dimPat , sty + j * dimPat+0.5*dimPat, (i+1) * dimPat ], 3)); } if(name=='cat1') { addAll(pisica1); } if(name=='cat2') { addAll(pisica2); } } function square(name,i,j,color) { var startX,startY; if(name=='cat1') { startX=cat1X; startY=cat1Y; addline(name,i,j,startX,startY); } if(name=='cat2') { startX=cat2X; startY=cat2Y; addline(name,i,j,startX,startY); } if(color==null) { color='rgba(255,0,0,0.5)'; } if(color=='white') var rect= new fabric.Rect({ width: dimPat-6, height: dimPat-6, left: startY+j*dimPat+3, top: startX+i*dimPat+3, fill: color }); else var rect= new fabric.Rect({ width: dimPat, height: dimPat, left: startY+j*dimPat, top: startX+i*dimPat, fill: color }); rect.i=i; rect.j=j; rect.cat=name; return rect; } function triangle(name,i,j,angle) { var startX,startY; if(name=='cat1') {startX=cat1X; startY=cat1Y; addline(name,i,j,startX,startY); } if(name=='cat2') {startX=cat2X; startY=cat2Y; addline(name,i,j,startX,startY); } var points; if(angle==0) {points = [ {x: 0, y: 0}, {x: dimPat, y: dimPat}, {x: 0, y: dimPat} ]; canvas.add(makeLine([startY+j*dimPat-0.5*dimPat, startX+i*dimPat-0.5*dimPat-2, startY+j*dimPat+dimPat-0.5*dimPat, startX+i*dimPat+dimPat-2-0.5*dimPat],4)); } if(angle==180) { points = [ {x: dimPat, y: dimPat}, {x: dimPat, y: 0}, {x: 0, y: 0} ]; canvas.add(makeLine([startY+j*dimPat-0.5*dimPat, startX+i*dimPat-0.5*dimPat-2, startY+j*dimPat+dimPat-0.5*dimPat, startX+i*dimPat+dimPat-2-0.5*dimPat],4)); } if(angle==90) { points = [ {x: 0, y: 0}, {x: dimPat, y: 0}, {x: 0, y: dimPat} ]; canvas.add(makeLine([startY+j*dimPat-0.5*dimPat, startX+i*dimPat-0.5*dimPat+dimPat, startY+j*dimPat+dimPat-0.5*dimPat, startX+i*dimPat-0.5*dimPat],4)); } if(angle==270) {points = [ {x: dimPat, y: 0}, {x: dimPat, y: dimPat}, {x: 0, y: dimPat} ]; canvas.add(makeLine([startY+j*dimPat-0.5*dimPat, startX+i*dimPat-0.5*dimPat-6+dimPat, startY+j*dimPat+dimPat-0.5*dimPat, startX+i*dimPat-6-0.5*dimPat],4)); } var trg= new fabric.Polygon(points, { left: startY+j*dimPat, top: startX+i*dimPat, fill: 'rgba(255,0,0,0.5)', selectable: false }); trg.i=i; trg.j=j; trg.cat=name; return trg; } function OnLoad() { canvas = new fabric.Canvas('can', { hoverCursor: 'pointer', selection: false}); canvas.setWidth(750); canvas.setHeight(380); initObjects(); canvas.renderAll(); canvas.on({ 'mouse:down' : Verify, 'mouse:up' : VerifyMatrix }); } function fix(obj) { obj.hasControls = obj.hasBorders = false; obj.lockMovementX=obj.lockMovementY=true; obj.selectable= false; return obj; } function initCat(pisicaModel,name) { var cat1 = []; for (var i = 0; i < 12; i++) for (var j = 0; j < 10; j++) switch (pisicaModel[i][j]) { case -1: cat1.push(fix(square(name, i, j, 'white'))); break; case 1: cat1.push(fix(square(name, i, j))); break; case 2: cat1.push(fix(triangle(name, i, j, 0))); break; case 3: cat1.push(triangle(name, i, j, 90)); break; case 4: cat1.push(triangle(name, i, j, 180)); break; case 5: cat1.push(triangle(name, i, j, 270)); break; case 6: cat1.push(fix(square(name, i, j, 'purple'))); break; } return cat1; } function makeLine(coords, width) { if(width==null) width=1; return new fabric.Line(coords, { fill: 'grey', stroke: 'grey', strokeWidth: width, selectable: false }); } function initGrid(height,width) { var x=[]; for(var i=0;i<=width/dimPat;i++) x.push(makeLine([i*dimPat-1,-height,i*dimPat,height])); for(var i=0;i<=height/dimPat;i++) x.push(makeLine([-width,i*dimPat-1,width,i*dimPat])); return x; } function initObjects() { var cat1=[]; cat1=initCat(pisica1,'cat1'); var cat2=[]; cat2=initCat(pisica2,'cat2'); var lines=[]; lines=initGrid(360,750); for (var i in cat1) { canvas.add(cat1[i]); } for (var i in cat2) { canvas.add(cat2[i]); } for (var i in lines) { canvas.add(lines[i]); } } function CorrectDiff(number) { var x; switch (number) { case 1: return 1; case -1: return 0; case 3: return 4; case 4: return 3; case 2: return 5; case 5: return 2; } } function Verify(e) { var ok=1; var obj = e.target; if(obj) { if(obj.cat=='cat1') { var x=9-obj.j; if(pisica1[obj.i][obj.j]!=pisica2[obj.i][9-obj.j]) {ok=0; if(pisica1[obj.i][obj.j]==2&&pisica2[obj.i][9-obj.j]==5) ok=1; if(pisica1[obj.i][obj.j]==5&&pisica2[obj.i][9-obj.j]==2) ok=1; if(pisica1[obj.i][obj.j]==3&&pisica2[obj.i][9-obj.j]==4) ok=1; if(pisica1[obj.i][obj.j]==4&&pisica2[obj.i][9-obj.j]==3) ok=1; } else if(pisica1[obj.i][obj.j]==2||pisica1[obj.i][obj.j]==3||pisica1[obj.i][obj.j]==4||pisica1[obj.i][obj.j]==5) ok=0; if(ok==0) {pisica1[obj.i][obj.j]= CorrectDiff(pisica2[obj.i][9-obj.j]); canvas.clear(); initObjects(); canvas.renderAll(); } //alert("i1="+obj.i+"j1="+obj.j+"kkk"+pisica1[obj.i][obj.j]+"i2="+obj.i+"j2="+x+"jj"+pisica2[obj.i][9-obj.j]) } else if(obj.cat=='cat2') { var x=9-obj.j; if(pisica2[obj.i][obj.j]!=pisica1[obj.i][9-obj.j]) {ok=0; if(pisica2[obj.i][obj.j]==2&&pisica1[obj.i][9-obj.j]==5) ok=1; if(pisica2[obj.i][obj.j]==5&&pisica1[obj.i][9-obj.j]==2) ok=1; if(pisica2[obj.i][obj.j]==3&&pisica1[obj.i][9-obj.j]==4) ok=1; if(pisica2[obj.i][obj.j]==4&&pisica1[obj.i][9-obj.j]==3) ok=1; } else if(pisica2[obj.i][obj.j]==2||pisica2[obj.i][obj.j]==3||pisica2[obj.i][obj.j]==4||pisica2[obj.i][obj.j]==5) ok=0; if(ok==0) { pisica2[obj.i][obj.j] = CorrectDiff(pisica1[obj.i][9-obj.j]); canvas.clear(); initObjects(); canvas.renderAll(); } //alert("i1="+obj.i+"j1="+obj.j+"kkk"+pisica1[obj.i][obj.j]+"i2="+obj.i+"j2="+x+"jj"+pisica2[obj.i][9-obj.j]); } } return; } function VerifyMatrix() { if(MatrixSymmetric()) { canvas.on({ 'mouse:down' : null, 'mouse:up' :null }); fabric.Image.fromURL('Images/Check.png', function(img) { img.scaleToWidth(100); img.set({ left: 340, top: 20 }); canvas.add(fix(img));}) canvas.renderAll(); } } function MatrixSymmetric() { for(var i=0;i<12;i++) for(var j=0;j<10;j++) {if(pisica1[i][j]==-1&&pisica2[i][9-j]!=0) return false; if(pisica1[i][j]==0&&(pisica2[i][9-j]!=0&&pisica2[i][9-j]!=-1)) return false; if(pisica1[i][j]==1&&pisica2[i][9-j]!=1) return false; if(pisica1[i][j]==2&&pisica2[i][9-j]!=5) return false; if(pisica1[i][j]==3&&pisica2[i][9-j]!=4) return false; if(pisica1[i][j]==4&&pisica2[i][9-j]!=3) return false; if(pisica1[i][j]==5&&pisica2[i][9-j]!=2) return false; if(pisica1[i][j]==6&&pisica2[i][9-j]!=6) return false; } return true; }
2627567b5916d593900f05f56d271f0ef5e2f505
[ "JavaScript" ]
1
JavaScript
ddana0909/cats
f73e9ccc323d49cc7a55dc45f524857d2d6632e0
5c29ec0d079804bcce0d0166b91b1077f2b2fac0
refs/heads/master
<file_sep># CalculatorProgram A simple non-graphical calculator that performs basic calculation functions <file_sep>import random import math import string # This function open's/read's up a password file (I need to find a way to iterate through the list # so that different passwords may be inserted. try: password_file = open('/media/lunga/LUNGA/PycharmProjects/automate_boring_stuff/SecretPasswordFile.txt') secret_password = password_file.read() # This requests the user to insert their credentials print('Please enter your password') typed_pass = input() # Verifies what is typed against what is in the file that was read in line 8 if typed_pass == secret_password: print('Access granted !!!\n\n') else: print('Incorrect password. So, "Access Denied!!!"\n\n') # I will execute the greeting function here def calc(): # This is is the welcome text print('''Welcome to <NAME>'s simple calculator simulator.\nWhere you will input two numbers,\nthen insert the symbol you wish to compute the two numbers with.\n ''') # I then request input from the user...however, this would need to be in # an integer format. I need to find a way to throw my own error that # keeps the flow control within the program num_1 = int(input('Faka iNumba yoku qala: ')) num_2 = int(input('faka iNumba yesi bili: ')) # This requests the user to insert a mathematical symbol for simple calculation. The current # options are (plus, minus, multiply and divide) operation_var = input(''' Please enter your mathematical elements you want to calculate with this calculator program: + for addition - for subtraction * for multiplication / for division % for Modulus ''') # In this block if operation_var == '+': print('{} + {} ='.format(num_1, num_2)) print('Impendulo yakho: \n', num_1 + num_2) elif operation_var == '-': print('{} - {} ='.format(num_1, num_2)) print('Impendulo yakho: \n', num_1 - num_2) elif operation_var == '*': print('{} * {} ='.format(num_1, num_2)) print('Impendulo yakho: \n', num_1 * num_2) elif operation_var == '/': print('{} / {} ='.format(num_1, num_2)) print('Impendulo yakho: \n', num_1 / num_2) elif operation_var == '%': print('{} / {} ='.format(num_1, num_2)) print('Impendulo yakho: \n', num_1 / num_2) else: print('Error! Invalid operation conducted!!! Please run program and try again with correct parameters!!!') calc() def play_again(): calc_again = input('''Ufuna ukubala futhi? uY for uYebo noma uQ for uQha! ''') while calc_again.upper() == 'Y': return calc() return play_again() if calc_again.upper() == 'Q': return print('Hamba Kahle :) ') play_again() except ZeroDivisionError: print("Error! Please note that you cannot divide a number by Zero (0)")
f47bbc2ab539766eb36d8f1cf613332e8d9ba3cf
[ "Markdown", "Python" ]
2
Markdown
LungaMthombothi/CalculatorProgram
52542d8f000a6d7ff8cab191941b5ecf09341ee3
62337d761bb9fe4ccd110c57e050095abce5db56
refs/heads/master
<repo_name>SarahRector/chocolate-pizza<file_sep>/test/example.test.js // IMPORT MODULES under test here: // import { example } from '../example.js'; const test = QUnit.test; test('testing', (expect) => { const expected = true; const actual = expected; expect.equal(actual, expected); });
e1359d0404008722ab36e7ee5a4652d3b4f70c6a
[ "JavaScript" ]
1
JavaScript
SarahRector/chocolate-pizza
49cf28c0b396db99ef624cf44d788f6592955755
3594a0ddb7395c899d9524fb34c860d5cc020fb4
refs/heads/master
<repo_name>AndreaChiaramonte/domoticz-python-melcloud<file_sep>/README.md # domoticz-python-melcloud ## Installation 1. Clone repository into your domoticz plugins folder ``` cd domoticz/plugins git clone https://github.com/gysmo38/domoticz-python-melcloud.git ``` 2. Restart domoticz 3. Make sure that "Accept new Hardware Devices" is enabled in Domoticz settings 4. Go to "Hardware" page and add new item with type "MELCloud plugin" ## Plugin update ``` cd domoticz/plugins/Melcloud git pull ``` ## Testing without Domoticz 1. Clone repository ``` cd scripts/tests git clone https://github.com/gysmo38/domoticz-python-melcloud.git ``` 2. Edit TestCode.py ``` Parameters['Username'] = '<EMAIL>' # your account mail Parameters['Password'] = '<PASSWORD>' # your account password ``` 3. Run test ``` python3 plugin.py ``` <file_sep>/TestCode.py import json from Domoticz import Connection from Domoticz import Device from Domoticz import Devices from Domoticz import Parameters # your params Parameters['Mode1'] = '0' Parameters['Username'] = '<EMAIL>' # your account mail Parameters['Password'] = '<PASSWORD>' # your account password Parameters['Mode6'] = 'Debug' # Debug or Normal def runtest(plugin): plugin.onStart() # First Heartbeat plugin.onHeartbeat() # Second Heartbeat plugin.onHeartbeat() exit(0) <file_sep>/Domoticz.py import requests import json import chardet Parameters = {"Mode5": "Debug"} Devices = {} Images = {} debug_Level = 0 def Debug(textStr): if debug_Level >= 62: print(u'Debug : {}'.format(textStr)) def Error(textStr): print(u'Error : {}'.format(textStr)) def Status(textStr): print(u'Status : {}'.format(textStr)) def Log(textStr): print(u'Log : {}'.format(textStr)) def Debugging(value): global debug_Level debug_Level = int(value) Log(u'debug_Level: {}'.format(debug_Level)) def Heartbeat(value): pass def UpdateDevice(num, Image='', nValue=0, sValue=''): pass class Connection: @property def Name(self): return self._name @property def data(self): return self._data @property def bp(self): return self._bp @bp.setter def bp(self, value): self._bp = value def __init__(self, Name="", Transport="", Protocol="", Address="", Port=""): self._name = Name self._transport = Transport self._ptrotocol = Protocol.lower() self._address = Address self._port = Port self._requestUrl = u'{}://{}:{}'.format(self._ptrotocol, self._address, self._port) self._data = None self._bp = None def Connect(self): Debug(u'requestUrl: {}'.format(self._requestUrl)) self._bp.onConnect('Connection', 0, 'Description') return None def Connecting(self): return True def Connected(self): return True def Send(self, params): params['Headers']['accept'] = 'application/json' if params['Verb'] == 'POST': url = u'{}/{}'.format(self._requestUrl, params['URL']) r = requests.post(url, data=params['Data'], headers=params['Headers']) # build onMessage params data = {} data["Status"] = r.status_code data["Data"] = bytes(json.dumps(r.json()), 'utf-8') r.encoding = 'utf-8' self._data = {} self._data["Status"] = r.status_code self._data["Data"] = bytes(json.dumps(r.json()), 'utf-8') self.bp.onMessage(self, data) return elif params['Verb'] == 'GET': url = u'{}/{}'.format(self._requestUrl, params['URL']) r = requests.get(url, data=params['Data'], headers=params['Headers']) # build onMessage params and onMessage call data = {} data["Status"] = r.status_code data["Data"] = bytes(json.dumps(r.json()), 'utf-8') self.bp.onMessage(self, data) r.encoding = 'utf-8' self._data = {} self._data["Status"] = r.status_code self._data["Data"] = bytes(json.dumps(r.json()), 'utf-8') return True class Device: global Devices @property def nValue(self): return self._nValue @nValue.setter def nValue(self, value): self._nValue = value @property def sValue(self): return self._sValue @sValue.setter def nValue(self, value): self._sValue = value @property def ID(self): return self._id @ID.setter def ID(self, value): self._id = value @property def DeviceID(self): return self._device_id @DeviceID.setter def DeviceID(self, value): self._device_id = value @property def Typename(self): return self._typeName @Typename.setter def Typename(self, value): self._typeName = value @property def Name(self): return self._name @Name.setter def Name(self, value): self._name = value @property def LastLevel(self): return 0 @property def Image(self): return self._image @Image.setter def Image(self, value): self._image = value def __init__(self, Name="", Unit=0, TypeName="", Used=0, Type=0, Subtype=0, Image="", Options=""): self._nValue = 0 self._sValue = '' self._name = Name self._unit = Unit self._typeName = TypeName self._used = Used self._type = Type self._subtype = Subtype self._image = Image self._options = Options self._id = len(Devices.keys()) + 101 self._device_id = len(Devices.keys()) + 4001 Debug(u'ID: {}'.format(self._id)) def Update(self, nValue=0, sValue='', Options='', Image=None): self._nvalue = nValue self._svalue = sValue self._image = Image txt_log = self.__str__() Log(txt_log) def __str__(self): txt_log = u'Info - Update device Name : {} nValue : {} sValue : {} Options : {} Image: {}\n' txt_log = txt_log.format(self._name, self._nvalue, self._svalue, self._options, self._image) return txt_log def Create(self): self._id = len(Devices.keys()) + 101 self._device_id = len(Devices.keys()) + 4001 txt_log = u'Info - Create device : \n\tName : {}\n\tUnit : {}\n\tTypeName : {}\n\tUsed : {}\n\tType : {}\n\tSubtype : {}' txt_log += u'\n\tImage : {}\n\tOptions : {}' txt_log = txt_log.format(self._name, self._unit, self._typeName, self._used, self._type, self._subtype, self._image, self._options) Log(txt_log) Devices[len(Devices.keys())] = self Debug(u'ID: {}'.format(self._id)) class Image: @property def Name(self): return self._name @Name.setter def ID(self, value): self._name = value @property def Base(self): return self._base @Base.setter def ID(self, value): self._base = value @property def ID(self): return self._filename @ID.setter def ID(self, value): self._filename = value def __init__(self, Filename=""): self._filename = Filename self._name = Filename self._base = Filename def Create(self): Images[self._filename.split(u' ')[0]] = self <file_sep>/plugin.py # MELCloud Plugin # Author: Gysmo, 2017 # Version: 0.7.7 # # Release Notes: # v0.7.8: Code optimization # v0.7.7: Add test on domoticz dummy # v0.7.6: Fix Auto Mode added # v0.7.5: Fix somes bugs and improve https connection # v0.7.4: Sometimes update fail. Update function sync to avoid this # v0.7.3: Add test in login process and give message if there is some errors # v0.7.2: Correct bug for onDisconnect, add timeoffset and add update time for last command in switch text # v0.7.1: Correct bug with power on and power off # v0.7 : Use builtin https support to avoid urllib segmentation fault on binaries # v0.6.1 : Change Update function to not crash with RPI # v0.6 : Rewrite of the module to be easier to maintain # v0.5.1: Problem with device creation # v0.5 : Upgrade code to be compliant wih new functions # v0.4 : Search devices in floors, areas and devices # v0.3 : Add Next Update information, MAC Address and Serial Number # Add Horizontal vane # Add Vertival vane # Add Room Temp # v0.2 : Add sync between Domoticz devices and MELCloud devices # Usefull if you use your Mitsubishi remote # v0.1 : Initial release """ <plugin key="MELCloud" version="0.7.8" name="MELCloud plugin" author="gysmo" wikilink="http://www.domoticz.com/wiki/Plugins/MELCloud.html" externallink="http://www.melcloud.com"> <params> <param field="Username" label="Email" width="200px" required="true" /> <param field="Password" label="<PASSWORD>" width="200px" required="true" /> <param field="Mode1" label="GMT Offset" width="75 px"> <options> <option label="-12" value="-12"/> <option label="-11" value="-11"/> <option label="-10" value="-10"/> <option label="-9" value="-9"/> <option label="-8" value="-8"/> <option label="-7" value="-7"/> <option label="-6" value="-6"/> <option label="-5" value="-5"/> <option label="-4" value="-4"/> <option label="-3" value="-3"/> <option label="-2" value="-2"/> <option label="-1" value="-1"/> <option label="0" value="0" default="true" /> <option label="+1" value="+1"/> <option label="+2" value="+2"/> <option label="+3" value="+3"/> <option label="+4" value="+4"/> <option label="+5" value="+5"/> <option label="+6" value="+6"/> <option label="+7" value="+7"/> <option label="+8" value="+8"/> <option label="+9" value="+9"/> <option label="+10" value="+10"/> <option label="+11" value="+11"/> <option label="+12" value="+12"/> </options> </param> <param field="Mode6" label="Debug" width="150px"> <options> <option label="None" value="0" default="true" /> <option label="Python Only" value="2"/> <option label="Basic Debugging" value="62"/> <option label="Basic+Messages" value="126"/> <option label="Connections Only" value="16"/> <option label="Connections+Python" value="18"/> <option label="Connections+Queue" value="144"/> <option label="All" value="-1"/> </options> </param> </params> </plugin> """ import time import json import Domoticz class BasePlugin: melcloud_conn = None melcloud_baseurl = "app.melcloud.com" melcloud_port = "443" melcloud_key = None melcloud_state = "Not Ready" melcloud_urls = {} melcloud_urls["login"] = "/Mitsubishi.Wifi.Client/Login/ClientLogin" melcloud_urls["list_unit"] = "/Mitsubishi.Wifi.Client/User/ListDevices" melcloud_urls["set_unit"] = "/Mitsubishi.Wifi.Client/Device/SetAta" melcloud_urls["unit_info"] = "/Mitsubishi.Wifi.Client/Device/Get" list_units = [] dict_devices = {} list_switchs = [] list_switchs.append({"id": 1, "name": "Mode", "typename": "Selector Switch", "image": 16, "levels": "Off|Warm|Cold|Vent|Dry|Auto"}) list_switchs.append({"id": 2, "name": "Fan", "typename": "Selector Switch", "image": 7, "levels": "Level1|Level2|Level3|Level4|Level5|Auto|Silence"}) list_switchs.append({"id": 3, "name": "Temp", "typename": "Selector Switch", "image": 15, "levels": "16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31"}) list_switchs.append({"id": 4, "name": "Vane Horizontal", "typename": "Selector Switch", "image": 7, "levels": "1|2|3|4|5|Swing|Auto"}) list_switchs.append({"id": 5, "name": "Vane Vertical", "typename": "Selector Switch", "image": 7, "levels": "1|2|3|4|5|Swing|Auto"}) list_switchs.append({"id": 6, "name": "Room Temp", "typename": "Temperature"}) list_switchs.append({"id": 7, "name": "Unit Infos", "typename": "Text"}) domoticz_levels = {} domoticz_levels["mode"] = {"0": 0, "10": 1, "20": 3, "30": 7, "40": 2, "50": 8} domoticz_levels["mode_pic"] = {"0": 9, "10": 15, "20": 16, "30": 7, "40": 11} domoticz_levels["fan"] = {"0": 1, "10": 2, "20": 3, "30": 4, "40": 255, "50": 0, "60": 1} domoticz_levels["temp"] = {"0": 16, "10": 17, "20": 18, "30": 19, "40": 20, "50": 21, "60": 22, "70": 23, "80": 24, "90": 25, "100": 26, "110": 27, "120": 28, "130": 29, "140": 30, "150": 31} domoticz_levels["vaneH"] = {"0": 1, "10": 2, "20": 3, "30": 4, "40": 5, "50": 12, "60": 0} domoticz_levels["vaneV"] = {"0": 1, "10": 2, "20": 3, "30": 4, "40": 5, "50": 7, "60": 0} runAgain = 6 enabled = False def __init__(self): return def onStart(self): Domoticz.Heartbeat(25) if Parameters["Mode6"] == "Debug": Domoticz.Debugging(62) # Start connection to MELCloud self.melcloud_conn = Domoticz.Connection(Name="MELCloud", Transport="TCP/IP", Protocol="HTTPS", Address=self.melcloud_baseurl, Port=self.melcloud_port) if __name__ == "__main__": self.melcloud_conn.bp = self self.melcloud_conn.Connect() return True def onStop(self): Domoticz.Log("Goobye from MELCloud plugin.") def onConnect(self, Connection, Status, Description): if Status == 0: Domoticz.Log("MELCloud connection OK") self.melcloud_state = "READY" self.melcloud_login() else: Domoticz.Log("MELCloud connection FAIL: "+Description) def extractDeviceData(self, device): if device['DeviceName'] not in self.dict_devices.keys(): self.dict_devices['DeviceName'] = device # print('\n---device\n', device, '\n---\n') if 'HasEnergyConsumedMeter' in device['Device'].keys(): return device['Device']['CurrentEnergyConsumed']/1000 else: return 0 def searchUnits(self, building, scope, idoffset): # building["Structure"]["Devices"] # building["Structure"]["Areas"] # building["Structure"]["Floors"] nr_of_Units = 0 cEnergyConsumed = 0 # Search in scope def oneUnit(self, device, idoffset, nr_of_Units, cEnergyConsumed, building, scope): self.melcloud_add_unit(device, idoffset) idoffset += len(self.list_switchs) nr_of_Units += 1 self.extractDeviceData(device) currentEnergyConsumed = self.extractDeviceData(device) cEnergyConsumed += currentEnergyConsumed text2log = "Found {} in building {} {} CurrentEnergyConsumed {} kWh" text2log = text2log.format(device['DeviceName'], building["Name"], scope, currentEnergyConsumed) Domoticz.Log(text2log) return (nr_of_Units, idoffset, cEnergyConsumed) for item in building["Structure"][scope]: if scope == u'Devices': if item["Type"] == 0: (nr_of_Units, idoffset, cEnergyConsumed) = oneUnit(self, item, idoffset, nr_of_Units, cEnergyConsumed, building, scope) elif scope in (u'Areas', u'Floors'): for device in item["Devices"]: (nr_of_Units, idoffset, cEnergyConsumed) = oneUnit(self, device, idoffset, nr_of_Units, cEnergyConsumed, building, scope) if scope == u'Floors': for device in item["Areas"]: (nr_of_Units, idoffset, cEnergyConsumed) = oneUnit(self, device, idoffset, nr_of_Units, cEnergyConsumed, building, scope) text2log = u'Found {} devices in building {} {} of the Type 0 (Aircondition) CurrentEnergyConsumed {:.0f} kWh' text2log = text2log.format(str(nr_of_Units), building["Name"], scope, cEnergyConsumed) Domoticz.Log(text2log) return (nr_of_Units, idoffset, cEnergyConsumed) def onMessage(self, Connection, Data): Status = int(Data["Status"]) if Status == 200: strData = Data["Data"].decode("utf-8", "ignore") response = json.loads(strData) Domoticz.Debug("JSON REPLY: "+str(response)) if self.melcloud_state == "LOGIN": if ("ErrorId" not in response.keys()) or (response["ErrorId"] is None): Domoticz.Log("MELCloud login successfull") self.melcloud_key = response["LoginData"]["ContextKey"] self.melcloud_units_init() elif response["ErrorId"] == 1: Domoticz.Log("MELCloud login fail: check login and password") self.melcloud_state = "LOGIN_FAILED" else: Domoticz.Log("MELCloud failed with unknown error "+str(response["ErrorId"])) self.melcloud_state = "LOGIN_FAILED" elif self.melcloud_state == "UNITS_INIT": idoffset = 0 Domoticz.Log("Find " + str(len(response)) + " buildings") for building in response: Domoticz.Log("Find " + str(len(building["Structure"]["Areas"])) + " areas in building "+building["Name"]) Domoticz.Log("Find " + str(len(building["Structure"]["Floors"])) + " floors in building "+building["Name"]) # Search in devices (nr_of_Units, idoffset, cEnergyConsumed) = self.searchUnits(building, "Devices", idoffset) # Search in areas (nr_of_Units, idoffset, cEnergyConsumed) = self.searchUnits(building, "Areas", idoffset) # Search in floors (nr_of_Units, idoffset, cEnergyConsumed) = self.searchUnits(building, "Floors", idoffset) self.melcloud_create_units() elif self.melcloud_state == "UNIT_INFO": for unit in self.list_units: if unit['id'] == response['DeviceID']: Domoticz.Log("Update unit {0} information.".format(unit['name'])) unit['power'] = response['Power'] unit['op_mode'] = response['OperationMode'] unit['room_temp'] = response['RoomTemperature'] unit['set_temp'] = response['SetTemperature'] unit['set_fan'] = response['SetFanSpeed'] unit['vaneH'] = response['VaneHorizontal'] unit['vaneV'] = response['VaneVertical'] unit['next_comm'] = False Domoticz.Debug("Heartbeat unit info: "+str(unit)) self.domoticz_sync_switchs(unit) elif self.melcloud_state == "SET": for unit in self.list_units: if unit['id'] == response['DeviceID']: date, time = response['NextCommunication'].split("T") hours, minutes, sec = time.split(":") mode1 = Parameters["Mode1"] if mode1 == '0': mode1 = '+0' sign = mode1[0] value = mode1[1:] Domoticz.Debug("TIME OFFSSET :" + sign + value) if sign == "-": hours = int(hours) - int(value) if hours < 0: hours = hours + 24 else: hours = int(hours) + int(value) if hours > 24: hours = hours - 24 next_comm = date + " " + str(hours) + ":" + minutes + ":" + sec unit['next_comm'] = "Update for last command at "+next_comm Domoticz.Log("Next update for command: " + next_comm) self.domoticz_sync_switchs(unit) else: Domoticz.Log("State not implemented:" + self.melcloud_state) else: Domoticz.Log("MELCloud receive unknonw message with error code "+Data["Status"]) def onCommand(self, Unit, Command, Level, Hue): Domoticz.Log("onCommand called for Unit " + str(Unit) + ": Parameter '" + str(Command) + "', Level: " + str(Level)) # ~ Get switch function: mode, fan, temp ... switch_id = Unit while switch_id > 7: switch_id -= 7 switch_type = self.list_switchs[switch_id-1]["name"] # ~ Get the unit in units array current_unit = False for unit in self.list_units: if (unit['idoffset'] + self.list_switchs[switch_id-1]["id"]) == Unit: current_unit = unit break if switch_type == 'Mode': if Level == 0: flag = 1 current_unit['power'] = 'false' Domoticz.Log("Switch Off the unit "+current_unit['name'] + "with ID offset " + str(current_unit['idoffset'])) Devices[1+current_unit['idoffset']].Update(nValue=0, sValue=str(Level), Image=9) Devices[2+current_unit['idoffset']].Update(nValue=0, sValue=str(Devices[Unit + 1].sValue)) Devices[3+current_unit['idoffset']].Update(nValue=0, sValue=str(Devices[Unit + 2].sValue)) Devices[4+current_unit['idoffset']].Update(nValue=0, sValue=str(Devices[Unit + 3].sValue)) Devices[5+current_unit['idoffset']].Update(nValue=0, sValue=str(Devices[Unit + 4].sValue)) Devices[6+current_unit['idoffset']].Update(nValue=0, sValue=str(Devices[Unit + 5].sValue)) elif Level == 10: Domoticz.Log("Set to WARM the unit "+current_unit['name']) Devices[1+current_unit['idoffset']].Update(nValue=1, sValue=str(Level), Image=15) elif Level == 20: Domoticz.Log("Set to COLD the unit "+current_unit['name']) Devices[1+current_unit['idoffset']].Update(nValue=1, sValue=str(Level), Image=16) elif Level == 30: Domoticz.Log("Set to Vent the unit "+current_unit['name']) Devices[1+current_unit['idoffset']].Update(nValue=1, sValue=str(Level), Image=7) elif Level == 40: Domoticz.Log("Set to Dry the unit "+current_unit['name']) Devices[1+current_unit['idoffset']].Update(nValue=1, sValue=str(Level), Image=11) elif Level == 50: Domoticz.Log("Set to Auto the unit "+current_unit['name']) Devices[1+current_unit['idoffset']].Update(nValue=1, sValue=str(Level), Image=11) if Level != 0: flag = 1 current_unit['power'] = 'true' self.melcloud_set(current_unit, flag) flag = 6 current_unit['power'] = 'true' current_unit['op_mode'] = self.domoticz_levels['mode'][str(Level)] Devices[2+current_unit['idoffset']].Update(nValue=1, sValue=str(Devices[Unit + 1].sValue)) Devices[3+current_unit['idoffset']].Update(nValue=1, sValue=str(Devices[Unit + 2].sValue)) Devices[4+current_unit['idoffset']].Update(nValue=1, sValue=str(Devices[Unit + 3].sValue)) Devices[5+current_unit['idoffset']].Update(nValue=1, sValue=str(Devices[Unit + 4].sValue)) Devices[6+current_unit['idoffset']].Update(nValue=1, sValue=str(Devices[Unit + 5].sValue)) elif switch_type == 'Fan': flag = 8 current_unit['set_fan'] = self.domoticz_levels['fan'][str(Level)] Domoticz.Log("Change FAN to value {0} for {1} ".format(self.domoticz_levels['temp'][str(Level)], current_unit['name'])) Devices[Unit].Update(nValue=Devices[Unit].nValue, sValue=str(Level)) elif switch_type == 'Temp': flag = 4 setTemp = 16 if Level != 0: setTemp = int(str(Level).strip("0")) + 16 Domoticz.Log("Change Temp to " + str(setTemp) + " for "+unit['name']) current_unit['set_temp'] = self.domoticz_levels['temp'][str(Level)] Devices[Unit].Update(nValue=Devices[Unit].nValue, sValue=str(Level)) elif switch_type == 'Vane Horizontal': flag = 256 current_unit['vaneH'] = self.domoticz_levels['vaneH'][str(Level)] Domoticz.Debug("Change Vane Horizontal to value {0} for {1}".format(self.domoticz_levels['vaneH'][str(Level)], current_unit['name'])) Devices[Unit].Update(Devices[Unit].nValue, str(Level)) elif switch_type == 'Vane Vertical': flag = 16 current_unit['vaneV'] = self.domoticz_levels['vaneV'][str(Level)] Domoticz.Debug("Change Vane Vertical to value {0} for {1}".format(self.domoticz_levels['vaneV'][str(Level)], current_unit['name'])) Devices[Unit].Update(Devices[Unit].nValue, str(Level)) else: Domoticz.Log("Device not found") self.melcloud_set(current_unit, flag) return True def onNotification(self, Name, Subject, Text, Status, Priority, Sound, ImageFile): Domoticz.Log("Notification: " + Name + "," + Subject + "," + Text + "," + Status + "," + str(Priority) + "," + Sound + "," + ImageFile) def onDisconnect(self, Connection): self.melcloud_state = "Not Ready" Domoticz.Log("MELCloud has disconnected") self.runAgain = 1 def onHeartbeat(self): if (self.melcloud_conn is not None and (self.melcloud_conn.Connecting() or self.melcloud_conn.Connected())): if self.melcloud_state != "LOGIN_FAILED": Domoticz.Debug("Current MEL Cloud Key ID:"+str(self.melcloud_key)) for unit in self.list_units: self.melcloud_get_unit_info(unit) else: self.runAgain = self.runAgain - 1 if self.runAgain <= 0: if self.melcloud_conn is None: self.melcloud_conn = Domoticz.Connection(Name="MELCloud", Transport="TCP/IP", Protocol="HTTPS", Address=self.melcloud_baseurl, Port=self.melcloud_port) self.melcloud_conn.Connect() self.runAgain = 6 else: Domoticz.Debug("MELCloud https failed. Reconnected in "+str(self.runAgain)+" heartbeats.") def melcloud_create_units(self): Domoticz.Log("Units infos " + str(self.list_units)) if len(Devices) == 0: # Init Devices # Creation of switches Domoticz.Log("Find " + str(len(self.list_units)) + " devices in MELCloud") for device in self.list_units: Domoticz.Log("Creating device: " + device['name'] + " with melID " + str(device['id'])) for switch in self.list_switchs: # Create switchs if switch["typename"] == "Selector Switch": switch_options = {"LevelNames": switch["levels"], "LevelOffHidden": "false", "SelectorStyle": "1"} Domoticz.Device(Name=device['name'] + " - "+switch["name"], Unit=switch["id"]+device['idoffset'], TypeName=switch["typename"], Image=switch["image"], Options=switch_options, Used=1).Create() else: Domoticz.Device(Name=device['name'] + " - "+switch["name"], Unit=switch["id"]+device['idoffset'], TypeName=switch["typename"], Used=1).Create() def melcloud_send_data(self, url, values, state): self.melcloud_state = state if self.melcloud_key is not None: headers = {'Content-Type': 'application/x-www-form-urlencoded;', 'Host': self.melcloud_baseurl, 'User-Agent': 'Domoticz/1.0', 'X-MitsContextKey': self.melcloud_key} if state == "SET": self.melcloud_conn.Send({'Verb': 'POST', 'URL': url, 'Headers': headers, 'Data': values}) else: self.melcloud_conn.Send({'Verb': 'GET', 'URL': url, 'Headers': headers, 'Data': values}) else: headers = {'Content-Type': 'application/x-www-form-urlencoded;', 'Host': self.melcloud_baseurl, 'User-Agent': 'Domoticz/1.0'} self.melcloud_conn.Send({'Verb': 'POST', 'URL': url, 'Headers': headers, 'Data': values}) return True def melcloud_login(self): data = "AppVersion=1.9.3.0&Email={0}&Password={1}".format(Parameters["Username"], Parameters["Password"]) self.melcloud_send_data(self.melcloud_urls["login"], data, "LOGIN") return True def melcloud_add_unit(self, device, idoffset): melcloud_unit = {} melcloud_unit['name'] = device["DeviceName"] melcloud_unit['id'] = device["DeviceID"] melcloud_unit['macaddr'] = device["MacAddress"] melcloud_unit['sn'] = device["SerialNumber"] melcloud_unit['building_id'] = device["BuildingID"] melcloud_unit['power'] = "" melcloud_unit['op_mode'] = "" melcloud_unit['room_temp'] = "" melcloud_unit['set_temp'] = "" melcloud_unit['set_fan'] = "" melcloud_unit['vaneH'] = "" melcloud_unit['vaneV'] = "" melcloud_unit['next_comm'] = False melcloud_unit['idoffset'] = idoffset self.list_units.append(melcloud_unit) def melcloud_units_init(self): self.melcloud_send_data(self.melcloud_urls["list_unit"], None, "UNITS_INIT") return True def melcloud_set(self, unit, flag): post_fields = "Power={0}&DeviceID={1}&OperationMode={2}&SetTemperature={3}&SetFanSpeed={4}&VaneHorizontal={5}&VaneVertical={6}&EffectiveFlags={7}&HasPendingCommand=true" post_fields = post_fields.format(unit['power'], unit['id'], unit['op_mode'], unit['set_temp'], unit['set_fan'], unit['vaneH'], unit['vaneV'], flag) Domoticz.Debug("SET COMMAND SEND {0}".format(post_fields)) self.melcloud_send_data(self.melcloud_urls["set_unit"], post_fields, "SET") def melcloud_get_unit_info(self, unit): url = self.melcloud_urls["unit_info"] + "?id=" + str(unit['id']) + "&buildingID=" + str(unit['building_id']) self.melcloud_send_data(url, None, "UNIT_INFO") def domoticz_sync_switchs(self, unit): # Default value in case of problem setDomFan = 0 setDomTemp = 0 setDomVaneH = 0 setDomVaneV = 0 if unit['next_comm'] is not False: Devices[self.list_switchs[6]["id"]+unit["idoffset"]].Update(nValue=1, sValue=str(unit['next_comm'])) else: if unit['power']: switch_value = 1 for level, mode in self.domoticz_levels["mode"].items(): if mode == unit['op_mode']: setModeLevel = level else: switch_value = 0 setModeLevel = '0' for level, pic in self.domoticz_levels["mode_pic"].items(): if level == setModeLevel: setPicID = pic Devices[self.list_switchs[0]["id"]+unit["idoffset"]].Update(nValue=switch_value, sValue=setModeLevel, Image=setPicID) for level, fan in self.domoticz_levels["fan"].items(): if fan == unit['set_fan']: setDomFan = level Devices[self.list_switchs[1]["id"]+unit["idoffset"]].Update(nValue=switch_value, sValue=setDomFan) for level, temp in self.domoticz_levels["temp"].items(): if temp == unit['set_temp']: setDomTemp = level Devices[self.list_switchs[2]["id"]+unit["idoffset"]].Update(nValue=switch_value, sValue=setDomTemp) for level, vaneH in self.domoticz_levels["vaneH"].items(): if vaneH == unit['vaneH']: setDomVaneH = level Devices[self.list_switchs[3]["id"]+unit["idoffset"]].Update(nValue=switch_value, sValue=setDomVaneH) for level, vaneV in self.domoticz_levels["vaneV"].items(): if vaneV == unit['vaneV']: setDomVaneV = level Devices[self.list_switchs[4]["id"]+unit["idoffset"]].Update(nValue=switch_value, sValue=setDomVaneV) Devices[self.list_switchs[5]["id"]+unit["idoffset"]].Update(nValue=switch_value, sValue=str(unit['room_temp'])) global _plugin _plugin = BasePlugin() def onStart(): """ On start """ global _plugin _plugin.onStart() def onStop(): global _plugin """ On stop """ _plugin.onStop() def onConnect(Connection, Status, Description): global _plugin """ On connect """ _plugin.onConnect(Connection, Status, Description) def onMessage(Connection, Data): global _plugin """ On message """ _plugin.onMessage(Connection, Data) def onCommand(Unit, Command, Level, Hue): global _plugin """ On command """ _plugin.onCommand(Unit, Command, Level, Hue) def onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile): """ On notification """ global _plugin _plugin.onNotification(Name, Subject, Text, Status, Priority, Sound, ImageFile) def onDisconnect(Connection): """ On disconnect """ global _plugin _plugin.onDisconnect(Connection) def onHeartbeat(): """ Heartbeat """ global _plugin _plugin.onHeartbeat() if __name__ == "__main__": from Domoticz import Parameters from Domoticz import Images from Domoticz import Devices from TestCode import runtest runtest(BasePlugin()) exit(0)
cd8b6ab2ccedf3de548fd16fe2d62b460132b1f9
[ "Markdown", "Python" ]
4
Markdown
AndreaChiaramonte/domoticz-python-melcloud
6bd96fb5ad83d0ba650c3e430ece7f3c485faa78
6d91ca7125f0e7216be0774b9d018f125a56d592
refs/heads/master
<repo_name>wesyoung9987/node-passport-boilerplate<file_sep>/controllers/client.js const Client = require('../models/client'); exports.getPendingUserClients = function(req, res, next) { const userId = req.body.userId; const clientType = req.body.clientType; Client.find({ userId: userId, type: clientType, actualSalePrice: 0 }, (err, data) => { if (err) { return next(err); } res.json({ pendingClients: data }); }); } <file_sep>/services/passport.js const passport = require('passport'); const User = require('../models/user'); const config = require('../config'); const JwtStrategy = require('passport-jwt').Strategy; const ExtractJwt = require('passport-jwt').ExtractJwt; const LocalStrategy = require('passport-local'); // Using LocalStrategy for login // Tell passport to use email instead of username const localOptions = { usernameField: 'email' }; const localLogin = new LocalStrategy(localOptions, function(email, password, done) { User.findOne({ email: email }, function(err, user) { if (err) { return done(err); } if (!user) { return done(null, false); } user.comparePassword(password, function(err, isMatch) { if (err) { return done(err); } if (!isMatch) { return done(null, false); } // here passport will take user and assign it to req.user return done(null, user); }); }); }); // Using JwtStrategy for authenticated requests // tell passport to look for token on header called authorization const jwtOptions = { jwtFromRequest: ExtractJwt.fromHeader('authorization'), secretOrKey: config.secret // the secret for passport to use in order to decode jwt }; const jwtLogin = new JwtStrategy(jwtOptions, function(payload, done) { User.findById(payload.sub, function(err, user) { if (err) { return done(err, false); } if (user) { done(null, user); } else { done(null, false); } }); }); passport.use(jwtLogin); passport.use(localLogin); <file_sep>/models/leadGroup.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const leadGroupSchema = new Schema({ userId: { type: Schema.Types.ObjectId, ref: 'user' }, utcDateString: { type: String, required: true }, contacts: { total: { type: Number, default: 0 }, other: { type: Number, default: 0 }, doorsKnocked: { type: Number, default: 0 }, internet: { type: Number, default: 0 }, sphere: { total: { type: Number, default: 0 }, other: { type: Number, default: 0 }, phone: { type: Number, default: 0 }, text: { type: Number, default: 0 }, email: { type: Number, default: 0 }, social: { type: Number, default: 0 }, }, forSaleByOwner: { total: { type: Number, default: 0 }, other: { type: Number, default: 0 }, phone: { type: Number, default: 0 }, text: { type: Number, default: 0 }, email: { type: Number, default: 0 }, social: { type: Number, default: 0 }, }, expiredListing: { total: { type: Number, default: 0 }, other: { type: Number, default: 0 }, phone: { type: Number, default: 0 }, text: { type: Number, default: 0 }, email: { type: Number, default: 0 }, social: { type: Number, default: 0 }, }, areaProsp: { total: { type: Number, default: 0 }, other: { type: Number, default: 0 }, phone: { type: Number, default: 0 }, text: { type: Number, default: 0 }, email: { type: Number, default: 0 }, social: { type: Number, default: 0 }, } }, followUps: { total: { type: Number, default: 0 }, other: { type: Number, default: 0 }, doorsKnocked: { type: Number, default: 0 }, internet: { type: Number, default: 0 }, sphere: { total: { type: Number, default: 0 }, other: { type: Number, default: 0 }, phone: { type: Number, default: 0 }, text: { type: Number, default: 0 }, email: { type: Number, default: 0 }, social: { type: Number, default: 0 }, }, forSaleByOwner: { total: { type: Number, default: 0 }, other: { type: Number, default: 0 }, phone: { type: Number, default: 0 }, text: { type: Number, default: 0 }, email: { type: Number, default: 0 }, social: { type: Number, default: 0 }, }, expiredListing: { total: { type: Number, default: 0 }, other: { type: Number, default: 0 }, phone: { type: Number, default: 0 }, text: { type: Number, default: 0 }, email: { type: Number, default: 0 }, social: { type: Number, default: 0 }, }, areaProsp: { total: { type: Number, default: 0 }, other: { type: Number, default: 0 }, phone: { type: Number, default: 0 }, text: { type: Number, default: 0 }, email: { type: Number, default: 0 }, social: { type: Number, default: 0 }, } }, setAppts: { total: { type: Number, default: 0 }, buyer: { type: Number, default: 0 }, seller: { type: Number, default: 0 } }, heldAppts: { total: { type: Number, default: 0 }, buyer: { type: Number, default: 0 }, seller: { type: Number, default: 0 } }, contractsSigned: { total: { type: Number, default: 0 }, buyer: { type: Number, default: 0 }, seller: { type: Number, default: 0 } }, pendingClose: { total: { type: Number, default: 0 }, buyer: [{ type: Schema.Types.ObjectId, ref: 'client' }], seller: [{ type: Schema.Types.ObjectId, ref: 'client' }] }, closed: { total: { type: Number, default: 0 }, buyer: [{ type: Schema.Types.ObjectId, ref: 'client' }], seller: [{ type: Schema.Types.ObjectId, ref: 'client' }] } }, { timestamps: true }); const ModelClass = mongoose.model('leadGroup', leadGroupSchema); module.exports = ModelClass; <file_sep>/controllers/authentication.js const jwt = require('jwt-simple'); const User = require('../models/user'); const config = require('../config'); function tokenForUser(user) { const timestamp = new Date().getTime(); return jwt.encode({ sub: user.id, iat: timestamp }, config.secret); } exports.signin = function(req, res, next) { // user was put onto req in passport localLogin res.send({ token: tokenForUser(req.user), userData: { id: req.user.id, firstName: req.user.firstName, email: req.user.email, role: req.user.role } }); } exports.signup = function(req, res, next) { const email = req.body.email; const password = <PASSWORD>; const firstName = req.body.firstName; const lastName = req.body.lastName; const role = req.body.role; console.log(req.body); if (!firstName || !lastName) { return res.status(422).send({ error: 'First and last name are required.'}); } if (!role) { return res.status(422).send({ error: 'User role must be specified.'} ); } if (!email || !password) { return res.status(422).send({ error: 'Email and password required'}); } User.findOne({ email: email }, function(err, existingUser) { if (err) { return next(err); } if (existingUser) { return res.status(422).send({ error: 'Email is in use' }); } const user = new User({ email: email, firstName: firstName, lastName: lastName, password: <PASSWORD>, role: role }); user.save(function(err) { if (err) { return next(err); } res.json({ token: tokenForUser(user), userData: { id: user.id, firstName: user.firstName, email: user.email, role: user.role } }); }); }); } <file_sep>/models/paymentDetails.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const paymentDetailsSchema = new Schema({ clientId: { type: Schema.Types.ObjectId, ref: 'client' }, stripeCustomer: { type: String, default: '' }, stripePlan: { type: String, default: '' }, stripeSubscription: { type: String, default: '' }, }, { timestamps: true }); const ModelClass = mongoose.model('paymentDetails', paymentDetailsSchema); module.exports = ModelClass; <file_sep>/models/team.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const teamSchema = new Schema({ name: { type: String, default: '' }, allowedMembers: { type: Number, default: 1 }, numberOfMembers: { type: Number, default: 1 }, }, { timestamps: true }); const ModelClass = mongoose.model('team', teamSchema); module.exports = ModelClass; <file_sep>/router.js const Authentication = require('./controllers/authentication'); const Lead = require('./controllers/lead'); const Client = require('./controllers/client'); const passportService = require('./services/passport'); const passport = require('passport'); // session false here tells passport to not create a // cookie based session const requireAuth = passport.authenticate('jwt', { session: false }); const requireSignin = passport.authenticate('local', { session: false }); module.exports = function(app) { app.get('/', requireAuth, function(req, res) { res.send({ message: 'Super secret code is ABC123' }); }); app.post('/signin', requireSignin, Authentication.signin); app.post('/signup', Authentication.signup); app.post('/get-lead-group-by-day', requireAuth, Lead.getLeadGroupByDay); app.post('/save-lead-group', requireAuth, Lead.saveLeadGroup); app.post('/save-pending-close', requireAuth, Lead.savePendingClose); app.post('/save-client-close', requireAuth, Lead.saveClientClose); app.post('/get-pending-user-clents', requireAuth, Client.getPendingUserClients); }
1145e5fff2093759ecec99362928f7f2c4a00c4f
[ "JavaScript" ]
7
JavaScript
wesyoung9987/node-passport-boilerplate
6b1b6729d24badcd46cdf810a8cc49accef38dfc
f2a98d8d9e0d3ed8489c0b91d2ec3fb622ea7584
refs/heads/master
<file_sep>''' author: <NAME> ''' import random, sys from copy import deepcopy marker = '123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' shortestPath = [] totalPath = [] def mazeGen(r, c): maze = [None for r in range(r)] rowIndex = 0 (rows, cols) = (r, c) rows -= 1 cols -= 1 (blank, roof, wall, corner) = ' -|+' M = str(roof * int(cols / 2)) n = random.randint(1, (int(cols / 2)) * (int(rows / 2) - 1)) for i in range(int(rows / 2)) : e = s = t = '' N = wall if i == 0 : t = '@' # add entry marker '@' on first row first col only for j in range(int(cols / 2)) : if i and(random.randint(0, 1) or j == 0) : s += N + blank t += wall N = wall M = M[1 : ] + corner else : s += M[0] + roof if i or j : t += blank # add blank to compensate for '@' on first row only N = corner M = M[1 : ] + roof n -= 1 t += ' #' [n == 0] if cols & 1 : s += s[-1] t += blank e = roof maze[rowIndex] = list(s + N) rowIndex += 1 maze[rowIndex] = list(t + wall) rowIndex += 1 if rows & 1 : maze[rowIndex] = list(t + wall) rowIndex += 1 maze[rowIndex] = list(roof.join(M) + e + roof + corner) return maze def traverseMaze(x, y, maze): ignore = ['|', '-', '+'] if maze[x][y] == '#': # checks if current spot is the '#' which is needed for recursion return x, y if maze[x + 1][y] not in ignore: if [x + 1, y] not in totalPath: totalPath.append([x + 1, y]) # store to full path list i, j = traverseMaze(x + 1, y, maze) # check the surrounding spots recursively if i != None or j != None: shortestPath.insert(0, [x, y]) # stores only the path directly related to finding the '#' return i, j if maze[x][y + 1] not in ignore: if [x, y + 1] not in totalPath: totalPath.append([x, y + 1]) # store to full path list i, j = traverseMaze(x, y + 1, maze) # check the surrounding spots recursively if i != None or j != None: # checks if '#' is found or not shortestPath.insert(0, [x, y]) # stores only the path directly related to finding the '#' return i, j return None, None # returns only if there are no open spaces to move to, needed in case this method is the n'th method in recursion def TotalPathsPossible(maze): # used to see all space in the maze temp = 0 for i in maze: for j in i: if j == ' ': temp += 1 return temp def ConvertShortestPath(): # used to find the directions, N or E, using the shortest route temp = '' for i in range(1, len(shortestPath)): if shortestPath[i][0] == shortestPath[i - 1][0]: # if the y values of the current and previous positions are the same temp += 'N' else: temp += 'E' return temp def ConvertTotalPath(): # create a string of all paths taken temp = '' index = 0 newNode = False for i in range(0, len(totalPath) - 1): if i == 0: # required to function because later checks look at 2 previous position temp += marker[index] elif i == 1: # required to function because later checks look at 2 previous position index += 1 temp += marker[index] # checks if the change is position is only down elif not newNode and (totalPath[i][0] - totalPath[i - 1][0] == 1) and totalPath[i][1] == totalPath[i - 1][1]: # checks if the previous position is also only down, if not that means the movement is a turn and must be modified if not ((totalPath[i - 1][0] - totalPath[i - 2][0] == 1) and totalPath[i - 1][1] == totalPath[i - 2][1]): index += 1 temp += marker[index] else: temp += marker[index] # checks if the change is position is only right elif not newNode and(totalPath[i][1] - totalPath[i - 1][1] == 1) and totalPath[i][0] == totalPath[i - 1][0]: # checks if the previous position is also only right, if not that means the movement is a turn and must be modified if not ((totalPath[i- 1][1] - totalPath[i - 2][1] == 1) and totalPath[i - 1][0] == totalPath[i - 2][0]): index += 1 temp += marker[index] else: temp += marker[index] # needed to continue along a path correctly if is jumps to a previous node found from a different recursion elif newNode and (totalPath[i][1] != totalPath[i - 1][1]): newNode = False temp += marker[index] # if all previous are false, it means that the recurion node has ended and a new node is being checked else: newNode = True index += 1 temp += marker[index] return temp def CreateSolvedMaze(maze, path): # used to display the path in the correct indexes of the maze for i in range(len(totalPath) - 1): maze[totalPath[i][0]][totalPath[i][1]] = path[i] return maze def PrintMaze(maze): # prints the maze for i in maze: for j in i: print(j, end="") print() if __name__ == "__main__": try: rows, cols = int(sys.argv[1]), int(sys.argv[2]) except (ValueError, IndexError): print("2 command line arguments expected...") print("Usage: python maze.py rows cols") print(" minimum rows >= 15 minimum cols >= 15 / maximum rows <= 25 maximum cols <= 25") sys.exit(0) try: assert rows >= 15 and rows <= 25 and cols >= 15 and cols <= 25 except AssertionError: print("Error: maze dimensions must be at least 15 x 15 and no greater than 25 x 25 ...") print("Usage: python maze.py rows cols") print(" minimum rows >= 15 minimum cols >= 15 / maximum rows <= 25 maximum cols <= 25") sys.exit(0) print('\nPYTHON MAZE GENERATOR and SOLVER!') print('\nRANDOM MAZE ({}, {})'.format(rows, cols)) maze = mazeGen(rows, cols) allPossibleMovements = TotalPathsPossible(maze) x, y = traverseMaze(1, 0, maze) PrintMaze(maze) direction = ConvertShortestPath() path = ConvertTotalPath() solvMaze = CreateSolvedMaze(deepcopy(maze), path) movementsUsedToSolve = len(totalPath) percent = format((movementsUsedToSolve / allPossibleMovements) * 100, '.4f') print('\nSOLVED MAZE ({}, {})'.format(rows, cols)) PrintMaze(solvMaze) print('\nmaze dimensions: ({}x{})\nfound # at coords: ({}, {})\ndirections: ({})\npath: {}\ntotal searches: ({}/{}) [{}%] of maze'.format(rows, cols, x, y, direction, path, movementsUsedToSolve, allPossibleMovements, percent))
2e5af5a6b2c5a32cc26ae2c95824db40194c1938
[ "Python" ]
1
Python
pziajski/Python-Maze-Solver
2457f0c48e82137235228c17ca90f8dfc6fd5c5c
139a0d316ed719921fa16ece15291ea011bfcacc
refs/heads/master
<repo_name>ElOleynik/hell<file_sep>/README.md "# hell" # hell # hell <file_sep>/src/main/java/WordCount.java import java.io.File; import java.io.FileNotFoundException; import java.util.*; public class WordCount { private static String CATALOGUE = "C:\\Users\\User\\IdeaProjects\\WordCount\\src\\main\\java\\Test.txt"; public static void main(String[] args) throws FileNotFoundException { getWordCount(CATALOGUE); } public static void getWordCount(String filename) throws FileNotFoundException { File file = new File(filename); Scanner scanner = new Scanner(file); Map<String, Integer> occurrences = new HashMap<>(); while (scanner.hasNext()) { List<String> list = new ArrayList<String>(Arrays.asList(scanner.next().split(" "))); for (String word : list) { Integer oldCount = occurrences.get(word); occurrences.put(word, oldCount == null ? 1 : oldCount + 1); } } System.out.println(occurrences); scanner.close(); } }
f21eadbcae8ae32eba443c449135b16432fba921
[ "Markdown", "Java" ]
2
Markdown
ElOleynik/hell
10d3bf8a32dff19bb2c1193be99797ca54813d68
dc6baf5b95bf13e450737b424073d4ab8259b580
refs/heads/master
<file_sep># Snake Game #### Criando jogo da cobrinha - Snake Game, tomando como base o bootcamp de HTML Dev do Digital Innovation One. ![Imagem do projeto final](https://github.com/HugoMendess/SnakeGame/blob/master/imagem-projeto.JPG) ## Começando ##### Esse arquivo fará com que você tenha uma cópia deste projeto para fins de estudo e teste. ## Pré-requisitos ##### Para implementar o projeto, você precisa ter conhecimentos básicos em HTML5, CSS3 e Javascript ## Construído com ##### HTML5 ##### CSS3 ##### Javascript ## Certificado do projeto - Criando Snake Game com Javascript - Digital Innovation One ![Certificado - Digital Innovation One](https://github.com/HugoMendess/SnakeGame/blob/master/Certificado%20-%20Jogo%20da%20Cobrinha%20com%20JavaScript%20-%20Certificado.png) ## Autor ##### <NAME> - Estudante de Engenharia da Computação na Universidade Estadual do Maranhão, UEMA. <file_sep>let canvas = document.getElementById("snake"); let context = canvas.getContext("2d"); let box = 32; let pont = 0; let tick = 0; let snake = []; snake[0] = { x: 8 * box, y: 8 * box } let direction = "right"; // Definindo a posição random aleatoria da comida let food = { x: Math.floor(Math.random() * 15 + 1) * box, y: Math.floor(Math.random() * 15 + 1) * box } function criarBG(){ context.fillStyle = "#8a2be2"; context.fillRect(0, 0, 16 * box, 16 * box); } function criarCobrinha(){ for(i=0; i<snake.length;i++){ context.fillStyle = "#00ced1"; context.fillRect(snake[i].x, snake[i].y, box, box); } } function drawFood(){ context.fillStyle = "#00ff00"; context.fillRect(food.x, food.y, box, box); } // Vai pegar o evento de clique "keydown" e chamar a funcao update document.addEventListener('keydown', update); function update(){ if(event.keyCode == 37 && direction != "right"){ direction = "left"; } if(event.keyCode == 38 && direction != "down"){ direction = "up"; } if(event.keyCode == 39 && direction != "left"){ direction = "right"; } if(event.keyCode == 40 && direction != "up"){ direction = "down"; } } function iniciarJogo(){ if(snake[0].x > 15 * box && direction == "right"){ snake[0].x = 0; } if(snake[0].x < 0 && direction == "left"){ snake[0].x = 16 * box; } if(snake[0].y > 15 * box && direction == "down"){ snake[0].y = 0; } if(snake[0].y < 0 && direction == "up"){ snake[0].y = 16 * box; } for(i = 1; i<snake.length; i++){ if(snake[0].x == snake[i].x && snake[0].y == snake[i].y){ pont = pont - 50; if(pont <= 0){ clearInterval(jogo); alert("GAME OVER! SEUS PONTOS:"+pont); } else{ document.getElementById("pont").innerHTML = "PONTOS: "+ pont; } } if (pont >= 300) { document.getElementById("mudar").innerHTML = "FASE 2"; } if (pont >= 400) { document.getElementById("mudar").innerHTML = "FASE 3"; } if (pont >= 700) { document.getElementById("mudar").innerHTML = "FASE 4"; } if (pont >= 800) { document.getElementById("mudar").innerHTML = "FASE FINAL"; } } criarBG(); criarCobrinha(); drawFood(); let snakeX = snake[0].x; let snakeY = snake[0].y; if(direction == "right") { snakeX = snakeX + box; } if (direction == "left") { snakeX = snakeX - box; } if (direction == "up") { snakeY = snakeY - box; } if (direction == "down") { snakeY = snakeY + box; } if(snakeX != food.x || snakeY != food.y){ snake.pop(); } else{ food.x = Math.floor(Math.random() * 15 + 1) * box; food.y = Math.floor(Math.random() * 15 + 1) * box; tick = tick + 1; if(tick == 10){ pont = pont + 35; document.getElementById("pont").innerHTML = "PONTOS: "+ pont; tick = tick - tick; } else{ pont = pont + 15; document.getElementById("pont").innerHTML = "PONTOS: "+ pont; } if(pont >= 1000){ clearInterval(jogo); alert("VOCÊ ZEROU O JOGO! SEUS PONTOS:"+pont); } } let newHead = { x: snakeX, y: snakeY } snake.unshift(newHead); } // passando intervelo para iniciar o jogo a cada 100 milesegundos let jogo = setInterval(iniciarJogo, 100);
13b1c735cbfa321a3980adf0970f1a516cce3226
[ "Markdown", "JavaScript" ]
2
Markdown
HugoMendess/SnakeGame
de85eea51a08ba3c52981ff9aa12d934ba65e5ca
952e3804d9d8d24a282a208f02d496fe50f81346
refs/heads/master
<file_sep><?php if (!$iniPath = get_cfg_var('cfg_file_path')) { $iniPath = 'WARNING: not using a php.ini file'; } echo "********************************\n"; echo "* *\n"; echo "* Symfony requirements check *\n"; echo "* *\n"; echo "********************************\n\n"; echo sprintf("php.ini used by PHP: %s\n\n", $iniPath); echo "** WARNING **\n"; echo "* The PHP CLI can use a different php.ini file\n"; echo "* than the one used with your web server.\n"; if ('\\' == DIRECTORY_SEPARATOR) { echo "* (especially on the Windows platform)\n"; } echo "* If this is the case, please ALSO launch this\n"; echo "* utility from your web server.\n"; echo "** WARNING **\n"; // mandatory echo_title("Mandatory requirements"); check(version_compare(phpversion(), '5.3.2', '>='), sprintf('Checking that PHP version is at least 5.3.2 (%s installed)', phpversion()), 'Install PHP 5.3.2 or newer (current version is '.phpversion(), true); check(ini_get('date.timezone'), 'Checking that the "date.timezone" setting is set', 'Set the "date.timezone" setting in php.ini (like Europe/Paris)', true); check(is_writable(__DIR__.'/../app/cache'), sprintf('Checking that app/cache/ directory is writable'), 'Change the permissions of the app/cache/ directory so that the web server can write in it', true); check(is_writable(__DIR__.'/../app/logs'), sprintf('Checking that the app/logs/ directory is writable'), 'Change the permissions of the app/logs/ directory so that the web server can write in it', true); check(function_exists('json_encode'), 'Checking that the json_encode() is available', 'Install and enable the json extension', true); check(class_exists('SQLite3') || in_array('sqlite', PDO::getAvailableDrivers()), 'Checking that the SQLite3 or PDO_SQLite extension is available', 'Install and enable the SQLite3 or PDO_SQLite extension.', true); check(function_exists('session_start'), 'Checking that the session_start() is available', 'Install and enable the session extension', true); check(function_exists('ctype_alpha'), 'Checking that the ctype_alpha() is available', 'Install and enable the ctype extension', true); /** * Checks a configuration. */ function check($boolean, $message, $help = '', $fatal = false) { echo $boolean ? " OK " : sprintf("\n\n[[%s]] ", $fatal ? ' ERROR ' : 'WARNING'); echo sprintf("$message%s\n", $boolean ? '' : ': FAILED'); if (!$boolean) { echo " *** $help ***\n"; if ($fatal) { die("You must fix this problem before resuming the check.\n"); } } } function echo_title($title) { echo "\n** $title **\n\n"; }
f76e207b578efc877f6478982432a57494595cdf
[ "PHP" ]
1
PHP
hollodk/casim
bef4095346d4b0c792d427a02966842ec145f990
c3cb2c5b8aa4328cc5b87fc20155c6f826d75674
refs/heads/main
<file_sep>function convertFahrToCelsius(data) { let dataType = function(){ if(data.constructor == [].constructor){ return 'this is an array.' } else if(data.constructor == {}.constructor){ return 'this is an object.' } }() if(data instanceof Object){ if(data instanceof Array){ return `${JSON.stringify(data)} is not a valid number but a/an ${dataType}` } return `${JSON.stringify(data)} is not a valid number but a/an ${dataType}` } return Number.parseFloat((data-32)/1.8).toFixed(4); } function checkYuGiOh (n){ if(!parseInt(n) == true){ return `An invalid parameter: ${JSON.stringify(n)}` } let myArr = [] for( let x = 1; x <= n; x++){ myArr.push(x) } //replacing 'yu', 'gi' or 'Oh' for(let i = 1; i < myArr.length; i++){ if(myArr[i] % 2 == 0){ //when divisible by both 2 and 3 if(myArr[i] % 3 == 0){ //when divisible by all if(myArr[i] % 5 == 0){ myArr.splice(i,1, 'yu-gi-oh') } else { myArr.splice(i,1, 'yu-gi') } } //when divisible by both 2 and 5 else if (myArr[i] % 5 == 0){ myArr.splice(i,1, 'yu-oh') } //when divisible by 2 only else{ myArr.splice(i,1, 'yu') } } else if(myArr[i] % 3 == 0){ //when divisible by both 3 and 5 if (myArr[i] % 5 == 0){ myArr.splice(i,1, 'gi-oh') } //when divisible by 3 only else{ myArr.splice(i,1, 'gi') } } //when divisible by 5 only else if(myArr[i] % 5 == 0){ myArr.splice(i,1, 'oh') } //when divisible by none else { continue } } return myArr }
913893541a1943e1e6c4aad0987c21ec24595e36
[ "JavaScript" ]
1
JavaScript
abdrah3Em/zuri-algorithm
89a83cf3ed41bff88e414a3bcd8dc393ccdf7359
8b126b2cd45c8063b40bdf5712d1e221fe40d681
refs/heads/master
<repo_name>RaysBox/TestingPopMenu<file_sep>/app/src/main/java/com/app/ray/testingpopmenu/MainActivity.java package com.app.ray.testingpopmenu; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.PopupMenu; import android.widget.TextView; import static android.widget.PopupMenu.OnMenuItemClickListener; public class MainActivity extends AppCompatActivity { private TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = (TextView) super.findViewById(R.id.text); text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final PopupMenu popupmenu = new PopupMenu(MainActivity.this, text); // popupmenu.inflate(R.menu.menu_demo1); // API 14以上才支援此方法. popupmenu.getMenuInflater().inflate(R.menu.menu_demo1, popupmenu.getMenu()); popupmenu.setOnMenuItemClickListener(new OnMenuItemClickListener() { // 設定popupmenu項目點擊傾聽者. @Override public boolean onMenuItemClick(MenuItem item) { // 項目被點擊後變更文字顏色. switch (item.getItemId()) { // 取得被點擊的項目id. case R.id.red: // 紅色項目被點擊,文字設定為紅色. text.setTextColor(Color.RED); break; case R.id.green: // 綠色項目被點擊,文字設定為綠色. text.setTextColor(Color.GREEN); break; case R.id.blue: // 藍色項目被點擊,文字設定為藍色. text.setTextColor(Color.BLUE); break; default: break; } return true; } }); popupmenu.show(); } }); // text.setOnLongClickListener(new OnLongClickListener() { // 設定text長按傾聽者. // // @Override // public boolean onLongClick(View v) { // 長按時建立彈出選單並顯示. // final PopupMenu popupmenu = new PopupMenu(MainActivity.this, text); //// popupmenu.inflate(R.menu.menu_demo1); // API 14以上才支援此方法. // popupmenu.getMenuInflater().inflate(R.menu.menu_demo1, popupmenu.getMenu()); // popupmenu.setOnMenuItemClickListener(new OnMenuItemClickListener() { // 設定popupmenu項目點擊傾聽者. // // @Override // public boolean onMenuItemClick(MenuItem item) { // 項目被點擊後變更文字顏色. // switch (item.getItemId()) { // 取得被點擊的項目id. // case R.id.red: // 紅色項目被點擊,文字設定為紅色. // text.setTextColor(Color.RED); // break; // case R.id.green: // 綠色項目被點擊,文字設定為綠色. // text.setTextColor(Color.GREEN); // break; // case R.id.blue: // 藍色項目被點擊,文字設定為藍色. // text.setTextColor(Color.BLUE); // break; // default: // break; // } // return true; // } // // }); // popupmenu.show(); // return true; // } // }); } }
ae23d465a69954394677ce64bfe2b292dc919c1c
[ "Java" ]
1
Java
RaysBox/TestingPopMenu
8684d6f8babf721603feefc760f9c7f05974916f
d7537447180157811a9887d7ab46e29d318531aa
refs/heads/main
<file_sep><?php namespace App\Http\Controllers; use DB; use Illuminate\Http\Request; class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } /** * Show the application dashboard. * * @return \Illuminate\Contracts\Support\Renderable */ public function index() { // $jumlah = 0; $user = DB::table('member')->count(); $peminjam = DB::table('peminjaman')->where('keadaan', '=', 'Belum Dikembalikan')->count(); $buku = DB::table('buku')->get(); $tot_buku = DB::table('buku')->count(); return view('home', ['var_user' => $user, 'var_peminjam' => $peminjam, 'var_buku' => $buku, 'var_tot' => $tot_buku]); } }<file_sep># project_perpustakaan <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\member_model; use App\users_model; use App\kategori_model; use App\buku_model; use App\peminjaman_model; use Illuminate\Support\Facades\Auth; use App\Http\Controllers\Hash; use DB; class DataController extends Controller { public function index() { return view('home'); } public function user() { $member = member_model::all(); return view('data_user', ['var_member' => $member]); } // Bagian Karyawan public function karyawan() { $users = users_model::all(); return view('data_karyawan', ['var_user' => $users]); } public function kategori_buku() { $kategori = kategori_model::all(); return view('kategori_buku', ['var_kategori' => $kategori]); } public function buku() { $kategori = kategori_model::all(); return view('buku', ['var_kategori' => $kategori]); } public function data_buku($id) { $buku = buku_model::where('id_kategori', $id)->get(); $kategori = kategori_model::where('id_kategori', $id)->first(); return view('detail_buku', ['var_buku' => $buku, 'var_id' => $id, 'var_kategori' => $kategori]); } public function peminjaman_buku() { $member = member_model::all(); $buku = buku_model::all(); $peminjaman = DB::table('peminjaman') ->join('member', 'peminjaman.id_member', '=', 'member.id_member') ->join('buku', 'peminjaman.id_buku', '=', 'buku.id') ->join('kategori_buku', 'buku.id_kategori', '=', 'kategori_buku.id_kategori') ->join('users', 'peminjaman.id', '=', 'users.id') ->select('peminjaman.*', 'member.nama_member', 'buku.judul_buku', 'users.name', 'kategori_buku.nama_kategori') ->get(); return view('peminjaman_buku', ['var_buku' => $buku, 'var_member' => $member, 'var_peminjaman' => $peminjaman]); } public function info() { return view('info'); } public function insert_member(Request $req) { $v = $this->validate($req, [ 'name' => 'required|max:200', 'alamat' => 'required|max:300', 'no_telp' => 'required|max:15', 'tgl_lahir' => 'required|date_format:Y-m-d' ]); if ($v) { $mb = new member_model(); $mb->nama_member = $req["name"]; $mb->alamat = $req["alamat"]; $mb->no_telp = $req["no_telp"]; $mb->tgl_lahir = $req["tgl_lahir"]; $mb->save(); session()->flash('berhasil', 'Data Anda Berhasil Ditambahkan'); return redirect('/user'); } } public function edit_member($id) { $member = member_model::where('id_member', $id)->first(); return view('/edit_member', ['var_member' => $member]); } public function proses_edit_member(Request $req) { $v = $this->validate($req, [ 'name' => 'required|max:200', 'alamat' => 'required|max:300', 'no_telp' => 'required|max:15', 'tgl_lahir' => 'required|date_format:Y-m-d' ]); if ($v) { $member = member_model::where('id_member', $req['id'])->update(['nama_member' => $req["name"], 'alamat' => $req["alamat"], 'no_telp' => $req["no_telp"], 'tgl_lahir' => $req["tgl_lahir"]]); if ($member) { session()->flash('berhasil', 'Data Anda Berhasil Diubah'); return redirect('/user'); } else { session()->flash('gagal', 'Data Anda Gagal Diubah'); return redirect('/ubah_member/' . $req["id"]); } } } public function hapus_member($id) { $member = member_model::where("id_member", $id); $member->delete(); session()->flash('berhasil', 'Data Anda Berhasil Dihapus'); return redirect('/user'); } public function insert_kategori(Request $req) { $v = $this->validate($req, [ 'name' => 'required|max:200', 'deskripsi' => 'required|max:300', ]); if ($v) { $kategori = new kategori_model(); $kategori->nama_kategori = $req['name']; $kategori->deskripsi = $req['deskripsi']; $kategori->created_by = Auth::user()->name; $kategori->save(); session()->flash('berhasil', 'Data Anda Berhasil Ditambahkan'); return redirect('/kategori_buku'); } } public function edit_kategori($id) { $kategori = kategori_model::where('id_kategori', $id)->first(); return view('/edit_kategori', ['var_kategori' => $kategori]); } public function proses_edit_kategori(Request $req) { $v = $this->validate($req, [ 'name' => 'required|max:200', 'deskripsi' => 'required|max:300', ]); if ($v) { $kategori = kategori_model::where('id_kategori', $req['id'])->update(['nama_kategori' => $req["name"], 'deskripsi' => $req["deskripsi"]]); if ($kategori) { session()->flash('berhasil', 'Data Anda Berhasil Diubah'); return redirect('/kategori_buku'); } else { session()->flash('gagal', 'Data Anda Gagal Diubah'); return redirect('/ubah_kategori/' . $req["id"]); } } } public function hapus_kategori($id) { $member = kategori_model::where("id_kategori", $id); $member->delete(); session()->flash('berhasil', 'Data Anda Berhasil Dihapus'); return redirect('/kategori_buku'); } public function insert_buku(Request $req) { $v = $this->validate($req, [ 'name' => 'required|max:300', 'pengarang' => 'required|max:300', 'penerbit' => 'required|max:200', 'tebal' => 'required|max:10', 'thn_terbit' => 'required|date_format:Y-m-d', 'edisi' => 'required|max:10', 'jumlah' => 'required|max:10' ]); if ($v) { $buku = new buku_model(); $buku->id_kategori = $req['id']; $buku->judul_buku = $req['name']; $buku->nama_pengarang = $req['pengarang']; $buku->nama_penerbit = $req['penerbit']; $buku->ketebalan = $req['tebal']; $buku->tahun_terbit = $req['thn_terbit']; $buku->edisi_buku = $req['edisi']; $buku->jumlah_buku = $req['jumlah']; $buku->created_by = Auth::user()->name; $buku->save(); session()->flash('berhasil', 'Data Anda Berhasil Ditambahkan'); return redirect('/detail_buku/' . $req["id"]); } } public function edit_buku($id) { $buku = buku_model::where('id', $id)->first(); $kategori = kategori_model::all(); return view('/edit_buku', ['var_buku' => $buku, 'var_kategori' => $kategori]); } public function proses_edit_buku(Request $req) { $v = $this->validate($req, [ 'name' => 'required|max:300', 'kategori' => 'required', 'pengarang' => 'required|max:300', 'penerbit' => 'required|max:200', 'tebal' => 'required|max:10', 'thn_terbit' => 'required|date_format:Y-m-d', 'edisi' => 'required|max:10', 'jumlah' => 'required|max:10' ]); if ($v) { $kategori = buku_model::where('id', $req['id'])->update(['id_kategori' => $req['kategori'], 'judul_buku' => $req["name"], 'nama_pengarang' => $req["pengarang"], 'nama_penerbit' => $req["penerbit"], 'ketebalan' => $req["tebal"], 'tahun_terbit' => $req["thn_terbit"], 'edisi_buku' => $req["edisi"], 'jumlah_buku' => $req["jumlah"], 'created_by' => Auth::user()->name]); if ($kategori) { session()->flash('berhasil', 'Data Anda Berhasil Diubah'); return redirect('/buku'); } else { session()->flash('gagal', 'Data Anda Gagal Diubah'); return redirect('/detail_buku/ubah_buku/' . $req["id"]); } } } public function hapus_buku($id) { $member = buku_model::where("id", $id); $member->delete(); session()->flash('berhasil', 'Data Anda Berhasil Dihapus'); return redirect('/buku'); } public function insert_peminjaman(Request $req) { $v = $this->validate($req, [ 'member' => 'required', 'buku' => 'required', ]); if ($v) { $peminjaman = new peminjaman_model(); $peminjaman->id_member = $req['member']; $peminjaman->id_buku = $req['buku']; $peminjaman->id = $req['penginput']; $peminjaman->keadaan = 'Belum Dikembalikan'; $peminjaman->save(); $jml_buku = DB::table('buku')->where('id', '=', $req['buku'])->select('jumlah_buku')->get(); $total = $jml_buku[0]->jumlah_buku - 1; // dd($total); $buku = buku_model::where('id', $req['buku'])->update(['jumlah_buku' => $total]); session()->flash('berhasil', 'Data Anda Berhasil Ditambahkan'); return redirect('/peminjaman_buku'); } } public function ubah_status($id) { $data = DB::table('peminjaman')->where('id_peminjaman', '=', $id)->select(DB::raw('datediff(updated_at,created_at) as total'))->get(); if ($data[0]->total > 7) { $denda = 25000; $administrasi = 5000; $total = $denda + $administrasi; } else { $denda = 0; $administrasi = 5000; $total = $denda + $administrasi; } $peminjaman = peminjaman_model::where("id_peminjaman", $id)->update(['lama' => $data[0]->total, 'keadaan' => "Sudah Dikembalikan", 'updated_by' => Auth::user()->name, 'denda' => $denda, 'administrasi' => $administrasi, 'total_biaya' => $total]); // Total Buku $jmlh = DB::table('peminjaman') ->where([['peminjaman.id_peminjaman', '=', $id]]) ->join('buku', 'peminjaman.id_buku', '=', 'buku.id') ->select('buku.*')->first(); $total = $jmlh->jumlah_buku + 1; $buku = buku_model::where("id", $jmlh->id)->update(['jumlah_buku' => $total]); if ($peminjaman && $buku) { session()->flash('berhasil', 'Data Anda Berhasil Diubah'); return redirect('/peminjaman_buku'); } else { session()->flash('gagal', 'Data Anda Gagal Diubah'); return redirect('/peminjaman_buku'); } } public function hapus_peminjaman($id) { $member = peminjaman_model::where("id_peminjaman", $id); $member->delete(); session()->flash('berhasil', 'Data Anda Berhasil Dihapus'); return redirect('/peminjaman_buku'); } // Ubah User public function ubah_user() { return view('edit_user'); } public function proses_edit_user(Request $req) { $v = $this->validate($req, [ 'name' => 'required', 'email' => 'required', 'password' => '<PASSWORD>' ]); if ($v) { if (\Hash::check($req['password'], Auth::user()->password)) { if ($req['email'] == Auth::user()->email) { users_model::where('id', Auth::user()->id)->update(['name' => $req['name'], 'email' => $req["email"]]); session()->flash('berhasil', 'Data Anda Berhasil Diubah'); return redirect('/home'); } else { $email = DB::table('users')->where('email', '=', $req['email'])->first(); if ($email) { session()->flash('gagal', 'Data Anda Gagal Diubah'); return redirect('/ubah_user'); } else { users_model::where('id', Auth::user()->id)->update(['name' => $req['name'], 'email' => $req["email"]]); session()->flash('berhasil', 'Data Anda Berhasil Diubah'); return redirect('/home'); } } } else { session()->flash('gagal', 'Data Anda Gagal Diubah'); return redirect('/ubah_user'); } } } }<file_sep><?php use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return redirect('/login'); }); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); Route::get('/user_karyawan', 'DataController@karyawan')->name('karyawan'); Route::get('/kategori_buku', 'DataController@kategori_buku')->name('kategori_buku'); Route::get('/buku', 'DataController@buku')->name('buku'); Route::get('/peminjaman_buku', 'DataController@peminjaman_buku')->name('peminjaman_buku'); Route::get('/info', 'DataController@info')->name('info'); Route::get('/detail_buku/{id}', 'DataController@data_buku'); // Data Member Route::post('/insert_new_member', 'DataController@insert_member')->name('insert_new_member'); Route::post('/proses_edit_member', 'DataController@proses_edit_member')->name('proses_edit_member'); Route::get('/user', 'DataController@user')->name('member'); Route::get('/ubah_member/{id}', 'DataController@edit_member'); Route::get('/hapus_member/{id}', 'DataController@hapus_member'); // Kategori Route::post('/insert_new_kategori', 'DataController@insert_kategori')->name('insert_new_kategori'); Route::get('/ubah_kategori/{id}', 'DataController@edit_kategori'); Route::get('/hapus_kategori/{id}', 'DataController@hapus_kategori'); Route::post('/proses_edit_kategori', 'DataController@proses_edit_kategori')->name('proses_edit_kategori'); Route::get('/hapus_kategori/{id}', 'DataController@hapus_kategori'); // Buku Route::post('/insert_new_buku', 'DataController@insert_buku')->name('insert_new_buku'); Route::get('/detail_buku/ubah_buku/{id}', 'DataController@edit_buku'); Route::get('/detail_buku/hapus_buku/{id}', 'DataController@hapus_buku'); Route::post('/proses_edit_buku', 'DataController@proses_edit_buku')->name('proses_edit_buku'); // Peminjaman Route::post('/insert_new_peminjaman', 'DataController@insert_peminjaman')->name('insert_new_peminjaman'); Route::get('/ubah_status/{id}', 'DataController@ubah_status'); Route::get('/hapus_peminjaman/{id}', 'DataController@hapus_peminjaman'); // User Route::get('/ubah_user', 'DataController@ubah_user')->name('ubah_user'); Route::post('/proses_edit_user', 'DataController@proses_edit_user')->name('proses_edit_user');
38767bd4880d21d797d6a8ba4ccdf661441886db
[ "Markdown", "PHP" ]
4
PHP
NizarDwiSetyawan/project_perpustakaan
cd8208759e496f88550dd5e7f15d74c4f9802a61
e10e40c2f243c81210ada59239b5ed02cdd70e4d
refs/heads/master
<repo_name>dokspribadi/example-php-sti-helloworld<file_sep>/README.md # PHP source to image Helloworld Example This is an example php application, which can be deployed to APPUiO using the following commands ## How to deploy ### Webconsole * log into your OpenShift V3 Master (eg. https://master.appuio-beta.ch) * Create a new Project * "Add to Project" a php:5.6 application * name the application for example appuio-php-sti-example and provide the git repository URL, in this example https://github.com/appuio/example-php-sti-helloworld.git * the build and deployment is automatically triggered and the example application will be deployed soon ### CLI / oc Client #### Create New OpenShift Project ``` $ oc new-project example-php-sti-helloworld ``` #### Create Application and expose Service ``` $ oc new-app https://github.com/appuio/example-php-sti-helloworld.git --name=appuio-php-sti-example $ oc expose service appuio-php-sti-example ``` ## Add Webhook to trigger rebuilds Take the Webhook GitHub URL from ``` $ oc describe bc appuio-php-sti-example oc describe bc appuio-php-sti-example Name: appuio-php-sti-example Created: 20 seconds ago Labels: app=appuio-php-sti-example Annotations: openshift.io/generated-by=OpenShiftNewApp Latest Version: 1 Strategy: Source Source Type: Git URL: https://github.com/appuio/example-php-sti-helloworld.git From Image: ImageStreamTag openshift/php:latest Output to: ImageStreamTag appuio-php-sti-example:latest Triggered by: Config, ImageChange Webhook GitHub: https://[Server]/oapi/v1/namespaces/example-php-sti-helloworld/buildconfigs/appuio-php-sti-example/webhooks/[GitHubsecret]/github Webhook Generic: https://[Server]/oapi/v1/namespaces/example-php-sti-helloworld/buildconfigs/appuio-php-sti-example/webhooks/[genericsecret]/generic ``` and add the URL as a Webhook in your github Repository, read https://developer.github.com/webhooks/ for more details about github Webhooks <file_sep>/env/index.php <?php $envs = getenv(); foreach ($envs as $key => $value){ print("Var: " . $key . "=" . $value . "/n"); } ?>
57e34d0fb7e82f978500a4f915603a963a9689e8
[ "Markdown", "PHP" ]
2
Markdown
dokspribadi/example-php-sti-helloworld
fa567b84c3ff050a14d8aafff697027d9857c607
95929b762f2caeaf0154ea04ea735b02c6c6f4be
refs/heads/main
<repo_name>marvinkome/webdrop<file_sep>/src/hooks/receive.ts import Peer from "peerjs" import React, { useState, useEffect, useRef } from "react" import { setupPeerJS } from "utils" import { FileBuilder } from "utils/file" import { useBitrate } from "./bitrate" export function useReceiveFile(dataConn?: Peer.DataConnection) { const [fileInfo, setFileInfo] = useState<{ name: string; size: number }>() const [transferStarted, setTransferStarted] = useState(false) const [transferCompleted, setTransferCompleted] = useState(false) const [transferedSize, setTransferredSize] = useState(0) const bitrateObj = useBitrate(false) const fileBuilder = useRef<FileBuilder>() function receiveFile(data: any) { if (typeof data === "string") { console.log("[receiveFile] Receive file details", data) const parsedData = JSON.parse(data) setFileInfo({ name: parsedData.name, size: parsedData.size }) fileBuilder.current = new FileBuilder(parsedData) fileBuilder.current.onAddChunk = (newSize) => { setTransferredSize(newSize) } fileBuilder.current.onComplete = () => { setTransferStarted(false) setTransferCompleted(true) bitrateObj.cancel() dataConn?.close() } return } if (!transferStarted) setTransferStarted(true) fileBuilder.current?.addChunk(data) } useEffect(() => { dataConn?.on("open", async () => { bitrateObj.init(dataConn?.peerConnection!) dataConn?.on("data", receiveFile) }) }, [dataConn]) return { fileInfo, transferCompleted, transferStarted, transferedSize, bitrate: bitrateObj.bitrate, } } export function useConnectionSetup() { const [peer, setPeer] = useState<Peer>() const [connection, setConnection] = useState<Peer.DataConnection>() // connection state const [hasError, setHasError] = useState(false) const [loading, setLoading] = useState(false) const [hasConnected, setHasConnected] = useState(false) // on mount set peer useEffect(() => { setupPeerJS().then((peer) => setPeer(peer)) }, []) // listen for error useEffect(() => { if (!peer) return const errorListener = (err: any) => { if (err.type === "peer-unavailable") { setHasError(true) setLoading(false) } } peer.on("error", errorListener) return () => { peer.off("error", errorListener) } }, [peer]) const connectWithSender = async (e: React.FormEvent) => { e.preventDefault() setHasError(false) // @ts-ignores const accessCode = e.target["code"].value // try to connect setLoading(true) const connection = peer?.connect(accessCode, { reliable: true, }) connection?.on("open", () => { setHasError(false) setLoading(false) setHasConnected(true) }) setConnection(connection) } return { state: { hasError, loading, hasConnected, }, peer, dataConn: connection, connect: connectWithSender, } } <file_sep>/src/utils/file.ts import { dowloadUrl } from "utils" // I'm doing this because EventTarget doens't exist on server side export function fileSplitterCreator(file: File, chunkSize?: number) { if (typeof window === "undefined") return class FileSplitter extends EventTarget { CHUNK_SIZE = 16384 offset: number = 0 fileReader = new FileReader() file: File paused: boolean = false constructor(file: File, chunkSize?: number) { super() this.file = file if (chunkSize && chunkSize !== 0) { this.CHUNK_SIZE = chunkSize } // add event listener for fileReader this.fileReader.addEventListener("load", (e) => { this.dispatchEvent( new CustomEvent("split-file", { detail: { chunk: e.target?.result }, }) ) this.offset += (e.target?.result as ArrayBuffer).byteLength this.dispatchEvent( new CustomEvent("update-offset", { detail: { offset: this.offset }, }) ) if (!this.paused && this.offset < this.file.size) { this.readSlice(this.offset) } }) } readSlice(offset: number) { const slice = this.file.slice(this.offset, offset + this.CHUNK_SIZE) this.fileReader.readAsArrayBuffer(slice) } start() { this.readSlice(0) this.dispatchEvent(new Event("start")) } pause() { this.paused = true this.dispatchEvent(new Event("pause")) } resume() { this.paused = false this.dispatchEvent(new Event("resume")) // resume reading from file this.readSlice(this.offset) } } return new FileSplitter(file, chunkSize) } export class FileBuilder { fileDetails: { name: string; size: number; type: string } chunkSize: number = 0 fs: any fileEntry: any onComplete?: () => void onAddChunk?: (newSize: number) => void onError?: () => void constructor(details: { name: string; size: number; type: string }) { this.fileDetails = details this._requestFs() } addChunk(chunk: ArrayBuffer) { const onError = (e: any) => console.log(this._errorHandler(e)) const onSuccess = (fileEntry: any) => { this.fileEntry = fileEntry fileEntry.createWriter((writer: any) => { const data = new Blob([chunk], { type: this.fileDetails.type }) writer.onwriteend = () => this._onWrite(data.size) writer.onerror = (error: any) => { this._errorHandler(error) this.onError && this.onError() } writer.seek(writer.length) writer.write(data) }, onError) } this.fs.root.getFile( this.fileDetails.name, { create: !!!this.chunkSize }, onSuccess, onError ) } saveFile() { console.log("[FileBuilder] File ready for download") let fileUrl // @ts-ignore if (window.webkitRequestFileSystem) { fileUrl = this.fileEntry.toURL() } else { this.fileEntry.file((file: any) => { fileUrl = URL.createObjectURL(file) }) } dowloadUrl(fileUrl, this.fileDetails.name) this.onComplete && this.onComplete() } _onWrite = (dataLength: number) => { this.chunkSize += dataLength const newSize = Math.floor((this.chunkSize / this.fileDetails.size) * 100) this.onAddChunk && this.onAddChunk(newSize) if (this.chunkSize >= this.fileDetails.size) { this.saveFile() } } _requestFs = () => { // @ts-ignore const requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem const onInit = (fs: any) => { this.fs = fs console.log("[FileBuilder]: File system setup - done.") } requestFileSystem( // @ts-ignore window.TEMPORARY, this.fileDetails.size, onInit, this._errorHandler ) } _errorHandler = (e: any) => { let msg = "" switch (e.code) { // @ts-ignore case FileError.QUOTA_EXCEEDED_ERR: msg = "QUOTA_EXCEEDED_ERR" break // @ts-ignore case FileError.NOT_FOUND_ERR: msg = "NOT_FOUND_ERR" break // @ts-ignore case FileError.SECURITY_ERR: msg = "SECURITY_ERR" break // @ts-ignore case FileError.INVALID_MODIFICATION_ERR: msg = "INVALID_MODIFICATION_ERR" break // @ts-ignore case FileError.INVALID_STATE_ERR: msg = "INVALID_STATE_ERR" break default: msg = "Unknown Error" break } console.log("[FileSystem] Error: " + msg) return msg } } <file_sep>/README.md # WebDrop [https://webdrop.netlify.app](https://webdrop.netlify.app) File transfer using WebRTC and PeerJS <file_sep>/src/utils/index.ts import { customAlphabet } from "nanoid" const alphabet = "123456789ABCDEFGHIJKLMNPQRSTUVWXYZ" const nanoid = customAlphabet(alphabet, 6) export function dowloadUrl(url: string, name: string) { const a = document.createElement("a") a.href = url a.download = name a.click() } export function chunkFile(file: File, onSplit: (e: ProgressEvent<FileReader>) => void) { const chunkSize = 16384 let offset = 0 let fileReader = new FileReader() const readSlice = (o: number) => { console.log("[chunkFile] readSlice: ", o) const slice = file.slice(offset, o + chunkSize) fileReader.readAsArrayBuffer(slice) } fileReader.addEventListener("error", (error) => console.error("Error reading file:", error)) fileReader.addEventListener("abort", (event) => console.log("File reading aborted:", event)) fileReader.addEventListener("load", (e) => { console.log("[read-file] FileRead.onload", e) onSplit(e) offset += (e.target?.result as ArrayBuffer).byteLength if (offset < file.size) { readSlice(offset) } }) return readSlice } export async function setupPeerJS() { const { default: PeerJS } = await import("peerjs") const code = nanoid() const options: any = {} if (process.env.NODE_ENV !== "production") { options.debug = 2 } return new PeerJS(code, options) } <file_sep>/src/hooks/transfer.ts import Peer from "peerjs" import { useState, useEffect, useRef } from "react" import { useToast } from "@chakra-ui/react" import { fileSplitterCreator } from "utils/file" import { setupPeerJS } from "utils" import { useBitrate } from "./bitrate" export function useFileTransfer(peer?: Peer, file?: File) { const [transferStarted, setTransferStarted] = useState(false) const [transferCompleted, setTransferCompleted] = useState(false) const [transferedSize, setTransferredSize] = useState(0) const bitrateObj = useBitrate(true) const fileSplitter = useRef<ReturnType<typeof fileSplitterCreator>>() function transferFile(dataConn: Peer.DataConnection) { if (!file) return // send file details to peer const fileDetails = JSON.stringify({ name: file.name, size: file.size, type: file.type, }) dataConn.send(fileDetails) // send file fileSplitter.current = fileSplitterCreator(file) fileSplitter.current?.start() // add listeners fileSplitter.current?.addEventListener("split-file", (e: any) => { setTransferStarted(true) dataConn.send(e.detail.chunk) }) fileSplitter.current?.addEventListener("update-offset", (e: any) => { const offset = e.detail.offset setTransferredSize(Math.floor((offset / file.size) * 100)) if (offset >= file.size) { setTransferStarted(false) setTransferCompleted(true) } }) } useEffect(() => { if (!peer) return const onConnection = (dataConn: Peer.DataConnection) => { dataConn.on("open", async () => { console.log(dataConn.peerConnection) await bitrateObj.init(dataConn.peerConnection) transferFile(dataConn) }) dataConn.on("close", bitrateObj.cancel) } peer.on("connection", onConnection) }, [peer, file]) return { transferStarted, transferCompleted, transferedSize, bitrate: bitrateObj.bitrate, } } export function useTransferSetup() { const toast = useToast({ position: "top-right", isClosable: true }) const [file, setFile] = useState<File>() const [peer, setPeer] = useState<Peer>() const onSelectFile = async (file: File) => { if (file.size === 0) { toast({ title: "File empty", description: "Please choose a valid file" }) return } const peer = await setupPeerJS() setFile(file) setPeer(peer) } return { file, peer, onSelectFile, } } <file_sep>/src/hooks/bitrate.ts import { useState, useRef } from "react" export function useBitrate(sending: boolean) { const [bitrate, setBitrate] = useState(0) const statsInterval = useRef<any>() const timestampStart = useRef(0) const timestampPrev = useRef(0) const bytesPrev = useRef(0) async function calculateBitrate(remoteConnection: RTCPeerConnection) { if (remoteConnection.iceConnectionState !== "connected") return const stats = await remoteConnection.getStats() let activeCandidatePair: any stats.forEach((report) => { if (report.type === "transport") { activeCandidatePair = stats.get(report.selectedCandidatePairId) } }) if (!activeCandidatePair) return if (timestampPrev.current === activeCandidatePair.timestamp) return const bytesNow = sending ? activeCandidatePair.bytesSent : activeCandidatePair.bytesReceived const bitrate = Math.round( ((bytesNow - bytesPrev.current) * 8) / ((activeCandidatePair.timestamp - timestampPrev.current) / 1000) ) timestampPrev.current = activeCandidatePair.timestamp bytesPrev.current = bytesNow setBitrate(bitrate) return bitrate } async function init(remoteConnection: RTCPeerConnection) { timestampStart.current = new Date().getTime() timestampStart.current = new Date().getTime() timestampPrev.current = timestampStart.current statsInterval.current = setInterval(() => calculateBitrate(remoteConnection), 500) await calculateBitrate(remoteConnection) } function cancel() { clearInterval(statsInterval.current) setBitrate(0) } return { bitrate, init, cancel } } <file_sep>/src/server.ts import express from "express" import { createServer } from "http" import next from "next" import { ExpressPeerServer } from "peer" const app = express() const server = createServer(app) const dev = process.env.NODE_ENV !== "production" const port = process.env.PORT || 8081 const nextApp = next({ dev }) const handle = nextApp.getRequestHandler() const peerServer = ExpressPeerServer(server, { path: "/peer", }) app.use("/api", peerServer) nextApp.prepare().then(() => { app.get("*", (req, res) => { return handle(req, res) }) server.listen(port, () => { console.log(`Ready! on localhost:${port}`) }) })
a645c68046ef0244a24f61740cced412d71d6b52
[ "Markdown", "TypeScript" ]
7
TypeScript
marvinkome/webdrop
a54f1ee90899cbfc8019c703009dc2d0835d9cf3
853e94464e91e5fd82f2eb5fde9d9c09160883b2
refs/heads/master
<repo_name>huangcheng/todo<file_sep>/src/app/todo.component.jsx import React from 'react'; /* * Paper component */ class Paper extends React.Component { constructor(props) { super(props); } render() { return ( <div className="layer paper"> <TodoListControls /> <TodoList { ...this.props }/> <TodoListPager /> </div> ); } } /* * Shadow component */ class Shadow extends React.Component { constructor(props) { super(props); } render() { let clsName = "layer shadow"; clsName += '-' + this.props.id; return ( <div className={ clsName }></div> ); } } /* * To-do list controls component */ class TodoListControls extends React.Component { render() { return ( <div className="controls"> <Checkbox /> <Separator /> <ControlContent /> </div> ); } } /* * To-do list component */ class TodoList extends React.Component { constructor(props) { super(props); } render() { let items = []; this.props.data.map(function(item) { items.push(<TodoItem key={ item.id } todo={ item } />); }); return ( <div className="list"> { items } </div> ); } } /* * To-do component */ class TodoItem extends React.Component { constructor(props) { super(props); } render() { return ( <div className="todo"> <Checkbox /> <Separator /> <TodoContent todo={ this.props.todo } /> </div> ); } } /* * Pager component. */ class TodoListPager extends React.Component { render() { return( <div className="pager"> <Checkbox /> <Separator /> <PagerContent /> </div> ); } } /* * Checkbox component */ class Checkbox extends React.Component { render() { return( <div className="checkbox"> <input type="checkbox" /> </div> ); } } /* * Separator component */ class Separator extends React.Component { render() { return( <span className="separator"></span> ); } } /* * Content component for control panel. */ class ControlContent extends React.Component { render() { return( <div className="content"> <div className="control add"> <i className="icon"></i> <span className="tip">Add</span> </div> <div classNameName="control trash"> <i className="icon"></i> <span className="tip">Trash</span> </div> <div className="control setting"> <i className="icon"></i> <span className="tip">Setting</span> </div> </div> ); } } /* * Content component for pager panel. */ class PagerContent extends React.Component { render() { return( <div className="content"> <span className="button prev"></span> <span className="button next"></span> </div> ); } } /* * Content component for to-do list item. */ class TodoContent extends React.Component { constructor(props) { super(props); } render() { return( <p className="content">{ this.props.todo.content } </p> ); } } export default class Todo extends React.Component { constructor(props) { super(props); } render() { var shadows = []; for(let i = 1; i <= this.props.shadowCount; ++i) { shadows.push(<Shadow key={i} id={i} />); } return ( <div className="todo-list"> <Paper data={ this.props.data }/> { shadows } </div> ); } }<file_sep>/README.md # Todo List [![devDependency Status](https://david-dm.org/huangcheng/todo/dev-status.svg)](https://david-dm.org/huangcheng/todo#info=devDependencies) [![Build Status](https://travis-ci.org/huangcheng/todo.svg?branch=master)](https://travis-ci.org/huangcheng/todo) ## Introduction A simple todo list built upon ***React.js*** ## Usage ### Run a live demo ``` shell gulp develop ``` ### Build ``` shell gulp build ``` ### Todo - [x] Constructing basic UI elements. - [ ] Storing & fetching data from ***Web SQL Database***. - [ ] Achieving multiple pages. - [ ] Achieving page switch effect. ## Acknowledgement Thanks for [<NAME>](https://dribbble.com/facugonzalez)'s [degin](https://dribbble.com/shots/240035-Simple-to-do-Freebie)<file_sep>/gulpfile.js /* * Load gulp and its plugins. */ const gulp = require('gulp'); const less = require('gulp-less'); const copy = require('gulp-copy'); const autoprefix = new (require('less-plugin-autoprefix'))({ browsers: ["last 2 versions"] }); /* * Load utilities. */ const webpack = require('webpack-stream'); const browserSync = require('browser-sync').create(); /* * Prevent a faulty task from crashing the server. */ function preventCrash (error) { console.log(error.toString()); this.emit('end'); } /* * Serve files under dist directory. */ gulp.task('browser-sync', function() { browserSync.init({ server: { baseDir: "dist" } }); }); gulp.task('webpack', function() { return gulp.src('src/app/main.js') .pipe(webpack(require('./webpack.config.js'))) .on('error', preventCrash) .pipe(gulp.dest('dist/js')); }); gulp.task('less', function() { return gulp.src('src/less/*.less') .pipe(less({ plugins: [autoprefix] })) .on('error', preventCrash) .pipe(gulp.dest('dist/css')); }); gulp.task('serve', ['browser-sync'], function() { gulp.watch("dist/*.html").on('change', browserSync.reload); gulp.watch("dist/js/*.js").on('change', browserSync.reload); gulp.watch("dist/css/*.css").on('change', browserSync.reload); }); gulp.task('watch', function() { gulp.watch('src/**/*.less', ['less']); gulp.watch(['src/**/*.js', 'src/**/*.jsx'], ['webpack']); gulp.watch('src/**/*.html', ['html']); gulp.watch('src/images/*.*', ['images']); }); gulp.task('html', function() { return gulp.src('src/**/index.html') .pipe(copy('dist/', { prefix: 2 })); }); gulp.task('images', function() { return gulp.src('src/images/*.*') .pipe(copy('dist/images', { prefix: 2 })); }); gulp.task('build', ['webpack', 'less', 'html', 'images']); gulp.task('develop', ['build', 'serve', 'watch']); gulp.task('default', ['build']); <file_sep>/src/app/main.js import React from 'react'; import ReactDOM from 'react-dom'; import Todo from './todo.component.jsx'; const todo = [ { id: 1, status: "pending", content: "Reading" }, { id: 2, status: "pending", content: "Coding" }, { id: 3, status: "pending", content: "Shopping" }, { id: 4, status: "pending", content: "Doing some homework" }, { id: 5, status: "pending", content: "Playing games" } ]; function main() { ReactDOM.render(<Todo shadowCount={ 3 } data={ todo }/>, document.getElementById('app')); } main();
93a8baf0cd1d80e74a94e9b5d3a29007a24c89bb
[ "JavaScript", "Markdown" ]
4
JavaScript
huangcheng/todo
1064c5509e2316012c9c3857b21e2091b6baccc6
cf1369386d8ad36482e4f3baa1b17518506c4b90
refs/heads/master
<file_sep>package app.footballclub import android.os.Parcelable import kotlinx.android.parcel.Parcelize @Parcelize data class Item (val name: String?, val image: Int?):Parcelable{ }<file_sep>package app.footballclub import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v7.view.menu.MenuView import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.widget.Toast import app.footballclub.R.attr.layoutManager import app.footballclub.R.id.* import app.footballclub.R.layout.item_list import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.item_list.view.* import org.jetbrains.anko.* import org.jetbrains.anko.recyclerview.v7.recyclerView import org.jetbrains.anko.sdk25.coroutines.onClick class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) MainActivityUI().setContentView(this) } class MainActivityUI : AnkoComponent<MainActivity> { override fun createView(ui: AnkoContext<MainActivity>) = with(ui) { verticalLayout { recyclerView { name?.onClick { startActivity<MainActivity>("name" to "{name.text}") } }.lparams(width = matchParent, height = wrapContent) fun initData() { val name = resources.getStringArray(R.array.club_name) val image = resources.obtainTypedArray(R.array.club_image) items.clear() for (i in name.indices) { items.add(Item(name[i], image.getResourceId(i, 0))) } //Recycle the typed array image.recycle() } } } //MutableList dari kelas Item.Kt private var items: MutableList<Item> = mutableListOf() }}
e1cceee0956402e84bbb016fb95db0b887d43c56
[ "Kotlin" ]
2
Kotlin
ReyzaldyIndra/KADE
e0c9e2790c4bd027dbabbebd34a43b9a83094e85
292e5551d11f0045b9f3796b1156935c2f812bc3
refs/heads/master
<file_sep>/** Programmer : Stanley Class : ET-575 Introduction to C++ Programming Design and Implementation Semester : Spring 2017 Date : 03/15/2017 Professor : Trowbridge Exam : Spring 2017 Final Exam Software uses : Code:blocks **/ #include <iostream> #include <cstdlib> using namespace std; //The dimension of the board. const int GRIDSIZE = 3; void populate(char board[GRIDSIZE][GRIDSIZE]); void output(char board[GRIDSIZE][GRIDSIZE]); bool isValidCoordinate(char board[GRIDSIZE][GRIDSIZE], int &posY, int &posX); bool isValidLocation(char board[GRIDSIZE][GRIDSIZE], int &posY, int &posX); void requestCoordinates(char board[GRIDSIZE][GRIDSIZE], int &posY, int &posX); void updateBoard(char board[GRIDSIZE][GRIDSIZE], char playerMark, int posY, int posX); bool checkRows(char board[GRIDSIZE][GRIDSIZE]); bool checkColumns(char board[GRIDSIZE][GRIDSIZE]); bool checkDiagonal(char board[GRIDSIZE][GRIDSIZE]); void menu(char board[GRIDSIZE][GRIDSIZE]); void checkGame(char board[GRIDSIZE][GRIDSIZE], char playerMark); int main() { cout << "+-------------------+" << endl; cout << "| TIC-TAC-TOE |" << endl; cout << "+-------------------+" << endl; char board[GRIDSIZE][GRIDSIZE]; menu(board); return 0; } //This function populate each element in the array with a ( _ ) . void populate(char board[GRIDSIZE][GRIDSIZE]){ for(int y = 0; y < GRIDSIZE; y++){ for(int x = 0; x < GRIDSIZE; x++){ board[y][x] = '_'; } } } //This function Print out the board on the console. void output(char board[GRIDSIZE][GRIDSIZE]){ //Clear the screen for the next game. system("CLS"); cout << " " << "+-------------------+" << endl; cout << " " << "| TIC-TAC-TOE |" << endl; cout << " " << "+-------------------+" << endl; for(int y = 0; y < GRIDSIZE; y++){ for(int x = 0; x < GRIDSIZE; x++){ board[y][x]; } } cout << endl << endl; cout << " " << board[0][0] << " | " << board[0][1] << " | " << board[0][2] << endl; cout << " " << "------+-------+------"<< endl; cout << " " << board[1][0] << " | " << board[1][1] << " | " << board[1][2] << endl; cout << " " << "------+-------+------"<< endl; cout << " " << board[2][0] << " | " << board[2][1] << " | " << board[2][2] << endl; } //This function check if a valid coordinate is entered for X or O. bool isValidCoordinate(char board[GRIDSIZE][GRIDSIZE], int &posY, int &posX){ if( (posX >= 0) && (posX < GRIDSIZE) && (posY >= 0) && (posY < GRIDSIZE) ){ return true; } return false; } //This function check if a the coordinate is empty ( _ ) or has an X or an O. bool isValidLocation(char board[GRIDSIZE][GRIDSIZE], int &posY, int &posX){ if( board[posY][posX] == '_'){ return true; } return false; } //This function request two numbers to form the coordinate for X or O. void requestCoordinates(char board[GRIDSIZE][GRIDSIZE], int &posY, int &posX){ do{ //Ask the current user player for y and X coordinate. cout << "Enter a value for Y-coordinate: "; cin >> posY; cout << "Enter a value for X-coordinate: "; cin >> posX; //Check if the Y and X values are valid. bool coordinate = isValidCoordinate(board, posY, posX); //If the coordinate is valid if(coordinate == true){ //Then check if the location on the array is empty. bool location = isValidLocation(board, posY, posX); //If the location is empty if(location == true){ //Get out of the loop break; } else{ //If the location is not empty, let the player knows cout << endl; cout << "Location is not empty, chose a different location!" << endl; //Then pause the game and wait for any key press to continue. system("Pause"); cout << endl; } }else{ //If the coordinate is not valid, let the current player knows cout << endl; cout << "The values are out of range!" << endl; //Then pause the game and for any key press to continue. system("Pause"); cout << endl; } }while(true); } //This function updated the board with an X or O after a valid coordinate is entered. void updateBoard(char board[GRIDSIZE][GRIDSIZE], char playerMark, int posY, int posX){ //Insert the player's mark in the array at location (Y,X) board[posY][posX] = playerMark; } //This function check if there is any row of X or O in the board. bool checkRows(char board[GRIDSIZE][GRIDSIZE]){ //Create a variable to count how many X found in each row. int x_count = 0; for(int y = 0; y < GRIDSIZE; y++){ x_count = 0; //reset the X counter for the next row. for(int x = 0; x < GRIDSIZE; x++){ //add one to the X counter each time an X is found. if(board[y][x] == 'X'){ x_count += 1; } } //If 3 X's are found in one row if(x_count == 3){ return true;//then, stop searching for more X. } } //Create a variable to count how many O found in each row. int o_count = 0; for(int y = 0; y < GRIDSIZE; y++){ o_count = 0; //reset the O counter for the next row. for(int x = 0; x < GRIDSIZE; x++){ //add one to the O counter each time an O is found. if(board[y][x] == 'O'){ o_count += 1; } } //If 3 O's are found in one row if(o_count == 3){ return true;//then, stop searching for more O. } } //Return false if there are no row with 3 X's or O's. return false; } //This function check if there is any column of X or O in the board. bool checkColumns(char board[GRIDSIZE][GRIDSIZE]){ //Create a variable to count how many X found in each column. int x_count = 0; for(int x = 0; x < GRIDSIZE; x++){ x_count = 0;//reset the X counter for the next column. for(int y = 0; y < GRIDSIZE; y++){ //add one to the X counter each time an X is found. if(board[y][x] == 'X'){ x_count += 1; } } //If 3 X's are found in one column if(x_count == 3){ return true; //then, stop searching for more X. } } //Create a variable to count how many o found in each column. int o_count = 0; for(int x = 0; x < GRIDSIZE; x++){ o_count = 0;//reset the o counter for the next column. for(int y = 0; y < GRIDSIZE; y++){ //add one to the O counter each time an O is found. if(board[y][x] == 'O'){ o_count += 1; } } //If 3 O's are found in one column if(o_count == 3){ return true;//then, stop searching for more O. } } //Return false if there are no column with 3 X's or O's. return false; } //This function check if there is any diagonal of X or O in the board. bool checkDiagonal(char board[GRIDSIZE][GRIDSIZE]){ //Check the first diagonal for 3 X's. if( (board[0][2] == 'X') && (board[1][1] == 'X') && (board[2][0] == 'X') ){ return true; //Check the first diagonal for 3 O's. }else if( (board[0][2] == 'O') && (board[1][1] == 'O') && (board[2][0] == 'O') ){ return true; //Check the second diagonal for 3 X's. }else if( (board[0][0] == 'X') && (board[1][1] == 'X') && (board[2][2] == 'X') ){ return true; //Check the second diagonal for 3 O's. }else if( (board[0][0] == 'O') && (board[1][1] == 'O') && (board[2][2] == 'O') ){ return true; } //return false if 3 X's or 3 O's are not found from either diagonal. return false; } //This function check if anyone of the player(X or O)won the game then, reset the board for the next game. void checkGame(char board[GRIDSIZE][GRIDSIZE], char playerMark){ //Create a row variable to hold the value of the checkRows function. bool rows = checkRows(board); //Create a column variable to hold the value of the checkColumns function. bool columns = checkColumns(board); //Create a diagonal variable to hold the value of the checkDiagonal function. bool diagonals = checkDiagonal(board); //If one of the 3 values above are true then, the current player won the game. if( (rows == true) || (columns == true) || (diagonals == true)){ //Showed which player won. cout << "Player " << playerMark << " has won!!!" << endl; //Pause the game and wait for the current player to press any key to continue. system("Pause"); //Clear the screen for the next game. system("CLS"); //Print out the title of the game to the screen. cout << "+-------------------+" << endl; cout << "| TIC-TAC-TOE |" << endl; cout << "+-------------------+" << endl; //Reset the board for the next game. populate(board); //Print out the board to the screen for the next game to start. output(board); } } //This function combine all the other function together to make the game works. void menu(char board[GRIDSIZE][GRIDSIZE]){ int posY = 0; int posX = 0; bool coordinate = false; bool location = false; char playerMark; int option = 0; //Populate the board with ( _ )when the game starts. populate(board); //Print out the board on the screen. output(board); int previousPlayer; int currentPlayer; //loop as long as any of the players does not enter 3. while(option != 3){ cout << endl; //Show a menu of option cout << "1. Play X" << endl; cout << "2. Play O" << endl; cout << "3. End game" << endl; cout << "Enter a number (from 1 to 3): "; cin >> option; //Take input from user (1 - 2 or 3). //Check if the current option chosen is the same as the old option that were chosen // This will determine if the same player is trying to play twice in a row. if(option == previousPlayer){ cout << endl << endl; //skip 2 lines. //Show a message error cout << "Sorry you can't play twice in a row...." << endl; system("Pause");//Pause the game and wait for the current player to press any key to continue. output(board);//Print out the new updated board to the screen. }else{ // Otherwise // The currentPlayer will be the option chosen currentPlayer = option; //Examine the option chosen switch(option){ case 1://If the current user chose 1. playerMark = 'X';//Then it is player X. requestCoordinates(board, posY, posX); //Request a location from the board to insert the X. cout << endl;//Skip a line to make the screen clean. updateBoard(board, playerMark, posY, posX);//Updated the board with the X using the coordinate. output(board);//Print out the new updated board to the screen. checkGame(board, playerMark);//Check if player X won the game. previousPlayer = currentPlayer;//The previousPlayer equal to the old option chosen break; case 2://If the current user chose 1. playerMark = 'O';//Then it is player O. requestCoordinates(board, posY, posX); //Request a location from the board to insert the X. cout << endl;//Skip a line to make the screen clean. updateBoard(board, playerMark, posY, posX);//Updated the board with the X using the coordinate. output(board);//Print out the new updated board to the screen. checkGame(board, playerMark);//Check if player X won the game. previousPlayer = currentPlayer;//The previousPlayer equal to the old option chosen break; case 3://If any of the players enter 3 //Then let the player knows the game will end. cout << "End the game" << endl; break; default: //If any of the player enter any number other than 1-2 or 3 //Let the player knows it is a wrong value. cout << "Wrong value. Enter a number (from 1 to 3): " << endl; system("Pause");//Pause the game and wait for the current player to press any key to continue. cout << endl << endl; //skip 2 lines. } } } }
0c16852ba2ae2c86a6cf255f91f94dd0651f3be4
[ "C++" ]
1
C++
Pouchyno29/Tic-Tac-Toe
df8916a93bd8c0ac2449d6a70469a6263aeb0ca5
0326a7beb374185ddb43ed7fe49d0210f0dad20f
refs/heads/master
<repo_name>KoryaginSergey/MVVM<file_sep>/MVVM/Source/ViewModel.xctemplate/___FILEBASENAME___ViewModel.swift // // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // Copyright © ___YEAR___ ___ORGANIZATIONNAME___ All rights reserved. // import Foundation import Combine protocol ___VARIABLE_sceneName___ViewModelProtocol: AnyObject { var viewState: AnyPublisher<___VARIABLE_sceneName___.Models.ViewState, Never> { get } var viewAction: AnyPublisher<___VARIABLE_sceneName___.Models.ViewAction, Never> { get } var route: AnyPublisher<___VARIABLE_sceneName___.Models.ViewRoute, Never> { get } func process(input: ___VARIABLE_sceneName___.Models.ViewModelInput) } final class ___VARIABLE_sceneName___ViewModel { // MARK: - Properties // @Injected(container: .shared) // private var hapticService: HapticFeedbackServiceProtocol private let viewStateSubj = CurrentValueSubject<___VARIABLE_sceneName___.Models.ViewState, Never>(.idle) private let viewActionSubj = PassthroughSubject<___VARIABLE_sceneName___.Models.ViewAction, Never>() private let routeSubj = PassthroughSubject<___VARIABLE_sceneName___.Models.ViewRoute, Never>() private var subscriptions = Set<AnyCancellable>() } // MARK: - ___VARIABLE_sceneName___ViewModelProtocol extension ___VARIABLE_sceneName___ViewModel: ___VARIABLE_sceneName___ViewModelProtocol { var viewState: AnyPublisher<___VARIABLE_sceneName___.Models.ViewState, Never> { viewStateSubj.eraseToAnyPublisher() } var viewAction: AnyPublisher<___VARIABLE_sceneName___.Models.ViewAction, Never> { viewActionSubj.eraseToAnyPublisher() } var route: AnyPublisher<___VARIABLE_sceneName___.Models.ViewRoute, Never> { routeSubj.eraseToAnyPublisher() } func process(input: ___VARIABLE_sceneName___.Models.ViewModelInput) { // input.onLoad.sink { [weak self] _ in // self?.fetch() // }.store(in: &subscriptions) } } // MARK: - Private private extension ___VARIABLE_sceneName___ViewModel { // func fetch() { // viewStateSubj.send(.loading) // service.fetch.sink { [weak self] result in // guard let self = self else { return } // switch result { // case .success([]): // self.viewStateSubj.send(.empty) // case let .success(items): // self.viewStateSubj.send(.loaded(items) // case let .failure(error): // self.viewStateSubj.send(.failure(error) // } // }.store(in: &subscriptions) // } } <file_sep>/MVVM/Source/Scene.xctemplate/MVVM TableViewController/___FILEBASENAME___DataSource.swift ../../Table DataSource.xctemplate/___FILEBASENAME___DataSource.swift<file_sep>/MVVM/Source/Scene.xctemplate/MVVM CollectionViewController/___FILEBASENAME___DataSource.swift ../../Collection DataSource.xctemplate/___FILEBASENAME___DataSource.swift<file_sep>/MVVM/README.md To install the MVVMR Xcode templates, run: > make install_templates To uninstall the MVVMR Xcode templates, run: > make uninstall_templates <file_sep>/MVVM/Source/Collection DataSource.xctemplate/___FILEBASENAME___DataSource.swift // // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // Copyright © ___YEAR___ ___ORGANIZATIONNAME___ All rights reserved. // import UIKit final class ___VARIABLE_sceneName___DataSource { // TODO: remove typealias or DataSource class from this file fileprivate typealias DataSource = UICollectionViewDiffableDataSource<___VARIABLE_sceneName___.Models.Section, ___VARIABLE_sceneName___.Models.Item> private typealias Snapshot = NSDiffableDataSourceSnapshot<___VARIABLE_sceneName___.Models.Section, ___VARIABLE_sceneName___.Models.Item> // MARK: - Properties private let collectionView: UICollectionView private lazy var dataSource = makeDataSource() // MARK: - Initializators init(collectionView: UICollectionView) { self.collectionView = collectionView collectionView.collectionViewLayout = makeLayout() collectionView.dataSource = dataSource makeSupplementaryProvider() registerReusable(in: collectionView) } // MARK: - Interface func updateSnapshot(_ items: [___VARIABLE_sceneName___.Models.Item], animated: Bool = true) { var snapshot = Snapshot() snapshot.appendSections([.main]) snapshot.appendItems(items) dataSource.apply(snapshot, animatingDifferences: animated) } } // MARK: - Private private extension ___VARIABLE_sceneName___DataSource { func registerReusable(in collectionView: UICollectionView) { // collectionView.register(cellType: MyCollectionCell.self) // collectionView.register(supplementaryViewType: MySectionView.self, ofKind: MySectionView.reuseIdentifier) } } // MARK: - DataSource private extension ___VARIABLE_sceneName___DataSource { func makeDataSource() -> DataSource { DataSource(collectionView: collectionView) { collectionView, indexPath, item -> UICollectionViewCell? in switch item { } } } func makeSupplementaryProvider() { dataSource.supplementaryViewProvider = { [weak self] collectionView, kind, indexPath in return nil // guard let self = self else { return nil } // // let section = self.dataSource.snapshot().sectionIdentifiers[indexPath.section] // switch section { // // } } } } // MARK: - Layout private extension ___VARIABLE_sceneName___DataSource { func makeLayout() -> UICollectionViewCompositionalLayout { UICollectionViewCompositionalLayout { [weak self] index, _ -> NSCollectionLayoutSection? in return nil } } } // MARK: - DataSource class //private extension ___VARIABLE_sceneName___DataSource { // // final class DataSource: UICollectionViewDiffableDataSource<___VARIABLE_sceneName___.Models.Section, ___VARIABLE_sceneName___.Models.Item>, // SkeletonCollectionViewDataSource { // // func collectionSkeletonView(_ skeletonView: UICollectionView, cellIdentifierForItemAt indexPath: IndexPath) -> ReusableCellIdentifier { // // } // } //} <file_sep>/MVVM/Source/Assembly.xctemplate/___FILEBASENAME___Assembly.swift // // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // Copyright © ___YEAR___ ___ORGANIZATIONNAME___ All rights reserved. // import UIKit extension ___VARIABLE_sceneName___ { enum Assembly {} } extension ___VARIABLE_sceneName___.Assembly { static func createModule(with viewModel: ___VARIABLE_sceneName___ViewModelProtocol) -> UIViewController { let viewController = ___VARIABLE_sceneName___ViewController.instantiate() viewController.setDependencies(viewModel: viewModel) return viewController } } <file_sep>/MVVM/Source/View Controller.xctemplate/UITableViewController/___FILEBASENAME___ViewController.swift // // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // Copyright © ___YEAR___ ___ORGANIZATIONNAME___ All rights reserved. // import UIKit import Combine final class ___VARIABLE_sceneName___ViewController: UIViewController, StoryboardBased { // MARK: - Properties @IBOutlet private weak var tableView: UITableView! private lazy var dataSource = ___VARIABLE_sceneName___DataSource(tableView: tableView) private var viewModel: ___VARIABLE_sceneName___ViewModelProtocol? private let onLoad = PassthroughSubject<Void, Never>() public var subscriptions = Set<AnyCancellable>() // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() setup() bind(to: viewModel) onLoad.send(()) } } // MARK: - Internal methods extension ___VARIABLE_sceneName___ViewController { func setDependencies(viewModel: ___VARIABLE_sceneName___ViewModelProtocol) { self.viewModel = viewModel } } // MARK: - Bind private extension ___VARIABLE_sceneName___ViewController { func bind(to viewModel: ___VARIABLE_sceneName___ViewModelProtocol?) { subscriptions.forEach { $0.cancel() } subscriptions.removeAll() let input = ___VARIABLE_sceneName___.Models.ViewModelInput(onLoad: onLoad.eraseToAnyPublisher()) viewModel?.process(input: input) viewModel?.viewState .removeDuplicates() .receive(on: DispatchQueue.main) .sink(receiveValue: { [weak self] state in self?.render(state) }).store(in: &subscriptions) viewModel?.route .receive(on: DispatchQueue.main) .sink(receiveValue: { [weak self] route in self?.handleRoute(route) }).store(in: &subscriptions) viewModel?.viewAction .receive(on: DispatchQueue.main) .sink(receiveValue: { [weak self] action in self?.handleAction(action) }).store(in: &subscriptions) } func render(_ state: ___VARIABLE_sceneName___.Models.ViewState) { switch state { case .idle: updateSnapshot([], animated: false) case .loading: startLoading() case .loaded: stopLoading() case .empty: stopLoading() case .failure: stopLoading() } } func handleAction(_ action: ___VARIABLE_sceneName___.Models.ViewAction) { switch action { //show alert //scrollToTop // ... } } func handleRoute(_ route: ___VARIABLE_sceneName___.Models.ViewRoute) { switch route { } } } // MARK: - DataSource private extension ___VARIABLE_sceneName___ViewController { func updateSnapshot(_ items: [___VARIABLE_sceneName___.Models.Item], animated: Bool = true) { dataSource.updateSnapshot(items, animated: animated) } } // MARK: - Private private extension ___VARIABLE_sceneName___ViewController { func setup() { } func startLoading() { } func stopLoading() { } } <file_sep>/MVVM/Source/View.xctemplate/UICollectionViewCell/___FILEBASENAME___.swift //___FILEHEADER___ import UIKit import Reusable final class ___FILEBASENAMEASIDENTIFIER___: ___VARIABLE_cocoaTouchSubclass___, NibReusable { struct State { } // MARK: - Properties var state: State? { didSet { configure() } } // MARK: - Lifecycle override func awakeFromNib() { super.awakeFromNib() setupUI() } /* override func layoutSubviews() { super.layoutSubviews() } override func prepareForReuse() { super.prepareForReuse() } */ } // MARK: - Internal methods extension ___FILEBASENAMEASIDENTIFIER___ { } // MARK: - Private methods private extension ___FILEBASENAMEASIDENTIFIER___ { func setupUI() { } func configure() { } } /* // MARK: - ___FILEBASENAMEASIDENTIFIER___.State + Hashable extension ___FILEBASENAMEASIDENTIFIER___.State: Hashable { } */ <file_sep>/MVVM/Source/View.xctemplate/UIViewXIB/___FILEBASENAME___.swift //___FILEHEADER___ import UIKit import Reusable final class ___FILEBASENAMEASIDENTIFIER___: XibView { struct State { } // MARK: - Properties var state: State? { didSet { configure() } } // MARK: - Lifecycle override func didMoveToSuperview() { super.didMoveToSuperview() setupUI() } /* override func layoutSubviews() { super.layoutSubviews() } */ } // MARK: - Internal methods extension ___FILEBASENAMEASIDENTIFIER___ { } // MARK: - Private methods private extension ___FILEBASENAMEASIDENTIFIER___ { func setupUI() { } func configure() { } } /* // MARK: - ___FILEBASENAMEASIDENTIFIER___.State + Hashable extension ___FILEBASENAMEASIDENTIFIER___.State: Hashable { } */ <file_sep>/MVVM/Source/Table DataSource.xctemplate/___FILEBASENAME___DataSource.swift // // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // Copyright © ___YEAR___ ___ORGANIZATIONNAME___ All rights reserved. // import UIKit final class ___VARIABLE_sceneName___DataSource { // TODO: remove typealias or DataSource class from this file fileprivate typealias DataSource = UITableViewDiffableDataSource<___VARIABLE_sceneName___.Models.Section, ___VARIABLE_sceneName___.Models.Item> private typealias Snapshot = NSDiffableDataSourceSnapshot<___VARIABLE_sceneName___.Models.Section, ___VARIABLE_sceneName___.Models.Item> // MARK: - Properties private let tableView: UITableView private lazy var dataSource = makeDataSource() // MARK: - Initializators init(tableView: UITableView) { self.tableView = tableView tableView.dataSource = dataSource registerReusable(in: tableView) } // MARK: - Interface func updateSnapshot(_ items: [___VARIABLE_sceneName___.Models.Item], animated: Bool = true) { var snapshot = Snapshot() snapshot.appendSections([.main]) snapshot.appendItems(items) dataSource.apply(snapshot, animatingDifferences: animated) } } // MARK: - Private private extension ___VARIABLE_sceneName___DataSource { func registerReusable(in tableView: UITableView) { // tableView.register(cellType: MyTableCell.self) } } // MARK: - DataSource private extension ___VARIABLE_sceneName___DataSource { func makeDataSource() -> DataSource { let source = DataSource(tableView: tableView) { tableView, indexPath, item -> UITableViewCell? in switch item { } } source.defaultRowAnimation = .fade return source } } // MARK: - DataSource class //private extension ___VARIABLE_sceneName___DataSource { // // final class DataSource: UITableViewDiffableDataSource<___VARIABLE_sceneName___.Models.Section, ___VARIABLE_sceneName___.Models.Item>, // SkeletonTableViewDataSource { // // func collectionSkeletonView(_ skeletonView: UITableView, cellIdentifierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier { // // } // } //} <file_sep>/MVVM/Source/Scene.xctemplate/MVVM TableViewController/___FILEBASENAME___ViewController.swift ../../View Controller.xctemplate/UITableViewController/___FILEBASENAME___ViewController.swift<file_sep>/MVVM/Source/Scene.xctemplate/MVVM CollectionViewController/___FILEBASENAME___ViewModel.swift ../../ViewModel.xctemplate/___FILEBASENAME___ViewModel.swift<file_sep>/MVVM/Source/Models.xctemplate/___FILEBASENAME___Models.swift // // ___FILENAME___ // ___PROJECTNAME___ // // Created by ___FULLUSERNAME___ on ___DATE___. // Copyright © ___YEAR___ ___ORGANIZATIONNAME___ All rights reserved. // import Foundation import Combine enum ___VARIABLE_sceneName___ {} extension ___VARIABLE_sceneName___ { enum Models {} } // MARK: - Models View Input/Output extension ___VARIABLE_sceneName___.Models { // MARK: Input struct ViewModelInput { let onLoad: AnyPublisher<Void, Never> } // MARK: Output enum ViewState: Equatable { case idle case loading case loaded case empty case failure } enum ViewAction { } enum ViewRoute { } } // MARK: - Scene Models //extension ___VARIABLE_sceneName___.Models { // // // MARK: List Models // enum Section: Hashable { // case main // } // // enum Item: Hashable { // } //} <file_sep>/MVVM/Source/Scene.xctemplate/MVVM CollectionViewController/___FILEBASENAME___Assembly.swift ../../Assembly.xctemplate/___FILEBASENAME___Assembly.swift<file_sep>/MVVM/Makefile XCODE_USER_TEMPLATES_DIR=~/Library/Developer/Xcode/Templates/File\ Templates TEMPLATES_SOURCE_DIR=Source TEMPLATES_DIR_NAME=MVVM+Combine install_templates: mkdir -p $(XCODE_USER_TEMPLATES_DIR) rm -fR $(XCODE_USER_TEMPLATES_DIR)/$(TEMPLATES_DIR_NAME) cp -LR $(TEMPLATES_SOURCE_DIR)/. $(XCODE_USER_TEMPLATES_DIR)/${TEMPLATES_DIR_NAME} uninstall_templates: rm -fR $(XCODE_USER_TEMPLATES_DIR)/$(TEMPLATES_DIR_NAME)
9ccc1e021b20493f20399c2c809bc167541e3e70
[ "Swift", "Makefile", "Markdown" ]
15
Swift
KoryaginSergey/MVVM
af8088c1dd627238d3b27884d03ab0cb0b343b92
e8641a183dafef60e78ddc7bfb63e61c25072e99
refs/heads/master
<file_sep>var settings = { rows: 3, columns: 5, viewWidth: 0, viewHeight: 0, pieceTemplate: '', cards:null, cellWidth: function(){ return settings.viewWidth/settings.columns; }, cellHeight: function(){ return settings.viewHeight/settings.rows; } }; var ani = { crtCellInx:0, aniInterval:null, crtCardIndex:0 }; $(document).ready(function() { settings.viewWidth = $('#myView').width(); settings.viewHeight = $('#myView').height(); settings.pieceTemplate = $('#myView').find('div.template:first-child').prop('outerHTML'); $.get('cards.json',function(data){ settings.cards = data; console.log(data); loadCard(ani.crtCardIndex); }); setTimeout(function(){ startAnimation(); },200); function startAnimation(){ ani.aniInterval = setInterval(function(){ $('#myView').find('.card:eq('+ani.crtCellInx+')').addClass('flipped'); ani.crtCellInx++; if(ani.crtCellInx>(settings.columns*settings.rows)-1){ //clearInterval(ani.aniInterval); ani.crtCellInx=0; ani.crtCardIndex++; console.log(ani.crtCardIndex+" "+Object.keys(settings.cards).length); if(ani.crtCardIndex===Object.keys(settings.cards).length){ ani.crtCardIndex = 0; console.log("reset"); } loadNextCard(ani.crtCardIndex); } },100); } function loadCard(cardIndex){ $('#myView').empty(); var piece = ''; console.log(settings.cards[cardIndex]); for (var i = 0; i < (settings.columns * settings.rows); i++) { piece = $(settings.pieceTemplate); $(piece).css({ 'width':settings.cellWidth()+'px', 'height':settings.cellHeight()+'px' }); $(piece).find('.front').append('<img src="cardSlices/c' + i + settings.cards[cardIndex][0] + '" style="width:' + settings.cellWidth() + 'px;height:' + settings.cellHeight() + 'px"/>'); $(piece).find('.back').append('<img src="cardSlices/c' + i + settings.cards[cardIndex][1] + '" style="width:' + settings.cellWidth() + 'px;height:' + settings.cellHeight() + 'px"/>'); $('#myView').append($(piece).prop('outerHTML')); } } function loadNextCard(cardIndex){ var image = settings.cards[cardIndex]; var pw = settings.viewWidth / settings.columns; var ph = settings.viewHeight / settings.rows; var index=0; $('.card').removeClass('flipped'); $('.card img').css({ 'width':pw+'px', 'height':ph+'px' }); $('#myView').find('.card').each(function(){ // console.log(index+" "+cardIndex); $(this).find('.front img').attr('src','cardSlices/c'+ index + settings.cards[cardIndex][0]); $(this).find('.back img').attr('src','cardSlices/c'+ index + settings.cards[cardIndex][1]); //$(this).removeClass('flipped'); index++; }); } });
d404cae2802c96757a97a4af9ee63e5fb5ecf98d
[ "JavaScript" ]
1
JavaScript
CafeCat/App-for-Ege
68c3a5a91cba4589e0222ba3d3eff0ec9d158a5b
da0a7aa90f25440c397b7b8a5e3c609ef1917345
refs/heads/master
<file_sep># coding: utf-8 from __future__ import unicode_literals from flask import Flask, request, abort from linebot import LineBotApi, WebhookHandler from linebot.exceptions import InvalidSignatureError from linebot.models import MessageEvent, TextMessage, TextSendMessage from janome.tokenizer import Tokenizer import os, re, json def load_env(): try: with open('.env') as f: content = f.read() except IOError: content = '' for line in content.splitlines(): m1 = re.match(r'\A([A-Za-z_0-9]+)=(.*)\Z', line) if m1: key, val = m1.group(1), m1.group(2) m2 = re.match(r"\A'(.*)'\Z", val) if m2: val = m2.group(1) m3 = re.match(r'\A"(.*)"\Z', val) if m3: val = re.sub(r'\\(.)', r'\1', m3.group(1)) os.environ.setdefault(key, val) load_env() app = Flask(__name__) line_bot_api = LineBotApi(os.environ.get('CHANNEL_ACCESS_TOKEN')) handler = WebhookHandler(os.environ.get('CHANNEL_SECRET')) @app.route("/callback", methods=['POST']) def callback(): signature = request.headers['X-LINE-Signature'] body = request.get_data(as_text=True) receive_json = json.loads(body) message = receive_json['events'][0]['message']['text'] response_arrays = [] t = Tokenizer() for token in t.tokenize(message): response_arrays.append(str(token)) response = '' for item in range(len(response_arrays)): if len(response_arrays) == item + 1: response += str(response_arrays[item]) else: response += str(response_arrays[item] + '\n') try: line_bot_api.reply_message(receive_json['events'][0]['replyToken'], TextSendMessage(text = response)) except InvalidSignatureError: abort(400) return 'OK' if __name__ == '__main__': app.run(host='0.0.0.0', port = 8003, threaded = True, debug = True) <file_sep>click==6.6 Flask==0.11.1 future==0.15.2 gunicorn==19.6.0 itsdangerous==0.24 Janome==0.2.8 Jinja2==2.8 line-bot-sdk==1.0.2 MarkupSafe==0.23 requests==2.11.1 Werkzeug==0.11.11 <file_sep># morphological-linebot ## Installation ```bash $ git clone https://github.com/nnsnodnb/morphological-linebot.git $ virtualenv venv $ source venv/bin/activate $ pip install requirements.txt $ mv .env.sample .env $ vim .env ``` Fill your BOT CHANNEL_ACCESS_TOKEN and CHANNEL_SECRET. ``` CHANNEL_ACCESS_TOKEN='' CHANNEL_SECRET='' ``` Change to suit your environment ```python app.run(host='0.0.0.0', port = 5000, threaded = True, debug = True) # or app.run(host='0.0.0.0', port = 5000, threaded = True, debug = False) # and so on. ``` ```bash $ python bot.py # or $ gunicorn bot:app --bind 0.0.0.0:5000 -D # and so on. ``` ## LICENSE MIT License. See [License](LICENSE)
33b4f9f789b0a4402c3ee6d738ffe2114783f9d6
[ "Markdown", "Python", "Text" ]
3
Python
nnsnodnb/morphological-linebot
703affa70a5cc2049f379f8e8948401bad3e5f0b
074c7111de028fc4aa42d094dbf897d5630a635d
refs/heads/main
<file_sep>var add = require('../mul'); describe("Mul Functionality",()=>{ it("should multiply positive numbers",()=>{ const result = add(4,5); expect(result).toEqual(20); }); it("should muliply negative numbers",()=>{ const result = add(-4,5); expect(result).toEqual(-20); }); });
322665cb71750e1574f28949a7ab67fc00007262
[ "JavaScript" ]
1
JavaScript
ruchika-dubey/jasmine-testing
1bfaff8ff2b586cc66f585205081fc293f5f886d
f2e590a67fb425e522bb3f2d63f4e20e7718e9d0
refs/heads/master
<file_sep>local swap = function(array, index1, index2) local temp = array[index2] array[index2] = array[index1] array[index1] = temp; end local heapadjust = function(array, parent, len) local child = 1; local value = array[parent]; child = 2 * parent while (child <= len) do if (child < len and array[child] < array[child + 1]) then child = child + 1 end if (value < array[child]) then array[parent] = array[child] else break end parent = child child = 2 * parent end array[parent] = value end -- 函数说明:堆排序,堆积是一个近似完全二叉树的结构(二叉堆), -- 并同时满足堆积的性质:即子结点的键值或索引总是小于(或者大于)它的父节点。。 -- -- @param {array} array 数组 -- @param {int} len 数组长度 -- -- @return 空 local heapsort = function(array, len) local i = math.floor(len / 2) for i = i, 1, -1 do heapadjust(array, i, len) end for i = len, 1, -1 do swap(array, 1, i); heapadjust(array, 1, i - 1); end end return heapsort --[[ local arr = {40, 32, 52, 22, 32, 55, 10} heapsort(arr, #arr) 40 32 52 -> 22 32 55 10 -------------------------------- 40 32 55 -> 22 32 52 10 -------------------------------- 55 32 52 -> 22 32 40 10 -------------------------------- now frist index is max. loop: swap(frist, last) get max heapadjust(1, len - 1) ]]-- <file_sep>-- 函数说明:数组拷贝 -- -- @param {array} src 源数组 -- @param {int} srcPos 源数组拷贝起始index -- @param {array} dest 目标数组 -- @param {int} destPos 目标数组起始index -- @param {int} length 拷贝长度 -- -- @return 空 local arraycopy = function(src, srcPos, dest, destPos, length) if(length <= 0 ) then return end for index = length - 1, 0, -1 do dest[destPos + index] = src[srcPos + index] end end -- 函数说明:合并排序,从中间分隔,左右两边的数都是递归排好序的,在合并的时候就可以递增比较合并了。 -- -- @param {array} src 需要排序的数组 -- @param {array} buffer 缓存数组 -- @param {int} start 排序的起始index -- @param {int} mid 排序的中间index -- @param {int} end_ 排序的结束index -- -- @return 空 local merge = function(source, buffer, start, mid, end_) local i = start local k = start local j = mid + 1 while (i <= mid and j < end_ + 1) do if (source[i] > source[j]) then buffer[k] = source[j] k = k + 1 j = j + 1 else buffer[k] = source[i] k = k + 1 i = i + 1 end end if (i ~= mid + 1) then arraycopy(source, i, source, i + (j - mid - 1), mid - i + 1) end arraycopy(buffer, start, source, start, i - start + j - mid - 1) end local mergeSort -- 函数说明:合并排序 -- -- @param {array} array 需要排序的数组 -- @param {array} temp 缓存数组 -- @param {int} start 排序的起始index -- @param {int} end_ 排序的结束index -- -- @return 空 mergeSort = function(array, temp, start, end_) if(start < end_) then local midIndex = math.floor((start + end_) / 2) mergeSort(array, temp, start, midIndex) mergeSort(array, temp, midIndex + 1, end_) merge(array, temp, start, midIndex, end_) end end -- local array = {3, 4, 2, 1, 5, 7, 9 , 332, 1, 32, 434, 332} -- {3, 4, 2, 1, 5, 7, 9 , 332, 1, 32, 434, 332} -> {1, 1, 2, 3, 4, 5, 9, 32, 332, 332 ,434} -- {3, 4, 2, 1, 5, 7}{9 , 332, 1, 32, 434, 332} -> {1, 2, 3, 4, 5, 7}{1, 9, 32, 332, 332, 434} -- {3, 4, 2}{1, 5, 7} -> {2, 3 ,4}{1, 5, 7} -- {3, 4}{2} -> {2, 3, 4} -- {3}{4} -- 从中间分隔,左右两边的数都是递归排好序的,在合并的时候就可以递增比较合并了。 -- local temp = {} -- mergeSort(array, temp, 1, #array) <file_sep>-- 函数说明:插入排序 -- -- @param {array} array 需要排序的数组 -- @param {int} s 排序的起始index -- @param {int} e 排序的结束index -- -- @return 空 local insert_sort = function(array, s, e) local start_ = 1 local end_ = #array if(s and e) then start_, end_ = s, e end for i = start_, end_, 1 do local insert_data = array[i] local j = i while (j > start_) do if(array[j - 1] > insert_data) then array[j] = array[j - 1] else break; end j = j - 1 end if(j ~= i) then array[j] = insert_data end end end return insert_sort <file_sep>local insert_sort = require('insert_sort') local swap = function(array, index1, index2) local temp = array[index2] array[index2] = array[index1] array[index1] = temp; end local partition = function(array, low, high, pivot_index) local pivot_value = array[pivot_index] swap(array, low, pivot_index) while (low < high) do while (low < high and array[high] >= pivot_value) do high = high - 1 end if (low < high) then array[low] = array[high] low = low + 1 end while (low < high and array[low] <= pivot_value) do low = low + 1 end if(low < high) then array[high] = array[low] high = high - 1 end end array[low] = pivot_value return low end local select local K_GROUP_SIZE = 5 -- 函数说明:BFPRT 算法解决的问题十分经典,即从某n个元素的序列中选出第 k 小(第 k 大)的元素,通过巧妙的分析,BFPRT 可以保证在最坏情况下仍为线性时间复杂度。 -- -- @param {array} array 数组 -- @param {int} left 数组起点 -- @param {int} right 数组终点 -- @param {int} k 第几大 -- -- @return 空 select = function(array, left, right, k) local size = right - left + 1 if (size <= K_GROUP_SIZE) then insert_sort(array, left, right) return array[k + left - 1] end local num_group = math.ceil(size / K_GROUP_SIZE) for i = 0, num_group - 1, 1 do local sub_left = left + i * K_GROUP_SIZE local sub_right = sub_left + K_GROUP_SIZE - 1 if (sub_right > right) then sub_right = right end insert_sort(array, sub_left, sub_right) local median = sub_left + math.floor((sub_right - sub_left) / 2); swap(array, left + i, median); end local pivot_index = left + math.floor((num_group - 1) / 2) select(array, left, left + num_group - 1, math.floor((num_group + 1) / 2)) local mid_index = partition(array, left, right, pivot_index) local _ith = mid_index - left + 1 if (k == _ith) then return array[mid_index] elseif (k < _ith) then return select(array, left, mid_index - 1, k) else return select(array, mid_index + 1, right, k - _ith) end end return select -- local arr = {15, 16, 7, 8, 29, 10, 11, 12, 13} -- local value = select(arr, 1, #arr, 4) <file_sep>-- low值做拆分的pivotekey,将数字拆分成两块。 -- pivotkey在多次交换后,会形成左边比pivotekey小,右边pivotekey大。 -- {4, 5, 1, 3, 8, 7} pivotkey: 4 -- 4, 5, 1, 3, 8, 7 -> -- l . . h -- 3, 5, 1, 3, 8, 7 -> -- l . h -- 3, 5, 1, 5, 8, 7 -> -- l . h -- 3, 1, 1, 5, 8, 7 -> (while end) -- lh -- 3, 1, 4, 5, 8, 7 -> (pivotkey is 4, left lower, right bigger) local partition = function(array, low, high) local pivotkey = array[low] while (low < high) do while (low < high and array[high] > pivotkey) do high = high - 1 end if (low < high) then array[low] = array[high] low = low + 1 end while (low < high and array[low] <= pivotkey) do low = low + 1 end if(low < high) then array[high] = array[low] high = high - 1 end end array[low] = pivotkey return low end local quicksort -- 函数说明:快速排序 -- -- @param {array} array 需要排序的数组 -- @param {int} low 排序的起始index -- @param {int} high 排序的结束index -- -- @return 空 quicksort = function(array, low, high) if (low < high) then local middle = partition(array, low, high) if (low < middle - 1) then quicksort(array, low, middle - 1) end if (middle + 1 < high) then quicksort(array, middle + 1, high) end end end return quicksort <file_sep># 一些基础算法 >> ## 参考文献 - [http://alfred-sun.github.io/blog/2015/03/11/ten-basic-algorithms-for-programmers](http://alfred-sun.github.io/blog/2015/03/11/ten-basic-algorithms-for-programmers "Blog Archive") ## 简单描述 - 线性查找:[bfprt_search](https://github.com/SpectatorWang/algorithms/blob/master/bfprt_search.lua) - 二分查找:[binary_search](https://github.com/SpectatorWang/algorithms/blob/master/binary_search.lua) - 堆排序:[heap_sort](https://github.com/SpectatorWang/algorithms/blob/master/heap_sort.lua) - 插入排序:[insert_sort](https://github.com/SpectatorWang/algorithms/blob/master/insert_sort.lua) - 合并排序:[merge_sort](https://github.com/SpectatorWang/algorithms/blob/master/merge_sort.lua) - 快速排序:[quick_sort](https://github.com/SpectatorWang/algorithms/blob/master/quick_sort.lua)<file_sep>-- 函数说明:二分查找算法,在有序数组中查找某一特定元素的搜索算法。 -- -- @param {array} array 数组 -- @param {int} value 需要查询的数 -- -- @return 空 local binary_search = function(array, value) local low = 1 local high = #array local mid = 1 while (low <= high) do -- 如果使用 (low + high) / 2 有可能计算 low + high 的时溢出 mid = math.ceil(low + (high - low) / 2) if(value == array[mid]) then return mid end if(value < array[mid]) then high = mid - 1 else low = mid + 1 end end return 0 end return binary_search -- local array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 15, 354} -- local index = binary_search(array, 15)
3395b1e1156a9a7eb1a7e31e7ec212b2721f385c
[ "Markdown", "Lua" ]
7
Lua
SpectatorWang/algorithms
1d622c93c501de4018cacc2f0141a4f1ec0424f0
8121f087d55cc7d71af9479277f042b042ae26e3
refs/heads/master
<file_sep>package com.markfront.spfh; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.tika.Tika; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.parser.Tag; import org.jsoup.select.Elements; import java.io.*; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Base64; import java.util.List; import java.util.concurrent.TimeUnit; import com.vdurmont.emoji.EmojiParser; public class Utils { public static boolean mergeIntoFatHtml(String page_url, String in_html_file, String out_filename, String curr_dir) { boolean success = false; try { System.out.println("page_url: " + page_url); File page_file = new File((in_html_file)); Document doc = Jsoup.parse(page_file, "UTF-8", page_url); String title = doc.title(); System.out.println("title: " + title); String out_html_file; String clean_title = EmojiParser.removeAllEmojis(title); clean_title = clean_title.replaceAll("[\\\\/:*?\"<>|]", ""); out_html_file = curr_dir + File.separatorChar + "F-" + out_filename + "." + clean_title + ".html"; // css style files Elements css_styles = doc.select("link[rel=\"stylesheet\"][type=\"text/css\"]"); System.out.println("\ncss files: "); for (Element css : css_styles) { String css_file = css.attr("href"); System.out.println(css_file); Element elem = new Element(Tag.valueOf("style"), ""); String css_str = readFileToString(curr_dir + File.separatorChar + css_file); System.out.println("css_str.length() = " + css_str.length()); elem.append(css_str); Element parent = css.parent(); parent.appendChild(elem); css.remove(); } // javascript files Elements js_files = doc.select("script"); System.out.println("\njavascript files: "); for (Element js : js_files) { String js_file = js.attr("src"); System.out.println(js_file); js.remove(); } // images Elements img_files = doc.select("img"); System.out.println("\nimg files: "); for (Element img : img_files) { String img_file = img.attr("src"); System.out.println(img_file); String img_base64 = readImageContentAsBase64(curr_dir + File.separatorChar + img_file); String mimeType = detectMimeType(curr_dir + File.separatorChar + img_file); // src="data:image/png;base64,......" String src_value = "data:" + mimeType + ";base64," + img_base64; Element elem = new Element(Tag.valueOf("img"), ""); elem.attr("src", src_value); Element parent = img.parent(); parent.appendChild(elem); img.remove(); } System.out.println("css files: " + css_styles.size()); System.out.println("js files: " + js_files.size()); System.out.println("img files: " + img_files.size()); writeStringToFile(doc.outerHtml(), out_html_file); System.out.println("\nresult fat html saved to: " + out_html_file); success = true; } catch (Exception e) { e.printStackTrace(); } return success; } public static void SaveHtmlToFile(String html_str, String file_path) { try (Writer out = new BufferedWriter(new OutputStreamWriter (new FileOutputStream(file_path), StandardCharsets.UTF_8))) { out.write(html_str); } catch (Exception e) { System.out.println("Exception: " + e.getMessage()); } } public static String ReadTextFile(String file_path) { StringBuilder sb = new StringBuilder(); Charset charset = StandardCharsets.UTF_8; try { List<String> lines = Files.readAllLines(new File(file_path).toPath(), charset); for (String line : lines) { sb.append(line).append("\n"); } } catch (IOException ex) { System.out.println("I/O Exception: " + ex); } return sb.toString(); } // https://www.techiedelight.com/read-file-contents-with-apache-commons-io-library-java/ public static String readFileToString(String file_path) { String content = ""; try { content = FileUtils.readFileToString(new File(file_path), StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } return content; } public static void writeStringToFile(String data_to_write, String file_path) { try { FileUtils.writeStringToFile(new File(file_path), data_to_write, StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } } public static String readImageContentAsBase64(String img_file) { String img_base64 = ""; try { byte[] img_content = FileUtils.readFileToByteArray(new File(img_file)); img_base64 = Base64.getEncoder().encodeToString(img_content); } catch (Exception e) { e.printStackTrace(); } return img_base64; } public static String detectMimeType(String file_path) { final Tika tika = new Tika(); return tika.detect(file_path); } public static boolean execSystemCommand(String[] cmd_with_args) { boolean success = false; try { System.out.println("building command"); ProcessBuilder builder = new ProcessBuilder(); builder.command(cmd_with_args); builder.directory(new File(System.getProperty("user.home"))); System.out.println("starting process"); Process process = builder.inheritIO().start(); System.out.println("waiting"); int status_code = process.waitFor(); if (status_code == 0) { success = true; } } catch (Exception e) { e.printStackTrace(); } System.out.println("returning"); return success; } }
7eaded26449b57be53805b1e18a5028a450bd443
[ "Java" ]
1
Java
aequis/SinglePageFullHtml
1ce4dd9fd27c5963f22b9263b142d629b4c37423
e9a7a0a7251d30cb6c2be35b8dd3cf55be8222a1
refs/heads/master
<repo_name>TheFredward/Python_project<file_sep>/MainPage.py import tkinter as tk import random import time from Dictionary import Dictionary class Page(tk.Frame): def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) def show(self): self.lift() class Page1(Page): def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) firstLabel = tk.Label(self, font=('arial', 50, 'bold'), text="Welcome to my Window", fg = "Black", bd = 10, anchor = 'w') firstLabel.grid(row = 0, column = 0) list = [ ] self.localtime = time.asctime(time.localtime(time.time())) TimeLabel = tk.Label(self, font=('arial', 20, 'bold'), text=self.localtime, fg = "Black", bd = 10, anchor = 'w') TimeLabel.grid(row = 0, column = 6) self.text_Input = tk.StringVar() self.operator = " " txtDisplay = tk.Entry(self, font=('arial', 15), textvariable = self.text_Input, bd = 5, insertwidth=4, bg = "white", justify = 'right') txtDisplay.grid(columnspan=4, row = 3, column = 1) IDLabel = tk.Label(self, font=('arial', 20, 'bold'), text="Enter ID Number", fg = "Black", bd = 10, anchor = 'w') IDLabel.grid(columnspan=4, row = 1, column = 1) okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "1", bg = "gray", command = lambda: buttonClick("1")).grid(row=4, column=1, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "2", bg = "gray", command = lambda: buttonClick("2")).grid(row=4, column=2, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "3", bg = "gray", command = lambda: buttonClick("3")).grid(row=4, column=3, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "4", bg = "gray", command = lambda: buttonClick("4")).grid(row=5, column=1, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "5", bg = "gray", command = lambda: buttonClick("5")).grid(row=5, column=2, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "6", bg = "gray", command = lambda: buttonClick("6")).grid(row=5, column=3, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "7", bg = "gray", command = lambda: buttonClick("7")).grid(row=6, column=1, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "8", bg = "gray", command = lambda: buttonClick("8")).grid(row=6, column=2, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "9", bg = "gray", command = lambda: buttonClick("9")).grid(row=6, column=3, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "OK", bg = "gray", command = lambda: AddClick()).grid(row=7, column=1, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "0", bg = "gray", command = lambda: buttonClick("0")).grid(row=7, column=2, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "<-", bg = "gray", command = lambda: DeleteClick()).grid(row=7, column=3, sticky="ew") def buttonClick(numbers): global operator self.operator = self.operator + str(numbers) self.text_Input.set(self.operator) return; # shold pass choice password, and the password itself so that we can recall it later def OKClick(passChoice): global operator # get value and store in passChoice print(self.passChoice) # have an empty dictionary to save the password but not sure if it will create a new one each time.... passwordKeys = {} # check that operator is not null if len(self.operator) > 0: passwordKeys = dict([(self.passChoice,self.operator)]) print(passwordKeys) else: print('No value has been input') return; def DeleteClick(): global operator self.operator = self.operator[:-1] self.text_Input.set(self.operator) return; def AddClick(): global operator DC = Dictionary() DC.AddToArray(self.operator, list) DC.PrintList(list) self.operator = " " self.text_Input.set(self.operator) return; class Page2(Page): def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) label = tk.Label(self, text="This is page 2") label.pack(side="top", fill="both", expand=True) class Page3(Page): def __init__(self, *args, **kwargs): Page.__init__(self, *args, **kwargs) label = tk.Label(self, text="This is page 3") label.pack(side="top", fill="both", expand=True) class MainView(tk.Frame): def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) p1 = Page1(self) p2 = Page2(self) p3 = Page3(self) buttonframe = tk.Frame(self) container = tk.Frame(self) buttonframe.pack(side="top", fill="x", expand=False) container.pack(side="top", fill="both", expand=True) p1.place(in_=container, x=0, y=0, relwidth=1, relheight=1) p2.place(in_=container, x=0, y=0, relwidth=1, relheight=1) p3.place(in_=container, x=0, y=0, relwidth=1, relheight=1) b1 = tk.Button(buttonframe, text="Page 1", command=p1.lift) b2 = tk.Button(buttonframe, text="Page 2", command=p2.lift) b3 = tk.Button(buttonframe, text="Page 3", command=p3.lift) b1.pack(side="left") b2.pack(side="left") b3.pack(side="left") root = tk.Tk() if __name__ == "__main__": main = MainView(root) main.pack(side="top", fill="both", expand=True) root.wm_geometry("400x400") root.mainloop() <file_sep>/MainView.py import tkinter as tk import random import time LARGE_FONT = ("Verdana", 12) class MainView(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) container = tk.Frame(self) container.pack(side="top", fill="both", expand = True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) #SP = StartPage(self) self.frames = { } frame = StartPage(container, self) #frame = MainPage(container, self) self.frames[StartPage] = frame #self.frames[MainPage] = frame #self.frames[MainPage] = MainPage(container, self) frame.grid(row=0, column=0, sticky="nsew") self.show_frame(StartPage) def show_frame(self, cont): frame = self.frames[cont] frame.tkraise() class StartPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) buttonframe = tk.Frame(self) buttonframe.pack(side="top", fill="x", expand=False) label = tk.Label(self, text = "Start Page", font=LARGE_FONT) label.pack(pady=10, padx=10) MP = MainPage(controller, self) b1 = tk.Button(buttonframe, text="Page 1", command=MP.lift) MP.place(in_=buttonframe, x=0, y=0, relwidth=1, relheight=1) b1.pack(side="left") class MainPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) # FrameOne = tk.Frame(self,height = 0, width = 1600, bg="blue") # FrameOne.pack(side="top") # # FrameTwo = tk.Frame(self, height = 700, width = 800, bg="blue") # FrameTwo.pack(side="left") # # FrameThree = tk.Frame(self, height = 700, cursor = "dot", width = 400, bg="light gray") # FrameThree.pack(side="right") # FrameFour = tk.Frame(self, height = 700, cursor = "dot", width = 400, bg="light gray") # FrameFour.pack(side="top") firstLabel = tk.Label(self, font=('arial', 50, 'bold'), text="Welcome to my Window", fg = "Black", bd = 10, anchor = 'w') firstLabel.grid(row = 0, column = 0) self.localtime = time.asctime(time.localtime(time.time())) TimeLabel = tk.Label(self, font=('arial', 20, 'bold'), text=self.localtime, fg = "Black", bd = 10, anchor = 'w') TimeLabel.grid(row = 1, column = 0) self.text_Input = tk.StringVar() operator = " " txtDisplay = tk.Entry(self, font=('arial', 15), textvariable = self.text_Input, bd = 5, insertwidth=4, bg = "white", justify = 'right') txtDisplay.grid(columnspan=4, row = 0, column = 0) IDLabel = tk.Label(self, font=('arial', 20, 'bold'), text="Enter ID Number", fg = "Black", bd = 10, anchor = 'w') IDLabel.grid(row = 0, column = 6) app = MainView() app.mainloop() <file_sep>/tkinter_Window.py from tkinter import* import random import time from Dictionary import Dictionary '''This is going to focus on the multi_window concept and focus on getting windows from different files within the same folder and properly displaying them''' window = Tk() #Parent Window window.geometry("1600x800+0+0") window.title("Testing Window") list = [] DC = Dictionary(); # class FrameSetup(): # mRelief = SUNKEN # def __init__(self,mWindow,mHeight, mWidth,mBg): # self.mWindow = mWindow # self.mWidth = mWidth # self.mHeight = mHeight # self.mBg = mBg # def setFrame(self): # Frame(mWindow, height = self.mHeight,width = self.mWidth, bg=self.mBg, relief=mRelief) FrameOne = Frame(window,height = 0, width = 1600, bg="blue", relief=SUNKEN) FrameOne.pack(side=TOP) FrameTwo = Frame(window, height = 700, width = 800, bg="blue", relief=SUNKEN) FrameTwo.pack(side=LEFT) FrameThree = Frame(window, height = 700, cursor = "dot", width = 400, bg="light gray", relief=SUNKEN) FrameThree.pack(side=RIGHT) FrameFour = Frame(window, height = 700, cursor = "dot", width = 400, bg="light gray", relief=SUNKEN) FrameFour.pack(side=TOP) firstLabel = Label(FrameOne, font=('arial', 50, 'bold'), text="Welcome to my Window", fg = "Black", bd = 10, anchor = 'w') firstLabel.grid(row = 0, column = 0) localtime = time.asctime(time.localtime(time.time())) TimeLabel = Label(FrameTwo, font=('arial', 20, 'bold'), text=localtime, fg = "Black", bd = 10, anchor = 'w') TimeLabel.grid(row = 1, column = 0) text_Input = StringVar() operator = " " txtDisplay = Entry(FrameThree, font=('arial', 15), textvariable = text_Input, bd = 5, insertwidth=4, bg = "white", justify = 'right') txtDisplay.grid(columnspan=4, row = 0, column = 0) IDLabel = Label(FrameFour, font=('arial', 20, 'bold'), text="Enter ID Number", fg = "Black", bd = 10, anchor = 'w') IDLabel.grid(row = 0, column = 6) #DC = Dictionary(operator) def buttonClick(numbers): global operator operator = operator + str(numbers) text_Input.set(operator) return; # shold pass choice password, and the password itself so that we can recall it later def OKClick(passChoice): global operator # get value and store in passChoice print(passChoice) # have an empty dictionary to save the password but not sure if it will create a new one each time.... passwordKeys = {} # check that operator is not null if len(operator) > 0: passwordKeys = dict([(passChoice,operator)]) print(passwordKeys) else: print('No value has been input') return; def DeleteClick(): global operator operator = operator[:-1] text_Input.set(operator) return; def AddClick(): global operator DC.AddToArray(operator, list) DC.PrintList(list) operator = " " text_Input.set(operator) return; class CreateButton(): """Doc: Class that will be used to create numerical keys and later alphabet keys to display and save the values in dictionaries so that they can be refered back via keys (for the time being)""" # local variables in create button class vark = StringVar(window) padx = 20 pady = 16 bd = 4 fg = "black" mFont = ('arial',15) mBg = 'gray' def __init__(self,frameNmbr,mText,mRow,mColumn): self.frameNmbr = frameNmbr self.mText = mText self.mRow = mRow self.mColumn = mColumn def passButtonVal(self): okayButton = Button(self.frameNmbr, padx = self.padx, pady = self.pady, bd = self.bd, fg = self.fg, font = self.mFont, text = self.mText, bg = self.mBg, command = lambda: buttonClick(self.mText)).grid(row=self.mRow, column = self.mColumn, sticky="ew") # the enterButton specially made due to the command being different as well as the deleteButton. The OkClick should pass the passwordSelected choice but doesn't at the moment...only passses the firstLabel def enterButton(self): okayButton = Button(self.frameNmbr, padx = self.padx, pady = self.pady, bd = self.bd, fg = self.fg, font = self.mFont, text = self.mText, bg = self.mBg, command = lambda: OKClick(mPassChoice)).grid(row=self.mRow, column= self.mColumn, sticky="ew") def deleteButton(self): okayButton = Button(self.frameNmbr, padx = self.padx, pady = self.pady, bd = self.bd, fg = self.fg, font = self.mFont, text = self.mText, bg = self.mBg, command = lambda: DeleteClick()).grid(row= self.mRow, column= self.mColumn, sticky="ew") def AddButton(self): okayButton = Button(self.frameNmbr, padx = self.padx, pady = self.pady, bd = self.bd, fg = self.fg, font = self.mFont, text = self.mText, bg = self.mBg, command = lambda: AddClick()).grid(row= self.mRow, column= self.mColumn, columnspan=3, sticky="ew") # dropDownMenu used to select password save position for retrival later on def dropDownMenu(self): vark = StringVar(window) PASSCHOICE = ['Select Password','<PASSWORD>','<PASSWORD>','<PASSWORD>'] vark.set(PASSCHOICE[0]) w = OptionMenu(window,vark,*PASSCHOICE) w.pack() # made mPasschoice global due to scope issues, need to correct this later on or problems will occur, such as other methods/functions being able to access this variables global mPassChoice mPassChoice = vark.get() # initialize all buttons using CreateButton class and pass the necessary values that are needed okayButton1 = CreateButton(FrameThree,"1",1,0) okayButton2 = CreateButton(FrameThree,"2",1,1) okayButton3 = CreateButton(FrameThree,"3",1,2) okayButton4 = CreateButton(FrameThree,"4",2,0) okayButton5 = CreateButton(FrameThree,"5",2,1) okayButton6 = CreateButton(FrameThree,"6",2,2) okayButton7 = CreateButton(FrameThree,"7",3,0) okayButton8 = CreateButton(FrameThree,"8",3,1) okayButton9 = CreateButton(FrameThree,"9",3,2) okayButton = CreateButton(FrameThree,"OK",4,0) okayButton0 = CreateButton(FrameThree,"0",4,1) okayButtonAdd = CreateButton(FrameThree, "Add", 5, 0) okayButton_bckspc = CreateButton(FrameThree,"<-",4,2) # create a password select dropdown menu as a CreateButton passwordSelect = CreateButton(FrameThree,'Select Password',5,1) passwordSelect.dropDownMenu() okayButton1.passButtonVal() okayButton2.passButtonVal() okayButton3.passButtonVal() okayButton4.passButtonVal() okayButton5.passButtonVal() okayButton6.passButtonVal() okayButton7.passButtonVal() okayButton8.passButtonVal() okayButton9.passButtonVal() okayButton.enterButton() okayButton0.passButtonVal() okayButtonAdd.AddButton() okayButton_bckspc.deleteButton() window.mainloop() <file_sep>/MyApp/MyApplication.py import tkinter as tk from tkinter import font as tkfont import random import time from Dictionary import Dictionary import sqlite3 from LoginDataBase import loginDB class MyApplication(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic") # the container is where we'll stack a bunch of frames # on top of each other, then the one we want visible # will be raised above the others container = tk.Frame(self) container.pack(side="top", fill="both", expand=True) container.grid_rowconfigure(0, weight=1) container.grid_columnconfigure(0, weight=1) self.frames = {} for F in (MainView, LoginView, CreateAccountView): page_name = F.__name__ frame = F(parent=container, controller=self) self.frames[page_name] = frame # put all of the pages in the same location; # the one on the top of the stacking order # will be the one that is visible. frame.grid(row=0, column=0, sticky="nsew") self.show_frame("LoginView") def show_frame(self, page_name): '''Show a frame for the given page name''' frame = self.frames[page_name] frame.tkraise() class MainView(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) # loginPage = LoginPage(self) self.controller = controller firstLabel = tk.Label(self, font=('arial', 50, 'bold'), text="Welcome to my Window", fg = "Black", bd = 10, anchor = 'w') firstLabel.grid(row = 0, column = 0) list = [ ] self.localtime = time.asctime(time.localtime(time.time())) TimeLabel = tk.Label(self, font=('arial', 20, 'bold'), text=self.localtime, fg = "Black", bd = 10, anchor = 'w') TimeLabel.grid(row = 0, column = 6) self.text_Input = tk.StringVar() self.operator = " " txtDisplay = tk.Entry(self, font=('arial', 15), textvariable = self.text_Input, bd = 5, insertwidth=4, bg = "white", justify = 'right') txtDisplay.grid(columnspan=4, row = 3, column = 1) IDLabel = tk.Label(self, font=('arial', 20, 'bold'), text="Enter ID Number", fg = "Black", bd = 10, anchor = 'w') IDLabel.grid(columnspan=4, row = 1, column = 1) okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "1", bg = "gray", command = lambda: buttonClick("1")).grid(row=4, column=1, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "2", bg = "gray", command = lambda: buttonClick("2")).grid(row=4, column=2, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "3", bg = "gray", command = lambda: buttonClick("3")).grid(row=4, column=3, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "4", bg = "gray", command = lambda: buttonClick("4")).grid(row=5, column=1, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "5", bg = "gray", command = lambda: buttonClick("5")).grid(row=5, column=2, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "6", bg = "gray", command = lambda: buttonClick("6")).grid(row=5, column=3, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "7", bg = "gray", command = lambda: buttonClick("7")).grid(row=6, column=1, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "8", bg = "gray", command = lambda: buttonClick("8")).grid(row=6, column=2, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "9", bg = "gray", command = lambda: buttonClick("9")).grid(row=6, column=3, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "OK", bg = "gray", command = lambda: AddClick()).grid(row=7, column=1, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "0", bg = "gray", command = lambda: buttonClick("0")).grid(row=7, column=2, sticky="ew") okayButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "<-", bg = "gray", command = lambda: DeleteClick()).grid(row=7, column=3, sticky="ew") LogOutButton = tk.Button(self, padx=20, pady=16, bd = 4, fg = "black", font = ('arial', 15), text = "Logout", bg = "orange", command = lambda: controller.show_frame("LoginView")).grid(columnspa=3, row=8, column=1, sticky="ew") def buttonClick(numbers): global operator self.operator = self.operator + str(numbers) self.text_Input.set(self.operator) return; # shold pass choice password, and the password itself so that we can recall it later def OKClick(passChoice): global operator # get value and store in passChoice print(self.passChoice) # have an empty dictionary to save the password but not sure if it will create a new one each time.... passwordKeys = {} # check that operator is not null if len(self.operator) > 0: passwordKeys = dict([(self.passChoice,self.operator)]) print(passwordKeys) else: print('No value has been input') return; def DeleteClick(): global operator self.operator = self.operator[:-1] self.text_Input.set(self.operator) return; def AddClick(): global operator DC = Dictionary() DC.AddToArray(self.operator, list) DC.PrintList(list) self.operator = " " self.text_Input.set(self.operator) return; class LoginView(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.usernametext = tk.StringVar() self.username = "" self.passwordtext = tk.StringVar() self.password = "" label = tk.Label(self, text="Login Page", font=('ariel',35, 'bold')) label.grid(columnspan=4, row = 0, column = 1) UsernameLabel = tk.Label(self, font=('arial', 20), text="Username: ", fg = "Black", bd = 10, anchor = 'w') UsernameLabel.grid(columnspan=4, row = 1, column = 1) PasswordLabel = tk.Label(self, font=('arial', 20), text="Password: ", fg = "Black", bd = 10, anchor = 'w') PasswordLabel.grid(columnspan=4, row = 2, column = 1) LoginButton = tk.Button(self, text="Login",command=lambda: CheckCredentials()) LoginButton.grid(columnspan=3, row = 7, column = 5, sticky = "ew") CreateButton = tk.Button(self, text="Create Account",command=lambda: CreateAccountClick()) CreateButton.grid(columnspan=3, row = 7, column = 8, sticky = "ew") UsernameInput = tk.Entry(self, font=('arial', 15), textvariable = self.usernametext, bd = 6, insertwidth=4, bg = "white", justify = 'right') UsernameInput.grid(columnspan=6, row = 1, column = 5) PasswordInput = tk.Entry(self, font=('arial', 15), show="*", textvariable = self.passwordtext, insertwidth=6, bd = 6, bg = "white", justify = 'right') PasswordInput.grid(columnspan=6, row = 2, column = 5) ErrorLabel = tk.Label(self, font=('arial', 12), text="Incorrect Username or Password", fg = "Red", bd = 10, anchor = 'w') ErrorLabel.grid_forget() def CreateAccountClick(): ErrorLabel.grid_forget() controller.show_frame("CreateAccountView") def CheckCredentials(): LogDB = loginDB() username = UsernameInput.get() password = PasswordInput.get() if LogDB.CheckDBCred(username, password): print('login successful') controller.show_frame("MainView") self.usernametext.set(self.username) self.passwordtext.set(self.password) else: ErrorLabel.grid(columnspan=6, row = 4, column = 5, sticky="ew") LogDB.___del___() class CreateAccountView(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.controller = controller self.causernametext = tk.StringVar() self.causername = "" self.capasswordtext = tk.StringVar() self.capassword = "" self.capasswordagaintext = tk.StringVar() self.capasswordagain = "" label = tk.Label(self, text="Create Your Account", font=('ariel',35, 'bold')) label.grid(columnspan=4, row = 0, column = 1) CAUsernameLabel = tk.Label(self, font=('arial', 20), text="Username: ", fg = "Black", bd = 10, anchor = 'w') CAUsernameLabel.grid(columnspan=4, row = 1, column = 1) CAPasswordLabel = tk.Label(self, font=('arial', 20), text="Password: ", fg = "Black", bd = 10, anchor = 'w') CAPasswordLabel.grid(columnspan=4, row = 2, column = 1) CADoneButton = tk.Button(self, text="Create",command=lambda: CreateAccount()) CADoneButton.grid(columnspan=3, row = 7, column = 5, sticky = "ew") ExitButton = tk.Button(self, text="Back",command=lambda: controller.show_frame("LoginView")) ExitButton.grid(columnspan=3, row = 7, column = 8, sticky = "ew") CAUsernameInput = tk.Entry(self, font=('arial', 15), textvariable = self.causernametext, bd = 6, insertwidth=4, bg = "white", justify = 'right') CAUsernameInput.grid(columnspan=6, row = 1, column = 5) CAPasswordInput = tk.Entry(self, font=('arial', 15), show="*", textvariable = self.capasswordtext, insertwidth=6, bd = 6, bg = "white", justify = 'right') CAPasswordInput.grid(columnspan=6, row = 2, column = 5) CAPasswordAgainLabel = tk.Label(self, font=('arial', 20), text="Password: ", fg = "Black", bd = 10, anchor = 'w') CAPasswordAgainLabel.grid(columnspan=4, row = 3, column = 1) CAPasswordAgainInput = tk.Entry(self, font=('arial', 15), show="*", textvariable = self.capasswordagaintext, insertwidth=6, bd = 6, bg = "white", justify = 'right') CAPasswordAgainInput.grid(columnspan=6, row = 3, column = 5) UsernameTakenLabel = tk.Label(self, font=('arial', 12), text="Username Taken", fg = "Red", bd = 10, anchor = 'w') UsernameTakenLabel.grid_forget() PasswordNoMatchLabel = tk.Label(self, font=('arial', 12), text="Passwords Do Not Match", fg = "Red", bd = 10, anchor = 'w') PasswordNoMatchLabel.grid_forget() def CreateAccount(): LogDB = loginDB() username = CAUsernameInput.get() password = <PASSWORD>() passwordagain = <PASSWORD>.get() UsernameTakenLabel.grid_forget() PasswordNoMatchLabel.grid_forget() if LogDB.CheckDBUser(username): UsernameTakenLabel.grid(columnspan=6, row = 5, column = 5, sticky="ew") return if not LogDB.CheckDBUser(username) and password == <PASSWORD>: LogDB.addUser(username, password) controller.show_frame("LoginView") self.causernametext.set(self.causername) self.capasswordtext.set(self.capassword) self.capasswordagaintext.set(self.capasswordagain) else: PasswordNoMatchLabel.grid(columnspan=6, row = 5, column = 5, sticky="ew") LogDB.___del___() if __name__ == "__main__": root = MyApplication() root.wm_geometry("1500x1000") root.title("My Application") root.mainloop() <file_sep>/source.py print('hello World! Time to learn a new language\n \n') import pygame # constant global variables S_WIDTH = 500 S_HEIGHT = 500 BLACK = (255,255,255) BLUE_HUE = (29,109,194) # create an object to help maintain time using Clock time_interval = pygame.time.Clock() screen = 'First display Test' class StartScreen(object): """docstring for StartScreen.""" # Update the clock also refers to frame rate time_rate = 60 #fps # global variable to hold in the user input user_input = '' def __init__(self, mScreenTitle,mWidth,mHeight): self.mScreenTitle = mScreenTitle self.mWidth = mWidth self.mHeight = mHeight # display blue hue by creating a display with specified WxH self.screen = pygame.display.set_mode((S_WIDTH,S_HEIGHT)) self.screen.fill(BLUE_HUE) #name of the screen pygame.display.set_caption(mScreenTitle) def loadScreen(self): END_DISPLAY = False font = pygame.font.Font(None,50) while not END_DISPLAY: # we get all events that are occurring, ie mouse clicks, keyboard strokes etc for event in pygame.event.get(): if event.type == pygame.QUIT: END_DISPLAY = True # check if the event is a keystroke elif event.type == pygame.KEYDOWN: # check if the keystroke is a alphabet and if it is then store to user_input if event.unicode.isalpha(): self.user_input += event.unicode # if enter is pressed clear user input then refill the screen with the same color elif event.key == pygame.K_RETURN: self.user_input = '' self.screen.fill(BLUE_HUE) # using the font from pygame render the input from the user block = font.render(self.user_input,True,BLACK) inputBox = block.get_rect() self.screen.blit(block,inputBox) # as long as the while loop is running we need to show and update the display as well as keep up with the time using .tick() pygame.display.update() time_interval.tick(self.time_rate) # NOTE: after importing pygame, initialize pygame pygame.init() # CREATE a new object from the class StartScreen and pass in the necessary values for the __init__ newScreen = StartScreen(screen,S_WIDTH,S_HEIGHT) # call the loadScreen on the variable created from the StartScreen class newScreen.loadScreen() # we need to end pygame and quit pygame.quit() quit() <file_sep>/MyApp/LoginDataBase.py import sqlite3 class loginDB(): def __init__(self): #Initialize db class variables self.connection = sqlite3.connect('LoginCredentials.db') self.cur = self.connection.cursor() def ___del___(self): #close sqlite3 connection self.connection.close() def addUser(self, newUserName, newPassword): with self.connection: self.cur.execute(" INSERT INTO LoginInfo VALUES (:username, :password)", {'username': newUserName, 'password': newPassword}) self.connection.commit() def CheckDBUser(self, userID): self.cur.execute("SELECT * FROM LoginInfo WHERE username=:username", {'username': userID}) return self.cur.fetchall() def CheckDBCred(self, userID, passCode): self.cur.execute("SELECT * FROM LoginInfo WHERE username=:username AND password=:password", {'username': userID, 'password':passCode}) return self.cur.fetchall() def DeleteUser(self, userID, passCode): with self.connection: self.cur.execute("DELETE from LoginInfo WHERE username=:username AND password=:password", {'username': userID, 'password':passCode}) self.connection.commit() def commit(self): #commit changes to database self.connection.commit() # conn = sqlite3.connect('LoginCredentials.db') # cursor = conn.cursor() ## create a table now # cursor.execute("""CREATE TABLE LoginInfo ( # username text, # password text # )""") ##ADD data to table # cursor.execute(" INSERT INTO LoginInfo VALUES ('hamzam', '9035712357')") # cursor.execute(" INSERT INTO LoginInfo VALUES ('freddiev', '4692267036')") # conn.commit() ##run query # cursor.execute("SELECT * FROM LoginInfo WHERE username='hamzam'") ##three ways to cycle through query ## 1. fetchone() --- gets the first occurance ## 2. fetchmany(*int*) --- gets that many occurances ## 3. fetchall() --- gets all the occurancs # print(cursor.fetchone()[1]) # conn.commit() ## commits the current changes # conn.close() ##good to close connection at end
54214912c898660c9592788112693611ca994615
[ "Python" ]
6
Python
TheFredward/Python_project
19c059bb0049878a3a68796ef1b67a4cf5562f2d
04463ee6227fce14c647ac01806c0d8469b4e67a
refs/heads/master
<repo_name>lyy1/PerfectServer<file_sep>/Sources/DB.swift // // DB.swift // PerfectTemplate // // Created by lyy on 2017/6/5. // // import Foundation import PerfectHTTP import PerfectLib import MySQL let Host = "127.0.0.1" let User = "root" let Password = "" enum DB: String { case bill = "Bill" case checkIn = "CheckIn" case courseManager = "CourseManager" case sysManage = "SysManage" } enum tablesofSysManage: String { case bed = "Bed" case check = "Checking" case medicine = "Medicine" case nursing = "Nursing" case user = "User" } enum tableofBill: String { case checkBill = "CheckBill" case medicineBill = "MedicineBill" case nursingBill = "NursingBill" } enum tableofCheckIn: String { case patient = "Patient" } enum tableofCourseManage: String { case advice = "AdviceofDoc" case medicalRecord = "Medicalrecord" case treatment = "Treatment" } class DataBaseManager { var mysql: MySQL init() { mysql = MySQL.init() guard mysql.setOption(MySQLOpt.MYSQL_SET_CHARSET_NAME, "utf8") else { print("not set") return } guard connectedDataBase() else { return } } private func connectedDataBase() -> Bool { let connected = mysql.connect(host: Host, user: User, password: <PASSWORD>) guard connected else { print("MySQL连接失败" + mysql.errorMessage()) return false } print("MySQL连接成功") return true } func mysqlStatement(sql: String) -> (success: Bool, mysqlResult: MySQL.Results?, errorMsg: String?) { let successQuery = mysql.query(statement: sql) guard successQuery else { let msg = "SQL失败:\(sql)" print(msg) return (false, nil, msg) } return (true, mysql.storeResults(), nil) } func selectAllDataBaseSQL(db: DB, tableName: String) -> (success: Bool, mysqlResult: MySQL.Results?, errorMsg: String?) { let connected = mysql.selectDatabase(named: db.rawValue) guard connected else { let msg = "连接此数据库失败" print(msg) return (false, nil, msg) } let SQL = "SELECT * FROM \(tableName)" return mysqlStatement(sql: SQL) } func selectLatestDataBaseSQL(db: DB, tableName: String, qty: Int) -> (success: Bool, mysqlResult: MySQL.Results?, errorMsg: String?) { let connected = mysql.selectDatabase(named: db.rawValue) guard connected else { let msg = "连接此数据库失败" print(msg) return (false, nil, msg) } let SQL = "SELECT * FROM \(tableName) ORDER BY Date DESC LIMIT \(qty)" return mysqlStatement(sql: SQL) } func selectDataBaseSQLWhere(db: DB, tableName: String, keyValue: String) -> (success: Bool, mysqlResult: MySQL.Results?, errorMsg: String?) { let connected = mysql.selectDatabase(named: db.rawValue) guard connected else { let msg = "连接此数据库失败" print(msg) return (false, nil, msg) } let SQL = "SELECT * FROM \(tableName) WHERE \(keyValue)" return mysqlStatement(sql: SQL) } func Login(userID: String, pwd: String) -> String{ let result = selectDataBaseSQLWhere(db:DB.sysManage, tableName: tablesofSysManage.user.rawValue, keyValue:"UserID ='\(userID)'") guard result.success else { print("查询数据失败") return "" } var userInfo = [String: String]() result.mysqlResult?.forEachRow(callback: { (row) in guard row[6] == pwd else { return } userInfo["Name"] = row[1] userInfo["Sex"] = row[2] userInfo["Age"] = row[3] userInfo["Tel"] = row[4] userInfo["SectionName"] = row[5] userInfo["RightInfo"] = row[7] }) let data : NSData! = try? JSONSerialization.data(withJSONObject: userInfo, options: []) as NSData! let JSONString = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) return JSONString! as String } func mysqlGetUserDataResult() -> String { let result = selectAllDataBaseSQL(db:DB.sysManage, tableName: tablesofSysManage.user.rawValue) var resultArray = [Dictionary<String, String>]() var dic = [String:String]() result.mysqlResult?.forEachRow(callback: { (row) in dic["UserID"] = row[0] dic["Name"] = row[1] dic["Sex"] = row[2] dic["Age"] = row[3] dic["Tel"] = row[4] dic["SectionName"] = row[5] dic["RightInfo"] = row[7] resultArray.append(dic) }) let data : NSData! = try? JSONSerialization.data(withJSONObject: resultArray, options: []) as NSData! let JSONString = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) return JSONString! as String } func mysqlGetBedDataResult() -> String { let result = selectAllDataBaseSQL(db:DB.sysManage, tableName: tablesofSysManage.bed.rawValue) var resultArray = [Dictionary<String, String>]() var dic = [String:String]() result.mysqlResult?.forEachRow(callback: { (row) in dic["BedNum"] = row[0] dic["SectionName"] = row[1] dic["RoomNum"] = row[2] dic["RoomSize"] = row[3] dic["BedPrice"] = row[4] dic["BedState"] = row[5] resultArray.append(dic) }) let data : NSData! = try? JSONSerialization.data(withJSONObject: resultArray, options: []) as NSData! let JSONString = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) return JSONString! as String } func mysqlGetMedicineDataResult() -> String { let result = selectAllDataBaseSQL(db:DB.sysManage, tableName: tablesofSysManage.medicine.rawValue) var resultArray = [Dictionary<String, String>]() var dic = [String:String]() result.mysqlResult?.forEachRow(callback: { (row) in dic["MedNum"] = row[0] dic["MedName"] = row[1] dic["MedUse"] = row[2] dic["MedPrice"] = row[3] resultArray.append(dic) }) let data : NSData! = try? JSONSerialization.data(withJSONObject: resultArray, options: []) as NSData! let JSONString = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) return JSONString! as String } func mysqlGetCheckDataResult() -> String { let result = selectAllDataBaseSQL(db:DB.sysManage, tableName: tablesofSysManage.check.rawValue) var resultArray = [Dictionary<String, String>]() var dic = [String:String]() result.mysqlResult?.forEachRow(callback: { (row) in dic["CheckNum"] = row[0] dic["CheckName"] = row[1] dic["CheckPrice"] = row[2] resultArray.append(dic) }) let data : NSData! = try? JSONSerialization.data(withJSONObject: resultArray, options: []) as NSData! let JSONString = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) return JSONString! as String } func mysqlGetNursingDataResult() -> String { let result = selectAllDataBaseSQL(db:DB.sysManage, tableName: tablesofSysManage.nursing.rawValue) var resultArray = [Dictionary<String, String>]() var dic = [String:String]() result.mysqlResult?.forEachRow(callback: { (row) in dic["NursingNum"] = row[0] dic["NursingName"] = row[1] dic["NursingPrice"] = row[2] resultArray.append(dic) }) let data : NSData! = try? JSONSerialization.data(withJSONObject: resultArray, options: []) as NSData! let JSONString = NSString(data: data as Data, encoding: String.Encoding.utf8.rawValue) return JSONString! as String } func mysqlAddSysManageData(db: String, table: String, dic: [String: String]) -> (success: Bool, mysqlResult: MySQL.Results?, errorMsg: String?) { let connected = mysql.selectDatabase(named: db) guard connected else { let msg = "连接此数据库失败" print(msg) return (false, nil, msg) } var value = "" var key = "" for item in dic { if value != "" { value += "," } if item.value == "" { value += "NULL" } else { value += "\'\(item.value)\'" } if key == "" { key += "\(item.key)" } else { key += ",\(item.key)" } } let SQL = "INSERT INTO \(table) (\(key)) VALUES (\(value));" print(SQL) return mysqlStatement(sql: SQL) } func mysqlDelete(db: String, table: String, Sname: String, num: String) -> (success: Bool, mysqlResult: MySQL.Results?, errorMsg: String?) { let connected = mysql.selectDatabase(named: db) guard connected else { let msg = "连接此数据库失败" print(msg) return (false, nil, msg) } let SQL = "DELETE FROM \(table) WHERE \(Sname)=\'\(num)\'" return mysqlStatement(sql: SQL) } func mysqlUpdate(db: String, table: String, dic: [String: String], Sname: String, num: String) -> (success: Bool, mysqlResult: MySQL.Results?, errorMsg: String?) { let connected = mysql.selectDatabase(named: db) guard connected else { let msg = "连接此数据库失败" print(msg) return (false, nil, msg) } var updateStr = "" for item in dic { if updateStr == "" { updateStr += "\(item.key)=\'\(item.value)\'" } else { updateStr += ",\(item.key)=\'\(item.value)\'" } } let SQL = "UPDATE \(table) SET \(updateStr) WHERE \(Sname)=\'\(num)\'" return mysqlStatement(sql: SQL) } func mysqlGetBillData() -> [String: Any] { var results = [String: [[String:String]]]() var CheckBillArray = [[String:String]]() let billsofCheck = selectLatestDataBaseSQL(db: DB.bill, tableName: tableofBill.checkBill.rawValue, qty: 3) billsofCheck.mysqlResult?.forEachRow(callback: { (row) in var dic = [String:String]() dic["Num"] = row[0] dic["PatientNum"] = row[1] dic["NurseNum"] = row[2] dic["CheckNum"] = row[3] dic["Date"] = row[4] dic["State"] = row[5] dic["Amount"] = row[6] dic["TotalPrice"] = row[7] CheckBillArray.append(dic) }) results["CheckBill"] = CheckBillArray var NursingBillArray = [[String:String]]() let billsofNurse = selectLatestDataBaseSQL(db: DB.bill, tableName: tableofBill.nursingBill.rawValue, qty: 3) billsofNurse.mysqlResult?.forEachRow(callback: { (row) in var dic = [String:String]() dic["Num"] = row[0] dic["PatientNum"] = row[1] dic["NurseNum"] = row[2] dic["CheckNum"] = row[3] dic["Date"] = row[4] dic["State"] = row[5] dic["Amount"] = row[6] dic["TotalPrice"] = row[7] NursingBillArray.append(dic) }) results["NursingBill"] = CheckBillArray var MedBillArray = [[String:String]]() let billsofMed = selectLatestDataBaseSQL(db: DB.bill, tableName: tableofBill.medicineBill.rawValue, qty: 3) billsofMed.mysqlResult?.forEachRow(callback: { (row) in var dic = [String:String]() dic["Num"] = row[0] dic["PatientNum"] = row[1] dic["NurseNum"] = row[2] dic["CheckNum"] = row[3] dic["Date"] = row[4] dic["State"] = row[5] dic["Amount"] = row[6] dic["TotalPrice"] = row[7] dic["Num1"] = row[8] dic["Num2"] = row[9] MedBillArray.append(dic) }) results["MedBill"] = MedBillArray let encoded = results return encoded } } <file_sep>/Sources/main.swift import PerfectLib import PerfectHTTP import PerfectHTTPServer let port1 = 8080 var server = HTTPServer() server.serverName = "maispangle" server.serverPort = UInt16(port1) enum apiaaa: String { case getUserData = "getAllUserData" case get } var routes = Routes() routes.add(method: .get, uri: "/api/getInfo/{api}", handler: { request, response in response.status = HTTPResponseStatus.accepted switch request.urlVariables["api"]! { case "getAllUserDataResult": response.setBody(string: DataBaseManager().mysqlGetUserDataResult()) case "getBedDataResult": response.setBody(string: DataBaseManager().mysqlGetBedDataResult()) case "getCheckDataResult": response.setBody(string: DataBaseManager().mysqlGetCheckDataResult()) case "getNursingDataResult": response.setBody(string: DataBaseManager().mysqlGetNursingDataResult()) case "getMedicineDataResult": response.setBody(string: DataBaseManager().mysqlGetMedicineDataResult()) case "getBillsDataResult": // response.setBody(string: DataBaseManager().mysqlGetBillData()) do { try response.setBody(json: DataBaseManager().mysqlGetBillData()) } catch { fatalError("\(error)") } default: response.status = .notFound } response.completed() }) routes.add(method: .get, uri: "/api/login", handler: { request, response in response.status = .accepted var username: String = "" var pwd: String = "" for (a, b) in request.queryParams { if a == "ID" { username = b } if a == "pwd" { pwd = b } } if username == "" || pwd == "" { response.status = .notFound } let result = DataBaseManager().Login(userID: username, pwd: pwd) response.setBody(string: result) response.completed() }) routes.add(method: .post, uri: "/api/Insert", handler: { request, response in response.status = .accepted var table: String var db: String let t = request.postParams if request.queryParams[0].0 == "db" && request.queryParams[1].0 == "table" { db = request.queryParams[0].1 table = request.queryParams[1].1 var dic = [String: String]() for (key, val) in t { dic[key] = val } if DataBaseManager().mysqlAddSysManageData(db: db, table: table, dic: dic).success { response.setBody(string: "true") } else { response.setBody(string: "fail") } } else { response.setBody(string: "fail") } response.completed() }) routes.add(method: .get, uri: "/api/Delete", handler: { request, response in response.status = .accepted var table: String var db: String var num: String var name: String if request.queryParams[0].0 == "db" && request.queryParams[1].0 == "table" && request.queryParams[2].0 == "Num" && request.queryParams[3].0 == "name" { db = request.queryParams[0].1 table = request.queryParams[1].1 num = request.queryParams[2].1 name = request.queryParams[3].1 if DataBaseManager().mysqlDelete(db: db, table: table, Sname: name, num: num).success { response.setBody(string: "true") } else { response.setBody(string: "fail") } } else { response.setBody(string: "fail") } response.completed() }) routes.add(method: .post, uri: "/api/Edit", handler: { request, response in response.status = .accepted var table: String var db: String let t = request.postParams var num: String var name: String if request.queryParams[0].0 == "db" && request.queryParams[1].0 == "table" && request.queryParams[2].0 == "Num" && request.queryParams[3].0 == "name" { db = request.queryParams[0].1 table = request.queryParams[1].1 num = request.queryParams[2].1 name = request.queryParams[3].1 var dic = [String: String]() for (key, val) in t { dic[key] = val } if DataBaseManager().mysqlUpdate(db: db, table: table, dic: dic, Sname: name, num: num).success { response.setBody(string: "true") } else { response.setBody(string: "fail") } } else { response.setBody(string: "fail") } response.completed() }) server.addRoutes(routes) //MARK: filter struct Filter404: HTTPResponseFilter { func filterBody(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) { callback(.continue) } func filterHeaders(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) { if case .notFound = response.status { response.setBody(string: "404 not found") response.setHeader(.contentLength, value: "\(response.bodyBytes.count)") callback(.done) } else { callback(.continue) } } } server.setResponseFilters([(Filter404(), .high)]) do { // Launch the servers based on the configuration data. try server.start() } catch { fatalError("\(error)") // fatal error launching one of the servers }
6f2f56fca565375e6a854c9120d8352b3ab80b3f
[ "Swift" ]
2
Swift
lyy1/PerfectServer
c66175c0df76929f95641f4b04e811ae1ea8102a
91adb6153c0b2c7ea7c49a648f4ecffdd19903c7
refs/heads/master
<file_sep>import Foundation public extension Object { /// объект, описывающий видеозапись public struct Video: Codable { /// ключ доступа к объекту public let access_key: String? /// идентификатор альбома, в котором находится видеозапись public let album_id: Int? /// дата добавления видеозаписи пользователем или группой в формате Unixtime public let adding_date: Int? /// если пользователь может добавить видеозапись к себе public let can_add: Object.Boolean? /// поле возвращается, если пользователь может редактировать видеозапись public let can_edit: Object.Positive? /// количество комментариев к видеозаписи public let comments: Int? /// запрещенный контент public let content_restricted: Object.Positive? /// дата создания видеозаписи в формате Unixtime public let date: Int? /// текст описания видеозаписи public let description: String /// длительность ролика в секундах public let duration: Int? /// URL первого фрейма ролика с размером 130x98 px public let first_frame_130: String? /// URL первого фрейма ролика с размером 160x120 px public let first_frame_160: String? /// URL первого фрейма ролика с размером 320x240 px public let first_frame_320: String? /// URL первого фрейма ролика с размером 800x450 px public let first_frame_800: String? /// высота public let height: Int? /// идентификатор видеозаписи public let id: Int /// приватное public let is_private: Object.Positive? /// видеозапись является прямой трансляцией public let live: Object.Positive? /// идентификатор владельца видеозаписи public let owner_id: Int /// URL изображения-обложки ролика с размером 130x98 px public let photo_130: String? /// URL изображения-обложки ролика с размером 320x240 px public let photo_320: String? /// URL изображения-обложки ролика с размером 640x480 px public let photo_640: String? /// URL изображения-обложки ролика с размером 800x450 px public let photo_800: String? /// название платформы (для видеозаписей, добавленных с внешних сайтов) public let platform: String? /// URL страницы с плеером, который можно использовать для воспроизведения ролика в браузере. Поддерживается flash и html5, плеер всегда масштабируется по размеру окна public let player: String? /// видеоролик находится в процессе обработки public let processing: Object.Positive? /// повторять видеозапись public let `repeat`: Object.Positive? /// название видеозаписи public let title: String /// трансляция скоро начнётся public let upcoming: Object.Positive? /// идентификатор пользователя public let user_id: Int? /// количество просмотров видеозаписи public let views: Int? /// ширина public let width: Int? } } <file_sep>import RxCocoa import RxSwift import UIKit import VK extension VK.Service { func observableRequest<C, S, T>(cancel: Observable<C>, delay: TimeInterval = 0, lang: String = "ru", logs: Logs = .none, queue: DispatchQueue = .global(), strategy: S, timeout: TimeInterval = 10, track: Bool = true, v: String = "5.80") -> Observable<Output<T>> where S: Strategy, S.Value == T { return request(cancel: cancel, delay: delay, lang: lang, logs: logs, queue: queue, strategy: strategy, timeout: timeout, track: track, v: v) } func observableRequest<S, T>(delay: TimeInterval = 0, lang: String = "ru", logs: Logs = .none, queue: DispatchQueue = .global(), strategy: S, timeout: TimeInterval = 10, track: Bool = true, v: String = "5.80") -> Observable<Output<T>> where S: Strategy, S.Value == T { let cancel = Observable<Void>.never() return request(cancel: cancel, delay: delay, lang: lang, logs: logs, queue: queue, strategy: strategy, timeout: timeout, track: track, v: v) } } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { let disposeBag = DisposeBag() var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { defer { let strategy = Method.Utils.GetServerTime(token: "c0ece882f55b39c5899af7065b923ed55bcb96ade6e52aa2693d0ea674c41063a2decc1616604739d8cd7") getService() .observableRequest(strategy: strategy) .debug() .subscribe() .disposed(by: disposeBag) } window = UIWindow(frame: UIScreen.main.bounds) window?.rootViewController = UINavigationController(rootViewController: UIViewController()) window?.makeKeyAndVisible() return true } } <file_sep>import Foundation /// стратегия запроса к API public protocol Strategy { /// ассоциированное занчение, которое соответствует исходному ответу associatedtype Raw: Decodable /// ассоциированное занчение, к которому должен быть приобразован финальный ответ associatedtype Value: Decodable /// трансформация из исходного ответа в финальный var transform: (Raw) -> Value { get } /// название метода API, к которому Вы хотите обратиться var method: String { get } /// входные параметры соответствующего метода API var parameters: [String: Any] { get } } <file_sep>use_frameworks! platform :ios, '10.0' target 'Auth' do pod 'VK', :path => '../' end post_install do |installer| installer.pods_project.targets.each do |target| target.build_configurations.each do |config| config.build_settings['SWIFT_VERSION'] = '4.1' end end end <file_sep>import Foundation public extension Object { /// объект описывающий сокращенную ссылку для текущего пользователя public struct ShortenedLink: Decodable, Hashable { public var hashValue: Int { return key.hashValue } enum CodingKeys: String, CodingKey { case accessKey = "access_key" case key = "key" case shortUrl = "short_url" case timestamp = "timestamp" case url = "url" case views = "views" } /// ключ доступа к приватной статистике public let accessKey: String? /// содержательная часть (символы после "vk.cc") public let key: String /// сокращенный URL public let shortUrl: String /// время создания ссылки в Unixtime public let timestamp: TimeInterval /// URL ссылки до сокращения public let url: String /// число переходов public let views: Int public init(accessKey: String?, key: String, shortUrl: String, timestamp: TimeInterval, url: String, views: Int) { self.accessKey = accessKey self.key = key self.shortUrl = shortUrl self.timestamp = timestamp self.url = url self.views = views } } } <file_sep>import Foundation public extension Object { /// public enum Target: Codable { /// внутренний case `internal` /// неизвестное значение case exception(String) init(rawValue: String) { switch rawValue { case "internal": self = .internal default: self = .exception(rawValue) } } public var rawValue: String { switch self { case .internal: return "internal" case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: String = try container.decode() self = Object.Target(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } } <file_sep>import Foundation public extension Object { /// объект описывающий данные о статистике public struct ShortenedLinkStats: Codable { /// геостатистика по городам public struct City: Codable { /// идентификатор города; public let city_id: Int? private let _city_id: String? /// число переходов из этого города public let views: Int private enum Key: String, CodingKey { case city_id case views } public init(from decoder: Decoder) throws { let container = try Key.container(decoder: decoder) views = try container.decode(key: Key.views) do { self.city_id = try container.decode(key: Key.city_id) self._city_id = nil } catch { self.city_id = nil self._city_id = try container.decodeIfPresent(String.self, forKey: Key.city_id) } } public func encode(to encoder: Encoder) throws { var encoder = Key.container(encoder: encoder) try encoder.encode(views, forKey: Key.views) if let city_id = self.city_id { try encoder.encode(city_id, forKey: Key.city_id) } else if let city_id = self._city_id { try encoder.encode(city_id, forKey: Key.city_id) } } } /// геостатистика по странам public struct Country: Codable { /// идентификатор страны public let country_id: Int? private let _country_id: String? /// число переходов из этой страны public let views: Int private enum Key: String, CodingKey { case country_id case views } public init(from decoder: Decoder) throws { let container = try Key.container(decoder: decoder) views = try container.decode(key: Key.views) do { self.country_id = try container.decode(key: Key.country_id) self._country_id = nil } catch { self.country_id = nil self._country_id = try container.decodeIfPresent(String.self, forKey: Key.country_id) } } public func encode(to encoder: Encoder) throws { var encoder = Key.container(encoder: encoder) try encoder.encode(views, forKey: Key.views) if let country_id = self.country_id { try encoder.encode(country_id, forKey: Key.country_id) } else if let country_id = self._country_id { try encoder.encode(country_id, forKey: Key.country_id) } } } /// половозрастная статистика public struct SexAge: Codable { /// обозначение возраста public let age_range: String /// число переходов пользователей женского пола public let female: Int /// число переходов пользователей мужского пола public let male: Int } /// геостатистику по городам public let cities: [Object.ShortenedLinkStats.City]? /// геостатистику по странам public let countries: [Object.ShortenedLinkStats.Country]? /// половозрастная статистика public let sex_age: [Object.ShortenedLinkStats.SexAge]? /// время создания ссылки в Unixtime public let timestamp: Int /// число переходов public let views: Int } } <file_sep>import Foundation public extension Object { /// медиавложение в записях на стене public enum Attachment: Codable { /// тип вложения public enum Typе: String, Codable { /// альбом с фотографиями case album /// контент приложения. Это устаревший тип вложений case app /// аудиозапись case audio /// документ case doc /// граффити. Это устаревший тип вложения case graffiti /// ссылка case link /// товар case market /// подборка товаров case market_album /// заметка case note /// вики-страница case page /// фотография case photo /// список фотографий case photos_list /// опрос case poll /// фотография, загруженная напрямую. Это устаревший тип вложения case posted_photo /// pretty_cards case pretty_cards /// стикер case sticker /// видеозапись case video } private enum Key: String, CodingKey { case album, app, audio, doc, graffiti, link, market, market_album, note, page, photo, photos_list, poll, posted_photo, pretty_cards, sticker, video, type } /// объект, описывающий альбом с фотографиями case album(Object.Album) /// объект, описывающий контент приложения case app(Object.App) /// объект, описывающий аудиозапись case audio(Object.Audio) /// объект, описывающий документ case doc(Object.Doc) /// объект, описывающий граффити case graffiti(Object.Graffiti) /// объект, описывающий прикрепленную ссылку case link(Object.Link) /// объект, описывающий товар case market(Object.MarketItem) /// объект, описывающий подборку товаров case market_album(Object.MarketAlbum) /// объект, описывающий заметку case note(Object.Note) /// объект, описывающий вики-страницу case page(Object.Page) /// объект, описывающий фотографию case photo(Object.Photo) /// список фотографий case photos_list([String]?) /// объект, описывающий опрос case poll(Object.Poll) /// объект, описывающий фотографию, загруженную напрямую case posted_photo(Object.PostedPhoto) /// карусель товаров case pretty_cards(Object.PrettyCards) /// объект, описывающий стикер case sticker(Object.Sticker) /// объект, описывающий видеозапись case video(Object.Video) public init(from decoder: Decoder) throws { let container = try Key.container(decoder: decoder) let type: Object.Attachment.Typе = try container.decode(key: Key.type) switch type { case .album: let album: Object.Album = try container.decode(key: Key.album) self = .album(album) case .app: let app: Object.App = try container.decode(key: Key.app) self = .app(app) case .audio: let audio: Object.Audio = try container.decode(key: Key.audio) self = .audio(audio) case .doc: let doc: Object.Doc = try container.decode(key: Key.doc) self = .doc(doc) case .graffiti: let graffiti: Object.Graffiti = try container.decode(key: Key.graffiti) self = .graffiti(graffiti) case .link: let link: Object.Link = try container.decode(key: Key.link) self = .link(link) case .market: let market: Object.MarketItem = try container.decode(key: Key.market) self = .market(market) case .market_album: let market_album: Object.MarketAlbum = try container.decode(key: Key.market_album) self = .market_album(market_album) case .note: let note: Object.Note = try container.decode(key: Key.note) self = .note(note) case .page: let page: Object.Page = try container.decode(key: Key.page) self = .page(page) case .photo: let photo: Object.Photo = try container.decode(key: Key.photo) self = .photo(photo) case .photos_list: let photos_list: [String]? = try container.decode(key: Key.photos_list) self = .photos_list(photos_list) case .poll: let poll: Object.Poll = try container.decode(key: Key.poll) self = .poll(poll) case .posted_photo: let posted_photo: Object.PostedPhoto = try container.decode(key: Key.posted_photo) self = .posted_photo(posted_photo) case .pretty_cards: let pretty_cards: Object.PrettyCards = try container.decode(key: Key.pretty_cards) self = .pretty_cards(pretty_cards) case .sticker: let sticker: Object.Sticker = try container.decode(key: Key.sticker) self = .sticker(sticker) case .video: let video: Object.Video = try container.decode(key: Key.video) self = .video(video) } } public func encode(to encoder: Encoder) throws { var container = Key.container(encoder: encoder) switch self { case .app(let app): try container.encode(Key.app.rawValue, forKey: Key.type) try container.encode(app, forKey: Key.app) case .album(let album): try container.encode(Key.album.rawValue, forKey: Key.type) try container.encode(album, forKey: Key.album) case .audio(let audio): try container.encode(Key.audio.rawValue, forKey: Key.type) try container.encode(audio, forKey: Key.audio) case .doc(let doc): try container.encode(Key.doc.rawValue, forKey: Key.type) try container.encode(doc, forKey: Key.doc) case .graffiti(let graffiti): try container.encode(Key.graffiti.rawValue, forKey: Key.type) try container.encode(graffiti, forKey: Key.graffiti) case .link(let link): try container.encode(Key.link.rawValue, forKey: Key.type) try container.encode(link, forKey: Key.link) case .market(let market): try container.encode(Key.market.rawValue, forKey: Key.type) try container.encode(market, forKey: Key.market) case .market_album(let market_album): try container.encode(Key.market_album.rawValue, forKey: Key.type) try container.encode(market_album, forKey: Key.market_album) case .note(let note): try container.encode(Key.note.rawValue, forKey: Key.type) try container.encode(note, forKey: Key.note) case .page(let page): try container.encode(Key.page.rawValue, forKey: Key.type) try container.encode(page, forKey: Key.page) case .photo(let photo): try container.encode(Key.photo.rawValue, forKey: Key.type) try container.encode(photo, forKey: Key.photo) case .photos_list(let photos_list): try container.encode(Key.photos_list.rawValue, forKey: Key.type) try container.encode(photos_list, forKey: Key.photos_list) case .poll(let poll): try container.encode(Key.poll.rawValue, forKey: Key.type) try container.encode(poll, forKey: Key.poll) case .posted_photo(let posted_photo): try container.encode(Key.posted_photo.rawValue, forKey: Key.type) try container.encode(posted_photo, forKey: Key.posted_photo) case .pretty_cards(let pretty_cards): try container.encode(Key.pretty_cards.rawValue, forKey: Key.type) try container.encode(pretty_cards, forKey: Key.pretty_cards) case .video(let video): try container.encode(Key.video.rawValue, forKey: Key.type) try container.encode(video, forKey: Key.video) case .sticker(let sticker): try container.encode(Key.sticker.rawValue, forKey: Key.type) try container.encode(sticker, forKey: Key.sticker) } } } } <file_sep>import Foundation public extension Object { /// граффити public struct Graffiti: Codable { /// идентификатор граффити public let id: Int? /// идентификатор автора граффити public let owner_id: Int? /// URL изображения для предпросмотра public let photo_130: String? /// URL изображения для предпросмотра public let photo_200: String? /// URL изображения для предпросмотра public let photo_586: String? /// URL полноразмерного изображения public let photo_604: String? } } <file_sep>import Foundation public extension Object { /// объект, описывающий подборку товаров public struct MarketAlbum: Codable { /// число товаров в подборке public let count: Int? /// идентификатор подборки public let id: Int? /// обложка подборки public let photo: Object.Photo? /// идентификатор владельца подборки public let owner_id: Int? /// название подборки public let title: String? /// дата обновления подборки в формате Unixtime public let updated_time: Int? } } <file_sep>import Foundation public extension Method.Utils { /// список сокращенных ссылок для текущего пользователя public struct GetLastShortenedLinks: Strategy { /// количество ссылок, которые необходимо получить public let count: Int /// сдвиг для получения определенного подмножества ссылок public let offset: Int /// пользовательские данные public let token: Token public init(count: Int = 10, offset: Int = 0, token: Token) { self.count = count self.offset = offset self.token = token } public var method: String { return "utils.getLastShortenedLinks" } public var parameters: [String : Any] { var dictionary = [String : Any]() dictionary["access_token"] = token dictionary["count"] = "\(count)" dictionary["offset"] = "\(offset)" return dictionary } public var transform: (Object.Response<Object.Items<Object.ShortenedLink>>) -> [Object.ShortenedLink] { return { $0.response.items } } } } <file_sep>import Foundation public extension Object { /// объект product, описывающий информацию о продукте public struct Product: Codable { /// объект price, описывающий цену public struct Price: Codable { /// объект currency, описывающий информацию о валюте public struct Currency: Codable { /// идентификатор валюты public let id: Int? /// буквенное обозначение валюты public let name: String? } /// целочисленное значение цены, умноженное на 100 public let amount: String? /// объект currency public let currency: Object.Product.Price.Currency? /// строка с локализованной ценой и валютой public let text: String? } /// объект price public let price: Object.Product.Price? } } <file_sep>import Foundation public extension Object { /// сообщество public struct Group: Codable { /// информация о том, является ли текущий пользователь руководителем public enum AdminLevel: Codable { /// модератор case moderator /// редактор case editor /// администратор case administrator /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 1: self = .moderator case 2: self = .editor case 3: self = .administrator default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .moderator: return 1 case .editor: return 2 case .administrator: return 3 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Group.AdminLevel(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// возрастное ограничение public enum AgeLimits: Codable { /// нет case none /// 16+ case above16 /// 18+ case above18 /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 1: self = .none case 2: self = .above16 case 3: self = .above18 default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .none: return 1 case .above16: return 2 case .above18: return 3 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Group.AgeLimits(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// информация о занесении в черный список сообщества public struct BanInfo: Codable { /// комментарий к блокировке public let comment: String? /// срок окончания блокировки в формате unixtime public let end_date: Int? } /// информация из блока контактов публичной страницы public struct Contact: Codable { /// должность public let desc: String? /// адрес e-mail public let email: String? /// номер телефона public let phone: String? /// идентификатор пользователя public let user_id: Int? } /// объект, содержащий счётчики сообщества public struct Counters: Codable { /// количество фотоальбомов public let albums: Int? /// количество аудиозаписей public let audios: Int? /// количество документов public let docs: Int? /// количество фотографий public let photos: Int? /// количество обсуждений public let topics: Int? /// количество видеозаписей public let videos: Int? } /// обложка сообщества public struct Cover: Codable { /// включена ли обложка public let enabled: Object.Boolean? /// копии изображений обложки public let images: [Object.Image]? } /// возвращается в случае, если сообщество удалено или заблокировано public enum Deactivated: String, Codable { /// сообщество заблокировано case banned /// сообщество удалено case deleted } /// является ли сообщество закрытым public enum IsClosed: Codable { /// открытое case opened /// закрытое case closed /// частное case `private` /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 0: self = .opened case 1: self = .closed case 2: self = .private default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .opened: return 0 case .closed: return 1 case .private: return 2 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Group.IsClosed(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// информация из блока ссылок сообщества public struct Link: Codable { /// описание ссылки public let desc: String? /// идентификатор ссылки public let id: Int? /// название ссылки public let name: String? /// URL изображения-превью шириной 100px public let photo_100: String? /// URL изображения-превью шириной 50px public let photo_50: String? /// URL public let url: String? } /// информация о главной секции public enum MainSection: Codable { /// отсутствует case no_main_section /// фотографии case photos /// обсуждения case topics /// аудиозаписи case audios /// видеозаписи case videos /// товары case market /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 0: self = .no_main_section case 1: self = .photos case 2: self = .topics case 3: self = .audios case 4: self = .videos case 5: self = .market default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .no_main_section: return 0 case .photos: return 1 case .topics: return 2 case .audios: return 3 case .videos: return 4 case .market: return 5 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Group.MainSection(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// информация о магазине public struct Market: Codable { /// информация о валюте public struct Currency: Codable { /// идентификатор валюты public let id: Int? /// символьное обозначение public let name: String? } /// идентификатор контактного лица для связи с продавцом. Возвращается отрицательное значение, если для связи с продавцом используются сообщения сообщества public let contact_id: Int? /// строковое обозначение валюты public let currency_text: String? /// информация о том, включен ли блок товаров в сообществе public let enabled: Object.Boolean? /// идентификатор главной подборки товаров public let main_album_id: Int? /// максимальная цена товаров public let price_max: Int? /// минимальная цена товаров public let price_min: Int? } /// статус участника текущего пользователя public enum MemberStatus: Codable { /// не является участником case not_member /// является участником case member /// не уверен, что посетит мероприятие case not_sure /// отклонил приглашение case declined_invitation /// подал заявку на вступление case sent_request /// приглашен case invited /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 0: self = .not_member case 1: self = .member case 2: self = .not_sure case 3: self = .declined_invitation case 4: self = .sent_request case 5: self = .invited default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .not_member: return 0 case .member: return 1 case .not_sure: return 2 case .declined_invitation: return 3 case .sent_request: return 4 case .invited: return 5 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Group.MemberStatus(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// место, указанное в информации о сообществе public struct Place: Codable { /// адрес public let address: String? /// идентификатор города public let city: Int? /// идентификатор страны public let country: Int? /// идентификатор места public let id: Int? /// географическая широта в градусах (от -90 до 90) public let latitude: Double? /// географическая долгота в градусах (от -180 до 180) public let longitude: Double? /// название места public let title: String? /// тип места public let type: String? } /// тип сообщества public enum Typе: String, Codable { /// мероприятие case event /// группа case group /// публичная страница case page } /// строка состояния публичной страницы. У групп возвращается строковое значение, открыта ли группа или нет, а у событий дата начала public let activity: String? /// уровень полномочий текущего пользователя public let admin_level: Object.Group.AdminLevel? /// возрастное ограничение public let age_limits: Object.Group.AgeLimits? /// информация о занесении в черный список сообщества public let ban_info: Object.Group.BanInfo? /// информация о том, может ли текущий пользователь создать новое обсуждение в группе public let can_create_topic: Object.Boolean? /// информация о том, может ли текущий пользователь написать сообщение сообществу public let can_message: Object.Boolean? /// информация о том, может ли текущий пользователь оставлять записи на стене сообщества public let can_post: Object.Boolean? /// информация о том, разрешено ли видеть чужие записи на стене группы public let can_see_all_posts: Object.Boolean? /// информация о том, может ли текущий пользователь загружать документы в группу public let can_upload_doc: Object.Boolean? /// информация о том, может ли текущий пользователь загружать видеозаписи в группу public let can_upload_video: Object.Boolean? /// город, указанный в информации о сообществе public let city: Object.City? /// информация из блока контактов публичной страницы public let contacts: [Object.Group.Contact]? /// объект, содержащий счётчики сообщества public let counters: Object.Group.Counters? /// страна, указанная в информации о сообществе public let country: Object.Country? /// обложка сообщества public let cover: Object.Group.Cover? /// возвращается в случае, если сообщество удалено или заблокировано public let deactivated: Object.Group.Deactivated? /// текст описания сообщества public let description: String? /// время в формате unixtime public let finish_date: String? /// идентификатор закрепленной записи public let fixed_post: Int? /// информация о том, установлена ли у сообщества главная фотография public let has_photo: Object.Boolean? /// идентификатор сообщества. public let id: Int /// идентификатор пользователя, который отправил приглашение в сообщество public let invited_by: Int? /// информация о том, является ли текущий пользователь руководителем public let is_admin: Object.Boolean? /// является ли сообщество закрытым public let is_closed: Object.Group.IsClosed? /// информация о том, находится ли сообщество в закладках у текущего пользователя public let is_favorite: Object.Boolean? /// информация о том, скрыто ли сообщество из ленты новостей текущего пользователя public let is_hidden_from_feed: Object.Boolean? /// информация о том, является ли текущий пользователь участником public let is_member: Object.Boolean? /// информация о том, заблокированы ли сообщения от этого сообщества (для текущего пользователя) public let is_messages_blocked: Object.Boolean? /// информация из блока ссылок сообщества public let links: [Object.Group.Link]? /// идентификатор основного фотоальбома public let main_album_id: Int? /// информация о главной секции public let main_section: Object.Group.MainSection? /// информация о магазине public let market: Object.Group.Market? /// статус участника текущего пользователя public let member_status: Object.Group.MemberStatus? /// количество участников public let members_count: Int? /// название сообщества public let name: String /// url главной фотографии с размером 100х100px public let photo_100: String? /// url главной фотографии в максимальном размере public let photo_200: String? /// url главной фотографии с размером 50x50px public let photo_50: String? /// место, указанное в информации о сообществе public let place: Object.Group.Place? /// текст описания для поля start_date public let public_date_label: String? /// короткий адрес public let screen_name: String? /// адрес сайта из поля «веб-сайт» в описании сообщества public let site: String? /// для встреч время в формате unixtime / для публичных страниц дата основания в формате YYYYMMDD public let start_date: String? /// status public let status: String? /// информация о том, есть ли у сообщества «огонёк» public let trending: Object.Boolean? /// тип сообщества public let type: Object.Group.Typе? /// информация о том, верифицировано ли сообщество public let verified: Object.Boolean? /// название главной вики-страницы public let wiki_page: String? } } <file_sep>import Foundation public extension Object { /// объект, описывающий альбом с фотографиями public struct Album: Codable { /// дата создания альбома в формате Unixtime public let created: Int? /// описание альбома public let description: String? /// идентификатор альбома public let id: String? /// идентификатор владельца альбома public let owner_id: Int? /// количество фотографий в альбоме public let size: Int? /// обложка альбома, объект photo public let thumb: Object.Photo? /// название альбома public let title: String? /// дата последнего обновления альбома в формате Unixtime public let updated: Int? } } <file_sep>import Foundation public extension Object { /// пользователь public struct Photo: Codable { /// формат описания размеров фотографии public struct Size: Codable { /// обозначение размера и пропорций копии public enum Typе: String, Codable { /// k case k /// l case l /// пропорциональная копия изображения с максимальной стороной 130px case m /// если соотношение "ширина/высота" исходного изображения меньше или равно 3:2, то пропорциональная копия с максимальной стороной 130px. Если соотношение "ширина/высота" больше 3:2, то копия обрезанного слева изображения с максимальной стороной 130px и соотношением сторон 3:2 case o /// если соотношение "ширина/высота" исходного изображения меньше или равно 3:2, то пропорциональная копия с максимальной стороной 200px. Если соотношение "ширина/высота" больше 3:2, то копия обрезанного слева и справа изображения с максимальной стороной 200px и соотношением сторон 3:2 case p /// если соотношение "ширина/высота" исходного изображения меньше или равно 3:2, то пропорциональная копия с максимальной стороной 320px. Если соотношение "ширина/высота" больше 3:2, то копия обрезанного слева и справа изображения с максимальной стороной 320px и соотношением сторон 3:2 case q /// если соотношение "ширина/высота" исходного изображения меньше или равно 3:2, то пропорциональная копия с максимальной стороной 510px. Если соотношение "ширина/высота" больше 3:2, то копия обрезанного слева и справа изображения с максимальной стороной 510px и соотношением сторон 3:2 case r /// пропорциональная копия изображения с максимальной стороной 75px case s /// пропорциональная копия изображения с максимальным размером 2560x2048px case w /// пропорциональная копия изображения с максимальной стороной 604px case x /// пропорциональная копия изображения с максимальной стороной 807px case y /// пропорциональная копия изображения с максимальным размером 1080x1024 case z } /// высота копии в пикселах public let height: UInt? /// URL копии изображения public let src: String /// обозначение размера и пропорций копии public let type: Object.Photo.Size.Typе /// ширина копии в пикселах public let width: UInt? } /// ключ доступа к объекту public let access_key: String? /// идентификатор альбома, в котором находится фотография public let album_id: Int? /// дата добавления в формате Unixtime public let date: Int? /// public let has_filter: Object.Positive? /// высота оригинала фотографии в пикселах public let height: UInt? /// идентификатор фотографии public let id: Int? /// public let is_mail: Object.Positive? /// public let is_room: Object.Positive? /// lat public let lat: Double? /// long public let long: Double? /// идентификатор владельца фотографии public let owner_id: Int? /// URL копии фотографии с максимальным размером 1280x1024px public let photo_1280: String? /// URL копии фотографии с максимальным размером 130x130px public let photo_130: String? /// URL копии фотографии с максимальным размером 2560x2048px public let photo_2560: String? /// URL копии фотографии с максимальным размером 604x604px public let photo_604: String? /// URL копии фотографии с максимальным размером 75x75px public let photo_75: String? /// URL копии фотографии с максимальным размером 807x807px public let photo_807: String? /// идентификатор записи, в которую была загружена фотография public let post_id: Int? /// массив с копиями изображения в разных размерах public let sizes: [Object.Photo.Size]? /// public let src_big: String? /// public let src_small: String? /// текст описания фотографии public let text: String? /// идентификатор пользователя public let user_id: Int? /// ширина оригинала фотографии в пикселах public let width: UInt? } } <file_sep>import Foundation public extension Object { /// объект, описывающий товар public struct MarketItem: Codable { /// статус доступности товара public enum Availability: Codable { /// товар доступен case available /// товар удален case deleted /// товар недоступен case unavailable /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 0: self = .available case 1: self = .deleted case 2: self = .unavailable default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .available: return 0 case .deleted: return 1 case .unavailable: return 2 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.MarketItem.Availability(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// категория товара public struct Category: Codable { /// секция public struct Section: Codable { /// идентификатор секции public let id: Int? /// название секции public let name: String? } /// идентификатор категории public let id: Int? /// название категории public let name: String? /// секция public let section: Object.MarketItem.Category.Section? } /// информация об отметках «Мне нравится» public struct Likes: Codable { /// число отметок «Мне нравится» let count: Int? /// есть ли отметка «Мне нравится» от текущего пользователя let user_likes: Object.Boolean? } /// объект, описывающий цену public struct Price: Codable { /// объект, описывающий информацию о валюте public struct Currency: Codable { /// идентификатор валюты public let id: Int? /// буквенное обозначение валюты public let name: String? } /// цена товара в сотых долях единицы валюты public let amount: String? /// объект currency public let currency: Object.MarketItem.Price.Currency? /// строка с локализованной ценой и валютой public let text: String? } /// статус доступности товара public let availability: Object.MarketItem.Availability? /// возможность комментировать товар для текущего пользователя public let can_comment: Object.Boolean? /// возможность сделать репост товара для текущего пользователя public let can_repost: Object.Boolean? /// категория товара public let category: Object.MarketItem.Category? /// creation date in Unixtime public let date: Int? /// текст описания товара public let description: String? /// идентификатор товара public let id: Int? /// информация об отметках «Мне нравится» public let likes: Object.MarketItem.Likes? /// идентификатор владельца товара public let owner_id: Int? /// изображения товара public let photos: [Object.Photo]? /// цена public let price: Object.MarketItem.Price? /// URL of the item photo public let thumb_photo: String? /// название товара public let title: String? } } <file_sep>import Foundation public extension Object { /// объект, описывающий кнопку public struct Button: Codable { /// действие для кнопки public struct Action: Codable { /// тип действия public enum Typе: String, Codable { /// вступить в группу и открыть адрес из поля url case join_group_and_open_url /// открыть адрес из поля url case open_url } /// идентификатор группы public let group_id: Int? /// public let target: Object.Target? /// тип действия public let type: Object.Button.Action.Typе? /// URL для перехода public let url: String? } /// действие для кнопки public let action: Object.Button.Action? /// название кнопки public let title: String? } } <file_sep>import Foundation /// специальный ключ доступа для идентификации в API public typealias Token = String <file_sep>//import Foundation // //public extension Method.Utils { // /// Возвращает информацию о том, является ли внешняя ссылка заблокированной на сайте ВКонтакте // public struct CheckLink { // /// ответ // public typealias Response = Object.CheckedLink // /// внешняя ссылка, которую необходимо проверить // public let url: String // /// пользовательские данные // public let user: App.User // // public init(url: String, user: App.User) { // self.url = url // self.user = user // } // } //} // //extension Method.Utils.CheckLink: ApiType { // // public var method_name: String { // return "utils.checkLink" // } // // public var parameters: [String: String] { // var dictionary = App.parameters // dictionary["access_token"] = user.token // dictionary["url"] = url // return dictionary // } //} // //extension Method.Utils.CheckLink: StrategyType { // // public var api: AnyApi<Method.Utils.CheckLink.Response> { // return AnyApi(api: self) // } //} <file_sep>//import Foundation // //public extension Method.Utils { // /// Позволяет получить URL, сокращенный с помощью vk.cc. // public struct DeleteFromLastShortened { // /// ответ // public typealias Response = Object.Positive // /// содержательная часть (символы после "vk.cc") // public let key: String // /// пользовательские данные // public let user: App.User // // public init(key: String, user: App.User) { // self.key = key // self.user = user // } // } //} // //extension Method.Utils.DeleteFromLastShortened: ApiType { // // public var method_name: String { // return "utils.deleteFromLastShortened" // } // // public var parameters: [String: String] { // var dictionary = App.parameters // dictionary["access_token"] = user.token // dictionary["key"] = key // return dictionary // } //} // //extension Method.Utils.DeleteFromLastShortened: StrategyType { // // public var api: AnyApi<Method.Utils.DeleteFromLastShortened.Response> { // return AnyApi(api: self) // } //} // <file_sep>import Foundation extension UnkeyedDecodingContainer { mutating func decode<T>() throws -> T where T: Decodable { return try decode(T.self) } } <file_sep>import Foundation public extension Object { /// объект, описывающий контент приложения public struct App: Codable { /// идентификатор приложения public let id: Int? /// название приложения public let name: String? /// URL изображения для предпросмотра public let photo_130: String? /// URL полноразмерного изображения public let photo_604: String? } } <file_sep>import RxCocoa import RxSwift extension Observable { func delayCompletion(_ dueTime: RxTimeInterval, scheduler: SchedulerType) -> Observable { let observableElement = self .observeOn(scheduler) .share(replay: 1, scope: .whileConnected) let observableCompleted = Observable<Int> .timer(0, period: dueTime, scheduler: scheduler) .map({ $0 > 0 }) .share(replay: 1, scope: .whileConnected) return Observable<(element: E, completed: Bool)> .combineLatest(observableElement, observableCompleted){(element: $0, completed: $1)} .filter({ $0.completed }) .map({ $0.element }) .take(1) .share(replay: 1, scope: .whileConnected) } func flatMapLatest<T>(observableCancel: Observable<T>, observableFactory: @escaping (E) throws -> Observable<T>) -> Observable<T> { return self .flatMapLatest({ element -> Observable<T> in return Observable<Observable<T>> .of(observableCancel, try observableFactory(element)) .merge() .take(1) }) .share(replay: 1, scope: SubjectLifetimeScope.whileConnected) } func observableTracked(activityRelay: ActivityRelay?) -> Observable { return activityRelay?.trackActivity(self) ?? self } } <file_sep>import Foundation public extension Object { /// объект, описывающий стикер public struct Sticker: Codable { /// высота в px public let height: Int? /// идентификатор стикера public let id: Int? /// URL изображения с высотой 128 px public let photo_128: String? /// URL изображения с высотой 256 px public let photo_256: String? /// URL изображения с высотой 352 px public let photo_352: String? /// URL изображения с высотой 64 px public let photo_64: String? /// идентификатор набора public let product_id: Int? /// ширина в px public let width: Int? } } <file_sep># git tag 3.0.0 # git push origin 3.0.0 # pod lib lint VK.podspec --no-clean # pod spec lint VK.podspec --allow-warnings # pod trunk push VK.podspec # pod lib lint VK+Extended.podspec --no-clean # pod spec lint VK+Extended.podspec --allow-warnings # pod trunk push VK+Extended.podspec Pod::Spec.new do |s| s.name = 'VK' s.version = '3.0.0' s.summary = 'vk.com, api, swift' s.description = 'vk.com, api, swift, decodable, moya, rxswift' s.homepage = 'https://github.com/iwheelbuy/VK' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'iWheelBuy' => '<EMAIL>' } s.source = { :git => 'https://github.com/iwheelbuy/VK.git', :tag => s.version.to_s } s.ios.deployment_target = '10.0' s.pod_target_xcconfig = { 'SWIFT_VERSION' => '4.1' } s.default_subspec = 'Base' s.subspec 'Base' do |ss| ss.source_files = 'VK/Core/**/*.swift', 'VK/Extra/**/*.swift', 'VK/Method/**/*.swift', 'VK/Object/**/*.swift' ss.dependency 'Moya/RxSwift' ss.dependency 'RxCocoa' end end <file_sep>//import Foundation // //public extension Method.Utils { // /// Позволяет получить URL, сокращенный с помощью vk.cc. // public struct GetShortLink { // /// ответ // public typealias Response = Object.ShortenedLink // /// статистика ссылки приватная // public let `private`: Bool // /// сдвиг для получения определенного подмножества ссылок // public let url: String // /// пользовательские данные // public let user: App.User // // public init(`private`: Bool = false, url: String, user: App.User) { // self.`private` = `private` // self.url = url // self.user = user // } // } //} // //extension Method.Utils.GetShortLink: ApiType { // // public var method_name: String { // return "utils.getShortLink" // } // // public var parameters: [String: String] { // var dictionary = App.parameters // dictionary["access_token"] = user.token // dictionary["private"] = `private` ? "1" : "0" // dictionary["url"] = url // return dictionary // } //} // //extension Method.Utils.GetShortLink: StrategyType { // // public var api: AnyApi<Method.Utils.GetShortLink.Response> { // return AnyApi(api: self) // } //} <file_sep>import Foundation public extension Object { /// изображение обложки public struct Image: Codable { /// высота копии public let height: Int? /// URL копии public let url: String? /// ширина копии public let width: Int? } } <file_sep>import Foundation public extension Object { /// перечисление, обозначающиее положительный или отрицательный результат public enum Boolean: Int, Codable { /// отрицательный результат case negative = 0 /// положительный результат case positive = 1 } } <file_sep>import Foundation public extension Method.Utils { /// Возвращает текущее время на сервере ВКонтакте в unixtime. public struct GetServerTime: Strategy { /// ключ доступа public let token: Token public init(token: Token) { self.token = token } public var method: String { return "utils.getServerTime" } public var parameters: [String : Any] { var dictionary = [String : Any]() dictionary["access_token"] = token return dictionary } public var transform: (Object.Response<Int>) -> Int { return { $0.response } } } } <file_sep>import Foundation public extension Object { /// объект, описывающий заметку public struct Note: Codable { /// количество комментариев public let comments: Int? /// дата создания заметки в формате Unixtime public let date: Int? /// идентификатор заметки public let id: Int? /// идентификатор владельца заметки public let owner_id: Int? /// количество прочитанных комментариев public let read_comments: Int? /// текст заметки public let text: String? /// заголовок заметки public let title: String? /// URL страницы для отображения заметки public let view_url: String? } } <file_sep>import Moya import RxSwift public protocol Service: class { /// func activity() -> Observable<Bool> /// func request<C, S, V>(cancel: Observable<C>, delay: TimeInterval, lang: String, logs: Logs, queue: DispatchQueue, strategy: S, timeout: TimeInterval, track: Bool, v: String) -> Observable<Output<V>> where S: Strategy, S.Value == V } public func getService() -> Service { return _Service() } // MARK: - Target: Moya.TargetType private struct Target: Moya.TargetType { let baseURL: URL let headers: [String: String]? = nil let method: Moya.Method let path: String let sampleData: Data let task: Moya.Task init<S>(_ lang: String, _ strategy: S, _ v: String) throws where S: Strategy { switch URL(string: "https://api.vk.com/method/") { case .some(let baseURL): self.baseURL = baseURL default: assertionFailure() throw Fault.baseUrl } self.method = Moya.Method.get self.path = strategy.method self.sampleData = Data() var parameters = strategy.parameters parameters["lang"] = lang parameters["v"] = v self.task = Moya.Task.requestParameters(parameters: parameters, encoding: URLEncoding()) } } // MARK: - Provider<T>: MoyaProvider<T> private class Provider<T>: MoyaProvider<T>, Disposable where T: Moya.TargetType { init(logs: Bool, queue: DispatchQueue) { let plugins = logs ? [NetworkLoggerPlugin(verbose: true)] : [] super.init(callbackQueue: queue, plugins: plugins) } func dispose() { // } } // MARK: - Service private class _Service { lazy var activityRelay = ActivityRelay() func observableCancel<C, T>(_ observableCancel: Observable<C>, _ observableTimeout: Observable<Output<T>>) -> Observable<Output<T>> { return Observable .of(observableTimeout, observableCancel.map({ _ in Output<T>.fault(.cancel) })) .merge() .take(1) .share(replay: 1, scope: SubjectLifetimeScope.whileConnected) } func observableFactory<S, T>(_ lang: String, _ logs: Bool, _ queue: DispatchQueue, _ strategy: S, _ v: String) -> () throws -> Observable<Output<T>> where S: Strategy, S.Value == T { return { () -> Observable<Output<T>> in assert(Thread.isMainThread == false) let target = try Target(lang, strategy, v) return Observable .using({ Provider<Target>(logs: logs, queue: queue) }, observableFactory: { (provider) -> Observable<Output<T>> in assert(Thread.isMainThread == false) return provider.rx .request(target, callbackQueue: queue) .asObservable() .map({ Output.with(response: $0, strategy: strategy) }) .catchError({ (error) -> Observable<Output<T>> in assert(Thread.isMainThread == false) let fault = Fault(error: error) return Observable .just(Output.fault(fault), scheduler: ConcurrentDispatchQueueScheduler(queue: queue)) }) }) } } func observableTimeout<T>(_ timeout: TimeInterval, _ queue: DispatchQueue) -> Observable<Output<T>> { return Observable<Int> .timer(timeout, period: timeout, scheduler: ConcurrentDispatchQueueScheduler(queue: queue)) .take(1) .map({ _ in Output<T>.fault(Fault.timeout) }) .share(replay: 1, scope: SubjectLifetimeScope.whileConnected) } } // MARK: - _Service: NetworkService extension _Service: Service { public func activity() -> Observable<Bool> { return activityRelay .asObservable() } public func request<C, S, V>(cancel: Observable<C>, delay: TimeInterval, lang: String, logs: Logs, queue: DispatchQueue, strategy: S, timeout: TimeInterval, track: Bool, v: String) -> Observable<Output<V>> where S: Strategy, S.Value == V { let observableTimeout: Observable<Output<V>> = self.observableTimeout(timeout, queue) let observableCancel: Observable<Output<V>> = self.observableCancel(cancel, observableTimeout) let observableFactory: () throws -> Observable<Output<V>> = self.observableFactory(lang, logs.contains(.request), queue, strategy, v) let observableRequest: Observable<Output<V>> = Observable .just((), scheduler: ConcurrentDispatchQueueScheduler(queue: queue)) .flatMapLatest(observableCancel: observableCancel, observableFactory: observableFactory) let observableDelayedTracked: Observable<Output<V>> = { switch (delay > 0, track) { case (true, true): return observableRequest .delayCompletion(delay, scheduler: ConcurrentDispatchQueueScheduler(queue: queue)) .observableTracked(activityRelay: activityRelay) case (true, false): return observableRequest .delayCompletion(delay, scheduler: ConcurrentDispatchQueueScheduler(queue: queue)) case (false, true): return observableRequest .observableTracked(activityRelay: activityRelay) case (false, false): return observableRequest } }() return observableDelayedTracked .share(replay: 1, scope: SubjectLifetimeScope.whileConnected) } } <file_sep>//import Foundation // //public extension Method.Utils { // /// тип объекта (пользователь, сообщество, приложение) и его идентификатор по короткому имени screen_name // public struct ResolveScreenName { // /// ответ // public typealias Response = Object.ResolvedScreenName? // /// короткое имя пользователя, группы или приложения // public let screen_name: String // /// пользовательские данные // public let user: App.User? // // public init(screen_name: String, user: App.User? = nil) { // self.screen_name = screen_name // self.user = user // } // } //} // //extension Method.Utils.ResolveScreenName: ApiType { // // public var method_name: String { // return "utils.resolveScreenName" // } // // public var parameters: [String: String] { // var dictionary = App.parameters // dictionary["access_token"] = user?.token // dictionary["screen_name"] = screen_name // return dictionary // } //} // //extension Method.Utils.ResolveScreenName: StrategyType { // // public var api: AnyApi<Method.Utils.ResolveScreenName.Response> { // return AnyApi(api: self) // } //} <file_sep>import Foundation public extension Object { /// запись на стене пользователя или сообщества public struct Wall: Codable { /// информация о комментариях к записи public struct Comments: Codable { /// количество комментариев let count: Int? /// информация о том, может ли текущий пользователь комментировать запись let can_post: Object.Boolean? /// информация о том, могут ли сообщества комментировать запись let groups_can_post: Bool? } /// информация о местоположении public struct Geo: Codable { /// тип места public enum Typе: Codable { /// место case place /// точка case point /// неизвестное значение case exception(String) init(rawValue: String) { switch rawValue { case "place": self = .place case "point": self = .point default: self = .exception(rawValue) } } public var rawValue: String { switch self { case .place: return "place" case .point: return "point" case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: String = try container.decode() self = Object.Wall.Geo.Typе(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// public enum Place { /// описание места public struct Place: Codable { /// адрес public let address: String? /// количество чекинов public let checkins: Int? /// идентификатор города public let city: Int? /// идентификатор страны public let country: Int? /// дата создания (если назначено) public let created: Int? /// идентификатор сообщества public let group_id: Int? /// URL миниатюры главной фотографии сообщества public let group_photo: String? /// URL изображения-иконки public let icon: String? /// идентификатор места (если назначено) public let id: Int? /// географическая широта public let latitude: Double? /// географическая долгота public let longitude: Double? /// название места (если назначено) public let title: String? /// тип чекина public let type: Int? /// время последнего чекина в Unixtime public let updated: Int? } /// описание точки public struct Point: Codable { /// название города public let city: String? /// название страны public let country: String? /// дата создания (если назначено) public let created: Int? /// URL изображения-иконки public let icon: String? /// идентификатор места (если назначено) public let id: Int? /// географическая широта public let latitude: Double? /// географическая долгота public let longitude: Double? /// название места (если назначено) public let title: String? } /// описание места case place(Object.Wall.Geo.Place.Place?) /// описание точки case point(Object.Wall.Geo.Place.Point?) } private enum Key: String, CodingKey { case coordinates case place case showmap case type } /// координаты места public let coordinates: String? /// описание места public let place: Object.Wall.Geo.Place /// showmap public let showmap: Object.Positive? /// тип места public let type: Object.Wall.Geo.Typе public init(from decoder: Decoder) throws { let container = try Key.container(decoder: decoder) coordinates = try container.decode(key: Key.coordinates) if container.contains(Key.showmap) { showmap = try container.decode(key: Key.showmap) } else { showmap = nil } type = try container.decode(key: Key.type) switch type { case .place: if container.contains(Key.place) { let place: Object.Wall.Geo.Place.Place? = try container.decode(key: Key.place) self.place = .place(place) } else { self.place = .place(nil) } case .point: if container.contains(Key.place) { let point: Object.Wall.Geo.Place.Point? = try container.decode(key: Key.place) self.place = .point(point) } else { self.place = .point(nil) } case .exception: let place: Object.Wall.Geo.Place.Place = try container.decode(key: Key.place) self.place = .place(place) } } public func encode(to encoder: Encoder) throws { var container = Key.container(encoder: encoder) try container.encode(coordinates, forKey: Key.coordinates) switch self.showmap { case .some(let showmap): try container.encode(showmap, forKey: Key.showmap) default: break } try container.encode(type, forKey: Key.type) switch self.place { case .place(let place): try container.encode(place, forKey: Key.place) case .point(let point): if case .some(let point) = point { try container.encode(point, forKey: Key.place) } } } } /// информация о лайках к записи public struct Likes: Codable { /// число пользователей, которым понравилась запись let count: Int? /// информация о том, может ли текущий пользователь поставить отметку «Мне нравится» let can_like: Object.Boolean? /// информация о том, может ли текущий пользователь сделать репост записи let can_publish: Object.Boolean? /// наличие отметки «Мне нравится» от текущего пользователя let user_likes: Object.Boolean? } /// тип записи public enum PostType: String, Codable { case copy case note case photo case post case postpone case reply case suggest case video } /// способ размещения записи на стене public struct PostSource: Codable { /// тип действия (только для type = vk или widget) public enum Data: String, Codable { /// донат case donation /// изменение статуса под именем пользователя (для type = vk) case profile_activity /// изменение профильной фотографии пользователя (для type = vk) case profile_photo /// виджет комментариев (для type = widget) case comments /// виджет «Мне нравится» (для type = widget) case like /// виджет опросов (для type = widget) case poll /// добавление в wishlist case wishlist_add /// покупка из wishlist case wishlist_buy } /// link public struct Link: Codable { /// description public let description: String? /// title public let title: String? /// url public let url: String? } /// название платформы, если оно доступно public enum Platform: String, Codable { /// admin_app case admin_app /// android case android /// chronicle case chronicle /// instagram case instagram /// ipad case ipad /// iphone case iphone /// windows case windows /// windows phone case wphone } /// тип источника public enum Typе: String, Codable { /// запись создана приложением через API case api /// мобильная версия m.vk.com case mvk /// запись создана посредством импорта RSS-ленты со стороннего сайта case rss /// запись создана посредством отправки SMS-сообщения на специальный номер case sms /// запись создана через основной интерфейс сайта case vk /// запись создана через виджет на стороннем сайте case widget } /// тип действия (только для type = vk или widget) let data: Object.Wall.PostSource.Data? /// link let link: Object.Wall.PostSource.Link? /// название платформы, если оно доступно let platform: Object.Wall.PostSource.Platform? /// тип источника let type: Object.Wall.PostSource.Typе /// URL ресурса, с которого была опубликована запись let url: String? } /// информация о репостах записи («Рассказать друзьям») public struct Reposts: Codable { /// число пользователей, скопировавших запись let count: Int? /// наличие репоста от текущего пользователя let user_reposted: Object.Boolean? } /// информация о просмотрах записи public struct Views: Codable { /// число просмотров записи let count: Int? } /// медиавложения записи (фотографии, ссылки и т.п.) public let attachments: [Object.Attachment]? /// информация о том, может ли текущий пользователь удалить запись public let can_delete: Object.Boolean? /// информация о том, может ли текущий пользователь редактировать запись public let can_edit: Object.Boolean? /// информация о том, может ли текущий пользователь закрепить запись public let can_pin: Object.Boolean? /// информация о комментариях к записи public let comments: Object.Wall.Comments? /// массив, содержащий историю репостов для записи. Возвращается только в том случае, если запись является репостом. Каждый из объектов массива, в свою очередь, является объектом-записью стандартного формата public let copy_history: [Object.Wall]? /// идентификатор администратора, который опубликовал запись public let created_by: Int? /// время публикации записи в формате unixtime public let date: TimeInterval /// final_post public let final_post: Object.Positive? /// запись была создана с опцией «Только для друзей» public let friends_only: Object.Positive? /// идентификатор автора записи (от чьего имени опубликована запись) public let from_id: Int /// информация о местоположении public let geo: Object.Wall.Geo? /// идентификатор записи public let id: Int? /// информация о том, что запись закреплена public let is_pinned: Object.Positive? /// информация о лайках к записи public let likes: Object.Wall.Likes? /// информация о том, содержит ли запись отметку "реклама" public let marked_as_ads: Object.Boolean? /// информация о способе размещения записи public let post_source: Object.Wall.PostSource /// тип записи public let post_type: Object.Wall.PostType? /// идентификатор владельца записи, в ответ на которую была оставлена текущая public let reply_owner_id: Int? /// идентификатор записи, в ответ на которую была оставлена текущая public let reply_post_id: Int? /// информация о репостах записи («Рассказать друзьям») public let reposts: Object.Wall.Reposts? /// идентификатор автора, если запись была опубликована от имени сообщества и подписана пользователем public let signer_id: Int? /// идентификатор владельца стены, на которой размещена запись public let owner_id: Int /// текст записи public let text: String /// информация о просмотрах записи public let views: Object.Wall.Views? } } <file_sep>import Foundation public extension Object { /// объект, описывающий вики-страницу public struct Page: Codable { /// информация о том, кто может просматривать/редактировать вики-страницу public enum Who: Codable { /// только руководители сообщества case managers /// только участники сообщества case members /// просматривать страницу могут все case all /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 0: self = .managers case 1: self = .members case 2: self = .all default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .managers: return 0 case .members: return 1 case .all: return 2 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Page.Who(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// дата создания вики-страницы в формате Unixtime public let created: Int? /// идентификатор создателя вики-страницы public let creator_id: Int? /// текущий пользователь может редактировать текст вики-страницы public let current_user_can_edit: Object.Boolean? /// текущий пользователь может изменять права доступа на вики-страницу public let current_user_can_edit_access: Object.Boolean? /// дата последнего изменения вики-страницы в формате Unixtime public let edited: Int? /// идентификатор пользователя, который редактировал вики-страницу последним public let editor_id: Int? /// идентификатор сообщества public let group_id: Int? /// текст страницы в html-формате, если был запрошен public let html: String? /// идентификатор вики-страницы public let id: Int? /// заголовок родительской страницы для навигации, если есть public let parent: String? /// заголовок второй родительской страницы для навигации, если есть public let parent2: String? /// текст страницы в вики-формате, если был запрошен public let source: String? /// название вики-страницы public let title: String? /// адрес страницы для отображения вики-страницы public let view_url: String? /// количество просмотров вики-страницы public let views: Int? /// указывает, кто может редактировать вики-страницу public let who_can_edit: Object.Page.Who? /// информация о том, кто может просматривать вики-страницу public let who_can_view: Object.Page.Who? } } <file_sep>import Foundation /// методы для работы с данными ВКонтакте public struct Method { /// служебные методы public struct Utils {} /// методы для работы с записями на стене. public struct Wall {} } <file_sep>import Foundation extension KeyedDecodingContainer { func decode<T>(key: K) throws -> T where T: Decodable { return try decode(T.self, forKey: key) } } <file_sep>import Foundation public extension Object { /// информацию о том, является ли внешняя ссылка заблокированной на сайте ВКонтакте public struct CheckedLink: Codable { /// статус ссылки public enum Status: Codable { /// ссылка не заблокирована case not_banned /// ссылка заблокирована case banned /// ссылка проверяется, необходимо выполнить повторный запрос через несколько секунд case processing /// неизвестное значение case exception(String) init(rawValue: String) { switch rawValue { case "not_banned": self = .not_banned case "banned": self = .banned case "processing": self = .processing default: self = .exception(rawValue) } } public var rawValue: String { switch self { case .not_banned: return "not_banned" case .banned: return "banned" case .processing: return "processing" case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: String = try container.decode() self = Object.CheckedLink.Status(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// исходная ссылка (url) либо полная ссылка (если в url была передана сокращенная ссылка) public let link: String? /// статус ссылки public let status: Object.CheckedLink.Status? } } <file_sep>import Foundation public extension Object { /// объект отвечающий короткому имени screen_name public struct ResolvedScreenName: Codable { /// тип объекта public enum Typе: Codable { /// пользователь case user /// сообщество case group /// приложение case application /// неизвестное значение case exception(String) init(rawValue: String) { switch rawValue { case "user": self = .user case "group": self = .group case "application": self = .application default: self = .exception(rawValue) } } public var rawValue: String { switch self { case .user: return "user" case .group: return "group" case .application: return "application" case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: String = try container.decode() self = Object.ResolvedScreenName.Typе(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// идентификатор объекта public let object_id: Int /// тип объекта public let type: Object.ResolvedScreenName.Typе } } <file_sep>import Foundation extension JSONDecoder { func decode<T>(data: Data) throws -> T where T: Decodable { return try decode(T.self, from: data) } } <file_sep>//import Foundation // //public extension Method.Wall { // /// Возвращает список записей со стены пользователя или сообщества // public struct Get { // /// ответ // public struct Response: Codable { // /// число результатов // public let count: Int // /// массив сообществ // public let groups: [Object.Group]? // /// массив объектов записей на стене // public let items: [Object.Wall] // /// массив пользователей // public let profiles: [Object.Profile]? // } // /// определяет, какие типы записей на стене необходимо получить // public enum Filter: String { // /// все записи на стене (owner + others) // case all // /// записи не от владельца стены // case others // /// записи владельца стены // case owner // /// отложенные записи // case postponed // /// предложенные записи на стене сообщества // case suggests // } // /// идентификатор пользователя или сообщества / короткий адрес пользователя или сообщества // public enum Owner { // /// короткий адрес пользователя или сообщества // case domain(String) // /// идентификатор пользователя или сообщества, со стены которого необходимо получить записи (по умолчанию — текущий пользователь) // case id(Int?) // } // /// // public enum Sizes { // /// включая массив с копиями изображения в разных размерах // case array // /// исключая массив с копиями изображения в разных размерах // case simple // var value: String? { // switch self { // case .array: // return "1" // default: // return nil // } // } // } // // public let filter: Method.Wall.Get.Filter // public let count: UInt // public let extended: Bool // public let offset: UInt // public let owner: Method.Wall.Get.Owner // public let photoSizes: Method.Wall.Get.Sizes // public let user: App.User // // public init(count: UInt, extended: Bool = false, filter: Method.Wall.Get.Filter = .all, offset: UInt, owner: Method.Wall.Get.Owner = .id(nil), photoSizes: Method.Wall.Get.Sizes = .simple, user: App.User) { // self.count = count // self.extended = extended // self.filter = filter // self.offset = offset // self.owner = owner // self.photoSizes = photoSizes // self.user = user // } // } //} // //extension Method.Wall.Get: ApiType { // // public var method_name: String { // return "wall.get" // } // // public var parameters: [String: String] { // var dictionary = App.parameters // if let value = photoSizes.value { // dictionary["photo_sizes"] = value // } // dictionary["access_token"] = user.token // dictionary["count"] = "\(count)" // dictionary["extended"] = extended ? "1" : "0" // dictionary["filter"] = filter.rawValue // dictionary["offset"] = "\(offset)" // if extended { // let fieldsUser = "about, activities, bdate, blacklisted, blacklisted_by_me, books, can_post, can_see_all_posts, can_see_audio, can_send_friend_request, can_write_private_message, career, city, common_count, connections, contacts, counters, country, crop_photo, domain, education, exports, first_name_abl, first_name_acc, first_name_dat, first_name_gen, first_name_ins, first_name_nom, followers_count, friend_status, games, has_mobile, has_photo, home_town, interests, is_favorite, is_friend, is_hidden_from_feed, last_name_abl, last_name_acc, last_name_dat, last_name_gen, last_name_ins, last_name_nom, last_seen, lists, maiden_name, military, movies, music, nickname, occupation, online, personal, photo_50, photo_100, photo_200_orig, photo_200, photo_400_orig, photo_id, photo_max, photo_max_orig, quotes, relatives, relation, schools, screen_name, sex, site, status, timezone, trending, tv, universities, verified, wall_comments" // let fieldsGroup = "id, name, screen_name, is_closed, deactivated, is_admin, admin_level, is_member, invited_by, type, photo_50, photo_100, photo_200, activity, age_limits, ban_info, can_create_topic, can_message, can_post, can_see_all_posts, can_upload_doc, can_upload_video, city, contacts, counters, country, cover, description, fixed_post, has_photo, is_favorite, is_hidden_from_feed, is_messages_blocked, links, main_album_id, main_section, market, member_status, members_count, place, public_date_label, site, start_date, finish_date, status, trending, verified, wiki_page" // dictionary["fields"] = [fieldsUser, fieldsGroup].joined(separator: ", ") // } // switch owner { // case .domain(let domain): // dictionary["domain"] = domain // case .id(let id): // if case .some(let owner_id) = id { // dictionary["owner_id"] = "\(owner_id)" // } // } // return dictionary // } //} // //extension Method.Wall.Get: StrategyType { // // public var api: AnyApi<Method.Wall.Get.Response> { // return AnyApi(api: self) // } //} <file_sep>import Foundation public extension Object { /// информация о городе public struct City: Codable { /// идентификатор города public let id: Int? /// название города public let title: String? } } <file_sep>import Foundation public extension Object { /// объект, описывающий аудиозапись public struct Audio: Codable { /// идентификатор альбома, в котором находится аудиозапись public let album_id: Int? /// исполнитель public let artist: String? /// запрещенный контент public let content_restricted: Object.Positive? /// дата добавления public let date: Int? /// длительность аудиозаписи в секундах public let duration: Int? /// идентификатор жанра из списка аудио жанров public let genre_id: Int? /// идентификатор аудиозаписи public let id: Int? /// аудио в высоком качестве public let is_hq: Bool? /// идентификатор текста аудиозаписи public let lyrics_id: Int? /// включена опция «Не выводить при поиске» public let no_search: Object.Positive? /// идентификатор владельца аудиозаписи public let owner_id: Int? /// название композиции public let title: String? /// ссылка на mp3 public let url: String? } } <file_sep>import Moya /// private struct Temp: Decodable { let error: Error } /// Результат запроса public enum Output<V> where V: Decodable { /// Ошибка case fault(Fault) /// Значение case value(V) static func with<S>(response: Moya.Response, strategy: S) -> Output<V> where S: Strategy, S.Value == V { assert(Thread.isMainThread == false) switch response.statusCode { case 200 ... 399: let data = response.data do { let raw: S.Raw = try JSONDecoder().decode(S.Raw.self, from: data) let value = strategy.transform(raw) return Output.value(value) } catch let error as Swift.DecodingError { guard case .keyNotFound(let key, _) = error, key.stringValue == "response" else { let fault = Fault(data: data, error: error) return Output<V>.fault(fault) } do { let error = try JSONDecoder().decode(Temp.self, from: data).error let fault = Fault.vkontakte(error) return Output<V>.fault(fault) } catch let error as Swift.DecodingError { guard case .keyNotFound(let key, _) = error, key.stringValue == "error" else { let fault = Fault(data: data, error: error) return Output<V>.fault(fault) } let fault = Fault.response return Output<V>.fault(fault) } catch let error { let fault = Fault(data: data, error: error) return Output<V>.fault(fault) } } catch let error { let fault = Fault(data: data, error: error) return Output<V>.fault(fault) } default: assertionFailure() let fault = Fault.unknown(code: response.statusCode, data: response.data) return Output<V>.fault(fault) } } public var fault: Fault? { switch self { case .fault(let value): return value default: return nil } } public var value: V? { switch self { case .value(let value): return value default: return nil } } } <file_sep>import Foundation /// объекты public struct Object { public struct Items<T>: Decodable where T: Decodable { public let count: Int public let items: [T] } public struct Response<T>: Decodable where T: Decodable { let response: T } } <file_sep>import Foundation public extension Object { /// pretty_cards public struct PrettyCards: Codable { /// public struct Card: Codable { /// public let button: Object.Button? /// public let card_id: String? /// public let images: [Object.Image]? /// public let link_url: String? /// public let link_url_target: String? /// public let price: String? /// public let title: String? } /// public let cards: [Object.PrettyCards.Card]? } } <file_sep>import Foundation public extension Object { /// объект, описывающий видеозапись public struct Profile: Codable { /// информация о карьере пользователя public struct Career: Codable { /// идентификатор сообщества (если доступно) public let group_id: Int? /// название компании (если доступно) public let company: String? /// идентификатор страны public let country_id: Int? /// идентификатор города (если доступно) public let city_id: Int? /// название города (если доступно) public let city_name: String? /// год начала работы public let from: Int? /// год окончания работы public let until: Int? /// должность public let position: String? } /// количество различных объектов у пользователя public struct Counters: Codable { /// количество фотоальбомов public let albums: Int? /// количество аудиозаписей public let audios: Int? /// количество подписчиков public let followers: Int? /// количество друзей public let friends: Int? /// количество сообществ public let groups: Int? /// количество общих друзей public let mutual_friends: Int? /// количество заметок public let notes: Int? /// количество друзей онлайн public let online_friends: Int? /// количество объектов в блоке «Интересные страницы» public let pages: Int? /// количество фотографий public let photos: Int? /// количество подписок (только пользователи) public let subsсriptions: Int? /// количество фотографий с пользователем public let user_photos: Int? /// количество видеозаписей с пользователем public let user_videos: Int? /// количество видеозаписей public let videos: Int? } /// данные о точках, по которым вырезаны профильная и миниатюрная фотографии пользователя public struct CropPhoto: Codable { /// вырезанная фотография пользователя public struct Rect: Codable { /// координата X левого верхнего угла в процентах public let x: Double? /// координата Y левого верхнего угла в процентах public let y: Double? /// координата X правого нижнего угла в процентах public let x2: Double? /// координата Y правого нижнего угла в процентах public let y2: Double? } /// вырезанная фотография пользователя public let crop: Object.Profile.CropPhoto.Rect? /// объект фотографии пользователя, из которой вырезается главное фото профиля public let photo: Object.Photo? /// миниатюрная квадратная фотография, вырезанная из фотографии crop public let rect: Object.Profile.CropPhoto.Rect? } /// статус дружбы с пользователем public enum FriendStatus: Codable { /// не является другом case notFriend /// отправлена заявка/подписка пользователю case requestSent /// имеется входящая заявка/подписка от пользователя case incomingRequest /// является другом case isFriend /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 0: self = .notFriend case 1: self = .requestSent case 2: self = .incomingRequest case 3: self = .isFriend default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .notFriend: return 0 case .requestSent: return 1 case .incomingRequest: return 2 case .isFriend: return 3 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Profile.FriendStatus(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// время последнего посещения public struct LastSeen: Codable { /// тип платформы public enum Platform: Codable { /// мобильная версия case mobileVersion /// приложение для iPhone case iPhone /// приложение для iPad case iPad /// приложение для Android case android /// приложение для Windows Phone case windowsPhone /// приложение для Windows 10 case windows10 /// полная версия сайта case fullSiteVersion /// VK Mobile case vkMobile /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 1: self = .mobileVersion case 2: self = .iPhone case 3: self = .iPad case 4: self = .android case 5: self = .windowsPhone case 6: self = .windows10 case 7: self = .fullSiteVersion case 8: self = .vkMobile default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .mobileVersion: return 1 case .iPhone: return 2 case .iPad: return 3 case .android: return 4 case .windowsPhone: return 5 case .windows10: return 6 case .fullSiteVersion: return 7 case .vkMobile: return 8 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Profile.LastSeen.Platform(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// тип платформы public let platform: Object.Profile.LastSeen.Platform? /// время последнего посещения в формате Unixtime public let time: Int? } /// информация о военной службе пользователя public struct Military: Codable { /// идентификатор страны, в которой находится часть public let country_id: Int? /// год начала службы public let from: Int? /// номер части public let unit: String? /// идентификатор части в базе данных public let unit_id: Int? /// год окончания службы public let until: Int? } /// информация о текущем роде занятия пользователя public struct Occupation: Codable { /// тип public enum Typе: String, Codable { /// среднее образование case school /// высшее образование case university /// работа case work } /// идентификатор школы, вуза, сообщества компании (в которой пользователь работает) public let id: Int? /// название школы, вуза или места работы public let name: String? /// тип public let type: Object.Profile.Occupation.Typе? } /// информация о полях из раздела «Жизненная позиция» public struct Personal: Codable { /// отношение к алкоголю public enum Alcohol: Codable { /// резко негативное case very_negative /// негативное case negative /// компромиссное case neutral /// нейтральное case compromisable /// положительное case positive /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 1: self = .very_negative case 2: self = .negative case 3: self = .neutral case 4: self = .compromisable case 5: self = .positive default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .very_negative: return 1 case .negative: return 2 case .neutral: return 3 case .compromisable: return 4 case .positive: return 5 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Profile.Personal.Alcohol(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// главное в жизни public enum LifeMain: Codable { /// семья и дети case family_children /// карьера и деньги case career_money /// развлечения и отдых case entertainment_leisure /// наука и исследования case science_research /// совершенствование мира case improving_the_world /// саморазвитие case personal_development /// красота и искусство case beauty_art /// слава и влияние case fame_influence /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 1: self = .family_children case 2: self = .career_money case 3: self = .entertainment_leisure case 4: self = .science_research case 5: self = .improving_the_world case 6: self = .personal_development case 7: self = .beauty_art case 8: self = .fame_influence default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .family_children: return 1 case .career_money: return 2 case .entertainment_leisure: return 3 case .science_research: return 4 case .improving_the_world: return 5 case .personal_development: return 6 case .beauty_art: return 7 case .fame_influence: return 8 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Profile.Personal.LifeMain(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// главное в людях public enum PeopleMain: Codable { /// ум и креативность case intellect_creativity /// доброта и честность case kindness_honesty /// красота и здоровье case health_beauty /// власть и богатство case wealth_power /// смелость и упорство case courage_persistance /// юмор и жизнелюбие case humor_love_for_life /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 1: self = .intellect_creativity case 2: self = .kindness_honesty case 3: self = .health_beauty case 4: self = .wealth_power case 5: self = .courage_persistance case 6: self = .humor_love_for_life default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .intellect_creativity: return 1 case .kindness_honesty: return 2 case .health_beauty: return 3 case .wealth_power: return 4 case .courage_persistance: return 5 case .humor_love_for_life: return 6 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Profile.Personal.PeopleMain(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// политические предпочтения public enum Political: Codable { /// коммунистические case communist /// социалистические case socialist /// умеренные case moderate /// либеральные case liberal /// консервативные case conservative /// монархические case monarchist /// ультраконсервативные case ultraconservative /// индифферентные case apathetic /// либертарианские case libertarian /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 1: self = .communist case 2: self = .socialist case 3: self = .moderate case 4: self = .liberal case 5: self = .conservative case 6: self = .monarchist case 7: self = .ultraconservative case 8: self = .apathetic case 9: self = .libertarian default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .communist: return 1 case .socialist: return 2 case .moderate: return 3 case .liberal: return 4 case .conservative: return 5 case .monarchist: return 6 case .ultraconservative: return 7 case .apathetic: return 8 case .libertarian: return 9 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Profile.Personal.Political(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// отношение к курению public enum Smoking: Codable { /// резко негативное case very_negative /// негативное case negative /// компромиссное case neutral /// нейтральное case compromisable /// положительное case positive /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 1: self = .very_negative case 2: self = .negative case 3: self = .neutral case 4: self = .compromisable case 5: self = .positive default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .very_negative: return 1 case .negative: return 2 case .neutral: return 3 case .compromisable: return 4 case .positive: return 5 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Profile.Personal.Smoking(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// отношение к алкоголю public let alcohol: Object.Profile.Personal.Alcohol? /// источники вдохновения public let inspired_by: String? /// языки public let langs: [String]? /// главное в жизни public let life_main: Object.Profile.Personal.LifeMain? /// мировоззрение public let religion: String? /// главное в людях public let people_main: Object.Profile.Personal.PeopleMain? /// политические предпочтения public let political: Object.Profile.Personal.Political? /// отношение к курению public let smoking: Object.Profile.Personal.Smoking? } /// семейное положение пользователя public enum Relation: Codable { /// не женат/не замужем case single /// есть друг/есть подруга case in_relationship /// помолвлен/помолвлена case engaged /// женат/замужем case married /// всё сложно case complicated /// в активном поиске case actively_searching /// влюблён/влюблена case in_love /// в гражданском браке case civil_union /// не указано case not_specified /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 1: self = .single case 2: self = .in_relationship case 3: self = .engaged case 4: self = .married case 5: self = .complicated case 6: self = .actively_searching case 7: self = .in_love case 8: self = .civil_union case 0: self = .not_specified default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .single: return 1 case .in_relationship: return 2 case .engaged: return 3 case .married: return 4 case .complicated: return 5 case .actively_searching: return 6 case .in_love: return 7 case .civil_union: return 8 case .not_specified: return 0 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Profile.Relation(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// пользователь в семейном положении public struct RelationPartner: Codable { /// фамилия public let first_name: String? /// идентификатор пользователя public let id: Int? /// имя public let last_name: String? } /// родственник текущего пользователя public struct Relative: Codable { /// тип родственной связи public enum Typе: String, Codable { /// сын/дочь case child /// внук/внучка case grandchild /// дедушка/бабушка case grandparent /// отец/мать case parent /// брат/сестра case sibling } /// идентификатор пользователя public let id: Int? /// имя родственника public let name: String? /// тип родственной связи public let type: Object.Profile.Relative.Typе? } /// список школ, в которых учился пользователь public struct School: Codable { /// идентификатор типа public enum Typе: Codable { /// школа case school /// гимназия case gymnasium /// лицей case lyceum /// школа-интернат case boarding_school /// школа вечерняя case evening_school /// школа музыкальная case music_school /// школа спортивная case sport_school /// школа художественная case artistic_school /// колледж case college /// профессиональный лицей case professional_lyceum /// техникум case technical_college /// ПТУ case vocational /// училище case specialized_school /// школа искусств case art_school /// детский сад case kindergarten /// проф. училище case professional_institute /// автошкола case driving_school /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 0: self = .school case 1: self = .gymnasium case 2: self = .lyceum case 3: self = .boarding_school case 4: self = .evening_school case 5: self = .music_school case 6: self = .sport_school case 7: self = .artistic_school case 8: self = .college case 9: self = .professional_lyceum case 10: self = .technical_college case 11: self = .vocational case 12: self = .specialized_school case 13: self = .art_school case 14: self = .kindergarten case 15: self = .professional_institute case 16: self = .driving_school default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .school: return 0 case .gymnasium: return 1 case .lyceum: return 2 case .boarding_school: return 3 case .evening_school: return 4 case .music_school: return 5 case .sport_school: return 6 case .artistic_school: return 7 case .college: return 8 case .professional_lyceum: return 9 case .technical_college: return 10 case .vocational: return 11 case .specialized_school: return 12 case .art_school: return 13 case .kindergarten: return 14 case .professional_institute: return 15 case .driving_school: return 16 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Profile.School.Typе(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// идентификатор школы public let id: String? /// идентификатор города, в котором расположена школа public let city: Int? /// буква класса public let `class`: String? /// идентификатор страны, в которой расположена школа public let country: Int? /// наименование школы public let name: String? /// специализация public let speciality: String? /// идентификатор типа public let type: Object.Profile.School.Typе? /// название типа (локализованное?) public let type_str: String? /// год начала обучения public let year_from: Int? /// год выпуска public let year_graduated: Int? /// год окончания обучения public let year_to: Int? } /// пол пользователя public enum Sex: Codable { /// женский case female /// мужской case male /// пол не указан case not_specified /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 1: self = .female case 2: self = .male case 0: self = .not_specified default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .female: return 1 case .male: return 2 case .not_specified: return 0 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Profile.Sex(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// вуз, в котором учился пользователь public struct University: Codable { /// идентификатор кафедры public let chair: Int? /// наименование кафедры public let chair_name: String? /// идентификатор города, в котором расположен университет public let city: Int? /// идентификатор страны, в которой расположен университет public let country: Int? /// форма обучения public let education_form: String? /// статус (например, «Выпускник (специалист)») public let education_status: String? /// идентификатор факультета public let faculty: Int? /// наименование факультета public let faculty_name: String? /// год окончания обучения public let graduation: Int? /// идентификатор университета public let id: Int? /// наименование университета public let name: String? } /// содержимое поля «О себе» из профиля public let about: String? /// содержимое поля «Деятельность» из профиля public let activities: String? /// содержимое поля «Деятельность» из профиля public let activity: String? /// дата рождения. Возвращается в формате D.M.YYYY или D.M (если год рождения скрыт). Если дата рождения скрыта целиком, поле отсутствует в ответе public let bdate: String? /// информация о том, находится ли текущий пользователь в черном списке public let blacklisted: Object.Boolean? /// информация о том, находится ли пользователь в черном списке у текущего пользователя public let blacklisted_by_me: Object.Boolean? /// содержимое поля «Любимые книги» из профиля пользователя public let books: String? /// информация о том, может ли текущий пользователь оставлять записи на стене public let can_post: Object.Boolean? /// информация о том, может ли текущий пользователь видеть чужие записи на стене public let can_see_all_posts: Object.Boolean? /// информация о том, может ли текущий пользователь видеть аудиозаписи public let can_see_audio: Object.Boolean? /// информация о том, будет ли отправлено уведомление пользователю о заявке в друзья от текущего пользователя public let can_send_friend_request: Object.Boolean? /// информация о том, может ли текующий пользователь загружать документы public let can_upload_doc: Object.Boolean? /// информация о том, может ли текущий пользователь отправить личное сообщение public let can_write_private_message: Object.Boolean? /// информация о карьере пользователя public let career: [Object.Profile.Career]? /// информация о городе, указанном на странице пользователя в разделе «Контакты» public let city: Object.City? /// количество общих друзей с текущим пользователем public let common_count: Int? /// количество различных объектов у пользователя public let counters: Object.Profile.Counters? /// информация о стране, указанной на странице пользователя в разделе «Контакты» public let country: Object.Country? /// данные о точках, по которым вырезаны профильная и миниатюрная фотографии пользователя public let crop_photo: Object.Profile.CropPhoto? /// если страница пользователя удалена или заблокирована, то содержит значение deleted или banned public let deactivated: String? /// короткий адрес страницы. Возвращается строка, содержащая короткий адрес страницы (например, andrew). Если он не назначен, возвращается "id"+user_id, например, id35828305 public let domain: String? /// форма обучения public let education_form: String? /// статус (например, «Выпускник (специалист)») public let education_status: String? /// facebook public let facebook: String? /// facebook_name public let facebook_name: String? /// идентификатор факультета public let faculty: Int? /// название факультета public let faculty_name: String? /// год окончания public let graduation: Int? /// имя пользователя public let first_name: String /// имя пользователя в предложном падеже public let first_name_abl: String? /// имя пользователя в винительном падеже public let first_name_acc: String? /// имя пользователя в дательном падеже public let first_name_dat: String? /// имя пользователя в родительном падеже public let first_name_gen: String? /// имя пользователя в творительном падеже public let first_name_ins: String? /// имя пользователя в именительном падеже public let first_name_nom: String? /// количество подписчиков пользователя public let followers_count: Int? /// статус дружбы с пользователем public let friend_status: Object.Profile.FriendStatus? /// содержимое поля «Любимые игры» из профиля public let games: String? /// информация о том, известен ли номер мобильного телефона пользователя public let has_mobile: Object.Boolean? /// пользователь установил фотографию для профиля public let has_photo: Object.Boolean? /// пользователь установил настройку «Кому в интернете видна моя страница» — «Только пользователям ВКонтакте» public let hidden: String? /// дополнительный номер телефона пользователя public let home_phone: String? /// название родного города public let home_town: String? /// идентификатор пользователя public let id: Int /// содержимое поля «Интересы» из профиля public let interests: String? /// instagram public let instagram: String? /// информация о том, есть ли пользователь в закладках у текущего пользователя public let is_favorite: Object.Boolean? /// информация о том, является ли пользователь другом текущего пользователя public let is_friend: Object.Boolean? /// информация о том, скрыт ли пользователь из ленты новостей текущего пользователя public let is_hidden_from_feed: Object.Boolean? /// фамилия пользователя public let last_name: String /// фамилия пользователя в предложном падеже public let last_name_abl: String? /// фамилия пользователя в винительном падеже public let last_name_acc: String? /// фамилия пользователя в дательном падеже public let last_name_dat: String? /// фамилия пользователя в родительном падеже public let last_name_gen: String? /// фамилия пользователя в творительном падеже public let last_name_ins: String? /// фамилия пользователя в именительном падеже public let last_name_nom: String? /// время последнего посещения public let last_seen: Object.Profile.LastSeen? /// разделенные запятой идентификаторы списков друзей, в которых состоит пользователь public let lists: String? /// livejournal public let livejournal: String? /// девичья фамилия public let maiden_name: String? /// информация о военной службе пользователя public let military: [Object.Profile.Military]? /// номер мобильного телефона пользователя public let mobile_phone: String? /// содержимое поля «Любимые фильмы» из профиля пользователя public let movies: String? /// содержимое поля «Любимая музыка» из профиля пользователя public let music: String? /// никнейм (отчество) пользователя public let nickname: String? /// информация о текущем роде занятия пользователя public let occupation: Object.Profile.Occupation? /// информация о том, находится ли пользователь сейчас на сайте public let online: Object.Boolean? /// идентификатор используемого приложения public let online_app: String? /// пользователь использует мобильное приложение либо мобильную версию сайта public let online_mobile: Object.Boolean? /// информация о полях из раздела «Жизненная позиция» public let personal: Object.Profile.Personal? /// url квадратной фотографии пользователя, имеющей ширину 100 пикселей public let photo_100: String? /// url квадратной фотографии пользователя, имеющей ширину 200 пикселей public let photo_200: String? /// url фотографии пользователя, имеющей ширину 200 пикселей public let photo_200_orig: String? /// url фотографии пользователя, имеющей ширину 400 пикселей public let photo_400_orig: String? /// url квадратной фотографии пользователя, имеющей ширину 50 пикселей public let photo_50: String? /// строковый идентификатор главной фотографии профиля пользователя в формате {user_id}_{photo_id}, например, 6492_192164258 public let photo_id: String? /// url квадратной фотографии пользователя с максимальной шириной public let photo_max: String? /// url фотографии пользователя максимального размера. Может быть возвращена фотография, имеющая ширину как 400, так и 200 пикселей public let photo_max_orig: String? /// любимые цитаты public let quotes: String? /// семейное положение пользователя public let relation: Object.Profile.Relation? /// пользователь в семейном положении public let relation_partner: Object.Profile.RelationPartner? /// список родственников текущего пользователя public let relatives: [Object.Profile.Relative]? /// список школ, в которых учился пользователь public let schools: [Object.Profile.School]? /// короткое имя страницы пользователя public let screen_name: String? /// пол пользователя public let sex: Object.Profile.Sex? /// адрес сайта, указанный в профиле сайт пользователя public let site: String? /// skype public let skype: String? /// строка, содержащая текст статуса, расположенного в профиле под именем пользовател public let status: String? /// информация о транслируемой композиции public let status_audio: Object.Audio? /// временная зона пользователя public let timezone: Int? /// информация о том, есть ли на странице пользователя «огонёк» public let trending: Object.Boolean? /// любимые телешоу public let tv: String? /// twitter public let twitter: String? /// список вузов, в которых учился пользователь public let universities: [Object.Profile.University]? /// идентификатор университета public let university: Int? /// название университета public let university_name: String? /// страница пользователя верифицирована public let verified: Object.Boolean? /// информация о том, включены ли комментарии на стене public let wall_comments: Object.Boolean? } } <file_sep>import Foundation public extension Object { /// прикрепленная ссылка public struct Link: Codable { /// public struct Rating: Codable { /// public let reviews_count: Int? /// public let stars: Double? } /// информация о кнопке для перехода public let button: Object.Button? /// действие для кнопки public let button_action: String? /// название для кнопки public let button_text: String? /// подпись ссылки (если имеется) public let caption: String? /// описание ссылки public let description: String? /// изображение превью, объект фотографии public let photo: Object.Photo? /// идентификатор вики-страницы с контентом для предпросмотра содержимого страницы public let preview_page: String? /// URL страницы с контентом для предпросмотра содержимого страницы public let preview_url: String? /// информация о продукте public let product: Object.Product? /// public let rating: Object.Link.Rating? /// target public let target: String? /// заголовок ссылки public let title: String? /// URL ссылки public let url: String? } } <file_sep>import Foundation import Moya public enum Fault: Swift.Error { /// Base url was incorrect case baseUrl /// Cancelled by the app case cancel /// Decoding error case decoding(error: Swift.DecodingError?) /// Internal Moya error case moya(MoyaError) /// The Internet connection appears to be offline case offline /// Some other error case other(error: Swift.Error) /// Response of unknown type case response /// Timeout exceeded case timeout /// Unknown response case unknown(code: Int, data: Data) /// Ошибка API ВКонтакте case vkontakte(Error) init(data: Data? = nil, error: Swift.Error) { assert(Thread.isMainThread == false) if let data = data { let text = String(data: data, encoding: String.Encoding.utf8) ?? "" #if DEBUG print("\n\(error)\n" + text) #endif assertionFailure("\(error)") } if let error = error as? Fault { self = error return } if let error = error as? MoyaError { self = .moya(error) return } if let error = error as? Swift.DecodingError { self = .decoding(error: error) return } switch (error as NSError).code { case -1001: self = .timeout case -1009: self = .offline default: self = .other(error: error) } } } /// Объект, описывающий ошибку ВКонтакте public struct Error: Decodable, Swift.Error { /// Коды ошибок public enum Code: Int, Decodable, Swift.Error { /// Произошла неизвестная ошибка case error_code_1 = 1 /// Приложение выключено. Необходимо включить приложение в настройках или использовать тестовый режим case error_code_2 = 2 /// Передан неизвестный метод case error_code_3 = 3 /// Неверная подпись case error_code_4 = 4 /// Авторизация пользователя не удалась case error_code_5 = 5 /// Слишком много запросов в секунду case error_code_6 = 6 /// Нет прав для выполнения этого действия. Проверьте, получены ли нужные права доступа при авторизации case error_code_7 = 7 /// Неверный запрос case error_code_8 = 8 /// Слишком много однотипных действий case error_code_9 = 9 /// Произошла внутренняя ошибка сервера case error_code_10 = 10 /// В тестовом режиме приложение должно быть выключено или пользователь должен быть залогинен case error_code_11 = 11 /// Требуется ввод кода с картинки (Captcha) case error_code_14 = 14 /// Доступ запрещён case error_code_15 = 15 /// Требуется выполнение запросов по протоколу HTTPS case error_code_16 = 16 /// Требуется валидация пользователя case error_code_17 = 17 /// Страница удалена или заблокирована case error_code_18 = 18 /// Данное действие запрещено для не Standalone приложений. Если ошибка возникает несмотря на то, что Ваше приложение имеет тип Standalone, убедитесь, что при авторизации Вы используете redirect_uri=https://oauth.vk.com/blank.html case error_code_20 = 20 /// Данное действие разрешено только для Standalone и Open API приложений case error_code_21 = 21 /// Метод был выключен case error_code_23 = 23 /// Требуется подтверждение со стороны пользователя case error_code_24 = 24 /// Ключ доступа сообщества недействителен case error_code_27 = 27 /// Ключ доступа приложения недействителен case error_code_28 = 28 /// Один из необходимых параметров был не передан или неверен case error_code_100 = 100 /// Неверный API ID приложения case error_code_101 = 101 /// Неверный идентификатор пользователя case error_code_113 = 113 /// Неверный timestamp case error_code_150 = 150 /// Доступ к альбому запрещён case error_code_200 = 200 /// Доступ к аудио запрещён. Убедитесь, что Вы используете верные идентификаторы, и доступ к запрашиваемому контенту для текущего пользователя есть в полной версии сайта case error_code_201 = 201 /// Доступ к группе запрещён. Убедитесь, что текущий пользователь является участником или руководителем сообщества case error_code_203 = 203 /// Альбом переполнен case error_code_300 = 300 /// Действие запрещено. Вы должны включить переводы голосов в настройках приложения case error_code_500 = 500 /// Нет прав на выполнение данных операций с рекламным кабинетом case error_code_600 = 600 /// Произошла ошибка при работе с рекламным кабинетом case error_code_603 = 603 } /// enum CodingKeys: String, CodingKey { case code = "error_code" case message = "error_msg" case parameters = "request_params" } /// public let code: Error.Code? /// public let message: String? /// public let parameters: [[String:String]]? } <file_sep>import Foundation public extension Object { /// фотография, загруженная напрямую public struct PostedPhoto: Codable { /// идентификатор фотографии public let id: Int? /// идентификатор владельца фотографии public let owner_id: Int? /// URL изображения для предпросмотра public let photo_130: String? /// URL полноразмерного изображения public let photo_604: String? } } <file_sep>import Foundation public extension Object { /// объект, описывающий документ public struct Doc: Codable { /// информация для предварительного просмотра документа public struct Preview: Codable { /// данные об аудиосообщении public struct AudioMsg: Codable { /// длительность аудиосообщения в секундах public let duration: Int? /// URL .mp3-файла public let link_mp3: String? /// URL .ogg-файла public let link_ogg: String? /// массив значений (integer) для визуального отображения звука public let waveform: [Int]? } /// данные о граффити public struct Graffiti: Codable { /// высота изображения в px public let height: Int? /// URL документа с граффити public let src: String? /// ширина изображения в px public let width: Int? } /// видео для предпросмотра public struct Video: Codable { /// размер файла public let file_size: Int? /// ширина public let height: Int? /// url видеозаписи public let src: String? /// высота public let width: Int? } /// изображения для предпросмотра public struct Photo: Codable { /// массив копий изображения в разных размерах public let sizes: [Object.Photo.Size]? } /// данные об аудиосообщении public let audio_msg: Object.Doc.Preview.AudioMsg? /// данные о граффити public let graffiti: Object.Doc.Preview.Graffiti? /// изображения для предпросмотра public let photo: Object.Doc.Preview.Photo? /// видеозапись для предпросмотра public let video: Object.Doc.Preview.Video? } /// тип документа public enum Typе: Codable { /// текстовые документы case text_documents /// архивы case archives /// gif case gif /// изображения case images /// аудио case audio /// видео case video /// электронные книги case e_books /// неизвестно case unknown /// неизвестное значение case exception(Int) init(rawValue: Int) { switch rawValue { case 1: self = .text_documents case 2: self = .archives case 3: self = .gif case 4: self = .images case 5: self = .audio case 6: self = .video case 7: self = .e_books case 8: self = .unknown default: self = .exception(rawValue) } } public var rawValue: Int { switch self { case .text_documents: return 1 case .archives: return 2 case .gif: return 3 case .images: return 4 case .audio: return 5 case .video: return 6 case .e_books: return 7 case .unknown: return 8 case .exception(let value): return value } } public init(from decoder: Decoder) throws { var container = try decoder.singleValueContainer() let rawValue: Int = try container.decode() self = Object.Doc.Typе(rawValue: rawValue) } public func encode(to encoder: Encoder) throws { var container = encoder.singleValueContainer() try container.encode(rawValue) } } /// ключ доступа к объекту public let access_key: String? /// дата добавления в формате Unixtime public let date: Int? /// расширение документа public let ext: String? /// идентификатор документа public let id: Int? /// идентификатор пользователя, загрузившего документ public let owner_id: Int? /// информация для предварительного просмотра документа public let preview: Object.Doc.Preview? /// размер документа в байтах public let size: Int? /// название документа public let title: String? /// тип документа public let type: Object.Doc.Typе? /// адрес документа, по которому его можно загрузить public let url: String? } } <file_sep>import Foundation public extension Object { /// информация о стране public struct Country: Codable { /// идентификатор страны public let id: Int? /// название страны public let title: String? } } <file_sep>import Foundation extension CodingKey { static func container(decoder: Decoder) throws -> KeyedDecodingContainer<Self> { return try decoder.container(keyedBy: Self.self) } static func container(encoder: Encoder) -> KeyedEncodingContainer<Self> { return encoder.container(keyedBy: Self.self) } } <file_sep>import Foundation public extension Object { /// перечисление, обозначающиее положительный результат public enum Positive: Int, Codable { /// положительный результат case positive = 1 } } <file_sep>import Foundation public extension Object { public struct Poll: Codable { /// вариант ответа public struct Answer: Codable { /// идентификатор ответа public let id: Int? /// рейтинг ответа public let rate: Double? /// текст ответа public let text: String? /// число проголосовавших за этот ответ public let votes: Int? } /// опрос анонимный public let anonymous: Object.Boolean? /// идентификатор варианта ответа, выбранного текущим пользователем public let answer_id: Int? /// массив объектов, которые содержат информацию о вариантах ответа public let answers: [Object.Poll.Answer]? /// дата создания в формате Unixtime public let created: Int? /// идентификатор опроса для получения информации о нем public let id: Int? /// идентификатор владельца опроса public let owner_id: Int? /// текст вопроса public let question: String? /// количество голосов public let votes: Int? } } <file_sep>//import Foundation // //public extension Method.Utils { // /// Возвращает статистику переходов по сокращенной ссылке. // public struct GetLinkStats { // /// интервал // public enum Interval: String, Codable { // /// час // case hour // /// день // case day // /// неделя // case week // /// месяц // case month // /// все время с момента создания ссылки // case forever // } // /// ответ // public struct Response: Codable { // /// входной параметр key // public let key: String // /// массив объектов, данные о статистике // public let stats: [Object.ShortenedLinkStats] // } // /// ключ доступа к приватной статистике // public let access_key: String? // /// возвращать расширенную статистику (пол/возраст/страна/город) // public let extended: Bool // /// единица времени для подсчета статистики // public let interval: Method.Utils.GetLinkStats.Interval // /// длительность периода для получения статистики в выбранных единицах (из параметра interval) // public let intervals_count: UInt // /// содержательная часть (символы после "vk.cc") // public let key: String // /// пользовательские данные // public let user: App.User // // public init(access_key: String? = nil, extended: Bool = false, interval: Method.Utils.GetLinkStats.Interval = .day, intervals_count: UInt = 1, key: String, user: App.User) { // self.access_key = access_key // self.extended = extended // self.interval = interval // self.intervals_count = intervals_count // self.key = key // self.user = user // } // } //} // //extension Method.Utils.GetLinkStats: ApiType { // // public var method_name: String { // return "utils.getLinkStats" // } // // public var parameters: [String: String] { // var dictionary = App.parameters // dictionary["access_token"] = user.token // dictionary["access_key"] = access_key // dictionary["interval"] = interval.rawValue // dictionary["intervals_count"] = "\(intervals_count)" // dictionary["extended"] = extended ? "1" : "0" // dictionary["key"] = key // return dictionary // } //} // //extension Method.Utils.GetLinkStats: StrategyType { // // public var api: AnyApi<Method.Utils.GetLinkStats.Response> { // return AnyApi(api: self) // } //}
88d562c3ea8f062dd81cd3b0d33f683ac619d8f8
[ "Swift", "Ruby" ]
55
Swift
iwheelbuy/VK
686ae394289d0790183be981dd4f38d72b179163
1dd67881eaf792507b4490df9c9c2c4293fa067a
refs/heads/master
<repo_name>jhodges10/dashdonate<file_sep>/client/rebuild.sh for i in "$(npm prefix -g)/lib/node_modules/"*; do sudo npm build -g "$i" done <file_sep>/client/src/App.js import React, { Component } from 'react'; import { Grid } from 'react-bootstrap'; import AppNav from './AppNav'; import grailsLogo from './images/grails-cupsonly-logo-white.svg'; import reactLogo from './images/logo.svg'; import charityLogo from './images/charity.png'; import { SERVER_URL, CLIENT_VERSION, REACT_VERSION } from './config'; import 'whatwg-fetch'; import Circle from 'react-circle'; import { Flex, Box } from 'reflexbox'; import QRCode from 'qrcode.react'; class App extends Component { constructor() { super(); this.state = { serverInfo: {}, clientInfo: { version: CLIENT_VERSION, react: REACT_VERSION } } } componentDidMount() { fetch(SERVER_URL + '/application') .then(r => r.json()) .then(json => this.setState({serverInfo: json})) .catch(error => console.error('Error connecting to server: ' + error)); fetch(SERVER_URL + '/api/proposaldonationinfo') .then(r => r.json()) .then(json => this.setState({pdinfos: json})) .catch(error => console.error('Error retrieving proposal donation informations: ' + error)); } render() { const serverInfo = this.state.serverInfo; const clientInfo = this.state.clientInfo; const pdinfos = this.state.pdinfos; const numCols = 5; return ( <div> <div className="grails-logo-container"> <img className="grails-logo" src={charityLogo} alt="Grails" /> <span className="plus-logo">+</span> <img className="hero-logo" src={reactLogo} alt="Dash" /> </div> <div id="content"> <section className="row colset-2-its"> <h1 style={{textAlign: 'center'}}>Welcome to Dash Donations</h1> <br/> <p> Below you can find a list of proposals that did not get funded the last voting cycle. For security reasons in the normal case each proposal has the original dash address requested in the proposal or an escrowed address so you can double check that by clicking each proposal link below. The site is automatically updated every 10 minutes. One proposal, dash venezuela 19 allied communities,have several other addresses being used and we are working on a solution to reflect those sums beeing received also, so do not worry if you sent to one of the other addresses, because that will be shown also later on. </p> <p> LEGAL DISCLAIMER: This site only provides already existing information that exists in the dash network and or in each proposal object and or in the forums such as receiving address. We do not suggest or propose that donations should be made. This site is for information purposes only. It is up to each individual to provide legal justification for each transaction made in blockchain networks, and its up to each receiver and sender to follow the rules of their respective country. Consider the rules of your country and the receiving country when sending a transaction if there are limits to each transaction. The creator(s) of this site does not take or accept any liability or cannot be held responsible for any usage of blockchain technology that any user might take due to the information provided on this website. <p><b>Implicit Agreement</b>. By using our Website, you implicitly signify your agreement to all parts of the above disclaimer. </p> </p> <p id="propInfos"> <Flex wrap align='center' mt={3} style={{ textTransform: 'uppercase' }} > <Box w={1/numCols} p={1}>Proposal</Box> <Box w={1/numCols} p={1}>Donated</Box> <Box w={1/numCols} p={1}>Minimum target</Box> <Box w={1/numCols} p={1}>Dash Address</Box> <Box w={1/numCols} p={1}>QR</Box> </Flex> {pdinfos ? pdinfos.map(pdinf => { var dashAddress = pdinf.dashAddress; if(!dashAddress) dashAddress="not provided"; return <Flex wrap align='center'> <Box p={1} w={1/numCols}><a href={pdinf.proposalUrl}>{pdinf.proposalName}</a> requests {pdinf.dashAmountRequested} dash and a minimum of {pdinf.donationSofttarget} Dash</Box> <Box p={1} w={1/numCols}><Circle progress={Number.parseFloat(pdinf.percentageDonatedOfRequested).toFixed(2)}></Circle></Box> <Box p={1} w={1/numCols}><Circle progress={Number.parseFloat(pdinf.percentageDonatedOfSoft).toFixed(2)}></Circle></Box> <Box p={1} w={1/numCols}>{dashAddress}</Box> <Box p={1} w={1/numCols}><QRCode value={dashAddress} size={64}></QRCode></Box> </Flex> }) : null } </p> </section> </div> </div> ); } } export default App;
70574599e05b737949bf3ae27c00f95d2cbcc462
[ "JavaScript", "Shell" ]
2
Shell
jhodges10/dashdonate
15722a4b5cbfb287b3cd9d3ea14ae5ea2c116a78
9d40142127b894c16d15dfddac7655dfc023690c
refs/heads/master
<repo_name>hoog1511/Project-Domotica<file_sep>/beveiliging.ino int kalibratietijd = 30; long unsigned int LowIn ; // tijd wanneer sensor outputs laag impuls long unsigned int pauze = 30000; // na deze tijd mag de arduino aannemen dat er geen beweging meer is boolean lockLow = true; boolean takeLowTime; #define irLedPin 5 #define irSensorPin 4 #define echoPin 3 #define triggerPin 2 #define ledPin 1 int maximumRange = 100; int minimumRange = 0; long duration, distance; int tijden[20]; int y = 0; int tijdvannu = 0; bool melding = false; int aantal = 0; volatile unsigned long seconden = 0; unsigned long seconden_oud = 0; int seco; int minu; int uren; unsigned int ethPort = 3300; byte mac [] = { 0x40, 0x6c, 0x8f, 0x36, 0x84, 0x8a }; //IPAddress ip(192, 168, 1, 102); ISR(TIMER1_OVF_vect) { TCNT1 = 0xBDC; seconden = seconden + 1; }; #include <SPI.h> #include <Ethernet.h> EthernetServer server(ethPort); void setup() { Serial.begin(9600); TIMSK1 = 0x01; // enabled global and timer overflow interrupt; TCCR1A = 0x00; // normal operation page 148 (mode0); TCNT1 = 0xBDC; // set initial value to remove time error (16bit counter register) TCCR1B = 0x04; // start timer/ set clock zetTijd(); if (Ethernet.begin(mac) == 0) { Serial.print("Geen address te vinden!"); while (true) {} } Serial.println("IP address "); Serial.print(Ethernet.localIP()); //Serial.print("192.168.1.102") Ethernet.begin(mac, Ethernet.localIP()); server.begin(); pinMode(triggerPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(ledPin, OUTPUT); pinMode(irSensorPin, INPUT); pinMode(irLedPin, OUTPUT); digitalWrite(irSensorPin, LOW); //kalibratie tijd Serial.println("---"); Serial.println("Kalibratie van sensor is bezig"); for (int i = 0; i < kalibratietijd; i++) { Serial.print("."); delay(200); } Serial.println(""); Serial.println("Klaar "); Serial.println("Sensor actief!"); delay(50); } void loop() { EthernetClient ethernetClient = server.available(); if (seconden_oud != seconden) { seconden_oud = seconden; seco++; if (seco == 60) { seco = 0; minu++; if (minu == 60) { minu = 0; uren++; if (uren == 24) { uren = 0; } } } } while (ethernetClient.available()) { char inByte = ethernetClient.read(); executeCommand(inByte); inByte = NULL; } if (digitalRead(irSensorPin) == HIGH) { digitalWrite(irLedPin, HIGH); //als de sensor hoog is moet de pin ook hoog zijn if (lockLow) { while (ethernetClient.available()) { char inByte = ethernetClient.read(); executeCommand(inByte); inByte = NULL; } lockLow = false; Serial.println("---"); Serial.println("motion gedetecteerd bij "); if (uren < 10) { Serial.print("0"); } Serial.print(uren); Serial.print(":"); if (minu < 10) { Serial.print("0"); } Serial.print(minu); digitalWrite(triggerPin, LOW); delayMicroseconds(2); digitalWrite(triggerPin, HIGH); delayMicroseconds(10); digitalWrite(triggerPin, LOW); duration = pulseIn(echoPin, HIGH); distance = (duration / 2) / 29.2; if (distance >= maximumRange || distance <= minimumRange) { //Serial.println("-1"); digitalWrite(ledPin, HIGH); } else { Serial.println(distance); Serial.print(" cm "); digitalWrite(ledPin, LOW); } delay(50); } } melding = true; if (melding == true && distance >= maximumRange || distance <= minimumRange) { if (y < 20) { { if (((uren * 100) + minu) != tijden[y - 1]) { tijden[y] = ((uren * 100) + minu); Serial.println(tijden[y]); y++; melding = false; } } } else { if (((uren * 100) + minu) != tijden[y - 1] && ((uren * 100) + minu) != tijden[19]) { y = 0; tijden[y] = ((uren * 100) + minu); Serial.println(tijden[y]); melding = false; } } } takeLowTime = true; if (digitalRead(irSensorPin) == LOW) { digitalWrite(irLedPin, LOW); //als de sensor laag is moet de pin ook laag zijn if (takeLowTime) { LowIn = millis(); //tijd van hoog naar laag takeLowTime = false; } //als de sensor langer laag blijft dan de pauze is er nieuwe motion if (!lockLow && millis() - LowIn > pauze) { lockLow = true; Serial.println("motion gestopt bij "); if (uren < 10) { Serial.print("0"); } Serial.print(uren); Serial.print(":"); if (minu < 10) { Serial.print("0"); } Serial.print(minu); delay(50); } digitalWrite(triggerPin, LOW); } } void zetTijd() { String tijd = __TIME__; uren = (tijd.charAt(0) - 48) * 10 + tijd.charAt(1) - 48; minu = (tijd.charAt(3) - 48) * 10 + tijd.charAt(4) - 48; seco = (tijd.charAt(6) - 48) * 10 + tijd.charAt(7) - 48; } void executeCommand(char cmd) { switch (cmd) { case 'q': //update log for (int i = 0; i <= y; i++) { if (tijden[i] != 0 && tijden[i] != tijden[i - 1]) { String tijd = String(tijden[i]); if (tijden[i] < 1000) { tijd = "0" + tijd; } for (int x = 0; x < 4; x++) { char c = tijd.charAt(x); server.write(c); Serial.println("{" + String(c) + "} + "); } Serial.println("{" + tijd + "} "); } } /*case 'q': //melding van motion if (tijdvannu > 19) { tijdvannu = 0; } String tijd = String(tijden[tijdvannu]); if (tijden[tijdvannu] < 1000) { tijd = "0" + tijd; } for (int a = 0; a < 4; a++) { char n = tijd.charAt(a); server.write(n); Serial.println("{" + String(n) + "} + "); } Serial.println("{" + tijd + "} "); tijdvannu++; }*/ } <file_sep>/DomoticaServer_groep20.ino #include <NewRemoteReceiver.h> #include <NewRemoteTransmitter.h> #include <RemoteTransmitter.h> // Domotica server with KAKU-controller // // By <NAME>, Student Computer Science NHL. // V0.1, 19/1/2017. Works with Xamarin // kaku, Gamma, APA3, codes based on Arduino -> Voorbeelden -> NewRemoteSwitch -> ShowReceivedCode // 1 Addr 21177114 unit 0 on/off, period: 270us replace with your own code // Supported KaKu devices -> find, download en install corresponding libraries #define unitCodeApa3 20144854 // replace with your own code // Include files. #include <time.h> #include <SPI.h> // Ethernet shield uses SPI-interface #include <Ethernet.h> // Ethernet library (use Ethernet2.h for new ethernet shield v2) #include <NewRemoteTransmitter.h> // Remote Control, Gamma, APA3 // Set Ethernet Shield MAC address (check yours) byte mac[] = { 0x40, 0x6c, 0x3f, 0x36, 0x64, 0x6a }; //Random mac adres int ethPort = 3300; // Take a free port (check your router) #define RFPin 3 // output, pin to control the RF-sender (and Click-On Click-Off-device) #define lowPin 5 // output, always LOW #define highPin 6 // output, always HIGH #define switchPin 7 // input, connected to some kind of inputswitch #define analogPin 0 // sensor value EthernetServer server(ethPort); // EthernetServer instance (listening on port <ethPort>). NewRemoteTransmitter apa3Transmitter(unitCodeApa3, RFPin, 270, 3); // APA3 (Gamma) remote, use pin <RFPin> //Is for the socket's int socket = 0; // output, defines the socket 0 or 1 bool pinState = false; // Variable to store actual pin state bool pinChange = false; // Variable to store actual pin change bool pinState1 = false; // Variable to store actual pin state bool pinChange1 = false; // Variable to store actual pin change // distance sensor int triggerPin = 4; int echoPin = 5; bool disstate = false; long Distance = 0; long duration = 0; //Is for the timer char Time[4]; int Clock = 0; char Time1[4]; int Clock1 = 0; volatile unsigned long seconds = 0; unsigned long seconds_old = 0; int Sec; int Min; int Hours; ISR(TIMER1_OVF_vect) { TCNT1 = 0xBDC; seconds = seconds + 1; } // for the Photoresistor const int pResistor = A0; // Photoresistor at Arduino analog pin A0 const int ledPin = 9; // Led pin at Arduino pin 9 int pRvalue = 0; // Store value from photoresistor (0-1023) bool onoff = false; bool onoff1 = false; void setup() { Serial.begin(9600); Serial.println("Domotica project, Arduino Domotica Server\n"); //Init I/O-pins pinMode(switchPin, INPUT); // hardware switch, for changing pin state pinMode(lowPin, OUTPUT); pinMode(highPin, OUTPUT); pinMode(RFPin, OUTPUT); pinMode(ledPin, OUTPUT); // Set lepPin - 9 pin as an output pinMode(pResistor, INPUT); // Set pResistor - A0 pin as an input pinMode(triggerPin, OUTPUT); pinMode(echoPin, INPUT); //Default states digitalWrite(switchPin, HIGH); // Activate pullup resistors (needed for input pin) digitalWrite(lowPin, LOW); digitalWrite(highPin, HIGH); digitalWrite(RFPin, LOW); // for the internal timer TIMSK1 = 0x01; // enabled global and timer overflow interrupt; TCCR1A = 0x00; // normal operation page 148 (mode0); TCNT1 = 0xBDC; // set initial value to remove time error (16bit counter register) TCCR1B = 0x04; // start timer/ set clock settime(); //Try to get an IP address from the DHCP server. if (Ethernet.begin(mac) == 0) { Serial.println("Could not obtain IP-address from DHCP -> do nothing"); while (true) { // no point in carrying on, so do nothing forevermore; check your router } } Serial.print("Input switch on pin "); Serial.println(switchPin); Serial.println("Ethernetboard connected (pins 10, 11, 12, 13 and SPI)"); Serial.println("Connect to DHCP source in local network"); //Start the ethernet server. server.begin(); // Print IP-address Serial.print("Listening address: "); Serial.print(Ethernet.localIP()); // for hardware debug int IPnr = getIPComputerNumber(Ethernet.localIP()); // Get computernumber in local network 192.168.1.3 -> 3) Serial.print(" ["); Serial.print(IPnr); Serial.print("] "); Serial.print(" [Testcase: telnet "); Serial.print(Ethernet.localIP()); Serial.print(" "); Serial.print(ethPort); Serial.println("]"); } void loop() { pRvalue = analogRead(pResistor); // update pRsensor value Photoresistor(pRvalue); checks(); // Internal Timer if (seconds_old != seconds) { seconds_old = seconds; Sec++; if (Sec == 60) { Sec = 0; Min++; if (Min == 60) { Min = 0; Hours++; if (Hours == 24) { Hours = 0; } } } Serial.print(Hours); Serial.print(':'); Serial.println(Min); Serial.println(pRvalue); // Listen for incomming connection (app) EthernetClient ethernetClient = server.available(); if (!ethernetClient) { return; // wait for connection } Serial.println("Application connected"); // Do what needs to be done while the socket is connected. while (ethernetClient.connected()) { checks(); if (disstate == true) { distance(); Serial.println(Distance); if (Distance < 300) { executeCommand('u'); } } // Execute when byte is received. while (ethernetClient.available()) { char inByte = ethernetClient.read(); // Get byte from the client executeCommand(inByte); // Wait for command to execute inByte = NULL; // Reset the read byte. } } Serial.println("Application disonnected"); } } // Choose and switch your Kaku device, state is true/false (HIGH/LOW) void switchDefault(bool state) { if (socket == 0) { Serial.println("code send 0"); } if (socket == 1) { Serial.println("code send 1"); } apa3Transmitter.sendUnit(socket, state); // APA3 Kaku (Gamma) delay(50); } // Implementation of (simple) protocol between app and Arduino // Request (from app) is single char ('a', 'u', 't' etc.) // Response (to app) is 6 chars (not all commands demand a response) void executeCommand(char cmd) { char buf[6] = {'\0', '\0', '\0', '\0', '\0', '\0'}; // Command protocol Serial.print("["); Serial.print(cmd); Serial.println("] -> "); switch (cmd) { /*case 'a': // Report sensor value to the app intToCharBuf(sensorValue, buf, 4); // convert to charbuffer server.write(buf, 4); // response is always 4 chars (\n included) break;*/ case 'u': // Toggle state of socket1; If state is already ON then turn it OFF socket = 1; if (pinState1) { pinState1 = false; Serial.println("Set pin state to \"OFF\""); } else { pinState1 = true; Serial.println("Set pin state to \"ON\""); } pinChange1 = true; break; case 't': // Toggle state; If state is already ON then turn it OFF socket = 0; if (pinState) { pinState = false; Serial.println("Set pin state to \"OFF\""); } else { pinState = true; Serial.println("Set pin state to \"ON\""); } pinChange = true; break; case 'd': // distance sensor if (disstate = false) { disstate = true; } else { disstate = false; } break; } } // checks if there is any changes in void checks() { checkEvent(switchPin, pinState); // update pin state checkEvent(switchPin, pinState1); // update pin1 state // Activate pin based op pinState if (pinChange) { if (pinState) { switchDefault(true); } else { switchDefault(false); } pinChange = false; } if (pinChange1) { if (pinState1) { switchDefault(true); } else { switchDefault(false); } pinChange1 = false; } } //checks for light value void Photoresistor (int value) { if (onoff == false && value > 681) { digitalWrite(ledPin, LOW); //Turn led off if (pinState == true) { executeCommand('t'); onoff = true; } } if (onoff1 == false && value > 681) { digitalWrite(ledPin, LOW); //Turn led off if (pinState1 == true) { executeCommand('u'); onoff1 = true; } } if (onoff == true && value < 680) { digitalWrite(ledPin, HIGH); //Turn led on if (pinState == false) { executeCommand('t'); onoff = false; } } if (onoff1 == true && value < 680) { digitalWrite(ledPin, HIGH); //Turn led on if (pinState1 == false) { executeCommand('u'); onoff1 = false; } } } void distance() { digitalWrite(triggerPin, LOW); delayMicroseconds(2); digitalWrite(triggerPin, HIGH); delayMicroseconds(10); digitalWrite(triggerPin, LOW); duration = pulseIn(echoPin, HIGH); Distance = duration / 58.2; Serial.println(Distance); Serial.print(" cm "); } // Convert int <val> char buffer with length <len> void intToCharBuf(int val, char buf[], int len) { String s; s = String(val); // convert tot string if (s.length() == 1) s = "0" + s; // prefix redundant "0" if (s.length() == 2) s = "0" + s; s = s + "\n"; // add newline s.toCharArray(buf, len); // convert string to char-buffer } // Check switch level and determine if an event has happend // event: low -> high or high -> low void checkEvent(int p, bool &state) { static bool swLevel = false; // Variable to store the switch level (Low or High) static bool prevswLevel = false; // Variable to store the previous switch level swLevel = digitalRead(p); if (swLevel) if (prevswLevel) delay(1); else { prevswLevel = true; // Low -> High transition state = true; pinChange = true; pinChange1 = true; } else // swLevel == Low if (!prevswLevel) delay(1); else { prevswLevel = false; // High -> Low transition state = false; pinChange = true; pinChange1 = true; } } // Convert IPAddress tot String (e.g. "192.168.1.105") String IPAddressToString(IPAddress address) { return String(address[0]) + "." + String(address[1]) + "." + String(address[2]) + "." + String(address[3]); } // Returns B-class network-id: 192.168.1.3 -> 1) int getIPClassB(IPAddress address) { return address[2]; } // Returns computernumber in local network: 192.168.1.3 -> 3) int getIPComputerNumber(IPAddress address) { return address[3]; } // Returns computernumber in local network: 192.168.1.105 -> 5) int getIPComputerNumberOffset(IPAddress address, int offset) { return getIPComputerNumber(address) - offset; } void settime() { String Time = __TIME__; Hours = (Time.charAt(0) - 48) * 10 + Time.charAt(1) - 48; Min = (Time.charAt(3) - 48) * 10 + Time.charAt(4) - 48; Sec = (Time.charAt(6) - 48) * 10 + Time.charAt(7) - 48; } <file_sep>/servo map/master/README.md # Slagboom master Library die basis vormt voor de interactie tussen de app en de Arduino. pls no copy<file_sep>/servo map/slave/slave.ino #include <VirtualWire.h> #include <ServoTimer2.h> const int KEY = 81; const int RF_RECEIVE_PIN = 7; const int ULTRA_ECHO_PIN = 6; const int ULTRA_TRIGGER_PIN = 11; const int ULTRA_MIN_DISTANCE = 2; // inch const int ULTRA_MAX_DISTANCE = 6; // inch const int SERVO_PIN = 5; const int SERVO_MIN_POS = 544; const int SERVO_MAX_POS = 1472; const int SERVO_STEP_SIZE = 32; const int MAX_SWEEPS = 4; bool start_signal = false; int distance = 0; int old_distance = distance; bool alternate = true; int sweep_count = 0; ServoTimer2 myservo; void setup() { Serial.begin(9600); Serial.setTimeout(100); // RF communication vw_set_rx_pin(RF_RECEIVE_PIN); vw_set_ptt_inverted(true); vw_setup(2000); vw_rx_start(); pinMode(ULTRA_ECHO_PIN, INPUT); pinMode(ULTRA_TRIGGER_PIN, OUTPUT); // Set start position open_servo(); } void loop() { // RF start signal received uint8_t id = receive_id(); if (id && id == KEY) { start_signal = true; sweep_count = 0; } // For old vs new distance comparison old_distance = distance ? distance : old_distance; distance = ping_distance(); // Movement detected if ((old_distance > 0) && (distance != old_distance) && (distance <= ULTRA_MAX_DISTANCE) && (distance >= ULTRA_MIN_DISTANCE) && (sweep_count < MAX_SWEEPS) || start_signal) { if (start_signal) start_signal = false; // Move servo if (alternate) close_servo(); else open_servo(); sweep_count++; alternate = !alternate; delay(250); } } String receive_msg() { uint8_t buf[VW_MAX_MESSAGE_LEN]; uint8_t buflen = VW_MAX_MESSAGE_LEN; String msg = ""; if (vw_get_message(buf, &buflen)) { for (int i = 0; i < buflen; i++) { msg += char(buf[i]); } } return msg; } uint8_t receive_id() { uint8_t buf[VW_MAX_MESSAGE_LEN]; uint8_t buflen = VW_MAX_MESSAGE_LEN; if (vw_get_message(buf, &buflen)) { for (int i = 0; i < buflen; i++) { Serial.print("R: "); Serial.println(buf[i]); } return buf[0]; } return 0; } unsigned int ping_distance() { delay(50); unsigned long duration, distance; digitalWrite(ULTRA_TRIGGER_PIN, LOW); delayMicroseconds(2); digitalWrite(ULTRA_TRIGGER_PIN, HIGH); delayMicroseconds(10); digitalWrite(ULTRA_TRIGGER_PIN, LOW); duration = pulseIn(ULTRA_ECHO_PIN, HIGH); return (duration/58.138) * .39; // remove *.39 for cm } void open_servo() { // Attach/detach to prevent RF interference myservo.attach(SERVO_PIN); for (int pos = SERVO_MAX_POS; pos >= SERVO_MIN_POS; pos -= SERVO_STEP_SIZE) { myservo.write(pos); delay(10); } myservo.detach(); } void close_servo() { // Attach/detach to prevent RF interference myservo.attach(SERVO_PIN); for (int pos = SERVO_MIN_POS; pos <= SERVO_MAX_POS; pos += SERVO_STEP_SIZE) { myservo.write(pos); delay(10); } myservo.detach(); } <file_sep>/servo map/master/src/CommandServer.h #pragma once #include <SPI.h> #include <Ethernet.h> typedef bool (*handler)(EthernetClient client, uint8_t * args, int length); typedef void (*event)(EthernetClient client); class CommandServer { public: CommandServer(unsigned int port = 3000); bool begin(void); void update(void); void addCommand(uint8_t id, handler callback); void setOnErrorHandler(event callback); void setOnConnectHandler(event callback); void setOnDisconnectHandler(event callback); private: handler commands[255]; event errorHandler; event connectHandler; event disconnectHandler; EthernetServer server; };<file_sep>/servo map/master/src/CommandServer.cpp #include "CommandServer.h" CommandServer::CommandServer(unsigned int port) : server(port) { } bool CommandServer::begin() { server.begin(); } void CommandServer::update() { EthernetClient client = server.available(); while (client.connected()) { if (connectHandler) connectHandler(client); uint8_t command; if (client.available()) { command = client.read(); if (!commands[command]) { if (errorHandler) errorHandler(client); if (disconnectHandler) disconnectHandler(client); client.stop(); return; } } else { if (errorHandler) errorHandler(client); if (disconnectHandler) disconnectHandler(client); client.stop(); return; } uint8_t buffer[client.available()]; int i = 0; while (client.available()) { buffer[i++] = client.read(); } commands[command](client, buffer, i); if (disconnectHandler) disconnectHandler(client); client.stop(); } } void CommandServer::addCommand(uint8_t id, handler callback) { commands[id] = callback; } void CommandServer::setOnErrorHandler(event callback) { errorHandler = callback; } void CommandServer::setOnConnectHandler(event callback) { connectHandler = callback; } void CommandServer::setOnDisconnectHandler(event callback) { disconnectHandler = callback; }<file_sep>/servo map/master/examples/SlagboomServer/SlagboomServer.ino #include <SPI.h> #include <Ethernet.h> #include <CommandServer.h> #include <VirtualWire.h> #define PORT 3000 #define STATUS_LED_PIN 7 #define TRANSMITTER_PIN 3 #define RECEIVER_PIN 2 byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD }; CommandServer server(PORT); void setup() { Serial.begin(9600); Serial.println(F("Setting up transmitter")); vw_set_tx_pin(TRANSMITTER_PIN); vw_set_ptt_inverted(true); vw_setup(2000); Serial.println(F("Transmitter ready for action")); Serial.println(F("Starting server")); if (!Ethernet.begin(mac)) { Serial.println(F("Failed to obtain DHCP address")); Serial.println(F("Foute boel. Tijd om niks te doen.")); while (true) ; } server.begin(); server.setOnErrorHandler(&onError); server.setOnConnectHandler(&onConnect); server.setOnDisconnectHandler(&onDisconnect); server.addCommand('p', &handlePing); server.addCommand('a', &handleBroadcast); Serial.print(F("Listening to connections on ")); Serial.print(Ethernet.localIP()); Serial.print(":"); Serial.println(PORT); } void loop() { server.update(); } void onError(EthernetClient client) { Serial.println(F("Error!")); } void onConnect(EthernetClient client) { Serial.println(F("Incoming connection")); } void onDisconnect(EthernetClient client) { Serial.println(F("Disconnected")); } bool handlePing(EthernetClient client, uint8_t * args, int length) { Serial.println(F("Pong!")); client.write("pong"); return true; } bool handleBroadcast(EthernetClient client, uint8_t * args, int length) { vw_send(args, length); vw_wait_tx(); Serial.print(F("Broadcasted: ")); for (int i = 0; i < length; i++) { Serial.println(args[i]); } return true; } <file_sep>/servo map/master/extras/tester/main.js var net = require('net'); var client = new net.Socket(); client.connect(3000, '192.168.1.100', function () { console.log('Connected'); client.write(new Buffer([97, 4, 5])); }); client.on('data', function (data) { console.log('Received: ' + data); }); client.on('close', function () { console.log('Bye!'); });<file_sep>/servo map/master/library.properties name=CommandServer version=1.0 author=<NAME> <<EMAIL>>, <NAME> <<EMAIL>> maintainer=Obe Attema <<EMAIL>> sentence=Handelt commando's af via TCP. paragraph=Dingen category=Communication url=http://frikandellen.party architectures=avr includes=CommandServer.h<file_sep>/servo map/master/master.ino #include <VirtualWire.h> const int RF_TRANSMIT_PIN = 7; void setup() { // RF communication vw_set_tx_pin(RF_TRANSMIT_PIN); vw_set_ptt_inverted(true); vw_setup(2000); } void loop() { // Read from serial for testing purposes if (Serial.available() > 0) { String msg = Serial.readString(); if (msg.length() > 0) transmit_msg(msg); } } void transmit_msg(String msg) { char buf[msg.length()+1]; msg.toCharArray(buf, msg.length()+1); vw_send((uint8_t *)buf, msg.length()+1); vw_wait_tx(); }
14d3d3a758b40c58151bfb4cc13ae1cc850c773a
[ "Markdown", "JavaScript", "C++", "INI" ]
10
C++
hoog1511/Project-Domotica
88409c824c6e26717bf20a3f5f9f338038796816
fbae8a1fd4e6c35e35650a6e3d0d5df20b0b8e2b
refs/heads/master
<file_sep>namespace mediator { public class Heater : IColleague { public IMachineMediator Mediator { get; set; } public void On(int temp) { System.Console.WriteLine("Heater is on..."); if (Mediator.CheckTemperature(temp)) { System.Console.WriteLine($"Temperature is set to {temp}"); } Mediator.Off(); } public void Off() { System.Console.WriteLine("Heater is off..."); Mediator.Wash(); } } }<file_sep>using System; namespace command { public class Email { public void SendEmail() => Console.WriteLine("Sending email......."); } }<file_sep>using System; namespace command { public class FileIO { public void Execute() => Console.WriteLine("Executing File IO operations..."); } }<file_sep>using System.Linq.Expressions; namespace interpreter { public class Add : IExpression { private IExpression leftExpression; private IExpression rightExpression; public int Interpret() => leftExpression.Interpret() + rightExpression.Interpret(); } }<file_sep>namespace command { public class FileIOJob : IJob { private FileIO _fileIO; public void Run() { if (_fileIO != null) { _fileIO.Execute(); } } public void FileIO(FileIO fileIo) => _fileIO = fileIo; } }<file_sep>namespace mediator { public class SoilRemoval { public void Low() => System.Console.WriteLine("Setting Soil Removal to low"); public void Medium() => System.Console.WriteLine("Setting Soil Removal to medium"); public void High() => System.Console.WriteLine("Setting Soil Removal to high"); } }<file_sep>using System; namespace mediator { public class CottonMediator : IMachineMediator { private const int DrumSpeed = 700; private const int Temperature = 40; private Machine machine { get; set; } private Heater heater { get; set; } private Motor motor { get; set; } private Sensor sensor { get; set; } private SoilRemoval soilRemoval { get; set; } private Valve valve { get; set; } public CottonMediator(Machine machine, Heater heater, Motor motor, Sensor sensor, SoilRemoval soilRemoval, Valve valve) { Console.WriteLine($"............... Setting up for COTTON program ..............."); this.machine = machine; this.heater = heater; this.motor = motor; this.sensor = sensor; this.soilRemoval = soilRemoval; this.valve = valve; } public void Start() => machine.Start(); public void Wash() { motor.StartMotor(); motor.RotateDrum(DrumSpeed); Console.WriteLine("Adding detergent"); soilRemoval.Low(); Console.WriteLine("Adding softener"); } public void Open() => valve.Open(); public void Closed() => valve.Closed(); public void On() => heater.On(Temperature); public void Off() => heater.Off(); public bool CheckTemperature(int temp) => sensor.CheckTemperature(temp); } }<file_sep># Behavioural Design Patterns (part one) This repo contains my solutions to a series of design pattern questions. Patterns implemented: - Chain - Command - Interpreter - Iterator - Mediator <file_sep>namespace mediator { public class Sensor { public bool CheckTemperature(int temp) { System.Console.WriteLine($"Temperature reached {temp} C"); return true; } } }<file_sep>using System; namespace mediator { public class Valve : IColleague { public IMachineMediator Mediator { get; set; } public void Open() { Console.WriteLine("Valve is opened..."); Console.WriteLine("Filling water..."); Mediator.Closed(); } public void Closed() { Console.WriteLine("Valve is closed..."); Mediator.On(); } } }<file_sep>using System; namespace command { public class Logging { public void Log() => Console.WriteLine("Logging..."); } }<file_sep>using System; using System.Collections.Generic; namespace worksheet_eight_behavioural_design_patterns { public static class TestChainOfResponsibility { public static void Main(string[] args) { IHandler textHandler = new TextFileHandler("Text Handler"); IHandler docHandler = new DocFileHandler("Doc Handler"); IHandler excelHandler = new ExcelFileHandler("Excel Handler"); IHandler audioHandler = new AudioFileHandler("Audio Handler"); IHandler videoHandler = new VideoFileHandler("Video Handler"); IHandler imageHandler = new ImageFileHandler("Image Handler"); textHandler.Handler = docHandler; docHandler.Handler = excelHandler; excelHandler.Handler = audioHandler; audioHandler.Handler = videoHandler; videoHandler.Handler = imageHandler; var file = new File("Abc.mp3", "audio", "C:"); textHandler.Process(file); Console.WriteLine("--------------------"); file = new File("Abc.jpg", "video", "C:"); textHandler.Process(file); Console.WriteLine("--------------------"); file = new File("Abc.doc", "doc", "C:"); textHandler.Process(file); Console.WriteLine("--------------------"); file = new File("Abc.bat", "bat", "C:"); textHandler.Process(file); } } }<file_sep>using System; namespace worksheet_eight_behavioural_design_patterns { public class ExcelFileHandler : IHandler { public ExcelFileHandler(string textHandler) { HandlerName = textHandler; } public IHandler Handler { get; set; } public string HandlerName { get; } public void Process(object file) { File fileObj = (File)file; if (fileObj.Type.Equals("excel")) { Console.WriteLine($"Process and saving excel file... by {HandlerName}"); } else { if (Handler != null) { Console.WriteLine($"{HandlerName} forwards request to {Handler.HandlerName}"); Handler.Process(file); } else { Console.WriteLine("File not supported"); } } } } }<file_sep>using System; namespace command { public static class TestCommandPattern { public static void Main(string[] args) { const int numberOfThreads = 10; const int numberOfJobs = 5; var pool = new ThreadPool<IJob>(numberOfThreads); var emailJob = new EmailJob(); var smsJob = new SmsJob(); var fileIOJob = new FileIOJob(); var logJob = new LoggingJob(); for (var i = 0; i < numberOfJobs; i++) { emailJob.Email(new Email()); smsJob.Sms(new Sms()); fileIOJob.FileIO(new FileIO()); logJob.Logging = new Logging(); pool.AddJob(emailJob); pool.AddJob(smsJob); pool.AddJob(fileIOJob); pool.AddJob(logJob); } pool.ShutdownPool(); } } }<file_sep>using System; namespace iterator { public static class TestIteratorPattern { public static void Main(string[] args) { var storage = new ShapeStorage<Shape>(); storage.AddShape("Polygon"); storage.AddShape("Hexagon"); storage.AddShape("Circle"); storage.AddShape("Rectangle"); storage.AddShape("Square"); var iterator = new ShapeIterator<ShapeStorage<Shape>>(storage); while (iterator.MoveNext()) { Console.WriteLine(iterator.Current); } Console.WriteLine("Removing items while iterating..."); iterator.Reset(); // reposition the iterator while (iterator.MoveNext()) { Console.WriteLine(iterator.Current); iterator.Dispose(); } } } }<file_sep>using System.Collections; using System.Collections.Generic; namespace iterator { public class ShapeIterator<TShape> : IEnumerator<TShape> { private TShape _collection; private int pos = -1; public ShapeIterator(TShape collection) { Current = collection; _collection = collection; } public bool MoveNext() { pos++; return false; // todo } public void Reset() { pos = -1; } public TShape Current { get; } object? IEnumerator.Current => Current; public void Dispose() { throw new System.NotImplementedException(); } } }<file_sep>using System; namespace mediator { public class Button : IColleague { public IMachineMediator Mediator { get; set; } public void Press() { Console.WriteLine("Button pressed."); Mediator.Start(); } } }<file_sep>using System; namespace worksheet_eight_behavioural_design_patterns { public class DocFileHandler : IHandler { public DocFileHandler(string textHandler) { HandlerName = textHandler; } public IHandler Handler { get; set; } public string HandlerName { get; } public void Process(object file) { File fileObj = (File)file; if (fileObj.Type.Equals("doc")) { Console.WriteLine($"Process and saving doc file... by {HandlerName}"); } else { if (Handler != null) { Console.WriteLine($"{HandlerName} forwards request to {Handler.HandlerName}"); Handler.Process(file); } else { Console.WriteLine("File not supported"); } } } } }<file_sep>using System; using System.Collections.Generic; namespace interpreter { public static class TestInterpreterPattern { public static void Main(string[] args) { var tokenString = "7 3 - 2 1 + *"; var stack = new Stack<IExpression>(); var tokenArray = tokenString.Split(" "); foreach (var s in tokenArray) { if (ExpressionUtils.IsOperator(s)) { var rightExpression = stack.Pop(); var leftExpression = stack.Pop(); var op = ExpressionUtils.GetOperator(s, leftExpression, rightExpression); stack.Push(new Number(op.Interpret())); } else { stack.Push(new Number(Int32.Parse(s))); } } Console.WriteLine($"( {tokenString} ) {stack.Pop().Interpret()}"); } } }<file_sep>using System; namespace iterator { public class ShapeStorage<T> where T : Shape, new() { private const int NumberOfShapes = 5; private readonly T[] _shapes = new T[NumberOfShapes]; private int _index = 0; public void AddShape(string name) => _shapes[_index++] = new T {Id = _index, Name = name}; public T[] GetShapes() { T[] copy = new T[NumberOfShapes]; for (int i = 0; i < NumberOfShapes; i++) { if (_shapes[i] != null) { copy[i] = _shapes[i]; } } //Array.Copy(_shapes, copy, NumberOfShapes); return copy; } // Additional methods? public T this[int i] { get => _shapes[i]; set => _shapes[i] = value; } // Indexer? } }<file_sep>namespace command { public class LoggingJob : IJob { public Logging Logging { set; get; } public void Run() { if (Logging != null) { Logging.Log(); } } } }<file_sep>using System; namespace mediator { public static class TestMediator { public static void Main(string[] args) { var sensor = new Sensor(); var soilRemoval = new SoilRemoval(); var motor = new Motor(); var machine = new Machine(); var heater = new Heater(); var valve = new Valve(); var button = new Button(); IMachineMediator mediator = new CottonMediator(machine, heater, motor, sensor, soilRemoval, valve); button.Mediator = mediator; machine.Mediator = mediator; heater.Mediator = mediator; valve.Mediator = mediator; button.Press(); Console.WriteLine("********************"); mediator = new DenimMediator(machine, heater, motor, sensor, soilRemoval, valve); button.Mediator = mediator; machine.Mediator = mediator; heater.Mediator = mediator; valve.Mediator = mediator; button.Press(); } } }<file_sep>using System; namespace mediator { public class Motor { public void StartMotor() => Console.WriteLine("Start motor..."); public void RotateDrum(int rpm) => Console.WriteLine($"Rotating drum at {rpm} rpm."); } }<file_sep>using System; namespace command { public class Sms { public void SendSms() => Console.WriteLine("Sending SMS..."); } }<file_sep>namespace worksheet_eight_behavioural_design_patterns { public interface IHandler { IHandler Handler { get; set; } string HandlerName { get; } void Process(object file); } }<file_sep>namespace command { public class SmsJob : IJob { private Sms _sms; public void Run() { if (_sms != null) { _sms.SendSms(); } } public void Sms(Sms sms) => _sms = sms; } }<file_sep>namespace interpreter { public class Product : IExpression { private IExpression leftExpression; private IExpression rightExpression; public int Interpret() => leftExpression.Interpret() * rightExpression.Interpret(); } }<file_sep>using System; using System.Collections.Concurrent; using System.Linq; using System.Threading; namespace command { public class ThreadPool<T> where T: IJob { private static BlockingCollection<T> jobQueue = new BlockingCollection<T>(); private Thread[] jobThreads; private static bool shutdown; public ThreadPool(int numberOfThreads) { jobThreads = new Thread[numberOfThreads]; for (var i = 0; i < numberOfThreads; i++) { Worker worker = new Worker(); jobThreads[i] = new Thread(worker.Run); jobThreads[i].Name = $"Job ID: {i}"; //throw new System.NotImplementedException(); } } public void AddJob(T job) { jobQueue.Add(job); } public void ShutdownPool() { const int sleepTime = 1000; while (jobQueue.Count > 0) { try { jobThreads.ToList().ForEach(n => n.Start()); Thread.Sleep(sleepTime); //jobThreads[0].Start(); //Thread.Sleep(sleepTime); // some code here? } catch (ThreadInterruptedException ex) { Console.WriteLine(ex.StackTrace); } } shutdown = true; foreach (var workerThread in jobThreads) { workerThread.Interrupt(); } } private class Worker /*(string name)*/ : ThreadLocal<IJob> { //string _name; //Worker(string name) //{ // _name = name; //} public void Run() { while (!shutdown) { try { var r = jobQueue.Take(); r.Run(); } catch (ThreadInterruptedException ex) { Console.WriteLine(ex.StackTrace); //? } } } } } }<file_sep>namespace interpreter { public sealed class ExpressionUtils { public static bool IsOperator(string s) { throw new System.NotImplementedException(); } public static IExpression GetOperator(string s, IExpression left, IExpression right) { throw new System.NotImplementedException(); } } }<file_sep>namespace command { public class EmailJob : IJob { private Email _email; public void Run() { if (_email != null) { _email.SendEmail(); } } public void Email(Email email) => _email = email; } }<file_sep>namespace interpreter { public class Number : IExpression { internal Number(int n) { throw new System.NotImplementedException(); } public int Interpret() { throw new System.NotImplementedException(); } } }<file_sep>namespace mediator { public interface IMachineMediator { void Start(); void Wash(); void Open(); void Closed(); void On(); void Off(); bool CheckTemperature(int temp); } }<file_sep>namespace mediator { public interface IColleague { IMachineMediator Mediator { get; set; } } }<file_sep>namespace worksheet_eight_behavioural_design_patterns { /// <summary> /// This is just a dummy class rather than using a real class - a mock. /// </summary> public class File { public string FileName { get; } public string Type { get; } public string Location { get; } public File(string fileName, string type, string location) { FileName = fileName; Type = type; Location = location; } } }<file_sep>namespace mediator { public class Machine : IColleague { public IMachineMediator Mediator { get; set; } public void Start() => Wash(); public void Wash() => Mediator.Open(); } }
9f579f6f8627afc8564652f1a6bc3ddd446b88a1
[ "Markdown", "C#" ]
35
C#
pazami01/behavioural-design-patterns-one
d301e5bd917fb86fcf3c364a8488d4a3680498d5
4dd95621004f0780749d513b514fa7cf016d22dc
refs/heads/master
<file_sep>/** * Getting Started Course with JavaScript lesson 12 * In this we will create a Jokenpô (Stone, Paper and Scissors) * @author <NAME> * Web Developer and Mobile */ // Main function function jogar(){ if(document.getElementById("pedra").checked == false && document.getElementById("papel").checked == false && document.getElementById("tesoura").checked == false ){ alert("Selecione uma opção"); } else{ var sorteio = Math.floor(Math.random() * 3); switch(sorteio){ case 0: document.getElementById("pc").src = "imagens_sons/pcpedra.png"; break; case 1: document.getElementById("pc").src = "imagens_sons/pcpapel.png"; break; case 2: document.getElementById("pc").src = "imagens_sons/pctesoura.png"; break; } // Check the winner or declare a tie. if((document.getElementById("pedra").checked == true && sorteio == 0) || (document.getElementById("papel").checked == true && sorteio == 1) || (document.getElementById("tesoura").checked == true && sorteio == 2)){ document.getElementById("placar").innerHTML = "Empate"; } else if ((document.getElementById("pedra").checked == true && sorteio == 2) || (document.getElementById("papel").checked == true && sorteio == 0) || (document.getElementById("tesoura").checked == true && sorteio == 1)){ document.getElementById("placar").innerHTML = "Jogador Venceu"; } else{ document.getElementById("placar").innerHTML = "Computador Venceu"; } } } function resetar(){ document.getElementById("pc").src = "imagens_sons/pc.png"; document.getElementById("placar").innerHTML = ""; }
2059a3a3fe1deaff638025a1f08a3b3c013c98b9
[ "JavaScript" ]
1
JavaScript
abraaocrvlho/jokenpo-js
b98eb57a212c0698b363779796e7c37e90400c65
da295420c0972352ca198ab8412b9e35341ce237
refs/heads/main
<file_sep>const Engine = Matter.Engine; const Render = Matter.Render; const World = Matter.World; const Bodies = Matter.Bodies; const Constraint = Matter.Constraint; const Body = Matter.Body; const Composites = Matter.Composites; const Composite = Matter.Composite; var stones = []; function setup() { createCanvas(windowWidth, windowHeight); engine = Engine.create(); world = engine.world; frameRate(80); rightwall = new Base(width/2+620,height-200,200,150); leftwall = new Base(width/2-620,height-200,200,150); joinPoint = new Base(width/2-655,height-200,200,150); bridge = new Bridge(27,{x:leftwall.body.position.x-20,y:height-280}); Matter.Composite.add(bridge.body,joinPoint); joinLink = new Link (bridge,joinPoint); for(var i = 0;i <= 8;i++){ var x = random(width/2-200,width/2+300); var y = random(-200,40); var stone = new Stone(x,y,40,40); stones.push(stone); } } function draw() { background(51); leftwall.display(); rightwall.display(); joinPoint.display(); bridge.show(); for(stone of stones){ stone.display(); } //for (var i = 0;i<stones.length;i++){ // showStone(i,stones); //} Engine.update(engine); } //function showStone(index,Stones){ //Stones[index].display(); //}
944a2086dacd6630d61c27aa50a2299199fe2538
[ "JavaScript" ]
1
JavaScript
Hemachandrasai/project_29
17110ac52ad8bed29820476323b4c4a1e0fccfd9
e4f04dae6bb63cb40eadcf8ffae9ecce80fab119
refs/heads/main
<repo_name>thinhtanpham/Intify-Music-App-Mobile<file_sep>/Intify-new/Server/config/deleteFile.js const fs = require("fs"); const rimraf = require("rimraf"); const path = require("path"); module.exports = function deleteFile(uploadDir) { uploadDir = "public/" + uploadDir.slice(25); try { fs.unlinkSync(uploadDir); } catch (err) { console.error(err); } }; <file_sep>/Intify-new/Server/Router/index.js const MusicRouter= require('./MusicRouter') const UserRouter= require('./UserRouter') function router (app) { app.use('/', MusicRouter) app.use('/account', UserRouter) } module.exports = router<file_sep>/Intify-new/Intify/Component/Login.js import React, {Component} from 'react'; import { StyleSheet, Text, View, TextInput, Button, TouchableHighlight, Image, Alert, } from 'react-native'; import AsyncStorage from '@react-native-async-storage/async-storage'; import LinearGradient from 'react-native-linear-gradient'; import api from '../api'; export default class LoginView extends Component { constructor(props) { super(props); this.state = { username: '', password: '', success: true, }; } async Login(navigation) { try { const response = await fetch('http://'+api+':5000/account/checkLogin', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username: this.state.username, password: <PASSWORD>, }), }); if (response.status === 500) { this.setState({ success: !this.state.success, }); setTimeout(() => { this.setState({ success: !this.state.success, }); }, 4000); } else { const json = await response.json(); try { await AsyncStorage.setItem( '@storage_accessToken', json.message.accessToken, ); await AsyncStorage.setItem( '@storage_refreshToken', json.message.refreshToken, ); console.log("ass: " +await AsyncStorage.getItem( '@storage_accessToken' )) console.log("ref: " +await AsyncStorage.getItem( '@storage_refreshToken' )) navigation.replace('User'); } catch (error) { console.log(error); } } } catch (error) { console.error(error); } } render() { const {navigation} = this.props; return ( <LinearGradient colors={['#52697A', '#5A6C91']} style={{flex: 1}}> <Image style={styles.imgLogo} source={require('./src/img/logo2.png')} /> <View style={styles.container}> <Text style={styles.warningText}> {' '} {this.state.success ? '' : '*Wrong Username or Password'} </Text> <View style={styles.inputContainer}> <TextInput style={styles.inputs} placeholder="Username" underlineColorAndroid="transparent" onChangeText={username => this.setState({username})} /> </View> <View style={styles.inputContainer}> <TextInput style={styles.inputs} placeholder="<PASSWORD>" secureTextEntry={true} underlineColorAndroid="transparent" onChangeText={password => this.setState({password})} /> </View> <TouchableHighlight style={[styles.buttonContainer, styles.loginButton]} onPress={() => this.Login(navigation)}> <Text style={styles.loginText}>Login</Text> </TouchableHighlight> {/* <TouchableHighlight style={styles.buttonContainer} onPress={}> <Text>Forgot your password?</Text> </TouchableHighlight> <TouchableHighlight style={styles.buttonContainer} onPress={}> <Text>Register</Text> </TouchableHighlight> */} </View> </LinearGradient> ); } } const styles = StyleSheet.create({ imgLogo: { height: 200, width: 200, marginLeft: 'auto', marginRight: 'auto', marginTop: 50, }, container: { marginTop: 50, flex: 1, alignItems: 'center', }, inputContainer: { borderBottomColor: '#F5FCFF', backgroundColor: '#FFFFFF', borderRadius: 5, borderBottomWidth: 1, width: 300, height: 45, marginBottom: 30, flexDirection: 'row', alignItems: 'center', }, inputs: { height: 45, marginLeft: 16, borderBottomColor: '#FFFFFF', flex: 1, }, inputIcon: { width: 30, height: 30, marginLeft: 15, justifyContent: 'center', }, buttonContainer: { height: 45, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginBottom: 20, marginTop: 50, width: 250, borderRadius: 5, }, loginButton: { backgroundColor: '#F7FA43', }, loginText: { color: 'black', fontWeight: 'bold', fontSize: 15, }, warningText: { color: 'red', marginBottom: 5, fontSize: 12, }, }); <file_sep>/Intify-new/Intify/Redux/Reducer/isPlayingReducer.js import { is } from 'immer/dist/internal'; import {ADD_PLAYING, RE_PLAYING} from '../Type/isPlayingType'; const isPlaying = { rePlaying: {}, isPlaying: {}, }; function isPlayingReducer(state = isPlaying, action) { switch (action.type) { case ADD_PLAYING: state.isPlaying = action.music state.isPlaying = {...state.isPlaying} return {...state}; case RE_PLAYING: state.rePlaying = action.music; state.rePlaying = {...state.rePlaying}; return {...state}; default: return {...state}; } } export default isPlayingReducer; <file_sep>/Intify-new/Server/Model/Music.js const mongoose = require("mongoose"); const Schema = mongoose.Schema; const Music = new Schema( { nameSong: { type: String, required: true }, nameArtist: { type: String, required: true }, idUser: { type: String, required: true}, img: { type: String, required: true }, mp3: { type: String, required: true }, }, { timestamps: true, } ); module.exports = mongoose.model("Music", Music); <file_sep>/Intify-new/Server/config/mongooseConvert.js module.exports= { arrayObjMongoose: function (mongoose) { return mongoose.map(mongoose => mongoose.toObject()) }, objMongoose: function (mongoose) { console.log(mongoose.toObject()) return mongoose ? mongoose.toObject() : mongoose } }<file_sep>/README.md # Intify-Music-App-Mobile PRM <file_sep>/Intify-new/Server/Router/MusicRouter.js const express = require("express"); const MusicController = require("../Controller/MusicController"); const Music = require("../Model/Music"); const router = express.Router(); const multer = require("multer"); const { isImg, isSong } = require("../config/compareFile"); const jwt = require('jsonwebtoken') const authenticateToken = require('../config/authenticate') const storage = multer.diskStorage({ destination: function (req, file, cb) { if (isImg(file.fieldname)) { cb(null, "public/uploads/imgSong"); } else if (isSong(file.fieldname)) { cb(null, "public/uploads/mp3"); } }, filename: function (req, file, cb) { //const fileType = file.originalname.split("."); if (isImg(file.fieldname)) { cb(null, req.body.nameSong.split(' ').join('-') + "-" + req.body.nameArtist.split(' ').join('-') +".jpg"); } else if (isSong(file.fieldname)) { cb(null, req.body.nameSong.split(' ').join('-') + "-" + req.body.nameArtist.split(' ').join('-') +".mp3"); } }, }); const upload = multer({ storage: storage }); const newSingUpload = upload.fields([{ name: "img" }, { name: "mp3" }]); router.get("/", MusicController.showListMusic); router.get("/artists", MusicController.showListArtist); router.get("/musics/:id", MusicController.musicsOfArtist); router.post("/add/newSong",authenticateToken, newSingUpload, MusicController.addNewMusic); // router.put("/editMusic/:_id",authenticateToken, MusicController.editMusic) router.delete("/delete/:id",MusicController.deleteMusic) module.exports = router; <file_sep>/Intify-new/Intify/Redux/Action/isPlayingAction.js import {ADD_PLAYING, RE_PLAYING} from '../Type/isPlayingType'; export function addPlaying(music) { return { type: ADD_PLAYING, music }; } export function rePlaying(music) { return { type: RE_PLAYING, music }; } <file_sep>/Intify-new/Intify/Component/UserComponent/UploadMusic.js import React, {useState} from 'react'; import { StyleSheet, Text, View, TouchableOpacity, TextInput, } from 'react-native'; import Modal from 'react-native-modal'; import DocumentPicker from 'react-native-document-picker'; import AsyncStorage from '@react-native-async-storage/async-storage'; import refreshToken from '../../refreshToken'; import StatusModal from './StatusModal'; import api from '../../api'; const UploadMusic = () => { const [imgUpload, setImgUpload] = useState(null); const [mp3Upload, setMp3Upload] = useState(null); const [nameSong, setNameSong] = useState(''); const [nameArtist, setNameArtist] = useState(''); const [stateUpload, setStateUpload] = useState(''); const [status, setStatus] = useState(false); const [nullField, setNullField] = useState(false); const uploadSong = async e => { if ( imgUpload != null && mp3Upload != null && nameSong.nameSong.length !== 0 && nameArtist.nameArtist.length !== 0 ) { setStateUpload('Waiting...'); setStatus(true); const data = new FormData(); data.append('nameSong', nameSong.nameSong); data.append('nameArtist', nameArtist.nameArtist); data.append('img', { uri: imgUpload[0].uri, type: imgUpload[0].type, name: imgUpload[0].name, }); data.append('mp3', { uri: mp3Upload[0].uri, type: mp3Upload[0].type, name: mp3Upload[0].name, }); try { const asAccessTk = await AsyncStorage.getItem('@storage_accessToken'); await fetch('http://' + api + ':3002/add/newSong', { method: 'post', headers: { Accept: 'application/json', type: 'formData', authorization: 'Bearer ' + asAccessTk, }, body: data, }) .then(async response => { const resJs = await response.json(); if (resJs.status === 200) { setStateUpload('Upload Successfull'); e.persist(); setTimeout(() => setStatus(false), 3000); } }) .catch(async error => { refreshToken(); try { const asAccessTk = await AsyncStorage.getItem( '@storage_accessToken', ); await fetch('http://' + api + ':3002/add/newSong', { method: 'post', headers: { Accept: 'application/json', type: 'formData', authorization: 'Bearer ' + asAccessTk, }, body: data, }) .then(async response => { const resJs = await response.json(); if (resJs.status === 200) { setStateUpload('Upload Successfull'); e.persist(); setTimeout(() => setStatus(false), 3000); } }) .catch(error => { if (error) { setStateUpload('Upload Failed'); e.persist(); setTimeout(() => setStatus(false), 3000); } }); } catch (error) { if (error) { setStateUpload('Upload Failed'); e.persist(); setTimeout(() => setStatus(false), 3000); } } }); } catch (error) { if (error) { setStateUpload(false); e.persist(); setTimeout(() => setStatus(false), 3000); } } } else { setNullField(true); e.persist(); setTimeout(() => setNullField(false), 5000); } }; const selectImage = async () => { try { const res = await DocumentPicker.pick({ type: DocumentPicker.types.images, }); setImgUpload(res); //setState } catch (err) { console.log(err); } }; const selectMp3 = async () => { try { const res = await DocumentPicker.pick({ type: DocumentPicker.types.audio, }); setMp3Upload(res); //setState } catch (err) { console.log(err); } }; return ( <View style={styles.mainBody}> <StatusModal status={status} stateUpload={stateUpload} /> <View style={{justifyContent: 'center'}}> {nullField ? ( <Text style={styles.textErr}>* Not null field</Text> ) : ( <Text style={styles.textErr}></Text> )} <View style={styles.inputContainer}> <TextInput style={styles.inputs} placeholder="name-song" underlineColorAndroid="transparent" onChangeText={nameSong => setNameSong({nameSong})} /> </View> <View style={styles.inputContainer}> <TextInput style={styles.inputs} placeholder="name-artist" underlineColorAndroid="transparent" onChangeText={nameArtist => setNameArtist({nameArtist})} /> </View> <TouchableOpacity style={styles.buttonStyle} activeOpacity={0.5} onPress={selectImage}> <Text style={styles.buttonTextStyle}>Select Image</Text> </TouchableOpacity> <TouchableOpacity style={styles.buttonStyle} activeOpacity={0.5} onPress={selectMp3}> <Text style={styles.buttonTextStyle}>Select File</Text> </TouchableOpacity> <TouchableOpacity style={styles.buttonStyle} activeOpacity={0.5} onPress={uploadSong}> <Text style={styles.buttonTextStyle}>Upload File</Text> </TouchableOpacity> </View> </View> ); }; const styles = StyleSheet.create({ mainBody: { flex: 1, justifyContent: 'center', padding: 20, }, buttonStyle: { backgroundColor: '#307ecc', borderWidth: 0, color: '#FFFFFF', borderColor: '#307ecc', height: 40, alignItems: 'center', borderRadius: 30, marginLeft: 35, marginRight: 35, marginTop: 15, }, buttonTextStyle: { color: '#FFFFFF', paddingVertical: 10, fontSize: 16, }, textStyle: { backgroundColor: '#fff', fontSize: 15, marginTop: 16, marginLeft: 35, marginRight: 35, textAlign: 'center', }, inputContainer: { borderBottomWidth: 1, width: 300, height: 45, marginBottom: 10, flexDirection: 'row', marginRight: 'auto', marginLeft: 'auto', }, inputs: { height: 45, marginLeft: 12, borderBottomColor: '#FFFFFF', flex: 1, }, textErr: { height: 20, color: 'red', marginLeft: 'auto', marginRight: 'auto', }, modal: { width: 350, backgroundColor: 'white', borderRadius: 5, marginTop: 250, marginBottom: 250, marginLeft: 'auto', marginRight: 'auto', }, }); export default UploadMusic; <file_sep>/Intify-new/Intify/App.js import React, {useState} from 'react'; import {StyleSheet, StatusBar, Button, Text} from 'react-native'; import ListMusics from './Component/ListMusics'; import {NavigationContainer} from '@react-navigation/native'; import {createNativeStackNavigator} from '@react-navigation/native-stack'; import FullMusic from './Component/FullMusic'; import ListMusicsArtist from './Component/ListMusicsArtist' import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'; import {faUserCircle} from '@fortawesome/free-solid-svg-icons'; import LoginView from './Component/Login'; import UploadMusic from './Component/UserComponent/UploadMusic'; import AsyncStorage from '@react-native-async-storage/async-storage'; import User from './Component/User'; import {Provider as StoreProvider} from 'react-redux'; import rootStore from './Redux/store'; import Context from './Component/Context' const Stack = createNativeStackNavigator(); function App() { const [isPlaying, setPlaying] = useState({}); return ( <StoreProvider store={rootStore}> <NavigationContainer> <Context.Provider value={{ isPlaying: isPlaying, setMusicPlaying: isPlaying => { setPlaying(isPlaying) } }}> <StatusBar hidden={true} /> <Stack.Navigator initialRouteName="ListMusics"> <Stack.Screen name="ListMusics" component={ListMusics} isPlaying={({params}) => params} options={({navigation}) => ({ headerTitle: '', headerRight: () => ( <FontAwesomeIcon icon={faUserCircle} onPress={async () => { try { const asAccessTk = await AsyncStorage.getItem( '@storage_accessToken', ); asAccessTk ? navigation.navigate('User') : navigation.navigate('Login'); } catch (error) { console.log(error); } }} style={styles.icon} size={25} /> ), headerStyle: { backgroundColor: '#243039', }, })} /> <Stack.Screen name="FullMusic" component={FullMusic} options={({navigation}) => ({ headerBackVisible: true, headerTitle: "", headerTintColor: "white", headerRight: () => ( <FontAwesomeIcon icon={faUserCircle} onPress={async () => { try { const asAccessTk = await AsyncStorage.getItem( '@storage_accessToken', ); asAccessTk ? navigation.navigate('User') : navigation.navigate('Login'); } catch (error) { console.log(error); } }} style={styles.icon} size={25} /> ), headerStyle: { backgroundColor: '#243039', }, })} /> <Stack.Screen name="Login" component={LoginView} options={{headerStyle: {backgroundColor: '#243039'}, headerTitleStyle: {color: "white"}, headerTintColor: "white" }} /> <Stack.Screen name="User" component={User} /> <Stack.Screen name="ListMusicsArtist" component={ListMusicsArtist} options={{headerStyle: {backgroundColor: '#243039'}, headerTitle: "", headerTintColor: "white"}} /> </Stack.Navigator> </Context.Provider> </NavigationContainer> </StoreProvider> ); } export default App; const styles = StyleSheet.create({ header: { backgroundColor: '#243039', }, headerLogin: { backgroundColor: '#587788', }, icon: { color: 'white', }, }); <file_sep>/Intify-new/Server/Controller/MusicController.js const Music = require("../Model/Music"); const { arrayObjMongoose } = require("../config/mongooseConvert"); const User = require("../Model/User"); const { findOne } = require("../Model/User"); const fs = require("fs"); const path = require("path"); const deleteFile = require("../config/deleteFile"); class MusicController { editMusic(req, res, next) { User.findOne({ username: req.user.name }, (err, user) => { if (err) return res.json({ status: 404, descp: err, }); if (!user) return res.json({ status: 404, }); else { Music.updateOne({ _id: req.params._id }, req.body) .then( res.json({ status: 200, descp: "Chinh sua thanh cong", }) ) .catch((error) => res.json({ status: 404, descp: error, }) ); } }); } //GET ListMusic showListMusic(req, res, body) { Music.find({}) .then((music) => res.json({ musics: music })) .catch((error) => next(error)); } showListArtist(req, res, body) { User.find({ hasUpload: true }) .then((users) => { const arrArtist = []; users.map((user) => { const artist = {}; artist.id = user.id; artist.nameApp = user.nameApp; artist.imgArtist = user.imgArtist; arrArtist.push(artist); }); res.json({ artists: arrArtist }); }) .catch((error) => res.json({ status: 404, descp: error, }) ); } musicsOfArtist(req, res, body) { Music.find({ idUser: req.params.id }) .then((music) => { res.json({ status: 200, musics: music, }); }) .catch((error) => res.json({ status: 404, err: error, }) ); } //POST AddNewMusic addNewMusic(req, res, body) { User.findOne({ username: req.user.username }, (err, user) => { if (err) return res.json({ status: 404, descp: err, }); User.updateOne({ _id: user._id }, { hasUpload: true }) .then() .catch((error) => res.json({ status: 404, descp: error, }) ); const newMusic = req.body; newMusic.idUser = user._id; newMusic.img = "http://192.168.0.18:3002/" + req.files.img[0].path.split("\\").splice(1).join("/"); newMusic.mp3 = "http://192.168.0.18:3002/" + req.files.mp3[0].path.split("\\").splice(1).join("/"); const music = new Music(newMusic); music .save() .then( res.json({ status: 200, descp: "create new music success", }) ) .catch((error) => res.json({ status: 404, descp: error, }) ); }); } deleteMusic(req, res, body) { Music.findById(req.params.id) .then((music) => { deleteFile(music.img); deleteFile(music.mp3); Music.findByIdAndDelete(req.params.id) .then( res.json({ status: 200, msg: "success delete", }) ) .catch((err) => res.json({ status: 404, msg: err, }) ); }) .catch((err) => res.json({ status: 404, msg: err, }) ); } } module.exports = new MusicController(); <file_sep>/Intify-new/Server/DB/dbConnect.js const mongoose = require('mongoose'); async function Connect () { try{ await mongoose.connect('mongodb://localhost:27017/Intify'); console.log("kết nối thành công nè") } catch(error){ console.log("lõi nè:" + error) } } module.exports= {Connect}<file_sep>/Intify-new/Intify/Component/User.js import React, {Component} from 'react'; import {createBottomTabNavigator} from '@react-navigation/bottom-tabs'; import InfomationUser from './UserComponent/InfomationUser'; import UploadMusic from './UserComponent/UploadMusic'; import {StatusBar} from 'react-native'; import MyUpload from './UserComponent/MyUpload'; import { FontAwesomeIcon } from '@fortawesome/react-native-fontawesome'; import {faUserCircle, faUpload, faClipboardList, faList} from '@fortawesome/free-solid-svg-icons'; const Tab = createBottomTabNavigator(); export default class User extends Component { render() { return ( <Tab.Navigator> <Tab.Screen options={{ headerShown: false, title: "User", tabBarIcon: () => <FontAwesomeIcon icon={faUserCircle} size={20} style={{color:"#307ecc"}}/> }} name="InformationUser" component={InfomationUser} /> <Tab.Screen options={{ headerShown: false, title: "Upload", tabBarIcon: () => <FontAwesomeIcon icon={faUpload} size={20} style={{color:"#307ecc"}}/> }} name="UploadMusic" component={UploadMusic} /> <Tab.Screen options={{ headerShown: false, title: "My List", tabBarIcon: () => <FontAwesomeIcon icon={faList} size={20} style={{color:"#307ecc"}}/> }} name="MyList" component={MyUpload} /> </Tab.Navigator> ); } } <file_sep>/Intify-new/Intify/Component/FullMusic.js import React, {Component, useEffect} from 'react'; import {Text, Button, View, Image, StyleSheet, FlatList} from 'react-native'; import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'; import { faPauseCircle, faPlayCircle, faEllipsisV, faHeart, faVolumeUp, } from '@fortawesome/free-solid-svg-icons'; import Slider from '@react-native-community/slider'; import systemSetting from 'react-native-system-setting'; import {connect} from 'react-redux'; import {addPlaying} from '../Redux/Action/isPlayingAction'; import Context from './Context'; import SplashScreen from './SplashScreen'; import FullLyrics from './ListMusicsArtist' const Sound = require('react-native-sound'); Sound.setCategory('Playback', true); class FullMusic extends Component { constructor(props) { super(props); this.state = { music: {}, musicPlaying: {}, timeDurarion: 0, currentTime: 0, setTime: {}, status: true, visible: false, volume: 0, }; } async componentDidMount() { await systemSetting.getVolume().then(volume => { this.setState({ volume: volume, }); }); this.setState( { music: this.props.rePlaying, }, async () => { const musicPlaying = new Sound( this.state.music.mp3, Sound.MAIN_BUNDLE, err => { if (err) { consoloe.log(err); } else { musicPlaying.nameArtist = this.state.music.nameArtist; musicPlaying.nameSong = this.state.music.nameSong; musicPlaying.img = this.state.music.img; this.setState({ musicPlaying: musicPlaying, timeDurarion: musicPlaying.getDuration(), }); } }, ); }, ); } async componentWillUnmount() { clearInterval(this.state.setTime); } convertTime(time) { const mn = Math.floor(time / 60); const sc = time % 60; return mn + ':' + sc; } changedVolume(index) { systemSetting.setVolume(index); this.setState({ volume: index, }); } isEmpty(obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) return true; } return false; } statusMusic(status, value) { this.setState( { status: status, }, async () => { const {musicPlaying} = this.state; if (status) { this.props.addPlaying(musicPlaying); clearInterval(this.state.setTime); musicPlaying.setCurrentTime(value); musicPlaying.play(success => { if (success) { console.log('successfully finished playing'); } else { console.log('playback failed due to audio decoding errors'); } }); this.state.setTime = setInterval(() => { musicPlaying.getCurrentTime(second => { this.setState({ currentTime: second, }); }); }, 1000); } else { musicPlaying.pause(); clearInterval(this.state.setTime); musicPlaying.setCurrentTime(value); musicPlaying.getCurrentTime(second => { this.setState({ currentTime: second, }); }); } }, ); } renderBotView() { return ( <> <View style={styles.botPlay}> <View style={{flex: 2, flexDirection: 'row'}}> <View style={{flex: 1, flexDirection: 'row', marginLeft: 50}}> <FontAwesomeIcon icon={faVolumeUp} size={20} onPress={() => { this.setState({ visible: !this.state.visible, }); setTimeout(() => { this.setState({ visible: !this.state.visible, }); }, 4000); }} style={styles.iconVolume} /> {this.state.visible ? ( <View style={styles.modal} animationType={'fade'} transparent={true} visible={this.state.visible}> <View style={{ backgroundColor: 'white', height: 30, width: 175, borderRadius: 15, }}> <Slider style={styles.sliderVolume} minimumValue={0} maximumValue={1} value={this.state.volume} step={0.1} onValueChange={value => this.changedVolume(value)} minimumTrackTintColor="#243039" maximumTrackTintColor="#000000" /> </View> </View> ) : ( <></> )} </View> </View> <View style={styles.sliderView}> <Slider style={styles.slider} minimumValue={0} maximumValue={this.state.timeDurarion} value={this.state.currentTime} onValueChange={value => this.statusMusic(this.state.status, value) } minimumTrackTintColor="#FFFFFF" maximumTrackTintColor="#000000" /> <View style={styles.timeView}> <Text>{this.convertTime(parseInt(this.state.currentTime))}</Text> <Text>{this.convertTime(parseInt(this.state.timeDurarion))}</Text> </View> </View> <View style={{flexDirection: 'row', flex: 2}}> <Context.Consumer> {context => ( <FontAwesomeIcon icon={ this.state.musicPlaying._playing ? faPauseCircle : faPlayCircle } onPress={async () => { this.state.musicPlaying._playing ? (context.setMusicPlaying(this.state.musicPlaying), this.statusMusic(false, this.state.currentTime)) : (context.setMusicPlaying(this.state.musicPlaying), this.statusMusic(true, this.state.currentTime)); }} style={styles.iconPlayPause} size={40} /> )} </Context.Consumer> </View> </View> </> ); } renderTopView(music) { return ( <> <View style={styles.header}> <Image source={{uri: music.img}} style={styles.img}></Image> </View> <View style={styles.title}> <FontAwesomeIcon icon={faEllipsisV} style={styles.icon} size={20} /> <View> <Text style={styles.titleNameSong}> {music.nameSong.length > 25 ? music.nameSong.slice(0, 25).concat('...') : music.nameSong} </Text> <Text style={styles.titleNameArtist}> {music.nameArtist.length > 30 ? music.nameArtist.slice(0, 30).concat('...') : music.nameArtist} </Text> </View> <FontAwesomeIcon icon={faHeart} style={styles.icon} size={20} /> </View> </> ); } render() { const {music} = this.state; return this.isEmpty(this.state.musicPlaying) ? ( <View style={styles.main}> <View style={styles.viewTop}>{this.renderTopView(music)}</View> <View style={styles.viewBot}>{this.renderBotView(music)}</View> </View> ) : ( <SplashScreen></SplashScreen> ); } } const styles = StyleSheet.create({ header: { flex: 8, marginTop: 20, }, title: { flex: 2, marginTop: 30, flexDirection: 'row', justifyContent: 'space-around', }, main: { flex: 1, backgroundColor: '#364855', justifyContent: 'space-around', }, img: { height: '100%', width: 250, borderRadius: 5, marginLeft: 'auto', marginRight: 'auto', }, viewTop: { flex: 1, }, viewBot: { flex: 1, justifyContent: 'flex-end', height: 335, }, botPlay: { width: '97%', flex: 0.9, marginRight: 'auto', marginLeft: 'auto', backgroundColor: 'rgba(96, 103, 109, 0.56)', borderTopRightRadius: 10, borderTopLeftRadius: 10, }, icon: { marginTop: 30, color: '#C4C4C4', }, iconPlayPause: { marginTop: 30, color: '#C4C4C4', marginLeft: 'auto', marginRight: 'auto', }, iconVolume: { marginTop: 30, color: '#C4C4C4', marginTop: 'auto', marginBottom: 'auto', }, titleNameSong: { textAlign: 'center', color: 'white', fontSize: 20, }, titleNameArtist: { textAlign: 'center', color: 'white', fontSize: 15, }, timeView: { flexDirection: 'row', justifyContent: 'space-around', }, slider: { marginRight: 'auto', marginLeft: 'auto', width: 319, height: 40, }, sliderVolume: { marginRight: 'auto', marginLeft: 'auto', marginTop: 'auto', marginBottom: 'auto', width: 150, height: 40, }, sliderView: { flex: 1, }, modal: { marginTop: 'auto', marginBottom: 'auto', marginLeft: 10, height: 30, margin: 0, }, icon: { color: '#C4C4C4', }, }); const mapStateToProps = state => { return { rePlaying: state.isPlayingReducer.rePlaying, isPlaying: state.isPlayingReducer.isPlaying, }; }; const mapDispatchToProps = dispatch => { return { addPlaying: music => { dispatch(addPlaying(music)); }, }; }; export default connect(mapStateToProps, mapDispatchToProps)(FullMusic); <file_sep>/Intify-new/Intify/Component/ListMusicsArtist.js import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'; import React, {Component} from 'react'; import {View, StyleSheet, Image, Text, Button, ScrollView} from 'react-native'; import LinearGradient from 'react-native-linear-gradient'; import api from '../api'; import MusicItem from './MusicItem'; import {faUserCircle} from '@fortawesome/free-solid-svg-icons'; export default class ListMusicsArtist extends Component { constructor() { super(); this.state = { musicsOfArt: [], }; } async componentDidMount() { try { await fetch( 'http://' + api + ':3002/musics/' + this.props.route.params.id, ) .then(async res => { const resJson = await res.json(); this.setState({ musicsOfArt: resJson.musics, }); }) .catch(error => console.error(error)); } catch (error) { console.error(error); } } renderFullLyrics(params) { return ( <> <LinearGradient colors={['#FFFFFF21', '#FFFFFF00']} style={styles.area_Lyric}> <View style={{flex: 1}}> {params.imgArtist ? ( <Image source={{uri: params.imgArtist}} style={styles.img}></Image> ) : ( <FontAwesomeIcon style={styles.iconAva} icon={faUserCircle} size={150} /> )} <Text style={styles.name}>{params.nameApp}</Text> </View> <View style={styles.listMusics}> <ScrollView showsVerticalScrollIndicator={false}> {this.state.musicsOfArt.map((music, index) => ( <MusicItem key={index} music={music} navigation={this.props.navigation} /> ))} </ScrollView> </View> </LinearGradient> </> ); } render() { const {params} = this.props.route; return ( <View style={styles.mainFullLyrics}> <View style={styles.mainTop}></View> <View style={styles.mainBot}>{this.renderFullLyrics(params)}</View> </View> ) } } const styles = StyleSheet.create({ mainFullLyrics: { backgroundColor: '#364855', flex: 1, }, iconAva: { top: -100, height: 160, width: 160, borderRadius: 5, marginLeft: 'auto', marginRight: 'auto', color: "#364855" }, mainTop: { flex: 1, }, mainBot: { flex: 4, }, img: { top: -100, height: 160, width: 160, borderRadius: 5, marginLeft: 'auto', marginRight: 'auto', }, area_Lyric: { marginLeft: 'auto', marginRight: 'auto', flex: 1, width: '95%', borderTopRightRadius: 10, borderTopLeftRadius: 10, flexDirection: 'column', justifyContent: 'space-evenly', }, listMusics: { flex: 4, }, name: { color: 'white', top: -90, fontSize: 25, fontWeight: 'bold', marginLeft: 'auto', marginRight: 'auto', }, }); <file_sep>/Intify-new/Intify/Component/Modal-Overlays/SmallPlaying.js import React, {Component} from 'react'; import {TouchableOpacity, View, Image, Text, StyleSheet} from 'react-native'; import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'; import {faPauseCircle, faPlayCircle} from '@fortawesome/free-solid-svg-icons'; import Slider from '@react-native-community/slider'; import Context from '../Context'; import {icon} from '@fortawesome/fontawesome-svg-core'; export default class SmallPlaying extends Component { constructor(props) { super(props); this.state = { isPlaying: this.props.music._playing, }; } isEmpty(obj) { for (var key in obj) { if (obj.hasOwnProperty(key)) return true; } return false; } render() { const {music} = this.props; if (this.isEmpty(music)) { return ( <View style={styles.itemView}> <View style={{marginBottom: 'auto', marginTop: 'auto'}}> <Image source={{uri: music.img}} style={styles.img}></Image> </View> <View style={styles.itemContent}> <View style={{flexDirection: 'row', flex: 1}}> <Text style={styles.titleNameSong}>{music.nameSong}</Text> <Text style={styles.titleNameSong}> - </Text> <Text style={styles.titleNameArtist}>{music.nameArtist}</Text> </View> <View style={{flexDirection: 'row', flex: 1}}> {/* <Context.Consumer> {(context) => */} <FontAwesomeIcon icon={this.state.isPlaying ? faPlayCircle : faPauseCircle} onPress={async () => { music._playing ? (this.setState({ isPlaying: !this.state.isPlaying, }), music.pause()) : (this.setState({ isPlaying: !this.state.isPlaying, }), music.play()); }} style={styles.iconPlayPause} size={30} /> {/* } </Context.Consumer> */} </View> </View> </View> ); } else { return <></>; } } } const styles = StyleSheet.create({ itemView: { backgroundColor: 'white', flexDirection: 'row', height: 82, zIndex: 3, }, itemContent: { flexDirection: 'column', marginLeft: 'auto', marginRight: 'auto', }, img: { marginLeft: 20, height: 75, width: 75, borderRadius: 5, }, titleNameSong: { marginTop: 'auto', marginBottom: 'auto', color: 'black', fontSize: 15, }, titleNameArtist: { marginTop: 'auto', marginBottom: 'auto', color: 'black', fontSize: 15, }, iconPlayPause: { color: '#C4C4C4', marginLeft: 'auto', marginRight: 'auto', }, slider: { marginRight: 'auto', marginLeft: 'auto', width: 250, height: 40, }, }); <file_sep>/Intify-new/Intify/Component/UserItem.js import React, {Component} from 'react'; import {View, Text, StyleSheet, Image, TouchableOpacity} from 'react-native'; import {FontAwesomeIcon} from '@fortawesome/react-native-fontawesome'; import {faUserCircle} from '@fortawesome/free-solid-svg-icons'; export default class UserItem extends Component { render() { const {artist, navigation} = this.props; return ( <TouchableOpacity onPress={()=> { navigation.push('ListMusicsArtist', artist) }} > <View style={styles.view}> {artist.imgArtist ? ( <Image style={styles.imgAvaBac} source={{uri: artist.imgArtist}} blurRadius={100}></Image> ) : ( <FontAwesomeIcon style={styles.avatar} icon={faUserCircle} size={150} /> )} <Image style={styles.imgAvaBac2} source={{uri: artist.imgArtist}} blurRadius={20}></Image> <Image style={styles.imgAva} source={{uri: artist.imgArtist}}></Image> <Text style={styles.name}>{artist.nameApp}</Text> </View> </TouchableOpacity> ); } } const styles = StyleSheet.create({ view: { marginBottom: 'auto', marginTop: 'auto', height: 200, width: 200, marginLeft: 20, marginRight: 10, }, avatar: { marginBottom: 20, marginLeft: 'auto', marginRight: 'auto', color: '#307ecc', }, name: { position: 'absolute', marginTop: -13, shadowColor: "black", textShadowOffset: { width: 2, height: 2 }, textShadowRadius:10, marginLeft: 20, color: 'white', fontSize: 25, fontWeight: 'bold', textAlign: 'center', }, imgAva: { height: 152, width: 152, marginTop: 20, borderWidth: 1, borderRadius: 10, marginLeft: 50, marginRight: 'auto', }, imgAvaBac: { position: 'absolute', height: 172, width: 172, top: -10, left: 10, opacity: 0.2, borderWidth: 2, borderRadius: 10, marginLeft: 'auto', marginRight: 'auto', }, imgAvaBac2: { position: 'absolute', height: 162, width: 162, top: 5, left: 30, opacity: 0.3, borderWidth: 2, borderRadius: 10, marginLeft: 'auto', marginRight: 'auto', }, }); <file_sep>/Intify-new/Intify/Component/ListMusics.js import React, {Component} from 'react'; import {View, ScrollView, StyleSheet, Text, RefreshControl, StatusBar} from 'react-native'; import getListMusic from '../Server'; import MusicItem from './MusicItem'; import LinearGradient from 'react-native-linear-gradient'; import FullMusic from './FullMusic'; import {connect} from 'react-redux'; import {thisExpression} from '@babel/types'; import SmallPlaying from './Modal-Overlays/SmallPlaying'; import Context from './Context' import SplashScreen from './SplashScreen'; import UserItem from './UserItem'; import { combineReducers } from 'redux'; import api from '.././api' export default class ListMusics extends Component { constructor(props) { super(props); this.state = { musicsList: [], artistsList: [], music: {}, refresh: false }; } callApiMyList() { getListMusic() .then(json => { this.setState({musicsList: json.musics}); }) .catch(err => consoloe.log(err)); } async componentDidMount() { this.callApiMyList() try { await fetch('http://'+ api +':3002/artists') .then(async res => { const resJson = await res.json() this.setState({ artistsList: resJson.artists }) }) .catch(error => console.error(error)) } catch (error) { console.error(error); } } refreshList(){ this.setState({ refresh: !this.state.refresh }) this.callApiMyList() setTimeout(() => { this.setState({ refresh: !this.state.refresh }) }, 2000); } render() { const {navigation} = this.props; return ( this.state.musicsList.length > 0 ? <View style={{flex: 1, backgroundColor: '#364855'}}> <StatusBar hidden={false} animated={true} backgroundColor="#243039"/> <View style={styled.topArea}> <ScrollView horizontal={true} showsHorizontalScrollIndicator={false}> {this.state.artistsList.map((artist, index) => <UserItem navigation={navigation} key={index} artist={artist}/> )} </ScrollView> </View> <View style={styled.bottomArea}> <Text style={styled.allList}>All List</Text> <LinearGradient colors={['#FFFFFF15', '#FFFFFF01']} style={styled.scrollView}> <ScrollView refreshControl={ <RefreshControl refreshing={this.state.refresh} onRefresh={() => this.refreshList(this.state.refresh)} /> }> {this.state.musicsList.map((music, index) => ( <MusicItem navigation={navigation} music={music} key={index} /> ))} </ScrollView> </LinearGradient> </View> <Context.Consumer>{context => <SmallPlaying music={context.isPlaying}/>} </Context.Consumer> </View> : <SplashScreen></SplashScreen> ); } } const styled = StyleSheet.create({ bottomArea: { flex: 6, marginLeft: 5, marginRight: 5, borderTopLeftRadius: 5, borderTopRightRadius: 5, }, topArea: { flex: 4, }, scrollView: { flex: 1, marginLeft: 'auto', marginRight: 'auto', width: '99.5%', borderTopRightRadius: 5, borderTopLeftRadius: 5, }, allList: { fontSize: 30, color: 'white', }, });
5ba9cadc556b8bd0b188235c27ceaf0d10702aa8
[ "JavaScript", "Markdown" ]
19
JavaScript
thinhtanpham/Intify-Music-App-Mobile
7139c2bda21ca1bbb4b32822115c25b94b48080c
be97136bf8a32060e4f7b9118a5fd4a6fafcbe14
refs/heads/master
<file_sep>// ==UserScript== // @name Raide Facile [modified by Deberron] // @namespace Snaquekiller // @version 8.6.1 // @author Snaquekiller + Autre + Deberron + Alu // @creator snaquekiller // @description Raide facile // @require https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js // @require https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js // @homepage http://lastworld.etenity.free.fr/ogame/raid_facile // @updateURL http://lastworld.etenity.free.fr/ogame/raid_facile/userscript.header.js // @downloadURL http://lastworld.etenity.free.fr/ogame/raid_facile/72438.user.js // @include http://*.ogame.gameforge.com/game/index.php?page=* // @exclude http://*.ogame.gameforge.com/game/index.php?page=buddies* // @exclude http://*.ogame.gameforge.com/game/index.php?page=notices* // @exclude http://*.ogame.gameforge.com/game/index.php?page=search* // @exclude http://*.ogame.gameforge.com/game/index.php?page=combatreport* // @exclude http://*.ogame.gameforge.com/game/index.php?page=eventList* // @exclude http://*.ogame.gameforge.com/game/index.php?page=jump* // @exclude http://*.ogame.gameforge.com/game/index.php?page=phalanx* // @exclude http://*.ogame.gameforge.com/game/index.php?page=techtree* // @exclude http://*.ogame.gameforge.com/game/index.php?page=techinfo* // @exclude http://*.ogame.gameforge.com/game/index.php?page=globalTechtree* // @grant GM_info // @grant GM_getValue // @grant GM_setValue // @grant GM_deleteValue // @grant GM_addStyle // @grant GM_xmlhttpRequest // ==/UserScript== // Sujet sur le forum officiel : http://board.ogame.fr/index.php?page=Thread&threadID=978693 /* Pour éditer ce fichier je conseille un de ces éditeurs lien: https://code.visualstudio.com/ lien: http://www.sublimetext.com/ lien: http://notepad-plus-plus.org/fr */ /* test encodage ces caractère doivent être ben accentués et bien écrits, sinon c'est qu'il y a un problème aâàã eéêè iîì ñ oôòõ uûù € */ /// <reference path="typings/greasemonkey/greasemonkey.d.ts"/> /* global XPathResult */ /* global chrome */ /** Logger **///{region function Logger() { this.logs = []; this.errors = []; } Logger.prototype.log = function(message) { if (info && !info.args.raidFacileDebug) { return; } var messageParts = []; for (var i = 0; i < arguments.length; i++) { messageParts.push(arguments[i]); } this.logs.push(messageParts); console.debug.apply(console, ['[raid facile]'].concat(messageParts)); }; Logger.prototype.error = function(message) { var messageParts = []; for (var i = 0; i < arguments.length; i++) { messageParts.push(arguments[i]); } this.errors.push(messageParts); console.error.apply(console, ['[raid facile]'].concat(messageParts)); }; var logger = new Logger(); //}endregion logger.log('Salut :)'); /** Variables utilitaires **///{region // Si jQuery n'est pas dans le scope courant c'est qu'il est dans le scope de l'unsafeWindow if (typeof $ === 'undefined') { var $; if(typeof jQuery === 'undefined'){ $ = unsafeWindow.$; } else{ $ = jQuery; } } // Variable contenant tout un tas d'informations utiles, pour ne pas laisser les variables dans le scope global. var info; /** Initialise et rempli la variable info */ var remplirInfo = function () { var parseOgameMeta = function () { var content, name; var metaVars = $('meta[name^=ogame-]', document.head); info.ogameMeta = {}; for (var i = 0; i < metaVars.length; ++i) { name = metaVars[i].getAttribute('name'); content = metaVars[i].getAttribute('content'); info.ogameMeta[name] = content; } }; info = { siteUrl: 'http://lastworld.etenity.free.fr/ogame/raid_facile/', firefox: navigator.userAgent.indexOf("Firefox") > -1 || navigator.userAgent.indexOf("Iceweasel") > -1, chrome: navigator.userAgent.indexOf("Chrome") > -1, opera: navigator.userAgent.indexOf('Opera') > -1, url: location.href, serveur: location.hostname, univers: location.hostname.replace('ogame.', ''), date: new Date(), startTime: Date.now(), session: $('meta[name=ogame-session]').attr('content') || location.href.replace(/^.*&session=([0-9a-f]*).*$/i, "$1"), pseudo: $('meta[name=ogame-player-name]').attr('content'), playerId: $('meta[name=ogame-player-id]').attr('content') // version // Tampermonkey // ogameMeta // args // hash }; parseUrl(); parseOgameMeta(); if (typeof chrome !== 'undefined' && chrome.runtime && chrome.runtime.getManifest) { // pour les extensions Chrome info.version = chrome.runtime.getManifest().version; info.tampermonkey = false; } if (typeof GM_info !== 'undefined') { // pour greasemonkey et ceux qui ont GM_info (greasemonkey et tampermonkey) info.version = GM_info.script.version; info.tampermonkey = GM_info.scriptHandler === "Tampermonkey"; } }; /** Parsing des paramètres situé après le "?" dans l'url, stoque les résultat dans info */ var parseUrl = function () { info.args = {}; info.hash = {}; var argString = location.search.substring(1).split('&'); var i, arg, kvp; if (argString[0] !== '') { for (i = 0; i < argString.length; i++) { arg = decodeURIComponent(argString[i]); if (arg.indexOf('=') === -1) { info.args[arg] = true; } else { kvp = arg.split('='); info.args[kvp[0]] = kvp[1]; } } } if (location.hash.length > 0) { var hashString = location.hash.substring(1).split('&'); for (i = 0; i < hashString.length; i++) { arg = decodeURIComponent(hashString[i]); if (arg.indexOf('=') === -1) { info.args[arg] = true; info.hash[arg] = true; } else { kvp = arg.split('='); info.args[kvp[0]] = kvp[1]; info.hash[kvp[0]] = kvp[1]; } } } }; //}endregion /** Fonctions de compatibilité **///{region // Si ces fonctions n'existent pas, elle sont créées if (typeof GM_getValue === 'undefined') { GM_getValue = function (key, defaultValue) { var retValue = localStorage.getItem(key); if (!retValue) { retValue = defaultValue; } return retValue; }; } if (typeof GM_setValue === 'undefined') { GM_setValue = function (key, value) { localStorage.setItem(key, value); }; } if (typeof GM_deleteValue === 'undefined') { GM_deleteValue = function (key) { localStorage.removeItem(key); }; } if (typeof GM_addStyle === 'undefined') { var addStyle = function (css, url) { if (url) { $('<link rel="stylesheet" type="text/css" media="screen" href="' + url + '">').appendTo(document.head); } else { $('<style type="text/css">' + css + '</style>').appendTo(document.head); } }; } else { var addStyle = function (css, url) { if (url) { $('<link rel="stylesheet" type="text/css" media="screen" href="' + url + '">').appendTo(document.head); } else { GM_addStyle(css); } }; } //}endregion /** Classe gérant le stockage de données **///{region function Stockage(namespace) { this.storageKeyName = 'RaidFacile ' + info.univers + ' ' + info.ogameMeta['ogame-player-id'] + ' ' + namespace; /* Le mapping sert à : - ce que ça prenne moins de place dans le stockage, mais qu'on ait toujours un texte compréhensible dans le code - définir la valeur par défaut au cas ou rien n'est encore stocké */ this.mapping = { // 'nom complet': ['nom court', 'valeur par défaut'] 'attaquer nouvel onglet': ['a', 1], 'couleur attaque': ['b', '#c7050d'], 'couleur attaque retour': ['c', '#e75a4f'], 'couleur attaque2': ['d', '#c7050d'], 'couleur attaque2 retour': ['e', '#e75a4f'], 'couleur espionnage': ['f', '#FF8C00'], 'couleur espionnage retour': ['f_r', ''], 'touche raid suivant': ['trs', 80], // touche P 'langue': ['l', navigator.language.substr(0,2)], 'popup duration': ['mt', 1000], }; if (!this.checkMappingCount()) { throw 'Erreur de mapping, ya pas le bon nombre!'; } } Stockage.prototype = { /** Renvoie la valeur d'une donnée en mémoire */ get: function (nom) { var key = this.mapping[nom][0]; if (this.data.hasOwnProperty(key)) { return this.data[key]; } else { return this.mapping[nom][1]; } }, /** Change la valeur en mémoire d'une donnée */ set: function (nom, valeur) { this.data[this.mapping[nom][0]] = valeur; return this; }, /** Charge en mémoire les données du stockage */ load: function () { this.data = JSON.parse(GM_getValue(this.storageKeyName, '{}')); return this; }, /** Sauvegarde dans le stockage les données en mémoire */ save: function () { GM_setValue(this.storageKeyName, JSON.stringify(this.data)); return this; }, /** Vérification qu'il n'y a pas eu d'erreur de mapping (que chaque valeur n'est utilisée qu'une fois) */ checkMappingCount: function () { var mappingCount = 0; var mappingCountCheck = 0; var mappingKeys = {}; for (var prop in this.mapping) { if (this.mapping.hasOwnProperty(prop)) { ++mappingCount; mappingKeys[this.mapping[prop][0]] = true; } } for (prop in mappingKeys) { if (mappingKeys.hasOwnProperty(prop)) { ++mappingCountCheck; } } return mappingCount === mappingCountCheck; } }; var stockageOption; var stockageData; //}endregion /** Classe de communication avec la page **///{region var Intercom = function () { this.loaded = false; this.listeAttente = []; this.listen(); }; Intercom.prototype = { /** send envoie un message à l'autre classe Intercom action (string) le nom de l'action data (object)(facultatif) les données à transmettre */ send: function (action, data) { // Si l'autre intercom n'est pas encore chargé on met les messages en attente if (this.loaded === false) { this.listeAttente.push([action, data]); return; } var données = { fromPage: false, namespace: 'Raid facile', action: action, data: data === undefined ? {} : data }; window.postMessage(données, '*'); }, /** Permet de recevoir les messages de l'autre intercom */ listen: function () { window.addEventListener('message', this.received.bind(this), false); }, /** Défini les actions à effectuer en cas de message reçu */ received: function (message) { // On s'assure que le message est bien pour nous if (message.data.namespace !== 'Raid facile' || message.data.fromPage === false) { return; } switch (message.data.action) { case 'loaded': // l'autre intercom est chargé, on peut donc traiter les messages en attente this.loaded = true; this.traiterListeAttente(); break; default: var handler = eventHandlers[message.data.action]; if (!handler) { logger.error('No handler for action :', message.data.action); break; } handler(message.data); } }, traiterListeAttente: function () { // On envoie tous les messages de la liste d'attente puis on vide la liste for (var i = 0; i < this.listeAttente.length; ++i) { this.send.apply(this, this.listeAttente[i]); } this.listeAttente = []; } }; var intercom; //}endregion /** Classe d'internationalisation **///{region function I18n() { this.fr = {}; this.en = {}; this.ro = {}; this.es = {}; } I18n.prototype = { get: function (key) { var local = this[langue][key]; if (local === undefined && key !== 'missing_translation') { logger.error(i18n('missing_translation') + ' : "' + key + '"'); } if (local === undefined && langue !== 'en') { local = this.en[key]; } if (local === undefined && langue !== 'fr') { local = this.fr[key]; } return local || '##' + key + '##'; }, exporter: function (langue) { return this[langue]; }, importer: function (langue, data) { this[langue] = data; } }; var i18n; //}endregion /** Fonctions de correction **///{region /** Ajuste la taille de la "box" d'ogame, au cas où le tableau prend trop de place pour le menu */ function ajusterTailleBox() { var tailleBox = $('#box').width(); var tailleMenuGauche = $('#links').outerWidth(true); var tailleMenuPlanetes = $('#rechts').outerWidth(true); var tailleRaidFacile = $('#div_raide_facile').outerWidth(true); var changementTaille = (tailleMenuGauche + tailleMenuPlanetes + tailleRaidFacile) - tailleBox; if (changementTaille > 0) { $('#box').width(tailleBox + changementTaille); $('#contentWrapper').width($('#contentWrapper').width() + changementTaille); var bannerSkyscraperLeft = parseInt($('#banner_skyscraper').css('left').slice(0, -2)) + changementTaille; $('#banner_skyscraper').css('left', bannerSkyscraperLeft); } } /** Certains select s'affichent façon ogame mais avec une largeur de 0px, cette fonction corrige le problème * en paramètre la fonction prend un objet jQuery contenant 1 ou plusieurs select */ function ogameStyleSelectFix(selects) { var ok = false; for (var i = 0; i < selects.length; ++i) { var select = $(selects[i]); var span = select.next(); if (span.width() === 0) { span.remove(); select.removeClass('dropdownInitialized'); ok = true; } select.addClass('fixed'); } if (ok) { intercom.send('ogame style'); } } //}endregion /** Fonctions utilitaires **///{region /** un des première fonction à être appelée, initialise un peu tout */ function init() { remplirInfo(); logger.log('Version', info.version); setPage(); if (info.page === 'optionsRaidFacile') { // impossible d'afficher la page options au départ on affiche donc le tableau info.hash.raidFacile = 'tableau'; } rebuildHash(); logger.log('Page', info.page); logger.log('Navigateur', JSON.stringify({ chrome: info.chrome, firefox: info.firefox, opera: info.opera, tampermonkey: info.tampermonkey })); intercom = new Intercom(); stockageOption = new Stockage('options'); stockageData = new Stockage('données'); stockageOption.load(); stockageData.load(); i18n = instanciateAsFunction(I18n, 'get'); window.addEventListener('hashchange', onHashChange, false); window.addEventListener('keyup', keyShortcut, false); plusTard(checkUpdate); logger.log('Init ok'); } function init2() { logger.log('Init 2'); afficher_lien(); logger.log('Init 2 ok'); } /** Fait l'action appropiée quand une touche du clavier est appuyée */ function keyShortcut(eventObject) { // logger.log(eventObject.type , eventObject.which, String.fromCharCode(eventObject.which)); if (eventObject.which === stockageOption.get('touche raid suivant')) { if (info.page === 'tableauRaidFacile') { eventObject.preventDefault(); eventObject.stopPropagation(); var ligneAttaquer = $('#corps_tableau2 > tr:not(.attaque):eq(0)'); var lienAttaquer = $('> td.boutonAttaquer > a', ligneAttaquer); lienAttaquer[0].click(); ligneAttaquer.addClass('attaque'); } } } /** Instancie une classe mais en mode fonction (comme jQuery) * mainMethod correspond à la méthode qui sera utilisé en mode raccourci * exemple : i18n(...) est identique à i18n.get(...) si mainMethod = 'get' */ function instanciateAsFunction(ClassObject, mainMethod) { var instance = new ClassObject(); var func = instance[mainMethod].bind(instance); for (var method in ClassObject.prototype) { func[method] = instance[method].bind(instance); } return func; } /** Permet d'exécuter une fonction, mais plus tard */ function plusTard(callback, temps) { if (temps === undefined) { temps = Math.random() * 1000 + 1500; // entre 1.5s et 2.5s } window.setTimeout(callback, temps); } /** Met à jour le hash et les variables correspondantes * Supprime le "go" du hash s'il est présent */ function rebuildHash() { var lengthDiff = 0; if (info.hash.go !== undefined) { delete info.hash.go; lengthDiff++; } var newHash = []; for (var key in info.hash) { if (info.hash[key] === true) { newHash.push(key); } else { newHash.push(key + '=' + info.hash[key]); } } if (newHash.length === 0 && lengthDiff === 0) { return; } location.hash = newHash.join('&'); parseUrl(); } /** Fait l'action appropriée quand le hash de la page change */ function onHashChange(/*eventObject*/) { parseUrl(); if (info.hash.go !== undefined) { rebuildHash(); location.reload(); } } /** met à jour info.page en fonction de l'URL */ function setPage() { info.page = info.args.page; if (info.args.raidefacil === 'scriptOptions' || info.args.raidFacile === 'tableau') { info.page = 'tableauRaidFacile'; } else if (info.args.raidFacile === 'options') { info.page = 'optionsRaidFacile'; } } /** Affiche ou masque les options si elle sont déjà affichées elles seront masquées et le tableau des scans sera affiché, si elle sont masquée elle seront affichées et le tableau des scans sera masqué */ function afficherMasquerOptions(eventObject) { eventObject.preventDefault(); if ($('#option_script').css('display') === 'none') { info.hash.raidFacile = 'options'; } else { info.hash.raidFacile = 'tableau'; } $('#option_script, #div_tableau_raide_facile').toggle(); rebuildHash(); } /** Affiche le lien de Raid facile */ function afficher_lien() { var selector; // si on est sur la page mouvements on prend l'url de la page flotte, sinon celle de la page mouvements if (info.args.page === 'movement') { selector = '#menuTable > li:nth-child(8) > a.menubutton'; } else { selector = '#menuTable > li:nth-child(8) > .menu_icon > a'; } var url = new Url(document.querySelector(selector).getAttribute('href')).hashes(info.hash); var li = $('<li id="raide-facile"></li>'); if (info.page === 'tableauRaidFacile' || info.page === 'optionsRaidFacile') { li.append('<span class="menu_icon"><a href="' + url.hashes({ raidFacile: 'options' }) + '" title="' + i18n.get('options de') + ' ' + i18n.get('raid facile') + '"><div class="menuImage traderOverview"></div></a></span>'); $('.menu_icon a', li).click(afficherMasquerOptions); } li.append('<a href="' + url.hashes({ raidFacile: 'tableau' }) + '" class="menubutton" id="lien_raide"><span class="textlabel">' + i18n.get('raid facile') + '</span></a>'); if (!GM_getValue("aJours_d", true)) { $('.textlabel', li).css('color', 'orange'); } li.appendTo('#menuTableTools'); logger.log('Lien ajouté dans le menu'); if (info.page === 'tableauRaidFacile' || info.page === 'optionsRaidFacile') { // On déselectionne le lien sélectionné $('#menuTable .menubutton.selected').removeClass('selected'); $('#menuTable .menuImage.highlighted').removeClass('highlighted'); // On sélectionne le lien de Raid facile $('.menubutton', li).addClass('selected'); $('.menuImage', li).addClass('highlighted'); intercom.send('tooltip', { selector: '#raide-facile .menu_icon a', settings: { hook: 'rightmiddle' } }); } } /** Colore les lignes en fonction des missions en cours */ function showAttaque(data) { var traiteFlotte = function (elem) { var destination = $.trim($('.destCoords a', elem).text()); var missionType = elem.data('mission-type'); var retour = elem.data('return-flight') ? 1 : 0; if (missions[destination] === undefined) { missions[destination] = {}; } if (missions[destination][missionType] === undefined) { missions[destination][missionType] = [0, 0]; } missions[destination][missionType][retour]++; }; var missions = {}; var html = $($.trim(data)); // On va chercher toutes les flottes (allers + retours) var flottes = $('#eventContent .eventFleet', html[0]); for (var i = 0; i < flottes.length; ++i) { traiteFlotte($(flottes[i])); } var couleur; var classe; var cible; var lignes; for (var destination in missions) { couleur = null; classe = ''; cible = missions[destination]; // On récupère les lignes du tableau de raid facile qui correspondent (il peut y en avoir plusieurs quand on ne supprime pas l'ancien scan) lignes = $(document.getElementsByClassName(destination)); /* cf l'api http://uni116.ogame.fr/api/localization.xml pour les nombres 1 Attaquer - 2 Attaque groupée - 3 Transporter - 4 Stationner - 5 Stationner - 6 Espionner - 7 Coloniser - 8 Recycler - 9 Détruire - 15 Expédition */ if (cible[9]) { // Détruire if (cible[9][0]) { // aller lignes.addClass('detruire'); couleur = col_dest; } else { // retour lignes.addClass('detruireRet'); couleur = col_dest_r; } } else if (cible[2]) { // Attaque groupée if (cible[2][0]) { // aller lignes.addClass('attaqueGr'); couleur = col_att_g; } else { // retour lignes.addClass('attaqueGrRet'); couleur = col_att_g_r; } } else if (cible[1]) { // Attaquer if (cible[1][0] >= 2) { lignes.addClass('attaque').addClass('attaque2'); couleur = stockageOption.get('couleur attaque2'); } else if (cible[1][1] >= 2) { lignes.addClass('attaqueRet').addClass('attaque2Ret'); couleur = stockageOption.get('couleur attaque2 retour'); } else { if (cible[1][0]) { // aller lignes.addClass('attaque'); couleur = col_att; } else { // retour lignes.addClass('attaqueRet'); couleur = col_att_r; } } } else if (cible[6] && cible[6][0]) { // Espionner, mais pas les retour lignes.addClass('espio'); couleur = stockageOption.get('couleur espionnage'); } var titre = 'Mission actuellement en cours<div class="splitLine"></div>'; for (var typeMission in cible) { titre += '<p>' + localization.missions[typeMission] + ' : ' + cible[typeMission][0] + ' +' + (cible[typeMission][1] - cible[typeMission][0]) + ' retour' + '</p>'; } $('.nombreAttaque', lignes).attr('title', titre); } intercom.send('tooltip', { selector: '#corps_tableau2 .nombreAttaque[title]' }); } /** Permet de récupérer un objet contenant toutes les options */ function exportOptions(target) { var optionExport = {}; optionExport.optionNew = { data: stockageOption.data, keyName: stockageOption.storageKeyName }; optionExport.optionOld = { option1: GM_getValue('option1' + info.serveur, '0/0/0/0/0/0/x:xxx:x/4000/0.3/0/1'), option2: GM_getValue('option2' + info.serveur, '0/100/100/0/12/1/0/4320/1/1/0/1/1/1/2/0/0'), option3: GM_getValue('option3' + info.serveur, '#C7050D/#025716/#FFB027/#E75A4F/#33CF57/#EFE67F'), option4: GM_getValue('option4' + info.serveur, '1/0/0/0/1/1/1/1/0/0/0/1/0/0/0/0/1/0/1/1/0/0/0/1/1/1/1/1/x/x/0/1/1/1'), }; var exportTxt = JSON.stringify(optionExport); $(target).val(exportTxt); } function importOptions(source) { try { var importData = JSON.parse($(source).val()); } catch(e) { fadeBoxx(i18n('erreur'), true); return; } if (!importData.optionNew || !importData.optionOld) { fadeBoxx(i18n('erreur'), true); return; } stockageOption.data = importData.optionNew.data; stockageOption.save(); GM_setValue('option1' + info.serveur, importData.optionOld.option1); GM_setValue('option2' + info.serveur, importData.optionOld.option2); GM_setValue('option3' + info.serveur, importData.optionOld.option3); GM_setValue('option4' + info.serveur, importData.optionOld.option4); $(source).val(''); fadeBoxx(i18n('ok')); } /** Renvoie un objet contenant toutes les données utiles pour les statistiques */ var getStatData = function () { var data = { id: info.ogameMeta['ogame-player-id'], univers: info.ogameMeta['ogame-universe'] }; return data; }; /** Affiche qu'il y a une mise à jour de disponible */ function mise_a_jour(version) { if (!/^\d+(?:\.\d+){1,3}$/.test(version)) { // La version ne ressemble pas à 8.4.4 return; } if (version.split('.') <= info.version.split('.')) { // pas de mise à jour return; } var popup = $('<div title="' + i18n.get('raid facile') + ' - Mise à jour">' + '<p>La version <b>'+version+'</b> est maintenant disponible.</p><br>' + '<p>Vous avez actuelement la version <b>'+info.version+'</b><br>' + 'Voulez vous installer la mise à jour ?</p>' //+'<p>Prochain rappel dans 6h.</p></div>' ).dialog({ width: 500, // modal: true, // resizable: false, buttons: { "Installer": function () { // preference.get()['lastUpdateCheck'] = info.now; // preference.save(); location.href = info.siteUrl; // popup.html('<iframe src="'+info.siteUrl+'" style="width:100%; height:98%"></iframe>').css({ // width:'590px', height:'400px' // }).parent().css({ // width:'auto', height:'auto' // }); GM_setValue("date_mise_ajours", '' + info.startTime + ''); popup.dialog('destroy'); }, "Changelog": function () { location.href = info.siteUrl + '?changelog'; // popup.html('<iframe src="'+info.siteUrl+'?changelog" style="width:100%; height:98%"></iframe>'); }, "Plus tard": function () { // preference.get()['lastUpdateCheck'] = info.now; // preference.save(); popup.dialog('destroy'); GM_setValue("date_mise_ajours", '' + (info.startTime + 1000 * 60 * 60 * 24 * 7) + ''); } } }); popup.css({ background: 'initial' }).parent().css({ 'z-index': '3001', background: 'black url(http://gf1.geo.gfsrv.net/cdn09/3f1cb3e1709fa2fa1c06b70a3e64a9.jpg) -200px -200px no-repeat' }); } /** Vérifie s'il y a une mise à jour */ function checkUpdate() { var lastUpdateDate = GM_getValue("date_mise_ajours", "0"); if ((info.startTime - parseInt(lastUpdateDate)) > 1000 * 60 * 60 * 6) { // vérification toutes les 6h var params = getStatData(); params.check = true; var url = new Url(info.siteUrl).params(params).toString(); if (typeof GM_xmlhttpRequest === 'undefined') { $.get(url, mise_a_jour); } else { GM_xmlhttpRequest({ method: 'GET', url: url, onload: function (response) { mise_a_jour(response.responseText); } }); } } } /** Converti des nombres en affichage numérique et en affichage court (ex: 10k) */ var numberConverter = { toInt: function (number) { var str = number.toString(); str = str.replace(/mm/i, '000 000 000').replace(/g/i, '000 000 000').replace(/m/i, '000 000').replace(/k/i, '000'); str = str.replace(/[\s.]/g, ''); return parseInt(str, 10); }, shortenNumber: function (number, factor) { var dividedNumber = number / factor; if (dividedNumber < 100) { return Math.round(dividedNumber * 10) / 10; } else { return Math.round(dividedNumber); } }, toPrettyString: function (number) { var k = 1000; var m = 1000000; var g = 1000000000; var factor; var unit; if (number >= g * 10) { factor = g; unit = 'G'; } else if (number >= m * 10) { factor = m; unit = 'M'; } else if (number >= k * 10) { factor = k; unit = 'k'; } else { factor = 1; unit = ''; } return this.shortenNumber(number, factor).toLocaleString() + unit; } }; /** Construit une URL */ function Url(url) { this.parse(url); } Url.prototype = { parse: function (url) { this._params = {}; this._hashes = {}; var hash = url.split('#')[1] || ''; hash = hash.split('&'); url = url.split('#')[0]; var params = url.split('?')[1] || ''; params = params.split('&'); this.url = url.split('?')[0]; var i, arg, kvp; if (params[0] !== '') { for (i = 0; i < params.length; i++) { arg = decodeURIComponent(params[i]); if (arg.indexOf('=') === -1) { this._params[arg] = true; } else { kvp = arg.split('='); this._params[kvp[0]] = kvp[1]; } } } if (hash[0] !== '') { for (i = 0; i < hash.length; i++) { arg = decodeURIComponent(hash[i]); if (arg.indexOf('=') === -1) { this._hashes[arg] = true; } else { kvp = arg.split('='); this._hashes[kvp[0]] = kvp[1]; } } } }, params: function (params) { for (var key in params) { this._params[encodeURIComponent(key)] = encodeURIComponent(params[key]); } return this; }, hashes: function (hashes) { for (var key in hashes) { this._hashes[encodeURIComponent(key)] = encodeURIComponent(hashes[key]); } return this; }, toString: function () { var url = this.url; var params = []; for (var pkey in this._params) { if (this._params[pkey] === 'true') { params.push(pkey); } else { params.push(pkey + '=' + this._params[pkey]); } } if (params.length) { url += '?' + params.join('&'); } var hash = []; for (var hkey in this._hashes) { if (this._hashes[hkey] === 'true') { hash.push(hkey); } else { hash.push(hkey + '=' + this._hashes[hkey]); } } if (hash.length) { url += '#' + hash.join('&'); } return url; } }; /** Demande à l'utilisateur d'appuyer sur une touche du clavier et détecte laquelle */ function findKey(options) { var which = options.defaultValue; function findKeyCallback(eventData) { eventData.preventDefault(); eventData.stopPropagation(); which = eventData.which; $('#which', popup).text(which); } var buttons = {}; buttons[i18n.get('ok')] = function () { if (which) { popup.dialog('close'); options.callback(which); } }; buttons[i18n.get('cancel')] = function () { popup.dialog('close'); options.callback(); }; var popupHtml = [ '<div title="' + i18n.get('raid facile') + '">', '<p>' + i18n.get('quelle_touche') + '</p><br>', '<p>Le code de la touche choisie est : <span id="which">' + which + '</span></p>', '</div>' ].join(''); var popup = $(popupHtml).dialog({ width: 500, modal: true, buttons: buttons, close: function () { $(document).off('keyup', findKeyCallback); popup.dialog('destroy'); } }); popup.css({ background: 'initial' }).parent().css({ background: 'black url(http://gf1.geo.gfsrv.net/cdn09/3f1cb3e1709fa2fa1c06b70a3e64a9.jpg) -200px -200px no-repeat' }); $(document).on('keyup', findKeyCallback); } /** Affiche le temps de manière lisible */ function timeFormat(time) { var size = 2; var formattedTime = []; var steps = [ {label: 'j', min: 60 * 60 * 24}, {label: 'h', min: 60 * 60}, {label: 'm', min: 60}, {label: 's', min: 1}, ]; steps.forEach(function(step) { if (formattedTime.length >= size || time < step.min) { return; } var nb = Math.floor(time / step.min); time = time % step.min; if (nb !== 0) { formattedTime.push(nb + step.label); } }); return formattedTime.join(' '); } //}endregion init(); /** initialisation des variables d'option **///{region /* Explication des options x/x/x/x/x/.... signifie arme/bouclier/protect/combus/impul/hyper/coordonee/date/option/ressource/classement/sauvegard auto/temps garde scan/exversion/coul_att/coul_att_g/coul_dest/lien/remplace/lien esp/rec/itesse/tps_vol/nom_j/nom_p/coord_q/prod_h/ress_h */ var option1 = GM_getValue('option1' + info.serveur, '0/0/0/0/0/0/x:xxx:x/1/0.3/0/1'); var option2 = GM_getValue('option2' + info.serveur, '0/100/100/0/12/1/0/4320/1/1/0/1/1/1/2/0/0'); var option3 = GM_getValue('option3' + info.serveur, '#C7050D/#025716/#FFB027/#E75A4F/#33CF57/#EFE67F'); var option4 = GM_getValue('option4' + info.serveur, '1/0/0/0/1/1/1/1/0/0/0/1/0/0/0/0/1/0/1/1/0/0/0/1/1/1/1/1/x/x/0/1/1/1'); var langue = stockageOption.get('langue'); var option1_split = option1.split('/'); var option2_split = option2.split('/'); var option3_split = option3.split('/'); var option4_split = option4.split('/'); //votre compte /**option1_mon_compte**/{ //Vos techno : var tech_arme_a = option1_split[0]; var tech_bouclier_a = option1_split[1]; var tech_protect_a = option1_split[2]; var tech_combus_a = option1_split[3]; var tech_impul_a = option1_split[4]; var tech_hyper_a = option1_split[5]; // Autre : var pos_depart = option1_split[6]; var vaisseau_lent = option1_split[7]; var pourcent_cdr = parseFloat(option1_split[8]); var pourcent_cdr_def = parseFloat(option1_split[9]); var vitesse_uni = parseInt(info.ogameMeta['ogame-universe-speed']); } //choix /**option2_variable**/{ //Selection de scan : var nb_scan_accpte = option2_split[0];// valeur de ressource a partir de laquel il prend le scan var valeur_cdr_mini = option2_split[1];// valeur de cdr a partir de laquel il prend le scan var valeur_tot_mini = option2_split[2];// valeur de total a partir de laquel il prend le scan var type_prend_scan = option2_split[3];// choix entre les 3options du haut a partir de laquel il prend le scan //Classement : var classement = option2_split[4];//0 date ; 1 coordonee ; 2 joueur ; 3 nom ^planette ; 4 ressource metal; 5 cristal ; 6 deut ; 7 activite ; 8 cdr possible ; 9 vaisseau; 10 defense ; 11 idrc ; 12 ressource total,13 reherche , 14 type de planette (lune ou planette) var reverse = option2_split[9]; var q_taux_m = (option2_split[11] !== undefined) ? option2_split[11] : 1; var q_taux_c = (option2_split[12] !== undefined) ? option2_split[12] : 1; var q_taux_d = (option2_split[13] !== undefined) ? option2_split[13] : 1; //Options de sauvegarde de scan : var scan_preenrgistre = option2_split[5];// si le scan est enregistre lorsqu'on le regarde ou seulement quand on clique sur enregistre. var scan_remplace = option2_split[6]; var nb_minutesgardescan = option2_split[7]; var minutes_opt = Math.floor(parseInt(nb_minutesgardescan) % 60); var nb_minutesgardescan2 = parseInt(nb_minutesgardescan) - minutes_opt; var heures_opt = Math.floor(Math.floor(nb_minutesgardescan2 / 60) % 24); nb_minutesgardescan2 = nb_minutesgardescan2 - heures_opt * 60; var jours_opt = Math.floor(nb_minutesgardescan2 / 60 / 24); var nb_ms_garde_scan = nb_minutesgardescan * 60 * 1000; var nb_max_def = option2_split[10] !== undefined ? option2_split[10] : 0; //Autre : var import_q_rep = option2_split[8]; var lien_raide_nb_pt_gt = (option2_split[14] !== undefined) ? option2_split[14] : 2; var nb_pourcent_ajout_lien = (option2_split[15] !== undefined) ? parseInt(option2_split[15]) : 0; var nb_ou_pourcent = (option2_split[16] !== undefined) ? option2_split[16] : 0; } //couleur /**option3_couleur**/{ var col_att = option3_split[0]; var col_att_g = option3_split[1]; var col_dest = option3_split[2]; var col_att_r = option3_split[3]; var col_att_g_r = option3_split[4]; var col_dest_r = option3_split[5]; } //afichage /**option4_variable**/{ //Changement dans les colonnes : var q_date_type_rep = option4_split[8]; var cdr_q_type_affiche = parseInt(option4_split[2]); //Changement dans boutons de droites : var simulateur = option4_split[11]; var q_mess = option4_split[12]; var espionnage_lien = option4_split[1]; var q_lien_simu_meme_onglet = (option4_split[25] !== undefined) ? option4_split[25] : 1; //Affichage de Colonne : var q_compteur_attaque = option4_split[21] !== undefined ? option4_split[21] : 0; var q_vid_colo = (option4_split[17] !== undefined) ? option4_split[17] : 0; var question_rassemble_col = option4_split[14]; var prod_h_q = option4_split[9]; var prod_gg = option4_split[10]; var prod_min_g = Math.floor(parseInt(prod_gg) % 60); var nb_minutesgardescan3 = parseInt(prod_gg) - prod_min_g; var prod_h_g = Math.floor(Math.floor(nb_minutesgardescan3 / 60) % 24); nb_minutesgardescan3 = nb_minutesgardescan3 - prod_h_g * 60; var prod_j_g = Math.floor(nb_minutesgardescan3 / 60 / 24); var date_affiche = option4_split[7];//0 date non affiche, 1 date affiche var tps_vol_q = option4_split[3]; var nom_j_q_q = option4_split[4]; var nom_p_q_q = option4_split[5]; var coor_q_q = option4_split[6]; var defense_question = (option4_split[26] !== undefined) ? option4_split[26] : 1; var vaisseau_question = (option4_split[27] !== undefined) ? option4_split[27] : 1; var pt_gt = (option4_split[32] !== undefined) ? option4_split[32] : 1; var tech_q = (option4_split[33] !== undefined) ? option4_split[33] : 1; //Affichage Global : var q_galaxie_scan = (option4_split[22] !== undefined) ? option4_split[22] : 0; var galaxie_demande = (option4_split[23] !== undefined) ? option4_split[23] : 1; var galaxie_plus_ou_moins = (option4_split[31] !== undefined) ? parseInt(option4_split[31]) : 1; var afficher_seulement = (option4_split[24] !== undefined) ? option4_split[24] : 0; var q_def_vis = (option4_split[19] !== undefined) ? option4_split[19] : 1; var q_flo_vis = (option4_split[18] !== undefined) ? option4_split[18] : 1; var nb_scan_page = parseInt(option4_split[13]); //Autre : var q_techzero = option4_split[15]; var tableau_raide_facile_value = (option4_split[30] !== undefined) ? option4_split[30] : 100; var q_icone_mess = option4_split[16]; } //}endregion /** initialisation des filtres **///{region var filtre_actif_inactif = 0; var filtre_joueur = ''; //}endregion /** option initialisation bbcode **///{region var option_bbcode_split = GM_getValue('option_bbcode' + info.serveur, '#872300/#EF8B16/#DFEF52/#CDF78B/#6BD77A/#6BD7AC/#6BC5D7/#6B7ED7/1/1/0/1').split('/'); var center_typeq = option_bbcode_split[7]; var q_url_type = option_bbcode_split[8]; var q_centre = option_bbcode_split[9]; var q_cite = option_bbcode_split[10]; var couleur2 = []; var bbcode_baliseo = []; var bbcode_balisem = []; var bbcode_balisef = []; couleur2[1] = option_bbcode_split[0]; couleur2[2] = option_bbcode_split[1]; couleur2[3] = option_bbcode_split[2]; couleur2[4] = option_bbcode_split[3]; couleur2[5] = option_bbcode_split[4]; couleur2[6] = option_bbcode_split[5]; couleur2[7] = option_bbcode_split[6]; bbcode_baliseo[0] = '[b]'; bbcode_balisef[0] = '[/b]'; bbcode_baliseo[1] = '[i]'; bbcode_balisef[1] = '[/i]'; bbcode_baliseo[2] = '[u]'; bbcode_balisef[2] = '[/u]'; bbcode_baliseo[3] = '[u]'; bbcode_balisef[3] = '[/u]'; bbcode_baliseo[4] = '[quote]'; bbcode_balisef[4] = '[/quote]'; if (option_bbcode_split[8] == 1) { bbcode_baliseo[5] = '[url=\''; bbcode_balisem[5] = '\']'; bbcode_balisef[5] = '[/url]'; } else { bbcode_baliseo[5] = '[url='; bbcode_balisem[5] = ']'; bbcode_balisef[5] = '[/url]'; } if (option_bbcode_split[7] == 1) { bbcode_baliseo[10] = '[align=center'; bbcode_balisem[10] = ']'; bbcode_balisef[10] = '[/align]'; } else { bbcode_baliseo[10] = '[center'; bbcode_balisem[10] = ']'; bbcode_balisef[10] = '[/center]'; } bbcode_baliseo[8] = '[color='; bbcode_balisem[8] = ']'; bbcode_balisef[8] = '[/color]'; //}endregion /** Variables de langues **///{region var text; text = { //{ Global 'raid facile': 'Raid Facile', missing_translation: 'Traduction manquante', //} //{ Menu de gauche 'options de': 'Options de', //} //option mon compte moncompte:'Mon compte ', vos_techno:'Vos technologies : ', q_coord:'Coordonnées de départ de vos raids', q_vaisseau_min:'Quel est le vaisseau le plus lent de votre flotte lors des raids ?', pourcent:'Pourcentage de débris de vaisseaux dans le cdr de votre univers', pourcent_def:'Pourcentage de débris de défense dans le cdr de votre univers', // option variable choix_certaine_vari:'Choix pour certaines variables', selec_scan_st:'Sélection de scan', q_apartir:'Butin', q_cdrmin:'CDR ', q_totmin:'CDR + Butin', q_prend_type:'Ne prendre les rapports avec ', rep_0_prend1:' Un CDR > ', rep_0_prend2:' ou un butin > ', rep_1_prend1:' Un CDR > ', rep_1_prend2:' et un butin > ', rep_2_prend:' Un CDR + butin > ', classement_st:'Classement', q_class:'Classer le tableau par ', c_date:'Date', c_coo:'Coordonnées', c_nj:'Nom de Joueur', c_np:'Nom de Planète', c_met:'Métal', c_cri:'Cristal', c_deu:'Deut', c_acti:'Activité', c_cdr:'Cdr possible', c_nbv:'Nb Vaisseau', c_nbd:'Nb Défense', c_ress:'Ressources Totales', c_type:'Type (lune ou planète)', c_cdrress:'Ressources + CDR', ressourcexh:'Ressources dans x heures', prod_classement:'Production', /*newe*/ c_vaisseau_valeur:'Valeur d\'attaque totale des vaisseaux', c_defense_valeur:'Valeur d\'attaque totale des défenses', /* news*/ q_reverse:'Classer par ordre', descroissant:' décroissant', croissant:' croissant', taux_classement_ressource:'Donner le taux pour le classement par ressources.', taux_m:'Taux M : ', taux_c:'Taux C : ', taux_d:'Taux D : ', option_save_scan_st:'Options de sauvegarde de scan', q_sae_auto:'Sauvegarde automatique des scans dès leur visionnage?', remp_scn:'Remplacer automatiquement les scans sur une même planète ?', q_garde:'Ne pas sauvegarder et supprimer les scans vieux de plus', jours:'jours', heures:'heures', min:'minutes', q_nb_max_def:'Nombre max de défense au-delà duquel le script ne prend pas les scans ?(0 = désactivé)', other_st:'Autre', import_q:'Lors de l\'importation, les scans', import_remplace:'remplacent les autres', import_rajoute:' sont ajoutés aux autres', lien_raide_nb_pt_gt:'Voulez-vous en appuyant sur le lien attaquer, préselectionner soit', //nb_pt:'Le nb de PT', //nb_gt:'Le nb de GT', rien:'rien', lien_raide_ajout_nb_pourcent:"Rajouter au nombre de PT/GT preselectionner de base", raccourcis:'Raccourcis', shortcut_attack_next:'Raccourci pour attaquer la cible suivante', modifier: 'Modifier', ce_nombre_est_keycode: 'Ce nombre correspond au code de la touche choisie', //couleur ligne couleur_ligne:'Couleur ligne ', q_color:' Couleur de la ligne d\'une cible si une flotte effectue une mission en mode', attt:'Attaquer', ag:'Attaque Groupée ', det:'Détruire', att_r:'Attaquer (R)', ag_r:'Attaque Groupée (R)', det_r:'Détruire (R)', //option affichage option_affichage:'Option d\'affichage ', affichage_changement_colonne:'Changement dans les colonnes', q_date_type:'Pour la date, on affiche ?', date_type_chrono:'Un chrono', date_type_heure:'L\'heure du scan', cdr_q:'Le comptage de cdr est affiché', recyclc:' en nombre de recycleurs', ressousrce:'en nombre de ressources', changement_boutondroite:'Changement dans les boutons de droite', question_afficher_icone_mess:'Voulez-vous affichez les icônes dans la partie messages ?', q_simul:'Quel simulateur voulez-vous utiliser ?', drago:'Dragosim', speed:'Speedsim', ogwinner:'Ogame-Winner', simu_exte:'Exporter le rapport d\'espionnage au format texte pour une autre utilisation', mess_q:'Afficher un lien vers le véritable message ?', lienespi:'Le lien d\'espionnage vous redirige', page_f:'Sur la page Flotte', page_g:'Sur la page Galaxie', q_lien_simu_meme_onglet:'Voulez-vous que les liens de simulations dirige sur', rep_onglet_norm:'Un nouvel onglet à chaque fois.', rep_onglet_autre:'Le même onglet sera rechargé.', affichage_colonne:'Affichage de Colonne :', q_inactif:'Afficher une colone pour marquer si le joueur est inactif ?', q_compteur_attaque:'Afficher une colonne qui donne le nombre de rapports de combat sur la planète en 24h ?', q_afficher_dernier_vid_colo:'Afficher l\'heure du dernier vidage de la colonie(approximatif) ?', question_rassemble_cdr_ress:'Voulez-vous rassembler les colonnes de ressources et de cdr ?', q_pt_gt:'Afficher le nombre de PT et de GT ?', q_prod:'Afficher la production par heure de la planète ?', q_ress_h:'Afficher les ressources dans (0 = pas affiché)', q_date:'Afficher la date dans le tableau ?', tps_vol:'Afficher le temps de vol ?', nom_j_q:'Afficher le nom du joueur ?', nom_p_q:'Afficher le nom de la planète ?', autre_planette:'Supprimer le nom de la planète mais l\'afficher en passant la souris sur les coordonnées', coor_q:'Afficher les coordonnées de la planète ?', defense_q:'Afficher les infos sur la défense ?', vaisseau_q:'Afficher les infos sur la flotte ?', defense_nb:'oui, son nombre', defense_valeur:'oui, sa valeur d\'attaque', q_tech: 'Afficher les tech.', affichage_global:'Affichage Global :', q_galaxie_scan:'Voulez-vous afficher seulement les scans de la galaxie de la planète sélectionnée ?', other:' autres', galaxie_plus_ou_moins:'Galaxie en cours + ou -', afficher_seulement:'Afficher seulement', toutt:'Tout', planete_sel:'Planète', lune:'Lune', filtrer : 'Filtrer', filtre_actif : 'Actif', filtre_inactif : 'Inactif', q_afficher_ligne_def_nvis:'Afficher la ligne si la défense n\'est pas visible ?', q_afficher_ligne_flo_nvis:'Afficher la ligne si la flotte n\'est pas visible ?', page:'Combien de scan voulez-vous afficher par page ? (0=tous)', //other_st:'Autre', q_techn_sizero:'Voulez-vous mettre vos techno à 0 si celles de la cible sont inconnues ?', lienraide:'Mettre le lien Raide-Facile', En_haut:'En haut', gauche:'A Gauche', /** news **/ banner_sky:'Position de la banniere de pub', myPlanets:'Position de la liste des planettes', tableau_raide_facile:'Taille du tableau raide-facile', /** news **/ //global oui:'oui', non:'non', ok: 'Ok', erreur: 'Erreur', cancel: 'Annuler', //option langue option_langue:'Language', q_langue:'Dans quelle langue voulez-vous le script ?', francais:'Français', anglais:'English', spagnol:'Español', roumain:'Roumain', //option bbcode text_centre:'Voulez-vous centrer le bbcode ?', text_cite:'Voulez-vous mettre en citation le bbcode ?', balise_centre:'Quelle balise utilisez-vous pour centrer le texte ?', balise1_center:'[align=center]', balise2_center:'[center]', balise_url:'Quelle balise utilisez-vous pour les url ?', balise1_url:'[url=\'adress\']', balise2_url:'[url=adresse]', color:'couleur', // tableau icone et autre // titre tableau th_nj:'Joueur', th_np:'Planète', th_coo:'Coordonnées', dated:'Date', tmp_vol_th:'Temps de Vol', prod_h_th:'Prod/h', th_h_vidage:'Heure vidage', ressource_xh_th:'Ressource x Heures', th_ress:'Butin', th_fleet:'PT/GT', th_ress_cdr_col:'CDR+Butin', nb_recycl:'Nb Recyleurs', th_nv:'Flottes', th_nd:'Défense', th_tech:'Tech.', // bouton de droite espionner:'Espionner', eff_rapp:'Effacer ce rapport', att:'Attaquer', simul:'Simuler', // entete mise_jours:'Mise à jour possible pour Raide-Facile', // interieur avec acronyme cdr_pos:'Cdr poss', metal:'M', cristal:'C', deut:'D', met_rc:'M', cri_rc:'C', nb_rc:'Recy.', nb_pt:'PT', nb_gt:'GT', retour_f:'Retour ', arriv_f:'Arrivée ', batiment_non_visible:'Batiment non visible', //message de pop up q_reset:'Voulez-vous remettre à zéro toutes les variables de raide?', reset:'Remise à zéro effectuée. Actualisez la page pour voir la différence.', q_reset_o:'Voulez-vous remetre à zéro toute les options ?', reset_s:'Remise à zéro effectuée. Actualisez la page pour voir la différence.', option_sv:'Options de Raide-Facile sauvegardées', del_scan:'Scans supprimés, rafraîchissement de la page', rep_mess_supri:'Messages Supprimés', quelle_touche: 'Quelle touche veux-tu utiliser ?', // ecrit dans les scans en pop up del_scan_d:'Effacer ce message', del_scan_script:'Effacer le message et le scan', del_script:'Effacer le scan', enleve_script:'Enlever le scan', add_scan:'Ajouter le scan', add_scan_d:'Ajouter le scan', // boutons save_optis:'Sauvegarder les options', remis_z:'Remise à zéro.', supr_scan_coche:'Supprimer les scans cochés', supr_scan_coche_nnslec:'Supprimer les scans non cochés', //import / export export_scan_se:'Exporter les scans sélectionnés', export_scan_nnse:'Exporter les scans non sélectionnés', export_options:'Exporter les options', import_options:'Importer les options', importer_scan:'Importer les scans', import_rep:'Scan importé et ajouté à votre base de données', importt:'Import :', exportt:'Export :', //bouton messages spr_scrptscan_a:'Supprimer Scan et Scan script affiché', spr_scrptscan_ns:'Supprimer Scan et Scan script non sélectionné', spr_scrptscan_s:'Supprimer Scan et Scan script sélectionné', spr_scan_a:'Supprimer Scan script affiché', spr_scan_ns:'Supprimer Scan script non sélectionné', spr_scan_s:'Supprimer Scan script sélectionné', add_scan_a:'Ajouter Scan Affiché ', add_scan_ns:'Ajouter Scan Non Sélectionné', add_scan_s:'Ajouter Scan Sélectionné', rep_mess_add:'Scan ajoutés', lm: 'Lanceur de missiles', lle: 'Artillerie laser légère', llo: 'Artillerie laser lourde', gauss: 'Canon de Gauss', ion: 'Artillerie à ions', pla: 'Lanceur de plasma', pb: 'Petit bouclier', gb: 'Grand bouclier', mic: 'Missile d`interception', mip: 'Missile Interplanétaire' }; i18n.importer('fr', text); if (langue == 'ro') { text = { //option mon compte moncompte:'<NAME> ', vos_techno:'Tehnologiile tale : ', q_coord:'Coordonatele flotei plecate', q_vaisseau_min:'Care este cea mai lenta nava în flota pe care o folosesti', pourcent:'Ce procent din flota ta este convertita în CR în universul tau ?', pourcent_def:'Ce procent din apararea ta este convertit în CR în universul tau ?', // option variable choix_certaine_vari:'Alege câteva variabile', q_apartir:'ia rapoarte de spionaj din', q_cdrmin:'Câmp de Ramasite minim ', q_totmin:'Câmp de Ramasite + minimum de Resurse recuperabile ', q_prend_type:'Ia doar scanari cu ', rep_0_prend1:' Câmp de Ramasite>', rep_0_prend2:' sau resurse >', rep_1_prend1:'Câmp de Ramasite>', rep_1_prend2:' si resurse > ', rep_2_prend:' Câmp de Ramasite + resurse > ', q_class:'Sorteaza tabelul dupa', c_date:'Date', c_coo:'Coordonate', c_nj:'Numele jucatorului', c_np:'Numele planetei', c_met:'Metal', c_cri:'Cristal', c_deu:'Deuteriu', c_acti:'Activitate', c_cdr:'Posibil Câmp de Ramasite', c_nbv:'Numarul de nave', c_nbd:'Numarul de aparare', c_ress:'Totalul resurselor', c_type:'Tip (luna sau planeta)', c_cdrress:'Resurse+CR', prod_classement:'Productie', ressourcexh:'resurse în x ore', c_vaisseau_valeur:' Puterea totala de atac a tuturor navelor', c_defense_valeur:' Puterea totala de atac a tuturor unitatilor de aparare', q_reverse:'clasamentul va fi în ordine :', descroissant:' descrescatoare', croissant:' crescatoare', q_sae_auto:'Automatic backup al rapoartele de spionaj când sunt vazute ? ', remp_scn:'Înlocuire automata a raportului de spionaj daca este de pe aceasi planeta ? ', q_garde:'Nu sterge rapoartele de spionaj mai vechi de ', jours:'zile', heures:'ore', min:'minute', import_q:'Când importeaza, fiecare scan ', import_remplace:' înlocuieste celelalte ', import_rajoute:' sunt adaugate la celelalte ', /***news **/ q_nb_max_def:'Numarul maxim de aparare dincolo de care script-ul nu scaneaza ?(0 = dezactiveaza) ', lien_raide_nb_pt_gt:'Vrei, când selectezi butonul de atac sa preselecteze fie una ori alta :', //nb_pt:'Numarul de transportatoare mici', //nb_gt:'Numarul de transportatoare mari', rien:'Nimic', /**fin news **/ //couleur ligne couleur_ligne:'Coloarea liniei ', q_color:' Culoarea linii tintei daca flota ta este în modul de', attt:'Atac', ag:'Atac ACS', det:'Distruge', att_r:'Atac (R)', ag_r:' Atac ACS (R)', det_r:'Distruge(R)', //option affichage option_affichage:'Optiuni de afisare ', lienraide:' Pune linkul de la Raide-Facile ', En_haut:'În top', gauche:'La stanga', lienespi:'Limkul din raportul de spionaj te va duce la :', page_f:'Vedere flota', page_g:'Vedere galaxie', cdr_q:'Cantitatea de câmp de ramasite este afisata : ', recyclc:' în numarul de Reciclatoare ', ressousrce:'în numarul de resurse', tps_vol:'Arata timpul de zbor?', nom_j_q:'Arata numele jucatorului ?', nom_p_q:'Arata numele plantei ?', autre_planette:'Nu-mi arata numele direct, dar arata-mi când dau click pe coordonate', coor_q:'Arata coordonatele planetei ?', defense_q:'Arata informatii despre aparare ?', vaisseau_q:'Arata informatii despre flota ?', defense_nb:'da, numarul lor.', defense_valeur:'da, puterea de atac', q_date:'Arata datele în tabel ?', q_date_type:'Pentru data aratam ?', date_type_chrono:'Timpul curent', date_type_heure:'Timpul rapoartelor de spionaj', q_prod:'Arata productia pe ora pe planeta', q_ress_h:'Arata resursele (0 = Nu arata)', mess_q:'Arata un link catre mesaje ?', q_simul:'Ce simulator de timp vrei sa folosesti ?', drago:'Dragosim', speed:'Speedsim', ogwinner:'Ogame-Winner', q_tech: 'Arata tech.', simu_exte:'sau ia raportul de spionaj în zona pentru export pentru alt simulator', page:'Câte scanari vrei sa fie afisate pe pagina ?(0=toate)', question_rassemble_cdr_ress:'Vrei sa aduni resursele si câmpul de ramasite ?', q_pt_gt:'Afiseaza ct/ht ?', q_techn_sizero:'Vrei sa îti pui tehnologiile pe 0 când raportul de spionaj nu arata tehnologiile oponentului ?', question_afficher_icone_mess:'Vrei sa afisezi icoanele ?', q_afficher_dernier_vid_colo:'Afiseaza timpul ultimelor raiduri (aproximativ) ?', /** news **/ q_afficher_ligne_def_nvis:'Afiseaza linia daca apararea nu este aparenta?', q_afficher_ligne_flo_nvis:'Afiseaza linia daca flota nu este aparenta ?', q_inactif:'Afiseaza o coloana pentru a arata ca jucatorul este inactiv ?', q_compteur_attaque:'Afiseaza o coloana care da numarul de rapoarte de batalie pe planea în 24H ?', q_galaxie_scan:'Vrei sa arati doar rapoartele de spionaj din galaxie pe planeta selectata ?', taux_classement_ressource:'Give the resources rate for the rainking by resources.', taux_m:'Rate M : ', taux_c:'Rate C : ', taux_d:'Rate D : ', other:' others', afficher_seulement:'Arata doar : ', toutt:'Toate', planete_sel:'Planeta', lune:'Luna', filtrer : 'Filter', filtre_actif : 'Active', filtre_inactif : 'Inactive', q_lien_simu_meme_onglet:'Vrei ca linkul de la simulator sa te duca la : ', rep_onglet_norm:'Un nou aratat de fiecare data.', rep_onglet_autre:'Acelasi tabel va fi reîncarcat.', affichage_global:'Afisare Generala :', affichage_colonne:'Afisare columna :', affichage_changement_colonne:'Schimba în coloane :', changement_boutondroite:'Schimbarea butoanelor din bara laterala în partea dreapta :', /** fin news **/ //option bbcode text_centre:'Vrei sa centrezi bbcode ?', text_cite:'Vrei BBcode în quotes ?', balise_centre:'Ce tag-uri vrei sa folosesti pentru centrare text ?', balise1_center:'[align=center]', balise2_center:'[center]', balise_url:'Ce tag-uri vrei sa folosesti "URL" ?', balise1_url:'[url=\'address\']', balise2_url:'[url=address]', color:'color', //sous titre pour separer les options other_st:'Alte', option_save_scan_st:'Backup options al rapoartele de spionaj', classement_st:'Clasament', selec_scan_st:'Selectare rapoartele de spionaj', // tableau icone et autre espionner:'spioneaza', eff_rapp:'Sterge acest raport de spionaj', att:'Ataca', simul:'Simuleaza', mise_jours:'Posibil Update al Raid Facile', cdr_pos:'Câmp de ramasite', dated:'Date', th_nj:'Jucator', th_coo:'Coordonate', th_np:'Planeta', th_ress:'Resurse', th_fleet:'ct/ht', th_nv:'flota', th_nd:'Aparare', th_tech:'', metal:'Metal', met_rc:'Metal Reciclat', cristal:'Cristal', cri_rc:'Cristal Reciclat', nb_rc:'reci.', nb_pt:'ct', nb_gt:'ht', deut:'Deut', nb_recycl:'Numarul de Reciclatoare', retour_f:'Întoarcere ', arriv_f:'Ajunge ', tmp_vol_th:'Timpul de zbor', prod_h_th:'Output/h', ressource_xh_th:'Resurse x Ore', th_ress_cdr_col:'DF+Res', th_h_vidage:'Timpul Raidului', //autre messages. q_reset:'Vrei sa resetezi toate variabilele si optiunile ?', reset:'Resetare terminata.Reîmprospateaza pagina ca sa vezi rezultatele.', q_reset_o:'Vrei sa resetezi toate optiunile ?', reset_s:'Resetare terminata. Reîmprospateaza pagina ca sa vezi rezultatele.', option_sv:'Optiunile Raide-Facile salvate', del_scan:'Rapoartele de spionare sterse, reîmprospateaza pagina', del_scan_d:'| sterge aceast mesaj', del_scan_script:'sterge mesaj + scanare script', del_script:'sterge scanarea de la script', enleve_script:'|sterge rapoartele de spionaj dar nu si scriptul', add_scan:'|Adauga rapoartele de spionaj de la script', add_scan_d:'Adauga scriptul la aceste rapoarte de spionaj', save_optis:'Salveaza optiunile', remis_z:'Reseteaza.', supr_scan_coche:'Sterge rapoartele de spionaj selectate', supr_scan_coche_nnslec:'Sterge rapoartele de spionaj neselectate', oui:'da', non:'nu', batiment_non_visible:'Nu arata Cladirile', rep_mess_supri:'Posturi sterse', //import / export export_scan_se:'Exporta rapoartele de spionaj selectate', export_scan_nnse:'Exporta rapoartele de spionaj neselectate', importer_scan:'Importa rapoarte de spionaj', import_rep:'Rapoarte de spionaj importate si adaugate la baza ta', importt:'Importa :', exportt:'Exporta :', //bouton messages spr_scrptscan_a:'Sterge raportul de spionaj si scanarea de script afisata', spr_scrptscan_ns:'Sterge raportul de spionaj si scanul de script neselectat', spr_scrptscan_s:'Delete esp report and selected Scan script', spr_scan_a:'Sterge scanul de script afisat', spr_scan_ns:'Sterge scanul de script neselectat', spr_scan_s:'Sterge scanul de script selectat ', add_scan_a:'Adauga raportul de spionaj afisat', add_scan_ns:'Adauga raportulde spionaj neselectat', add_scan_s:'Adauga raportul de spionaj selectat', rep_mess_add:'Raport de spionaj adaugat', //option langue option_langue:'Limba', q_langue:'În ce limba vrei sa folosesti scriptul? ?', francais:'Franceza', anglais:'Engleza', spagnol:'Español', roumain:'Rumano', autre:'Alte' }; i18n.importer('ro', text); } else if (langue == 'es') { text = { //option mon compte moncompte:'Mi Cuenta', vos_techno:'Tus tecnologías : ', q_coord:'Coordenadas de salida de tu flota', q_vaisseau_min:'Cuál es tu nave más lenta en la flota que utilizas', pourcent:'¿Qué porcentaje de escombros genera tu flota al ser destruida en tu Universo?', pourcent_def:'¿Qué porcentaje de escombros generan tus defensas al ser destruidas en tu Universo?', // option variable choix_certaine_vari:'Selecciona algunas variables', selec_scan_st:'Selección del informe de espionaje', q_apartir:'leer el informe de espionaje de', q_cdrmin:'Escombros mínimo ', q_totmin:'Escombros + Recursos mínimos recuperables ', q_prend_type:'Leer sólo lecturas con ', rep_0_prend1:'Escombros>', rep_0_prend2:'o recursos >', rep_1_prend1:'Escombros>', rep_1_prend2:'and resources > ', rep_2_prend:'Escombrosd + recursos > ', classement_st:'Ranking', q_class:'Ordenar la tabla por', c_date:'Fecha', c_coo:'Coordenadas', c_nj:'Nombre del Jugador', c_np:'Nombre del Planeta', c_met:'Metal', c_cri:'Cristal', c_deu:'Deut', c_acti:'Actividad', c_cdr:'Posibles Escombros', c_nbv:'Nº de Naves', c_nbd:'Nº de Defensas', c_ress:'Recursos totales', c_type:'Tipo (luna o planeta)', c_cdrress:'Recursos+Escombros', prod_classement:'Producción', ressourcexh:'recursos en x horas', q_reverse:'el ranking se mostrará en orden :', descroissant:'descendente', croissant:'ascendente', taux_classement_ressource:'Dar los ratios de recursos al ordenar por recursos.', taux_m:'Ratio M : ', taux_c:'Ratio C : ', taux_d:'Ratio D : ', option_save_scan_st:'Guardar opciones del informe de espionaje', q_sae_auto:'¿Guardar automáticamente el informe de espionaje al verlo? ', remp_scn:'¿Actualizar automáticamente del informe de espionaje anterior cuando sea del mismo planeta? ', q_garde:'No hacerlo y borrar el informe de espionaje anterior', jours:'días', heures:'horas', min:'minutos', other_st:'Otro', import_q:'Al importar cada sondeo', import_remplace:'reemplazará el anterior', import_rajoute:'será añadido a los anteriores', q_nb_max_def:'¿Número máximo de defensas a partir del cual el script no almacenará los informes?(0 = desactivado) ', lien_raide_nb_pt_gt:'¿Quieres que al seleccionar el botón Atacar, se preseleccione una nave u otra :', //nb_pt:'Número de NPC', //nb_gt:'Número de NGC', rien:'Nada', //couleur ligne couleur_ligne:'Línea de color', q_color:'Color de la línea del objetivo si tu tipo de floa es', attt:'Ataque', ag:'SAC', det:'Destruir', att_r:'Ataque (R)', ag_r:' SAC (R)', det_r:'Destruir (R)', //option affichage option_affichage:'Mostrar opciones', affichage_changement_colonne:'Cambiar entre columnas:', q_date_type:'¿Mostrar por fecha?', date_type_chrono:'Hora actual', date_type_heure:'Hora del informe de espionaje', cdr_q:'Cantidad de Escombros se muestra: ', recyclc:'por número de Recicladores', ressousrce:'por números de recursos', changement_boutondroite:'Cambiar los botones del menu lateral derecho:', question_afficher_icone_mess:'¿Quieres mostrar iconos?', q_simul:'¿Qué simulador quieres utilizar?', drago:'Dragosim', speed:'Speedsim', ogwinner:'Ogame-Winner', simu_exte:'o coger el informe de espionaje para exportarlo a otro simulador', mess_q:'¿Mostrar un enlace a los mensajes?', lienespi:'En enlace en el informe de espionaje te lleva a :', page_f:'Vista de Flota', page_g:'Vista de Galaxia', q_lien_simu_meme_onglet:'¿Quieres que los enlaces a los simuladores se abran: ', rep_onglet_norm:'en una nueva pestaña cada vez.', rep_onglet_autre:'La misma pestaña se actualizarál.', affichage_colonne:'Mostrar Columna:', q_inactif:'¿Mostrar una columna si que muestre si un jugador está inactivo?', q_compteur_attaque:'¿Mostrar una columna que indique el número de Informe de Batallas en el planeta en las últimas 24h?', q_afficher_dernier_vid_colo:'¿Mostrar la hora de los ultimos saqueos (aproximadamente)?', question_rassemble_cdr_ress:'¿Quieres recursos y Escombros quieres reunir?', q_pt_gt:'Mostrar ct/ht ?', q_prod:'Mostrar la producción por horas del planeta', q_ress_h:'Mostrar los recursos (0 = No mostrar)', q_date:'¿Mostrar fecha en la tabla?', tps_vol:'¿Mostrar tiempo de vuelo?', nom_j_q:'¿Mostrar en nombre del jugador?', nom_p_q:'¿Mostrar el nombre del planeta?', autre_planette:'¿No mostrar el nombre directamente pero mostrar el clickar sobre las coordenadas', coor_q:'¿Mostrar las coordenadas del planeta?', q_tech: '¿Mostrar tech.', affichage_global:'Visió General:', q_galaxie_scan:'¿Quieres mostrar sólo los informes de espionaje de la galaxía del planeta seleccionado?', other:' otros', afficher_seulement:'Mostrar sólo: ', toutt:'Todo', planete_sel:'Planeta', lune:'Luna', filtrer : 'Filter', filtre_actif : 'Active', filtre_inactif : 'Inactive', q_afficher_ligne_def_nvis:'¿Mostrar la línea si las defensas no aparecen?', q_afficher_ligne_flo_nvis:'¿Mostrar la línea si la flota no aparece?', page:'¿Cuántos sondeos quieres mostrar por página?(0=todos)', //other_st:'Otro', q_techn_sizero:'¿Quieres poner tus tecnologías a 0 cuando el informe de espionaje del enemigo no muestre sus tecnologías?', lienraide:'Poner el enlace de Raide-Facile', En_haut:'En la parte superior', gauche:'En la izquierda', //global oui:'si', non:'no', //option langue option_langue:'Idioma', q_langue:'¿En qué idioma quieres usar el Script?', francais:'Francés', anglais:'Inglés', spagnol:'Español', roumain:'Rumano', //option bbcode text_centre:'¿Quieres centrar el bbcode?', text_cite:'¿Quieres el BBcode en las citas?', balise_centre:'¿Qué código quieres usar para centrar el texto?', balise1_center:'[align=center]', balise2_center:'[center]', balise_url:'¿Qué código quieres usar para una URL?', balise1_url:'[url=\'address\']', balise2_url:'[url=address]', color:'color', // tableau icone et autre // titre tableau th_nj:'Jugador', th_np:'Planeta', th_coo:'Coordenadas', dated:'Fecha', tmp_vol_th:'Tiempo de vuelo', prod_h_th:'Output/h', th_h_vidage:'Tiempo del Saqueo', ressource_xh_th:'Recursos x hora', th_ress:'Recursos', th_fleet:'ct/ht', th_ress_cdr_col:'Escombros+Recursos', nb_recycl:'Nº de Recicladores', th_nv:'flota', th_nd:'Defensa', th_tech:'', // bouton de droite espionner:'Espiar', eff_rapp:'Eliminar el informe de espionaje', att:'Atacar', simul:'Simular', // entete mise_jours:'Actualizar Raid Facile', // interieur avec acronyme cdr_pos:'Escombros', metal:'Metal', deut:'Deut', cristal:'Cristal', met_rc:'Metal Reciclable', cri_rc:'Cristal Reciclable', nb_rc:'reci.', nb_pt:'ct', nb_gt:'ht', retour_f:'Retorno ', arriv_f:'Llegada ', batiment_non_visible:'Construcción no mostrada', //message de pop up q_reset:'¿quieres resetear todas las variables y opciones?', reset:'Reseteo hecho. Actualiza la página para ver el resultado.', q_reset_o:'QUieres resetear todas las opciones?', reset_s:'Reseteo hecho. Actualiza la página para ver el resultado.', option_sv:'Opciones de Raide-Facile guardadas', del_scan:'Informes de espionaje borrados, páginas actualizadas', rep_mess_supri:'Posts eliminados', // ecrit dans les scans en pop up del_scan_d:'|borrar este mensaje', del_scan_script:'eliminar fallos + revisar el script', del_script:'eliminar script', enleve_script:'|eliminar el informe de espionaje pero no el script', add_scan:'|Añadir el informe de espionaje desde el script', add_scan_d:'Añadir el script desde este informe de espionaje', // boutons save_optis:'Guardar opciones', remis_z:'Resetear.', supr_scan_coche:'Eliminar los informes de espionaje seleccionados', supr_scan_coche_nnslec:'Eliminar los informes de espionaje no seleccionados', //import / export export_scan_se:'Exportar los informes de espionaje seleccionados', export_scan_nnse:'Exportar los informes de espionaje no seleccionados', importer_scan:'Importar informes de espionaje', import_rep:'informe de espionaje y añadido a la Base de Datos', importt:'Import :', exportt:'Export :', //bouton messages spr_scrptscan_a:'Eliminar informe de espionaje mostrado', spr_scrptscan_ns:'Eliminar informe de espionaje no seleccionado', spr_scrptscan_s:'Eliminar informe de espionaje seleccionado', spr_scan_a:'Eliminar el Scan script mostrado', spr_scan_ns:'Eliminar el Scan script no seleccionado', spr_scan_s:'Eliminar el Scan script seleccionado', add_scan_a:'Añadir informe de espionaje mostrado', add_scan_ns:'Añadir informe de espionaje no seleccionado', add_scan_s:'Añadir informe de espionaje seleccionado', rep_mess_add:'Informe de espionaje añadido' }; i18n.importer('es', text); } else if (langue !== 'fr') { /* anglais */ text = { //{ Global 'raid facile': 'Easy Raid', missing_translation: 'Missing translation', //} //{ Menu de gauche 'options de': 'Options of', //} //option mon compte moncompte:'My account ', vos_techno:'Your technologies : ', q_coord:'Coordinates of departure fleet', q_vaisseau_min:'What\'s your slowest ship in your fleet that you use', pourcent:'What percentage of your fleet is converted to DF in your universe?', pourcent_def:'What percentage of your defense is converted to DF in your universe?', // option variable choix_certaine_vari:'Choice for some variables', selec_scan_st:'Selection of espionage report', q_apartir:'take espionage report from', q_cdrmin:'Minimal Debris field ', q_totmin:'Debris Field + minimum of Resources recoverable ', q_prend_type:'Take only scans with ', rep_0_prend1:' Debris Field>', rep_0_prend2:' or resources >', rep_1_prend1:'Debris Field>', rep_1_prend2:' and resources > ', rep_2_prend:' Debris Field + resources > ', classement_st:'Ranking', q_class:'Sort the table by', c_date:'Date', c_coo:'Coordinates', c_nj:'Name of Player', c_np:'Name of Planet', c_met:'Metal', c_cri:'Crystal', c_deu:'Deut', c_acti:'Activity', c_cdr:'Possible Debris Field', c_nbv:'Nr of ships', c_nbd:'Nr of Defense', c_ress:'Total resources', c_type:'Type (moon or planet)', c_cdrress:'Resource+DF', prod_classement:'Production', ressourcexh:'resources in x hours', c_vaisseau_valeur:'Total Attack Strength of all Ships', c_defense_valeur:'Total Attack Strength of all defense units', q_reverse:'the ranking will be in order :', descroissant:' decreasing', croissant:' increasing', taux_classement_ressource:'Give the resources rate for the rainking by resources.', taux_m:'Rate M : ', taux_c:'Rate C : ', taux_d:'Rate D : ', option_save_scan_st:'Backup options of espionage report', q_sae_auto:'Automatic backup of espionage report where they are viewed ? ', remp_scn:'Automatic replacement of espionage report if they are from the same planet ? ', q_garde:'Do not make and erase espionage report older than ', jours:'days', heures:'hours', min:'minutes', q_nb_max_def:'Maximum nomber of defense beyond which the script doesn\'t take espionnage reports ?(0= desactivate)', other_st:'Other', import_q:'When importing, each scan ', import_remplace:' replaces the other ', import_rajoute:' are added to the others ', lien_raide_nb_pt_gt:'Do you want, when selecting Attack boutton, preselect either or either :', //nb_pt:'Number of SC', //nb_gt:'Number of LC', rien:'Nothing', raccourcis: 'Shortcuts', shortcut_attack_next: 'Shortcut to attack the next target', modifier: 'Modify', ce_nombre_est_keycode: 'This number correspond to the keycode of the chosen key', //couleur ligne couleur_ligne:'Colour line ', q_color:' Color of the line of the target if your fleet mode is', attt:'Attack', ag:'ACS attack ', det:'Destroy', att_r:'Attack (R)', ag_r:' ACS attack (R)', det_r:'Destroy (R)', //option affichage option_affichage:'Display Options ', affichage_changement_colonne:'Change in the columns :', q_date_type:'For the date we show ?', date_type_chrono:'Current time', date_type_heure:'Time of the espionage report', cdr_q:'The amount of Debris Field is displayed : ', recyclc:' in numbers of Recyclerss ', ressousrce:'in numbers of resource', changement_boutondroite:'Change in the right sidebar buttons :', question_afficher_icone_mess:'Do you want to display icons ?', q_simul:'What flight Simulator do you want to use ?', drago:'Dragosim', speed:'Speedsim', ogwinner:'Ogame-Winner', simu_exte:'or take the espionage report in area for export in other simulator', mess_q:'Show a link to messages ?', lienespi:'The link in the spy-report takes you to :', page_f:'The fleet view', page_g:'The galaxy view', q_lien_simu_meme_onglet:'Do you want the simulators links to lead you to : ', rep_onglet_norm:'A new tab shown every time.', rep_onglet_autre:'The same tab will reloaded.', affichage_colonne:'Column Display :', q_inactif:'Display a column to show that the player is inactif ?', q_compteur_attaque:'Display a column that give the number of Combat Reports on the planet in 24H ?', q_afficher_dernier_vid_colo:'Display the time of the last raids (approximate) ?', question_rassemble_cdr_ress:'Do you want to gather resources and Debris Fields ?', q_pt_gt:'Show ct/ht ?', q_prod:'Show the hourly production of the planet', q_ress_h:'Show the resource (0 = Not shown)', q_date:'Show date in the table ?', tps_vol:'Show flight time?', nom_j_q:'Show name of the player ?', nom_p_q:'Show name of the planet ?', autre_planette:'Don\'t show the name directly but it show when you click on the coordinates', coor_q:'Show of the coordinates of the panet ?', defense_q:'Display infos about the defense ?', vaisseau_q:'Display infos about the fleet ?', defense_nb:'yes, its number.', defense_valeur:'yes, its attack strength', q_tech: 'Show tech.', affichage_global:'Global Display :', q_galaxie_scan:'Do you want to show only the spy reports of the galaxy of the selected planet ?', other:' others', afficher_seulement:'Display only : ', toutt:'All', planete_sel:'Planet', lune:'Moon', filtrer : 'Filter', filtre_actif : 'Active', filtre_inactif : 'Inactive', q_afficher_ligne_def_nvis:'Display the line if the défense isn\'t apparent?', q_afficher_ligne_flo_nvis:'Display the line if the fleet isn\'t apparent ?', page:'How many scans you want to display per page ?(0=all)', //other_st:'Other', q_techn_sizero:'Do you want to put your tech to 0 when the espionage report do not display the opponent\'s tech ?', lienraide:' Put the link of Raide-Facile ', En_haut:'On the top', gauche:'At the left', //global oui:'yes', non:'no', ok: 'Ok', erreur: 'Error', cancel: 'Cancel', //option langue option_langue:'Language', q_langue:'In what Language do you want to use the script ?', francais:'Français', anglais:'English', spagnol:'Español', roumain:'Romanian', //option bbcode text_centre:'Do you want to center the bbcode ?', text_cite:'Do you want the BBcode in quotes ?', balise_centre:'What tags do you use for center text ?', balise1_center:'[align=center]', balise2_center:'[center]', balise_url:'What tags do you use for the "URL" ?', balise1_url:'[url=\'address\']', balise2_url:'[url=address]', color:'color', // tableau icone et autre // titre tableau th_nj:'Player', th_np:'Planet', th_coo:'Coordinates', dated:'Date', tmp_vol_th:'Flight time', prod_h_th:'Output/h', th_h_vidage:'Raid Time', ressource_xh_th:'Resource x Hours', th_ress:'Resource', th_fleet:'ct/ht', th_ress_cdr_col:'DF+Res', th_nv:'fleet', th_nd:'Defense', th_tech:'Tech.', // bouton de droite espionner:'spying', eff_rapp:'Remove this espionage report', att:'Attack', simul:'Simulate', // entete mise_jours:'Possible Update of Raid Facile', // interieur avec acronyme cdr_pos:'Debris Field', metal:'Metal', cristal:'Crystal', deut:'Deut', met_rc:'Metal Recyclable', cri_rc:'Crystal Recyclable', nb_rc:'recy.', nb_pt:'ct', nb_gt:'ht', nb_recycl:'Nr of Recyclers', retour_f:'Return ', arriv_f:'Arrival ', batiment_non_visible:'Building not shown', //message de pop up q_reset:'Do you want to reset all variables and options ?', reset:'Reset done. Refresh the page to see the result.', q_reset_o:'Do you want to reset all options ?', reset_s:'Reset done. Refresh the page to see the result.', option_sv:'Options of Raide-Facile saved', del_scan:'Spying reports deleted, pages refresh', rep_mess_supri:'Posts deleted', quelle_touche: 'What key do you want to use ?', // ecrit dans les scans en pop up del_scan_d:'|delete this message', del_scan_script:'delete mess + scan script', del_script:'delete scan script', enleve_script:'|delete the espionage report but not the script', add_scan:'|Add the esp report from the script', add_scan_d:'Add the script from this spying reports', // boutons save_optis:'Save options', remis_z:'Reset.', supr_scan_coche:'Delete selected esp reports', supr_scan_coche_nnslec:'Delete unselected esp reports', //import / export export_scan_se:'Export selected esp reports', export_scan_nnse:'Export unselected esp reports', export_options:'Export options', import_options:'Import options', importer_scan:'Import esp reports', import_rep:'esp report imported and added to your Database', importt:'Import :', exportt:'Export :', //bouton messages spr_scrptscan_a:'Delete esp report and displayed Scan script', spr_scrptscan_ns:'Delete esp report and unselected Scan script', spr_scrptscan_s:'Delete esp report and selected Scan script', spr_scan_a:'Delete displayed Scan script', spr_scan_ns:'Delete unselected Scan script', spr_scan_s:'Delete selected Scan script ', add_scan_a:'Add displayed esp report ', add_scan_ns:'Add unselected esp report', add_scan_s:'Add selected esp Report', rep_mess_add:'esp Report added', lm: 'Rocket Launcher', lle: 'Light Laser', llo: 'Heavy Laser', gauss: 'Gauss Cannon', ion: 'Ion Cannon', pla: 'Plasma Turret', pb: 'Small Shield Dome', gb: 'Large Shield Dome', mic: 'Anti-Ballistic Missiles', mip: 'Interplanetary Missiles' }; i18n.importer('en', text); } var vari, localization; if (info.ogameMeta['ogame-language'] === 'fr') { localization = { missions: { '1': 'Attaquer', '2': 'Attaque groupée', '3': 'Transporter', '4': 'Stationner', '5': 'Stationner', '6': 'Espionner', '7': 'Coloniser', '8': 'Recycler le champ de débris', '9': 'Détruire', '15': 'Expédition' } }; vari = { sur: 'sur ', de: ' de ', pt: 'Petit transporteur', gt: 'Grand transporteur', cle: 'Chasseur léger', clo: 'Chasseur lourd', cro: 'Croiseur', vb: 'Vaisseau de bataille', vc: 'Vaisseau de colonisation', rec: 'Recycleur', esp: 'Sonde d`espionnage', bb: 'Bombardier', sat: 'Satellite solaire', dest: 'Destructeur', edlm: 'Étoile de la mort', tra: 'Traqueur', lm: 'Lanceur de missiles', lle: 'Artillerie laser légère', llo: 'Artillerie laser lourde', gauss: 'Canon de Gauss', ion: 'Artillerie à ions', pla: 'Lanceur de plasma', pb: 'Petit bouclier', gb: 'Grand bouclier', mic: 'Missile d`interception', mip: 'Missile Interplanétaire', tech_arm: 'Technologie Armes', tech_bouc: 'Technologie Bouclier', tech_pro: 'Technologie Protection des vaisseaux spatiaux', tech_com: 'Technologie Combustion', tech_imp: 'Technologie Impulsion', tech_hyp: 'Technologie Hyper-Espace', mine_m: 'Mine de métal', mine_c: 'Mine de cristal', mine_d: 'Synthétiseur de deutérium', lang_speedsin: 'fr', lang_dragosin: 'french' }; } else if (location.href.indexOf('pl.ogame', 0) >= 0) { localization = { missions: { '1': 'Atakuj', '2': 'Atak zwiazku', '3': 'Transportuj', '4': 'Stacjonuj', '5': 'Zatrzymaj', '6': 'Szpieguj', '7': 'Kolonizuj', '8': 'Recykluj pola zniszczen', '9': 'Niszcz', '15': 'Ekspedycja' } }; vari = { sur: 'na ', de: ' z ', tech_arm: 'Technologia bojowa', tech_bouc: 'Technologia ochronna', tech_pro: 'Opancerzenie', tech_hyp: 'Naped nadprzestrzenny', tech_com: 'Naped spalinowy', tech_imp: 'Naped impulsowy', pt: 'Maly transporter', gt: 'Duzy transporter', cle: 'Lekki mysliwiec', clo: 'Ciezki mysliwiec', cro: 'Krazownik', vb: 'Okret wojenny', vc: 'Statek kolonizacyjny', rec: 'Recykler', esp: 'Sonda szpiegowska', bb: 'Bombowiec', sat: 'Satelita sloneczny ', dest: 'Niszczyciel', edlm: '<NAME>', tra: 'Pancernik', lm: 'Wyrzutnia rakiet', lle: 'Lekkie dzialo laserowe ', llo: 'Ciezkie dzialo laserowe', gauss: 'Dzialo Gaussa', ion: 'Dzialo jonowe', pla: 'Wyrzutnia plazmy', pb: 'Mala powloka ochronna', gb: 'Duza powloka ochronna', mic: 'Przeciwrakieta', mip: 'Rakieta miedzyplanetarna', mine_m: 'Kopalnia metalu', mine_c: 'Kopalnia krysztalu', mine_d: 'Ekstraktor deuteru', lang_speedsin: 'en', lang_dragosin: 'english' }; } else if (location.href.indexOf('es.ogame', 0) >= 0 || location.href.indexOf('.ogame.com.ar', 0) >= 0) { localization = { missions: { '1': 'Atacar', '2': 'Ataq. confederación', '3': 'Transporte', '4': 'Desplegar', '5': 'Mantener posición', '6': 'Espionaje', '7': 'Colonizar', '8': 'Reciclar campo de escombros', '9': 'Destruir', '15': 'Expedición' } }; vari = { sur: 'en ', de: ' desde ', tech_arm: 'Tecnología Militar', tech_bouc: 'Tecnología de Defensa', tech_pro: 'Tecnología de Blindaje', tech_hyp: 'Propulsor Hiperespacial', tech_com: 'Motor de Combustible', tech_imp: 'Motor de Impulso', pt: 'Nave Pequeña de Carga', gt: 'Nave Grande de Carga', cle: 'Cazador Ligero', clo: 'Cazador Pesado', cro: 'Crucero', vb: 'Nave de Batalla', vc: 'Nave de Colonia', rec: 'Reciclador', esp: 'Sonda de Espionaje', bb: 'Bombardero', sat: 'Satélite Solar', dest: 'Destructor', edlm: 'Estrella de la Muerte', tra: 'Acorazado', lm: 'Lanzamisiles', lle: 'Láser Pequeño', llo: 'Láser Grande', gauss: 'Cañón de Gauss', ion: 'Cañón Iónico', pla: 'Cañón de Plasma', pb: 'Cúpula Pequeña de Protección', gb: 'Cúpula Grande Protección', mic: 'Misiles Antibalísticos', mip: 'Misiles Interplanetarios', mine_m: 'Mina de Metal', mine_c: 'Mina de Cristal', mine_d: 'Sintetizador de Deuterio', lang_speedsin: 'en', lang_dragosin: 'english' }; } else if (location.href.indexOf('ro.ogame', 0) >= 0) {// thanks <NAME>zi localization = { missions: { '1': 'Atac', '2': 'Atac SAL', '3': 'Transport', '4': 'Desfasurare', '5': 'Aparare SAL', '6': 'Spionaj', '7': 'Colonizare', '8': 'Recicleaza campul de ramasite', '9': 'Distrugerea Lunii', '15': 'Expeditie' } }; vari = { sur: 'la ', de: ' de la ', tech_arm: 'Tehnologia Armelor', tech_bouc: 'Tehnologia Scuturilor', tech_pro: 'Tehnologia Armurilor', tech_hyp: 'Motor Hiperspatial', tech_com: 'Motor de Combustie', tech_imp: 'Motor pe impuls', pt: 'Transportator mic', gt: 'Transportator mare', cle: 'Vânator Usor', clo: 'Vânator Greu', cro: 'Crucisator', vb: 'Nava de razboi', vc: 'Nava de colonizare', rec: 'Reciclator', esp: 'Proba de spionaj', bb: 'Bombardier', sat: 'Satelit Solar', dest: 'Distrugator', edlm: 'RIP', tra: 'Interceptor', lm: 'Lansatoare de Rachete', lle: 'Lasere usoare', llo: 'Lasere Grele', gauss: 'Tunuri Gauss', ion: 'Tunuri Magnetice', pla: 'Turele de Plasma', pb: 'Scut planetar mic', gb: 'Scut planetar mare', mic: 'Rachete Anti-Balistice', mip: 'Rachete Interplanetare', mine_m: 'Mina de Metal', mine_c: 'Mina de Cristal', mine_d: 'Sintetizator de Deuteriu', lang_speedsin: 'en', lang_dragosin: 'english' }; } else if (location.href.indexOf('it.ogame', 0) >= 0) {// thanks Tharivol localization = { missions: { '1': 'Attacco', '2': 'Attacco federale', '3': 'Trasporto', '4': 'Schieramento', '5': 'Stazionamento', '6': 'Spionaggio', '7': 'Colonizzazione', '8': 'Ricicla campo detriti', '9': 'Distruzione Luna', '15': 'Spedizione' } }; vari = { sur: 'su ', de: ' di ', tech_arm: 'Tecnologia delle Armi', tech_bouc: 'Tecnologia degli Scudi', tech_pro: 'Tecnologia delle Corazze', tech_hyp: 'Propulsore Iperspaziale', tech_com: 'Propulsore a Combustione', tech_imp: 'Propulsore a Impulso', pt: 'Cargo Leggero', gt: 'Cargo Pesante', cle: 'Caccia Leggero', clo: 'Caccia Pesante', cro: 'Incrociatore', vb: 'Nave da Battaglia', vc: 'Colonizzatrice', rec: 'Riciclatrice', esp: 'Sonda spia', bb: 'Bombardiere', sat: 'Satellite Solare', dest: 'Corazzata', edlm: 'Morte Nera', tra: 'Incrociatore da Battaglia', lm: 'Lanciamissili', lle: 'Laser Leggero', llo: 'Laser Pesante', gauss: 'Cannone Gauss', ion: 'Cannone Ionico', pla: 'Cannone al Plasma', pb: 'Cupola Scudo', gb: 'Cupola Scudo Potenziata', mic: 'Missili Anti Balistici', mip: 'Missili Interplanetari', mine_m: 'Miniera di Metallo', mine_c: 'Miniera di Cristalli', mine_d: 'Sintetizzatore di Deuterio', lang_speedsin: 'it', lang_dragosin: 'italian' }; } else if (location.href.indexOf('gr.ogame', 0) >= 0) {// Traduit par faethnskonhmou http://userscripts.org/users/499485 localization = { missions: { '1': 'Επίθεση', '2': 'Επίθεση ACS', '3': 'Μεταφορά', '4': 'Παράταξη', '5': 'Άμυνα ACS', '6': 'Κατασκοπεία', '7': 'Αποίκιση', '8': 'Ανακυκλώστε το πεδίο συντριμμιών', '9': 'Καταστροφή Φεγγαριού', '15': 'Αποστολή' } }; vari = { sur: 'στο ', de: ' απο ', tech_arm: 'Τεχνολογία Όπλων', tech_bouc: 'Τεχνολογία Ασπίδων', tech_pro: 'Τεχνολογία Θωράκισης', tech_hyp: 'Προώθηση Καύσεως', tech_com: 'Ωστική Προώθηση', tech_imp: 'Υπερδιαστημική Προώθηση', pt: 'Μικρό Μεταγωγικό', gt: 'Μεγάλο Μεταγωγικό', cle: 'Ελαφρύ Μαχητικό', clo: 'Βαρύ Μαχητικό', cro: 'Καταδιωκτικό', vb: 'Καταδρομικό', vc: 'Σκάφος Αποικιοποίησης', rec: 'Ανακυκλωτής', esp: 'Κατασκοπευτικό Στέλεχος', bb: 'Βομβαρδιστικό', sat: 'Ηλιακοί Συλλέκτες', dest: 'Destroyer', edlm: 'Deathstar', tra: 'Θωρηκτό Αναχαίτισης', lm: 'Εκτοξευτής Πυραύλων', lle: 'Ελαφρύ Λέιζερ', llo: 'Βαρύ Λέιζερ', gauss: 'Κανόνι Gauss', ion: 'Κανόνι Ιόντων', pla: 'Πυργίσκοι Πλάσματος', pb: 'Μικρός Αμυντικός Θόλος', gb: 'Μεγάλος Αμυντικός Θόλος', mic: 'Αντι-Βαλλιστικοί Πύραυλοι', mip: 'Διαπλανητικοί Πύραυλοι', mine_m: 'Ορυχείο Μετάλλου', mine_c: 'Ορυχείο Κρυστάλλου', mine_d: 'Συνθέτης Δευτέριου' }; } else /* anglais */ { localization = { missions: { '1': 'Attack', '2': 'ACS Attack', '3': 'Transport', '4': 'Deployment', '5': 'ACS Defend', '6': 'Espionage', '7': 'Colonization', '8': 'Recycle debris field', '9': 'Moon Destruction', '15': 'Expedition' } }; vari = { sur: 'on ', de: ' from ', tech_arm: 'Weapons Technology', tech_bouc: 'Shielding Technology', tech_pro: 'Armour Technology', tech_hyp: 'Hyperspace Drive', tech_com: 'Combustion Drive', tech_imp: 'Impulse Drive', pt: 'Small Cargo', gt: 'Large Cargo', cle: 'Light Fighter', clo: 'Heavy Fighter', cro: 'Cruiser', vb: 'Battleship', vc: 'Colony Ship', rec: 'Recycler', esp: 'Espionage Probe', bb: 'Bomber', sat: 'Solar Satellite', dest: 'Destroyer', edlm: 'Deathstar', tra: 'Battlecruiser', lm: 'Rocket Launcher', lle: 'Light Laser', llo: 'Heavy Laser', gauss: 'Gauss Cannon', ion: 'Ion Cannon', pla: 'Plasma Turret', pb: 'Small Shield Dome', gb: 'Large Shield Dome', mic: 'Anti-Ballistic Missiles', mip: 'Interplanetary Missiles', // ressource:'Ressources',//pour antigame mine_m: 'Metal Mine', mine_c: 'Crystal Mine', mine_d: 'Deuterium Synthesizer', lang_speedsin: 'en', lang_dragosin: 'english' }; } //}endregion /** fonction globale**///{region function strcmp(str1, str2) { //Accent ? //return (mini == str2 ? 1 : -1); var a = str1.toLowerCase(); var b = str2.toLowerCase(); if (a == b) { return 0; } return (a > b ? 1 : -1); } var addPoints = numberConverter.toPrettyString.bind(numberConverter); function insertAfter(elem, after) { var dad = after.parentNode; if (dad.lastchild == after) { dad.appendChild(elem); } else { dad.insertBefore(elem, after.nextSibling); } } //suprimer les 0 devants. function supr0(number) { number = number.toString(); var i = 0; for (; i < number.length - 1 && number[i] == '0'; ++i) { number[i] = ''; } return number.substring(i, number.length); } //raccourcisseur de noms function raccourcir(nomAraccourcir) { // conditions ? si c'est vrai : si c'est faut return nomAraccourcir.length >= 10 ? nomAraccourcir.substring(0, 10) : nomAraccourcir; } /** Affiche un message sous forme de popup qui disparait avec le temps * message - le message à afficher * isError - true (pour afficher une erreur), false sinon * duration - la durée d'affichage du message en millisecondes */ function fadeBoxx(message, isError, duration) { if (duration === undefined) { duration = stockageOption.get('popup duration'); } $("#fadeBoxStyle").attr("class", isError ? "failed" : "success"); $("#fadeBoxContent").html(message); $("#fadeBox").stop(true, true).fadeIn(0).delay(duration).fadeOut(500); } /** Affiche l'icône "new" avec un commentaire en "title" */ function iconeNew(commentaire) { return '<img src="http://snaquekiller.free.fr/ogame/messraide/raidefacile%20mess/iconeNew.png" alt="new" title="' + commentaire + '">'; } //}endregion /** page de tableau **///{region function save_option(serveur) { /** checked -> 0, pas checked -> 1 */ var checkedFromIdToInt = function (id) { var elem = document.getElementById(id); if (elem === null) { return 0; } return elem.checked === true ? 0 : 1; }; {//mon compte // Vos technos var techno_arme = parseInt(document.getElementById('valeur_arme').value, 10); var techno_boulier = parseInt(document.getElementById('valeur_boulier').value, 10); var techno_protect = parseInt(document.getElementById('valeur_protection').value, 10); var techno_combu = parseInt(document.getElementById('valeur_combustion').value, 10); var techno_impu = parseInt(document.getElementById('valeur_impulsion').value, 10); var techno_hyper = parseInt(document.getElementById('valeur_hyper').value, 10); // Autre var coordonee_depart = document.getElementsByClassName('valeur_coordonee')[0].value; // vitesse du vaisseaux le plus lent. var vitesse_vaisseaux_plus_lent = document.getElementById('vaisseau_vite').value; // pourcentage de vaisseau dans le cdr var pourcent_cdr_q = document.getElementById('cdr_pourcent').value; pourcent_cdr_q = Math.round(parseFloat(pourcent_cdr_q) / 10); pourcent_cdr_q = pourcent_cdr_q / 10; // pourcentage de defense dans le cdr var pourcent_cdr_def_q = document.getElementById('cdr_pourcent_def').value; pourcent_cdr_def_q = Math.round(parseFloat(pourcent_cdr_def_q) / 10); pourcent_cdr_def_q = pourcent_cdr_def_q / 10; var option1 = techno_arme + '/' + techno_boulier + '/' + techno_protect + '/' + techno_combu + '/' + techno_impu + '/' + techno_hyper + '/' + coordonee_depart + '/' + vitesse_vaisseaux_plus_lent + '/' + pourcent_cdr_q + '/' + pourcent_cdr_def_q + '/' + vitesse_uni; GM_setValue('option1' + serveur, option1); } {//choix variable //Selection de scan : var ressource_prend = numberConverter.toInt(document.getElementById('val_res_min').value); var cdr_prend = numberConverter.toInt(document.getElementById('valeur_cdr_mini').value); var tot_prend = numberConverter.toInt(document.getElementById('valeur_tot_mini').value); var prend_type0 = document.getElementById("prend_type0").checked; var prend_type1 = document.getElementById("prend_type1").checked; var prend_type_x; if (prend_type0 === true) { prend_type_x = 0; } else if (prend_type1 === true) { prend_type_x = 1; } else { prend_type_x = 2; } //Classement : var selection_classement = document.getElementById('classement').value; var q_reverse_croissant = document.getElementById("q_reverse_croissant").checked; var q_reverse_c = q_reverse_croissant === true ? 0 : 1; var taux_m_rep = parseFloat(document.getElementById('q_taux_m').value, 10); var taux_c_rep = parseFloat(document.getElementById('q_taux_c').value, 10); var taux_d_rep = parseFloat(document.getElementById('q_taux_d').value, 10); //Options de sauvegarde de scan : var save_auto_scan_non_q = document.getElementById("save_auto_scan_non").checked; var save_auto_scan_rep = save_auto_scan_non_q === true ? 0 : 1; var scan_remplace_non = document.getElementById("scan_remplace_non").checked; var scan_remplace_rep = scan_remplace_non === true ? 0 : 1; var heures_suprime_scan = parseInt(document.getElementsByClassName('heures_suprime')[0].value) || 0; var jours_suprime_scan = parseInt(document.getElementsByClassName('jours_suprime')[0].value) || 0; var minutes_suprime_scan = parseInt(document.getElementsByClassName('minutes_suprime')[0].value) || 0; var minutes_total_suprime_scan = minutes_suprime_scan + 60 * (heures_suprime_scan + 24 * jours_suprime_scan); var nb_max_def_dans_scan = parseInt(document.getElementById('nb_max_def').value); // Autre : var import_remplace = document.getElementById("import_remplace").checked; var import_qq_rep = import_remplace === true ? 0 : 1; var nb_gt_preremplit = document.getElementById("lien_raide_nb_gt_remplit").checked; var nb_pt_preremplit = document.getElementById("lien_raide_nb_pt_remplit").checked; var nb_pt_ou_gt_preremplit; if (nb_gt_preremplit === true) { nb_pt_ou_gt_preremplit = 0; } else if (nb_pt_preremplit === true) { nb_pt_ou_gt_preremplit = 1; } else { nb_pt_ou_gt_preremplit = 2; } var nb_pourcent_ajout_lien_rep = document.getElementById('nb_pourcent_ajout_lien').value; var nb_ou_pourcent_rep = document.getElementById('nb_ou_pourcent').value; var option2 = ressource_prend + '/' + cdr_prend + '/' + tot_prend + '/' + prend_type_x + '/' + selection_classement + '/' + save_auto_scan_rep + '/' + scan_remplace_rep + '/' + minutes_total_suprime_scan + '/' + import_qq_rep + '/' + q_reverse_c + '/' + nb_max_def_dans_scan + '/' + taux_m_rep + '/' + taux_c_rep + '/' + taux_d_rep + '/' + nb_pt_ou_gt_preremplit + '/' + nb_pourcent_ajout_lien_rep + '/' + nb_ou_pourcent_rep; GM_setValue('option2' + serveur, option2); } //{ couleur ligne var coll_att = document.getElementById('att1').value; var coll_att_r = document.getElementById('att1_r').value; stockageOption.set('couleur attaque', document.getElementById('att1').value); stockageOption.set('couleur attaque retour', document.getElementById('att1_r').value); stockageOption.set('couleur attaque2', document.getElementById('att2').value); stockageOption.set('couleur attaque2 retour', document.getElementById('att2_r').value); stockageOption.set('couleur espionnage', document.getElementById('colEspio').value); var coll_att_g = document.getElementsByClassName('att_group')[0].value; var coll_att_g_r = document.getElementsByClassName('att_group_r')[0].value; var coll_dest = document.getElementsByClassName('det')[0].value; var coll_dest_r = document.getElementsByClassName('det_r')[0].value; var option3 = coll_att + '/' + coll_att_g + '/' + coll_dest + '/' + coll_att_r + '/' + coll_att_g_r + '/' + coll_dest_r; GM_setValue('option3' + serveur, option3); //} //{ Affichage //{ Changement dans les colonnes : var date_type_chrono = document.getElementById("date_type_chrono").checked; var qq_date_type_rep = date_type_chrono === true ? 0 : 1; var recycleur_type_affichage_ressource_rep = document.getElementById("recycleur_type_affichage_ressource").checked; var affichage_colone_recycleur_rep = recycleur_type_affichage_ressource_rep === true ? 0 : 1; //} //{ Changement dans boutons de droites : var qq_sim_q_dra = document.getElementById("sim_q_dra").checked; var qq_sim_q_speed1 = document.getElementById("sim_q_speed").checked; var qq_sim_q_ogwin = document.getElementById("sim_q_ogwin").checked; var qq_sim_q; if (qq_sim_q_dra === true) { qq_sim_q = 0; } else if (qq_sim_q_speed1 === true) { qq_sim_q = 1; } else if (qq_sim_q_ogwin === true) { qq_sim_q = 2; } else { qq_sim_q = 3; } var mess_origine_aff_non = document.getElementById("mess_origine_aff_non").checked; var qq_mess; if (mess_origine_aff_non === true) { qq_mess = 0; } else { qq_mess = 1; } var option_scan_espionn_gala = document.getElementById("espionn_galaxie").checked; var option_respon_lien_espi; if (option_scan_espionn_gala === true) { option_respon_lien_espi = 0; } else { option_respon_lien_espi = 1; } //{ Le lien attaquer s'ouvre dans stockageOption.set('attaquer nouvel onglet', parseInt($('#rf_attaquer_ouvredans').val())); //} //option de l'onglet simulateur. var qq_lien_simu_meme_onglet_oui = document.getElementById("q_lien_simu_meme_onglet_oui").checked; var q_rep_lien_simu_meme_onglet; if (qq_lien_simu_meme_onglet_oui === true) { q_rep_lien_simu_meme_onglet = 0; } else { q_rep_lien_simu_meme_onglet = 1; } //} //{ Affichage de Colonne : var q_rep_compteur_attaque = checkedFromIdToInt('compteur_attaque_aff_non'); var q_vid_colo_rep = checkedFromIdToInt('aff_vid_colo_non'); var rassemble_qrep = checkedFromIdToInt('rassemble_cdr_ress_non'); var affiche_pt_gt = checkedFromIdToInt('q_pt_gt_non'); var affiche_prod_h = checkedFromIdToInt('prod_h_aff_non'); var ress_nb_j = parseInt(document.getElementsByClassName('ress_nb_j')[0].value); var ress_nb_h = parseInt(document.getElementsByClassName('ress_nb_h')[0].value); var ress_nb_min = parseInt(document.getElementsByClassName('ress_nb_min')[0].value); var ress_x_h = Math.floor(ress_nb_min + (ress_nb_h * 60) + (ress_nb_j * 60 * 24)); var date_q_repons = checkedFromIdToInt('date_affi_non'); var tps_vol_afficher_rep = checkedFromIdToInt('tps_vol_afficher_non'); var affiche_nom_joueur = checkedFromIdToInt('nom_joueur_affi_non'); var affiche_nom_planet = checkedFromIdToInt('nom_planet_affi_non'); var affiche_coor_q = checkedFromIdToInt('coord_affi_non'); var affiche_def_non = document.getElementById("defense_q_n").checked; var affiche_def_oui_nb = document.getElementById("defense_q_nb").checked; var affiche_def; if (affiche_def_non === true) { affiche_def = 0; } else if (affiche_def_oui_nb === true) { affiche_def = 1; } else { affiche_def = 2; } var affiche_flotte_non = document.getElementById("vaisseau_q_n").checked; var affiche_flotte_oui_nb = document.getElementById("vaisseau_q_nb").checked; var affiche_flotte; if (affiche_flotte_non === true) { affiche_flotte = 0; } else if (affiche_flotte_oui_nb === true) { affiche_flotte = 1; } else { affiche_flotte = 2; } var affiche_tech = checkedFromIdToInt('tech_aff_non'); //} //{ Affichage Global : var scan_galaxie_cours_non = document.getElementById("scan_galaxie_cours_non").checked; var scan_galaxie_cours_oui = document.getElementById("scan_galaxie_cours_oui").checked; var scan_galaxie_plus_moin = document.getElementById("scan_galaxie_plus_ou_moin").checked; var q_galaxie_rep; if (scan_galaxie_cours_non === true) { q_galaxie_rep = 0; } else if (scan_galaxie_cours_oui === true) { q_galaxie_rep = 1; } else if (scan_galaxie_plus_moin === true) { q_galaxie_rep = 3; } else { q_galaxie_rep = 2; } var galaxie_demande_rep = parseInt(document.getElementById('galaxie_demande').value, 10); var galaxie_demande_plus_moin_text_rep = document.getElementById('galaxie_demande_plus_moin_text').value; var afficher_lune_planet = document.getElementById("afficher_lune_planet").checked; var afficher_planet_seul = document.getElementById("afficher_planet_seul").checked; var afficher_seulement_rep; if (afficher_lune_planet === true) { afficher_seulement_rep = 0; } else if (afficher_planet_seul === true) { afficher_seulement_rep = 1; } else { afficher_seulement_rep = 2; } var q_rep_def_vis = checkedFromIdToInt('aff_lign_def_invisible_non'); var q_rep_flo_vis = checkedFromIdToInt('aff_lign_flot_invisible_non'); var q_nb_scan_page = document.getElementById('nb_scan_page').value; if (q_nb_scan_page.replace(/[^0-9-]/g, "") === '') { q_nb_scan_page = 0; } //} //{ Autre : var qq_techzero = checkedFromIdToInt('q_techzero_non'); var tableau_raide_facile_q = parseInt(document.getElementById('tableau_raide_facile_q').value, 10); var q_icone_mess_rep = checkedFromIdToInt('icone_parti_mess_non'); //} var option4 = 'x/'+ option_respon_lien_espi +'/'+ affichage_colone_recycleur_rep +'/'+ tps_vol_afficher_rep + //0-3 '/'+ affiche_nom_joueur +'/'+ affiche_nom_planet +'/'+ affiche_coor_q +'/'+ date_q_repons +//4-5-6-7 '/'+ qq_date_type_rep +'/'+ affiche_prod_h +'/'+ ress_x_h +'/'+ qq_sim_q +//8-11 '/'+ qq_mess +'/'+ q_nb_scan_page +'/'+ rassemble_qrep + '/'+ qq_techzero + '/'+ q_icone_mess_rep +//12-16 '/'+ q_vid_colo_rep +'/'+ q_rep_flo_vis +'/'+ q_rep_def_vis +'/x/'+ q_rep_compteur_attaque +//17-21 '/'+ q_galaxie_rep +'/'+ galaxie_demande_rep + '/'+ afficher_seulement_rep +'/'+ q_rep_lien_simu_meme_onglet +//22-25 '/'+ affiche_def +'/'+ affiche_flotte +//26-27 '/x/x/'+ tableau_raide_facile_q +'/'+ galaxie_demande_plus_moin_text_rep +//28-29-30-31 '/'+affiche_pt_gt +'/'+ affiche_tech;//32-33 GM_setValue('option4' + serveur, option4); //} // option de langue stockageOption.set('langue', document.getElementById('langue').value); stockageOption.save(); fadeBoxx(i18n('option_sv')); } function save_optionbbcode(serveur) { var col1 = document.getElementById('col_1').value; var col2 = document.getElementById('col_2').value; var col3 = document.getElementById('col_3').value; var col4 = document.getElementById('col_4').value; var col5 = document.getElementById('col_5').value; var col6 = document.getElementById('col_6').value; var col7 = document.getElementById('col_7').value; var q_cite0 = document.getElementById("cite0").checked; var q_cite1 = document.getElementById("cite1").checked; var q_cite; if (q_cite0 === true) { q_cite = 0; } else if (q_cite1 === true) { q_cite = 1; } var q_centre0 = document.getElementById("centre0").checked; var q_centre1 = document.getElementById("centre1").checked; var q_centre; if (q_centre0 === true) { q_centre = 0; } else if (q_centre1 === true) { q_centre = 1; } var q_centre_type0 = document.getElementById("centre_type0").checked; var q_centre_type1 = document.getElementById("centre_type1").checked; var rep_center_type; if (q_centre_type0 === true) { rep_center_type = 0; } else if (q_centre_type1 === true) { rep_center_type = 1; } var q_url_type0 = document.getElementById("url_type0").checked; var q_url_type1 = document.getElementById("url_type1").checked; var q_url_type; if (q_url_type0 === true) { q_url_type = 0; } else if (q_url_type1 === true) { q_url_type = 1; } var option_save_bbcode = col1 + '/' + col2 + '/' + col3 + '/' + col4 + '/' + col5 + '/' + col6 + '/' + col7 + '/' + rep_center_type + '/' + q_url_type + '/' + q_centre + '/' + q_cite; GM_setValue('option_bbcode' + serveur, option_save_bbcode); } function reset(serveur) { var continuer = confirm(i18n('q_reset')); if (continuer === true) { GM_setValue('scan' + serveur, ''); fadeBoxx(i18n('reset'), 0, 3000); } } //function pour connaitre les scans qui sont affiché. function connaitre_scan_afficher(serveur, nb_scan_page, url, nb) { // on regarde par rapport au nombre de scan par page et par rapport a la page ou on est pour savoir a partir de quel scan on affiche et on s'arrete ou . var nb_scan_deb; var nb_scan_fin; if (nb_scan_page !== 0) { var num_page; if (url.indexOf('&page_r=') != -1) { num_page = parseInt(url.split('&page_r=')[1].replace(/[^0-9-]/g, "")); } else { num_page = 1; } if (!num_page || num_page === 1) { nb_scan_deb = 0; nb_scan_fin = nb_scan_page; } else if (num_page >= 1) { nb_scan_deb = (parseInt(num_page) - 1) * nb_scan_page; nb_scan_fin = parseInt(num_page) * nb_scan_page; } } else { nb_scan_fin = nb; nb_scan_deb = 0; } var retour_scan = [nb_scan_fin, nb_scan_deb]; return retour_scan; } // fonction pour creer un tableau html exportable function export_html(serveur, check, url, nb_scan_page) { var id_num; var tr_num; var scan_info = GM_getValue('scan' + serveur, '').split('#'); var nb = scan_info.length; var export_html_2 = ''; var nb_scan_deb_fin = connaitre_scan_afficher(serveur, nb_scan_page, url, nb); for (var p = nb_scan_deb_fin[1]; p < nb_scan_deb_fin[0]; p++) { id_num = 'check_' + p + ''; if (scan_info[p]) { if (scan_info[p] !== '' && scan_info[p] !== ' ' && scan_info[p]) { if (document.getElementById(id_num)) { if (document.getElementById(id_num).checked == check) { tr_num = 'tr_' + p + ''; export_html_2 = export_html_2 + '\n' + document.getElementById(tr_num).innerHTML.split('<td> <a href="http')[0] + '</tr>'; } } else { nb_scan_deb_fin[0]++; } } else { nb_scan_deb_fin[0]++; } } } export_html_2 = '<table style="text-align:center;border: 1px solid black;font-size:10px;"><caption>Raide Facile. </caption><thead id="haut_table2"><tr>' + document.getElementById("haut_table2").innerHTML + '</thead><tbody id="export_html_textarea" >' + export_html_2 + '</tbody></table>'; document.getElementById("text_html").innerHTML = export_html_2; } //function d'export des scans. function export_scan(check, target) { var id_num; var scan_info = GM_getValue('scan' + info.serveur, '').split('#'); var nb = scan_info.length; var export_f = ''; var nb_scan_deb_fin = connaitre_scan_afficher(info.serveur, nb_scan_page, info.url, nb); for (var p = nb_scan_deb_fin[1]; p < nb_scan_deb_fin[0]; p++) { id_num = 'check_' + p + ''; if (scan_info[p]) { if (scan_info[p] !== '' && scan_info[p] !== ' ' && scan_info[p]) { if (document.getElementById(id_num)) { if (document.getElementById(id_num).checked == check) { export_f = export_f + '#' + scan_info[p]; } } else { nb_scan_deb_fin[0]++; } } else { nb_scan_deb_fin[0]++; } } } $(target).val(export_f); } //function d'import des scans. function import_scan(variable_q, source) { var scan_info = GM_getValue('scan' + info.serveur, ''); var scan_add = $(source).val(); scan_add = scan_add.split('#'); var scan_info3 = ''; if (variable_q == 1) { for (var p = 0; p < scan_add.length; p++) { if (scan_add[p].split(';').length > 2) { scan_info3 = scan_info3 + '#' + scan_add[p]; } } } else { // variable_q = 0 for (var q = 0; q < scan_add.length; q++) { if (scan_add[q].split(';').length > 2) { if (q === 0) { scan_info3 = scan_info3 + scan_add[q]; } else { scan_info3 = scan_info3 + '#' + scan_add[q]; } } } } if (variable_q == 1) { scan_info = scan_info + scan_info3; } else { scan_info = scan_info3; } scan_info = scan_info.replace(/\#{2,}/g, "#"); GM_setValue('scan' + info.serveur, scan_info); fadeBoxx(text.import_rep, 0, 3000); } // fonction pour savoir le nombre de pt et gt qu'il faut pour prendre le maximum de reosourcce en raidant function shipCount(m, k, d, cargo, pourcent) { return Math.ceil((Math.ceil(Math.max(m + k + d, Math.min(0.75 * (m * 2 + k + d), m * 2 + d))) * (pourcent / 100)) / cargo); } // pouvoir suprimer plusieurs scan. depuis raide-facile grace au checbox function del_scan_checkbox(serveur, check) { var id_num; var scan_info = GM_getValue('scan' + serveur, '').split('#'); var nb = scan_info.length; // on regarde de quel scan on doit commencer et combien normalement on doit regarder var p; var nb_scan_fin; if (nb_scan_page !== 0) { var num_page = info.url.split('&page_r=')[1]; if (num_page === undefined || num_page == 1) { p = 0; nb_scan_fin = nb_scan_page; } else if (num_page >= 1) { p = (parseInt(num_page) - 1) * nb_scan_page; nb_scan_fin = parseInt(num_page) * nb_scan_page; } } else { nb_scan_fin = nb; p = 0; } for (; p < nb_scan_fin; p++) { id_num = 'check_' + p + ''; if (scan_info[p]) { // on verifie que le scan est bien afficher dans la colone sinon on rajoute +1 au nombre final pour verifier les scan afficher l(par rapport au nombre demander) if (scan_info[p] !== '' && scan_info[p] !== ' ' && scan_info[p].split(';')[4] && document.getElementById(id_num) !== null) { if (document.getElementById(id_num).checked == check) { scan_info[p] = ''; } } else { nb_scan_fin++; } } } scan_info = scan_info.join('#'); scan_info = scan_info.replace(/\#{2,}/g, "#"); GM_setValue('scan' + serveur, scan_info); fadeBoxx(text.del_scan, 0, 3000); } //calcul la production en met/cri/deut par heure selon les coordonees , les mines et la temperature max. function calcule_prod(mine_m, mine_c, mine_d, coordonee, tmps_max) { var retour = {}; if (mine_m != '?' && mine_m != '?' && mine_m != '?' && coordonee.split(':')[2] !== undefined) { var prod_m = Math.floor((30 * parseInt(mine_m) * Math.pow(1.1, parseInt(mine_m)) + 30) * vitesse_uni); retour.metal = prod_m; var prod_c = Math.floor((20 * parseInt(mine_c) * Math.pow(1.1, parseInt(mine_c)) + 15) * vitesse_uni); retour.cristal = prod_c; // on cherche la temperature de la planette grace au coordonée si on ne la connait pas if (tmps_max === '?' || tmps_max === ' ' || tmps_max === '') { var pos_planette = coordonee.split(':')[2].replace(/[^0-9-]/g, ""); if (pos_planette <= 3) { tmps_max = 123; } else if (pos_planette <= 6) { tmps_max = 65; } else if (pos_planette <= 9) { tmps_max = 35; } else if (pos_planette <= 12) { tmps_max = 15; } else if (pos_planette <= 15) { tmps_max = -40; } } var prod_d = vitesse_uni * Math.floor(10 * parseInt(mine_d) * (Math.pow(1.1, parseInt(mine_d)) * (1.44 - (tmps_max * 0.004)))); retour.deut = prod_d; return retour; } else {retour.metal = '?';retour.cristal = '?';retour.deut = '?'; return retour;} } function vitesse_vaisseau(impulsion, hyper_h, combus, value_select) { if (!value_select) { return; } var vitesse_pt = parseInt(impulsion) >= 5 ? 10000 : 5000; var prop_pt = parseInt(impulsion) >= 5 ? 'imp' : 'comb'; var vitesse_bb = parseInt(hyper_h) >= 8 ? 5000 : 4000; var prop_bb = parseInt(hyper_h) >= 8 ? 'hyp' : 'imp'; var donnéesVaisseaux = [ { nom: vari.pt, vitesse: vitesse_pt, prop: prop_pt }, { nom: vari.gt, vitesse: 7500, prop: 'comb' }, { nom: vari.cle, vitesse: 12500, prop: 'comb' }, { nom: vari.clo, vitesse: 10000, prop: 'imp' }, { nom: vari.cro, vitesse: 15000, prop: 'imp' }, { nom: vari.vb, vitesse: 10000, prop: 'hyp' }, { nom: vari.vc, vitesse: 2500, prop: 'imp' }, { nom: vari.rec, vitesse: 2000, prop: 'comb' }, { nom: vari.esp, vitesse: 100000000, prop: 'comb' }, { nom: vari.bb, vitesse: vitesse_bb, prop: prop_bb }, { nom: vari.dest, vitesse: 5000, prop: 'hyp' }, { nom: vari.edlm, vitesse: 100, prop: 'hyp' }, { nom: vari.tra, vitesse: 10000, prop: 'hyp' }, ]; // on regarde le vaisseau selectionner et on cherche sa vitesse minimale var vitesse_mini; if (donnéesVaisseaux[value_select].prop === "comb") { vitesse_mini = Math.round(donnéesVaisseaux[value_select].vitesse * (1 + (0.1 * parseInt(combus)))); } else if (donnéesVaisseaux[value_select].prop === "imp") { vitesse_mini = Math.round(donnéesVaisseaux[value_select].vitesse * (1 + (0.2 * parseInt(impulsion)))); } else if (donnéesVaisseaux[value_select].prop === "hyp") { vitesse_mini = Math.round(donnéesVaisseaux[value_select].vitesse * (1 + (0.3 * parseInt(hyper_h)))); } return vitesse_mini; } function vaisseau_vitesse_mini(impulsion, hyper_h, combus, value_select, coordonee_cible) { /*************** Distance *********************/ var planette_selec = info.ogameMeta['ogame-planet-coordinates'].split(':').map(function (pos) { return parseInt(pos); }); var galaxie_j = planette_selec[0]; var system_j = planette_selec[1]; var planet_j = planette_selec[2]; var coordonee_cible_split = coordonee_cible.split(':').map(function (pos) { return parseInt(pos); }); var galaxie_c = coordonee_cible_split[0]; var system_c = coordonee_cible_split[1]; var planet_c = coordonee_cible_split[2]; // on calcule la distance entre la cible et la planette d'attaque (de depart) var distance; if (galaxie_j !== galaxie_c) { distance = 20000 * Math.abs(galaxie_j - galaxie_c); } else if (system_j !== system_c) { distance = 2700 + 95 * Math.abs(system_j - system_c); } else { distance = 1000 + 5 * Math.abs(planet_j - planet_c); } /*************** Temps de vol *********************/ var vitesse_mini = vitesse_vaisseau(impulsion, hyper_h, combus, value_select); var temps_de_vol_sec = 10 + ((35000 / 100) * (Math.sqrt((distance * 1000) / vitesse_mini))); temps_de_vol_sec = Math.round(temps_de_vol_sec / vitesse_uni); var minutes = Math.floor(temps_de_vol_sec / 60); var heures = Math.floor(minutes / 60); var jours = Math.floor(heures / 24); var secondes = Math.floor(temps_de_vol_sec % 60); minutes = Math.floor(minutes % 60); heures = Math.floor(heures % 24); var temp_vol = jours + 'j ' + heures + 'h ' + minutes + 'min' + secondes + 's'; var sec_arrive = info.startTime + temps_de_vol_sec * 1000; var date_arrive = new Date(); date_arrive.setTime(parseInt(sec_arrive)); var date_arrive_f = date_arrive.getDate() + '/' + date_arrive.getMonth() + '/' + date_arrive.getFullYear() + ' à ' + date_arrive.getHours() + 'h ' + date_arrive.getMinutes() + 'min' + date_arrive.getSeconds() + 's'; var sec_retour = info.startTime + temps_de_vol_sec * 2000; var date_retour = new Date(); date_retour.setTime(sec_retour); var date_retour_f = date_retour.getDate() + '/' + date_retour.getMonth() + '/' + date_retour.getFullYear() + ' à ' + date_retour.getHours() + 'h ' + date_retour.getMinutes() + 'min' + date_retour.getSeconds() + 's'; var acconyme_temps = '<acronym title=" ' + text.arriv_f + ' : ' + date_arrive_f + ' | ' + text.retour_f + ' : ' + date_retour_f + '">' + temp_vol + '</acronym>'; return acconyme_temps; } function calcul_dernier_vidage(metal, cristal, deut, prod_m, prod_c, prod_d, heure_scan, mine_m) { if (mine_m !== '?' && prod_m !== 0 && prod_m !== '?') { //prod_par_h on change en prod par minutes. var prod_m_sec = parseInt(prod_m) / 3600; var prod_c_sec = parseInt(prod_c) / 3600; var prod_d_sec = parseInt(prod_d) / 3600; // on cherche le nombre de seconde pour produire le metal/cristal/deut sur la planette var nb_sec_m = Math.round(parseInt(metal) / prod_m_sec); var nb_sec_c = Math.round(parseInt(cristal) / prod_c_sec); var nb_sec_d = Math.round(parseInt(deut) / prod_d_sec); // on trie var sortNumber = function (a, b) { return a - b; }; var array_nb_sec = [nb_sec_m, nb_sec_c, nb_sec_d]; array_nb_sec.sort(sortNumber); // on prend le temps le plus grand var heure_dernier_vidage = parseInt(heure_scan) - array_nb_sec[0] * 1000; var datecc = new Date(); datecc.setTime(heure_dernier_vidage); var date_final = datecc.getDate() + '/' + (datecc.getMonth() + 1) + '/' + datecc.getFullYear() + ' ' + datecc.getHours() + ':' + datecc.getMinutes() + ':' + datecc.getSeconds(); return date_final; } else { return '?'; } } //suprime les attaque comptabilisé il y a plus de 24h . function suprimmer_attaque_24h_inutile() { var attaque_deja = GM_getValue('attaque_24h', ''); var attaque_deja_split = attaque_deja.split('#'); var attaque_heure; var heure_moin24h = info.startTime - 24 * 60 * 60 * 1000; for (var t = 0; t < attaque_deja_split.length; t++) { attaque_heure = attaque_deja_split[t].split('/')[0]; if (attaque_heure < heure_moin24h)// alors l'attaque etait fait il y a plus de 24h donc on s'en fou { attaque_deja_split[t] = ''; } } attaque_deja = attaque_deja_split.join('#').replace(/\#{2,}/g, "#"); GM_setValue('attaque_24h', attaque_deja); } //}endregion var eventHandlers = { }; /** page de combat report **///{region //recupere les informations des rapports de combat pour que le compteur d'attaque function getDate(fullDate) { var fullDateSplit = fullDate.split(' '); var date = fullDateSplit[0].split('.').map(function (s) { return parseInt(s); }); var heure = fullDateSplit[1].split(':').map(function (s) { return parseInt(s); }); return new Date(date[2], date[1] - 1, date[0], heure[2], heure[1], heure[0]); } function get_info_combat() { if (document.getElementById('battlereport')) { //recupere la date du combat. var date_complet_combat = document.getElementsByClassName('infohead')[0].getElementsByTagName('td')[3].textContent;//exemple : 28.06.2015 10:13:14 var date_combat_ms = getDate(date_complet_combat).getTime(); if (date_combat_ms > (info.startTime - 24 * 60 * 60 * 1000)) {//on verifie que cela fait moin de 24h que l'attaque a eu lieu var attaque_deja = GM_getValue('attaque_24h', ''); if (attaque_deja.indexOf(date_combat_ms) == -1) {// si le combat n'est pas déja enregistré // recuperer les coordonées du combats. var info_head = document.getElementsByClassName('infohead')[0].getElementsByTagName('tr')[2].getElementsByTagName('td')[0].innerHTML; var coordonee_combat = info_head.split('[')[1].split(']')[0]; // on prend le pseudo des joueurs pour connaitre de quelle coté est le joueur var pseudo_de; if (info.pseudo.indexOf(vari.de) != -1) { pseudo_de = info.pseudo.split(vari.de)[0]; } else { pseudo_de = info.pseudo; } var bloc_combatants = document.getElementById("combatants").children; var bloc_attaquant = bloc_combatants[0].children; var attaquant = []; for (var k = 0; k < bloc_attaquant.length; k++) { attaquant[k] = bloc_attaquant[k].firstElementChild.textContent; } var bloc_defenseur = bloc_combatants[2].children; var defenseur = []; for (var l = 0; l < bloc_defenseur.length; l++) { defenseur[l] = bloc_defenseur[l].firstElementChild.textContent; } if ($.inArray(pseudo_de, attaquant) !== -1) { // le joueur est un des attaquants var attaque_news = date_combat_ms + '/' + coordonee_combat; attaque_deja = attaque_deja + '#' + attaque_news; attaque_deja = attaque_deja.replace(/\#{2,}/g, "#"); GM_setValue('attaque_24h', attaque_deja); } } } } } //}endregion /************************* PAGE DE MESSAGE *************************///{ // function suprimer un scan depuis le pop-up function supr_scan1(serveur) { var dateCombat = $('div.showmessage[data-message-id] .infohead tr:eq(3) td').text().match(/(\d+)\.(\d+)\.(\d+) (\d+):(\d+):(\d+)/); if (dateCombat.length != 7) { logger.error('Erreur n°15045'); } var date_scan = new Date(dateCombat[3], parseInt(dateCombat[2]) - 1, dateCombat[1], dateCombat[4], dateCombat[5], dateCombat[6]).getTime(); var scan_info = GM_getValue('scan' + serveur, '').split('#'); var listeDateRC; var suppr = 0; for (var i = 0; i < scan_info.length; i++) { listeDateRC = scan_info[i].split(';')[0]; if (listeDateRC == date_scan) { scan_info[i] = ''; ++suppr; } } scan_info = scan_info.join('#'); scan_info = scan_info.replace( /\#{2,}/g, "#"); GM_setValue('scan' + serveur, scan_info); fadeBoxx(suppr + ' ' +text.rep_mess_supri, 0, 3000); } function save_scan(serveur, id_rc, popup, afficherResultat) { if (!id_rc) return; var date_combat_total = ""; var document_spatio; if (popup) {// on se place dans le scan en pop up document_spatio = $('div.showmessage[data-message-id="'+id_rc+'"]').get(0); date_combat_total = document_spatio.getElementsByClassName('infohead')[0].innerHTML; } else { // on se place dans la partie du scan(partie pour les scans pré-ouverts) var nom_spatio = 'spioDetails_'+ id_rc; document_spatio = document.getElementById(nom_spatio); var document_entete = document.getElementById(id_rc + 'TR'); if (!document_entete) // Pour la version 5.0.0 document_entete = document.getElementById('TR' + id_rc); date_combat_total = document_entete.getElementsByClassName('date')[0].innerHTML; } // heure du scans var date_combat = date_combat_total.match(/(\d+)\.(\d+)\.(\d+) (\d+):(\d+):(\d+)/i); var jours = parseInt(date_combat[1]); var mois = parseInt(date_combat[2]) - 1; var annee = parseInt(date_combat[3]); var heure = parseInt(date_combat[4]); var min = parseInt(date_combat[5]); var sec = parseInt(date_combat[6]); var date_scan = new Date(annee, mois, jours, heure, min, sec).getTime(); // nom de planette et coordoné et nom joueurs var planette_et_joueur_scan = document_spatio.getElementsByClassName('material spy')[0].getElementsByTagName('tr')[0].getElementsByTagName('th')[0].innerHTML; var spans = document_spatio.getElementsByClassName('material spy')[0].getElementsByTagName('tr')[0].getElementsByTagName('th')[0].getElementsByTagName('span'); var nom_joueur = spans[spans.length - 1].innerHTML; // si antigame est installé et interfere dans le nom du joueurs if (nom_joueur.indexOf('war-riders.de') !== -1) { nom_joueur = document_spatio.getElementsByClassName('material spy')[0].getElementsByTagName('tr')[0].getElementsByTagName('th')[0].getElementById("player_name").innerHTML; } var coordonnee = document_spatio.getElementsByClassName('material spy')[0].getElementsByClassName('area')[0].getElementsByTagName('a')[0].innerHTML; var nom_plannette = '?'; if (planette_et_joueur_scan.indexOf('<span>') >= 0) { nom_plannette = planette_et_joueur_scan.split(' <span>')[0]; nom_plannette = nom_plannette.split(vari.sur)[1]; } else { nom_plannette = planette_et_joueur_scan.split(' <a')[0]; // normalement il y a une balise <figure> entre le "sur" et le nom de la planète // nom_plannette = nom_plannette.split(vari.sur)[1]; nom_plannette = nom_plannette.split('</figure>')[1]; } //si le nom de planete a un # on le remplace pour pas qu'il interfere dans le split plus tard if (nom_plannette.indexOf('#') >= 0) { nom_plannette = nom_plannette.replace(/\#/g, "1diez1"); } // type de joueur var typeJoueur = ""; var pourcent = 50; if (planette_et_joueur_scan.indexOf('status_abbr_active') >= 0) typeJoueur = ""; else if (planette_et_joueur_scan.indexOf('status_abbr_honorableTarget') >= 0) { typeJoueur = "ph"; pourcent = 75; } else if (planette_et_joueur_scan.indexOf('status_abbr_outlaw') >= 0) typeJoueur = "o"; else if (planette_et_joueur_scan.indexOf('status_abbr_inactive') >= 0) typeJoueur = "i"; else if (planette_et_joueur_scan.indexOf('status_abbr_longinactive') >= 0) typeJoueur = "I"; else if (planette_et_joueur_scan.indexOf('status_abbr_strong') >= 0) typeJoueur = "f"; else if (planette_et_joueur_scan.indexOf('status_abbr_vacation') >= 0) typeJoueur = "v"; // else if(planette_et_joueur_scan.indexOf('status_abbr_ally_own')>= 0) // else if(planette_et_joueur_scan.indexOf('status_abbr_ally_war')>= 0) // type de joueur var typeHonor = ""; if (planette_et_joueur_scan.indexOf('rank_bandit1') >= 0) { typeHonor = "b1"; pourcent = 100; } else if (planette_et_joueur_scan.indexOf('rank_bandit2') >= 0) { typeHonor = "b2"; pourcent = 100; } else if (planette_et_joueur_scan.indexOf('rank_bandit3') >= 0) { typeHonor = "b3"; pourcent = 100; } else if (planette_et_joueur_scan.indexOf('rank_starlord1') >= 0) typeHonor = "s1"; else if (planette_et_joueur_scan.indexOf('rank_starlord2') >= 0) typeHonor = "s2"; else if (planette_et_joueur_scan.indexOf('rank_starlord3') >= 0) typeHonor = "s3"; // on recupere l'id du rc var idRC; if (info.url.indexOf('index.php?page=messages') >= 0) {//si on est dans les scan preouvert idRC = id_rc; } else {// si on est dans la page pop up idRC = info.url.split('&msg_id=')[1]; if (info.url.indexOf('&mids') === -1) { idRC = idRC.split('&cat')[0]; } else { idRC = idRC.split('&mids')[0]; } } //modif deberron // on recupere avec le lien pour attaquer si c'est un lune ou une planette var type_planette = document_spatio.getElementsByClassName('defenseattack spy')[0].getElementsByClassName('attack')[0].innerHTML.match(/type=(\d+)/i); type_planette = type_planette ? type_planette[1] : 1; // on verifie si le scan est nouveau var newscan = GM_getValue('scan' + serveur, '').indexOf(idRC) === -1; // on verifie si le scan peut etre enregistré par rapport a sa date d'expiration(parametre d'option) et si il est nouveau if (newscan && (info.startTime - nb_ms_garde_scan) < date_scan) { // on recupere les ressources de la planettes var ressource_m_scan = document_spatio.getElementsByClassName('material spy')[0].getElementsByClassName('fragment spy2')[0].getElementsByTagName('td')[1].innerHTML.replace(/[^0-9-]/g, ""); var ressource_c_scan = document_spatio.getElementsByClassName('material spy')[0].getElementsByClassName('fragment spy2')[0].getElementsByTagName('td')[3].innerHTML.replace(/[^0-9-]/g, ""); var ressource_d_scan = document_spatio.getElementsByClassName('material spy')[0].getElementsByClassName('fragment spy2')[0].getElementsByTagName('td')[5].innerHTML.replace(/[^0-9-]/g, ""); // on cherche si il y a eu de l'activité et combien de temps var activite_scan = document_spatio.getElementsByClassName('aktiv spy')[0].innerHTML; activite_scan = activite_scan.split('</div></div></span>')[1].replace(/[^0-9-]/g, ""); if (activite_scan == '') { activite_scan = 'rien'; } // on creer des array par rapport a ce que l'on veut recupere var vaisseau = new Array(vari.pt, vari.gt, vari.cle, vari.clo, vari.cro, vari.vb, vari.vc, vari.rec, vari.esp, vari.bb, vari.sat, vari.dest, vari.edlm, vari.tra); var defense = new Array(vari.lm, vari.lle, vari.llo, vari.gauss, vari.ion, vari.pla, vari.pb, vari.gb, vari.mic, vari.mip); var recherche = new Array(vari.tech_arm, vari.tech_bouc, vari.tech_pro); var mine = new Array(vari.mine_m, vari.mine_c, vari.mine_d); // array de perte d'unité par rapport au vaisseau/defense var vaisseau_perte = new Array("4000", "12000", "4000", "10000", "27000", "60000", "30000", "16000", "1000", "75000", "2000", "110000", "9000000", "70000"); var vaisseau_perte_m = new Array("2000", "6000", "3000", "6000", "20000", "45000", "10000", "10000", "0", "50000", "0", "60000", "5000000", "30000"); var vaisseau_perte_c = new Array("2000", "6000", "1000", "4000", "7000", "15000", "20000", "6000", "1000", "25000", "2000", "50000", "4000000", "40000"); var def_perte = new Array("2000", "2000", "8000", "35000", "8000", "100000", "20000", "100000", "0", "0"); var def_perte_m = new Array("2000", "1500", "6000", "20000", "2000", "50000", "10000", "50000", "0", "0"); var def_perte_c = new Array("0", "500", "2000", "15000", "6000", "50000", "10000", "50000", "0", "0"); //valeur de base d'attaque pour vaissea/défense var valeur_attaque_vaisseau = new Array("5", "5", "50", "150", "400", "1000", "50", "1", "1", "1000", "1", "2000", "200000", "700"); var valeur_attaque_defense = new Array("80", "100", "250", "1100", "150", "3000", "1", "1", "0", "0"); //on initialise tout ce qu'on a besoin. var cdr_possible_def = 0; var cdr_possible_def_m = 0; var cdr_possible_def_c = 0; var cdr_possible = 0; var cdr_possible_m = 0; var cdr_possible_c = 0; var valeur_attaque_def = 0; var valeur_attaque_flotte = 0; var nb_vaisseau_s = 0; var nb_def_s = 0; var vaisseau_scan = new Array("0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"); var defense_scan = new Array("0", "0", "0", "0", "0", "0", "0", "0", "0", "0"); var recherche_scan = new Array("0", "0", "0"); var mine_scan = new Array("0", "0", "0"); var nb_def_type = ' '; var nb_recherche = ''; var nb_mine = ''; /******* RECHERCHE *******/ // j'ai la mit la recherche avant alors que c'est apres a cause du besoin de recherche pour calculer la valeur de flotte/def if (document_spatio.getElementsByClassName('fleetdefbuildings spy')[3]) { var flotte_inter3 = document_spatio.getElementsByClassName('fleetdefbuildings spy')[3].innerHTML; } else { flotte_inter3 = ''; } if (document_spatio.getElementsByClassName('fleetdefbuildings spy')[3] && flotte_inter3.indexOf('area plunder', 0) == -1) { // on compte le nombre de type de recherche affiché. var nb_type_recherche = document_spatio.getElementsByClassName('fleetdefbuildings spy')[3].getElementsByClassName('key').length; for (var j = 0; j < nb_type_recherche; j++) { var type_recherche = document_spatio.getElementsByClassName('fleetdefbuildings spy')[3].getElementsByClassName('key')[j].innerHTML;//23.03.2010 22:27:56 for (var k = 0; k < recherche.length; k++) { //on recupere le type de recherche et apres on cherche c'est lequels, et on remplit les infos dans la case qui lui correspond dans les array if (type_recherche == recherche[k]) { nb_recherche = document_spatio.getElementsByClassName('fleetdefbuildings spy')[3].getElementsByClassName('value')[j].innerHTML; recherche_scan[k] = parseInt(nb_recherche); } } } } else { //sinon elle existe pas alors on le voit pas donc ? nb_recherche = '?'; recherche_scan = new Array("?", "?", "?"); } var recherche_pour_valeur = (recherche_scan[0] == "?") ? new Array(0, 0, 0) : recherche_scan; /******* VAISSEAU + CDR *******/// on recupere les vaisseaux et le cdr creables. var flotte_inter = (document_spatio.getElementsByClassName('fleetdefbuildings spy')[0]) ? document_spatio.getElementsByClassName('fleetdefbuildings spy')[0].innerHTML : ''; // on verifie que l'on voit bien la flotte if (document_spatio.getElementsByClassName('fleetdefbuildings spy')[0] && flotte_inter.indexOf('area plunder', 0) == -1) { // on compte le nombre de type de vaisseau affiché. var nb_type_vaisseau = document_spatio.getElementsByClassName('fleetdefbuildings spy')[0].getElementsByClassName('key').length; for (var j = 0; j < nb_type_vaisseau; j++) { //on recupere le type du vaisseau et apres on cherche c'est lequels, et on remplit les infos dans la case qui lui correspond dans les array var type_vaisseau = document_spatio.getElementsByClassName('fleetdefbuildings spy')[0].getElementsByClassName('key')[j].innerHTML; for (var k = 0; k < vaisseau.length; k++) { if (type_vaisseau == vaisseau[k]) { var nb_vaisseau_type = parseInt(document_spatio.getElementsByClassName('fleetdefbuildings spy')[0].getElementsByClassName('value')[j].textContent.replace(/[^0-9-]/g, '')); valeur_attaque_flotte = valeur_attaque_flotte + nb_vaisseau_type * parseInt(valeur_attaque_vaisseau[k]) * (1 + 0.1 * recherche_pour_valeur[0]); cdr_possible = cdr_possible + parseInt(vaisseau_perte[k]) * nb_vaisseau_type; cdr_possible_m = cdr_possible_m + parseInt(vaisseau_perte_m[k]) * nb_vaisseau_type; cdr_possible_c = cdr_possible_c + parseInt(vaisseau_perte_c[k]) * nb_vaisseau_type; vaisseau_scan[k] = parseInt(vaisseau_scan[k]) + nb_vaisseau_type; nb_vaisseau_s = nb_vaisseau_s + nb_vaisseau_type; } } } } else { cdr_possible = '?'; valeur_attaque_flotte = '?'; vaisseau_scan = new Array("?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?"); nb_vaisseau_s = -1; } if (cdr_possible == '' || cdr_possible == ' ') { cdr_possible = 0; } /******* DEFENSE *******/ if (document_spatio.getElementsByClassName('fleetdefbuildings spy')[1]) { var flotte_inter1 = document_spatio.getElementsByClassName('fleetdefbuildings spy')[1].innerHTML; } else { flotte_inter1 = ''; } // on verifie que l'on voit bien la def et on verifie que ce que je prenne c'est pas le tableau d'antigame if (document_spatio.getElementsByClassName('fleetdefbuildings spy')[1] && flotte_inter1.indexOf('area plunder', 0) == -1) { // on compte le nombre de type de vaisseau affiché. var nb_type_def = document_spatio.getElementsByClassName('fleetdefbuildings spy')[1].getElementsByClassName('key').length; for (var j = 0; j < nb_type_def; j++) { //on recupere le type de la defense et apres on cherche c'est lequels, et on remplit les infos dans la case qui lui correspond dans les array var type_def = document_spatio.getElementsByClassName('fleetdefbuildings spy')[1].getElementsByClassName('key')[j].innerHTML;//23.03.2010 22:27:56 for (var k = 0; k < defense.length; k++) { if (type_def == defense[k]) { nb_def_type = (document_spatio.getElementsByClassName('fleetdefbuildings spy')[1].getElementsByClassName('value')[j].innerHTML).replace(/[^0-9-]/g, ""); valeur_attaque_def = valeur_attaque_def + parseInt(nb_def_type) * parseInt(valeur_attaque_defense[k]) * (1 + 0.1 * recherche_pour_valeur[0]);// +t pour faire fonctionner la fonction replace defense_scan[k] = parseInt(defense_scan[k]) + parseInt(nb_def_type); nb_def_s = nb_def_s + parseInt(nb_def_type); cdr_possible_def = cdr_possible_def + parseInt(def_perte[k]) * parseInt(nb_def_type); cdr_possible_def_m = cdr_possible_def_m + parseInt(def_perte_m[k]) * parseInt(nb_def_type); cdr_possible_def_c = cdr_possible_def_c + parseInt(def_perte_c[k]) * parseInt(nb_def_type); } } } var cdr_def = cdr_possible_def + '/' + cdr_possible_def_m + '/' + cdr_possible_def_c; } else { nb_def_type = '?'; valeur_attaque_def = '?'; defense_scan = new Array("?", "?", "?", "?", "?", "?", "?", "?", "?", "?"); nb_def_s = -1; var cdr_def = '?/?/?'; } /******* Batiment (MINE) *******/ if (document_spatio.getElementsByClassName('fleetdefbuildings spy')[2]) { var flotte_inter2 = document_spatio.getElementsByClassName('fleetdefbuildings spy')[2].innerHTML; } else { flotte_inter2 = ''; } // on verifie que l'on voit le batiment et que ce n'est pas antigame if (document_spatio.getElementsByClassName('fleetdefbuildings spy')[2] && flotte_inter2.indexOf('area plunder', 0) == -1) { // on compte le nombre de type de batiment affiché. var nb_type_mine = document_spatio.getElementsByClassName('fleetdefbuildings spy')[2].getElementsByClassName('key').length; for (var jj = 0; jj < nb_type_mine; jj++) { //on recupere le type de la batiment et apres on cherche c'est lequels, et on remplit les infos dans la case qui lui correspond dans les array var type_mine = document_spatio.getElementsByClassName('fleetdefbuildings spy')[2].getElementsByClassName('key')[jj].innerHTML;//23.03.2010 22:27:56 for (var kk = 0; kk < mine.length; kk++) { if (type_mine == mine[kk]) { nb_mine = document_spatio.getElementsByClassName('fleetdefbuildings spy')[2].getElementsByClassName('value')[jj].innerHTML; mine_scan[kk] = parseInt(nb_mine); } } } }//si on elle existe pas alors on le voit pas donc ? else { nb_mine = '?'; mine_scan = new Array("?", "?", "?"); } /* ******* INFO FINAL ********* */ // on verifie que l'on peut enregistré selon toute les options var ressource_pillable = parseInt(ressource_m_scan) + parseInt(ressource_c_scan) + parseInt(ressource_d_scan); var cdr_possible2 = Math.round((cdr_possible !== '?' ? cdr_possible : 0) * pourcent_cdr) + Math.round((cdr_possible_def !== '?' ? cdr_possible_def : 0) * pourcent_cdr_def); // les trois premiere ligne c'est selon le type d'enregistrement par rapport au ressource /cdr ou les deux. / la derniere ligne pour savoir par rapport a la def et que on voit bien les coordonées if (((type_prend_scan == 0 && (cdr_possible2 >= parseInt(valeur_cdr_mini) || (ressource_pillable * pourcent / 100) >= parseInt(nb_scan_accpte))) || (type_prend_scan == 1 && cdr_possible2 >= parseInt(valeur_cdr_mini) && (ressource_pillable * pourcent / 100) >= parseInt(nb_scan_accpte)) || (type_prend_scan == 2 && (cdr_possible2 + (ressource_pillable * pourcent / 100)) >= valeur_tot_mini)) && coordonnee != '' && (nb_max_def == 0 || nb_max_def > nb_def_s)) { var info_final = date_scan + ';' + coordonnee + ';' + nom_joueur + ';' + nom_plannette //0-1-2-3 + ';' + ressource_m_scan + ';' + ressource_c_scan + ';' + ressource_d_scan + ';' //4-5-6 + activite_scan + ';' + cdr_possible + ';' + vaisseau_scan.join('/') //7-8-9 + ';' + defense_scan.join('/') + ';' + idRC + ';' + ressource_pillable //10-11-12 + ';' + recherche_scan.join('/') + ';' + type_planette /*13/14*/ + ';' + cdr_possible_m + ';' + cdr_possible_c + ';' + nb_vaisseau_s + ';' + nb_def_s //15-16-17-18 + ';' + mine_scan.join('/') + ';x' + ';' + cdr_def //19-20-21 + ';' + valeur_attaque_flotte + ';' + valeur_attaque_def //22-23 + ';' + typeJoueur + ';' + typeHonor; //24-25 var scan_info = GM_getValue('scan' + serveur, '').split('#'); //alert(info_final); // on suprime les scan trop vieux if (nb_ms_garde_scan != 0) { for (var i = 0; i < scan_info.length; i++) { var scan_info25 = scan_info[i].split(';'); if (info.startTime - nb_ms_garde_scan > parseInt(scan_info25[0])) { scan_info[i] = ''; } } } // puis on sauvegarde si on remplace les scan de la meme planette et qu'il existe un scan avec les meme coordonées var scan_info2; if (GM_getValue('scan' + serveur, '').indexOf(coordonnee) > -1 && scan_remplace == 1) { var scan_remplacer_q = 0;// on boucle par rapport au nombre de scan for (var p = 0; p < scan_info.length; p++) { var scan_test = scan_info[p].split(';'); // on verifie que le scan existe et on cherche si c'est les meme coordonées, si oui alors on regarde si il est plus récent, et si c'est bien le meme type (lune/planette) if (scan_test[9]) { if (scan_info[p].indexOf(coordonnee) != -1 && scan_test[14] == type_planette) { scan_remplacer_q = 1; if (parseInt(scan_test[0]) < date_scan) { // on vient d'ajouter un scan plus récent pour le même endroit scan_info[p] = info_final; } } } } // on regarde si il a remplacer ou pas le scan par un ancien, si non alors on l'ajoute scan_info2 = scan_info.join('#'); if (scan_remplacer_q == 0) { scan_info2 += '#' + info_final; } scan_info2 = scan_info2.replace(/\#{2,}/g, "#"); if (scan_info2 == '' || scan_info2 == '#') { GM_setValue('scan' + serveur, ''); } else { GM_setValue('scan' + serveur, scan_info2); } }// si on remplace pas alors on ajoute sans reflechir et on suprime les scan '' else { scan_info2 = scan_info.join('#').replace(/\#{2,}/g, "#"); if (scan_info2 == '' || scan_info2 == '#') { GM_setValue('scan' + serveur, info_final); } else { GM_setValue('scan' + serveur, scan_info2 + '#' + info_final); } } if (afficherResultat) { fadeBoxx('1 ' + text.rep_mess_add, 0, 1000); } return true; } } if (afficherResultat) { fadeBoxx('0 ' + text.rep_mess_add, 0, 500); } return false; } function bouton_supr_scan_depuis_mess() { if (document.getElementById('Bouton_Rf') == null && document.getElementById('mailz')) { var style_css = ' <style type="text/css">' + '.Buttons_scan_mess input {' + ' -moz-background-inline-policy:continuous;' + ' border:0 none; cursor:pointer;' + ' height:32px; text-align:center; width:35px;' + '}</style>'; // document.getElementById.getElementsByClassName('infohead')[0].getElementsByTagName('td')[0].innerHTML; var lien_dossier_icone = 'http://snaquekiller.free.fr/ogame/messraide/raidefacile%20mess/'; var bouton_supr_mess_et_scan = '<BR /><div class="Buttons_scan_mess"> <input type="button" title="'+ text.spr_scrptscan_a +'" style=\'background:url("'+ lien_dossier_icone +'supscan2aff.png") no-repeat scroll transparent;\' id="scan_mess_a" mod="9"/>' + '<input type="button" title="'+ text.spr_scrptscan_ns +'" style=\'background:url("'+ lien_dossier_icone +'supscan2nsel.png") no-repeat scroll transparent;\' id="scan_mess_ns" mod="10" />' + '<input type="button" title="'+ text.spr_scrptscan_s +'" style=\'background:url("'+ lien_dossier_icone +'supscan2sel.png") no-repeat scroll transparent;\' id="scan_mess_s" mod="7"/>'; var bouton_supr_scan = ' '+ ' '+'<input type="button" title="'+ text.spr_scan_a +'" style=\'background:url("'+ lien_dossier_icone +'supscanaff.png") no-repeat scroll transparent;\' id="scan_a" />' + '<input type="button" title="'+ text.spr_scan_ns +'" style=\'background:url("'+ lien_dossier_icone +'supscannsel.png") no-repeat scroll transparent;\' id="scan_ns" />' + '<input type="button" title="'+ text.spr_scan_s +'" style=\'background:url("'+ lien_dossier_icone +'supscansel.png") no-repeat scroll transparent;\' id="scan_s" />'; var bouton_add_scan = ' '+ ' '+'<input type="button" title="'+ text.add_scan_a +'" style=\'background:url("'+ lien_dossier_icone +'ajscanaff2.png") no-repeat scroll transparent;\' id="scan_add_a" />' + '<input type="button" title="'+ text.add_scan_ns +'" style=\'background:url("'+ lien_dossier_icone +'ajscannsel2.png") no-repeat scroll transparent;\' id="scan_add_ns" />' + '<input type="button" title="'+ text.add_scan_s +'" style=\'background:url("'+ lien_dossier_icone +'ajscansel2.png") no-repeat scroll transparent;\' id="scan_add_s" /></div>'; var texte_a_affichers = style_css + bouton_supr_mess_et_scan + bouton_supr_scan + bouton_add_scan; var sp1 = document.createElement("span"); // on cree une balise span sp1.setAttribute("id", "Bouton_Rf"); // on y ajoute un id sp1.innerHTML = texte_a_affichers; var element_avant_lenotre = document.getElementById('mailz'); insertAfter(sp1, element_avant_lenotre); // merci a sylvercloud pour les icones document.getElementById("scan_mess_a").addEventListener("click", function (event) { supr_scan_dep_mess(1, true); if (info.firefox) { unsafeWindow.mod = 9; } else { window.mod = 9; } document.getElementsByClassName('buttonOK deleteIt')[0].click(); }, true); document.getElementById("scan_mess_s").addEventListener("click", function (event) { supr_scan_dep_mess(2, true); if (info.firefox) { unsafeWindow.mod = 7; } else { window.mod = 7; } document.getElementsByClassName('buttonOK deleteIt')[0].click(); }, true); document.getElementById("scan_mess_ns").addEventListener("click", function (event) { supr_scan_dep_mess(2, false); if (info.firefox) { unsafeWindow.mod = 10; } else { window.mod = 10; } document.getElementsByClassName('buttonOK deleteIt')[0].click(); }, true); document.getElementById("scan_a").addEventListener("click", function (event) { supr_scan_dep_mess(1, true); }, true); document.getElementById("scan_s").addEventListener("click", function (event) { supr_scan_dep_mess(2, true); }, true); document.getElementById("scan_ns").addEventListener("click", function (event) { supr_scan_dep_mess(2, false); }, true); document.getElementById("scan_add_a").addEventListener("click", function (event) { add_scan_dep_mess(1, true); }, true); document.getElementById("scan_add_s").addEventListener("click", function (event) { add_scan_dep_mess(2, true); }, true); document.getElementById("scan_add_ns").addEventListener("click", function (event) { add_scan_dep_mess(2, false); }, true); } } function add_scan_dep_mess(type_clique, check_q) { //type_clique 1=affiche, 2 = select juste supr scan script , 3/4 idem mais script +scan var nb_scan_total_a_enr = document.getElementsByClassName('material spy').length; var tout_mess = document.getElementById('messageContent').innerHTML; tout_mess = tout_mess.split('switchView(\'spioDetails_'); var nb_scan_plus_un = tout_mess.length; var nb_scan_enregistre = 0; if (type_clique == 2) { for (var nb_scan_s = 1; nb_scan_s < nb_scan_plus_un; nb_scan_s++) { var id_rc = tout_mess[nb_scan_s].split('\');')[0]; if (document.getElementById(id_rc).checked == check_q) { if (save_scan(info.serveur, id_rc, false)) nb_scan_enregistre = nb_scan_enregistre + 1; } } } else if (type_clique == 1) { for (var nb_scan_s = 1; nb_scan_s < nb_scan_plus_un; nb_scan_s++) { var id_rc = tout_mess[nb_scan_s].split('\');')[0]; if (save_scan(info.serveur, id_rc, false)) nb_scan_enregistre = nb_scan_enregistre + 1; } } else { fadeBoxx(i18n('erreur'), true); nb_scan_enregistre = 0; } debugger; fadeBoxx(nb_scan_enregistre + ' ' + i18n('rep_mess_add')); } function supr_scan_dep_mess(type_clique, check_q) { //type_clique 1=affiche, 2 = select juste supr scan script , 3/4 idem mais script +scan var info_scan = GM_getValue('scan' + info.serveur, ''); var info_scan_i = info_scan.split('#'); var nb_scan_total_a_enr = document.getElementsByClassName('material spy').length; var tout_mess = document.getElementById('messageContent').innerHTML; tout_mess = tout_mess.split('switchView(\'spioDetails_'); var nb_scan_plus_un = tout_mess.length; var id_rc; if (type_clique == 2) { for (var nb_scan_s = 1; nb_scan_s < nb_scan_plus_un; nb_scan_s++) { id_rc = tout_mess[nb_scan_s].split('\');')[0]; if (info_scan.indexOf(id_rc) >= 0 && document.getElementById(id_rc).checked == check_q) { for (var p = 0; p < info_scan_i.length; p++) { if (info_scan_i[p].indexOf(id_rc, 0) >= 0) { info_scan_i[p] = ''; } } } } } else if (type_clique == 1) { for (var nb_scan_s = 1; nb_scan_s < nb_scan_plus_un; nb_scan_s++) { id_rc = tout_mess[nb_scan_s].split('\');')[0]; if (info_scan.indexOf(id_rc, 0) >= 0) { for (var p = 0; p < info_scan_i.length; p++) { if (info_scan_i[p].indexOf(id_rc, 0) >= 0) { info_scan_i[p] = ''; } } } } } info_scan_i = info_scan_i.join('#'); info_scan_i = info_scan_i.replace(/\#{2,}/g, "#"); GM_setValue('scan' + info.serveur, info_scan_i); fadeBoxx(text.rep_mess_supri, 0, 3000); } function scan_pop_up() { var pop_up = $('div.showmessage[data-message-id]'); if (!pop_up.length) { // il n'y a pas de popup return; } if (info.chrome) { $('.contentPageNavi a', pop_up).click(function () { setTimeout(waitAjaxSuccessPopup, 333); }); } var msg_id = pop_up.attr('data-message-id'); if ($('.textWrapper .material.spy', pop_up).length) { if (scan_preenrgistre == 1) { save_scan(info.serveur, msg_id, true, true); } var tout_supr = ''; // tout_supr += '<li class="delete" ><a class="tips2 action" id="2" href=""><span class="icon icon_trash float_left" id="RF_icon_delMEssScan"></span><span class="text" id="RF_delMEssScan">'+ text.del_scan_script +'</span></a></li>'; tout_supr += '<li class="delete" ><a class="tips2 action" href=""><span class="icon icon_trash float_left" id="RF_icon_delScan"></span><span class="text" id="RF_delScan">' + text.del_script + '</span></a></li>'; tout_supr += '<li class="delete" ><a href=""><span class="icon float_left" style="background-position: 0 -64px; id="RF_icon_addScan"></span><span class="text" id="RF_addScan">' + text.add_scan_d + '</span></a></li>'; var newElement = $(tout_supr); // $('#RF_delMEssScan', newElement).closest('a').click(function(e){supr_scan1(info.serveur);}); $('#RF_delScan', newElement).closest('a').click(function (e) { e.preventDefault(); supr_scan1(info.serveur); }); $('#RF_addScan', newElement).closest('a').click(function (e) { e.preventDefault(); save_scan(info.serveur, msg_id, true, true); }); newElement.insertBefore('.toolbar .delete', pop_up); } } //} /*######################################### SCRIPT ################################################## */ init2(); /////////////////// Scan des Rapports d'espionnage /////////////////// if (info.page === 'messages') { function sauve_option2() { if (document.getElementById('messageContent')) { var scans = $('#mailz > tbody > tr[id^="spioDetails"]'); if (!scans.length) { // pas de rapport d'espionnage disponible return; } // "Afficher le rapport d`espionnage complet" est coché // On a au moins un rapport d'espionnage var nb_scan_enregistre = 0; for (var i = 0; i < scans.length; i++) { if (scan_preenrgistre == 1) { if (save_scan(info.serveur, scans[i].id.replace('spioDetails_', ''), false)) { ++nb_scan_enregistre; } } } if (nb_scan_enregistre > 0) { fadeBoxx(nb_scan_enregistre + ' ' + i18n('rep_mess_add')); } } } function safeWrap(f) { return function () { setTimeout.apply(window, [f, 0].concat([].slice.call(arguments))); }; } // switch des actions suivant la catégorie function switchCat(cat) { switch (cat) {/*7 espionner , 5combat , 6joueur , 8expe,2 alli, 4 divers ^^*/ case "9": case "7": case "10": sauve_option2(); if (q_icone_mess == 1) { bouton_supr_scan_depuis_mess(); } break; } } // SCAN PREVOUERT var waitAjaxSuccessPreouvert = function () { // on vérifie si l'image de chargement est encore là if ($('#messageContent>img').length) { logger.log('Attente des messages'); setTimeout(waitAjaxSuccessPreouvert, 333); } else { var form = $('#messageContent>form'); // si on est sur le carnet d'adresse on ne fait rien if (!form.length) return; // récupération de la catégorie var cat = $('#messageContent>form').attr('action').replace(/^.*displayCategory=([\d-]*).*$/, "$1"); switchCat(cat); } }; // en cas de clic on attend que l'action se fasse $('.mailWrapper, #tab-msg').on('click keypress', function (e) { setTimeout(waitAjaxSuccessPreouvert, 333); }); waitAjaxSuccessPreouvert(); // SCAN POPUP var waitAjaxSuccessPopup = function () { // on vérifie si l'image de chargement est encore là if ($('#messageContent>img').length) { logger.log('Attente de la popup'); setTimeout(waitAjaxSuccessPopup, 333); } else { var form = $('#messageContent>form'); // si on est sur le carnet d'adresse on ne fait rien if (!form.length) return; scan_pop_up(); } }; // en cas de clic on attend que l'action se fasse $('.mailWrapper, #tab-msg').on('click keypress', function (e) { setTimeout(waitAjaxSuccessPopup, 333); }); waitAjaxSuccessPopup(); } /////////////////// TABLEAU /////////////////// else if (info.page === 'tableauRaidFacile' || info.page === 'optionsRaidFacile') { var planetes = document.querySelectorAll('a.planetlink, a.moonlink'); for (var i = 0; i < planetes.length; ++i) { planetes[i].setAttribute('href', planetes[i].getAttribute('href') + '#raidFacile=tableau&go'); } /* ********************** On recupere les infos ************************/ var url_2 = info.url.split('&raidefacil=scriptOptions')[0]; var scanList = GM_getValue('scan' + info.serveur, '').split('#'); var bbcode_export = ' '; if ((info.url.indexOf('&del_scan=', 0)) >= 0) { var numero_scan = info.url.split('del_scan=')[1].split('&')[0]; scanList.splice(numero_scan, 1); GM_setValue('scan' + info.serveur, scanList.join('#')); } /************************************** Trie du tableau ******************************************************/ function trie_tableau(serveur, classementsecondaire, type_trie) { var scan_i = GM_getValue('scan' + serveur, '').split('#'); var nb = scan_i.length; for (var h = 0; h < nb; h++) {// on split chaque scan en un tableau scan_i[h] = scan_i[h].split(';'); } if (nb_scan_page != 0) { var num_page = info.url.split('&page_r=')[1]; if (num_page == undefined || num_page == 1) { var nb_scan_deb = 0; var nb_scan_fin = nb_scan_page; } else if (num_page >= 1) { var nb_scan_deb = (parseInt(num_page) - 1) * nb_scan_page; var nb_scan_fin = parseInt(num_page) * nb_scan_page; } } else { var nb_scan_fin = nb; var nb_scan_deb = 0; } //("ccoordonee","cplanete","cdate","cprod_h","cressourcexh","cress","ccdr","ccdr_ress","cnb_v1","cnb_v2","cnb_d1","cnb_d2"); //("1","3","0","20e","20d","12","8","20c","17","22","18","23"); // pour classement par colone if (classementsecondaire != -1 && classementsecondaire != -2 && classementsecondaire != undefined) classement = classementsecondaire; if (parseInt(classement.replace(/[^0-9-]/g, "")) == 1) {//si le classement est par coordonee on fait que les coordonees soit classable for (var gh = 0; gh < nb; gh++) { if (scan_i[gh] != undefined && scan_i[gh].indexOf(';;;;;;;;;;;;;;;;;x;;') == -1) { if (scan_i[gh][9] != undefined && scan_i[gh][1].split(':')[1]) { //on recupere les coordonées var coordosplit = scan_i[gh][1].split(':'); var galaxie = coordosplit[0].replace(/[^0-9-]/g, ""); var systeme = coordosplit[1].replace(/[^0-9-]/g, ""); var planette = coordosplit[2].replace(/[^0-9-]/g, ""); // on fait ques les systeme soit en 3 chiffre et les planetes soit en deux if (parseInt(systeme) < 100) { if (parseInt(systeme) < 10) systeme = '00' + '' + systeme; else systeme = '0' + '' + systeme; } if (parseInt(planette) < 10) { planette = '0' + '' + planette; } // on met les "nouvellle coordonée". avec '' pour bien que les system /galaxie ne se melange pas scan_i[gh][20] = parseInt(galaxie + '' + systeme + '' + planette); } } } } else if (classement == '20c') {//classement par cdr + ressources. for (var gh = 0; gh < nb; gh++) { if (scan_i[gh] != undefined) { if (scan_i[gh][9] != undefined && scan_i[gh].indexOf(';;;;;;;;;;;;;;;;;x;;') == -1) { //ressource var ressource_m = scan_i[gh][4]; var ressource_c = scan_i[gh][5]; var ressource_d = scan_i[gh][6]; var ressource_total = parseInt(ressource_m) * q_taux_m + parseInt(ressource_c) * q_taux_c + parseInt(ressource_d) * q_taux_d; var pourcent = 50; if (scan_i[gh][24] == "ph") pourcent = 75; if (scan_i[gh][25] == "b1" || scan_i[gh][25] == "b2" || scan_i[gh][25] == "b3") pourcent = 100; //cdr possible avec flotte var cdr_possible_m = Math.round(parseInt(scan_i[gh][15]) * pourcent_cdr); var cdr_possible_c = Math.round(parseInt(scan_i[gh][16]) * pourcent_cdr); //cdr defense var cdr_def = scan_i[gh][21] ? scan_i[gh][21].split('/') : '?'; if (cdr_def[0] != '?' && pourcent_cdr_def != 0 && cdr_def != 'undefined') { var cdr_possible_def_m = Math.round(parseInt(cdr_def[1]) * pourcent_cdr_def); var cdr_possible_def_c = Math.round(parseInt(cdr_def[2]) * pourcent_cdr_def); } else {//du a la transition des rapports qui ne comptait pas encore les cdr de defense var cdr_possible_def_m = 0; var cdr_possible_def_c = 0; } var cdr_possible_def_total = cdr_possible_def_m * q_taux_m + cdr_possible_def_c * q_taux_c; var cdr_ressource = ressource_total * (pourcent / 100) + cdr_possible_m * q_taux_m + cdr_possible_c * q_taux_c + cdr_possible_def_total; scan_i[gh][20] = cdr_ressource; } else { scan_i[gh][20] = '-1'; } } } } else if (classement == '20d') {//classement des ressources dans x heures for (var gh = 0; gh < nb; gh++) { if (scan_i[gh] != undefined) { if (scan_i[gh][9] != undefined && scan_i[gh] != ';;;;;;;;;;;;;;;;;x;;' && scan_i[gh][1].split(':')[2]) { // batiment adversaire + prodh + resrrouce x h //+bat +prod/h var coordonee = scan_i[gh][1]; var mine_array = scan_i[gh][19].split('/'); var mine_m = mine_array[0]; var mine_c = mine_array[1]; var mine_d = mine_array[2]; //ressource x h if (mine_array != '?/?/?' && coordonee) { var prod_t = calcule_prod(mine_m, mine_c, mine_d, coordonee, '?'); var prod_m_h = prod_t.metal; var prod_c_h = prod_t.cristal; var prod_d_h = prod_t.deut; //ressource var ressource_m = scan_i[gh][4]; var ressource_c = scan_i[gh][5]; var ressource_d = scan_i[gh][6]; var ressource_total = parseInt(ressource_m) + parseInt(ressource_c) + parseInt(ressource_d); var prod_m_xh = parseInt(prod_m_h) * (parseInt(prod_gg) / 60); var prod_c_xh = parseInt(prod_c_h) * (parseInt(prod_gg) / 60); var prod_d_xh = parseInt(prod_d_h) * (parseInt(prod_gg) / 60); var ressource_m_xh = parseInt(ressource_m) + prod_m_xh; var ressource_c_xh = parseInt(ressource_c) + prod_c_xh; var ressource_d_xh = parseInt(ressource_d) + prod_d_xh; var ressource_tt_xh = ressource_m_xh * q_taux_m + ressource_c_xh * q_taux_c + ressource_d_xh * q_taux_d; scan_i[gh][20] = ressource_tt_xh; } else { scan_i[gh][20] = '-1'; } } else { scan_i[gh][20] = '-1'; } } } } else if (classement == '20e') {//si c'est le classement par production par heure for (var gh = 0; gh < nb; gh++) { if (scan_i[gh] != undefined && scan_i[gh].indexOf(';;;;;;;;;;;;;;;;;x;;') == -1) { if (scan_i[gh][9] != undefined) { // batiment adversaire + prodh + resrrouce x h //+bat +prod/h var mine_array = scan_i[gh][19].split('/'); var mine_m = mine_array[0]; var mine_c = mine_array[1]; var mine_d = mine_array[2]; var coordonee = scan_i[gh][1]; if (mine_array != '?/?/?') { var prod_t = calcule_prod(mine_m, mine_c, mine_d, coordonee, '?'); var prod_m_h = prod_t.metal; var prod_c_h = prod_t.cristal; var prod_d_h = prod_t.deut; var prod_tot = parseInt(prod_m_h) * q_taux_m + parseInt(prod_c_h) * q_taux_c + parseInt(prod_d_h) * q_taux_d; scan_i[gh][20] = prod_tot; } else { scan_i[gh][20] = '-1'; } } else { scan_i[gh][20] = '-1'; } } } } else if (parseInt(classement.replace(/[^0-9-]/g, "")) == 12) {// classement par ressources for (var gh = 0; gh < nb; gh++) { if (scan_i[gh] != undefined && scan_i[gh].indexOf(';;;;;;;;;;;;;;;;;x;;') == -1) { if (scan_i[gh][9] != undefined) { //ressource var ressource_m = scan_i[gh][4]; var ressource_c = scan_i[gh][5]; var ressource_d = scan_i[gh][6]; var ressource_total = parseInt(ressource_m) * q_taux_m + parseInt(ressource_c) * q_taux_c + parseInt(ressource_d) * q_taux_d; var pourcent = 50; if (scan_i[gh][24] == "ph") pourcent = 75; if (scan_i[gh][25] == "b1" || scan_i[gh][25] == "b2" || scan_i[gh][25] == "b3") pourcent = 100; scan_i[gh][20] = ressource_total * (pourcent / 100); } else { scan_i[gh][20] = '-1'; } } } } if (classement == 2 || classement == 3) { // si c'est un classement par rapport au nom de joueur ou de planète var sort_Info = function (a, b) { return strcmp(a[parseInt(classement.replace(/[^0-9-]/g, ""))], b[parseInt(classement.replace(/[^0-9-]/g, ""))]); }; } else if (classement == 12 || classement == 1) { // si c'est par ressources ou par coordonnées var sort_Info = function (a, b) { return b[20] - a[20]; }; } else { var sort_Info = function (a, b) { return b[parseInt(classement.replace(/[^0-9-]/g, ""))] - a[parseInt(classement.replace(/[^0-9-]/g, ""))]; }; } if (parseInt(classement.replace(/[^0-9-]/g, "")) > -1) scan_i.sort(sort_Info); // si on a fait a coché la case reverse ou que l'on trie grace au colone if (reverse == '0' || type_trie == 'decroissant') scan_i.reverse(); // On remet à x la valeur qui nous a servir pour le tri if (parseInt(classement.replace(/[^0-9-]/g, "")) == 20 || classement == 12 || classement == 1) { for (var gh = 0; gh < nb; gh++) { if (scan_i[gh] != undefined) scan_i[gh][20] = 'x'; } } for (var h = 0; h < nb; h++) { scan_i[h] = scan_i[h].join(';'); } GM_setValue('scan' + serveur, scan_i.join('#')); } // fin fonction trie_tableau /*************************************************** ON AFFICHE LE TABLEAU ****************************************************************/ function afficher_ligne_interieur_tab(serveur) { var scan_info = GM_getValue('scan' + serveur, '').split('#'); var ligne_tableau = ' '; var nb = scan_info.length; var nb_scan_deb_fin = connaitre_scan_afficher(serveur, nb_scan_page, info.url, nb); var nb_scan_fin = nb_scan_deb_fin[0]; var nb_scan_deb = nb_scan_deb_fin[1]; var url_2 = info.url.split('&raidefacil=scriptOptions')[0]; var bbcode_export = ' '; //var inactif_normal = GM_getValue('inactif', ''); //on recupere les infos sur les attaques des 24h dernieres suprimmer_attaque_24h_inutile(); var attaque_24h = GM_getValue('attaque_24h', ''); var attaque_24h_split = attaque_24h.split('#'); var attaque_24h_split2 = attaque_24h_split; for (var x = 0; x < attaque_24h_split.length; x++) { attaque_24h_split2[x] = attaque_24h_split[x].split('/'); } // on regarde la planette selectionner(liste de droite des planettes) pour connaitre la galaxie if (document.getElementsByName('ogame-planet-coordinates')[0]) { var coordonnee_slelec = document.getElementsByName('ogame-planet-coordinates')[0].content; } else { if (pos_depart != 'x:xxx:x') { var coordonnee_slelec = pos_depart; } else { var coordonnee_slelec = '0'; } } // on les utilises et les place var cptLigne = 0; for (var i = nb_scan_deb; i < nb_scan_fin; i++) { if (scan_info[i] != undefined && scan_info[i] != ';;;;;;;;;;;;;;;;;x;;') { var scan_info_i = scan_info[i].split(';'); //on verifie si c'est ok pour l'afficher if (scan_info_i[9] != undefined && scan_info_i[1].split(':')[1] && (q_flo_vis == 1 || scan_info_i[9] != '?/?/?/?/?/?/?/?/?/?/?/?/?/') && (q_def_vis == 1 || scan_info_i[10] != '?/?/?/?/?/?/?/?/?/?')) { //on veut savoir si on n'affiche que les scan de la galaxie, si oui on vérifie la galaxie if((q_galaxie_scan == 1 && coordonnee_slelec.split(':')[0].replace( /[^0-9-]/g, "") == scan_info_i[1].split(':')[0].replace( /[^0-9-]/g, "")) || q_galaxie_scan == 0 || (galaxie_demande == scan_info_i[1].split(':')[0].replace( /[^0-9-]/g, "") && q_galaxie_scan == 2) || (q_galaxie_scan == 3 && (parseInt(coordonnee_slelec.split(':')[0].replace( /[^0-9-]/g, "")) + galaxie_plus_ou_moins) >= parseInt(scan_info_i[1].split(':')[0].replace( /[^0-9-]/g, "")) && (parseInt(coordonnee_slelec.split(':')[0].replace( /[^0-9-]/g, "")) - galaxie_plus_ou_moins) <= parseInt(scan_info_i[1].split(':')[0].replace( /[^0-9-]/g, ""))) || filtre_joueur != '' //si on filtre sur le joueur, on affiche toutes les coordonnées ){ //###### Gestion des filtres ######// var filtre = false; // on regarde ce qu'on affiche : planette + lune = 0, planette =1 , lune =2 if( (afficher_seulement == 0) || (afficher_seulement == 1 && scan_info_i[14]== 1) || (afficher_seulement == 2 && scan_info_i[14]!= 1) ) // on regarde ce qu'on affiche : actif + inactif = 0, actif =1 , inactif =2 if( (filtre_actif_inactif == 0) || (filtre_actif_inactif == 1 && scan_info_i[24]!= 'i' && scan_info_i[24]!= 'I' ) || (filtre_actif_inactif == 2 && (scan_info_i[24]== 'i' || scan_info_i[24]== 'I')) ) // on regarde le joueur qu'on affiche if ((filtre_joueur == '') || (filtre_joueur != '' && filtre_joueur.toLowerCase() == scan_info_i[2].toLowerCase())) filtre = true; if (filtre) { // date var date_scan = parseInt(scan_info_i[0]); var datecc = new Date(); datecc.setTime(date_scan); var date_final = datecc.getDate() + '/' + (datecc.getMonth() + 1) + '/' + datecc.getFullYear() + ' ' + datecc.getHours() + ':' + datecc.getMinutes() + ':' + datecc.getSeconds(); // si la date est demander en chronos var date2; if (q_date_type_rep == 0) { var datecc2 = (info.ogameMeta['ogame-timestamp'] ? parseInt(info.ogameMeta['ogame-timestamp']) * 1000 : info.startTime) - date_scan; date2 = timeFormat(datecc2 / 1000); } else { date2 = ((datecc.getDate() < 10) ? '0' : '') + datecc.getDate() + '/' + (datecc.getMonth() < 10 ? '0' : '') + (datecc.getMonth() + 1) + '/' + (datecc.getFullYear() - 2000) + ' ' + (datecc.getHours() < 10 ? '0' : '') + datecc.getHours() + ':' + (datecc.getMinutes() < 10 ? '0' : '') + datecc.getMinutes() + ':' + (datecc.getSeconds() < 10 ? '0' : '') + datecc.getSeconds(); } // type de la planette var type_planette = scan_info_i[14]; var l_q = ''; if (type_planette != 1) { l_q = ' L'; } //nom joueur et planette var nom_joueur = scan_info_i[2]; var nom_planete_complet = scan_info_i[3]; if (nom_planete_complet.indexOf('1diez1') >= 0) { nom_planete_complet = nom_planete_complet.replace(/1diez1/g, "#"); } var nom_planete = raccourcir(nom_planete_complet); //coordonee + url var coordonee = scan_info_i[1]; var coordonee_split = coordonee.split(':'); var galaxie = (coordonee_split[0]).replace(/[^0-9-]/g, ""); var systeme = (coordonee_split[1]).replace(/[^0-9-]/g, ""); var planette = (coordonee_split[2]).replace(/[^0-9-]/g, ""); var url_galaxie = document.getElementById("menuTable").getElementsByClassName('menubutton ')[8].href; var url_fleet1 = document.getElementById("menuTable").getElementsByClassName('menubutton ')[7].href; if (espionnage_lien == 1) { var espionnage = url_fleet1 + '&galaxy=' + galaxie + '&system=' + systeme + '&position=' + planette + '&type=' + type_planette + '&mission=6'; } else if (espionnage_lien == 0) { var espionnage = url_galaxie + '&galaxy=' + galaxie + '&system=' + systeme + '&position=' + planette + '&planetType=1&doScan=1'; } var coordonee_fin = '<a href="' + url_galaxie + '&galaxy=' + galaxie + '&system=' + systeme + '&position=' + planette + '"'; if (nom_j_q_q != 1 && nom_p_q_q != 1) coordonee_fin += ' title=" Planette: ' + nom_planete_complet.replace(/"/g, '&quot;') + ' | Joueur: ' + nom_joueur + '">'; else if (nom_j_q_q != 1) coordonee_fin += ' title=" Joueur: ' + nom_joueur + '">'; else if (nom_p_q_q != 1) coordonee_fin += ' title=" Planette: ' + nom_planete_complet.replace(/"/g, '&quot;') + '">'; else coordonee_fin += '>'; coordonee_fin += coordonee + l_q + '</a>'; var pourcent = 50; var type_joueur = scan_info_i[24] ? scan_info_i[24] : '&nbsp'; if (type_joueur == "ph") { type_joueur = '<span class="status_abbr_honorableTarget">' + type_joueur + '</span>'; pourcent = 75; } else if (type_joueur == "o") type_joueur = '<span class="status_abbr_outlaw">' + type_joueur + '</span>'; else if (type_joueur == "i") type_joueur = '<span class="status_abbr_inactive">' + type_joueur + '</span>'; else if (type_joueur == "I") type_joueur = '<span class="status_abbr_longinactive">' + type_joueur + '</span>'; else if (type_joueur == "f") type_joueur = '<span class="status_abbr_strong">' + type_joueur + '</span>'; else if (type_joueur == "v") type_joueur = '<span class="status_abbr_vacation">' + type_joueur + '</span>'; var type_honor = scan_info_i[25] ? scan_info_i[25] : '&nbsp'; if (type_honor == "b1") { type_honor = '<span class="honorRank rank_bandit1"></span>'; pourcent = 100; } else if (type_honor == "b2") { type_honor = '<span class="honorRank rank_bandit2"></span>'; pourcent = 100; } else if (type_honor == "b3") { type_honor = '<span class="honorRank rank_bandit3"></span>'; pourcent = 100; } else if (type_honor == "s1") type_honor = '<span class="honorRank rank_starlord1"></span>'; else if (type_honor == "s2") type_honor = '<span class="honorRank rank_starlord2"></span>'; else if (type_honor == "s3") type_honor = '<span class="honorRank rank_starlord3"></span>'; //activite var activite = scan_info_i[7]; if (activite == 'rien') { var activite_fin = ' '; } else { if (parseInt(activite) <= 15) { var activite_fin = '<img style="width: 12px; height: 12px;" src="http://gf1.geo.gfsrv.net/cdn12/b4c8503dd1f37dc9924909d28f3b26.gif" alt="' + activite + ' min " title="' + activite + ' min"/>'; } else { var activite_fin = '<span style="background-color: #000000;border: 1px solid #FFA800;border-radius: 3px 3px 3px 3px;color: #FFA800;">' + activite + '</span>'; } } //ressource var ressource_m = scan_info_i[4]; var ressource_c = scan_info_i[5]; var ressource_d = scan_info_i[6]; var nb_pt = shipCount(parseInt(ressource_m), parseInt(ressource_c), parseInt(ressource_d), 5000, pourcent); var nb_gt = shipCount(parseInt(ressource_m), parseInt(ressource_c), parseInt(ressource_d), 25000, pourcent); var ressource_total = parseInt(ressource_m) + parseInt(ressource_c) + parseInt(ressource_d); if (question_rassemble_col == 0) { var ressourceTitle = [ pourcent + '% de ressources pillables', addPoints(nb_pt) + ' ' + text.nb_pt + ' | ' + addPoints(nb_gt) + ' ' + text.nb_gt, text.metal + ': ' + addPoints(Math.round(parseInt(ressource_m) * (pourcent / 100))) + ' | ' + text.cristal + ': ' + addPoints(Math.round(parseInt(ressource_c) * (pourcent / 100))) + ' | ' + text.deut + ': ' + addPoints(Math.round(parseInt(ressource_d) * (pourcent / 100))) ]; var ressource = '<acronym title="' + ressourceTitle.join('<br>') + '">' + addPoints(Math.round(ressource_total * (pourcent / 100))) + '</acronym>'; } // vitesse minimum. var accronyme_temp_vol = vaisseau_vitesse_mini(tech_impul_a, tech_hyper_a, tech_combus_a, vaisseau_lent, coordonee); //cdr possible var cdr_possible = Math.round(parseInt(scan_info_i[8]) * pourcent_cdr); var cdr_possible_m = Math.round(parseInt(scan_info_i[15]) * pourcent_cdr); var cdr_possible_c = Math.round(parseInt(scan_info_i[16]) * pourcent_cdr); // on verifie que cdr possible existe et soit un chiffre if (cdr_possible == '?' || isNaN(cdr_possible)) { var cdr_aff = 0; cdr_possible = '?'; } else { var cdr_aff = cdr_possible; } // cdr de défense // on verifie que le cdr def est bien creer dans le scan info if (scan_info_i[21]) { var cdr_def = scan_info_i[21].split('/'); } else { var cdr_def = '?'; } if (cdr_def[0] != '?' && pourcent_cdr_def != 0 && cdr_def != 'undefined') { var cdr_possible_def = Math.round(parseInt(cdr_def[0]) * pourcent_cdr_def); var cdr_possible_def_m = Math.round(parseInt(cdr_def[1]) * pourcent_cdr_def); var cdr_possible_def_c = Math.round(parseInt(cdr_def[2]) * pourcent_cdr_def); } else { var cdr_possible_def = 0; var cdr_possible_def_m = 0; var cdr_possible_def_c = 0; } if (cdr_possible != '?') { cdr_possible = cdr_possible + cdr_possible_def; } else { cdr_possible = cdr_possible; } cdr_aff = cdr_aff + cdr_possible_def; cdr_possible_m = cdr_possible_m + cdr_possible_def_m; cdr_possible_c = cdr_possible_c + cdr_possible_def_c; if (isNaN(cdr_aff)) { cdr_aff = 0; } else { cdr_aff = cdr_aff; } if (question_rassemble_col == 0) { var cdrTitle = addPoints(Math.ceil(cdr_aff / 20000)) + ' ' + text.nb_rc + '<br>' + text.met_rc + ': ' + addPoints(cdr_possible_m) + ' | ' + text.cri_rc + ': ' + addPoints(cdr_possible_c); var cdrDisplayedNumber = addPoints(cdr_q_type_affiche === 0 ? cdr_possible : Math.ceil(cdr_aff / 20000)); var cdr_aco = '<acronym title="' + cdrTitle + ' ">' + cdrDisplayedNumber + '</acronym>'; } // colonne cdr + resource if (question_rassemble_col == 1) { var col_cdr = '<acronym title="' + pourcent + '% | ' + addPoints(nb_pt) + text.nb_pt + '/' + addPoints(nb_gt) + text.nb_gt + ' | ' + text.metal + ': ' + addPoints(Math.round(parseInt(ressource_m) * (pourcent / 100))) + ' | ' + text.cristal + ': ' + addPoints(Math.round(parseInt(ressource_c) * (pourcent / 100))) + ' | ' + text.deut + ': ' + addPoints(Math.round(parseInt(ressource_d) * (pourcent / 100))) + '\n' + addPoints(Math.ceil(cdr_aff / 20000)) + text.nb_rc + ' | ' + text.met_rc + ': ' + addPoints(cdr_possible_m) + ' | ' + text.cri_rc + ': ' + addPoints(cdr_possible_c) + '">' + addPoints(cdr_aff + Math.round(ressource_total * (pourcent / 100))) + '</acronym>'; } //recherhe adersersaire var recherche_ad = scan_info_i[13].split('/'); var tech_arme_d = recherche_ad[0]; var tech_bouclier_d = recherche_ad[1]; var tech_protect_d = recherche_ad[2]; //recupere vaisseau et defense var vaisseau_type = new Array(vari.pt, vari.gt, vari.cle, vari.clo, vari.cro, vari.vb, vari.vc, vari.rec, vari.esp, vari.bb, vari.sat, vari.dest, vari.edlm, vari.tra); var defense_type = new Array(i18n.get('lm'), i18n.get('lle'), i18n.get('llo'), i18n.get('gauss'), i18n.get('ion'), i18n.get('pla'), i18n.get('pb'), i18n.get('gb'), i18n.get('mic'), i18n.get('mip')); //type pour les different simulateur. var vaisseau_speed = new Array("ship_d0_0_b", "ship_d0_1_b", "ship_d0_2_b", "ship_d0_3_b", "ship_d0_4_b", "ship_d0_5_b", "ship_d0_6_b", "ship_d0_7_b", "ship_d0_8_b", "ship_d0_9_b", "ship_d0_10_b", "ship_d0_11_b", "ship_d0_12_b", "ship_d0_13_b"); var def_speed = new Array("ship_d0_14_b", "ship_d0_15_b", "ship_d0_16_b", "ship_d0_17_b", "ship_d0_18_b", "ship_d0_19_b", "ship_d0_20_b", "ship_d0_21_b", "abm_b", ""); var vaisseau_win = new Array("d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "d10", "d11", "d12", "d13"); var def_win = new Array("d14", "d15", "d16", "d17", "d18", "d19", "d20", "d21", "", ""); var vaisseau_drag = new Array("numunits[1][0][k_t]", "numunits[1][0][g_t]", "numunits[1][0][l_j]", "numunits[1][0][s_j]", "numunits[1][0][kr]", "numunits[1][0][sc]", "numunits[1][0][ko]", "numunits[1][0][re]", "numunits[1][0][sp]", "numunits[1][0][bo]", "numunits[1][0][so]", "numunits[1][0][z]", "numunits[1][0][t]", "numunits[1][0][sk]"); var def_drag = new Array("numunits[1][0][ra]", "numunits[1][0][l_l]", "numunits[1][0][s_l]", "numunits[1][0][g]", "numunits[1][0][i]", "numunits[1][0][p]", "numunits[1][0][k_s]", "numunits[1][0][g_s]", "missiles_available_v", ""); var url_dragosim = ''; var url_speedsim = ''; var url_ogamewinner = ''; // def et vaisseau variable var acronyme_vaisseau = ' '; var nb_totalvaisseau = 0; var acronyme_def = i18n.get('th_nd') + '<div class="splitLine"></div>'; var nb_totaldef = 0; var vaisseau22 = scan_info_i[9]; if (vaisseau22 != '?/?/?/?/?/?/?/?/?/?/?/?/?/?') { var vaisseau = vaisseau22.split('/'); for (var k = 0; k < vaisseau.length; k++) { if (parseInt(vaisseau[k]) != 0) { acronyme_vaisseau = acronyme_vaisseau + ' | ' + vaisseau_type[k] + ' : ' + addPoints(parseInt(vaisseau[k])); nb_totalvaisseau = nb_totalvaisseau + parseInt(vaisseau[k]); url_speedsim = url_speedsim + '&amp;' + vaisseau_speed[k] + '=' + parseInt(vaisseau[k]); url_dragosim = url_dragosim + '&amp;' + vaisseau_drag[k] + '=' + parseInt(vaisseau[k]); url_ogamewinner = url_ogamewinner + '&amp;' + vaisseau_win[k] + '=' + parseInt(vaisseau[k]); } } nb_totalvaisseau = addPoints(nb_totalvaisseau); } else { var vaisseau = vaisseau22.split('/'); acronyme_vaisseau = '?'; nb_totalvaisseau = '?'; } var defense2 = scan_info_i[10]; if (defense2 != '?/?/?/?/?/?/?/?/?/?') { var defense = defense2.split('/'); for (var k = 0; k < defense.length; k++) { if (parseInt(defense[k]) != 0) { acronyme_def = acronyme_def + '<br>' + defense_type[k] + ' : ' + addPoints(parseInt(defense[k])); url_speedsim = url_speedsim + '&amp;' + def_speed[k] + '=' + parseInt(defense[k]); url_dragosim = url_dragosim + '&amp;' + def_drag[k] + '=' + parseInt(defense[k]); url_ogamewinner = url_ogamewinner + '&amp;' + def_win[k] + '=' + parseInt(defense[k]); if (k != 8 && k != 9) {// si k n'est pas des missiles (interplanetaire ou de def) nb_totaldef = nb_totaldef + parseInt(defense[k]); } } } nb_totaldef = addPoints(nb_totaldef); } else { var defense = defense2.split('/'); acronyme_def = '?'; nb_totaldef = '?'; } var acronyme_vaisseau2 = ''; if (vaisseau_question == 1) acronyme_vaisseau2 = '<acronym title=" ' + acronyme_vaisseau + '">' + nb_totalvaisseau + '</acronym>'; else if (vaisseau_question == 2 && (scan_info_i[22] == '?' || !scan_info_i[2])) acronyme_vaisseau2 = '<acronym title=" ' + acronyme_vaisseau + ',' + text.c_nbv + ' ' + nb_totalvaisseau + ' ">?</acronym>'; else if (vaisseau_question == 2) acronyme_vaisseau2 = '<acronym title=" ' + acronyme_vaisseau + ',' + text.c_nbv + ' ' + nb_totalvaisseau + ' ">' + addPoints(parseInt(scan_info_i[22])) + '</acronym>'; var acronyme_def2 = ''; // ------------------------------------------------------------------------------------------------- if (defense_question == 1) acronyme_def2 = '<div class="tooltipTitle">' + acronyme_def + '</div><acronym>' + nb_totaldef + '</acronym>'; else if (defense_question == 2 && (scan_info_i[23] == '?' || !scan_info_i[23])) acronyme_def2 = '<div class="tooltipTitle">' + acronyme_def + ',' + text.c_nbd + ' ' + nb_totaldef + '</div><acronym>?</acronym>'; else if (defense_question == 2) acronyme_def2 = '<div class="tooltipTitle>" ' + acronyme_def + ',' + text.c_nbd + ' ' + nb_totaldef + '</div><acronym>' + addPoints(parseInt(scan_info_i[23])) + '</acronym>'; // ------------------------------------------------------------------------------------------------- //url d'attaque //am202 = pt / am203 = gt var url_fleet1 = document.getElementById("menuTable").getElementsByClassName('menubutton ')[7].href; var url_attaquer = url_fleet1 + '&galaxy=' + galaxie + '&system=' + systeme + '&position=' + planette + '&type=' + type_planette + '&mission=1'; if (lien_raide_nb_pt_gt == 1) { var nb_pt2; if (nb_ou_pourcent == 1) { nb_pt2 = nb_pt + nb_pourcent_ajout_lien; } else { nb_pt2 = Math.ceil(nb_pt + (nb_pt / 100) * nb_pourcent_ajout_lien); } url_attaquer += '&am202=' + nb_pt2; } else if (lien_raide_nb_pt_gt == 0) { var nb_gt2; if (nb_ou_pourcent == 1) { nb_gt2 = nb_gt + nb_pourcent_ajout_lien; } else { nb_gt2 = Math.ceil(nb_gt + (nb_gt / 100) * nb_pourcent_ajout_lien); } url_attaquer += '&am203=' + nb_gt2; } // url de simulation if (q_techzero == 1 && recherche_ad[0] == "?") { var tech_arme_a_sim = 0; var tech_protect_a_sim = 0; var tech_bouclier_a_sim = 0; var tech_arme_d_sim = 0; var tech_bouclier_d_sim = 0; var tech_protect_d_sim = 0; } else { var tech_arme_a_sim = tech_arme_a; var tech_protect_a_sim = tech_protect_a; var tech_bouclier_a_sim = tech_bouclier_a; var tech_arme_d_sim = tech_arme_d; var tech_bouclier_d_sim = tech_bouclier_d; var tech_protect_d_sim = tech_protect_d; } if (simulateur == 1) { var url_simul = 'http://websim.speedsim.net/index.php?version=1&lang=' + vari.lang_speedsin + '&tech_a0_0=' + tech_arme_a_sim + '&tech_a0_1=' + tech_bouclier_a_sim + '&tech_a0_2=' + tech_protect_a_sim + '&engine0_0=' + tech_combus_a + '&engine0_1=' + tech_impul_a + '&engine0_2=' + tech_hyper_a + '&start_pos=' + coordonnee_slelec + '&tech_d0_0=' + tech_arme_d_sim + '&tech_d0_1=' + tech_bouclier_d_sim + '&tech_d0_2=' + tech_protect_d_sim + '&enemy_name=' + nom_planete_complet.replace(/"/g, '&quot;') + '&perc-df=' + (pourcent_cdr * 100) + '&enemy_pos=' + coordonee + '&enemy_metal=' + parseInt(ressource_m) + '&enemy_crystal=' + parseInt(ressource_c) + '&enemy_deut=' + parseInt(ressource_d) + url_speedsim + '&uni_speed=' + vitesse_uni + '&perc-df=' + pourcent_cdr * 100 + '&plunder_perc=' + pourcent + '&del_techs=1&rf=1'; } else if (simulateur == 0) { var url_simul = 'http://drago-sim.com/index.php?style=new&template=New&lang=' + vari.lang_dragosin + '&' + 'techs[0][0][w_t]=' + tech_arme_a_sim + '&techs[0][0][s_t]=' + tech_bouclier_a_sim + '&techs[0][0][r_p]=' + tech_protect_a_sim + '&engine0_0=' + tech_combus_a + '&engine0_1=' + tech_impul_a + '&engine0_2=' + tech_hyper_a + '&start_pos=' + coordonnee_slelec + '&techs[1][0][w_t]=' + tech_arme_d_sim + '&techs[1][0][s_t]=' + tech_bouclier_d_sim + '&techs[1][0][r_p]=' + tech_protect_d_sim + '&v_planet=' + nom_planete_complet.replace(/"/g, '&quot;') + '&debris_ratio=' + pourcent_cdr + '&v_coords=' + coordonee + '&v_met=' + parseInt(ressource_m) + '&v_kris=' + parseInt(ressource_c) + '&v_deut=' + parseInt(ressource_d) + url_dragosim; } else if (simulateur == 2) { var url_simul = 'http://www.gamewinner.fr/cgi-bin/csim/index.cgi?lang=fr?' + '&aattack=' + tech_arme_a_sim + '&ashield=' + tech_bouclier_a_sim + '&aarmory=' + tech_protect_a_sim + '&dattack=' + tech_arme_d_sim + '&dshield=' + tech_bouclier_d_sim + '&darmory=' + tech_protect_d_sim + '&enemy_name=' + nom_planete_complet.replace(/"/g, '&quot;') + '&enemy_pos=' + coordonee + '&dmetal=' + parseInt(ressource_m) + '&dcrystal=' + parseInt(ressource_c) + '&ddeut=' + parseInt(ressource_d) + url_ogamewinner; } // batiment adversaire + prodh + resrrouce x h //+bat +prod/h var mine_array = scan_info_i[19].split('/'); var mine_m = mine_array[0]; var mine_c = mine_array[1]; var mine_d = mine_array[2]; // si on a besoin de la production pour afficher une colone if (prod_h_q == 1 || prod_gg != 0 || q_vid_colo == 1) { if (mine_array != '?,?,?') { var prod_t = calcule_prod(mine_m, mine_c, mine_d, coordonee, '?'); var prod_m_h = prod_t.metal; var prod_c_h = prod_t.cristal; var prod_d_h = prod_t.deut; var prod_tot = parseInt(prod_m_h) + parseInt(prod_c_h) + parseInt(prod_d_h); var acro_prod_h = '<acronym title=" ' + text.metal + ' : ' + addPoints(parseInt(prod_m_h)) + ' | ' + text.cristal + ' : ' + addPoints(parseInt(prod_c_h)) + ' | ' + text.deut + ' : ' + addPoints(parseInt(prod_d_h)) + ' ">' + addPoints(prod_tot) + '</acronym>'; //ressource x h var prod_m_xh = Math.round(parseInt(prod_m_h) * (parseInt(prod_gg) / 60)); var prod_c_xh = Math.round(parseInt(prod_c_h) * (parseInt(prod_gg) / 60)); var prod_d_xh = Math.round(parseInt(prod_d_h) * (parseInt(prod_gg) / 60)); var prod_tt_xh = prod_m_xh + prod_c_xh + prod_d_xh; var ressource_m_xh = parseInt(ressource_m) + prod_m_xh; var ressource_c_xh = parseInt(ressource_c) + prod_c_xh; var ressource_d_xh = parseInt(ressource_d) + prod_d_xh; var ressource_tt_xh = ressource_m_xh + ressource_c_xh + ressource_d_xh; var acro_ress_xh = '<acronym title=" ' + text.metal + ' : ' + addPoints(ressource_m_xh) + '(+' + addPoints(prod_m_xh) + ') | ' + text.cristal + ' : ' + addPoints(ressource_c_xh) + '(+' + addPoints(prod_c_xh) + ') | ' + text.deut + ' : ' + addPoints(ressource_d_xh) + '(+' + addPoints(prod_d_xh) + ') | +' + addPoints(prod_tt_xh) + ' ">' + addPoints(ressource_tt_xh) + '</acronym>'; } else { var acro_prod_h = '<acronym title="' + text.batiment_non_visible + '"> ? </acronym>'; var acro_ress_xh = '<acronym title="' + text.batiment_non_visible + '"> ? </acronym>'; } } //case simuler en mode exporter vers un autre simulateur. if (simulateur == 3) { var saut = '\n'; var tabulation = '&nbsp;&nbsp;&nbsp;&nbsp;'; var export_scan_simul = 'Ressources sur Mirage ' + coordonee + ' (joueur \'' + nom_joueur + '\') le ' + datecc.getMonth() + '-' + datecc.getDate() + ' ' + datecc.getHours() + 'h ' + datecc.getMinutes() + 'min ' + datecc.getSeconds() + 's' + saut + saut + 'Métal:' + tabulation + addPoints(parseInt(ressource_m)) + tabulation + 'Cristal:' + tabulation + addPoints(parseInt(ressource_c)) + saut + 'Deutérium:' + tabulation + addPoints(parseInt(ressource_d)) + tabulation + ' Energie:' + tabulation + '5.000' + saut + saut + 'Activité' + saut + 'Activité' + saut + 'Activité signifie que le joueur scanné était actif sur la planète au moment du scan ou qu`un autre joueur a eu un contact de flotte avec cette planète à ce moment là.' + saut + 'Le scanner des sondes n`a pas détecté d`anomalies atmosphériques sur cette planète. Une activité sur cette planète dans la dernière heure peut quasiment être exclue.' + saut + 'Flottes'; var vaisseau_nom = new Array(vari.pt, vari.gt, vari.cle, vari.clo, vari.cro, vari.vb, vari.vc, vari.rec, vari.esp, vari.bb, vari.sat, vari.dest, vari.edlm, vari.tra); var q_saut_v = 0; if (vaisseau22 != '?/?/?/?/?/?/?/?/?/?') { var vaisseau = vaisseau22.split('/'); for (var k = 0; k < vaisseau.length; k++) { if (parseInt(vaisseau[k]) != 0) { if (q_saut_v < 3) { export_scan_simul = export_scan_simul + ' | ' + vaisseau_nom[k] + tabulation + ' : ' + addPoints(parseInt(vaisseau[k])); q_saut_v++; } else { export_scan_simul = export_scan_simul + saut + ' | ' + vaisseau_nom[k] + tabulation + ' : ' + addPoints(parseInt(vaisseau[k])); q_saut_v = 0; } } } } export_scan_simul = export_scan_simul + saut + 'Défense'; var defense_nom = new Array(vari.lm, vari.lle, vari.llo, vari.gauss, vari.ion, vari.pla, vari.pb, vari.gb, vari.mic, vari.mip); var q_saut = 0; if (defense2 != '?/?/?/?/?/?/?/?/?/?') { var defense = defense2.split('/'); for (var k = 0; k < defense.length; k++) { if (parseInt(defense[k]) != 0) { if (q_saut < 3) { export_scan_simul = export_scan_simul + ' | ' + defense_nom[k] + tabulation + ' : ' + addPoints(parseInt(defense[k])); q_saut++; } else { export_scan_simul = export_scan_simul + saut + ' | ' + defense_nom[k] + tabulation + ' : ' + addPoints(parseInt(defense[k])); q_saut = 0; } } } } export_scan_simul = export_scan_simul + saut + 'Bâtiment' + saut + vari.mine_m + tabulation + mine_m + tabulation + vari.mine_c + tabulation + mine_c + saut + vari.mine_d + tabulation + mine_d + tabulation + saut + 'Recherche' + saut + vari.tech_arm + tabulation + tech_arme_d + tabulation + vari.tech_bouc + tabulation + tech_bouclier_a + tabulation + saut + vari.tech_pro + tabulation + tech_protect_d + saut + 'Probabilité de contre-espionnage : 0 %'; } //compteur d'attaque if (q_compteur_attaque == 1) {//si il est activé var coordonee2_ss_crochet = galaxie + ':' + systeme + ':' + planette; if (attaque_24h.indexOf(coordonee2_ss_crochet) > -1) {//si il est pas compté. var compteur = 0; for (var s = 0; s < attaque_24h_split.length; s++) { if (attaque_24h_split2[s][1] == coordonee2_ss_crochet) { compteur++; } } var attaque_deja_fait = compteur; } else { var attaque_deja_fait = 0; } } //ligne du tableau <tr> de toute les infos du scan cptLigne++; ligne_tableau += '\n<tr class="' + coordonee + '" id="tr_' + i + '">'; var num_scan = nb_scan_deb + cptLigne; ligne_tableau += '<td class="right">' + num_scan + '.</td>'; ligne_tableau += '<td><input type="checkbox" name="delcase" value="' + i + '" id="check_' + i + '"/></td>'; ligne_tableau += '<td class="marqueur"></td>'; if (nom_j_q_q == 1) ligne_tableau += '<td class="left">' + nom_joueur + '</td>'; if (coor_q_q == 1) ligne_tableau += '<td class="coordonee">' + coordonee_fin + '</td>'; ligne_tableau += '<td>' + type_honor + '</td>'; ligne_tableau += '<td>' + type_joueur + '</td>'; ligne_tableau += '<td>' + activite_fin + '</td>'; /* var indexof_inactif = inactif_normal.indexOf(nom_joueur); if(q_inactif == 0 && indexof_inactif != -1) var inactif_nom_j = '('+'<span style="color:#4A4D4A">i</span>'+')'; else var inactif_nom_j = ''; if(nom_p_q_q == 1) ligne_tableau += '<td>' + nom_planete + inactif_nom_j + '</td>'; if(q_inactif == 1 && indexof_inactif != -1) ligne_tableau += '<td>' + '<input type="checkbox" checked="checked" name="inactif" value="'+ nom_joueur +'" class="inactif" id="inactif_'+ i +'"/>' + '</td>'; else if(q_inactif == 1 && indexof_inactif == -1) ligne_tableau += '<td>' + '<input type="checkbox" name="inactif" value="'+ nom_joueur +'" class="inactif" id="inactif_'+ i +'"/>' + '</td>'; */ if (nom_p_q_q == 1) ligne_tableau += '<td title="' + nom_planete_complet.replace(/"/g, '&quot;') + '">' + nom_planete + '</td>'; if (date_affiche == 1) ligne_tableau += '<td class="right">' + date2 + '</td>'; if (tps_vol_q == 1) ligne_tableau += '<td>' + accronyme_temp_vol + '</td>'; if (prod_h_q == 1) ligne_tableau += '<td>' + acro_prod_h + '</td>'; if (prod_gg != 0) ligne_tableau += '<td>' + acro_ress_xh + '</td>'; if (q_vid_colo == 1) ligne_tableau += '<td>' + calcul_dernier_vidage(ressource_m, ressource_c, ressource_d, prod_m_h, prod_c_h, prod_d_h, date_scan, mine_m) + '</td>'; if (question_rassemble_col == 0) { if (pt_gt != 0) ligne_tableau += '<td>' + addPoints(nb_pt) + '/' + addPoints(nb_gt) + '</td>'; ligne_tableau += '<td class="right">' + ressource + '</td>'; ligne_tableau += '<td class="right">' + cdr_aco + '</td>'; } else { ligne_tableau += '<td class="right">' + col_cdr + '</td>'; if (pt_gt != 0) ligne_tableau += '<td>' + addPoints(nb_pt) + '/' + addPoints(nb_gt) + '</td>'; } if (vaisseau_question != 0) ligne_tableau += '<td class="right">' + acronyme_vaisseau2 + '</td>'; if (defense_question != 0) ligne_tableau += '<td class="right htmlTooltip">' + acronyme_def2 + '</td>'; if (tech_q == 1) ligne_tableau += '<td class="right">' + tech_arme_d + '/' + tech_bouclier_d + '/' + tech_protect_d + '</td>'; if (q_compteur_attaque == 1) ligne_tableau += '<td class="nombreAttaque">' + attaque_deja_fait + '</td>'; ligne_tableau += '<td> <a href="' + espionnage + '" title="' + text.espionner + '"> <img src="http://gf2.geo.gfsrv.net/45/f8eacc254f16d0bafb85e1b1972d80.gif" height="16" width="16"></a></td>'; ligne_tableau += '<td> <a class="del1_scan" data-id="' + i + '" title="' + text.eff_rapp + '" ><img src="http://gf1.geo.gfsrv.net/99/ebaf268859295cdfe4721d3914bf7e.gif" height="16" width="16"></a></td>'; var target; if (stockageOption.get('attaquer nouvel onglet') === 1) { target = ''; } else if (stockageOption.get('attaquer nouvel onglet') === 2) { target = ' target="_blank"'; } else { target = ' target="attaque"'; } ligne_tableau += '<td class="boutonAttaquer"> <a href="' + url_attaquer + '" title="' + text.att + '"' + target + '><img src="http://gf1.geo.gfsrv.net/9a/cd360bccfc35b10966323c56ca8aac.gif" height="16" width="16"></a></td>'; if (q_mess == 1) { var url_href = 'index.php?page=showmessage&session=' + info.session + '&ajax=1&msg_id=' + scan_info_i[11] + '&cat=7'; ligne_tableau += '<td><a class="overlay" href="' + url_href + '" id="' + scan_info_i[11] + '"><img src="http://snaquekiller.free.fr/ogame/messages.jpg" height="16" width="16"/></a></td>'; } if (simulateur != 3 && q_lien_simu_meme_onglet == 1) ligne_tableau += '<td> <a href="' + url_simul + '" title="' + text.simul + '" target="_blank"><img src="http://snaquekiller.free.fr/ogame/simuler.jpg" height="16" width="16"></a></td></tr>'; else if (simulateur != 3 && q_lien_simu_meme_onglet != 1) ligne_tableau += '<td> <a href="' + url_simul + '" title="' + text.simul + '" target="RaideFacileSimul"><img src="http://snaquekiller.free.fr/ogame/simuler.jpg" height="16" width="16"></a></td></tr>'; else ligne_tableau += '<td> <a href="#" title="' + text.simul + '" id="simul_' + i + '" class="lien_simul_' + i + '"><img src="http://snaquekiller.free.fr/ogame/simuler.jpg" height="16" width="16"></a></td></tr>'; if (simulateur == 3) { ligne_tableau += '<tr style="display:none;" id="textarea_' + i + '" class="textarea_simul_' + i + '">' + '<TD COLSPAN=20> <textarea style="width:100%;background-color:transparent;color:#999999;text-align:center;">' + export_scan_simul + '</textarea></td></tr>'; } /**************** BBCODE EXPORT **************/ // bbcode_export = bbcode_export + coordonee +'==>'; bbcode_export = bbcode_export + bbcode_baliseo[8] + couleur2[1] + bbcode_balisem[8] + nom_joueur + '' + bbcode_balisef[8]; if (coor_q_q == 1) { bbcode_export = bbcode_export + bbcode_baliseo[8] + couleur2[2] + bbcode_balisem[8] + ' ==> ' + coordonee + '' + bbcode_balisef[8]; } // bbcode_export = bbcode_export +'==>' + activite_fin + ''; if (nom_p_q_q == 1) { bbcode_export = bbcode_export + bbcode_baliseo[8] + couleur2[3] + bbcode_balisem[8] + ' ==> ' + nom_planete_complet + '' + bbcode_balisef[8]; } bbcode_export = bbcode_export + bbcode_baliseo[8] + couleur2[4] + bbcode_balisem[8] + ' ==> ' + addPoints(parseInt(ressource_m)) + 'metal ,' + addPoints(parseInt(ressource_c)) + 'cristal ,' + addPoints(parseInt(ressource_d)) + 'deut (' + nb_pt + '/' + nb_gt + ')' + '' + bbcode_balisef[8]; bbcode_export = bbcode_export + bbcode_baliseo[8] + couleur2[5] + bbcode_balisem[8] + ' ==> ' + addPoints(cdr_possible_m) + ' metal ,' + addPoints(cdr_possible_c) + ' cristal ,' + addPoints(Math.round(cdr_possible / 25000)) + ' rc ' + bbcode_balisef[8]; if (acronyme_vaisseau != ' ') { bbcode_export = bbcode_export + bbcode_baliseo[8] + couleur2[6] + bbcode_balisem[8] + ' ==> ' + acronyme_vaisseau + '' + bbcode_balisef[8]; } if (acronyme_vaisseau != ' ') { bbcode_export = bbcode_export + bbcode_baliseo[8] + couleur2[7] + bbcode_balisem[8] + ' ==> ' + acronyme_def + '\n' + bbcode_balisef[8]; } else { bbcode_export = bbcode_export + '\n\n'; } } else nb_scan_fin++; // on rajoute un scan a afficher } else nb_scan_fin++; } else if (scan_info[i] && scan_info[i].indexOf(';;;;;;;;;;;;;;;;;x;;') === -1) { scan_info[i] = ''; nb_scan_fin++; } else nb_scan_fin++; } else if (scan_info[i] && scan_info[i].indexOf(';;;;;;;;;;;;;;;;;x;;') === -1) scan_info[i] = ''; } document.getElementById('corps_tableau2').innerHTML = ligne_tableau; /**************** BBCODE EXPORT **************/{ var bbcode_haut = ' '; if (q_centre == 1) { bbcode_haut = bbcode_haut + bbcode_baliseo[10] + bbcode_balisem[10]; } if (q_cite == 1) { bbcode_haut = bbcode_haut + bbcode_baliseo[4]; } bbcode_haut = bbcode_haut + bbcode_baliseo[8] + couleur2[1] + bbcode_balisem[8] + text.th_nj + '' + bbcode_balisef[8]; if (coor_q_q == 1) { bbcode_haut = bbcode_haut + bbcode_baliseo[8] + couleur2[2] + bbcode_balisem[8] + ' ==> ' + text.th_coo + '' + bbcode_balisef[8]; } // bbcode_haut = bbcode_haut +'==>' + activite_fin + ''; if (nom_p_q_q == 1) { bbcode_haut = bbcode_haut + bbcode_baliseo[8] + couleur2[3] + bbcode_balisem[8] + ' ==> ' + text.th_np + '' + bbcode_balisef[8]; } bbcode_haut = bbcode_haut + bbcode_baliseo[8] + couleur2[4] + bbcode_balisem[8] + ' ==> ' + text.th_ress + ' metal , cristal ,deut (pt/gt)' + '' + bbcode_balisef[8]; bbcode_haut = bbcode_haut + bbcode_baliseo[8] + couleur2[5] + bbcode_balisem[8] + ' ==> ' + text.cdr_pos + ' metal , cristal ,' + text.nb_rc + bbcode_balisef[8]; bbcode_haut = bbcode_haut + bbcode_baliseo[8] + couleur2[6] + bbcode_balisem[8] + ' ==> pt/gt/cle/clo/cro/vb/vc/rec/esp/bb/sat/dest/edlm/tra' + bbcode_balisef[8]; bbcode_haut = bbcode_haut + bbcode_baliseo[8] + couleur2[7] + bbcode_balisem[8] + ' ==> lm/lle/llo/gauss/ion/plas/pb/gb/mic/mip \n\n' + bbcode_balisef[8]; bbcode_export = bbcode_export + '\n\n\n' + bbcode_baliseo[1] + bbcode_baliseo[5] + 'http://board.ogame.fr/index.php?=Thread&postID=10726546#post10726546' + bbcode_balisem[5] + 'par Raide-Facile' + bbcode_balisef[5] + bbcode_balisef[1]; if (q_centre == 1) { bbcode_export = bbcode_export + bbcode_balisef[10]; } if (q_cite == 1) { bbcode_export = bbcode_export + bbcode_balisef[4]; } document.getElementById('text_bbcode').innerHTML = bbcode_haut + bbcode_export; } } /*************** anti reload automatique de la page. ***************/{ var script = document.createElement("script"); script.setAttribute("type", "text/javascript"); script.setAttribute("language", "javascript"); script.text = 'function reload_page() {' + '}'; document.body.appendChild(script); } /*************** Option du scripts ***************/{ var option_html = '<div id="option_script" style="display:none;text-align:center;" >' + '<div class="sectionTitreOptions" data-cible="mon_compte"> '+ text.moncompte +' </div>' + '<div class="sectionOptions" id="mon_compte">' + '<table class="tableau_interne">' + '<tr><td colspan="4" class="titre_interne"><strong>'+ text.vos_techno +' </strong></td></tr>' + '<tr><td><label for="valeur_arme">• '+ vari.tech_arm +' </label></td><td><input type="text" id="valeur_arme" value="'+ tech_arme_a +'" style="width:20px;" /></td></tr>' + '<tr><td><label for="valeur_boulier">• '+ vari.tech_bouc +' </label></td><td><input type="text" id="valeur_boulier" value="'+ tech_bouclier_a +'" style="width:20px;" /></td></tr>' + '<tr><td><label for="valeur_protection">• '+ vari.tech_pro +' </label></td><td><input type="text" id="valeur_protection" value="'+ tech_protect_a +'" style="width:20px;" /></td></tr>' + '<tr><td><label for="valeur_combustion">• '+ vari.tech_com +' </label></td><td><input type="text" id="valeur_combustion" value="'+ tech_combus_a +'" style="width:20px;" /></td></tr>' + '<tr><td><label for="valeur_impulsion">• '+ vari.tech_imp +' </label></td><td><input type="text" id="valeur_impulsion" value="'+ tech_impul_a +'" style="width:20px;" /></td></tr>' + '<tr><td><label for="valeur_hyper">• '+ vari.tech_hyp +' </label></td><td><input type="text" id="valeur_hyper" value="'+ tech_hyper_a +'" style="width:20px;" /></td></tr>' + '<tr></tr><tr></tr>' + '<tr><td colspan="4" class="titre_interne"><strong> '+ text.other_st +'</strong></td></tr>' + '<tr><td><label for="valeur_co">• '+ text.q_coord +' </label></td><td><input type="text" id="valeur_co" class="valeur_coordonee" value="'+ pos_depart +'" style="width:55px;" /></td></tr>' + '<tr><td><label for="vaisseau_vite">• '+ text.q_vaisseau_min +' </label></td><td><select name="vaisseau_vite" id="vaisseau_vite">' + '<option value="0" id="selec_q_0" >'+ vari.pt +'('+ vitesse_vaisseau(tech_impul_a ,tech_hyper_a ,tech_combus_a, 0) +')'+ '</option>' + '<option value="1" id="selec_q_1">'+ vari.gt +'('+ vitesse_vaisseau(tech_impul_a ,tech_hyper_a ,tech_combus_a, 1) +')'+ '</option>' + '<option value="2" id="selec_q_2">'+ vari.cle +'('+ vitesse_vaisseau(tech_impul_a ,tech_hyper_a ,tech_combus_a, 2) +')'+ '</option>' + '<option value="3" id="selec_q_3">'+ vari.clo +'('+ vitesse_vaisseau(tech_impul_a ,tech_hyper_a ,tech_combus_a, 3) +')'+ '</option>' + '<option value="4" id="selec_q_4">'+ vari.cro +'('+ vitesse_vaisseau(tech_impul_a ,tech_hyper_a ,tech_combus_a, 4) +')'+ '</option>' + '<option value="5" id="selec_q_5">'+ vari.vb +'('+ vitesse_vaisseau(tech_impul_a ,tech_hyper_a ,tech_combus_a, 5) +')'+ '</option>' + '<option value="6" id="selec_q_6">'+ vari.vc +'('+ vitesse_vaisseau(tech_impul_a ,tech_hyper_a ,tech_combus_a, 6) +')'+ '</option>' + '<option value="7" id="selec_q_7">'+ vari.rec +'('+ vitesse_vaisseau(tech_impul_a ,tech_hyper_a ,tech_combus_a, 7) +')'+ '</option>' + '<option value="8" id="selec_q_8">'+ vari.esp +'('+ vitesse_vaisseau(tech_impul_a ,tech_hyper_a ,tech_combus_a, 8) +')'+ '</option>' + '<option value="9" id="selec_q_9">'+ vari.bb +'('+ vitesse_vaisseau(tech_impul_a ,tech_hyper_a ,tech_combus_a, 9) +')'+ '</option>' + '<option value="10" id="selec_q_10">'+ vari.dest +'('+ vitesse_vaisseau(tech_impul_a ,tech_hyper_a ,tech_combus_a, 10) +')'+ '</option>' + '<option value="11" id="selec_q_11">'+ vari.edlm +'('+ vitesse_vaisseau(tech_impul_a ,tech_hyper_a ,tech_combus_a, 11) +')'+ '</option>' + '<option value="12" id="selec_q_12">'+ vari.tra +'('+ vitesse_vaisseau(tech_impul_a ,tech_hyper_a ,tech_combus_a, 12) +')'+ '</option>' + ' </select></td></tr>' + '<tr><td><label for="cdr_pourcent">• '+ text.pourcent +' </label></td><td><input type="text" id="cdr_pourcent" value="'+ (pourcent_cdr*100) +'" style="width:20px;" /></td></tr>' + '<tr><td><label for="cdr_pourcent_def">• '+ text.pourcent_def +' </label></td><td><input type="text" id="cdr_pourcent_def" value="'+ (pourcent_cdr_def*100) +'" style="width:20px;" /></td></tr>' +'</table>' +'</div>' + '<div class="sectionTitreOptions" data-cible="choix_var">'+text.choix_certaine_vari +' </div>' + '<div class="sectionOptions" id="choix_var">' + '<table class="tableau_interne">' + '<tr></tr><tr></tr><tr><td colspan="4" class="titre_interne"><strong> '+ text.selec_scan_st +'</strong></td></tr>' + '<tr><td><label for="val_res_min" >• '+ text.q_apartir +' </label></td><td><input type="text" id="val_res_min" value="'+ numberConverter.toPrettyString(nb_scan_accpte) +'" class="w50"></td></tr>' + '<tr><td><label for="valeur_cdr_mini">• '+ text.q_cdrmin +' </label></td><td><input type="text" id="valeur_cdr_mini" value="'+ numberConverter.toPrettyString(valeur_cdr_mini) +'" class="w50"></td></tr>' + '<tr><td><label for="valeur_tot_mini">• '+ text.q_totmin +' </label></td><td><input type="text" id="valeur_tot_mini" value="'+ numberConverter.toPrettyString(valeur_tot_mini) +'" class="w50"></td></tr>' + '<tr><td><label>• '+ text.q_prend_type +' </label></td><td> <label for="prend_type0"><input type="radio" name="prend_type" value="0" id="prend_type0">'+ text.rep_0_prend1 +'<span class="x">'+ valeur_cdr_mini +'</span> '+ text.rep_0_prend2 +'<span class="y">'+nb_scan_accpte +'</span></label><br> <label for="prend_type1"><input type="radio" name="prend_type" value="1" id="prend_type1">'+ text.rep_1_prend1 +'<span class="x">'+ valeur_cdr_mini +'</span> '+ text.rep_1_prend2 +'<span class="y">'+nb_scan_accpte +'</span></label><br> <label for="prend_type2"><input type="radio" name="prend_type" value="2" id="prend_type2">'+ text.rep_2_prend +'<span class="z">'+ valeur_tot_mini +'</span></label> </td></tr>' //0 date ; 1 coordonee ; 2 joueur ; 3 nom planète ; 4 ressource metal; 5 cristal ; 6 deut ; 7 activite ; 8 cdr possible ; 9 vaisseau; 10 defense ; 11 idrc ; 12 ressource total,13 reherche , 14 type de planète (lune ou planète) + '<tr></tr><tr></tr><tr><td colspan="4" class="titre_interne"><strong> '+ text.classement_st+'</strong></td></tr>' + '<tr><td><label for="classement">• '+ text.q_class +' </label></td><td><select name="classement" id="classement">' + '<option value="0" id="selec_0" >'+ text.c_date +'</option>' + '<option value="1" id="selec_1">'+ text.c_coo +'</option>' + '<option value="2" id="selec_2">'+ text.c_nj +'</option>' + '<option value="3" id="selec_3">'+ text.c_np +'</option>' + '<option value="4" id="selec_4">'+ text.c_met +'</option>' + '<option value="5" id="selec_5">'+ text.c_cri +'</option>' + '<option value="6" id="selec_6">'+ text.c_deu +'</option>' + '<option value="7" id="selec_7">'+ text.c_acti +'</option>' + '<option value="8" id="selec_8">'+ text.c_cdr +'</option>' + '<option value="17a" id="selec_9">'+ text.c_nbv +'</option>' + '<option value="18a" id="selec_10">'+ text.c_nbd +'</option>' + '<option value="12" id="selec_12">'+ text.c_ress +'</option>' + '<option value="14" id="selec_14">'+ text.c_type +'</option>' + '<option value="20c" id="selec_15">'+ text.c_cdrress +'</option>' + '<option value="20d" id="selec_16">'+ text.ressourcexh +'</option>' + '<option value="20e" id="selec_17">'+ text.prod_classement +'</option>' + '<option value="22" id="selec_22">'+ text.c_vaisseau_valeur +'</option>' + '<option value="23" id="selec_23">'+ text.c_defense_valeur +'</option>' + ' </select></td></tr>' + '<tr><td><label>• '+ text.q_reverse +' </label></td><td> <label for="q_reverse_decroissant">'+ text.descroissant +'</label>&nbsp<input type="radio" name="q_reverse" value="1" id="q_reverse_decroissant" /> <label for="q_reverse_croissant">'+ text.croissant +'</label>&nbsp<input type="radio" name="q_reverse" value="0" id="q_reverse_croissant" /></td></tr>' + '<tr><td><label>• '+ text.taux_classement_ressource +' </label></td><td> <label for="q_taux_m">'+ text.taux_m +'</label>&nbsp<input type="text" id="q_taux_m" value="'+ q_taux_m +'" style="width:50px;" />&nbsp<label for="q_taux_c">'+ text.taux_c +'</label>&nbsp<input type="text" id="q_taux_c" value="'+ q_taux_c +'" style="width:50px;" />&nbsp<label for="q_taux_d">'+ text.taux_d +'</label>&nbsp<input type="text" id="q_taux_d" value="'+ q_taux_d +'" style="width:50px;" /></td></tr>' + '<tr></tr><tr></tr><tr><td colspan="4" class="titre_interne"><strong> '+ text.option_save_scan_st +'</strong></td></tr>' + '<tr><td><label>• '+ text.q_sae_auto +' </label></td><td> <label for="save_auto_scan_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="option_scan_save_o" value="1" id="save_auto_scan_oui" /> <label for="save_auto_scan_non">'+ text.non +'</label>&nbsp<input type="radio" name="option_scan_save_o" value="0" id="save_auto_scan_non" /></td></tr>' + '<tr><td><label>• '+ text.remp_scn +' </label></td><td> <label for="scan_remplace_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="scan_remplace" value="1" id="scan_remplace_oui" /> <label for="scan_remplace_non">'+ text.non +'</label>&nbsp<input type="radio" name="scan_remplace" value="0" id="scan_remplace_non" /></td></tr>' + '<tr><td><label for="jourrr">• '+ text.q_garde +' </label></td><td> <input type="text" id="jourrr" class="jours_suprime" value="'+ jours_opt +'" style="width:20px;" /> '+ text.jours +'&nbsp<input type="text" class="heures_suprime" value="'+ heures_opt +'" style="width:20px;" />&nbsp'+ text.heures +'&nbsp<input type="text" class="minutes_suprime" value="'+ minutes_opt +'" style="width:20px;" />&nbsp'+ text.min +'&nbsp</td></tr>' + '<tr><td><label for="nb_max_def">• '+ text.q_nb_max_def +' </label></td><td><input id="nb_max_def" type="text" value="'+ nb_max_def +'" style="width:60px;" /></td></tr>' + '<tr></tr><tr></tr><tr><td colspan="4" class="titre_interne"><strong> '+ text.other_st +'</strong></td></tr>' + '<tr><td><label>• '+ text.import_q +' </label> </td><td><label><input type="radio" name="import_q" value="1" id="import_rajoute"> '+ text.import_rajoute +'</label><br><label><input type="radio" name="import_q" value="0" id="import_remplace"> '+ text.import_remplace +'</label></td></tr>' + '<tr><td><label>• '+ text.lien_raide_nb_pt_gt +' </label> </td><td><label for="lien_raide_nb_pt_remplit">'+ text.nb_pt +'</label>&nbsp<input type="radio" name="lien_raide_nb_pt_gt" value="1" id="lien_raide_nb_pt_remplit" />&nbsp<label for="lien_raide_nb_gt_remplit">'+ text.nb_gt +'</label>&nbsp<input type="radio" name="lien_raide_nb_pt_gt" value="0" id="lien_raide_nb_gt_remplit" />&nbsp<label for="lien_raide_nb_pt_gt2">'+ text.rien +'</label>&nbsp<input type="radio" name="lien_raide_nb_pt_gt" value="2" id="lien_raide_nb_pt_gt2" /></td></tr>' + '<tr><td><label>• '+ text.lien_raide_ajout_nb_pourcent +' </label></td><td> <input type="text" id="nb_pourcent_ajout_lien" value="'+ nb_pourcent_ajout_lien +'" style="width:20px;" />&nbsp<select name="nb_ou_pourcent" id="nb_ou_pourcent"><option value="0"> %</option> <option value="1"> en plus</option></select></td></tr>' + '<tr></tr><tr></tr><tr><td colspan="4" class="titre_interne"><strong> '+ i18n('raccourcis') +'</strong></td></tr>' + '<tr><td><label>'+ i18n('shortcut_attack_next') +'</label></td><td><input type="text" id="shortcut_attack_next" value="'+ stockageOption.get('touche raid suivant') +'" title="'+i18n('ce_nombre_est_keycode')+'" style="width:20px" readonly> <button id="shortcut_attack_next_modify" class="ui-button ui-widget ui-state-default ui-corner-all">'+ i18n('modifier') +'</button></td></tr>' +'</table>' +'</div>' + '<div class="sectionTitreOptions" data-cible="color_ligne"> '+ text.couleur_ligne +' </div>' + '<div class="sectionOptions" id="color_ligne">' + '<table class="tableau_interne">' + '<tr><td colspan="4" class="titre_interne"><strong>'+ text.q_color +'</strong></td></tr>' + '<tr><td></td><td><strong>Aller</strong></td><td><strong>Retour</strong></td></tr>' + '<tr><td><label for="att1">• '+ text.attt +' </label> </td><td><input id="att1" type="text" class="att" value="'+ col_att +'" style="width:60px;background-color:'+ col_att +';" /></td><td><input id="att1_r" type="text" class="att_r" value="'+ col_att_r +'" style="width:60px;background-color:'+ col_att_r +';" /></td></tr>' + '<tr><td><label for="att2">• '+ text.attt +' (2)</label> </td><td><input id="att2" type="text" class="att" value="'+ stockageOption.get('couleur attaque2') +'" style="width:60px;background-color:'+ stockageOption.get('couleur attaque2') +';" /></td><td><input id="att2_r" type="text" class="att_r" value="'+ stockageOption.get('couleur attaque2 retour') +'" style="width:60px;background-color:'+ stockageOption.get('couleur attaque2 retour') +';" /></td></tr>' + '<tr><td><label for="att_group">• '+ text.ag +' </label> </td><td><input id="att_group" type="text" class="att_group" value="'+ col_att_g +'" style="width:60px;background-color:'+ col_att_g +';" /></td><td><input id="att_group_r" type="text" class="att_group_r" value="'+ col_att_g_r +'" style="width:60px;background-color:'+ col_att_g_r +';" /></td></tr>' + '<tr><td><label for="det">• '+ text.det +' </label> </td><td><input id="det" type="text" class="det" value="'+ col_dest +'" style="width:60px;background-color:'+ col_dest +';" /></td><td><input id="det_r" type="text" class="det_r" value="'+ col_dest_r +'" style="width:60px;background-color:'+ col_dest_r +';" /></td></tr>' + '<tr><td><label for="colEspio">• '+ localization.missions[6] +'</label> </td><td><input id="colEspio" type="text" value="'+ stockageOption.get('couleur espionnage') +'" style="width:60px;background-color:'+ stockageOption.get('couleur espionnage') +';" /></td></tr>' +'</table>' + '</div>' + '<div class="sectionTitreOptions" data-cible="choix_affichage"> '+ text.option_affichage +' </div>' + '<div class="sectionOptions" id="choix_affichage">' + '<table class="tableau_interne">' + '<tr></tr><tr></tr><tr><td colspan="4" class="titre_interne"><strong> '+ text.affichage_changement_colonne +' </strong></td></tr>' + '<tr><td><label>• '+ text.q_date_type +' </label> </td><td><label for="date_type_heure"> '+ text.date_type_heure +'</label>&nbsp<input type="radio" name="q_date_type" value="1" id="date_type_heure" /> <label for="date_type_chrono">'+ text.date_type_chrono +'</label>&nbsp<input type="radio" name="q_date_type" value="0" id="date_type_chrono" /></td></tr>' + '<tr><td><label>• '+ text.cdr_q +' </label> </td><td> <label for="recycleur_type"> '+ text.recyclc +'</label>&nbsp<input type="radio" name="recycleur_type" value="1" id="recycleur_type_affichage_recyleur" /> <label for="recycleur_type_affichage_ressource">'+ text.ressousrce +'</label>&nbsp<input type="radio" name="recycleur_type" value="0" id="recycleur_type_affichage_ressource" /></td></tr>' + '<tr></tr><tr></tr><tr><td colspan="4" class="titre_interne"><strong> '+ text.changement_boutondroite +' </strong></td></tr>' + '<tr><td><label>• '+ text.q_simul +' </label> </td><td><label for="sim_q_dra">'+ text.drago +'</label>&nbsp<input type="radio" name="q_sim" value="0" id="sim_q_dra" /><br><label for="sim_q_speed">'+ text.speed +'</label>&nbsp<input type="radio" name="q_sim" value="1" id="sim_q_speed" /><br><label for="sim_q_ogwin">'+ text.ogwinner +'</label>&nbsp<input type="radio" name="q_sim" value="2" id="sim_q_ogwin" /><br><label for="sim_q_autre">' + text.simu_exte +'</label>&nbsp<input type="radio" name="q_sim" value="3" id="sim_q_autre" /></td></tr>' + '<tr><td><label>• '+ text.mess_q +' </label> </td><td><label for="mess_origine_aff_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="q_mess" value="1" id="mess_origine_aff_oui" /> <label for="mess_origine_aff_non">'+ text.non +'</label>&nbsp<input type="radio" name="q_mess" value="0" id="mess_origine_aff_non" /></td></tr>' + '<tr><td><label>• '+ text.lienespi +' </label> </td><td><label for="espionn_galaxie">'+ text.page_g +'</label>&nbsp<input type="radio" name="espionn" value="0" id="espionn_galaxie" /> <label for="espionn_fleet">'+ text.page_f +'</label>&nbsp<input type="radio" name="espionn" value="1" id="espionn_fleet" /></td></tr>' + '<tr><td><label>• Le lien attaquer s\'ouvre dans</label></td><td><select id="rf_attaquer_ouvredans" style="width:210px;"><option value="1"'+(stockageOption.get('attaquer nouvel onglet') === 1 ? ' selected':'')+'>L\'onglet actuel</option><option value="2"'+(stockageOption.get('attaquer nouvel onglet') === 2 ? ' selected':'')+'>Un nouvel onglet</option><option value="3"'+(stockageOption.get('attaquer nouvel onglet') === 3 ? ' selected':'')+'>Toujours le même nouvel onglet</option></select></td></tr>' + '<tr><td><label>• '+ text.q_lien_simu_meme_onglet +' </label> </td><td><label for="q_lien_simu_meme_onglet_non">'+ text.rep_onglet_norm +'</label>&nbsp<input type="radio" name="q_lien_simu_meme_onglet" value="1" id="q_lien_simu_meme_onglet_non" /> <label for="q_lien_simu_meme_onglet_oui">'+ text.rep_onglet_autre +'</label>&nbsp<input type="radio" name="q_lien_simu_meme_onglet" value="0" id="q_lien_simu_meme_onglet_oui" /></td></tr>' + '<tr></tr><tr></tr><tr><td colspan="4" class="titre_interne"><strong> '+ text.affichage_colonne +' </strong></td></tr>' + '<tr><td><label>• '+ text.nom_j_q +' </label></td><td><label for="nom_joueur_affi_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="nom_j_q" value="1" id="nom_joueur_affi_oui" /> <label for="nom_joueur_affi_non">'+ text.non +'</label>&nbsp<input type="radio" name="nom_j_q" value="0" id="nom_joueur_affi_non" /></td></tr>' + '<tr><td><label>• '+ text.coor_q +' </label></td><td><label for="coord_affi_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="coor_q" value="1" id="coord_affi_oui" /> <label for="coord_affi_non">'+ text.non +'</label>&nbsp<input type="radio" name="coor_q" value="0" id="coord_affi_non" /></td></tr>' + '<tr><td><label>• '+ text.nom_p_q +' </label></td><td><label for="nom_planet_affi_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="nom_p_q" value="1" id="nom_planet_affi_oui" /> <label for="nom_planet_affi_non">'+ text.non +'</label>&nbsp<input type="radio" name="nom_p_q" value="0" id="nom_planet_affi_non" /></td></tr>' // + '<tr><td><label>• '+ text.nom_p_q +' </label></td><td><label for="nom_planet_affi_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="nom_p_q" value="1" id="nom_planet_affi_oui" /> <label for="nom_planet_affi_non">'+ text.non +'</label>&nbsp<input type="radio" name="nom_p_q" value="0" id="nom_planet_affi_non" /> <label for="nom_planet_affi_autre">'+ text.autre_planette +'</label>&nbsp<input type="radio" name="nom_p_q" value="2" id="nom_planet_affi_autre" /></td></tr>' + '<tr><td><label>• '+ text.q_date +' </label></td><td><label for="date_affi_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="date_q" value="1" id="date_affi_oui" /> <label for="date_affi_non">'+ text.non +'</label>&nbsp<input type="radio" name="date_q" value="0" id="date_affi_non" /></td></tr>' + '<tr><td><label>• '+ text.tps_vol +' </label></td><td><label for="tps_vol_afficher_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="tps_vol" value="1" id="tps_vol_afficher_oui" /> <label for="tps_vol_afficher_non">'+ text.non +'</label>&nbsp<input type="radio" name="tps_vol" value="0" id="tps_vol_afficher_non" /></td></tr>' + '<tr><td><label>• '+ text.q_prod +' </label></td><td><label for="prod_h_aff_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="prod_h_q" value="1" id="prod_h_aff_oui" /> <label for="prod_h_aff_non">'+ text.non +'</label>&nbsp<input type="radio" name="prod_h_q" value="0" id="prod_h_aff_non" /></td></tr>' + '<tr><td><label>• '+ text.q_afficher_dernier_vid_colo +' </label></td><td><label for="aff_vid_colo_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="q_vid_colo" value="1" id="aff_vid_colo_oui" /> <label for="aff_vid_colo_non">'+ text.non +'</label>&nbsp<input type="radio" name="q_vid_colo" value="0" id="aff_vid_colo_non" /></td></tr>' + '<tr><td><label>• '+ text.q_pt_gt +' </label></td><td><label for="q_pt_gt_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="q_pt_gt" value="1" id="q_pt_gt_oui" /> <label for="q_pt_gt_non">'+ text.non +'</label>&nbsp<input type="radio" name="q_pt_gt" value="0" id="q_pt_gt_non" /></td></tr>' + '<tr><td><label>• '+ text.question_rassemble_cdr_ress +' </label></td><td><label for="rassemble_cdr_ress_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="rassemble_q" value="1" id="rassemble_cdr_ress_oui" /> <label for="rassemble_cdr_ress_non">'+ text.non +'</label>&nbsp<input type="radio" name="rassemble_q" value="0" id="rassemble_cdr_ress_non" /></td></tr>' + '<tr><td><label>• '+ text.q_ress_h +'</label></td><td><input type="text" class="ress_nb_j" value="'+ prod_j_g +'" style="width:20px;" />&nbsp'+ text.jours +'&nbsp<input type="text" class="ress_nb_h" value="'+ prod_h_g +'" style="width:20px;" />&nbsp'+ text.heures +'&nbsp<input type="text" class="ress_nb_min" value="'+ prod_min_g +'" style="width:20px;" />&nbsp'+ text.min +'</td></tr> ' + '<tr><td><label>• '+ text.vaisseau_q +' </label></td><td><label for="vaisseau_q_n">'+ text.non +'</label>&nbsp<input type="radio" name="vaisseau_q" value="0" id="vaisseau_q_n" /> <label for="vaisseau_q_nb">'+ text.defense_nb +'</label>&nbsp<input type="radio" name="vaisseau_q" value="1" id="vaisseau_q_nb" /> <label for="vaisseau_q_val">'+ text.defense_valeur +'</label>&nbsp<input type="radio" name="vaisseau_q" value="2" id="vaisseau_q_val" /></td></tr>' + '<tr><td><label>• '+ text.defense_q +' </label> </td><td><label for="defense_q_n">'+ text.non +'</label>&nbsp<input type="radio" name="defense_q" value="0" id="defense_q_n" /> <label for="defense_q_nb">'+ text.defense_nb +'</label>&nbsp<input type="radio" name="defense_q" value="1" id="defense_q_nb" /> <label for="defense_q_val">'+ text.defense_valeur +'</label>&nbsp<input type="radio" name="defense_q" value="2" id="defense_q_val" /></td></tr>' + '<tr><td><label>• '+ text.q_tech +' </label></td><td><label for="tech_aff_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="tech_q" value="1" id="tech_aff_oui" /> <label for="tech_aff_non">'+ text.non +'</label>&nbsp<input type="radio" name="tech_q" value="0" id="tech_aff_non" /></td></tr>' + '<tr><td><label>• '+ text.q_compteur_attaque +' </label> </td><td><label for="compteur_attaque_aff_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="q_compteur_attaque" value="1" id="compteur_attaque_aff_oui" /> <label for="compteur_attaque_aff_non">'+ text.non +'</label>&nbsp<input type="radio" name="q_compteur_attaque" value="0" id="compteur_attaque_aff_non" /></td></tr>' + '<tr></tr><tr></tr><tr><td colspan="4" class="titre_interne"><strong> '+ text.affichage_global +' </strong></td></tr>' + '<tr><td><label>• '+ text.q_galaxie_scan +' </label> </td><td><label for="scan_galaxie_cours_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="q_galaxie_scan" value="1" id="scan_galaxie_cours_oui" />&nbsp<label for="scan_galaxie_cours_non">'+ text.non +'</label>&nbsp<input type="radio" name="q_galaxie_scan" value="0" id="scan_galaxie_cours_non" /><br/><label for="scan_galaxie_autre">'+ text.other +'</label>&nbspG&nbsp<input type="text" id="galaxie_demande" value="'+ galaxie_demande +'" style="width:20px;" />&nbsp<input type="radio" name="q_galaxie_scan" value="2" id="scan_galaxie_autre" /><br/><label for="scan_galaxie_plus_ou_moin">'+ text.galaxie_plus_ou_moins + '</label>&nbsp<input type="text" id="galaxie_demande_plus_moin_text" value="'+ galaxie_plus_ou_moins +'" style="width:20px;" />&nbsp<input type="radio" name="q_galaxie_scan" value="3" id="scan_galaxie_plus_ou_moin" /></td></tr>' + '<tr><td><label>• '+ text.afficher_seulement +' </label> </td><td><label for="afficher_lune_planet">'+ text.toutt +'</label>&nbsp<input type="radio" name="afficher_seulement" value="1" id="afficher_lune_planet" /> <label for="afficher_planet_seul">'+ text.planete_sel +'</label>&nbsp<input type="radio" name="afficher_seulement" value="0" id="afficher_planet_seul" />&nbsp<label for="afficher_lune_seul">'+ text.lune +'</label>&nbsp<input type="radio" name="afficher_seulement" value="2" id="afficher_lune_seul" /></td></tr>' + '<tr><td><label>• '+ text.q_afficher_ligne_def_nvis +' </label> </td><td><label for="aff_lign_def_invisible_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="q_def_vis" value="1" id="aff_lign_def_invisible_oui" /> <label for="aff_lign_def_invisible_non">'+ text.non +'</label>&nbsp<input type="radio" name="q_def_vis" value="0" id="aff_lign_def_invisible_non" /></td></tr>' + '<tr><td><label>• '+ text.q_afficher_ligne_flo_nvis +' </label> </td><td><label for="aff_lign_flot_invisible_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="q_flo_vis" value="1" id="aff_lign_flot_invisible_oui" /> <label for="aff_lign_flot_invisible_non">'+ text.non +'</label>&nbsp<input type="radio" name="q_flo_vis" value="0" id="aff_lign_flot_invisible_non" /></td></tr>' + '<tr><td><label>• '+ text.page +'</label> </td><td><input type="text" id="nb_scan_page" value="'+ nb_scan_page +'" style="width:40px;" /> </td></tr>' + '<tr></tr><tr></tr><tr><td colspan="4" class="titre_interne"><strong> '+ text.other_st +'</strong></td></tr>' + '<tr><td><label>• '+ text.q_techn_sizero +' </label> </td><td><label for="q_techzero_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="q_techzero" value="1" id="q_techzero_oui" /> <label for="q_techzero_non">'+ text.non +'</label>&nbsp<input type="radio" name="q_techzero" value="0" id="q_techzero_non" /></td></tr>' + '<tr><td><label>• '+ text.tableau_raide_facile +' </label> </td><td>+ <input type="text" id="tableau_raide_facile_q" value="'+ tableau_raide_facile_value +'" style="width:40px;" />&nbsppx</td></tr>' + '<tr><td><label>• '+ text.question_afficher_icone_mess +' </label> </td><td><label for="icone_parti_mess_oui">'+ text.oui +'</label>&nbsp<input type="radio" name="q_icone_mess" value="1" id="icone_parti_mess_oui" /> <label for="icone_parti_mess_non">'+ text.non +'</label>&nbsp<input type="radio" name="q_icone_mess" value="0" id="icone_parti_mess_non" /></td></tr>' +'</table>' + '</div>' // option bbcode + '<div class="sectionTitreOptions" data-cible="option_bbcode_interieur"> BBCode </div>' + '<div class="sectionOptions" id="option_bbcode_interieur">' +'<table class="tableau_interne">' + '<tr></tr><tr></tr><tr><td colspan="4" class="titre_interne"><strong>Couleurs : </strong></td></tr>' + '<tr><td><label>• '+ text.color +'1</label></td><td><input type="text" id="col_1" value="'+ couleur2[1] +'" style="width:60px;background-color:'+ couleur2[1] +';" /></td></tr>' + '<tr><td><label>• '+ text.color +'2</label></td><td><input type="text" id="col_2" value="'+ couleur2[2] +'" style="width:60px;background-color:'+ couleur2[2] +';" /></td></tr>' + '<tr><td><label>• '+ text.color +'3</label></td><td><input type="text" id="col_3" value="'+ couleur2[3] +'" style="width:60px;background-color:'+ couleur2[3] +';" /></td></tr>' + '<tr><td><label>• '+ text.color +'4</label></td><td><input type="text" id="col_4" value="'+ couleur2[4] +'" style="width:60px;background-color:'+ couleur2[4] +';" /></td></tr>' + '<tr><td><label>• '+ text.color +'5</label></td><td><input type="text" id="col_5" value="'+ couleur2[5] +'" style="width:60px;background-color:'+ couleur2[5] +';" /></td></tr>' + '<tr><td><label>• '+ text.color +'6</label></td><td><input type="text" id="col_6" value="'+ couleur2[6] +'" style="width:60px;background-color:'+ couleur2[6] +';" /></td></tr>' + '<tr><td><label>• '+ text.color +'7</label></td><td><input type="text" id="col_7" value="'+ couleur2[7] +'" style="width:60px;background-color:'+ couleur2[7] +';" /></td></tr>' + '<tr><td><label>• '+ text.text_cite +' </label></td><td>'+ text.oui +'&nbsp<input type="radio" name="cite" value="1" id="cite1" />&nbsp'+ text.non +'&nbsp<input type="radio" name="cite" value="0" id="cite0" /></td></tr>' + '<tr><td><label>• '+ text.text_centre +' </label></td><td>'+ text.oui +'&nbsp<input type="radio" name="centre" value="1" id="centre1" />&nbsp'+ text.non +'&nbsp<input type="radio" name="centre" value="0" id="centre0" /></td></tr>' + '<tr><td><label>• '+ text.balise_centre +' </label></td><td> '+ text.balise1_center +'&nbsp<input type="radio" name="centre_type" value="1" id="centre_type1" />&nbsp'+ text.balise2_center +'&nbsp<input type="radio" name="centre_type" value="0" id="centre_type0" /></td></tr>' + '<tr><td><label>• '+ text.balise_url +' </label></td><td> '+ text.balise1_url +'&nbsp<input type="radio" name="url_type" value="1" id="url_type1" />&nbsp'+ text.balise2_url +'&nbsp<input type="radio" name="url_type" value="0" id="url_type0" /></td></tr>' +'</table>' + '</div>' //option de langue + '<div class="sectionTitreOptions" data-cible="choix_langue"> '+ text.option_langue +' </div>' + '<div class="sectionOptions" id="choix_langue">' + '<BR /><label>• '+ text.q_langue +' </label>' + '<select name="langue" id="langue" class="w200" style="min-width:120px">' + '<option value="fr">'+ text.francais +'</option>' + '<option value="en">'+ text.anglais +'</option>' + '<option value="es">'+ text.spagnol +'</option>' + '<option value="ro">'+ text.roumain +'</option>' // + '<option value="2" id="langue2">'+ text.autre +'</option>' + ' </select>' + '</div>' + '<input type="submit" value="'+ text.save_optis +'" id="sauvegarder_option" href=# style="margin-top:5px;"/></div>'; } //########### TABLEAU A AFFICHER ########## var texte_a_afficher = ''; /************** TABLEAU INGAME ***************/ if (nb_scan_page != 0) {// on affiche les numeros pages var page_bas = '<span id="page" >Page : '; var num_page = info.url.split('&page_r=')[1]; var scan_info = GM_getValue('scan' + info.serveur, '').split('#'); var nb = scan_info.length; var nb_page_poss = Math.ceil(nb / nb_scan_page); if (num_page == undefined || num_page == 1 || num_page == '') { num_page = 1; } for (var i = 1; i < (nb_page_poss + 1); i++) { if (i != num_page) { page_bas = page_bas + ' <a href="' + url_2 + '&amp;raidefacil=scriptOptions&amp;page_r=' + i + '" >' + i + '</a>'; } else { page_bas = page_bas + ' ' + i; } if (i != nb_page_poss) { page_bas = page_bas + ','; } } page_bas = page_bas + '</span>'; } else { var page_bas = '<span id="page" ></span>'; } var filtres = '<div id="filtres"><select name="choix_affichage2" id="choix_affichage2" class="w100">' + '<option value="0" id="tout" >'+ text.toutt +'</option>' + '<option value="1" id="planete_seul" >'+ text.planete_sel +'</option>' + '<option value="2" id="lune_seul" >'+ text.lune +'</option>' + '</select> '; filtres += '<select name="filtre_actif_inactif" id="filtre_actif_inactif" class="w100">' + '<option value="0" >'+ text.toutt +'</option>' + '<option value="1" >'+ text.filtre_actif +'</option>' + '<option value="2" >'+ text.filtre_inactif +'</option>' + '</select> '; filtres += text.th_nj +': <input type="text" id="filtre_joueur" value="" style="width:140px;" /> '; filtres += '<input type="submit" value="' + text.filtrer + '" id="change_value_affiche" href=# /></div>'; /**************** tete tableau + les titres des colonnes ****************/{ var titre_div = '<div id="raide_facile_titre"><div style="background-color:#1A2128;color:#6F9FC8;padding:5px;text-align:center;border-bottom: 1px solid black;font-size:18px;">'+i18n.get('raid facile')+ ' - version ' + info.version +'</div>' +'<a style="font-size:10px;cursor:pointer;" id="htmlclique" data-cible="text_html_bbcode">[Export Forum]</a> ' +'<a style="font-size:10px;cursor:pointer;" id="imp_exp_clique" data-cible="div_import_exp">[Import/Export de sauvegarde]</a> ' // +'<a style="font-size:10px;cursor:pointer;" id=info_news_clique >[Info]</a> ' +'<a style="font-size:10px;cursor:pointer;" id="optionclique" class="htmlTooltip"><div class="tooltipTitle">'+ iconeNew('Version 8.0') +'<br>Depuis la version 8.0<br>Le lien pour afficher les options est dans le menu de gauche : <div class="menu_icon"><div class="menuImage traderOverview highlighted"></div></div></div>[Option]</a></div>'; var haut_tableau = '<table id="tableau_raide_facile" cellspacing="0" cellpadding="0">'; var titre_colonne_tableau = '\n<thead id=haut_table2 style="background-color:#1A2128;color:#6F9FC8;"><tr><th></th><th></th><th></th>'; if(nom_j_q_q == 1) titre_colonne_tableau += '<th id="cjoueur"><a>'+ text.th_nj +'</a></th>'; if(coor_q_q == 1) titre_colonne_tableau += '\n<th id="ccoordonee" ><a>'+ text.th_coo +'</a></th>'; titre_colonne_tableau += '\n<th></th>'; titre_colonne_tableau += '\n<th></th>'; titre_colonne_tableau += '\n<th></th>'; if(nom_p_q_q == 1) titre_colonne_tableau += '\n<th id="cplanete"><a>'+ text.th_np +'</a></th>'; if(date_affiche == 1) titre_colonne_tableau += '\n<th id="cdate"><a>'+ text.dated +'</a></th>\n'; if(tps_vol_q == 1) titre_colonne_tableau += '\n<th id="ctmps_vol"><a>'+ text.tmp_vol_th +'</a></th>\n'; if(prod_h_q == 1) titre_colonne_tableau += '\n<th id="cprod_h"><a>'+ text.prod_h_th +'</a></th>\n'; if(prod_gg != 0) titre_colonne_tableau += '\n<th id="cressourcexh"><a>'+ text.ressource_xh_th +'</a></th>\n'; if(q_vid_colo != 0) titre_colonne_tableau += '\n<th>'+ text.th_h_vidage +'</th>\n'; if(question_rassemble_col == 0) { if(pt_gt != 0) titre_colonne_tableau += '\n<th id="cfleet">'+ text.th_fleet +'</th>'; titre_colonne_tableau += '\n<th id="cress"><a>'+ text.th_ress +'</a></th>'; if(cdr_q_type_affiche === 0) titre_colonne_tableau += '<th id="ccdr"><a>' + text.cdr_pos+'</a></th>'; else if(cdr_q_type_affiche === 1) titre_colonne_tableau += '<th id="ccdr"><a>' + text.nb_recycl+'</a></th>'; }else{ titre_colonne_tableau += '\n<th id="ccdr_ress"><a>'+ text.th_ress_cdr_col +'</a></th>'; if(pt_gt != 0) titre_colonne_tableau += '\n<th id="cfleet"><a>'+ text.th_fleet +'</a></th>'; } if(vaisseau_question != 0) titre_colonne_tableau += '\n<th id="cnb_v'+vaisseau_question +'"><a>'+ text.th_nv +'</a></th>\n'; if(defense_question != 0) titre_colonne_tableau += '<th id="cnb_d'+defense_question +'"><a>'+ text.th_nd +'</a></th>'; if(tech_q != 0) titre_colonne_tableau += '\n<th>'+ text.th_tech +'</th>'; if(q_compteur_attaque == 1) titre_colonne_tableau += '\n<th title="Nombre d\'attaque dans les dernières 24h + Nombre d\'attaque en cours">#</th>'; //Bouton titre_colonne_tableau += '\n<th class="RF_icon"></th>'; titre_colonne_tableau += '\n<th class="RF_icon"></th>'; titre_colonne_tableau += '\n<th class="RF_icon"></th>'; titre_colonne_tableau += '\n<th class="RF_icon"></th>'; titre_colonne_tableau += '\n<th class="RF_icon"></th>'; titre_colonne_tableau += '\n</tr>\n</thead>\n' + '\n<tbody id="corps_tableau2" > \n</tbody>' // + '\n<tbody id=corps_tableau2>' + ligne_tableau + '\n</tbody>' + '\n</table>'; } /**************** HTML/BBCODE EXPORT **************/{ var html_bbcode = '<div id="text_html_bbcode"><center style="margin-left: auto; margin-right: auto; width: 99%;">'; html_bbcode += '<textarea style="margin-top:5px; margin-bottom:10px; width:100%;background-color:black;color:#999999;text-align:center;" id="text_html" >'+ '</textarea>'; html_bbcode += '<textarea style="margin-top:5px; margin-bottom:10px; width:100%;background-color:black;color:#999999;text-align:center;" id="text_bbcode" >'+ '</textarea>'; html_bbcode += '</center></div>'; } /**************** IMPORT / EXPORT **************/{ var import_export = '<div id="div_import_exp" style="text-align:center">'; import_export += '<input type="submit" id="export_script" value="'+ i18n('export_scan_se') +'" />'; import_export += '<input type="submit" id="export_script_ns" value="'+ i18n('export_scan_nnse') +'" />'; import_export += '<input type="submit" id="export_options" value="'+ i18n('export_options') +'">'; import_export += '<br><label for="area_export">' + i18n('exportt') + '</label><textarea id="area_export" readonly style="box-sizing:border-box; width:100%"></textarea>'; import_export += '<label for="area_import">' + i18n('importt') + '</label><textarea id="area_import" style="box-sizing:border-box; width:100%"></textarea>'; import_export += '<input type="submit" id="import_scan" value="'+ i18n('importer_scan') +'" />'; import_export += '<input type="submit" id="import_options" value="'+ i18n('import_options') +'" />'; import_export += '</div>'; } /****************************/ texte_a_afficher = '<div id="div_raide_facile">' + titre_div + option_html + '<div id="div_tableau_raide_facile">' + '\n<div id="boutons_haut"></div>' + haut_tableau + titre_colonne_tableau + '<div id="boutons_bas"></div>' + '</div>' + html_bbcode + import_export + '</div>'; //document.getElementById('inhalt').innerHTML = texte_a_afficher; document.getElementById('inhalt').style.display = "none"; var div_raide_facile = document.createElement('div'); insertAfter(div_raide_facile, document.getElementById('inhalt')); div_raide_facile.outerHTML = texte_a_afficher; // Stylisation des éléments (select, input, ...) comme ogame intercom.send('ogame style'); // Activation des tooltips dans le style ogame intercom.send('tooltip', { selector: '#corps_tableau2 acronym[title]' }); intercom.send('tooltip', { selector: '#corps_tableau2 .htmlTooltip', htmlTooltip: true }); intercom.send('tooltip', { selector: '#raide_facile_titre #optionclique', htmlTooltip: true }); intercom.send('tooltip', { selector: '#option_script #shortcut_attack_next' }); //document.getElementById("contentWrapper").appendChild(document.createElement('div')).outerHTML = texte_a_afficher; //on affiche les boutons de suppression de scan . /**bouton en hauts **/{ document.getElementById('boutons_haut').innerHTML = '<center><a id="plus_moins" style="float:left;"><img src="http://snaquekiller.free.fr/ogame/messraide/raidefacile%20mess/plus.png" id="img_moin_plus" height="16" width="16"/></a><a id="supr_scan_h" style="display:none;"><input type="submit" value="' + text.supr_scan_coche + '" style="margin-bottom:5px;"/></a> <a id="supr_scan_nn_selec_h" style="display:none;"><input type="submit" value="' + text.supr_scan_coche_nnslec + '" style="margin-bottom:5px;"/></a></center>' + '<div id="page_h" style="float:right;display:none;">' + page_bas + '</div>' + filtres; // ouvrir fermer le span du haut pour les boutons document.getElementById('plus_moins').addEventListener("click", function (event) { var img_plus_moin = document.getElementById('plus_moins'); var supr_scan_h = document.getElementById('supr_scan_h'); var supr_scan_nn_selec_h = document.getElementById('supr_scan_nn_selec_h'); var page_h = document.getElementById('page_h'); if (supr_scan_h.style.display == 'none') { supr_scan_h.style.display = ''; supr_scan_nn_selec_h.style.display = ''; page_h.style.display = ''; img_plus_moin.src = 'http://snaquekiller.free.fr/ogame/messraide/raidefacile%20mess/moins.png'; } else { supr_scan_h.style.display = 'none'; supr_scan_nn_selec_h.style.display = 'none'; page_h.style.display = 'none'; img_plus_moin.src = 'http://snaquekiller.free.fr/ogame/messraide/raidefacile%20mess/plus.png'; } }, true); //supressions de scan document.getElementById("supr_scan_h").addEventListener("click", function (event) { del_scan_checkbox(info.serveur, true); remlir_tableau(-1, 0); }, true); document.getElementById("supr_scan_nn_selec_h").addEventListener("click", function (event) { del_scan_checkbox(info.serveur, false); remlir_tableau(-1, 0); }, true); } /**bouton en en bas**/{ document.getElementById('boutons_bas').innerHTML = '<a id="zero_b" style="float:left;">'+ text.remis_z +'</a>' + '<div style="float:right;">'+ page_bas +'</div><br/>' + '<center><a id="supr_scan_b"><input type="submit" value="'+ text.supr_scan_coche +'" style="margin-top:5px;"/></a> <a id="supr_scan_nn_selec_b"><input type="submit" value="'+ text.supr_scan_coche_nnslec +'" style="margin-top:5px;"/></a></center>'; //remise a 0 document.getElementById("zero_b").addEventListener("click", function(event){reset(info.serveur);remlir_tableau(-1, 0);}, true); //supressions de scan document.getElementById("supr_scan_b").addEventListener("click", function(event){del_scan_checkbox(info.serveur, true);remlir_tableau(-1, 0);}, true); document.getElementById("supr_scan_nn_selec_b").addEventListener("click", function(event){del_scan_checkbox(info.serveur, false);remlir_tableau(-1, 0);}, true); } /////// on trie le tableau ,affiche les lignes, on remplit en meme temps les export(bbcode/html) et colorie les lignes de flottes en vol. /////////////////////////////////// function remlir_tableau(classementsecondaire, type_croissant) { // on trie le tableau que si besoin est. if (parseInt(classementsecondaire) !== -1) { trie_tableau(info.serveur, classementsecondaire, type_croissant); } afficher_ligne_interieur_tab(info.serveur); // On crée les événement pour les suppressions de scans via l'icone corbeille $('.del1_scan').on('click', function() { // on extrait le numéro du scan de l'id var numero_scan = parseInt($(this).data('id')); var scanList = GM_getValue('scan' + info.serveur, '').split('#'); scanList.splice(numero_scan, 1); GM_setValue('scan' + info.serveur, scanList.join('#')); remlir_tableau(-1, 0); }); // on colorie les lignes selon les mouvements de flottes $.get('/game/index.php?page=eventList&ajax=1', showAttaque, 'html'); // on affiche les numeros de pages si un nombre de scans par page est demandé var page_bas = ''; if (nb_scan_page != 0) { page_bas = 'Page : '; var num_page = info.url.split('&page_r=')[1]; var scan_info = GM_getValue('scan' + info.serveur, '').split('#'); var nb = scan_info.length; var nb_page_poss = Math.ceil(nb / nb_scan_page); if (num_page == undefined || num_page == 1 || num_page == '') { num_page = 1; } for (var i = 1; i < (nb_page_poss + 1); i++) { if (i != num_page) { page_bas = page_bas + ' <a href="' + url_2 + '&amp;raidefacil=scriptOptions&amp;page_r=' + i + '" >' + i + '</a>'; } else { page_bas = page_bas + ' ' + i; } if (i != nb_page_poss) { page_bas = page_bas + ','; } } } document.getElementById('page').innerHTML = page_bas; } remlir_tableau(-2, 0); //classer par colone croissante /decroissante grace au titre de colone /** Truc pour classer en cliquant sur le titre des colones **///{ var id_th_classement = new Array("ccoordonee","cjoueur","cplanete","cdate","cprod_h","cressourcexh","cress","ccdr","ccdr_ress","cnb_v1","cnb_v2","cnb_d1","cnb_d2"); var numero_th_classement = new Array("1","2","3","0","20e","20d","12","8","20c","17","22","18","23"); var trierColonneCallback = function (event) { var id_colone_titre = this.id; for (var e = 0; e < (id_th_classement.length); e++) { if (id_th_classement[e] == id_colone_titre) { if (this.className != "decroissant") {// soit pas de classe soit croissant remlir_tableau(numero_th_classement[e], 'croissant'); this.className = 'decroissant'; } else { remlir_tableau(numero_th_classement[e], 'decroissant'); this.className = "croissant"; } } } }; for (var q = 0; q < id_th_classement.length; q++) { if (document.getElementById(id_th_classement[q])) { document.getElementById(id_th_classement[q]).addEventListener("click", trierColonneCallback, true); } } //} // changement du select pour lune /planete/tout document.getElementById("change_value_affiche").addEventListener("click", function (event) { afficher_seulement = document.getElementById('choix_affichage2').value; filtre_actif_inactif = document.getElementById('filtre_actif_inactif').value; filtre_joueur = document.getElementById('filtre_joueur').value; remlir_tableau(-1, 0); }, true); //////////////// on coche les options et rajoute les addevents et rajoute les boutons /////////////// // OPTION PRESELECTIONNER function preselectiionne(variable1, check0, check1) { if (variable1 == 0) { document.getElementById(check0).checked = "checked"; } else if (variable1 == 1) { document.getElementById(check1).checked = "checked"; } } /** preselectionn de toute les options selon des variables **/{ //mon compte // Autre : document.getElementById('vaisseau_vite').value = vaisseau_lent; //variables // Selection de scan : if(type_prend_scan == 0) {document.getElementById("prend_type0").checked = "checked";} else if(type_prend_scan == 1) {document.getElementById("prend_type1").checked = "checked";} else if(type_prend_scan == 2) {document.getElementById("prend_type2").checked = "checked";} //Classement : document.getElementById('classement').value = classement; preselectiionne(reverse, "q_reverse_croissant" , "q_reverse_decroissant"); //Options de sauvegarde de scan : preselectiionne(scan_preenrgistre, "save_auto_scan_non" , "save_auto_scan_oui"); preselectiionne(scan_remplace, "scan_remplace_non" , "scan_remplace_oui"); //Autre : preselectiionne(import_q_rep, "import_remplace" , "import_rajoute"); preselectiionne(lien_raide_nb_pt_gt, "lien_raide_nb_gt_remplit" , "lien_raide_nb_pt_remplit"); if(lien_raide_nb_pt_gt == 2){document.getElementById("lien_raide_nb_pt_gt2").checked = "checked";} document.getElementById('nb_ou_pourcent').value = nb_ou_pourcent; // affichages // Changement dans les colonnes : preselectiionne(q_date_type_rep, "date_type_chrono" , "date_type_heure"); preselectiionne(cdr_q_type_affiche, "recycleur_type_affichage_ressource" , "recycleur_type_affichage_recyleur"); //Changement dans boutons de droites : if(simulateur == 0) {document.getElementById("sim_q_dra").checked = "checked";} else if(simulateur == 1) {document.getElementById("sim_q_speed").checked = "checked";} else if(simulateur == 2) {document.getElementById("sim_q_ogwin").checked = "checked";} else if(simulateur == 3) {document.getElementById("sim_q_autre").checked = "checked";} preselectiionne(q_mess, "mess_origine_aff_non" , "mess_origine_aff_oui"); preselectiionne(espionnage_lien, "espionn_galaxie" , "espionn_fleet"); preselectiionne(q_lien_simu_meme_onglet, "q_lien_simu_meme_onglet_oui" , "q_lien_simu_meme_onglet_non"); //Affichage de Colonne : preselectiionne(q_compteur_attaque, "compteur_attaque_aff_non" , "compteur_attaque_aff_oui"); preselectiionne(q_vid_colo, "aff_vid_colo_non" , "aff_vid_colo_oui"); preselectiionne(question_rassemble_col, "rassemble_cdr_ress_non" , "rassemble_cdr_ress_oui"); preselectiionne(pt_gt, "q_pt_gt_non" , "q_pt_gt_oui"); preselectiionne(prod_h_q, "prod_h_aff_non" , "prod_h_aff_oui"); preselectiionne(date_affiche, "date_affi_non" , "date_affi_oui"); preselectiionne(tps_vol_q, "tps_vol_afficher_non" , "tps_vol_afficher_oui"); preselectiionne(nom_j_q_q, "nom_joueur_affi_non" , "nom_joueur_affi_oui"); if(nom_p_q_q == 0) document.getElementById('nom_planet_affi_non').checked = "checked"; else document.getElementById('nom_planet_affi_oui').checked = "checked"; // else if(nom_p_q_q == 2) // {document.getElementById('nom_planet_affi_autre').checked = "checked";} preselectiionne(coor_q_q, "coord_affi_non" , "coord_affi_oui"); preselectiionne(defense_question, "defense_q_n" , "defense_q_nb"); if(defense_question == 2){document.getElementById("defense_q_val").checked = "checked";} preselectiionne(vaisseau_question, "vaisseau_q_n" , "vaisseau_q_nb"); if(vaisseau_question == 2){document.getElementById("vaisseau_q_val").checked = "checked";} preselectiionne(tech_q, "tech_aff_non" , "tech_aff_oui"); //Affichage Global : preselectiionne(q_galaxie_scan, "scan_galaxie_cours_non" , "scan_galaxie_cours_oui"); if(q_galaxie_scan == 2){document.getElementById("scan_galaxie_autre").checked = "checked";} else if(q_galaxie_scan == 3){document.getElementById("scan_galaxie_plus_ou_moin").checked = "checked";} preselectiionne(afficher_seulement, "afficher_lune_planet" , "afficher_planet_seul"); if(afficher_seulement == 2){document.getElementById("afficher_lune_seul").checked = "checked";} preselectiionne(q_def_vis, "aff_lign_def_invisible_non" , "aff_lign_def_invisible_oui"); preselectiionne(q_flo_vis, "aff_lign_flot_invisible_non" , "aff_lign_flot_invisible_oui"); //Autre : preselectiionne(q_techzero, "q_techzero_non" , "q_techzero_oui"); preselectiionne(q_icone_mess, "icone_parti_mess_non" , "icone_parti_mess_oui"); // select document.getElementById('choix_affichage2').value = afficher_seulement; /** langue **/ document.getElementById('langue').value = langue; /** bbcode **/ preselectiionne(q_cite, "cite0" , "cite1"); preselectiionne(q_centre, "centre0" , "centre1"); preselectiionne(center_typeq, "centre_type0" , "centre_type1"); preselectiionne(q_url_type, "url_type0" , "url_type1"); } //changement des chiffres dans les options document.getElementById("val_res_min").addEventListener("change", function (event) { var val_res_minn = document.getElementById("val_res_min").value; document.getElementsByClassName("y")[0].innerHTML = val_res_minn; document.getElementsByClassName("y")[1].innerHTML = val_res_minn; }, true); document.getElementById("valeur_cdr_mini").addEventListener("change", function (event) { var valeur_cdr_minis = document.getElementById("valeur_cdr_mini").value; document.getElementsByClassName("x")[0].innerHTML = valeur_cdr_minis; document.getElementsByClassName("x")[1].innerHTML = valeur_cdr_minis; }, true); document.getElementById("valeur_tot_mini").addEventListener("change", function (event) { var valeur_tot_minis = document.getElementById("valeur_tot_mini").value; document.getElementsByClassName("z")[0].innerHTML = valeur_tot_minis; }, true); /******** Partie qui rajoute les events d'ouverture/fermeture de blocs avec des clics **********///{ /* permet d'afficher/masquer un panneau d'options en cliquant sur un lien * le panneau d'options affiché/masqué est celui désigné par l'attribut "data-cible" du lien * les autres panneaux d'options déjà affiché seront masqué si un autre s'affiche */ var changeDisplayedOption = function (eventObject) { var titre = $(eventObject.target); var contenu = $('#' + titre.data('cible')); var closed = contenu.css('display') === 'none'; // on ferme tous les panneaux d'option titre.parent().children('.open').removeClass('open'); // si le contenu est caché alors on ouvre ce panneau if (closed) { titre.addClass('open'); contenu.addClass('open'); var selects = $('select.dropdownInitialized:not(.fixed)', contenu); if (selects.length) { ogameStyleSelectFix(selects); } } }; /* permet d'afficher/masquer un élément en cliquant sur un lien * l'élément affiché/masqué est celui désigné par l'attribut "data-cible" du lien */ var afficherMasquerPanneau = function (eventObject) { var titre = $(eventObject.target); var contenu = $('#' + titre.data('cible')); titre.toggleClass('open'); contenu.toggleClass('open'); if (eventObject.data !== null && eventObject.data.callback !== undefined) { eventObject.data.callback(); } }; // fonction qui met le listener pour afficher/masquer le textarea de simulation function display_change(idclique, idouvre_f) { document.getElementById(idclique).addEventListener("click", function (event) { var cellule = $('#' + idouvre_f); cellule.toggle(); }, true); } // Afficher la fenêtre de choix de touche $('#shortcut_attack_next_modify').click(function () { findKey({ defaultValue: stockageOption.get('touche raid suivant'), callback: function (which) { if (which) { stockageOption.set('touche raid suivant', which).save(); $('#shortcut_attack_next').val(which); logger.log('touche choisie : ' + which); } } }); }); // afficher/masquer les options $('#optionclique').click(afficherMasquerOptions); // afficher/masque les panneaux d'options $('#option_script > .sectionTitreOptions').click(changeDisplayedOption); // afficher/masquer l'import/export $('#imp_exp_clique').click(afficherMasquerPanneau); // afficher/masquer le bbcode + html $('#htmlclique').click({ callback: export_html.bind(this, info.serveur, false, info.url, nb_scan_page) }, afficherMasquerPanneau); //ouvrir fermer export scan simulateur if (simulateur == 3) { for (var p = 0; p <= i; p++) { if (document.getElementById('simul_' + p)) { display_change('simul_' + p, 'textarea_' + p); } } } //} // sauvegarder option si clique document.getElementById("sauvegarder_option").addEventListener("click", function (event) { save_option(info.serveur); save_optionbbcode(info.serveur); // On recharge la page pour que les changements prennent effet setTimeout(location.reload.bind(location), 1000); }, true); // import/export document.getElementById("export_script").addEventListener("click", export_scan.bind(undefined, true, '#area_export'), true); document.getElementById("export_script_ns").addEventListener("click", export_scan.bind(undefined, false, '#area_export'), true); document.getElementById("export_options").addEventListener("click", exportOptions.bind(undefined, '#area_export'), true); document.getElementById("import_scan").addEventListener("click", import_scan.bind(undefined, import_q_rep, '#area_import'), true); document.getElementById("import_options").addEventListener("click", importOptions.bind(undefined, '#area_import'), true); /**** partie pour le css du tableau avec les options + déplacer le menu planette ***************/{ // modification du css de la page et du tableau. tableau_raide_facile_value = parseInt(tableau_raide_facile_value); /*if (tableau_raide_facile_value !== 0) { if (document.getElementById("banner_skyscraper")){ var value = parseInt(document.getElementById("banner_skyscraper").offsetLeft) + tableau_raide_facile_value; document.getElementById("banner_skyscraper").style.left = value + 'px'; }; }*/ /*if(document.getElementById("div_raide_facile")) { var value = parseInt(document.getElementById("contentWrapper").offsetWidth) + tableau_raide_facile_value; document.getElementById("div_raide_facile").style.minWidth = value +'px'; }*/ var style_css = '#raide_facile_titre {background-color:#0D1014; border:1px solid black; padding:5px 5px 10px 5px; font-weight:bold; text-align:center;}' + '\n #raid_facile_news {background-color:#0D1014; border:1px solid black; margin-top:10px; padding:5px 5px 10px 5px;}' + '\n #option_script {background-color:#0D1014; border:1px solid black; margin-top:10px; padding:5px 5px 10px 5px; font-size:11px; color:#848484;}' + '\n #div_tableau_raide_facile {background-color:#0D1014; border:1px solid black; margin-top:10px; padding:5px 5px 10px 5px;}' + '\n #text_html_bbcode {display:none; background-color:#0D1014; border:1px solid black; margin-top:10px; padding:5px 5px 10px 5px;}' + '\n #text_html_bbcode.open {display:block;}' + '\n #div_import_exp {display:none; background-color:#0D1014; border:1px solid black; margin-top:10px; padding:5px 5px 10px 5px;}' + '\n #div_import_exp.open {display:block;}' + '\n #filtres {width:100%; padding:5px 5px 5px 5px; font-size:11px; color:#848484; text-align: center;}' + '\n acronym {cursor: pointer;}' + '\n a {cursor: pointer;text-decoration:none;}' + '\n #haut_table2 {background-color: #0D1014;}' + '\n #corps_tableau2 {background-color: #13181D;}' + '\n #corps_tableau2 tr:nth-child(2n) {background-color:#1A2128;}' + '\n #corps_tableau2 tr.attaque {color:'+col_att+';}' + '\n #corps_tableau2 tr.attaqueRet {color:'+col_att_r+';}' + '\n #corps_tableau2 tr.attaque2 {color:'+stockageOption.get('couleur attaque2')+';}' + '\n #corps_tableau2 tr.attaqueRet2 {color:'+stockageOption.get('couleur attaque2 retour')+';}' + '\n #corps_tableau2 tr.attaqueGr {color:'+col_att_g+';}' + '\n #corps_tableau2 tr.attaqueGrRet {color:'+col_att_g_r+';}' + '\n #corps_tableau2 tr.espio {color:'+stockageOption.get('couleur espionnage')+';}' + '\n #corps_tableau2 tr.detruire {color:'+col_dest+';}' + '\n #corps_tableau2 tr.detruireRet {color:'+col_dest_r+';}' + '\n #bas_tableau2 {background-color: #0D1014;}' + '\n #collapse {border-collapse:separate ;}' + '\n #div_raide_facile {float:left; z-index:2;min-width:'+(670+tableau_raide_facile_value)+'px}' + '\n .sectionTitreOptions{text-indent:35px; text-align:left;cursor:pointer;border:1px solid black;font-weight: bold;color:#6F9FC8; background-color: #0D1014;background-attachment: scroll; background-clip: border-box; background-color: #13181D; background-image: url("/cdn/img/layout/fleetOpenAll.gif"); background-origin: padding-box; background-position: 0 0; background-repeat: no-repeat; background-size: auto auto; height: 22px; line-height: 22px; margin-right:auto; margin-left:auto; width:99%; margin-bottom:5px}'+ '\n .sectionTitreOptions:hover{background-color: #23282D;}'+ '\n .sectionTitreOptions.open{background-image: url("/cdn/img/layout/fleetCloseAll.gif");}'+ '\n .sectionOptions{display:none; margin-right:auto; margin-left:auto; width:95%; padding:5px; margin-top:5px; margin-bottom:5px; text-align:left; border:1px solid black; background-color:#13181D;}'+ '\n .sectionOptions.open{display:block;}'+ '\n .titre_interne{font-weight:bold;color:#5A9FC8;}'+ '\n .tableau_interne{padding-top:0px;border-bottom:0px;}'+ '\n #div_raide_facile input[type="submit"] {border: 1px solid #6F899D; color: white; background-color: rgb(92, 118, 139);}'+ '\n #raid_facile_news{color:#FFFFFF; text-align:left; font-size:11px; }'+ '\n #raid_facile_news a {color:#6F9FC8;}'+ '\n #raid_facile_news h4{margin-top:5px;text-indent:10px;font-size:11px;font-weight:bold;color:#6F9FC8;}'+ '\n #tableau_raide_facile{margin-top:5px; margin-bottom:5px; background-color:#0D1014; text-align:center;border-top: 1px solid black; border-bottom: 1px solid black; font-size:10px;line-height:20px;white-space:nowrap;width:100%;}'+ // ' .boutons_haut{text-align:right;}'+ '\n #tableau_raide_facile td {padding-right:2px;padding-left:2px;}'+ '\n #tableau_raide_facile td.right {text-align:right;padding-right:2px;padding-left:2px;}'+ '\n #tableau_raide_facile th.RF_icon {width: 18px;}'+ '\n #tableau_raide_facile th {color: #6F9FC8;}'+ '\n #tableau_raide_facile a {color: #6F9FC8;}'+ '\n #tableau_raide_facile a {color: #6F9FC8;}'+ // Options '#div_raide_facile .tableau_interne tr:hover { color:white; }'+ // Tableau des scans '#div_raide_facile .htmlTooltip > .tooltipTitle { display:none; }'; var heads = document.getElementsByTagName("head"); if (heads.length > 0) { var node = document.createElement("style"); node.type = "text/css"; node.appendChild(document.createTextNode(style_css)); heads[0].appendChild(node); } // détection automatique de la bonne taille pour décaler le menu des planètes plusTard(ajusterTailleBox); } } /* global Tipped */ /* test encodage ces caractère doivent être ben accentués et bien écrits, sinon c'est qu'il y a un problème aâàã eéêè iîì ñ oôòõ uûù € */ (function(){ var injectScript = function() { "use strict"; /** classe de communication avec le script *///{ var Intercom = function() { this.listen(); }; Intercom.prototype = { send: function(action, data){ if (data === undefined) { data = {}; } data.fromPage = true; data.namespace = 'Raid facile'; data.action = action; window.postMessage(data, '*'); }, listen: function(){ window.addEventListener('message', this.received.bind(this), false); }, received: function(event){ if (event.data.namespace !== 'Raid facile' || event.data.fromPage === true) { return; } var data = event.data.data; switch(event.data.action) { case 'ogame style': // Affichage des select et des boutons façon Ogame $('#div_raide_facile select').ogameDropDown(); $('#div_raide_facile input[type="submit"]').button(); break; case 'tooltip': var tooltipSettings = { hideOn: [ { element: 'self', event: 'mouseleave' }, { element: 'tooltip', event: 'mouseenter' } ], skin: 'cloud' }; for (var prop in data.settings) { tooltipSettings[prop] = data.settings[prop]; } var elems = $(data.selector); if (data.htmlTooltip) { for (var i = 0; i < elems.length; ++i) { Tipped.create(elems[i], $('>.tooltipTitle', elems[i])[0], tooltipSettings); } } else { for (var j = 0; j < elems.length; ++j) { Tipped.create(elems[j], tooltipSettings); } } break; } } }; var intercom = new Intercom(); intercom.send('loaded'); //} }; // injection du script var script = document.createElement('script'); script.setAttribute('type', 'text/javascript'); script.innerHTML = '('+injectScript.toString()+')();'; document.head.appendChild(script); })(); // console.profileEnd('Raid facile'); <file_sep>Raid-Facile =========== Raid facile est un userscript pour Ogame qui analyse les rapport d'espionnage afin d'aider à optimiser le choix des cibles. ### Description Voir sur le forum officiel [board.fr.ogame.gameforge.com/raid-facile](http://board.fr.ogame.gameforge.com/board1474-ogame-le-jeu/board641-les-cr-ations-ogamiennes/board642-logiciels-tableurs/p12885519-raide-facile/#post12885519)
533790228e417bb6dac3dd058c264b28c9df5364
[ "JavaScript", "Markdown" ]
2
JavaScript
nmss/Raid-Facile
d8579a9c744ea8cfeb07c30cb2cfd1c04c3d3bbb
e26ceec7a8956a26e7c1f335c707910d3714f8de
refs/heads/master
<repo_name>davve94/WorkoutBackend<file_sep>/src/main/java/db/Entities/WorkoutPlan.java package db.Entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import java.util.List; @Entity public class WorkoutPlan { @Id @GeneratedValue private Integer id; private String timestamp; @OneToMany private List<Workout> workout; private String description; public WorkoutPlan(Integer id, String timestamp, List<Workout> workout, String description) { this.id = id; this.timestamp = timestamp; this.workout = workout; this.description = description; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public List<Workout> getWorkout() { return workout; } public void setWorkout(List<Workout> workout) { this.workout = workout; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } } <file_sep>/src/main/java/db/Entities/Food.java package db.Entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity public class Food { @Id @GeneratedValue private Integer id; private String name; @ManyToOne private FoodCategory foodCategory; private String ingredients; public Food(Integer id, String name, FoodCategory foodCategory, String ingredients) { this.id = id; this.name = name; this.foodCategory = foodCategory; this.ingredients = ingredients; } 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; } public FoodCategory getFoodCategory() { return foodCategory; } public void setFoodCategory(FoodCategory foodCategory) { this.foodCategory = foodCategory; } public String getIngredients() { return ingredients; } public void setIngredients(String ingredients) { this.ingredients = ingredients; } } <file_sep>/src/main/java/db/Entities/FoodPlan.java package db.Entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import java.util.List; @Entity public class FoodPlan { @Id @GeneratedValue private Integer id; private String timestamp; @OneToMany private List<Food> food; private String description; public FoodPlan(Integer id, String timestamp, List<Food> food, String description) { this.id = id; this.timestamp = timestamp; this.food = food; this.description = description; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTimestamp() { return timestamp; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public List<Food> getFood() { return food; } public void setFood(List<Food> food) { this.food = food; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
da9514c440c25ae1091293448d218b05b0d1782d
[ "Java" ]
3
Java
davve94/WorkoutBackend
93db96d65a95a90631dfda5d3827730f9210b585
f7e134a7ef3fc31dd483aac3cddbf48e9e24c071
refs/heads/master
<file_sep># ssm_crud 功能 ssm分页查询、添加、修改、单个删除、批量删除 技术 ssm、bootstrap、ajax <file_sep>package com.ssm.dao; import com.ssm.entity.DeptEntity; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface DeptDao{ int insert(DeptEntity deptEntity); int updateById(DeptEntity deptEntity); List<DeptEntity> selectById(DeptEntity deptEntity); }<file_sep>package com.ssm.dao; import com.ssm.entity.EmployeeEntity; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; /** * @author lijinghua * @Description: * @date */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:mybatis-config.xml" , "classpath:applicationContext.xml" }) public class EmployeeDaoTest { @Autowired private EmployeeDao employeeDao; private EmployeeEntity employeeEntity = new EmployeeEntity(); @Test public void insert() { for(int i = 1; i <= 100; i++){ employeeEntity.setdId(1); employeeEntity.setEmpName("陈奕迅"); employeeEntity.setEmail("<EMAIL>"); employeeEntity.setGender("1"); int result = employeeDao.insert(employeeEntity); System.out.println(result); } } @Test public void updateById() { employeeEntity.setdId(1); employeeEntity.setEmpName("刘若英"); employeeEntity.setEmail("<EMAIL>"); employeeEntity.setEmpId(1); employeeEntity.setGender("0"); int result = employeeDao.updateById(employeeEntity); System.out.println(result); } @Test public void selectById() { //List<EmployeeEntity> result = employeeDao.selectById(employeeEntity); EmployeeEntity result = employeeDao.selectByPrimaryKey(1); System.out.println(result); } }<file_sep>package com.ssm.dao; import com.ssm.entity.DeptEntity; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.List; /** * @author lijinghua * @Description: * @date */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:mybatis-config.xml" , "classpath:applicationContext.xml" }) public class DeptDaoTest { @Autowired private DeptDao deptDao; private DeptEntity deptEntity = new DeptEntity(); @Test public void insert() { DeptEntity deptEntity = new DeptEntity(); deptEntity.setDeptId(11); deptEntity.setDeptName("中台研发部"); int result = deptDao.insert(deptEntity); System.out.println(result); } @Test public void updateById() { deptEntity.setDeptName("海关业务部"); deptEntity.setDeptId(11); int result = deptDao.updateById(deptEntity); System.out.println(result); } @Test public void selectById() { List<DeptEntity> result = deptDao.selectById(deptEntity); System.out.println(result); } }
b4654f3639c2524c67f742b9bc51006072287871
[ "Markdown", "Java" ]
4
Markdown
ljh88/ssm_crud
efa813613a85d5933c07fbf175ad3ebfe1d89154
b823d6964d117d65f8a729a09e934d55f9791281
refs/heads/master
<file_sep><?php class custom_video_player { function init() { $this->localeSection = "Custom Actions: Video Player"; $this->JSconfig = array( "title" => \FileRun\Lang::t("Video Player", $this->localeSection), 'iconCls' => 'fa fa-fw fa-play-circle-o', 'useWith' => array('wvideo'), "popup" => true, "requiredUserPerms" => array("download") ); } function run() { global $config; \FileRun::checkPerms("download"); $ext = \FM::getExtension($this->data['fileName']); $handlers = array( 'flv' => 'flv', 'm4v' => 'flv', 'mpg' => 'mpg', 'swf' => 'swf', 'wmv' => 'wmv', 'mov' => 'html5', 'ogv' => 'html5', 'mp4' => 'html5', 'mkv' => 'html5', 'webm' => 'html5' ); $handle = $handlers[$ext]; if (!$handle) { exit('The file type is not supported by this player.'); } require(gluePath($this->path, $handle, "/display.php")); } function stream() { \FileRun::checkPerms("download"); \FileRun\Utils\Downloads::sendFileToBrowser($this->data['filePath']); \FileRun\Log::add(false, "preview", array( "relative_path" => $this->data['relativePath'], "full_path" => $this->data['filePath'], "method" => "Video Player" )); exit(); } }<file_sep><?php include_once realpath($_SERVER["DOCUMENT_ROOT"])."/setting/control.php"; ?> <?php $email = htmlentities($_POST['userEmail'], ENT_QUOTES, "UTF-8"); $password = htmlentities($_POST['userPassword'], ENT_QUOTES, "UTF-8"); if (!RegexCheck($_regexMail,$email)){ echo ' <div class="alert alert-dismissible alert-danger"> <button type="button" class="close" data-dismiss="alert">&times;</button> <strong>Error:</strong> <a href="#" class="alert-link">Please type correct email. </div> '; exit(); } if (!RegexCheck($_regexPassword,$email)){ echo ' <div class="alert alert-dismissible alert-danger"> <button type="button" class="close" data-dismiss="alert">&times;</button> <strong>Error:</strong> <a href="#" class="alert-link">Please type correct password. </div> '; exit(); } echo ' <div class="alert alert-dismissible alert-success"> <button type="button" class="close" data-dismiss="alert">&times;</button> <strong>Success:</strong> You have successful logged! </div>'; sleep(3); echo '<script>loadLoginNavigationBar();</script>'; exit(); ?><file_sep><?php class custom_office_web_viewer { var $online = true; function init() { $proto = isSSL() ? "https" : "http"; $this->URL = $proto."://view.officeapps.live.com/op/view.aspx"; $this->JSconfig = array( "title" => \FileRun\Lang::t("Office Web Viewer", 'Custom Actions: Office Web Viewer'), "icon" => 'images/icons/office.png', "extensions" => array( "doc", "docx", "docm", "dotm", "dotx", "xls", "xlsx", "xlsb", "xls", "xlsm", "ppt", "pptx", "ppsx", "pps", "pptm", "potm", "ppam", "potx", "ppsm" ), "popup" => true, "requiredUserPerms" => array("download") ); } function run() { $url = $this->weblinks->getOneTimeDownloadLink($this->data['filePath']); if (!$url) { echo "Failed to setup weblink"; exit(); } \FileRun\Log::add(false, "preview", array( "relative_path" => $this->data['relativePath'], "full_path" => $this->data['filePath'], "method" => "Office Web Viewer" )); ?> <html> <head> <title></title> <style> body { border: 0px; margin: 0px; padding: 0px; overflow:hidden; } </style> </head> <body> <iframe scrolling="no" width="100%" height="100%" border="0" src="<?php echo $this->URL?>?src=<?php echo urlencode($url)?>"> </iframe> </body> </html> <?php } }<file_sep><?php global $app, $settings, $config; ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title></title> <link rel="stylesheet" type="text/css" href="css/style.css?v=<?php echo $settings->currentVersion;?>" /> <link rel="stylesheet" type="text/css" href="css/ext.php?v=<?php echo $settings->currentVersion;?>" /> <script type="text/javascript" src="js/min.php?extjs=1&v=<?php echo $settings->currentVersion;?>"></script> <script src="customizables/custom_actions/code_editor/app.js?v=<?php echo $settings->currentVersion;?>"></script> <script src="?module=fileman&section=utils&page=translation.js&sec=<?php echo S::forURL("Custom Actions: Text Editor")?>&lang=<?php echo S::forURL(\FileRun\Lang::getCurrent())?>"></script> <script src="customizables/custom_actions/code_editor/ace/ace.js" type="text/javascript" charset="utf-8"></script> <script src="customizables/custom_actions/code_editor/ace/ext-modelist.js" type="text/javascript" charset="utf-8"></script> <script> var URLRoot = '<?php echo S::safeJS($config['url']['root'])?>'; var path = '<?php echo S::safeJS($this->data['relativePath'])?>'; var filename = '<?php echo S::safeJS($this->data['fileName'])?>'; var windowId = '<?php echo S::safeJS(S::fromHTML($_REQUEST['_popup_id']))?>'; var charset = '<?php echo S::safeJS(S::fromHTML($_REQUEST['charset']))?>'; var charsets = <?php $list = array(); foreach($enc as $e) { $list[] = array($e); } echo json_encode($list); ?> </script> <style>.ext-el-mask { background-color: white; }</style> </head> <body id="theBODY" onload="FR.init()"> <textarea style="display:none" id="textContents"><?php echo S::safeHTML(S::convert2UTF8($this->data['fileContents']))?></textarea> </body> </html><file_sep><?php include_once $_phpPath."/setting/trigger/sqlstore.php"; // asdjnoqlinfkjvnu!Q@#EDASnkjnasdfkjn!@#E|+ include_once $_phpPath."/setting/trigger/emailstore.php"; // asdjnoqlinfkjvnu!Q@#EDASnkjnasdfkjn!@#E|++ include_once $_phpPath."/setting/trigger/smtpstore.php"; // asdjnoqlinfkjvnu!Q@#EDASnkjnasdfkjn!@#E|+++ include_once $_phpPath."/setting/installer/privatekey.php"; // Get Private Key if ($_privateKey != NULL){ $decryptPrivateKey = base64_decode(hex2bin(strrev($_privateKey))); $explodeKey = explode('|',$decryptPrivateKey); $selectedKey = array(); foreach($explodeKey AS $key) { if(strlen($key) > 1) array_push($selectedKey,$key); } }else{ echo "<br><span color='red'>Cannot Define Private Key</span>"; echo "<br><a href='".$_url."setting/installer/'>Please create the private key!</a>"; exit(); } if ($_sqlEncryptString != NULL){ function decryptSQLString($encryptSQLString, $iv_size, $privateKey){ $ciphertext_dec = base64_decode($encryptSQLString); $iv_dec = substr($ciphertext_dec, 0, $iv_size); $ciphertext_dec = substr($ciphertext_dec, $iv_size); $plaintext_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $privateKey, $ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec); return $plaintext_dec; } $sqlPackage = decryptSQLString($_sqlEncryptString, $selectedKey[1], $selectedKey[0]); }else{ echo "<br><span color='red'>Cannot Define SQL Connect Package</span>"; echo "<br><a href='".$_url."setting/installer/'>Please config your database!</a>"; exit(); } ?><file_sep><?php include_once realpath($_SERVER["DOCUMENT_ROOT"])."/setting/control.php"; ?> <?php // Bug > // Test //echo ValidPassword(CreatingHash('1234'),'<PASSWORD>b<PASSWORD> <KEY>'); //echo ValidPassword(CreatingHash('1234'),CreatingSalt(CreatingHash('1234'))); // Perfect $privateKey = "<KEY>"; $salt = "<KEY>"; echo encryptData("Test",$privateKey,$salt); echo "<br>"; echo decryptData("6av<KEY>",$privateKey,$salt); ?><file_sep><?php class custom_kml_viewer { var $online = true; function init() { $this->URL = 'https://earth.google.com/kmlpreview/'; $this->JSconfig = array( "title" => \FileRun\Lang::t('Google Earth', 'Custom Actions: Google Earth'), 'icon' => 'images/icons/gearth.png', "extensions" => array("kml", "kmz"), "popup" => true, "requiredUserPerms" => array("download") ); } function run() { $data = $this->weblinks->createForService($this->data['filePath'], 2, $this->data['shareInfo']['id']); $url = $this->weblinks->getURL(array( "id_rnd" => $data['id_rnd'], "filename" => $this->data['fileName'] ) ); if (!$url) { echo "Failed to setup weblink"; exit(); } \FileRun\Log::add(false, "preview", array( "relative_path" => $this->data['relativePath'], "full_path" => $this->data['filePath'], "method" => "google-earth" )); ?> <html> <head> <title></title> <style> body { border: 0px; margin: 0px; padding: 0px; overflow:hidden; } </style> </head> <body> <iframe scrolling="no" width="100%" height="100%" border="0" src="<?php echo $this->URL?>#url=<?php echo urlencode($url)?>"> </iframe> </body> </html> <?php } }<file_sep><?php if ($sqlPackage != NULL){ // TODO: Need to implement multiple DB Connect As Well // Seperate the Package $explodeSQLKey = explode('|',$sqlPackage); $selectedSQLKey = array(); foreach($explodeSQLKey AS $key) { if(strlen($key) > 1) array_push($selectedSQLKey,$key); } // Globals Variable $GLOBALS['hostname'] = $selectedSQLKey[0]; $GLOBALS['username'] = $selectedSQLKey[1]; $GLOBALS['password'] = $selectedSQLKey[2]; $GLOBALS['database'] = $selectedSQLKey[3]; // Function to connect to DB function ConnectDB($hostname, $username, $password, $database){ $_db = new mysqli($hostname, $username, $password, $database); if($_db->connect_error){ die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error()); } return $_db; } }else{ consoleData("Please insert database information"); echo "<br><a href='".$_url."setting/installer/'>Please config your database!</a>"; exit(); } ?><file_sep><?php $url = $config['url']['root']; $url .= "/?module=fileman_myfiles&section=ajax&page=thumbnail"; $url .= "&path=".S::forURL($this->data['relativePath']); $url .= "&noCache=1"; ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title></title> <script> function run() { document.getElementById('imgHolder').innerHTML = '<img src="<?php echo $url?>&width='+encodeURIComponent(document.body.clientWidth)+'&height='+encodeURIComponent(document.body.clientHeight)+'" border="0" />'; } </script> <style>body {margin:0px;padding:0px;}</style> </head> <body onload="javscript:run()"> <table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="center" id="imgHolder"></td> </tr> </table> </body> </html><file_sep><?php ?> <html> <head> <title></title> <style> body { border: 0px; margin: 0px; padding: 0px; overflow:hidden; } </style> <!-- Load Feather code --> <script type="text/javascript" src="https://dme0ih8comzn4.cloudfront.net/imaging/v3/editor.js"></script> <!-- Instantiate Feather --> <script type='text/javascript'> var featherEditor = new Aviary.Feather({ apiKey: '<KEY>', theme: 'light', displayImageSize: true, tools: 'all', noCloseButton: true, fileFormat: 'original', appendTo: 'injection_site', onLoad: function() { launchEditor('image1', '<?php echo S::safeJS($this->data['fileURL'])?>'); }, onSave: function(imageID, newURL) { var img = document.getElementById(imageID); img.src = newURL; with (window.parent) { Ext.Ajax.request({ url: '<?php echo S::safeJS($this->data['saveURL'])?>&fromURL='+encodeURIComponent(newURL), callback: function(opts, succ, req) { FR.utils.reloadGrid(); FR.UI.feedback(req.responseText); } }); } }, onError: function(errorObj) {alert(errorObj.message);} }); function launchEditor(id, src) { featherEditor.launch({ image: id, url: src }); return false; } </script> </head> <body> <div id="injection_site"></div> <table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td align="center" valign="middle"> <img id="image1" style="display:none;" src="<?php echo $this->data['fileURL']?>" /> </td> </tr> </table> </body> </html><file_sep><div class="container"> <hr> <?php require_once $thisPageContent ?> <hr> <?php require_once $_phpPath."page/_layout/body/_footer.php"; ?> </div> <div class="downer-containner"> <?php if (!empty($thisPageDownerContent)){require_once $thisPageDownerContent;} ?> </div><file_sep><?php // Shortcut connect DB function Db(){ $_db = ConnectDB($GLOBALS['hostname'],$GLOBALS['username'],$GLOBALS['password'],$GLOBALS['database']); return $_db; } ?><file_sep><nav class="navbar navbar-default" role="navigation" id="nav"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#"><?php echo $_siteName;?></a> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav"> <li><a href="<?php echo $_url;?>">Home</a></li> <li><a href="<?php echo $_url;?>about">About</a></li> <li><a href="#">Page 2</a></li> <li><a href="#">Page 3</a></li> </ul> <ul class="nav navbar-nav navbar-right" id="userNavbar"> </ul> </div> </div> </nav> <!-- Need auto get page --> <file_sep><?php class custom_admin_indexer_test { function init() { $this->config = array( 'localeSection' => 'Custom Actions: Admin: Text Indexer Test' ); $this->JSconfig = array( 'title' => $this->getString('Admin: Text Indexer Test'), 'iconCls' => 'fa fa-fw fa-bug', 'requiredUserPerms' => array('download'), "popup" => true, 'width' => 500 ); } function isDisabled() { global $settings; return (!$settings->search_enable || !\FileRun\Perms::isSuperUser()); } function getString($s) { return S::safeJS(\FileRun\Lang::t($s, $this->config['localeSection'])); } function run() { $search = new \FileRun\Search(); $tika = $search->getApacheTika(); header('Content-type: text/plain; charset=UTF-8'); if (\FM::isPlainText(array('fileName' => $this->data['fileName']))) { echo $tika->getText($this->data['filePath']); } else { echo S::convert2UTF8($tika->getText($this->data['filePath'])); } } }<file_sep><?php $thisPageName = "About"; $thisPageMeta = ""; $thisPageHeading = $thisPageName; $thisPageSubHeading = "PHP Easy"; $thisPageContent = $_SERVER['DOCUMENT_ROOT']."/page/about/view/aboutView.php"; $thisPageBreadCrumbUse = 1; require_once $_SERVER['DOCUMENT_ROOT']."/page/_layout/_layout.php"; //echo realpath('.'); ?><file_sep><?php function RegexCheck($regexPattern, $string){ return (preg_match($regexPattern,$string)?true:false); } function RedirectURL ($redirectInSecond, $toURL){ return header( "refresh:".$redirectInSecond.";url=".$toURL."" ); } function ConsoleData($data) { echo (is_array($data)?"<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>":"<script>console.log( 'Debug Objects: " . $data . "' );</script>"); } function GetIpUser(){ return (!empty($_SERVER['HTTP_CLIENT_IP']))?$ip = $_SERVER['HTTP_CLIENT_IP']:(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))?$ip = $_SERVER['HTTP_X_FORWARDED_FOR']:$ip = $_SERVER['REMOTE_ADDR']; } function ConnectSQL($connectString){ } function FileReader ($fileDirectory){ if ($openFile = fopen($fileDirectory, "r")){ $readFile = fread($openFile,filesize($fileDirectory)); fclose($openFile); return $readFile; } return "Cannot Read File"; } function FileWriter ($fileDirectory){ } function GenerateLinkPath($path,$_url){ $explode = explode("/",$path); $countExplode = count($explode); $link[0] = $_url; for ($x = 1; $x < $countExplode; $x++){ $link[$x] = $link[$x-1].$explode[$x].'/'; $result .= '<a href="'.substr($link[$x],0,-1).'">'.ucfirst($explode[$x]).'</a>'.' > '; } return substr($result,0,-2); } function GetAllFileInFolder($path){ return array_diff(scandir($path),array('..', '.')); } function GetAllFileInFolderWithType($path, $fileType){ $listOfAllFile = array_diff(scandir($path),array('..', '.')); return preg_grep("/^.*\.(".$fileType.")$/", $listOfAllFile); } function PriorityKey($array, $value){ $key = array_search($value, $array); if($key){ unset($array[$key]); array_unshift($array, $value); } return $array; } function isSSL() { if( !empty( $_SERVER['https'] ) ) return true; if( !empty( $_SERVER['HTTP_X_FORWARDED_PROTO'] ) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' ) return true; return false; } include_once $_phpPath."setting/encrypt_library.php"; ?> <file_sep><?php ///////////////////////////////////////////////// // Version 1 // Create priority for jquery.js must be load first /*foreach (priorityKey(getAllFileInFolderWithType($_phpPath.'js', 'js'), "jquery-3.1.1.min.js") as $jsFile){ echo '<script type="text/javascript" src="'.$_url.'js/'.$jsFile.'"></script>'; } foreach (getAllFileInFolderWithType($_phpPath.'page'.(empty(substr($_SERVER['REQUEST_URI'],1))?'/index':$_SERVER['REQUEST_URI']).'/view/js', 'js') as $jsFile){ echo '<script type="text/javascript" src="'.$_url.'page/'.(empty(substr($_SERVER['REQUEST_URI'],1))?'index':$_SERVER['REQUEST_URI']).'/view/js/'.$jsFile.'"></script>'; } /* Need to auto import .php, maybe delete js-top */ ////////////////////////////////////////////////// // Version 2 // TODO: Need re check some value get wrong // TODO: Need to check if file has been include, must apply history $_SESSION['jsIncluded'] = List<String> for ($x = 0; $x < $_countGetPath; $x++){ // Get All Public Inheritent File $_combineLine[$x] = $_combineLine[$x - 1].$_getPath[$x].'/'; foreach (priorityKey(priorityKey(getAllFileInFolderWithType($_phpPath.'js'.$_combineLine[$x], 'js'), "bootstrap.min.js"), "jquery-3.1.1.min.js") as $jsFile){ echo('<script type="text/javascript" src="'.$_url.'js'.$_combineLine[$x].$jsFile.'"></script>'); //consoleData($jsFile); } // Include all .php except this file foreach (getAllFileInFolderWithType($_phpPath.'js'.$_combineLine[$x], 'php') as $jsFile){ //echo('<script type="text/javascript" src="'.$_url.'js'.$_combineLine[$x].$jsFile.'"></script>'); if (basename(__FILE__, '.') != $jsFile){ //consoleData($jsFile); include_once $_phpPath.'js'.$_combineLine[$x].$jsFile; } } // Get Private File if ($x == ($_countGetPath - 1)){ //consoleData($_phpPath.'js'.$_combineLine[$x].'private'); foreach (getAllFileInFolderWithType($_phpPath.'js'.$_combineLine[$x].'private', 'js') as $jsFile){ echo('<script type="text/javascript" src="'.$_url.'js'.$_combineLine[$x].'private/'.$jsFile.'"></script>'); } foreach (getAllFileInFolderWithType($_phpPath.'js'.$_combineLine[$x].'private', 'php') as $jsFile){ if (basename(__FILE__, '.') != $jsFile){ //consoleData($jsFile); include_once $_phpPath.'js'.$_combineLine[$x].'private/'.$jsFile; } } } } ?> <script src="//fast.eager.io/kcBx5lOVwX.js"></script> <file_sep><meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="icon" href="<?php echo $_url;?>favicon.ico"> <?php echo $_thisPageMeta; ?><file_sep>FR.UI.imagePreview = { UI: {}, items: new Ext.util.MixedCollection(), highDPIRatio: 2, blankSrc: 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==', init: function(clickedItem) { this.open = true; this.baseSrc = URLRoot+'/t.php'; this.items.clear(); if (!this.body) { this.body = Ext.getBody(); } this.showMask(); var startIndex = this.collectItems(clickedItem); this.createImageDOM(); this.createUI(); this.setItem(startIndex); }, getNaturalSize: function (img) { if (Ext.isIE8) { var tmpImg = new Image(); tmpImg.src = img.src; return {width: tmpImg.width, height: tmpImg.height}; } else { return {width: img.naturalWidth, height: img.naturalHeight}; } }, createImageDOM: function() { if (!this.iconEl) { this.iconEl = Ext.DomHelper.append(this.body, { tag: 'img', alt: '', cls: 'fr-image-preview-icon', src: this.blankSrc }, true); this.iconEl.setVisibilityMode(Ext.Element.DISPLAY); } if (!this.loaderEl) { this.loaderEl = Ext.DomHelper.append(this.body, {tag: 'img'}, true); Ext.get(this.loaderEl).on('load', function () { if (this.loaderEl.settingBlankPixel) { this.loaderEl.settingBlankPixel = false; return false; } this.imgDOM.set({src: this.loaderEl.getAttribute('src')}); }, this); } if (!this.imgDOM) { this.imgDOM = Ext.DomHelper.append(this.body,{ tag: 'img', alt: '', cls: 'fr-image-preview', src: this.blankSrc }, true); this.imgDrag = new Ext.dd.DD(this.imgDOM, false, {moveOnly: true, scroll: false}); this.imgDrag.lock(); Ext.get(this.imgDOM).on('load', function () { if (this.imgDOM.settingBlankPixel) { this.imgDOM.settingBlankPixel = false; return false; } if (this.zoomed) { var min = this.body.getHeight(); min = Math.round(min-10/100*min); var nSize = this.getNaturalSize(this.imgDOM.dom); this.UI.zoomSlider.setMinValue(min); this.UI.zoomSlider.setMaxValue(nSize.height); this.UI.zoomSlider.suspendEvents(); this.UI.zoomSlider.setValue(nSize.height); this.UI.zoomSlider.resumeEvents(); } this.adjustImageSize(); if (this.isCached(true)) { this.iconEl.hide(); this.imgDOM.setVisible(true); } else { this.iconEl.fadeOut({stopFx: true, duration: 0.2, useDisplay: true}); this.imgDOM.fadeIn({stopFx: true}); } }, this); } }, createUI: function() { if (this.UI.tbarWrap) { if (FR.currentSection == 'trash'){ this.commentsBtn.hide(); this.downloadBtn.hide(); } else { this.commentsBtn.show(); this.downloadBtn.show(); } this.hideUITask.cancel(); this.UI.tbarWrap.show(); this.UI.tbarEl.show(); if (this.count > 1) { this.UI.navLeftWrap.show(); this.UI.navLeft.show(); this.UI.navRightWrap.show(); this.UI.navRight.show(); } this.nav.enable(); return false; } this.UI.tbarWrap = Ext.DomHelper.append(this.body, {tag: 'div', cls: 'fr-prv-tbar-ct-wrap'}, true); this.UI.tbarEl = Ext.DomHelper.append(this.UI.tbarWrap, {tag: 'div', cls: 'fr-prv-tbar-ct'}, true); this.UI.icon = new Ext.Toolbar.Item({cls: 'fr-prv-tbar-icon'}); this.UI.filename = new Ext.Toolbar.TextItem({cls: 'fr-prv-tbar-filename'}); this.UI.pageInfo = new Ext.Toolbar.TextItem({cls: 'fr-prv-tbar-pageinfo', listeners: {'afterrender': FR.UI.tooltip('Use "Page Down" and "Page Up" to change the page')}}); this.UI.status = new Ext.Toolbar.TextItem({cls: 'fr-prv-tbar-status'}); this.UI.zoomSlider = new Ext.Slider({ width: 110, minValue: 0, maxValue: 100, value: 100, hidden: true, cls: 'fr-prv-tbar-slider', listeners: { 'change': function (s, v) { this.applyZoom.cancel(); this.applyZoom.delay(50, false, this, [v]); }, scope: this } }); this.UI.zoomToggle = new Ext.Button({ iconCls: 'fa fa-fw fa-arrows-alt fa-lg', enableToggle: true, toggleHandler: function(b, pressed) { if (pressed){ this.initZoom(); } else { this.cancelZoom(); this.getMaxSize(); this.loadThumb(); } }, scope: this, listeners: {'afterrender': FR.UI.tooltip(FR.T('Zoom'))} }); this.commentsBtn = new Ext.Button({ iconCls: 'fa fa-fw fa-comments-o fa-lg', handler: this.showComments, scope: this, hidden: (!User.perms.read_comments || (FR.currentSection == 'trash')), listeners: {'afterrender': FR.UI.tooltip(FR.T('Comments'))} }); this.downloadBtn = new Ext.Button({ iconCls: 'fa fa-fw fa-download fa-lg', handler: this.download, scope: this, hidden: (FR.currentSection == 'trash'), listeners: {'afterrender': FR.UI.tooltip(FR.T('Download'))} }); this.tbar = new Ext.Toolbar({ autoCreate: {cls: 'fr-prv-tbar'}, renderTo: this.UI.tbarEl, items: [ this.UI.icon, this.UI.filename, this.UI.pageInfo, '->', this.UI.status, this.UI.zoomSlider, this.UI.zoomToggle, this.commentsBtn, this.downloadBtn, { iconCls: 'fa fa-fw fa-close fa-lg', handler: this.close, scope: this, listeners: {'afterrender': FR.UI.tooltip(FR.T('Close'))} } ] }); this.UI.navLeftWrap = Ext.DomHelper.append(this.body, {tag: 'div', cls: 'fr-prv-nav-left-wrap'}, true); this.UI.navLeft = Ext.DomHelper.append(this.UI.navLeftWrap, {tag: 'div', cls: 'fr-prv-nav-btn', style:'float:left', html: '<i class="fa fa-angle-left"></i>'}, true); this.UI.navLeft.on('click', this.previousItem, this); this.UI.navRightWrap = Ext.DomHelper.append(this.body, {tag: 'div', cls: 'fr-prv-nav-right-wrap'}, true); this.UI.navRight = Ext.DomHelper.append(this.UI.navRightWrap, {tag: 'div', cls: 'fr-prv-nav-btn', style:'float:right', html: '<i class="fa fa-angle-right"></i>'}, true); this.UI.navRight.on('click', this.nextItem, this); new Ext.ToolTip({ target: this.UI.navRight, showDelay: 250, html: FR.T('Next'), anchor: 'left', baseCls: 'headerTbar-btn-tooltip' }); new Ext.ToolTip({ target: this.UI.navLeft, showDelay: 250, html: FR.T('Previous'), anchor: 'right', baseCls: 'headerTbar-btn-tooltip' }); if (this.count == 1) { this.UI.navLeftWrap.hide(); this.UI.navLeft.hide(); this.UI.navRightWrap.hide(); this.UI.navRight.hide(); } /* this.UI.tbarWrap.on('mouseleave', this.hideUI, this); this.UI.navLeftWrap.on('mouseleave', this.hideUI, this); this.UI.navRightWrap.on('mouseleave', this.hideUI, this); this.imgDOM.on('mouseleave', this.hideUI, this); this.UI.tbarWrap.on('mouseenter', this.showUI, this); this.imgDOM.on('mouseenter', this.showUI, this); this.UI.navLeftWrap.on('mouseenter', this.showUI, this); this.UI.navRightWrap.on('mouseenter', this.showUI, this); */ this.setupKeys(); }, initZoom: function() { if (!this.zoomed) { this.UI.zoomSlider.show(); this.imgDrag.unlock(); this.maxW = 10000; this.maxH = 10000; this.zoomed = true; this.loadThumb(); } }, applyZoom: new Ext.util.DelayedTask(function(v) { this.imgDOM.setHeight(v).center(); }), cancelZoom: function() { if (this.zoomed) { this.zoomed = false; this.UI.zoomSlider.hide(); this.imgDrag.lock(); this.UI.zoomToggle.toggle(false, true); this.getMaxSize(); } }, showUI: function() {this.showUITask.delay(50, false, this);}, showUITask: new Ext.util.DelayedTask(function() { this.hideUITask.cancel(); if (this.UI.hidden) { this.UI.hidden = false; this.UI.tbarEl.fadeIn({ duration: .2, stopFx: true, /*callback: function () { this.UI.hidden = false; },*/ scope: this }); if (this.count > 1) { this.UI.navLeft.fadeIn({duration: .2, stopFx: true}); this.UI.navRight.fadeIn({duration: .2, stopFx: true}); } } }), hideUI: function() {this.hideUITask.delay(1000, false, this);}, hideUITask: new Ext.util.DelayedTask(function() { this.showUITask.cancel(); if (!this.UI.hidden) { this.UI.hidden = true; this.UI.tbarEl.fadeOut({ duration: 1, stopFx: true, /*callback: function () { this.UI.hidden = true; }, */scope: this }); if (this.count > 1) { this.UI.navLeft.fadeOut({duration: 1, stopFx: true}); this.UI.navRight.fadeOut({duration: 1, stopFx: true}); } } }), setupKeys: function() { this.nav = new Ext.KeyNav(this.body, { 'left' : function() {this.previousItem();}, 'right' : function(){this.nextItem();}, 'space' : function(){this.nextItem();}, 'up': function() {}, 'down': function() {}, 'pageUp': function() {this.previousPage();}, 'pageDown': function () {this.nextPage();}, 'enter' : function(){this.download();}, 'esc': function() {this.close();}, scope : this }); }, collectItems: function(clickedItem) { var startIndex = 0; this.count = 0; FR.UI.gridPanel.store.each(function(item) { if (!item.data.isFolder && item.data.thumb && item.data.filetype != 'wvideo'){ this.items.add(this.count, item.data); if (clickedItem == item) { startIndex = this.count; } this.count++; } }, this); return startIndex; }, setItem: function(index, page) { this.hideComments(); if (index != this.currentIndex) { this.cancelZoom(); } this.currentIndex = index; this.currentItem = this.items.get(index); this.pageIndex = page || 0; this.currentPath = this.currentItem.path || FR.currentPath+'/'+this.currentItem.filename; this.fileSize = this.currentItem.filesize; this.UI.icon.update('<img src="images/fico/'+this.currentItem.icon+'" height="20" />'); this.currentItem.extension = FR.utils.getFileExtension(this.currentItem.filename); this.UI.filename.setText(this.currentItem.filename); if (this.count > 1) { this.UI.status.setText(FR.T('%1 of %2 items').replace('%1', this.currentIndex+1).replace('%2', this.count)); } else { this.UI.status.setText('&nbsp;'); } var pageInfo = '&nbsp;'; if (this.isMultiPage()) { if (this.pageIndex == 0) { pageInfo = FR.T('First page'); } else { pageInfo = FR.T('Page %1').replace('%1', this.pageIndex + 1); } } this.UI.pageInfo.setText(pageInfo); if (!this.zoomed) { this.getMaxSize(); } this.loadThumb(); }, nextItem: function() { var index = 0; if (this.currentIndex < this.count-1) { index = this.currentIndex+1; } this.setItem(index); }, previousItem: function() { var index = this.count-1; if (this.currentIndex > 0) { index = this.currentIndex-1; } this.setItem(index); }, nextPage: function() { if (!this.isMultiPage()) {return false;} this.setItem(this.currentIndex, this.pageIndex+1); }, previousPage: function() { if (!this.isMultiPage()) {return false;} if (this.pageIndex > 0) { this.setItem(this.currentIndex, this.pageIndex-1); } }, isCached: function(addNow) { var cacheId = this.maxW + ':' + this.maxH + ':' + this.pageIndex; if (!this.currentItem.cache) { this.currentItem.cache = new Ext.util.MixedCollection(); } else { if (this.currentItem.cache.get(cacheId)) { return true; } } if (addNow) { this.currentItem.cache.add(cacheId, {}); } }, isMultiPage: function() { return (['pdf', 'tif'].indexOf(this.currentItem.extension) != -1); }, loadThumb: function() { this.lastRequestedSize = { w: this.maxW, h: this.maxH }; var src = this.baseSrc+'?p='+encodeURIComponent(this.currentPath); src += '&noCache=1'; src += '&width='+this.maxW+'&height='+this.maxH; src += '&pageNo='+this.pageIndex; src += '&fsize='+this.fileSize; if (!this.isCached()) { if (this.currentItem.thumbURL) { //set thumb this.imgDOM.set({src: this.currentItem.thumbURL}); } else { this.imgDOM.setVisible(false); this.iconEl.set({src: 'images/fico/' + this.currentItem.icon}); this.iconEl.show(); this.iconEl.center(); } //load preview this.loaderEl.set({src: src}); return false; } this.imgDOM.set({src: src}); }, showMask: function() { this.mask = this.body.mask(); this.mask.addClass('darkMask'); this.mask.on('click', function() {this.close();}, this); }, hideMask: function() { this.body.unmask(); }, close: function() { this.hideComments(); this.cancelZoom(); this.hideUITask.cancel(); this.UI.tbarWrap.hide(); this.UI.tbarEl.hide(); this.UI.navLeftWrap.hide(); this.UI.navRightWrap.hide(); this.UI.navLeft.hide(); this.UI.navRight.hide(); this.loaderEl.settingBlankPixel = true; this.loaderEl.set({src: this.blankSrc}); this.imgDOM.settingBlankPixel = true; this.imgDOM.set({src: this.blankSrc}); this.iconEl.set({src: this.blankSrc}); this.nav.disable(); this.iconEl.hide(); this.imgDOM.setVisible(false); this.hideMask(); this.open = false; }, getMaxSize: function() { this.maxH = this.body.getHeight(); this.maxW = this.body.getWidth(); this.maxH = Math.round(this.maxH-10/100*this.maxH-30) * this.highDPIRatio; this.maxW = Math.round(this.maxW-10/100*this.maxW) * this.highDPIRatio; }, adjustImageSize: function() { //if (!this.lastSize) {this.alignImage();return false;} //if (this.lastSize.h != this.maxH) { var h = Math.round(this.maxH / this.highDPIRatio); var nSize = this.getNaturalSize(this.imgDOM.dom); if (nSize.height < h) { h = nSize.height; } this.imgDOM.setHeight(h); //} this.alignImage(); }, alignImage: function() { this.imgDOM.alignTo(this.body, 'c-c', [0, 10]); }, onWindowResize: function() { if (!this.open) {return false;} if (this.zoomed) { this.imgDOM.center(); return false; } this.lastSize = { h: this.maxH, w: this.maxW }; this.getMaxSize(); if (this.maxH > this.lastRequestedSize.h || this.maxW > this.lastRequestedSize.w) { var nSize = this.getNaturalSize(this.imgDOM.dom); if (nSize.height < this.lastRequestedSize.h) { } else { this.newSize = 'larger'; } } else { this.newSize = 'smaller'; } this.adjustImageSize(); if (this.newSize == 'larger') { this.loadThumb(); } }, download: function() { FR.actions.download([this.currentPath]); }, showComments: function() { if (!this.cPanel) { this.cPanel = new FR.components.commentsPanel(); this.cPanel.inputBox.on('focus', function() {this.nav.disable();}, this); this.cPanel.inputBox.on('blur', function() {this.nav.enable();}, this); this.cPanel.active = true; this.cWin = new Ext.Window({ title: FR.T('Comments'), closeAction: 'hide', hideBorders: true, width: 300, height: 330, layout: 'fit', items: this.cPanel }); } this.cWin.show(); this.cWin.alignTo(this.body, 'br-br', [-50, -10]); this.cPanel.setItem(this.currentPath); }, hideComments: function() { if (this.cWin) { this.cWin.hide(); } } }; Ext.EventManager.onWindowResize(function() {FR.UI.imagePreview.onWindowResize();});<file_sep><?php function GenerateRandomString($length = 64) { $characters = '0123456789abcdefABCDEF'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } function EncryptKey($decryptkey){ return strrev(bin2hex(base64_encode($decryptkey))); } function DecryptKey($encryptKey){ return base64_decode(hex2bin(strrev($encryptKey))); } function CreatePrivateKey(){ $privateKey = pack('H*', GenerateRandomString()); $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $key = $privateKey."|".$iv_size."|".$iv."|+"; $encryptKey = EncryptKey($key); return $encryptKey; } function CreatingHash($string){ // Reverse $encryptStep[0] = strrev($string); // Bin2Hex $encryptStep[1] = bin2hex($encryptStep[0]); // Base 64 Encode $encryptStep[2] = base64_encode($encryptStep[1]); // MD5 Encode $encryptStep[3] = md5($encryptStep[2]); // Hash512 $encryptStep[4] = hash('sha512', $encryptStep[3]); // Finish Here return $encryptFinish = $encryptStep[4]; } function CreatingSalt($string){ // Create Salt $makeSalt[0] = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CFB), MCRYPT_DEV_URANDOM); $makeSalt[1] = '$6$'.substr(str_shuffle("!@#$%^&*()./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345‌​6789".$makeSalt[0]), 0, 25); $makeSalt[2] = crypt($string,$makeSalt[1]); // Encrypt Salt $makeSalt[3] = bin2hex(strrev(base64_encode(strrev(base64_encode($makeSalt[2]))))); // Finish Here return $makeSaltFinish = $makeSalt[3]; } function ValidPassword($hashPassword,$salt){ return (password_verify($hashPassword,base64_decode(strrev(base64_decode(strrev(hex2bin($salt)))))))?true:false; } function encryptData($decrypted, $privateKey, $password) { // Build a 256-bit $key which is a SHA256 hash of $salt and $password. $key = hash('SHA256', $password . $privateKey, true); // Build $iv and $iv_base64. We use a block size of 128 bits (AES compliant) and CBC mode. (Note: ECB mode is inadequate as IV is not used.) srand(); $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND); if (strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != 22) return false; // Encrypt $decrypted and an MD5 of $decrypted using $key. MD5 is fine to use here because it's just to verify successful decryption. $encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $decrypted . md5($decrypted), MCRYPT_MODE_CBC, $iv)); // We're done! return $iv_base64 . $encrypted; } function decryptData($encrypted, $privateKey, $password ) { // Build a 256-bit $key which is a SHA256 hash of $salt and $password. $key = hash('SHA256', $password . $privateKey, true); // Retrieve $iv which is the first 22 characters plus ==, base64_decoded. $iv = base64_decode(substr($encrypted, 0, 22) . '=='); // Remove $iv from $encrypted. $encrypted = substr($encrypted, 22); // Decrypt the data. rtrim won't corrupt the data because the last 32 characters are the md5 hash; thus any \0 character has to be padding. $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, base64_decode($encrypted), MCRYPT_MODE_CBC, $iv), "\0\4"); // Retrieve $hash which is the last 32 characters of $decrypted. $hash = substr($decrypted, -32); // Remove the last 32 characters from $decrypted. $decrypted = substr($decrypted, 0, -32); // Integrity check. If this fails, either the data is corrupted, or the password/salt was incorrect. if (md5($decrypted) != $hash) return false; // Yay! return $decrypted; } ?><file_sep><?php $_privateKey = ""; ?><file_sep><?php /* Bing KML viewer */ class custom_bing_kml_viewer { var $online = true; function init() { $this->JSconfig = array( "title" => \FileRun\Lang::t("Bing Maps", 'Custom Actions: Bing Maps'), "iconCls" => 'fa fa-fw fa-cloud', 'icon' => 'images/icons/bing.png', "extensions" => array("xml", "kmz", "kml"), "popup" => true ); } function run() { $url = $this->weblinks->getOneTimeDownloadLink($this->data['filePath']); if (!$url) { echo "Failed to setup weblink"; exit(); } $proto = isSSL() ? "https" : "http"; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>View with Bing</title> <script type="text/javascript" src="<?php echo $proto?>://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.3"></script> <script type="text/javascript"> var map = null; function EventMapLoad() { var shapeLayer = new VEShapeLayer(); var shapeSpec = new VEShapeSourceSpecification(VEDataType.ImportXML,"<?php echo $url; ?>", shapeLayer); map.ImportShapeLayerData(shapeSpec); } function CreateMap() { map = new VEMap('myMap'); //Api key is not mandatory, use only if you want generate access report on your bing account //map.SetCredentials("Your API KEY"); map.onLoadMap = EventMapLoad; map.LoadMap(null, 3, VEMapStyle.Hybrid); } </script> </head> <body onload="CreateMap();"> <div id="myMap" style="position:absolute;width: 100%; height: 100%;"></div> </body> </html> <?php } }<file_sep><?php class custom_google_docs_viewer { var $online = true; function init() { $this->URL = "https://docs.google.com/viewer"; $this->JSconfig = array( "title" => \FileRun\Lang::t("Google Docs Viewer", 'Custom Actions: Google Docs Viewer'), 'icon' => 'images/icons/gdocs.png', "extensions" => array( "pdf", "ppt", "pptx", "doc", "docx", "xls", "xlsx", "dxf", "ps", "eps", "xps", "psd", "tif", "tiff", "bmp", "svg", "pages", "ai", "dxf", "ttf" ), "popup" => true, "requiredUserPerms" => array("download") ); } function run() { $url = $this->weblinks->getOneTimeDownloadLink($this->data['filePath']); if (!$url) { echo "Failed to setup weblink"; exit(); } \FileRun\Log::add(false, "preview", array( "relative_path" => $this->data['relativePath'], "full_path" => $this->data['filePath'], "method" => "Google Docs Viewer" )); ?> <html> <head> <title></title> <style> body { border: 0px; margin: 0px; padding: 0px; overflow:hidden; } </style> </head> <body> <iframe scrolling="no" width="100%" height="100%" border="0" src="<?php echo $this->URL?>?url=<?php echo urlencode($url)?>&embedded=true"> </iframe> </body> </html> <?php } }<file_sep><?php class custom_image_viewer { function init() { $this->localeSection = "Image Viewer"; $this->JSconfig = array( "title" => \FileRun\Lang::t("Image Viewer", $this->localeSection), 'iconCls' => 'fa fa-fw fa-picture-o', 'useWith' => array('nothing'), "popup" => true, "requiredUserPerms" => array("download") ); } function run() { global $config; \FileRun::checkPerms("download"); require(gluePath($this->path, "/display.php")); } }<file_sep><?php /* $thisPageJs = ""; $thisPageCss = ""; // Need function get all css // Need function get all js */ ?> <!-- Marketing Icons Section --> <file_sep><?php include_once realpath($_SERVER["DOCUMENT_ROOT"])."/setting/control.php"; ?> <?php ?> <file_sep><?php /* * Plugin for authenticating FileRun users against a LDAP directory * * */ class customAuth_ldap { var $error, $errorCode, $cid, $userRecord; function pluginDetails() { return array( 'name' => 'LDAP', 'description' => 'Authenticate users against LDAP.', 'fields' => array( array( 'name' => 'host', 'label' => 'Server hostname', 'default' => 'ldap.forumsys.com', 'required' => true ), array( 'name' => 'port', 'label' => 'Server port number', 'default' => 389 ), array( 'name' => 'bind_dn', 'label' => 'Bind DN', 'default' => 'cn=read-only-admin,dc=example,dc=com' ), array( 'name' => 'bind_password', 'label' => 'Bind password', 'default' => '<PASSWORD>' ), array( 'name' => 'user_dn', 'label' => 'User DN template', 'default' => 'uid={USERNAME},dc=example,dc=com', 'required' => true ), array( 'name' => 'search_dn', 'label' => 'Search DN', 'default' => 'dc=example,dc=com', 'required' => true ), array( 'name' => 'search_filter', 'label' => 'Search filter template', 'default' => '(&(uid={USERNAME})(objectClass=person))', 'required' => true ), array( 'name' => 'allow_iwa_sso', 'label' => 'Enable IWA SSO', 'default' => 'yes', 'required' => false ), array( 'name' => 'mapping_name', 'label' => 'First name field', 'default' => 'cn', 'required' => true ), array( 'name' => 'mapping_name2', 'label' => 'Last name field', 'default' => 'cn' ), array( 'name' => 'mapping_email', 'label' => 'E-mail field', 'default' => 'mail' ), array( 'name' => 'mapping_company', 'label' => 'Company name field', 'default' => '' ), array( 'name' => 'test_username', 'label' => 'Test username', 'default' => 'einstein' ), array( 'name' => '<PASSWORD>_password', 'label' => 'Test password', 'default' => '<PASSWORD>' ) ) ); } function pluginTest($opts) { $pluginInfo = self::pluginDetails(); //check required fields foreach($pluginInfo['fields'] as $field) { if ($field['required'] && !$opts['auth_plugin_ldap_'.$field['name']]) { return 'The field "'.$field['label'].'" needs to have a value.'; } } if (!function_exists('ldap_connect')) { return 'PHP is missing LDAP support! Make sure the LDAP PHP extension is enabled.'; } $cid = ldap_connect($opts['auth_plugin_ldap_host'], $opts['auth_plugin_ldap_port']); if (!$cid) { return 'Connection to the LDAP server failed! Make sure the hostname and the port number are correct.'; } ldap_set_option($cid, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($cid, LDAP_OPT_REFERRALS, 0); if ($opts['auth_plugin_ldap_bind_dn']) { $rs = @ldap_bind($cid, $opts['auth_plugin_ldap_bind_dn'], $opts['auth_plugin_ldap_bind_password']); if (!$rs) { return "Bind with bind DN failed: ".ldap_error($cid); } else { echo 'Bind with bind DN successful!'; echo '<br>'; } } else { $user_dn = str_replace('{USERNAME}', $opts['auth_plugin_ldap_test_username'], $opts['auth_plugin_ldap_user_dn']); $rs = @ldap_bind($cid, $user_dn, $opts['auth_plugin_ldap_test_password']); if (!$rs) { return "Bind with test account failed: ".ldap_error($cid); } else { echo 'Bind with test account successful!'; echo '<br>'; } } $filter = str_replace("{USERNAME}", $opts['auth_plugin_ldap_test_username'], $opts['auth_plugin_ldap_search_filter']); echo 'Searching with filter: '.$filter; echo '<br>'; $rs = @ldap_search($cid, $opts['auth_plugin_ldap_search_dn'], $filter); if (!$rs) { return "Failed to search for the LDAP record: ".ldap_error($cid); } $entry = ldap_first_entry($cid, $rs); if (!$entry) { return 'LDAP record not found. Verify the search filter.'; } if ($opts['auth_plugin_ldap_bind_dn']) { $user_dn = ldap_get_dn($cid, $entry); echo 'User DN retrieved: '.$user_dn; echo '<br>'; $rs = @ldap_bind($cid, $user_dn, $opts['auth_plugin_ldap_test_password']); if (!$rs) { return "Bind with test account failed: " . ldap_error($cid); } else { echo 'Bind with test account successful!'; echo '<br>'; } } echo 'Record found:'; $attr = ldap_get_attributes($cid, $entry); $values = array(); if (array($attr)) { echo '<div style="background-color:whitesmoke;margin:5px;border:1px solid silver">'; foreach ($attr as $k => $a) { if (!is_numeric($k) && $k != 'count') { $values[$k] = $a[0]; echo '<div style="margin-left:10px;">'.S::safeHTML($k).': '.S::safeHTML($a[0]).'</div>'; } } echo '</div>'; } echo 'Fields mapping:'; echo '<div style="background-color:whitesmoke;margin:5px;border:1px solid silver">'; echo '<div style="margin-left:10px;">Name ('.$opts['auth_plugin_ldap_mapping_name'].'): '.S::safeHTML($values[$opts['auth_plugin_ldap_mapping_name']]).'</div>'; echo '<div style="margin-left:10px;">Last name ('.$opts['auth_plugin_ldap_mapping_name2'].'): '.S::safeHTML($values[$opts['auth_plugin_ldap_mapping_name2']]).'</div>'; echo '<div style="margin-left:10px;">E-mail ('.$opts['auth_plugin_ldap_mapping_email'].'): '.S::safeHTML($values[$opts['auth_plugin_ldap_mapping_email']]).'</div>'; if ($opts['auth_plugin_ldap_mapping_company']) { echo '<div style="margin-left:10px;">Company (' . $opts['auth_plugin_ldap_mapping_company'] . '): ' . S::safeHTML($values[$opts['auth_plugin_ldap_mapping_company']]) . '</div>'; } echo '</div>'; return 'The test was successful'; } function getSetting($fieldName) { global $settings; $keyName = 'auth_plugin_ldap_'.$fieldName; return $settings->$keyName; } function ssoEnabled() { if ($this->getSetting('allow_iwa_sso') != 'yes') { $this->error = 'IWA SSO needs to be set to "yes" in the authentication plugin\'s settings'; return false; } if (!$this->getSetting('bind_dn')) { $this->error = 'Plugins requires a bind_dn for SSO to work'; return false; } return true; } function singleSignOn() { if (!$this->ssoEnabled()) {return false;} $rs = $this->ldapConnect(); if (!$rs) {return false;} $username = S::fromHTML($_SERVER['AUTH_USER']); $backSlashPos = strpos($username, '\\'); if ($backSlashPos !== false) { $username = substr($username, $backSlashPos+1); } if (!$username) {return false;} return $username; } function ldapConnect($username = false, $password = false) { if ($this->cid) {return true;} $this->cid = ldap_connect($this->getSetting('host'), $this->getSetting('port')); if (!$this->cid) { $this->errorCode = 'PLUGIN_CONFIG'; $this->error = 'Connection to the LDAP server failed!'; return false; } ldap_set_option($this->cid, LDAP_OPT_PROTOCOL_VERSION, 3); ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 0); if ($this->getSetting('bind_dn')) { $rs = @ldap_bind($this->cid, $this->getSetting('bind_dn'), $this->getSetting('bind_password')); if (!$rs) { //"Bind failed: ".ldap_error($cid); $this->errorCode = 'PLUGIN_CONFIG'; $this->error = 'Authentication with the bind DN failed'; return false; } } else { $user_bind_dn = str_replace('{USERNAME}', $username, $this->getSetting('user_dn')); $rs = @ldap_bind($this->cid, $user_bind_dn, $password); if (!$rs) { $this->errorCode = 'WRONG_PASS'; $this->error = "Invalid password."; return false; } } return true; } function getUserInfo($username, $password = false) { $this->userRecord = $this->getRemoteUserRecord($username); if (!$this->userRecord) { $this->errorCode = 'USERNAME_NOT_FOUND';//allows fall back to local authentication $this->error = 'The username was not found in the remote database'; return false; } $rs = $this->formatUserDetails($this->userRecord); if (!$rs) {return false;} $userData = $rs['userData']; $userPerms = $rs['userPerms']; $userGroups = $rs['userGroups']; if ($password) {//not present for SSO $userData['password'] = $password; } return array( 'userData' => $userData, 'userPerms' => $userPerms, 'userGroups' => $userGroups ); } function formatUserDetails($remoteRecord) { $remoteRecord = ldap_get_attributes($this->cid, $remoteRecord); $values = array(); if (array($remoteRecord)) { foreach ($remoteRecord as $k => $a) { if (!is_numeric($k) && $k != 'count') { $values[$k] = $a[0]; } } } $mapName = $this->getSetting('mapping_name'); $mapName2 = $this->getSetting('mapping_name2'); if ($mapName == $mapName2) { $name = $values[$mapName]; $parts = explode(" ", $name); $name = array_pop($parts); $name2 = implode(" ", $parts); } else { $name = $values[$mapName]; $name2 = $values[$mapName2]; } $userData = array( 'name' => $name, 'name2' => $name2, 'email' => $values[$this->getSetting('mapping_email')] ); if ($values['uid']) { $userData['username'] = $values['uid']; } if ($values[$this->getSetting('mapping_company')]) { $userData['company'] = $values[$this->getSetting('mapping_company')]; } $userPerms = array(); if ($values['homeDirectory']) { $userPerms['homefolder'] = str_replace('\\', '/', $values['homeDirectory']); } if (!$userData['name']) { $this->error = 'Missing name for the user record'; return false; } return array( 'userData' => $userData, 'userPerms' => $userPerms, 'userGroups' => array('LDAP') ); } function getRemoteUserRecord($username) { $filter = str_replace("{USERNAME}", $username, $this->getSetting('search_filter')); $rs = @ldap_search($this->cid, $this->getSetting('search_dn'), $filter); if (!$rs) { $this->errorCode = 'PLUGIN_CONFIG'; $this->error = "Failed to search for the LDAP record: ".ldap_error($this->cid); return false; } return ldap_first_entry($this->cid, $rs); } function authenticate($username, $password) { $rs = $this->ldapConnect($username, $password); if (!$rs) {return false;} $this->userRecord = $this->getRemoteUserRecord($username); if (!$this->userRecord) { $this->errorCode = 'USERNAME_NOT_FOUND';//allows fall back to local authentication $this->error = 'The provided username is not valid'; return false; } if ($this->getSetting('bind_dn')) { //binding was done with predefined credentials //check user provided credentials $user_dn = ldap_get_dn($this->cid, $this->userRecord); if (!$user_dn) { $this->errorCode = 'PLUGIN_CONFIG'; $this->error = 'Failed to retrieve user DN for the found record!'; return false; } $rs = @ldap_bind($this->cid, $user_dn, $password); if (!$rs) { $this->errorCode = 'WRONG_PASS'; $this->error = "Invalid password."; return false; } } $rs = $this->getUserInfo($username, $password); return $rs; } function listAllUsers() { $rs = $this->ldapConnect(); if (!$rs) {return false;} $filter = '(objectClass=person)'; $dn = $this->getSetting('search_dn'); $rs = @ldap_search($this->cid, $dn, $filter); if (!$rs) { $this->error = "Failed to retrieve LDAP records: ".ldap_error($this->cid); return false; } $rs = ldap_get_entries($this->cid, $rs); if (!is_array($rs)) {return false;} array_shift($rs); $list = array(); foreach ($rs as $record) { $list[] = $this->formatUserDetails($record); } return $list; } function listRemovedUsers() { $rs = $this->ldapConnect(); if (!$rs) {return false;} $filter = '(objectClass=person)'; $dn = "ou=removed,dc=example,dc=com";//you need to configure this $rs = @ldap_search($this->cid, $dn, $filter); if (!$rs) { $this->error = "Failed to retrieve LDAP records: ".ldap_error($this->cid); return false; } $rs = ldap_get_entries($this->cid, $rs); if (!is_array($rs)) {return false;} array_shift($rs); $list = array(); foreach ($rs as $record) { $list[] = $this->formatUserDetails($record); } return $list; } } <file_sep>FR.components.detailsPanel = Ext.extend(Ext.Panel, { metadataCache: new Ext.util.MixedCollection(), readMe: false, initComponent: function() { this.metaLoaderTask = new Ext.util.DelayedTask(function(){this.loadMeta()}, this); this.folderIcon = '<i class="fa fa-folder" style="font-size: 35px;color:#8F8F8F"></i>'; Ext.apply(this, { title: '<i class="fa fa-fw fa-2x fa-info" style="font-size:2.1em"></i>', cls: 'fr-details-panel', autoScroll: true, html: '<div id="fr-details-previewbox" style="visibility:hidden">' + '<div class="title">' + '<div style="display:table-row">' + '<div id="fr-details-icon"></div>' + '<div id="fr-details-filename"></div>' + '</div>' + '</div>' + '<div style="clear:both;"></div>' + '<div class="thumb" id="fr-details-thumb" style="display:none"></div>' + '</div>'+ '<div id="fr-details-info" style="display:none"></div>'+ '<div id="fr-details-readme" style="display:none"></div>'+ '<div id="fr-details-metadata" style="display:none"></div>', listeners: { 'afterrender': function() { this.previewBox = Ext.get('fr-details-previewbox'); this.fileNameEl = Ext.get('fr-details-filename'); this.iconEl = Ext.get('fr-details-icon'); this.thumbContainer = Ext.get('fr-details-thumb'); this.thumbContainer.setVisibilityMode(Ext.Element.DISPLAY); this.thumbContainer.on('click', function(){ if (this.item.filetype == 'img') { FR.UI.imagePreview.init(this.item); } else { FR.utils.showPreview(this.item); } }, this); this.infoEl = Ext.get('fr-details-info').enableDisplayMode(); this.readMeEl = Ext.get('fr-details-readme').enableDisplayMode(); this.metadataEl = Ext.get('fr-details-metadata').enableDisplayMode(); this.body.first().on('contextmenu', function() { FR.UI.gridPanel.showContextMenu(); }); }, 'activate': function(p){ p.active = true; this.gridSelChange(); }, 'deactivate': function(p) {p.active = false;}, 'resize': function() {if (this.active && this.item) {this.updateQuickView();}}, scope: this } }); FR.components.detailsPanel.superclass.initComponent.apply(this, arguments); }, onRender: function() { FR.components.detailsPanel.superclass.onRender.apply(this, arguments); }, setReadMe: function(t) {this.readMe = t;}, gridSelChange: function() { if (!this.active) {return false;} if (!FR.UI.tree.currentSelectedNode) {return false;} this.countSel = FR.UI.infoPanel.countSel; this.countAll = FR.UI.infoPanel.countAll; this.item = FR.UI.infoPanel.item; if (this.item) { this.itemPath = (this.item.data.path || FR.currentPath+'/'+this.item.data.filename); } this.updateQuickView(); }, reset: function() { this.metaLoaderTask.cancel(); this.readMeEl.hide().update(''); this.metadataEl.update(''); this.infoEl.update(''); }, setItemTitle: function(itemTitle) { this.fileNameEl.update(itemTitle); this.previewBox.show(); }, setIcon: function(icon) { this.iconEl.update(icon); }, updateQuickView: function() { if (!this.active) {return false;} this.reset(); if (this.countSel == 1) { this.metadataEl.show(); this.loadQuickView(); } else { this.thumbContainer.hide(); var iconCls = FR.UI.tree.currentSelectedNode.attributes.iconCls || 'fa-folder'; this.setIcon('<i class="fa '+iconCls+'" style="font-size: 35px;color:#8F8F8F"></i>'); this.setItemTitle(FR.UI.tree.currentSelectedNode.text); var size = ''; if (this.countAll == 0) { var statusText = FR.T('There are no files in this folder.'); } else { var sel; if (this.countSel == 0) { sel = FR.UI.gridPanel.store.data.items; if (this.countAll == 1) { statusText = FR.T('One item'); } else if (this.countAll > 0) { statusText = FR.T('%1 items').replace('%1', this.countAll); } } else { sel = FR.UI.gridPanel.selModel.getSelections(); statusText = FR.T('%1 items selected').replace('%1', this.countSel); } size = 0; Ext.each(sel, function (item) { if (item.data.isFolder) { size = false; return false; } size += parseInt(item.data.filesize); }); if (size > 0) { size = Ext.util.Format.fileSize(size); } else { size = ''; } } var info = '<div class="status">' + '<div class="text">'+statusText+'</div>' + '<div class="size">'+size+'</div>' + '<div style="clear:both"></div><div>'; this.infoEl.update(info).show(); if (this.readMe) { this.readMeEl.update(this.readMe).show(); } } }, loadQuickView: function() { var title = this.item.data.isFolder ? this.item.data.filename : FR.utils.dimExt(this.item.data.filename); if (this.item.data.isFolder) { this.setIcon(this.folderIcon); this.setItemTitle(title); } else { var iconSrc = 'images/fico/' + this.item.data.icon; this.setIcon('<img src="'+iconSrc+'" height="30" align="left" style="margin-right:5px;" />'); this.setItemTitle(title); } this.thumbContainer.hide(); this.thumbContainer.update(''); if (this.item.data.thumb) { var imageSrc; if (this.item.data.thumbImg) { imageSrc = this.item.data.thumbImg.dom.src; } else { imageSrc = FR.UI.getThumbURL(this.item.data); } this.thumbImg = Ext.get(Ext.DomHelper.createDom({tag: 'img', cls:'detailsThumb'})); this.thumbImg.on('load', function() { if (this.thumbImg.dom) { var naturalWidth = this.thumbImg.dom.width; var maxWidth = FR.UI.infoPanel.getWidth(); var w = maxWidth-45; if (naturalWidth < w) {w = naturalWidth;} this.thumbImg.set({width: w, height: 'auto'}); this.thumbContainer.appendChild(this.thumbImg); this.thumbContainer.show(); } }, this); this.thumbImg.set({src: imageSrc}); } var info = ''; if (['starred', 'search', 'webLinked', 'photos'].indexOf(FR.currentSection) !== -1) { var pInfo = FR.utils.pathInfo(this.item.data.path); info += '<tr>' + '<td class="fieldName">'+FR.T('Location')+'</td>' + '<td class="fieldValue"><a href="javascript:;" onclick="FR.utils.locateItem(\''+pInfo.dirname+'\', \''+pInfo.basename+'\')">'+FR.utils.humanFilePath(pInfo.dirname)+'</a></td>' + '</tr>'; } if (FR.currentSection == 'trash') { info += '<tr>' + '<td class="fieldName">'+FR.T('Deleted from')+'</td>' + '<td class="fieldValue">'+this.item.data.trash_deleted_from+'</td>' + '</tr>'; } if (!this.item.data.isFolder) { info += '<tr>' + '<td class="fieldName">' + FR.T('Size') + '</td>' + '<td class="fieldValue" title="' + Ext.util.Format.number(this.item.data.filesize, '0,000') + ' ' + FR.T('bytes') + '">' + this.item.data.nice_filesize + '</td>' + '</tr>'; } info += '<tr>' + '<td class="fieldName">'+FR.T('Type')+'</td>' + '<td class="fieldValue">'+this.item.data.type+'</td>' + '</tr>'; if (!this.item.data.isFolder) { if ((this.item.data.modified && this.item.data.created) && (this.item.data.modified.getTime() != this.item.data.created.getTime())) { info += '<tr>' + '<td class="fieldName">' + FR.T('Modified') + '</td>' + '<td class="fieldValue" ext:qtip="'+this.item.data.modified+'">' + (Settings.grid_short_date ? this.item.data.modifiedHuman : Ext.util.Format.date(this.item.data.modified, FR.T('Date Format: Files'))) + '</td>' + '</tr>'; } } if (this.item.data.created) { info += '<tr>' + '<td class="fieldName">' + FR.T('Created') + '</td>' + '<td class="fieldValue" ext:qtip="'+this.item.data.created+'">' + (Settings.grid_short_date ? this.item.data.createdHuman : Ext.util.Format.date(this.item.data.created, FR.T('Date Format: Files'))) + '</td>' + '</tr>'; } info = '<table cellspacing="1" width="100%">' + info + '</table>'; this.infoEl.update(info).show(); if (!this.item.data.isFolder) { if (this.metadataCache.containsKey(this.itemPath)) { this.metadataEl.update(this.metadataCache.get(this.itemPath)); } else { this.metaLoaderTask.delay(500); } } }, loadMeta: function() { if (!User.perms.metadata) {return false;} if (!this.item) {return false;} this.metadataEl.update('<span style="color:silver;font-size:9px;margin:5px;">'+FR.T('Loading metadata...')+'</span>'); Ext.Ajax.request({ url: FR.baseURL+'/?module=metadata&page=quick_view', params: {path: this.itemPath}, callback: function(opts, succ, req) { if (req.responseText.length == 0) {return false;} if (!this.metadataCache.containsKey(this.itemPath)) { this.metadataCache.add(this.itemPath, req.responseText); } else { this.metadataCache.replace(this.itemPath, req.responseText); } this.metadataEl.update(req.responseText); }, scope: this }); }, editMeta: function() { FR.actions.openMetadata({title: this.item.data.filename, path: this.itemPath}); } });<file_sep><?php require_once realpath('.')."/page/index/indexContent.php"; ?><file_sep><?php $thisPageName = "This is new page"; $thisPageMeta = ""; $thisPageHeading = "New page"; $thisPageSubHeading = ""; $thisPageUpperContent = $_SERVER['DOCUMENT_ROOT']."/page/index/view/newpageUpperView.php"; $thisPageDownerContent = ""; $thisPageCSS = $_SERVER['DOCUMENT_ROOT']."/page/index/view/css/cssNewpage.php"; $thisPageJS = $_SERVER['DOCUMENT_ROOT']."/page/index/view/js/jsNewpage.php"; $thisPageContent = $_SERVER['DOCUMENT_ROOT']."/page/index/view/newpageView.php"; $thisPageController = $_SERVER['DOCUMENT_ROOT']."/page/index/controller/controllerNewpage.php"; if (!empty($thisPageController)){require_once $thisPageController;} require_once $_SERVER['DOCUMENT_ROOT']."/page/_layout/_layout.php"; //echo realpath('.'); ?><file_sep><?php class custom_zamzar { var $online = true; var $urlBase = 'https://sandbox.zamzar.com/v1'; static $localeSection = 'Custom Actions: Zamzar'; function init() { $this->settings = array( array( 'key' => 'APIKey', 'title' => self::t('API key'), 'comment' => \FileRun\Lang::t('Get it from %1', 'Admin', array('<a href="https://developers.zamzar.com" target="_blank">https://developers.zamzar.com</a>')) ) ); $this->JSconfig = array( 'nonTouch' => true, "title" => self::t("Zamzar"), 'icon' => 'images/icons/zamzar.png', "popup" => true, 'width' => 580, 'height' => 400, "requiredUserPerms" => array("download", "upload") ); } function isDisabled() { return (strlen(self::getSetting('APIKey')) == 0); } static function getSetting($k) { global $settings; $key = 'plugins_zamzar_'.$k; return $settings->{$key}; } static function t($text, $vars = false) { return \FileRun\Lang::t($text, self::$localeSection, $vars); } function run() { global $fm; \FileRun::checkPerms("download"); $ext = $fm->getExtension($this->data['fileName']); $url = $this->urlBase.'/formats/'.S::forURL($ext); $http = new \GuzzleHttp\Client(); try { $response = $http->request('GET', $url, [ 'auth' => [self::getSetting('APIKey'), ''] ]); } catch (\GuzzleHttp\Exception\ConnectException $e) { jsonFeedback(false, 'Network connection error: '.$e->getMessage()); } catch (\GuzzleHttp\Exception\ClientException $e) { if ($e->getResponse()->getStatusCode() == 404) { echo "Zamzar doesn't seem to provide any conversion option for the ".mb_strtoupper($ext)." file type."; exit(); } else { echo 'Error: '.$e->getResponse()->getStatusCode(); } } catch (\GuzzleHttp\Exception\ServerException $e) { echo 'Server error: '.$e->getResponse()->getStatusCode(); exit(); } catch (RuntimeException $e) { echo 'Error: '.$e->getMessage(); exit(); } $rs = $response->getBody()->getContents(); if (!$rs) { jsonFeedback(false, 'Error checking status: empty server response!'); } $rs = json_decode($rs, true); require($this->path."/display.php"); } function requestConversion() { $url = $this->urlBase.'/jobs'; $http = new \GuzzleHttp\Client(); try { $response = $http->request('POST', $url, [ 'auth' => [self::getSetting('APIKey'), ''], 'multipart' => [ [ 'name' => 'target_format', 'contents' => S::fromHTML($_POST['format']) ], [ 'name' => 'source_file', 'contents' => fopen($this->data['filePath'], 'r') ] ] ]); } catch (\GuzzleHttp\Exception\ConnectException $e) { jsonFeedback(false, 'Network connection error: '.$e->getMessage()); } catch (\GuzzleHttp\Exception\ClientException $e) { $rs = json_decode($e->getResponse()->getBody()->getContents(), true); jsonFeedback(false, 'Server error: '. $rs['errors'][0]['message']); } catch (\GuzzleHttp\Exception\ServerException $e) { jsonFeedback(false, 'Server error: '.$e->getResponse()->getStatusCode()); } catch (RuntimeException $e) { jsonFeedback(false, 'Error: '.$e->getMessage()); } $rs = $response->getBody()->getContents(); if (!$rs) { jsonFeedback(false, 'Error requesting conversion: empty server response!'); } $rs = json_decode($rs, true); jsonOutput(array( 'success' => true, 'msg' => 'Zamzar: '. $rs['status'], 'jobId' => $rs['id'] )); } function getStatus() { global $fm; $url = $this->urlBase.'/jobs/'.S::forURL(S::fromHTML($_POST['jobId'])); $http = new \GuzzleHttp\Client(); try { $response = $http->request('GET', $url, [ 'auth' => [self::getSetting('APIKey'), ''] ]); } catch (\GuzzleHttp\Exception\ConnectException $e) { jsonFeedback(false, 'Network connection error: '.$e->getMessage()); } catch (\GuzzleHttp\Exception\ClientException $e) { $rs = json_decode($e->getResponse()->getBody()->getContents(), true); jsonOutput(array( 'success' => false, 'msg' => 'Zamzar status: '.$rs['status'], 'status' => $rs['status'] )); } catch (\GuzzleHttp\Exception\ServerException $e) { echo 'Server error: '.$e->getResponse()->getStatusCode(); exit(); } catch (RuntimeException $e) { echo 'Error: '.$e->getMessage(); exit(); } $rs = $response->getBody()->getContents(); if (!$rs) { jsonFeedback(false, 'Error checking status: empty server response!'); } $rs = json_decode($rs, true); $rs['output']['size'] = $fm->formatFileSize($rs['output']['size']); jsonOutput(array( 'success' => true, 'msg' => 'Zamzar: '.$rs['status'], 'status' => $rs['status'], 'fileId' => $rs['target_files'][0]['id'] )); } function downloadConverted() { global $myfiles, $fm; $tempFilePath = $this->data['filePath'].'.zamzar.tmp'; $toFile = fopen($tempFilePath, "wb") or die("Failed to create temporary file"); $http = new \GuzzleHttp\Client(); $local = \GuzzleHttp\Psr7\stream_for($toFile); $newName = $fm->replaceExtension($this->data['fileName'], S::fromHTML($_POST['format'])); $url = $this->urlBase.'/files/'.S::forURL(S::fromHTML($_POST['fileId'])).'/content'; try { $response = $http->request('GET', $url, [ 'auth' => [self::getSetting('APIKey'), ''], 'save_to' => $local ]); } catch (\GuzzleHttp\Exception\ConnectException $e) { jsonFeedback(false, 'Network connection error: '.$e->getMessage()); } catch (\GuzzleHttp\Exception\ClientException $e) { $rs = json_decode($e->getResponse()->getBody()->getContents(), true); jsonOutput(array( 'success' => false, 'msg' => 'Zamzar status: '.$rs['status'], 'status' => $rs['status'] )); } catch (\GuzzleHttp\Exception\ServerException $e) { jsonFeedback(false, 'Server error: '.$e->getResponse()->getStatusCode()); } catch (RuntimeException $e) { jsonFeedback(false, 'Error: '.$e->getMessage()); } if ($response->getStatusCode() == 200) { fclose($toFile); $rs = $myfiles->newFile($fm->dirname($this->data['relativePath']), $newName, $tempFilePath, false, true); if (!$rs) { jsonFeedback(false, 'Failed to write file data.'); } jsonOutput(array( 'success' => true, 'newFileName' => $newName )); } } }<file_sep><?php function consoleData($data) { echo (is_array($data)?"<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>":"<script>console.log( 'Debug Objects: " . $data . "' );</script>"); } function generateRandomString($length = 64) { $characters = '0123456789abcdefABCDEF'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } function encryptSQLString($hostname, $username, $password, $database){ try{ $string = $hostname."|".$username."|".$password."|".$database."|+"; // Create Private Key $privateKey = pack('H*', generateRandomString()); $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); $encryptKey = strrev(bin2hex(base64_encode($privateKey."|".$iv_size."|+"))); // Insert to privatekey $fileOpen = fopen("./privatekey.php","w"); (fwrite($fileOpen,'<?php $_privateKey = "'.$encryptKey.'";?>'))?consoleData("Create Private Key Success"):consoleData("Create Private Key Fail"); fclose($fileOpen); $ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $privateKey,$string, MCRYPT_MODE_CBC, $iv); $ciphertext = $iv . $ciphertext; $ciphertext_base64 = base64_encode($ciphertext); $fileOpen = fopen("../trigger/sqlstore.php","w"); (fwrite($fileOpen,'<?php $_sqlEncryptString = "'.$ciphertext_base64.'";?>'))?consoleData("Create Encrypt SQL String Success"):consoleData("Create Encrypt SQL String Fail"); fclose($fileOpen); consoleData("SQL String has been encrypted: ".$ciphertext_base64); }catch (Exception $e){ consoleData("Error when encrypt SQL String: ".$e->getMessage()); } return ; } encryptSQLString($_POST['hostname'],$_POST['username'],$_POST['password'],$_POST['database']); header("Location: http://".$_SERVER['SERVER_NAME']."/"); ?><file_sep><?php class custom_alternate_download { static $localeSection = "Custom Actions: Alternate Download"; function init() { $this->settings = array( array( 'key' => 'config', 'title' => self::t('Configuration JSON'), 'large' => true, 'comment' => self::t('See <a href="%1" target="_blank">this page</a> for more information.', array('http://docs.filerun.com/alternate_downloads')) ) ); global $config; $postURL = $config['url']['root'].'/?module=custom_actions&action=alternate_download&method=run'; $this->JSconfig = array( "title" => self::t("Alternate Download"), 'iconCls' => 'fa fa-fw fa-download', 'useWith' => array( 'img', 'wvideo', 'mp3' ), "fn" => "FR.UI.backgroundPost(false, '".\S::safeJS($postURL)."')", "requiredUserPerms" => array("download") ); } function isDisabled() { return (strlen(self::getSetting('config')) == 0); } static function getSetting($k) { global $settings; $key = 'plugins_alternate_download_'.$k; return $settings->{$key}; } function run() { global $fm; \FileRun::checkPerms("download"); $cfg = self::getSetting('config'); $this->config = json_decode($cfg, true); if (!$this->config) { $this->reportError('Failed to decode JSON config!'); } if (!is_array($this->config['paths'])) { $this->reportError('The plugin is configured with an invalid JSON set!'); } $parentPath = $fm->dirname($this->data['filePath']); $newParentPath = false; $newExt = false; foreach($this->config['paths'] as $path) { if ($fm->inPath($parentPath, $path['normal'])) { $newParentPath = $path['alternate']; $newExt = $path['extension']; $subPath = substr($parentPath, strlen($path['normal'])); continue; } } if (!$newParentPath) { $this->reportNotFound(); } if ($newExt) { $fileName = $fm->replaceExtension($this->data['fileName'], $newExt); } else { $fileName = $this->data['fileName']; } $newPath = gluePath($newParentPath, $subPath, $fileName); if (!is_file($newPath)) { $this->reportNotFound(); } $fileSize = $fm->getFileSize($newPath); \FileRun\Utils\Downloads::sendHTTPFile($newPath); $bytesSentToBrowser = \FileRun\Utils\Downloads::$bytesSentToBrowser; $logData = array( "relative_path" => $this->data['relativePath'], "full_path" => $this->data['filePath'], "actual_path" => $newPath, "file_size" => $fileSize, "interface" => "alternate_download", 'original_path' => $this->data['filePath'], "bytes_sent" => $bytesSentToBrowser ); \FileRun\Log::add(false, "download", $logData); } static function t($text, $vars = false) { return \FileRun\Lang::t($text, self::$localeSection, $vars); } function reportNotFound() { return $this->reportError('No alternate download found for the selected file.'); } function reportError($msg) { echo '<script>window.parent.FR.UI.feedback(\''.self::t($msg).'\');</script>'; exit(); } }<file_sep><?php class custom_code_editor { function init() { $this->localeSection = "Custom Actions: Text Editor"; $this->JSconfig = array( "title" => \FileRun\Lang::t("Text Editor", $this->localeSection), 'iconCls' => 'fa fa-fw fa-file-text-o', 'useWith' => array('txt', 'noext'), "popup" => true, "createNew" => array( "title" => \FileRun\Lang::t("Text File", $this->localeSection), "options" => array( array( 'fileName' => \FileRun\Lang::t('New Text File.txt', $this->localeSection), 'title' => \FileRun\Lang::t('Plain Text', $this->localeSection), 'iconCls' => 'fa fa-fw fa-file-text-o', ), array( 'fileName' => 'index.html', 'title' => \FileRun\Lang::t('HTML', $this->localeSection), 'iconCls' => 'fa fa-fw fa-file-code-o', ), array( 'fileName' => 'script.js', 'title' => \FileRun\Lang::t('JavaScript', $this->localeSection), 'iconCls' => 'fa fa-fw fa-file-code-o', ), array( 'fileName' => 'style.css', 'title' => \FileRun\Lang::t('CSS', $this->localeSection), 'iconCls' => 'fa fa-fw fa-file-code-o', ), array( 'fileName' => 'index.php', 'title' => \FileRun\Lang::t('PHP', $this->localeSection), 'iconCls' => 'fa fa-fw fa-file-code-o', ), array( 'fileName' => 'readme.md', 'title' => \FileRun\Lang::t('Markdown', $this->localeSection), 'iconCls' => 'fa fa-fw fa-file-code-o', ), array( 'fileName' => '', 'title' => \FileRun\Lang::t('Other..', $this->localeSection), 'iconCls' => 'fa fa-fw fa-file-text-o', ) ) ), "requiredUserPerms" => array("download", "upload") ); } function run() { \FileRun::checkPerms("download"); $this->data['fileContents'] = file_get_contents(S::forFS($this->data['filePath'])); $enc = mb_list_encodings(); if ($_REQUEST['charset'] && in_array($_REQUEST['charset'], $enc)) { $this->data['fileContents'] = S::convert2UTF8($this->data['fileContents'], $_REQUEST['charset']); } require($this->path."/display.php"); \FileRun\Log::add(false, "preview", array( "relative_path" => $this->data['relativePath'], "full_path" => $this->data['filePath'], "method" => "Code Editor" )); } function saveChanges() { global $myfiles, $fm; \FileRun::checkPerms("upload"); $textContents = S::fromHTML($_POST['textContents']); $charset = S::fromHTML($_POST['charset']); if ($charset != 'UTF-8') { $textContents = S::convertEncoding($textContents, 'UTF-8', $charset); } $rs = $myfiles->newFile($fm->dirname($this->data['relativePath']), $this->data['fileName'], false, $textContents); if ($rs) { jsonOutput(array("rs" => true, "filename" => $this->data['fileName'], "msg" => \FileRun\Lang::t("File successfully saved", $this->localeSection))); } else { jsonOutput(array("rs" => false, "msg" => $myfiles->error['msg'])); } } function createBlankFile() { global $myfiles, $fm; \FileRun::checkPerms("upload"); if (strlen($this->data['fileName']) == 0) { jsonOutput(array("rs" => false, "msg" => \FileRun\Lang::t('Please type a file name', $this->localeSection))); } else { if (is_file($this->data['filePath'])) { jsonOutput(array("rs" => false, "msg" => \FileRun\Lang::t('A file with that name already exists', $this->localeSection))); } $rs = $myfiles->newFile($fm->dirname($this->data['relativePath']), $this->data['fileName'], false, ""); if ($rs) { jsonOutput(array("rs" => true, 'path' => $this->data['relativePath'], "filename" => $this->data['fileName'], "msg" => \FileRun\Lang::t("File successfully created", $this->localeSection))); } else { jsonOutput(array("rs" => false, "msg" => $myfiles->error['msg'])); } } } }<file_sep><?php class custom_open_in_browser { function init() { $this->JSconfig = array( "title" => \FileRun\Lang::t('Open in browser', 'Custom Actions'), 'iconCls' => 'fa fa-fw fa-eye', 'useWith' => array('nothing'), "requiredUserPerms" => array("download") ); } function run() { \FileRun::checkPerms("download"); $ext = \FM::getExtension($this->data['fileName']); if ($ext == 'pdf') { $browserIsiOS = preg_match("/iPhone|Android|iPad|iPod|webOS/", $_SERVER['HTTP_USER_AGENT']); $browserIsChrome = (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'chrome') !== false); $browserIsFirefox = (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'firefox') !== false); $browserIsIE8OrLower = preg_match('/(?i)msie [2-8]/',$_SERVER['HTTP_USER_AGENT']); if (!$browserIsChrome && !$browserIsFirefox && !$browserIsIE8OrLower && !$browserIsiOS) { $url = '?module=custom_actions&action=pdfjs'; $url .= "&path=".S::forURL(S::forHTML($this->data['relativePath'])); siteRedirect($url); } } \FileRun\Utils\Downloads::sendFileToBrowser($this->data['filePath']); \FileRun\Log::add(false, "preview", array( "relative_path" => $this->data['relativePath'], "full_path" => $this->data['filePath'], "method" => "Open in browser" )); } }<file_sep><?php require_once $_SERVER['DOCUMENT_ROOT']."/page/user/register/registerContent.php"; ?><file_sep><?php include_once realpath($_SERVER["DOCUMENT_ROOT"])."/setting/control.php"; ?> <script> // Need to be include function SetRegisterDialogToLoading(registerDialog){ registerDialog.setType(BootstrapDialog.TYPE_PRIMARY); registerDialog.setMessage('Please wait ...'); registerDialog.setTitle('PROCESSING'); return; } function SetRegisterDialogToError(registerDialog, message){ registerDialog.setType(BootstrapDialog.TYPE_DANGER); registerDialog.setMessage(message); registerDialog.setTitle('ERROR'); return; } function OpenRegisterDialog(registerDialog){ registerDialog.open(); return; } function SetDialogInGeneral(registerDialog, message, title, type){ registerDialog.setType('type-'+type); registerDialog.setMessage(message); registerDialog.setTitle(title); return; } </script> <script> // Initial Dialog var registerDialog = new BootstrapDialog(); SetRegisterDialogToLoading(registerDialog); OpenRegisterDialog(registerDialog); </script> <?php function SetRegisterDialogToError($message){ echo "<script>SetRegisterDialogToError(registerDialog, '".$message."');</script>"; } function SetDialogInGeneral($message, $title, $type){ echo "<script>SetDialogInGeneral(registerDialog, '".$message."', '".$title."', '".$type."')</script>"; } ?> <file_sep><?php global $fm, $settings; $getID3 = new getID3; $fInfo = $getID3->analyze($this->data['filePath']); $path = str_replace('&', '%26', $this->data['relativePath']); $URL = $config['url']['root']."/"; $URL .= S::forURL("?"); $URL .= "module=custom_actions"; $URL .= S::forURL("&"); $URL .= "action=video_player"; $URL .= S::forURL("&"); $URL .= "method=stream"; $URL .= S::forURL("&"); $URL .= "path=".S::forURL($path); ?> <html> <head> <title></title> <style> body { background-color: black; border: 0px; margin: 0px; padding: 0px; overflow:hidden; } </style> <script type="text/javascript" charset="utf-8" src="<?php echo $config['url']['root']?>/js/swfobject/swfobject.js?v=<?php echo $settings->currentVersion;?>"></script> </head> <body> <table border="0" cellpadding="0" cellspacing="0" height="100%" width="100%" style="height:100%" border="0"> <tr> <td align="center" valign="middle"> <div id="videoPlayer" style="width:100%;height:100%;"></div> <script type="text/javascript"> var videoSize = { width: parseInt('<?php echo $fInfo['video']['resolution_x']?:0; ?>'), height: parseInt('<?php echo $fInfo['video']['resolution_y']?:0; ?>') }; if (videoSize.width < 100 || videoSize.width > window.innerWidth) { videoSize.width = '100%'; } if (videoSize.height < 100 || videoSize.width > window.innerHeight) { videoSize.height = '100%'; } var flashVars = { video: "<?php echo $URL?>", skin: '<?php echo $config['url']['root']?>/customizables/custom_actions/video_player/flv/mySkin.swf?v=<?php echo $settings->currentVersion;?>', autoplay: 1, menu: false, }; var params = { allowFullScreen: true, wmode: 'window', quality: 'high' } swfobject.embedSWF("<?php echo $config['url']['root']?>/customizables/custom_actions/video_player/flv/player.swf?v=<?php echo $settings->currentVersion;?>", "videoPlayer", videoSize.width, videoSize.height, "9.0.0", "js/swfobjectexpressInstall.swf", flashVars, params); </script> </td> </tr> </table> </body> </html><file_sep><?php require_once $_SERVER['DOCUMENT_ROOT']."/setting/config.php"; ?> <?php class Page(){ function SystemPath($thisPagePath){ return $_phpPath.$thisPagePath; } function Name($thisPageName){ return $thisPageName; } function Meta($thisPageMeta){ return $thisPageMeta; } function Heading($thisPageHeading){ return $thisPageHeading; } function SubHeading($thisPageSubHeading){ return $thisPageSubHeading; } function Controller(){ } } ?><file_sep><?php $thisPageName = "Register"; $thisPageMeta = ""; $thisPageHeading = "Register New Account"; $thisPageContent = $_SERVER['DOCUMENT_ROOT']."/page/user/register/view/registerView.php"; $thisPageController = $_SERVER['DOCUMENT_ROOT']."/page/user/register/controller/registerController.php"; if (!empty($thisPageController)){require_once $thisPageController;} require_once $_SERVER['DOCUMENT_ROOT']."/page/_layout/_layout.php"; ?><file_sep><?php /* FileRun The username is "superuser". The password is " <PASSWORD> ". */ ?><file_sep><?php $_smtpEncryptString = ""; ?><file_sep><?php //////////////////////////////////////////////////// // Version 1 // Load general css /* foreach (getAllFileInFolderWithType($_phpPath.'css', 'css') as $cssFile){ echo '<link rel="stylesheet" href="'.$_url.'css/'.$cssFile.'">'; } foreach (getAllFileInFolderWithType($_phpPath.'page'.(empty(substr($_SERVER['REQUEST_URI'],1))?'/index':$_SERVER['REQUEST_URI']).'/view/css', 'css') as $cssFile){ echo '<link rel="stylesheet" href="'.$_url.'page/'.(empty(substr($_SERVER['REQUEST_URI'],1))?'index':$_SERVER['REQUEST_URI']).'/view/css/'.$cssFile.'">'; } */ /////////////////////////////////////////////////// // Version 2 // On Work // consoleData($_documentPath); // // On Test // Get Private chi co minh no /* Vi du: css > product Tat ca cac file trong product chi co minh no dc xem */ // Va tat ca cac Public thi se co may thang khac nua /* Vi du: css > product > public css > product > viewdetail view viewdetail se thua huong tu css product > public neu cay dai` hon css > product > viewdetail > item Thi item se thua huong cua css > product > public css > product > viewdetail > public */ // Should be in config.php to re-use for ($x = 0; $x < $_countGetPath; $x++){ // Get All Public Inheritent File $_combineLine[$x] = $_combineLine[$x - 1].$_getPath[$x].'/'; //consoleData('Path: '.$_phpPath.'css'.$combineLine[$x]); //consoleData(getAllFileInFolderWithType($_phpPath.'css'.$combineLine[$x], 'css')); foreach (getAllFileInFolderWithType($_phpPath.'css'.$_combineLine[$x], 'css') as $cssFile){ echo('<link rel="stylesheet" href="'.$_url.'css'.$_combineLine[$x].$cssFile.'">'); } // Get Private File if ($x == ($_countGetPath - 1)){ // consoleData($_phpPath.'css'.$_documentPath.'/private'); foreach (getAllFileInFolderWithType($_phpPath.'css'.$_combineLine[$x].'private', 'css') as $cssFile){ echo('<link rel="stylesheet" href="'.$_url.'css'.$_combineLine[$x].'private/'.$cssFile.'">'); } } } ?><file_sep><?php use \CloudConvert\Api; class custom_cloudconvert { var $online = true; static $localeSection = "Custom Actions: CloudConvert"; function init() { $this->settings = array( array( 'key' => 'APIKey', 'title' => self::t('API Key'), 'comment' => \FileRun\Lang::t('Get it from %1', 'Admin', array('<a href="https://cloudconvert.com/api" target="_blank">https://cloudconvert.com/api</a>')) ) ); $this->JSconfig = array( 'nonTouch' => true, "title" => self::t("CloudConvert"), 'icon' => 'images/icons/cloudconvert.png', "popup" => true, 'width' => 580, 'height' => 400, "requiredUserPerms" => array("download", "upload") ); } function isDisabled() { return (strlen(self::getSetting('APIKey')) == 0); } static function getSetting($k) { global $settings; $key = 'plugins_cloudconvert_'.$k; return $settings->{$key}; } static function t($text, $vars = false) { return \FileRun\Lang::t($text, self::$localeSection, $vars); } function run() { global $fm; \FileRun::checkPerms("download"); $ext = $fm->getExtension($this->data['fileName']); $api = new Api(self::getSetting('APIKey')); $rs = $api->get('/conversiontypes', ['inputformat' => \S::forURL($ext)]); require($this->path."/display.php"); } function requestConversion() { global $fm; $ext = $fm->getExtension($this->data['fileName']); $targetFormat = S::fromHTML($_POST['format']); $api = new Api(self::getSetting('APIKey')); try { $process = $api->convert([ 'inputformat' => $ext, 'outputformat' => $targetFormat, 'input' => 'upload', 'filename' => $this->data['fileName'], 'file' => fopen($this->data['filePath'], 'r'), 'callback' => 'http://_INSERT_PUBLIC_URL_TO_/callback.php' ]); } catch (\CloudConvert\Exceptions\ApiBadRequestException $e) { jsonFeedback(false, "Error: " . $e->getMessage()); } catch (\CloudConvert\Exceptions\ApiConversionFailedException $e) { jsonFeedback(false, "Conversion failed, maybe because of a broken input file: " . $e->getMessage()); } catch (\CloudConvert\Exceptions\ApiTemporaryUnavailableException $e) { jsonFeedback(false, "API temporary unavailable: ".$e->getMessage()); } catch (Exception $e) { jsonFeedback(false, "Error: " . $e->getMessage()); } jsonOutput(array( 'success' => true, 'msg' => 'CloudConvert: '. $process->message, 'url' => $process->url )); } function getStatus() { global $fm; $url = S::fromHTML($_POST['statusURL']); if (strtolower(substr($url, 0, 6)) != 'https:') { $url = 'https:'.$url; } $api = new Api(self::getSetting('APIKey')); $process = new \CloudConvert\Process($api, $url); $process->refresh(); if ($process->step == 'finished') { $tempFile = gluePath($this->data['filePath'].'.'.$process->output->size.'.upload'); $rs = $process->download($tempFile); global $myfiles; $fileName = \FM::replaceExtension($this->data['fileName'], $process->output->ext); $rs = $myfiles->newFile($fm->dirname($this->data['relativePath']), $fileName, $tempFile, false, true); if (!$rs) { jsonOutput(array( 'success' => false, 'msg' => 'Failed to save the downloaded file', 'step' => 'error' )); } jsonOutput(array( 'success' => true, 'msg' => 'Converted file was saved', 'step' => 'downloaded', 'newFileName' => $fileName )); } jsonOutput(array( 'success' => false, 'msg' => 'CloudConvert: '.$process->message, 'step' => $process->step, 'percent' => $process->percent, 'output' => $process->output )); } }<file_sep><?php $thisPageName = "Homepage"; $thisPageMeta = ""; $thisPageHeading = "Welcome to Modern Business"; $thisPageSubHeading = ""; $thisPageUpperContent = $_SERVER['DOCUMENT_ROOT']."/page/index/view/indexUpperView.php"; $thisPageDownerContent = ""; $thisPageContent = $_SERVER['DOCUMENT_ROOT']."/page/index/view/indexView.php"; $thisPageController = $_SERVER['DOCUMENT_ROOT']."/page/index/controller/controllerIndex.php"; if (!empty($thisPageController)){require_once $thisPageController;} require_once $_SERVER['DOCUMENT_ROOT']."/page/_layout/_layout.php"; //echo realpath('.'); ?><file_sep>// JavaScript Document // This function need to be improve: // Because if second level apply it will be wrong. $(function() { var pgurl = window.location.href; $("#nav ul li a").each(function(){ if(/*regexCheck($(this).attr("href"), pgurl) ||*/ $(this).attr("href") == pgurl || $(this).attr("href") == '' ) $(this).parent().addClass("active"); }) $("img").lazyload(); }); <file_sep><?php require_once $_SERVER['DOCUMENT_ROOT']."/setting/control.php"; ?> <?php // Should Include Auto get CSS and JS private only, Must check if include yes or not. ?><file_sep><?php $_sqlEncryptString = ""; ?><file_sep><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title></title> <link rel="stylesheet" type="text/css" href="css/style.css?v=<?php echo $settings->currentVersion;?>" /> <link rel="stylesheet" type="text/css" href="css/ext.php?v=<?php echo $settings->currentVersion;?>" /> <script type="text/javascript" src="js/min.php?extjs=1&v=<?php echo $settings->currentVersion;?>"></script> <script src="customizables/custom_actions/audio_player/js/soundmanager2-nodebug-jsmin.js?v=<?php echo $settings->currentVersion;?>"></script> <script type="text/javascript" src="customizables/custom_actions/audio_player/js/app.js?v=<?php echo $settings->currentVersion;?>"></script> <script type="text/javascript" src="customizables/custom_actions/audio_player/js/aurora.js?v=<?php echo $settings->currentVersion;?>"></script> <script type="text/javascript" src="customizables/custom_actions/audio_player/js/flac.js?v=<?php echo $settings->currentVersion;?>"></script> <script type="text/javascript"> var URLRoot = '<?php echo S::safeJS($config['url']['root'])?>'; FR.popupId = '<?php echo S::safeJS(S::fromHTML($_REQUEST['_popup_id']))?>'; FR.countFiles = <?php echo sizeof($audioFiles)?>; FR.files = <?php echo json_encode($audioFiles)?>; FR.currentIndex = <?php echo $currentIndex?>; </script> <style> .x-grid3-scroller {overflow-x: hidden;} </style> </head> <body id="theBODY" onload="FR.init()"> </body> </html><file_sep>// JavaScript Document function regexCheck(regexPattern, inputString){ "use strict"; return (regexPattern.test(inputString))?true:false; } function emailPattern(){ "use strict"; const emailPattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return emailPattern; } /*function passwordPattern(){ const passwordPattern = //; return passwordPattern; } */ function matching2WordsPattern(inputString){ "use strict"; const matching2WordsPattern = new RegExp("^("+inputString+")$"); return matching2WordsPattern; } function passwordPattern(){ "use strict"; const passwordPattern = /^[^\s\"\']+$/; return passwordPattern; } function passwordComplexPattern(){ "use strict"; const passwordComplexPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$/; return passwordComplexPattern; } function textPattern(){ "use strict"; const textPattern = /^[\d\w\s\!\@\#\$\%\^\&\*\(\)\+\-\.\_\-]+$/; return textPattern; } <file_sep>FR.components.infoPanel = Ext.extend(Ext.Panel, {//if using TabPanel directly, there are layout problems baseCls: 'fr-info-panel', initComponent: function() { Ext.apply(this, { listeners: { 'collapse': function() { FR.UI.actions.info.toggle(false, true); }, 'expand': function() { FR.UI.actions.info.toggle(true, true); this.gridSelChange(); } } }); FR.components.infoPanel.superclass.initComponent.apply(this, arguments); }, customCollapse: function() { FR.localSettings.set('infoPanelState', 'collapsed'); this.collapse(); }, customExpand: function() { FR.localSettings.set('infoPanelState', 'expanded'); this.expand(); }, onRender: function() { FR.components.infoPanel.superclass.onRender.apply(this, arguments); }, gridSelChange: function() { if (this.collapsed) {return false;} this.countSel = FR.UI.gridPanel.countSel; this.countAll = FR.UI.gridPanel.store.getCount(); var showActivityTab = false; var hideCommentsTab = !User.perms.read_comments; if (this.countSel == 1) { this.item = FR.currentSelectedFile; if (FR.currentSection == 'trash' || this.item.data.isFolder) { hideCommentsTab = true } else { FR.UI.commentsPanel.setItem(this.item.data.path, this.item.data.comments); } } else { hideCommentsTab = true; this.tabPanel.unhideTabStripItem(1); if (FR.currentSection == 'myfiles') { this.tabPanel.unhideTabStripItem(1); showActivityTab = User.perms.file_history; } else if (FR.currentSection == 'sharedFolder') { showActivityTab = Settings.filelog_for_shares; } this.item = null; } if (!showActivityTab) { if (this.tabPanel.getActiveTab() == FR.UI.activityPanel) { this.tabPanel.setActiveTab(0); } this.tabPanel.hideTabStripItem(1); } if (hideCommentsTab) { if (this.tabPanel.getActiveTab() == FR.UI.commentsPanel) { FR.UI.infoPanel.tabPanel.setActiveTab(0); } this.tabPanel.hideTabStripItem(2); } else { this.tabPanel.unhideTabStripItem(2); } FR.UI.detailsPanel.gridSelChange(); }, folderChange: function() { FR.UI.detailsPanel.metadataCache.clear(); if (this.tabPanel.getActiveTab() == FR.UI.activityPanel) { FR.UI.activityPanel.load(); } } });<file_sep>Need a function to get all information of the current login member When request successful (After regex check) Get privatekey of him => This key will need to encrypt all his data. Otherwise it will show there data in F12 which is not cool Need function check exist file RETURN true false Business layer implement => Access to db and do the business logic Like have a coffeemachine need to find the employee responsible to the coffee machine => Code the get employee responsible in the business layer Include it in the file controller Call that function in there. --------- Should put _partialLayout --------- Control Email template Replace @example to word that wanted -------- Put escape string in to remove error <<<<<<< HEAD -------- V2.1: config.php will include control.php => Version 1 migrate to version 2 is possible. ======= -------- Cronjob: https://github.com/rse/jquery-schedule - http://shawnchin.github.io/jquery-cron/ - http://www.aegissofttech.com/Articles/use-of-jqeury-cron-in-dot-net-mvc-application.html Log: https://github.com/remybach/jQuery.clientSideLogging >>>>>>> origin/master <file_sep>Current Version: 2.0.0.0 Alpha Testing Server: Hostinger.vn, Hostfree.pw Consider to update: Get absolute path file: NOT YET substr(__FILE__, 0, -strlen($_SERVER['SCRIPT_NAME'])); Rewrite URL: DONE $URL/page/about to $URL/about Multiple mini project in big project: Original: $URL/page/User/.../ User/register/ User/login/ User/forgotpassword/ User/viewdetails/ User/index = User/ Auto get CSS and JS in folder: DONE 1st Level Need: Create a function Auto Active Link in Navbar: DONE 1st Level Finish auto active link in first level page: Index, Contact, About Unfinish: Product > Viewdetail Need: - Do loop to get all level of directory and go backward to active link. - Or: Find the url and active the link if inside link active outside do to apply on CSS. Lazyload: https://www.appelsiini.net/projects/lazyload Should be apply *********************************************************************** Task: Planning Tomorrow Task: - Finish wiki for create new page, need to check the logic again. Daily Task: *********************************************************************** ****************This website template made by NeV3RmI****************** *********************************************************************** 1/ Config FOR RMIT Student: Open File and change all the s3515215 to your student number 2/ Config MySQL Open setting/mysql_config.php Notice this template use [mysqli] not [mysql] 3/ Enable JS + Bootstrap + Jquery PHP + Connect MySQL + All link to one Other Feature + GZIP Compression + .htaccess + .htpasswd<file_sep><?php class custom_pixlr { var $online = true; var $localeSection = "Custom Actions: Pixlr"; function init() { $this->JSconfig = array( "title" => \FileRun\Lang::t("Pixlr", $this->localeSection), 'icon' => 'images/icons/pixlr.png', "extensions" => array("jpg", "jpeg", "gif", "png", "psd", "bmp", "pxd"), "popup" => true, "external" => true, "requiredUserPerms" => array("download", "upload"), "createNew" => array( "title" => \FileRun\Lang::t("Image with Pixlr", $this->localeSection), "defaultFileName" => \FileRun\Lang::t("Untitled.png", $this->localeSection) ) ); $this->outputName = "image"; } function run() { global $config; $weblinkInfo = $this->weblinks->createForService($this->data['filePath'], false, $this->data['shareInfo']['id']); if (!$weblinkInfo) { echo "Failed to setup weblink"; exit(); } $this->data['fileURL'] = $this->weblinks->getURL(array("id_rnd" => $weblinkInfo['id_rnd'])); $this->data['saveURL'] = $this->weblinks->getSaveURL($weblinkInfo['id_rnd'], false, "pixlr"); \FileRun\Log::add(false, "preview", array( "relative_path" => $this->data['relativePath'], "full_path" => $this->data['filePath'], "method" => "Pixlr" )); $proto = isSSL() ? "https" : "http"; $url = $proto."://apps.pixlr.com/editor/"; //$url .= "?method=POST"; $url .= "?image=".urlencode($this->data['fileURL']); $url .= "&referrer=".urlencode($config['settings']['app_title']); $url .= "&target=".urlencode($this->data['saveURL']); $url .= "&title=".urlencode($this->data['fileName']); $url .= "&redirect=false"; $url .= "&locktitle=true"; $url .= "&locktype=true"; header('Location: '.$url); } function createBlankFile() { global $myfiles, $fm; if (!\FileRun\Perms::check('upload')) {exit();} if (file_exists($this->data['filePath'])) { jsonOutput(array("rs" => false, "msg" => \FileRun\Lang::t('A file with the specified name already exists. Please try again.', $this->localeSection))); } $blankFilePath = gluePath($this->path, "blank.png"); $rs = $myfiles->newFile($fm->dirname($this->data['relativePath']), $this->data['fileName'], $blankFilePath); if ($rs) { jsonOutput(array("rs" => true, 'path' => $this->data['relativePath'], "filename" => $this->data['fileName'], "msg" => \FileRun\Lang::t("Blank image created successfully", $this->localeSection))); } else { jsonOutput(array("rs" => false, "msg" => $myfiles->error['msg'])); } } function getNewFileContents() { return file_get_contents(S::fromHTML($_GET['image'])); } }<file_sep><?php class custom_handle_url { var $localeSection = 'Custom Actions: Link Opener'; function init() { $this->JSconfig = array( 'title' => \FileRun\Lang::t('Link Opener', $this->localeSection), 'iconCls' => 'fa fa-fw fa-share-square-o', 'extensions' => array('url'), 'replaceDoubleClickAction' => true, 'popup' => true, 'requiredUserPerms' => array('download') ); } function run() { \FileRun::checkPerms("download"); $c = file($this->data['filePath']); foreach ($c as $r) { if (stristr($r, 'URL=') !== false) { header('Location: '.str_ireplace(array('URL=', '\''), array(''), $r)); exit(); } } } } <file_sep><script type="text/javascript"> function getURL(){ return "<?php echo $_url?>"; } </script><file_sep><?php // Priority $_phpPath = $_SERVER['DOCUMENT_ROOT']."/"; // Include User Config include_once $_phpPath."setting/config.php"; // Configuration $_q = "'"; $_p = '"'; $_url = "http".($_useHTTPs == 1 ? "s" : "")."://" . $_SERVER['SERVER_NAME']."/"; $_fullUrl = "http".($_useHTTPs == 1 ? "s" : "")."://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; $_documentPath = $_SERVER['REQUEST_URI']; $_getPath = explode("/",$_documentPath); if ($_getPath[1] == "" || !isset($_getPath[1])){ $_getPath[1] = "index"; } $_countGetPath = count($_getPath); // Page Setting $_copyRight = "Copyright ".$_sitePublisher." &copy; ". $_siteCopyrightYear; // PHP FUNCTION // PHP Library Include if ($_usePhpLibrary == 1){ include_once $_phpPath."setting/php_library.php"; } // Trigger Package: SQL, SMTP, Email if ($_useTrigger == 1){ include_once $_phpPath."setting/trigger/trigger.php"; } // Connecting MySQL if ($_useMysql == 1){ include_once $_phpPath."setting/database_access.php"; include_once $_phpPath."setting/mysql_config.php"; } if ($_useGzipCompress == 1){ if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start('ob_gzhandler'); else ob_start(); } if ($_useHTTPs == 1){ } /* if ($turnofferror_s == 0){ error_reporting(0); }*/ if ($_useSession == 1){ session_start(); } ?><file_sep><?php //0-None, 1-Use $_useTrigger = 1; // This include config for SMTP, Email, SQL $_useMysql = 1; $_usePhpLibrary = 1; $_useGzipCompress = 1; $_useDebug = 1; // 0 - Off, 1 - Simple, 2 - All $_useSession = 1; $_useHTTPs = 1; // Learn how to make a free SSL: http://www.selfsignedcertificate.com/ $_useFileManager = 1; // System Variable $_siteName = "PHP Easy"; $_sitePublisher = "NeV3RmI"; $_siteCopyrightYear = "2013 - 2016"; $_siteVersion = "2.0.0.0"; // General Meta Variable //Regex Library $_regexMail = '/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'; $_regexPassword = '/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*(_|[^\w])).+$/'; // Connect DB String $_dbHostName = $selectedSQLKey[0]; $_dbUsername = $selectedSQLKey[1]; $_dbPassword = $selectedSQLKey[2]; $_dbDatabase = $selectedSQLKey[3]; ?><file_sep><?php $_emailEncryptString = ""; ?><file_sep><?php require_once $_SERVER['DOCUMENT_ROOT']."/page/about/aboutContent.php"; ?><file_sep><?php global $config, $settings, $fm; ?> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title></title> <link rel="stylesheet" type="text/css" href="css/ext.php?v=<?php echo $settings->currentVersion;?>" /> <script type="text/javascript" src="js/min.php?extjs=1&v=<?php echo $settings->currentVersion;?>"></script> <script type="text/javascript" src="customizables/custom_actions/arch/grid.js?v=<?php echo $settings->currentVersion;?>"></script> <style> .x-grid3-cell {font-family: tahoma, arial, helvetica, sans-serif;} </style> </head> <body> <table id="theTable" width="100%"> <thead> <tr class="header"> <th name="filename">File name</td> <th name="size">Size</td> <th name="path">Path</td> </tr> </thead> <tbody> <?php $limit = 50; $i = 0; foreach ($list as $key => $item) { if ($i == $limit) { ?> <tr> <td>Archive contains <?php echo $count-$limit;?> files more that are not displayed in this preview.</td> <td>&nbsp;</td> </tr> <?php break; } if ($item['checksum'] != "00000000") { if ($item['utf8_encoded']) { $srcEnc = "UTF-8"; } else { if ($config['app']['encoding']['unzip']) {//convert from a predefined encoding $srcEnc = $config['app']['encoding']['unzip']; } else { $srcEnc = S::detectEncoding($item['filename']); } } $item['filename'] = \S::convert2UTF8($item['filename'], $srcEnc); if ($item['type'] == "file" && $item['filename']) { ?> <tr> <td><img src="<?php echo $fm->getFileIconURL($item['filename']);?>" border="0" height="16" width="16"> <?php echo S::safeHTML($item['filename']);?></td> <td width="100"><?php echo $fm->formatFileSize($item['filesize']);?></td> <td><?php echo S::forHTML(gluePath("/", $item['path']), 1);?></td> </tr> <?php $i++; } } } ?> </tbody> </table> </body> </html><file_sep>css and js is private to this page only<file_sep><?php $config['app']['software_update']['url'] = 'https://www.filerun.com/updates/ionCube7';<file_sep><?php if (isset($_GET['oauth2'])) { $files = array( 'roboto/load.css', 'normalize.css', 'skeleton.css', 'oauth2.css' ); } else if (isset($_GET['file_request'])) { $files = array( 'roboto/load.css', 'file_request.css' ); } else { $files = array( 'roboto/load.css', //'_ext-all.css', 'ext-all.min.css', 'ext-filerun.css', '../js/ext/ux/ProgressColumn/ProgressColumn.css', 'font-awesome/css/font-awesome.min.css' ); } if (extension_loaded("zlib") && (ini_get("output_handler") != "ob_gzhandler")) { ini_set("zlib.output_compression", 1); } header("Content-type: text/css; charset: UTF-8"); header("Cache-control: public"); header("Pragma: cache"); header("Expires: " . gmdate ("D, d M Y H:i:s", time() + 31356000) . " GMT"); foreach ($files as $key => $file) { readfile($file); echo "\r\n"; }<file_sep><?php include_once realpath($_SERVER["DOCUMENT_ROOT"])."/setting/control.php"; ?> <li> <p class="navbar-text">Already have an account?</p> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><b>Login</b> <span class="caret"></span></a> <ul id="login-dp" class="dropdown-menu"> <li> <div class="row" id="loginMessage"> </div> </li> <li> <div class="row"> <div class="col-md-12"> Login via <div class="social-buttons"> <a href="#" class="btn btn-fb"><i class="fa fa-facebook"></i> Facebook</a> <a href="#" class="btn btn-tw"><i class="fa fa-twitter"></i> Twitter</a> </div> or <form class="form" accept-charset="UTF-8" id="userLoginForm"> <div class="form-group"> <label class="sr-only" for="exampleInputEmail2" id="userEmail">Email address</label> <input type="email" class="form-control" id="exampleInputEmail2" placeholder="Email address" name="userEmail" required> </div> <div class="form-group"> <label class="sr-only" for="exampleInputPassword2" id="userPassword">Password</label> <input type="<PASSWORD>" class="form-control" id="exampleInputPassword2" placeholder="<PASSWORD>" name="userPassword" required> <div class="help-block text-right"><a href="">Forget the password ?</a></div> </div> <div class="form-group"> <a class="btn btn-primary btn-block" id="userRequestLogin" onClick="submitForm('#userLoginForm')">Sign in</a> </div> <div class="checkbox"> <label> <input type="checkbox" name="userKeepLogin"> <span>Keep me logged-in</span> </label> </div> </form> </div> <div class="bottom text-center"> New here ? <a href="<?php echo $_url;?>user/register"><b>Join Us</b></a> </div> </div> </li> </ul> </li> <file_sep><?php include_once realpath($_SERVER["DOCUMENT_ROOT"])."/setting/control.php"; ?> <?php include_once $_phpPath."page/user/register/partialview/addNewUserPartialView.php"; ?> <?php $email = $_POST['registerEmail']; $password = $_POST['registerPassword']; $retypePassword = $_POST['registerRetypePassword']; $termAndCondition = $_POST['registerRuleAccepted']; // Regex Value if (!RegexCheck($_regexMail,$email)){ SetRegisterDialogToError("Invalid type of email"); exit(); }; if (!RegexCheck($_regexPassword,$password)){ SetRegisterDialogToError("Invalid type of password"); exit(); }; if (!RegexCheck($_regexPassword,$retypePassword)){ SetRegisterDialogToError("Invalid type of retype password"); exit(); }; if ($termAndCondition != "on"){ SetRegisterDialogToError("You must agree term before sign up"); exit(); }; // // Create Private Key if ($privateKey = CreatePrivateKey()){ if ($salt = CreatingSalt(CreatingHash($password))){ $result = "Your Private Key: ".$privateKey."<br>Your Salt: ".$salt; SetDialogInGeneral($result,"Personal Details","primary"); }else{ SetRegisterDialogToError("Cannot create Salt"); exit(); } }else{ SetRegisterDialogToError("Cannot create Private Key"); exit(); } // Need to run independently ?><file_sep><?php if (!empty($_SESSION['id'])){ echo '<script type="text/javascript" defer>$(function(){loadLoginNavigationBar();});</script>'; }else{ echo '<script type="text/javascript" defer>$(function(){loadBeforeLoginNavigationBar();});</script>'; } ?> <file_sep><?php chdir(dirname(dirname(__FILE__))); if (isset($_GET['cpanel'])) { $files = array( 'js/ext/ux/ScriptLoader.js', 'js/cpanel/ext.overrides.js', 'js/cpanel/app.js', 'js/cpanel/tree.js', 'js/cpanel/grid.js', 'js/cpanel/layout.js', 'js/fileman/user_chooser.js', 'js/cpanel/userslist.comp.js', 'js/cpanel/editform.comp.js', 'js/genpass.js', 'js/ext/ux/statusbar/StatusBar.js' ); } else if (isset($_GET['extjs'])) { if (isset($_GET['debug'])) { $files = array( 'js/ext/adapter/ext/_ext-base-debug.js', 'js/ext/_ext-all-debug-w-comments.js', 'js/ext/ux/overrides.js', 'js/ext/ux/LocalStorage.js', 'js/ext/ux/FileRunPrompt.js', 'js/ext/ux/ListPanel.js' ); } else { $files = array( 'js/ext/adapter/ext/ext-base.js', 'js/ext/ext-all.js', 'js/ext/ux/overrides.js', 'js/ext/ux/LocalStorage.js', 'js/ext/ux/FileRunPrompt.js', 'js/ext/ux/ListPanel.js' ); } } else if (isset($_GET['weblink_gallery'])) { $files = array( 'js/jquery/jquery.min.js', 'js/nanobar.min.js', 'js/headroom.min.js', 'js/jquery/jG/jquery.justifiedGallery.min.js', 'js/weblink.js' ); if (isset($_GET['debug'])) { $files[] = 'js/jquery/swipebox/js/_jquery.swipebox.js'; } else { $files[] = 'js/jquery/swipebox/js/jquery.swipebox.min.js'; } } else if (isset($_GET['file_request'])) { $files = array( 'js/file_request.js' ); if (isset($_GET['debug'])) { $files[] = 'js/flow/_flow.js'; $files[] = 'js/flow/_flowfile.js'; $files[] = 'js/flow/_flowchunk.js'; } else { $files[] = 'js/flow/all-standalone.min.js'; } } else if (isset($_GET['flow'])) { if (isset($_GET['debug'])) { $files[] = 'js/flow/_flow.js'; $files[] = 'js/flow/_flowfile.js'; $files[] = 'js/flow/_flowchunk.js'; $files[] = 'js/flow/_flowext.js'; } else { $files[] = 'js/flow/all.min.js'; } } else if (isset($_GET['flow-standalone'])) { if (isset($_GET['debug'])) { $files[] = 'js/flow/_flow.js'; $files[] = 'js/flow/_flowfile.js'; $files[] = 'js/flow/_flowchunk.js'; } else { $files[] = 'js/flow/all-standalone.min.js'; } } else { $files = array( 'js/ext/ux/ProgressColumn/ProgressColumn.js', 'js/ext/ux/GridDragSelector.js', 'js/fileman/filerun.js', 'js/fileman/toolbars_and_menus.js', 'js/fileman/grid.js', 'js/fileman/tree.js', 'js/fileman/info_panel.js', 'js/fileman/details_panel.js', 'js/fileman/download_cart.js', 'js/fileman/activity_panel.js', 'js/fileman/comments_panel.js', 'js/fileman/layout.js', 'js/fileman/ui_utils.js', 'js/fileman/actions.js', 'js/fileman/image_viewer.js' ); if (isset($_GET['debug'])) { $files[] = 'js/flow/_flow.js'; $files[] = 'js/flow/_flowfile.js'; $files[] = 'js/flow/_flowchunk.js'; $files[] = 'js/flow/_flowext.js'; } else { $files[] = 'js/flow/all.min.js'; } } if (extension_loaded("zlib") && (ini_get("output_handler") != "ob_gzhandler")) { ini_set("zlib.output_compression", 1); } header("Content-Type: application/javascript; charset=UTF-8"); header("Cache-control: public"); header("Pragma: cache"); header("Expires: " . gmdate ("D, d M Y H:i:s", time() + 31356000) . " GMT"); foreach ($files as $key => $file) { readfile($file); echo "\r\n"; }<file_sep><?php class custom_audio_player { function init() { $this->localeSection = "Custom Actions: Audio Player"; $this->JSconfig = array( "title" => \FileRun\Lang::t("Audio Player", $this->localeSection), 'iconCls' => 'fa fa-fw fa-music', 'useWith' => array('mp3'), "popup" => true, 'width' => 400, 'height' => 400, "requiredUserPerms" => array("download") ); } function run() { global $config, $settings, $fm; $folderRelativePath = \FM::dirname($this->data['relativePath']); $folderPath = \FM::dirname($this->data['filePath']); $ext = \FM::getExtension($this->data['fileName']); $audioFiles = array(); $currentIndex = 0; if ($ext == "m3u" || $ext == "m3u8") { $lines = file($this->data['filePath']); foreach ($lines as $line) { if (substr($line, 0, 5) == "http:") { $audioFiles[] = array($line, $line); } } } else if ($ext == "pls") { $lines = file($this->data['filePath']); foreach ($lines as $line) { if (substr($line, 0, 4) == "File") { $pos = strpos($line, "="); $url = substr($line, $pos+1); $audioFiles[] = array($url, $url); } } } else { if (isset($config['app']['audioplayer']['playlist']) && !$config['app']['audioplayer']['playlist']) { $url = $config['url']['root']; $url .= "/?module=custom_actions&action=audio_player&method=stream"; $url .= "&path=" . S::forURL(gluePath($folderRelativePath, $this->data['fileName'])); $audioFiles[] = array($url, $this->data['fileName']); $currentIndex = 0; } else { $list = \FileRun\Files\Utils::listFolder($folderPath, false, false, false, true); if (is_array($list) && sizeof($list) > 0) { $i = 0; foreach ($list as $fileName) { $info = $fm->fileTypeInfo($fileName); if ($info['type'] == 'mp3') { $url = $config['url']['root']; $url .= "/?module=custom_actions&action=audio_player&method=stream"; $url .= "&path=" . S::forURL(gluePath($folderRelativePath, $fileName)); $audioFiles[$i] = array($url, $fileName); if ($fileName == $this->data['fileName']) { $currentIndex = $i; } $i++; } } } } } require($this->path."/display.php"); } function stream() { \FileRun::checkPerms("download"); \FileRun\Utils\Downloads::sendFileToBrowser($this->data['filePath']); \FileRun\Log::add(false, "preview", array( "relative_path" => $this->data['relativePath'], "full_path" => $this->data['filePath'], "method" => "Audio Player" )); exit(); } }<file_sep><?php $thisPageName = "500 ERROR"; $thisPageMeta = ""; $thisPageHeading = "ERROR"; $thisPageSubHeading = "500"; $thisPageContent = $_SERVER['DOCUMENT_ROOT']."/page/_layout/error/view/_404.php"; require_once $_SERVER['DOCUMENT_ROOT']."/page/_layout/_layout.php"; //echo realpath('.'); ?><file_sep><?php class custom_msoffice { var $online = true; var $ext = array( 'word' => ["doc", "docx", "docm", "dotm", "dotx", "odt"], 'excel' => ["xls", "xlsx", "xlsb", "xls", "xlsm", "ods"], 'powerpoint' => ["ppt", "pptx", "ppsx", "pps", "pptm", "potm", "ppam", "potx", "ppsm", "odp"], 'project' => ['mpp'], 'visio' => ['vsd', 'vss', 'vst', 'vdx', 'vsx', 'vtx'] ); function init() { global $config; $postURL = $config['url']['root'].'/?module=custom_actions&action=msoffice&method=run'; $this->JSconfig = array( "title" => \FileRun\Lang::t("Office", 'Custom Actions: Office'), "icon" => 'images/icons/office.png', "extensions" => call_user_func_array('array_merge', $this->ext), "requiredUserPerms" => array("download"), "fn" => "FR.UI.backgroundPost(false, '".\S::safeJS($postURL)."')" ); } function run() { $data = $this->weblinks->createForService($this->data['filePath'], 1); $args = array( "id_rnd" => $data['id_rnd'], "password" => $<PASSWORD>['<PASSWORD>'] ); //Allowed URIs must conform to the standards proposed in RFC 3987 – Internationalized Resource Identifiers (IRIs) //Characters identified as reserved in RFC 3986 should not be percent encoded. //Filenames must not contain any of the following characters: \ / : ? < > | " or *. $args['filename'] = str_replace('"', '_', $this->data['fileName']); $extension = \FM::getExtension($this->data['fileName']); $type = false; foreach($this->ext as $k => $extList) { if (in_array($extension, $extList)) { $type = $k; break; } } if (!$type) {return false;} $url = $this->weblinks->getURLRW($args); if (!$url) { echo "Failed to setup weblink"; exit(); } header('Location: ms-'.$type.':ofv|u|'.$url); exit(); } }<file_sep><body> <?php require_once $_phpPath."page/_layout/body/_navigationbar.php"; ?> <?php require_once $_phpPath."page/_layout/body/_header.php"; ?> <?php require_once $_phpPath."page/_layout/body/_container.php"; ?> <?php require_once $_phpPath."css/css.php"; ?> <?php //if(!empty($thisPageCSS)){require_once $thisPageCSS;} echo $thisPageCSS; ?> <?php require_once $_phpPath."js/js.php"; ?> <?php //if(!empty($thisPageJS)){require_once $thisPageJS;} echo $thisPageJS; ?> </body><file_sep>FR.spaceQuota = { store: new Ext.data.SimpleStore({ fields: [ {name: 'id', type: 'integer'}, {name: 'username'}, {name: 'name'}, {name: 'max'}, {name: 'maxNice'}, {name: 'used'}, {name: 'usedNice'}, {name: 'percent'} ] }), sb: new Ext.ux.StatusBar({id: 'my-status', defaultText:'&nbsp;'}) } FR.spaceQuota.store.loadData(FR.users); FR.spaceQuota.grid = new Ext.grid.GridPanel({ title: FR.T('File space quota usage'), border: false, store: FR.spaceQuota.store, cm: new Ext.grid.ColumnModel({ defaults: {sortable: true}, columns: [ {header: FR.T("Id"), width: 30, dataIndex: 'id', hidden: true}, {header: '&nbsp;', width: 28, resizable: false, sortable: false, renderer: function(v, m, r) {return '<img src="a/?uid='+r.data.id+'" class="avatar-xs">';}}, {id:'uname', header: FR.T("Name"), width: 150, dataIndex: 'name'}, {id:'usrname', header: FR.T("Username"), width: 150, dataIndex: 'username'}, {header: FR.T("Quota"), width: 75, renderer: function(v, m, r) {return r.data.maxNice;}, dataIndex: 'max'}, {header: FR.T("Used"), width: 75, renderer: function(v, m, r) { if (r.data.max > 0 && (v >= r.data.max)) { return '<span style="color:red;">' +r.data.usedNice+ '</span>'; } else { return r.data.usedNice; } }, dataIndex: 'used'}, {header: FR.T("Usage"), width: 85, renderer: function(v, m, r) { if (v > FR.highlightLimit) { return '<span style="color:red;">' +v+ '%</span>'; } else { if (v) {return v+'%';} else {return '';} } }, dataIndex: 'percent'} ] }), bbar: FR.spaceQuota.sb, listeners: { 'afterrender': function() { var data = FR.spaceQuota.store.data; if (data.length > 0) { FR.currentUID = 0; FR.spaceQuota.getQuota(data.items[FR.currentUID].data.id, data.items[FR.currentUID]); } }, 'destroy': function() { Ext.Ajax.abort(FR.spaceQuota.ajaxReq); FR.spaceQuota = false; } } }); FR.spaceQuota.getQuota = function(uid, r) { if (FR.spaceQuota.sb) { FR.spaceQuota.sb.showBusy(FR.T('Calculating quota usage for "%1"...').replace('%1', r.data.name)); this.ajaxReq = Ext.Ajax.request({ url: FR.URLRoot+'/?module=cpanel&section=tools&page=space_quota&action=get&uid='+uid, method: 'GET', success: function(result, request) { try { rs = Ext.util.JSON.decode(result.responseText); } catch(er) {} if (rs && FR.spaceQuota) { r.set('max', rs.max); r.set('maxNice', rs.maxNice); r.set('used', rs.used); r.set('usedNice', rs.usedNice); r.set('percent', rs.percent); r.commit(); FR.currentUID++; var data = FR.spaceQuota.store.data; if (data.items[FR.currentUID] && FR.spaceQuota) { FR.spaceQuota.getQuota(data.items[FR.currentUID].data.id, data.items[FR.currentUID]); } else { FR.spaceQuota.sb.clearStatus(); } } } }); } } Ext.getCmp('appTab').add(FR.spaceQuota.grid); Ext.getCmp('appTab').doLayout();<file_sep><?php $URL = $config['url']['root']."/?module=custom_actions&action=video_player&method=stream&path=".S::forURL($this->data['relativePath']); ?> <html> <head> <title></title> <style>body {border: 0px;margin: 0px;padding: 0px;overflow:hidden;}</style> </head> <body> <script type="text/javascript" src="<?php echo $config['url']['root']?>/js/swfobject/swfobject.js"></script> <table border="0" cellpadding="0" cellspacing="0" height="100%" width="100%" style="height:100%" border="0"> <tr> <td align="center" valign="middle"> <div id="swf" style="width:100%;height:100%;">Loading Flash movie...</div> <script type="text/javascript"> swfobject.embedSWF("<?php echo $URL?>", "swf", '100%', '100%', "9.0.124"); </script> </td> </tr> </table> </body> </html><file_sep><?php class custom_crypt { static $localeSection = 'Custom Actions: File Encryption'; function init() { $pathToAESCrypt = 'H:/apps/tools/aescrypt.exe'; //and set the path here $this->config = array( 'encrypt_command' => $pathToAESCrypt.' -e -p [%pass%] [%filePath%]', 'decrypt_command' => $pathToAESCrypt.' -d -p [%pass%] [%filePath%]', 'encrypted_file_extension' => 'aes', 'debug' => false ); $this->settings = array( array( 'key' => 'pathToAESCrypt', 'title' => self::t('Path to AESCrypt'), 'comment' => self::t('Download and install AESCrypt from <a href="%1" target="_blank">here</a>.', array('https://www.aescrypt.com')) ) ); $this->JSconfig = array( 'nonTouch' => true, 'title' => self::t('AES File Encryption'), 'iconCls' => 'fa fa-fw fa-lock', 'requiredUserPerms' => array('upload', 'alter'), 'fn' => 'FR.customActions.crypt.run()' ); } function isDisabled() { return (strlen(self::getSetting('pathToAESCrypt')) == 0); } static function getSetting($k) { global $settings; $key = 'plugins_crypt_'.$k; return $settings->{$key}; } static function t($text, $vars = false) { return \FileRun\Lang::t($text, self::$localeSection, $vars); } function run() { global $fm; if (!\FileRun\Perms::check("upload") || !\FileRun\Perms::check("download")) { jsonFeedback(false, self::t("The user doesn't have permission to use this function!")); } else { $deleteSrc = (S::fromHTML($_POST['deleteSrc']) == 1 ? true : false); if (is_file($this->data['filePath'])) { $extension = $fm->getExtension($this->data['fileName']); session_write_close(); if ($extension == $this->config['encrypted_file_extension']) { $targetFileName = str_replace(".".$this->config['encrypted_file_extension'], "", $this->data['fileName']); $targetPath = gluePath($this->data['path'], $targetFileName); if (!file_exists($targetPath)) { $rs = $this->decrypt(); if ($rs) { if ($deleteSrc) { $this->deleteSource(); } \FileRun\Log::add(false, "file_decrypted", array( "relative_path" => $this->data['relativePath'], "to_relative_path" => gluePath($fm->dirname($this->data['relativePath']), $targetFileName), "full_path" => $this->data['filePath'], "to_full_path" => $targetPath, "method" => "AES" ), $this->data['filePath']); jsonFeedback(true, self::t("The selected file was successfully decrypted.")); } else { jsonFeedback(false, self::t("Failed to decrypt the selected file!")); } } else { jsonFeedback(false, self::t("A file named \"%1\" already exists!", array($targetFileName))); } } else { $targetFileName = $this->data['fileName'].".".$this->config['encrypted_file_extension']; $targetPath = gluePath($this->data['path'], $targetFileName); if (!file_exists($targetPath)) { $rs = $this->encrypt(); if ($rs) { if ($deleteSrc) { $this->deleteSource(); } \FileRun\Log::add(false, "file_encrypted", array( "relative_path" => $this->data['relativePath'], "to_relative_path" => gluePath($fm->dirname($this->data['relativePath']), $targetFileName), "full_path" => $this->data['filePath'], "to_full_path" => $targetPath, "method" => "AES" ), $this->data['filePath']); jsonFeedback(true, self::t("The selected file was successfully encrypted.")); } else { jsonFeedback(false, self::t("Failed to encrypt the selected file!")); } } else { jsonFeedback(false, self::t("A file named \"%1\" already exists!", array($targetFileName))); } } } else { jsonFeedback(false, self::t("The selected file was not found!")); } } } function JSinclude() { include(gluePath($this->path, "include.js.php")); } function encrypt() { $cmd = $this->parseCmd($this->config['encrypt_command']); return $this->runCmd($cmd); } function decrypt() { $cmd = $this->parseCmd($this->config['decrypt_command']); return $this->runCmd($cmd); } function parseCmd($cmd) { return str_replace( array("[%pass%]", "[%filePath%]"), array($this->escapeshellarg(S::fromHTML($_POST['pass'])), $this->escapeshellarg($this->data['filePath'])), $cmd); } function escapeshellarg($s) { return '"'.addslashes($s).'"'; } function deleteSource() { global $myfiles, $fm; return $myfiles->deleteFile($fm->dirname($this->data['relativePath']), $this->data['fileName'], $permanent = false); } function runCmd($cmd) { @exec($cmd, $return_text, $return_code); if ($return_code != 0) { if ($this->config['debug']) { echo " * command: ".$cmd."<br>"; echo " * returned code: ".$return_code."<br>"; echo " * returned text: "; print_r($return_text); flush(); } return false; } else { return true; } } } <file_sep><?php class custom_mediainfo { function init() { $this->config = array( 'localeSection' => 'Custom Actions: MediaInfo' ); $this->JSconfig = array( 'title' => $this->getString('Media Info'), 'iconCls' => 'fa fa-fw fa-info-circle', 'requiredUserPerms' => array('download'), "popup" => true, 'width' => 500 ); } function getString($s) { return S::safeJS(\FileRun\Lang::t($s, $this->config['localeSection'])); } function run() { global $fm; /* \FileRun\MetaTypes::$debug=true; global $db; //$db->debug=1; \FileRun\MetaTypes::auto($this->data['filePath']);exit(); */ //asdf(\FileRun\Media\Image\Image::fromFile($this->data['filePath'])->getXmp()->dom->saveHTML()); /* $rec = \FileRun\Media\Image\Image::fromFile($this->data['filePath'])->getReconcile(); $rec->debug=true; asdf($rec->get('DateCreated')); */ $getID3 = new getID3; $fInfo = $getID3->analyze($this->data['filePath']); //asdf($fInfo); require($this->path."/display.php"); } function displayRow($title, $value) { $tmp = ''; if (is_array($value)) { foreach($value as $v) { $tmp .= '<div>'; $tmp .= S::safeHTML(S::forHTML($v)); $tmp .= '</div>'; } } else { $tmp = S::safeHTML(S::forHTML($value)); } if (strlen($tmp) > 0 && $tmp != "0") { echo '<tr>'; echo '<td>'.$title.'</td>'; echo '<td>'.$tmp.'</td>'; echo '</tr>'; } } } <file_sep><?php $getID3 = new getID3; $fInfo = $getID3->analyze($this->data['filePath']); $URL = $config['url']['root']."/?module=custom_actions&action=video_player&method=stream&path=".S::forURL($this->data['relativePath']); ?> <html> <head> <title></title> <style> body { border: 0; margin: 0; padding: 0; overflow: hidden; } video { position: absolute; min-width: 100%; min-height: 100%; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style> </head> <body> <script> var videoSize = { width: parseInt('<?php echo $fInfo['video']['resolution_x']?:0; ?>'), height: parseInt('<?php echo $fInfo['video']['resolution_y']?:0; ?>') }; var html = '<video controls="controls" autoplay="autoplay"'; if (window.innerWidth < window.innerHeight) { var width = videoSize.width; if (videoSize.width > window.innerWidth) { width = window.innerWidth; } html += ' width="'+width+'"'; } else { var height = videoSize.height; if (videoSize.height > window.innerHeight) { height = window.innerHeight; } html += ' height="'+height+'"'; } html += ' src="<?php echo $URL?>"></video>'; document.write(html); </script> </body> </html><file_sep><?php include_once realpath($_SERVER["DOCUMENT_ROOT"])."/setting/config.php"; ?> <?php for ($x = 0; $x < 2; $x++){ $v[$x] = htmlentities($_POST['v'.$x], ENT_QUOTES, "UTF-8"); } emailValid($v[0]); passwordValid($v[1]); if ($encrypt_u_pwd_s == 1){ $v[1] = creatingHash_Nev($v[1]); $u[0] = mysqli_query($connect5, "SELECT * FROM `user` WHERE `u_email`='".$v[0]."' AND `u_level` < '1000000'"); $u[1] = mysqli_num_rows($u[0]); if ($u[1] == 1){ while($r = mysqli_fetch_array($u[0])){ $pwd = $r['<PASSWORD>']; $phn = $r['u_mphone']; $lel = $r['u_level']; $uid = $r['u_id']; $ugr = $r['gr_id']; } }else{ echo 'Whether you has been banned or this account has been deleted!'; exit(); } if (validUserandPassin($v[1],$pwd) == true){ $_SESSION['uema'] = $v[0]; $_SESSION['upws'] = $v[1]; $_SESSION['uphn'] = $phn; $_SESSION['uuse'] = explode('@',$_SESSION['uema']); $_SESSION['ulev'] = $lel; $_SESSION['uid'] = $uid; $_SESSION['grid'] = $ugr; echo '<script type="text/javascript"> $("#formGetin").load("'.$url_s.'page/mainpage/insideloginbox.php"); $("#alreadylogin").load("'.$url_s.'page/mainpage/insidenavigation.php"); $("#loadingPage").load("'.$url_s.'page/mainpage/index/insided.php"); $("#messageInfo").html(""); </script>'; exit(); }else{ echo 'Email/password is invalid'; exit(); } }else{ $v[1] = creatingHash_Nev($v[1]); // Check user $u[0] = mysqli_query($connect5, "SELECT * FROM `user` WHERE `u_email`='".$v[0]."' AND `u_password`='".$v[1]."' AND `u_level` < '1000000'"); $u[1] = mysqli_num_rows($u[0]); if ($u[1] == 1){ while($r = mysqli_fetch_array($u[0])){ $_SESSION['ulev'] = $r['u_level']; $_SESSION['uid'] = $r['u_id']; $_SESSION['grid'] = $r['gr_id']; } $_SESSION['uema'] = $v[0]; $_SESSION['upws'] = $v[1]; $_SESSION['uuse'] = explode('@',$_SESSION['uema']); echo '<script type="text/javascript"> $("#formGetin").load("'.$url_s.'page/mainpage/insideloginbox.php"); $("#alreadylogin").load("'.$url_s.'page/mainpage/insidenavigation.php"); $("#loadingPage").load("'.$url_s.'page/mainpage/index/insided.php"); $("#messageInfo").html(""); </script>'; exit(); }else{ echo 'Email/password is invalid'; exit(); } } ?> <file_sep><?php require_once $_SERVER['DOCUMENT_ROOT']."/setting/control.php"; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <?php require_once $_phpPath."page/_layout/_head.php"; ?> <?php require_once $_phpPath."page/_layout/_body.php"; ?> </html><file_sep><?php echo '<script>function privateIndexJS(){return;}</script>'; ?><file_sep><?php class custom_markdown_viewer { var $localeSection = 'Custom Actions: Markdown Viewer'; function init() { $this->JSconfig = array( "title" => \FileRun\Lang::t("Markdown Viewer", $this->localeSection), 'iconCls' => 'fa fa-fw fa-quote-right', 'extensions' => array('md'), "popup" => true, "requiredUserPerms" => array("download") ); } function run() { \FileRun::checkPerms("download"); $this->data['fileContents'] = file_get_contents(S::forFS($this->data['filePath'])); $enc = mb_list_encodings(); if ($_REQUEST['charset'] && in_array($_REQUEST['charset'], $enc)) { $this->data['fileContents'] = S::convert2UTF8($this->data['fileContents'], $_REQUEST['charset']); } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link href="<?php echo $this->url;?>/markdown.css" rel="stylesheet" /> </head> <body class="markdown-body"> <?php echo \FileRun\Utils\Markup\Markdown::toHTML($this->data['fileContents']);?> </body> </html> <?php \FileRun\Log::add(false, "preview", array( "relative_path" => $this->data['relativePath'], "full_path" => $this->data['filePath'], "method" => "Markdown Viewer" )); } }<file_sep> -- phpMyAdmin SQL Dump -- version 3.5.2.2 -- http://www.phpmyadmin.net -- -- Host: localhost -- Generation Time: Dec 09, 2016 at 05:40 PM -- Server version: 10.0.22-MariaDB -- PHP Version: 5.2.17 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: `u285953378_permi` -- -- -------------------------------------------------------- -- -- Table structure for table `ActionPermission` -- CREATE TABLE IF NOT EXISTS `ActionPermission` ( `ActPerId` int(255) NOT NULL AUTO_INCREMENT, `UserId` int(255) NOT NULL, `GroupId` int(255) NOT NULL, `PageId` int(255) NOT NULL, `PermissionId` int(255) NOT NULL, `IsSuperUser` tinyint(1) NOT NULL, `ActPerAvailable` int(255) NOT NULL, PRIMARY KEY (`ActPerId`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `Error` -- CREATE TABLE IF NOT EXISTS `Error` ( `ErrorId` int(255) NOT NULL AUTO_INCREMENT, `ErrorName` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `ErrorDescription` text COLLATE utf8_unicode_ci NOT NULL, `ErrorCodeName` varchar(128) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`ErrorId`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `Group` -- CREATE TABLE IF NOT EXISTS `Group` ( `GroupId` int(255) NOT NULL AUTO_INCREMENT, `GroupName` varchar(50) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`GroupId`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `Page` -- CREATE TABLE IF NOT EXISTS `Page` ( `PageId` int(255) NOT NULL AUTO_INCREMENT, `PageUrl` varchar(512) COLLATE utf8_unicode_ci NOT NULL, `PageName` varchar(30) COLLATE utf8_unicode_ci NOT NULL, `PageAvailable` tinyint(1) NOT NULL, `PageMeta` text COLLATE utf8_unicode_ci NOT NULL, `PageIsSpecial` tinyint(1) NOT NULL, PRIMARY KEY (`PageId`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `Permission` -- CREATE TABLE IF NOT EXISTS `Permission` ( `PermissionId` int(255) NOT NULL AUTO_INCREMENT, `PermissionName` varchar(20) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`PermissionId`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `User` -- CREATE TABLE IF NOT EXISTS `User` ( `UserId` int(255) NOT NULL AUTO_INCREMENT, `UserName` varchar(50) COLLATE utf8_unicode_ci NOT NULL, `UserPassword` varchar(1024) COLLATE utf8_unicode_ci NOT NULL, `UserLevel` tinyint(1) NOT NULL, PRIMARY KEY (`UserId`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ; /*!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><?php global $app, $settings, $fm, $config; ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title></title> <link rel="stylesheet" type="text/css" href="css/style.css?v=<?php echo $settings->currentVersion;?>" /> <link rel="stylesheet" type="text/css" href="customizables/custom_actions/zamzar/style.css?v=<?php echo $settings->currentVersion;?>" /> <link rel="stylesheet" type="text/css" href="css/ext.php?v=<?php echo $settings->currentVersion;?>" /> <script type="text/javascript" src="js/min.php?extjs=1&v=<?php echo $settings->currentVersion;?>"></script> <script src="customizables/custom_actions/zamzar/app.js?v=<?php echo $settings->currentVersion;?>"></script> <script src="?module=fileman&section=utils&page=translation.js&sec=<?php echo S::forURL("Custom Actions: Zamzar")?>&lang=<?php echo S::forURL(\FileRun\Lang::getCurrent())?>"></script> <script> var URLRoot = '<?php echo S::safeJS($config['url']['root'])?>'; var path = '<?php echo S::safeJS($this->data['relativePath'])?>'; var windowId = '<?php echo S::safeJS(S::fromHTML($_REQUEST['_popup_id']))?>'; </script> <style>.ext-el-mask { background-color: white; }</style> </head> <body> <div id="selectFormat"> <div style="clear:both;margin:10px;"> <?php if (sizeof($rs['targets']) > 0){ echo self::t('Convert "%1" to:', array(S::safeHTML($this->data['fileName']))); } else { echo self::t('No conversion option found for the "%1" file type.', array(strtoupper(S::safeHTML($fm->getExtension($this->data['fileName']))))); } ?> </div> <div style="max-width:600px"> <?php foreach ($rs['targets'] as $format) { $fileTypeInfo = $fm->fileTypeInfo(false, $format['name']); ?> <div class="format" data-format="<?php echo S::safeHTML($format['name']);?>"> <img src="images/fico/<?php echo $fileTypeInfo['icon'];?>" width="96" height="96" border="0" /> <?php echo S::safeHTML(strtoupper($format['name']))?> </div> <?php } ?> </div> </div> </body> </html><file_sep><?php class custom_pdfjs { function init() { $this->localeSection = "Custom Actions: PDF Viewer"; $this->JSconfig = array( "title" => \FileRun\Lang::t("PDF Viewer", $this->localeSection), "iconCls" => 'fa fa-fw fa-file-pdf-o', "extensions" => array("pdf"), "popup" => true, "requiredUserPerms" => array("download") ); } function run() { require($this->path."/display.php"); } function download() { \FileRun::checkPerms("download"); $rs = \FileRun\Utils\Downloads::sendFileToBrowser($this->data['filePath']); if ($rs && ($rs == "unknown" || $rs == "final")) { \FileRun\Log::add(false, "preview", array( "relative_path" => $this->data['relativePath'], "full_path" => $this->data['filePath'], "method" => "PDF Viewer" )); } } }<file_sep><?php /* Edit image files with Adobe Creative Cloud */ class custom_creative_cloud { var $online = true; function init() { $this->localeSection = "Custom Actions: Creative Cloud"; $this->JSconfig = array( "title" => \FileRun\Lang::t("Creative Cloud", $this->localeSection), "iconCls" => 'fa fa-fw fa-cloud', 'icon' => 'images/icons/creative_cloud.png', "extensions" => array("jpg", "jpeg", "png"), "popup" => true, "requiredUserPerms" => array("download") ); $this->outputName = "imageOutput"; } function run() { $weblinkInfo = $this->weblinks->createForService($this->data['filePath'], false, $this->data['shareInfo']['id']); if (!$weblinkInfo) { echo "Failed to setup weblink"; exit(); } $this->data['fileURL'] = $this->weblinks->getURL(array("id_rnd" => $weblinkInfo['id_rnd'])); $this->data['saveURL'] = $this->weblinks->getSaveURL($weblinkInfo['id_rnd'], false, "creative_cloud"); require($this->path."/display.php"); \FileRun\Log::add(false, "preview", array( "relative_path" => $this->data['relativePath'], "full_path" => $this->data['filePath'], "method" => "Creative Cloud" )); } function getNewFileContents() { $fromURL = S::fromHTML($_REQUEST['fromURL']); if (!$fromURL) { echo 'No URL specified'; exit(); } return file_get_contents($fromURL); } }<file_sep><?php class custom_autodesk { var $online = true; var $authURL = 'https://developer.api.autodesk.com/authentication/v1/authenticate'; var $bucketsURL = 'https://developer.api.autodesk.com/oss/v1/buckets'; var $registerURL = 'https://developer.api.autodesk.com/viewingservice/v1/register'; var $viewURL = 'https://developer.api.autodesk.com/viewingservice/v1'; var $authData = array(); static $localeSection = 'Custom Actions: Autodesk'; function init() { $this->settings = array( array( 'key' => 'clientID', 'title' => self::t('API client ID') ), array( 'key' => 'clientSecret', 'title' => self::t('API client secret'), 'comment' => \FileRun\Lang::t('Get them from %1', 'Admin', array('<a href="https://developer.autodesk.com" target="_blank">https://developer.autodesk.com</a>')) ) ); $this->JSconfig = array( "title" => self::t("Autodesk"), 'icon' => 'images/icons/autodesk.png', "extensions" => array('3dm', '3ds', 'asm', 'cam360', 'catpart', 'catproduct', 'cgr', 'dae', 'dlv3', 'dwf', 'dwfx', 'dwg', 'dwt', 'dxf', 'exp', 'f3d', 'fbx', 'g', 'gbxml', 'iam', 'idw', 'ifc', 'ige', 'iges', 'igs', 'ipt', 'jt', 'model', 'neu', 'nwc', 'nwd', 'obj', 'prt', 'rvt', 'sab', 'sat', 'session', 'sim', 'sim360', 'skp', 'sldasm', 'sldprt', 'smb', 'smt', 'ste', 'step', 'stl', 'stla', 'stlb', 'stp', 'wire', 'x_b', 'x_t', 'xas', 'xpr'), "popup" => true, "requiredUserPerms" => array("download"), 'loadingMsg' => \FileRun\Lang::t('Loading...') ); } function isDisabled() { return (strlen(self::getSetting('clientID')) == 0) || (strlen(self::getSetting('clientSecret')) == 0); } static function getSetting($k) { global $settings; $key = 'plugins_autodesk_'.$k; return $settings->{$key}; } static function t($text, $vars = false) { return \FileRun\Lang::t($text, self::$localeSection, $vars); } function run() { \FileRun::checkPerms("download"); require($this->path."/display.php"); } function start() { $http = new \GuzzleHttp\Client(); try { $response = $http->request('POST', $this->authURL, [ 'form_params' => [ 'client_id' => self::getSetting('clientID'), 'client_secret' => self::getSetting('clientSecret'), 'grant_type' => 'client_credentials', 'scope' => 'data:read data:write bucket:create' ] ]); } catch (\GuzzleHttp\Exception\ConnectException $e) { jsonFeedback(false, 'Network connection error: '.$e->getMessage()); } catch (\GuzzleHttp\Exception\ClientException $e) { $rs = json_decode($e->getResponse()->getBody()->getContents(), true); jsonFeedback(false, 'Error while authenticating with Autodesk API: '. $rs['developerMessage']); } catch (\GuzzleHttp\Exception\ServerException $e) { jsonFeedback(false, 'Server error: '.$e->getResponse()->getStatusCode()); } catch (RuntimeException $e) { jsonFeedback(false, 'Error: '.$e->getMessage()); } $rs = $response->getBody()->getContents(); if (!$rs) { jsonFeedback(false, 'Error: empty server response!'); } $rs = json_decode($rs, 1); if (!$rs['access_token']) { jsonFeedback(false, 'Error: missing acess token!'); } $this->authData = $rs; $bucketKey = 'my-bucket-'.time(); $rs = $this->createBucket($bucketKey); if (!$rs) { jsonFeedback(false, 'Error: failed to create bucket!'); } $rs = $this->uploadFile($bucketKey); $urn = $rs['objects'][0]['id']; $rs = $this->registerFileWithService($urn); if ($rs) { jsonOutput(array('success' => true, 'msg' => \FileRun\Lang::t('Processing data...'), 'urn' => base64_encode($urn), 'access_token' => $this->authData['access_token'])); } } function createBucket($key) { $http = new \GuzzleHttp\Client(); try { $response = $http->request('POST', $this->bucketsURL, [ 'headers' => [ 'Authorization' => 'Bearer ' . $this->authData['access_token'] ], 'json' => [ 'bucketKey' => $key, 'policy' => 'transient' ] ]); } catch (\GuzzleHttp\Exception\ConnectException $e) { jsonFeedback(false, 'Network connection error: '.$e->getMessage()); } catch (\GuzzleHttp\Exception\ClientException $e) { $response = $e->getResponse()->getBody()->getContents(); $rs = @json_decode($response, true); if (!is_array($rs)) { jsonFeedback(false, 'Error while creating bucket: '. $response); } jsonFeedback(false, 'Error while creating bucket: '. $rs['reason']); } catch (\GuzzleHttp\Exception\ServerException $e) { jsonFeedback(false, 'Server error: '.$e->getResponse()->getStatusCode()); } catch (RuntimeException $e) { jsonFeedback(false, 'Error: '.$e->getMessage()); } $rs = $response->getBody()->getContents(); if (!$rs) { jsonFeedback(false, 'Error creating bucket: empty server response!'); } return json_decode($rs, true); } function uploadFile($bucketKey) { global $fm; $http = new \GuzzleHttp\Client(); try { $response = $http->request('PUT', $this->bucketsURL.'/'.S::forURL($bucketKey).'/objects/'.S::forURL($this->data['fileName']), [ 'headers' => [ 'Authorization' => 'Bearer ' . $this->authData['access_token'], 'Content-Length', $fm->getFileSize($this->data['filePath']), 'Content-Type', 'application/octet-stream', 'Expect', '' ], 'body' => fopen($this->data['filePath'], 'r') ]); } catch (\GuzzleHttp\Exception\ConnectException $e) { jsonFeedback(false, 'Network connection error: '.$e->getMessage()); } catch (\GuzzleHttp\Exception\ClientException $e) { $rs = json_decode($e->getResponse()->getBody()->getContents(), true); jsonFeedback(false, 'Error while uploading file: '. $rs['reason']); } catch (\GuzzleHttp\Exception\ServerException $e) { jsonFeedback(false, 'Server error: '.$e->getResponse()->getStatusCode()); } catch (RuntimeException $e) { jsonFeedback(false, 'Error: '.$e->getMessage()); } $rs = $response->getBody()->getContents(); if (!$rs) { jsonFeedback(false, 'Error uploading file: empty server response!'); } \FileRun\Log::add(false, "preview", array( "relative_path" => $this->data['relativePath'], "full_path" => $this->data['filePath'], "method" => "Autodesk" )); return json_decode($rs, true); } function registerFileWithService($urn) { $http = new \GuzzleHttp\Client(); try { $response = $http->request('POST', $this->registerURL, [ 'headers' => [ 'Authorization' => 'Bearer ' . $this->authData['access_token'] ], 'json' => ['urn' => base64_encode($urn)] ]); } catch (\GuzzleHttp\Exception\ConnectException $e) { jsonFeedback(false, 'Network connection error: '.$e->getMessage()); } catch (\GuzzleHttp\Exception\ClientException $e) { $rs = json_decode($e->getResponse()->getBody()->getContents(), true); jsonFeedback(false, 'Error while registering file with service: '. $rs['reason']); } catch (\GuzzleHttp\Exception\ServerException $e) { jsonFeedback(false, 'Server error: '.$e->getResponse()->getStatusCode()); } catch (RuntimeException $e) { jsonFeedback(false, 'Error: '.$e->getMessage()); } $rs = $response->getBody()->getContents(); if (!$rs) { jsonFeedback(false, 'Error registering file: empty server response!'); } return json_decode($rs, true); } function checkStatus() { $urn = S::fromHTML($_REQUEST['urn']); $access_token = S::fromHTML($_REQUEST['access_token']); $http = new \GuzzleHttp\Client(); try { $response = $http->request('GET', $this->viewURL.'/'.$urn.'/status', [ 'headers' => [ 'Authorization' => 'Bearer ' . $access_token ], 'json' => ['urn' => base64_encode($urn)] ]); } catch (\GuzzleHttp\Exception\ConnectException $e) { jsonFeedback(false, 'Network connection error: '.$e->getMessage()); } catch (\GuzzleHttp\Exception\ClientException $e) { $rs = json_decode($e->getResponse()->getBody()->getContents(), true); jsonFeedback(false, 'Error checking status: '. $rs['reason']); } catch (\GuzzleHttp\Exception\ServerException $e) { jsonFeedback(false, 'Server error: '.$e->getResponse()->getStatusCode()); } catch (RuntimeException $e) { jsonFeedback(false, 'Error: '.$e->getMessage()); } $rs = $response->getBody()->getContents(); if (!$rs) { jsonFeedback(false, 'Error checking status: empty server response!'); } $rs = json_decode($rs, true); $percent = strstr($rs['success'], '%', true); jsonOutput(array('success' => true, 'data' => $rs, 'percent' => $percent)); } }<file_sep><?php class custom_onlyoffice { var $online = true; var $outputName = 'content'; var $canEdit = array( 'doc', 'docx', 'odt', 'rtf', 'txt', 'xls', 'xlsx', 'ods', 'csv', 'ppt', 'pptx', 'odp' ); function init() { $this->settings = array( array( 'key' => 'serverURL', 'title' => self::t('ONLYOFFICE server URL'), 'comment' => self::t('Download and install %1', array('<a href="https://github.com/ONLYOFFICE/DocumentServer" target="_blank">ONLYOFFICE DocumentServer</a>')) ) ); $this->JSconfig = array( "title" => self::t("ONLYOFFICE"), "popup" => true, 'icon' => 'images/icons/onlyoffice.png', "loadingMsg" => self::t('Loading document in ONLYOFFICE. Please wait...'), 'useWith' => array( 'office' ), "requiredUserPerms" => array( "download", "upload" ), "createNew" => array( "title" => self::t("Document with ONLYOFFICE"), "options" => array( array( "fileName" => self::t("New Document.docx"), "title" => self::t("Word Document"), "iconCls" => 'fa fa-fw fa-file-word-o' ), array( "fileName" => self::t("New Spreadsheet.xlsx"), "title" => self::t("Spreadsheet"), "iconCls" => 'fa fa-fw fa-file-excel-o' ), array( "fileName" => self::t("New Presentation.pptx"), "title" => self::t("Presentation"), "iconCls" => 'fa fa-fw fa-file-powerpoint-o' ) ) ) ); } function isDisabled() { return (strlen(self::getSetting('serverURL')) == 0); } static function getSetting($k) { global $settings; $key = 'plugins_onlyoffice_'.$k; return $settings->{$key}; } static function t($text, $vars = false) { $section = 'Custom Actions: ONLYOFFICE'; return \FileRun\Lang::t($text, $section, $vars); } function getNewFileContents() { $body_stream = file_get_contents("php://input"); if ($body_stream === false) {return false;} $this->POST = json_decode($body_stream, true); if ($this->POST["status"] != 2) {return false;} return file_get_contents($this->POST["url"]); } function saveFeedback($success, $message) { if ($this->POST["status"] != 2) { //ONLYOFFICE makes various calls to the save URL exit('{"error":0}'); } if ($success) { exit('{"error":0}'); } else { exit($message); } } function createBlankFile() { global $myfiles, $fm; if (!\FileRun\Perms::check('upload')) {exit();} $ext = $fm->getExtension($this->data['fileName']); if (!in_array($ext, $this->canEdit)) { jsonOutput(array("rs" => false, "msg" => self::t('The file extension needs to be one of the following: %1', array(implode(', ', $this->canEdit))))); } if (file_exists($this->data['filePath'])) { jsonOutput(array("rs" => false, "msg" => self::t('A file with the specified name already exists. Please try again.'))); } $src = gluePath($this->path, 'blanks/blank.'.$ext); $rs = $myfiles->newFile($fm->dirname($this->data['relativePath']), $this->data['fileName'], $src); if ($rs) { jsonOutput(array("rs" => true, 'path' => $this->data['relativePath'], "filename" => $this->data['fileName'], "msg" => self::t("Blank file created successfully"))); } else { jsonOutput(array("rs" => false, "msg" => $myfiles->error['msg'])); } } function run() { global $fm; \FileRun::checkPerms("download"); if (\FileRun\Perms::check('upload') && (!$this->data['shareInfo'] || ($this->data['shareInfo'] && $this->data['shareInfo']['perms_upload']))) { $weblinkInfo = $this->weblinks->createForService($this->data['filePath'], false, $this->data['shareInfo']['id']); if (!$weblinkInfo) { echo "Failed to setup saving weblink"; exit(); } $saveURL = $this->weblinks->getSaveURL($weblinkInfo['id_rnd'], false, "onlyoffice"); } else { $saveURL = ""; } $extension = $fm->getExtension($this->data['fileName']); if (in_array($extension, array('docx', 'doc','odt','txt','rtf','html','htm','mht','epub','pdf','djvu','xps'))) { $docType = 'text'; } else if (in_array($extension, array('xlsx','xls','ods','csv'))) { $docType = 'spreadsheet'; } else { $docType = 'presentation'; } $url = $this->weblinks->getURL(array('id_rnd' => $weblinkInfo['id_rnd'], 'download' => 1)); if (!$url) { echo "Failed to setup weblink"; exit(); } //add the action to the user activity log \FileRun\Log::add(false, "preview", array( "relative_path" => $this->data['relativePath'], "full_path" => $this->data['filePath'], "method" => "ONLYOFFICE" )); $mode = 'view'; if (in_array($extension, $this->canEdit)) { $mode = 'edit'; } global $auth; $author = \FileRun\Users::formatFullName($auth->currentUserInfo); $fileSize = \FM::getFileSize($this->data['filePath']); $documentKey = substr($fileSize.md5($this->data['filePath']), 0, 20); ?> <html> <head> <title></title> <style> body { border: 0; margin: 0; padding: 0; overflow:hidden; } </style> </head> <body> <div id="placeholder"></div> <script type="text/javascript" src="<?php echo self::getSetting('serverURL');?>/web-apps/apps/api/documents/api.js"></script> <script> var innerAlert = function (message) { if (console && console.log) console.log(message); }; var onReady = function () { innerAlert("Document editor ready"); }; var onDocumentStateChange = function (event) { var title = document.title.replace(/\*$/g, ""); document.title = title + (event.data ? "*" : ""); }; var onError = function (event) { if (event) innerAlert(event.data); }; var docEditor = new DocsAPI.DocEditor("placeholder", { "documentType": "<?php echo $docType;?>", "type": "desktop", "document": { "fileType": "<?php echo $extension;?>", "key": "<?php echo $documentKey;?>", "title": "<?php echo \S::safeJS($this->data['fileName']);?>", "url": "<?php echo \S::safeJS($url);?>", "info": { "author": "<?php echo \S::safeJS($author);?>" } }, "editorConfig": { "mode": '<?php echo $mode;?>', "lang": '<?php echo $this->getShortLangName(\FileRun\Lang::getCurrent());?>', "callbackUrl": "<?php echo \S::safeJS($saveURL);?>", "user": { "firstname": "<?php echo \S::safeJS($auth->currentUserInfo['name']);?>", "id": "<?php echo \S::safeJS($auth->currentUserInfo['id']);?>", "lastname": "<?php echo \S::safeJS($auth->currentUserInfo['name2']);?>" } }, "customization": { 'about': false, 'comments': false, 'feedback': false, 'goback': false }, "events": { 'onReady': onReady, 'onDocumentStateChange': onDocumentStateChange, 'onError': onError } }); </script> </body> </html> <?php } function getShortLangName($langName) { $codes = array( 'basque' => 'eu', 'brazilian portuguese' => 'pt', 'chinese traditional' => 'zh', 'chinese' => 'zh', 'danish' => 'da', 'dutch' => 'nl', 'english' => 'en', 'finnish' => 'fi', 'french' => 'fr', 'german' => 'de', 'italian' => 'it', 'polish' => 'pl', 'romanian' => 'ro', 'russian' => 'ru', 'spanish' => 'es', 'swedish' => 'sv', 'turkish' => 'tr' ); return $codes[$langName]; } }<file_sep>FR.initTree = function() { var t = new Ext.tree.TreePanel({ id: 'FR-Tree-Panel', region: 'center', enableDD: !User.perms.read_only, ddGroup: 'TreeDD', dropConfig: {appendOnly:true}, bodyStyle: 'padding-top:1px;padding-bottom:30px;', animate: true, autoScroll: true, rootVisible: false, lines: false, useArrows: true, listeners: { 'afterrender': function () { if (User.perms.upload) { FlowUtils.DropZoneManager.add({ domNode: FR.UI.tree.panel.el.dom, overClass: 'x-tree-drag-append', findTarget: function (e) { var n, el = Ext.get(e.target); if (el && !el.hasClass('x-tree-node-el')) {el = el.parent('div.x-tree-node-el');} if (!el) {return false;} var treeNodeId = el.getAttribute('tree-node-id', 'ext'); if (!treeNodeId) {return false;} var treeNode = FR.UI.tree.panel.getNodeById(treeNodeId); if (!treeNode) {return false;} if (['myfiles', 'sharedFolder'].indexOf(treeNode.attributes.section) != -1) { if (!treeNode.attributes.perms || treeNode.attributes.perms.upload) { return {el: el.dom, node: treeNode}; } } }, onDrop: function (e, target) { var up = new FR.components.uploadPanel({ targetPath: target.node.getPath('pathname'), dropEvent: e }); FR.UI.uploadWindow(FR.T('Upload to "%1"').replace('%1', target.node.text), up); }, scope: this }); } if (User.perms.alter) { FR.UI.tree.panel.on('nodedragover', function (e) { if (FR.currentSection == 'trash' || FR.currentSection == 'starred' || FR.currentSection == 'search' || FR.currentSection == 'webLinked' || (e.dropNode && e.dropNode.attributes.readonly) || (e.target.attributes.perms && (!e.target.attributes.perms.alter && !e.target.attributes.perms.upload)) || (FR.currentPath == e.target.getPath('pathname')) ) { e.cancel = true; return false; } }); FR.UI.tree.panel.on('beforenodedrop', function (drop) { FR.actions.move(drop, drop.target.getPath('pathname')); return false; }); } }, scope: this } }); FR.UI.tree.panel = t; var ui = FR.components.TreeNodeCustomUI; var r = new Ext.tree.TreeNode({pathname: 'ROOT', allowDrag: false, allowDrop: false}); t.setRootNode(r); FR.UI.tree.root = r; t.getSelectionModel().on('selectionchange', function(selectionModel, treeNode) { FR.UI.tree.onSelectionChange(selectionModel, treeNode); }); t.getSelectionModel().on('beforeselect', function(selectionModel, treeNode) { if (treeNode.attributes.section == 'userWithShares') {treeNode.expand();if (treeNode.loaded) {treeNode.firstChild.select();}return false;} if (!treeNode.attributes.pathname) {return false;} }); FR.UI.tree.loader = new Ext.tree.TreeLoader({ dataUrl: this.myfilesBaseURL+'&page=tree', baseAttrs: {uiProvider: ui}, listeners: {'beforeload': function(loader, node){loader.baseParams.path = node.getPath('pathname');}} }); FR.UI.tree.searchResultsNode = new Ext.tree.TreeNode({ text: FR.T('Search Results'), readonly: true, uiProvider: ui, leaf: false, allowDrag: false, allowDrop: false, hidden: true, iconCls: 'fa-search icon-gray', pathname: 'SEARCH', section: 'search' }); r.appendChild(FR.UI.tree.searchResultsNode); FR.UI.tree.homeFolderNode = new Ext.tree.AsyncTreeNode({ text: FR.T('My Files'), pathname: 'HOME', section: 'myfiles', iconCls: 'fa-folder', homefolder: true, allowDrag: false, allowDrop: !User.perms.read_only, custom: FR.homeFolderCfg.customAttr, loader: FR.UI.tree.loader, uiProvider: ui }); r.appendChild(FR.UI.tree.homeFolderNode); r.appendChild(new Ext.tree.TreeNode({ text: FR.T('Photos'), pathname: 'PHOTOS', section: 'photos', iconCls: 'fa-picture-o', uiProvider: ui, hidden: Settings.hidePhotos, leaf: false, allowDrag: false, allowDrop: false, readonly: true })); //text: FR.T('Music'), pathname: 'MUSIC', section: 'music', iconCls: 'fa-headphones', FR.UI.tree.sharesLoader = new Ext.tree.TreeLoader({ dataUrl:FR.myfilesBaseURL+'&page=tree_shares&nocache=1', baseAttrs: {uiProvider: ui}, listeners: {'beforeload': function(loader, node){loader.baseParams.path = node.getPath('pathname');}} }); Ext.each(AnonShares, function(fld) { r.appendChild(new Ext.tree.AsyncTreeNode(Ext.apply(fld, { readonly: true, allowDrag: false, allowDrop: fld.perms.upload, loader: FR.UI.tree.sharesLoader, section: 'sharedFolder', uiProvider: ui }))); }); Ext.each(Sharing, function(usr) { r.appendChild(new Ext.tree.AsyncTreeNode({ text: usr.name, pathname: usr.id, section: 'userWithShares', uid: usr.id, iconCls: 'avatar', allowDrag: false, allowDrop: false, loader: FR.UI.tree.sharesLoader, uiProvider: ui })); }); FR.UI.tree.starredNode = new Ext.tree.TreeNode({ text: FR.T('Starred'), readonly: true, uiProvider: ui, leaf: false, allowDrag: false, allowDrop: false, hidden: User.perms.read_only, iconCls: 'fa-star icon-gray', pathname: 'STARRED', section: 'starred' }); r.appendChild(FR.UI.tree.starredNode); FR.UI.tree.webLinksNode = new Ext.tree.TreeNode({ text: FR.T('Shared links'), readonly: true, uiProvider: ui, leaf: false, allowDrag: false, allowDrop: false, hidden: !User.perms.weblink, iconCls: 'fa-link icon-gray', pathname: 'WLINKED', section: 'webLinked' }); r.appendChild(FR.UI.tree.webLinksNode); FR.UI.tree.trashNode = new Ext.tree.TreeNode({ text: FR.T('Trash'), readonly: true, uiProvider: ui, leaf: false, allowDrag: false, allowDrop: false, iconCls: 'fa-trash icon-gray', pathname: 'TRASH', section: 'trash' }); r.appendChild(FR.UI.tree.trashNode); if (!User.trashCount || User.perms.read_only) { FR.UI.tree.trashNode.getUI().hide(); } FR.UI.tree.getCurrentPath = function() { return this.currentSelectedNode.getPath('pathname'); }; FR.UI.tree.onSelectionChange = function(selectionModel, treeNode) { FR.UI.tree.currentSelectedNode = treeNode; if (!treeNode) {return false;} var path = treeNode.getPath('pathname'); if (path != FR.currentPath) { var section = treeNode.attributes.section; FR.UI.gridPanel.load(path); FR.currentFolderPerms = treeNode.attributes.perms ? treeNode.attributes.perms : false; FR.currentSection = treeNode.attributes.section; if (section == 'myfiles' || section == "sharedFolder") { treeNode.expand(); FR.UI.actions.searchField.setSearchFolder(FR.currentPath, treeNode.text); if (FR.UI.gridPanel.dropZone) { FR.UI.gridPanel.dropZone.unlock(); } } else { if (FR.UI.gridPanel.dropZone) { FR.UI.gridPanel.dropZone.lock(); } FR.UI.actions.searchField.setSearchFolder('/ROOT/HOME', FR.T('My Files')); } if (section == 'search') { FR.UI.tree.searchResultsNode.getUI().show(); FR.UI.tree.searchResultsNode.ensureVisible(); } if (section == 'photos') { FR.UI.gridPanel.changeView('large', true); } else { FR.UI.gridPanel.restorePreviousView(); } var gridCM = FR.UI.gridPanel.getColumnModel(); gridCM.setHidden(gridCM.getIndexById('path'), (['starred', 'webLinked', 'search'].indexOf(section) == -1)); gridCM.setHidden(gridCM.getIndexById('trash_deleted_from'), (section != 'trash')); } }; FR.UI.tree.panel.on('contextmenu', function(node, e) {FR.UI.tree.showContextMenu(node,e);}); }; FR.UI.tree.reloadNode = function(treeNode, callback) { treeNode.loaded = false; treeNode.collapse(); treeNode.expand(false, true, callback); }; FR.UI.tree.updateIcon = function(treeNode) { treeNode.getUI().updateIcons(); }; FR.UI.tree.showContextMenu = function(node, e) { FR.UI.contextMenu.event({ location: 'tree', target: node.attributes }); if (e) {e.stopEvent();} return false; }; FR.components.TreeNodeCustomUI = Ext.extend(Ext.tree.TreeNodeUI, { getIcons: function() { var n = this.node; var icons = ''; if (n.attributes.custom) { if (n.attributes.custom.share) { icons += ' <i class="fa fa-user-plus"></i>'; } if (n.attributes.custom.weblink) { icons += ' <i class="fa fa-link"></i>'; } if (n.attributes.custom.sync) { icons += ' <i class="fa fa-retweet"></i>'; } if (n.attributes.custom.notInfo) { icons += ' <i class="fa fa-bell-o"></i>'; } if (n.attributes.custom.star) { icons += ' <i class="fa fa-star-o"></i>'; } } if (n.attributes['new']) { icons += ' <i class="fa fa-asterisk icon-red"></i>'; } return icons; }, updateIcons: function() { this.frIconsNodeEl.update(this.getIcons()); }, renderElements : function(n, a, targetNode, bulkRender){ this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : ''; var showMenuTrigger = (n.attributes.section == 'myfiles' || n.attributes.section == 'sharedFolder' || n.attributes.section == 'trash'); var icons = this.getIcons(); var nel, buf = '<li class="x-tree-node">' + '<div ext:tree-node-id="'+n.id+'" class="x-tree-node-el x-tree-node-leaf x-unselectable '+(a.cls || '')+'" unselectable="on">' + '<span class="x-tree-node-indent">'+this.indentMarkup+"</span>"+ '<i class="x-tree-ec-icon fa fa-caret-right"></i>'+ '<i '+(a.uid ? 'style="background-image:url(\'a/?uid='+a.uid+'\')" class="avatar"' : 'class="x-tree-node-icon fa fa-lg fa-fw icon-silver '+(a.iconCls || "fa-folder")+'"' )+' unselectable="on"></i>'+ '<a hidefocus="on" class="x-tree-node-anchor">' + '<span unselectable="on">'+n.text+"</span>" + '<span style="color:silver">' + icons + '</span>' + "</a>" + (showMenuTrigger ? '<div class="nodeMenu"><div class="triangle"></div></div>':'') + '</div>'+ '<ul class="x-tree-node-ct" style="display:none;"></ul>'+ '</li>'; if (bulkRender !== true && n.nextSibling && (nel = n.nextSibling.ui.getEl())) { this.wrap = Ext.DomHelper.insertHtml("beforeBegin", nel, buf); } else { this.wrap = Ext.DomHelper.insertHtml("beforeEnd", targetNode, buf); } this.elNode = this.wrap.childNodes[0]; this.ctNode = this.wrap.childNodes[1]; var cs = this.elNode.childNodes; this.indentNode = cs[0]; this.ecNode = cs[1]; this.iconNode = cs[2]; this.iconNodeEl = Ext.get(this.iconNode); this.anchor = cs[3]; this.textNode = cs[3].firstChild; this.frIconsNodeEl = Ext.get(cs[3].lastChild); if (showMenuTrigger) { this.menuTriggerNode = cs[4]; Ext.get(this.menuTriggerNode).on('click', function(e) { FR.UI.tree.showContextMenu(n, e); e.stopEvent(); }); } }, updateExpandIcon : function(){ if(this.rendered){ var n = this.node,hasChild = n.hasChildNodes(); if(hasChild || n.attributes.expandable){ if (n.expanded){ Ext.fly(this.ecNode).replaceClass('fa-caret-right', 'fa-caret-down'); } else { Ext.fly(this.ecNode).replaceClass('fa-caret-down', 'fa-caret-right'); } } else { Ext.fly(this.ecNode).removeClass('fa-caret-right'); } } }, beforeLoad : function() { var i = this.iconNodeEl; i.origCSSClass = i.getAttribute('class'); i.set({'class': 'x-tree-node-icon fa fa-lg fa-fw icon-silver fa-refresh fa-spin'}); }, afterLoad : function() { this.iconNodeEl.set({'class': this.iconNodeEl.origCSSClass}); } });<file_sep><head> <?php require_once $_phpPath."page/_layout/head/_generalmeta.php"; ?> <title><?php echo $thisPageName?> | <?php echo $_siteName ?></title> <?php //require_once $_phpPath."js/js_top.php"; ?> </head><file_sep><div class="row"> <div class="row" id="registerStatus"> </div> <form class="form-horizontal col-lg-offset-2 col-lg-8" id="registerNewAccount"> <fieldset class="well bs-component"> <div class="form-group"> <label for="inputEmail" class="col-lg-2 control-label">Email</label> <div class="col-lg-10"> <input type="text" class="form-control" id="inputEmail" placeholder="Email" name="registerEmail"> <label class="control-label bold" for="inputEmail" id="inputEmailStatus">&nbsp;</label> </div> </div> <div class="form-group"> <label for="inputPassword" class="col-lg-2 control-label">Password</label> <div class="col-lg-10"> <input type="password" class="form-control" id="inputPassword" placeholder="<PASSWORD>" name="registerPassword"> <label class="control-label bold" for="inputPassword" id="inputPasswordStatus">&nbsp;</label> </div> </div> <div class="form-group"> <label for="inputRetypePassword" class="col-lg-2 control-label">Retype Password</label> <div class="col-lg-10"> <input type="password" class="form-control" id="inputRetypePassword" placeholder="<PASSWORD>" name="registerRetypePassword"> <label class="control-label bold" for="inputRetypePassword" id="inputRetypePasswordStatus">&nbsp;</label> </div> </div> <div class="form-group"> <div class="checkbox"> <label class="col-lg-12 control-label text-center"> <input type="checkbox" name="registerRuleAccepted" id="registerRuleAccepted"> <span id="registerRuleAcceptedStatus bold"> By signing up, you agree to the <?php echo $_siteName?> Service Terms & Conditions and the Privacy Policy. </span> </label> </div> </div> <div class="form-group"> <div class="col-lg-12 float-right text-right"> <a class="btn btn-primary" id="submitNewAccount">Submit</a> </div> </div> <!--<div class="form-group"> <div class="col-lg-10 col-lg-offset-2"> <button type="reset" class="btn btn-default">Cancel</button> <button type="submit" class="btn btn-primary">Submit</button> </div> </div>--> </fieldset> </form> </div><file_sep><?php class custom_zoho { var $online = true; static $localeSection = "Custom Actions: Zoho"; var $writerExtensions = array("doc", "docx", "html", "htm", "rtf", "txt", "odt"); var $sheetExtensions = array("xls", "xlsx", "sxc", "csv", "ods", "tsv"); var $showExtensions = array("ppt", "pptx", "pps", "odp", "sxi", "ppts", "ppsx"); var $writerURL = "https://writer.zoho.com/writer/remotedoc.im"; var $sheetURL = "https://sheet.zoho.com/sheet/remotedoc.im"; var $showURL = "https://show.zoho.com/show/remotedoc.im"; function init() { $this->settings = array( array( 'key' => 'APIKey', 'title' => self::t('API key'), 'comment' => \FileRun\Lang::t('Get it from %1', 'Admin', array('<a href="https://zapi.zoho.com" target="_blank">https://zapi.zoho.com</a>')) ) ); $this->JSconfig = array( "title" => self::t("Zoho Editor"), 'icon' => 'images/icons/zoho.png', "extensions" => array_merge($this->writerExtensions, $this->sheetExtensions, $this->showExtensions), "popup" => true, "requiredUserPerms" => array("download", 'upload'), "createNew" => array( "title" => self::t("Document with Zoho"), "options" => array( array( "fileName" => self::t("New Document.odt"), "title" => self::t("Word Document"), "icon" => 'images/icons/zwriter.png' ), array( "fileName" => self::t("New Spreadsheet.ods"), "title" => self::t("Spreadsheet"), "icon" => 'images/icons/zsheet.png' ), array( "fileName" => self::t("New Presentation.odp"), "title" => self::t("Presentation"), "icon" => 'images/icons/zshow.png' ) ) ) ); } function isDisabled() { return (strlen(self::getSetting('APIKey')) == 0); } static function getSetting($k) { global $settings; $key = 'plugins_zoho_'.$k; return $settings->{$key}; } static function t($text, $vars = false) { return \FileRun\Lang::t($text, self::$localeSection, $vars); } function run() { global $fm, $auth; \FileRun::checkPerms("download"); if (\FileRun\Perms::check('upload') && (!$this->data['shareInfo'] || ($this->data['shareInfo'] && $this->data['shareInfo']['perms_upload']))) { $weblinkInfo = $this->weblinks->createForService($this->data['filePath'], false, $this->data['shareInfo']['id']); if (!$weblinkInfo) { echo "Failed to setup saving weblink"; exit(); } $saveURL = $this->weblinks->getSaveURL($weblinkInfo['id_rnd'], false, "zoho"); } else { $saveURL = ""; } $extension = $fm->getExtension($this->data['fileName']); if (in_array($extension, $this->writerExtensions)) { $url = $this->writerURL; } else if (in_array($extension, $this->showExtensions)) { $url = $this->showURL; } else { $url = $this->sheetURL; } $post = array( ['name' => 'apikey', 'contents' => self::getSetting('APIKey')], ['name' => 'username', 'contents' => $auth->currentUserInfo['name']], ['name' => 'output', 'contents' => 'url'], ['name' => 'mode', 'contents' => 'collabedit'], ['name' => 'filename', 'contents' => $this->data['fileName']], ['name' => 'format', 'contents' => $extension], ['name' => 'saveurl', 'contents' => $saveURL], ['name' => 'content', 'contents' => fopen($this->data['filePath'], 'r')] ); $d = \FileRun\MetaFields::getTable(); $docIdMetaFieldId = $d->selectOneCol('id', array(array('system', '=', 1), array('name', '=', $d->q('zoho_collab')))); $metaFileId = FileRun\MetaFiles::getId($this->data['filePath']); if ($metaFileId) { $zohoDocId = \FileRun\MetaValues::get($metaFileId, $docIdMetaFieldId); if ($zohoDocId) { $post[] = ['name' => 'documentid', 'contents' => $zohoDocId]; $post[] = ['name' => 'id', 'contents' => $zohoDocId]; } } else { $post[] = ['name' => 'id', 'contents' => uniqid(rand())]; } $http = new \GuzzleHttp\Client(); try { $response = $http->request('POST', $url, [ 'headers' => ['User-Agent' => ''], 'multipart' => $post ]); } catch (\GuzzleHttp\Exception\ConnectException $e) { jsonFeedback(false, 'Network connection error: '.$e->getMessage()); } catch (\GuzzleHttp\Exception\ClientException $e) { echo 'Server error: '.$e->getResponse()->getStatusCode(); echo $e->getMessage(); exit(); } catch (\GuzzleHttp\Exception\ServerException $e) { echo 'Server error: '.$e->getResponse()->getStatusCode(); echo $e->getMessage(); exit(); } catch (RuntimeException $e) { echo 'Error: '.$e->getMessage(); exit(); } $rs = $response->getBody()->getContents(); if (!$rs) { jsonFeedback(false, 'Error uploading file: empty server response!'); } $rs = $this->parseZohoReply($rs); if ($rs['RESULT'] != "FALSE") { //save document id for collaboration if ($rs['DOCUMENTID']) { \FileRun\MetaValues::setByPath($this->data['filePath'], $docIdMetaFieldId, $rs['DOCUMENTID']); } \FileRun\Log::add(false, "preview", array( "relative_path" => gluePath($this->data['relativePath'], $this->data['fileName']), "full_path" => $this->data['filePath'], "method" => "Zoho" )); header("Location: ".$rs['URL'].""); exit(); } else { echo "<strong>Zoho:</strong>"; echo "<div style=\"margin:5px;border:1px solid silver;padding:5px;overflow:auto;\"><pre>"; echo $response; if (strstr($rs['warning'], "unable to import content")) { echo "\r\n\r\nZoho.com service does not support this type of documents or was not able to access this web server."; } else { echo $response; } echo "</pre></div>"; } } function createBlankFile() { global $myfiles, $fm; if (!\FileRun\Perms::check('upload')) {exit();} if (file_exists($this->data['filePath'])) { jsonOutput(array("rs" => false, "msg" => self::t('A file with the specified name already exists. Please try again.'))); } $rs = $myfiles->newFile($fm->dirname($this->data['relativePath']), $this->data['fileName'], false, ""); if ($rs) { jsonOutput(array("rs" => true, 'path' => $this->data['relativePath'], "filename" => $this->data['fileName'], "msg" => self::t("Blank file created successfully"))); } else { jsonOutput(array("rs" => false, "msg" => $myfiles->error['msg'])); } } function getNewFileContents() { if ($_FILES['content']['tmp_name']) { return file_get_contents($_FILES['content']['tmp_name']); } } function parseZohoReply($reply) { $lines = explode("\n", $reply); $rs = array(); foreach ($lines as $line) { $line = trim($line); $p = strpos($line, "="); $key = substr($line, 0, $p); $val = substr($line, $p+1); if (strlen($key) > 0) { $rs[$key] = $val; } } return $rs; } }<file_sep><?php class custom_webodf { function init() { $this->localeSection = "Custom Actions: OpenDocument Viewer"; $this->JSconfig = array( "title" => \FileRun\Lang::t("OpenDocument Viewer", $this->localeSection), 'iconCls' => 'fa fa-fw fa-file-text-o', "extensions" => array("odt", "ods", "odp"), "popup" => true, "requiredUserPerms" => array("download") ); } function run() { require($this->path."/display.php"); } function download() { \FileRun::checkPerms("download"); \FileRun\Utils\Downloads::sendFileToBrowser($this->data['filePath']); \FileRun\Log::add(false, "preview", array( "relative_path" => $this->data['relativePath'], "full_path" => $this->data['filePath'], "method" => "OpenDocument Viewer" )); } }<file_sep><?php class custom_contact_sheet { function init() { $this->config = array( 'localeSection' => 'Custom Actions: Photo Proof Sheet' ); $this->JSconfig = array( 'title' => $this->getString('Create photo proof sheet'), 'iconCls' => 'fa fa-fw fa-th', 'requiredUserPerms' => array('download'), "ajax" => true, 'width' => 400, 'height' => 400, 'multiple' => true, 'onlyMultiple' => true ); } function isDisabled() { global $settings; return !$settings->thumbnails_imagemagick; } function getString($s, $v = false) { return S::safeJS(\FileRun\Lang::t($s, $this->config['localeSection'], $v)); } function run() { global $settings, $fm, $myfiles, $config; if (stripos($this->data['relativePath'], '/ROOT/HOME') === false) { $this->data['relativePath'] = '/ROOT/HOME'; } if (sizeof($_POST['paths']) < 2) { exit('You need to select at least two files'); } $imagemagick_convert = $settings->thumbnails_imagemagick_path; $filename = $fm->basename($imagemagick_convert); $graphicsMagick = false; if (in_array($filename, array('gm', 'gm.exe'))) { $graphicsMagick = true; $imagemagick_convert = $imagemagick_convert.' convert'; } $cmd = str_replace('convert', 'montage', $imagemagick_convert); $cmd .= " -label \"%f\" -font Arial -pointsize 20 -background \"#ffffff\" -fill \"black\" -strip -define jpeg:size=600x500 -geometry 600x500+2+2"; if (!$graphicsMagick) { if ($config['imagemagick_limit_resources']) { $cmd .= " -limit area 20mb"; $cmd .= " -limit disk 500mb"; } if (!$config['imagemagick']['no_auto_orient']) { $cmd .= " -auto-orient"; } } if (sizeof($_POST['paths']) > 8) { $cmd .= ' -tile 2x4'; } else { $cmd .= ' -tile 2x'; } foreach ($_POST['paths'] as $relativePath) { $relativePath = S::fromHTML($relativePath); if (!\FileRun\Files\Utils::isCleanPath($relativePath)) { echo 'Invalid path!'; exit(); } if (\FileRun\Files\Utils::isSharedPath($relativePath)) { $pathInfo = \FileRun\Files\Utils::parsePath($relativePath); $shareInfo = \FileRun\Share::getInfoById($pathInfo['share_id']); if (!$shareInfo['perms_download']) { jsonOutput(array('success' => false, 'msg' => $this->getString('You are not allowed to access the requested file!'))); } } $filePath = $myfiles->getUserAbsolutePath($relativePath); if (!file_exists($filePath)) { jsonOutput(array('success' => false, 'msg' => $this->getString('The file you are trying to process is no longer available!'))); } $filename = $fm->basename($relativePath); $ext = $fm->getExtension($filename); if ($this->isSupportedImageFile($ext)) { $cmd .= ' "'.$filePath; if (in_array($ext, array('tiff', 'tif', 'pdf', 'gif', 'ai', 'eps'))) { $cmd .= '[0]'; } $cmd .= '"'; } } $outputFilename = 'Contact_sheet_'.time().'.jpg'; $outputPath = $myfiles->getUserAbsolutePath(gluePath($this->data['relativePath'], $outputFilename)); $cmd .= ' "'.$outputPath.'"'; if ($fm->os == "win") { $cmd .= " && exit"; } else { $cmd .= " 2>&1"; } $return_text = array(); $return_code = 0; session_write_close(); exec($cmd, $return_text, $return_code); if ($return_code != 0) { jsonOutput(array('success' => false, 'msg' => $this->getString('Action failed: %1 %2', array($return_code, implode(',', $return_text))))); } else { \FileRun\Paths::addIfNotFound($outputPath); jsonOutput(array('success' => true, 'refresh' => 'true', 'highlight' => $outputFilename, 'msg' => $this->getString('Photo proof sheet successfuly created'))); } } function isSupportedImageFile($ext) { global $settings, $fm; $ext = strtolower($ext); $typeInfo = $fm->fileTypeInfo(false, $ext); if ($typeInfo['type'] == "img") { return "gd"; } if ($settings->thumbnails_imagemagick && in_array($ext, explode(",", strtolower($settings->thumbnails_imagemagick_ext)))) { return "imagemagick"; } return false; } }
d1f7d4bc40eb83e460de631e51cb6043214d663a
[ "SQL", "JavaScript", "Markdown", "Text", "PHP" ]
93
PHP
nev3rmi/PHPEasyTemplate
238a1096cc5b9ad64f0b47c360639ed87f5f1d82
c2f66bf530e932a14311edd233f84fb76fb867ea
refs/heads/master
<repo_name>mdf25/CommuMod<file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/blocks/BlockAradactiteOre.java package io.cyb3rwarri0r8.commumod.blocks; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.util.IIcon; /** * Created by noah on 5/17/14. */ public class BlockAradactiteOre extends Block { public BlockAradactiteOre() { super(Material.rock); setBlockName("aradactiteOre"); setBlockTextureName(Reference.MODID + ":" +getUnlocalizedName().substring(5)); setCreativeTab(main.modTab); setStepSound(soundTypePiston); setHardness(3.0F); setResistance(8.5F); setHarvestLevel("pickaxe", 1); } @Override public IIcon getIcon(int p_149691_1_, int p_149691_2_) { return super.getIcon(p_149691_1_, p_149691_2_); } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/blocks/BlockRuby.java package io.cyb3rwarri0r8.commumod.blocks; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.util.IIcon; /** * Created by noah on 8/22/14. */ public class BlockRuby extends Block { public BlockRuby(Material material) { super(material); setBlockName("rubyBlock"); setBlockTextureName(Reference.MODID + ":" + getUnlocalizedName().substring(5)); setCreativeTab(main.modTab); setStepSound(soundTypePiston); setHardness(3.0F); setResistance(15F); setHarvestLevel("pickaxe",1); } //Render block as icon @Override public IIcon getIcon(int par1, int par2) { return super.getIcon(par1, par2); } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/items/ItemRubyPickaxe.java package io.cyb3rwarri0r8.commumod.items; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.item.ItemPickaxe; /** * Created by noah on 8/8/14. */ public class ItemRubyPickaxe extends ItemPickaxe { public ItemRubyPickaxe(ToolMaterial material) { super(material); setUnlocalizedName("rubyPickaxe"); setTextureName(Reference.MODID + ":" + getUnlocalizedName().substring(5)); setCreativeTab(main.modTab); } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/items/food_items/FoodSuperCarrot.java package io.cyb3rwarri0r8.commumod.items.food_items; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.world.World; /** * Created by noah on 5/29/14. */ public class FoodSuperCarrot extends ItemFood { public FoodSuperCarrot(int hunger, float saturation, boolean isWolffood) { super(hunger, saturation, isWolffood); setUnlocalizedName("superCarrot"); setTextureName(Reference.MODID + ":" + getUnlocalizedName().substring(5)); setCreativeTab(main.modTab); setPotionEffect(Potion.heal.id, 5, 5, 5); } protected void onFoodEaten(ItemStack item, World world, EntityPlayer player) { player.addPotionEffect(new PotionEffect(Potion.fireResistance.id, 2400, 5)); player.addPotionEffect(new PotionEffect(Potion.heal.id, 1200, 5)); player.addPotionEffect(new PotionEffect(Potion.resistance.id, 1500, 4)); player.addPotionEffect(new PotionEffect(Potion.moveSpeed.id, 1800, 3)); } @Override public boolean hasEffect(ItemStack item) { return true; } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/items/ItemSuperbiumSword.java package io.cyb3rwarri0r8.commumod.items; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.world.World; import java.util.List; /** * Created by noah on 5/14/14. */ public class ItemSuperbiumSword extends ItemSword { public ItemSuperbiumSword(ToolMaterial material) { super(material); setUnlocalizedName("superbiumSword"); setTextureName(Reference.MODID + ":" + getUnlocalizedName().substring(5)); setCreativeTab(main.modTab); } @Override public void onUpdate(ItemStack stack, World world, Entity entity, int par4, boolean par5) { super.onUpdate(stack, world, entity, par4, par5); { EntityPlayer player = (EntityPlayer) entity; ItemStack equipped = player.getCurrentEquippedItem(); if (equipped == stack){ player.addPotionEffect(new PotionEffect(Potion.moveSpeed.id, 5, 3)); player.addPotionEffect(new PotionEffect(Potion.damageBoost.id, 5, 3)); } } } @Override public boolean hasEffect(ItemStack item) { return true; } @Override public void addInformation(ItemStack itemStack, EntityPlayer entityPlayer, List list, boolean b) { list.add("Adds amazing buffs"); super.addInformation(itemStack, entityPlayer, list, b); } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/items/ItemAradactiteHoe.java package io.cyb3rwarri0r8.commumod.items; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.item.ItemHoe; /** * Created by noah on 5/18/14. */ public class ItemAradactiteHoe extends ItemHoe { public ItemAradactiteHoe(ToolMaterial material) { super(material); setUnlocalizedName("aradactiteHoe"); setTextureName(Reference.MODID + ":" + getUnlocalizedName().substring(5)); setCreativeTab(main.modTab); } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/lib/proxy/proxyCommon.java package io.cyb3rwarri0r8.commumod.lib.proxy; import com.google.common.base.Predicates; import com.google.common.collect.Iterators; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.common.registry.GameRegistry; import io.cyb3rwarri0r8.commumod.lib.handler.ModGuiHandler; import io.cyb3rwarri0r8.commumod.entity.EntityMiner; import io.cyb3rwarri0r8.commumod.entity.TileEntityPurifier; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.entity.EnumCreatureType; import net.minecraft.world.biome.BiomeGenBase; /** * Created by noah on 5/27/14. */ public abstract class proxyCommon{ public void registerRenderers() { } public void preinit(){ } public void registerSounds() { } public void registerEntitySpawn(){ BiomeGenBase[] allBiomes = Iterators.toArray(Iterators.filter(Iterators.forArray(BiomeGenBase.getBiomeGenArray()), Predicates.notNull()), BiomeGenBase.class); System.out.println("Registering natural spawns"); EntityRegistry.addSpawn(EntityMiner.class, 10, 3, 10, EnumCreatureType.creature, BiomeGenBase.extremeHills); EntityRegistry.addSpawn(EntityMiner.class, 40, 3, 10, EnumCreatureType.creature, BiomeGenBase.extremeHillsEdge); EntityRegistry.addSpawn(EntityMiner.class, 40, 3, 10, EnumCreatureType.creature, BiomeGenBase.extremeHillsPlus); } public static void registerTileEntities() { GameRegistry.registerTileEntity(TileEntityPurifier.class, Reference.MODID + ":purifierTileEntity"); } public void registerNetwork() { NetworkRegistry.INSTANCE.registerGuiHandler(main.instance, new ModGuiHandler()); } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/entity/EntityAxe.java package io.cyb3rwarri0r8.commumod.entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.projectile.EntityThrowable; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.MovingObjectPosition.MovingObjectType; import net.minecraft.world.World; /** * Created by noah on 6/13/14. */ public class EntityAxe extends EntityThrowable { public EntityAxe(World world, double par2, double par4, double par6) { super(world, par2, par4, par6); } public EntityAxe(World par1World, EntityLivingBase par2EntityLivingBase) { super(par1World, par2EntityLivingBase); } public EntityAxe(World par1World) { super(par1World); } @Override protected void onImpact(MovingObjectPosition mop) { //If this hit's a block, continue if(mop.typeOfHit == MovingObjectType.BLOCK) { /* * You might be wondering what * all these case and break are * These are use to switch the number * mop.sideHit * * Example: * If mop.sideHit == 3 whatever is in * case 3 Happens! */ switch(mop.sideHit) { case 0: //BOTTOM mop.blockY--; break; case 1: //TOP mop.blockY++; break; case 2: //EAST mop.blockZ--; break; case 3: //WEST mop.blockZ++; break; case 4: //NORTH mop.blockX--; break; case 5: //SOUTH mop.blockX++; break; } /* This method creates the explosion! * It uses the entity (Can be null) * the three coordinates, the strength * and if it should set neighboring blocks on fire * around after exploding, the last parameter * is if it should spawn smoke particles */ this.worldObj.newExplosion(this, mop.blockX, mop.blockY, mop.blockZ, 4.0F, false, false); } //If the Server is online and works, kill this entity if (!this.worldObj.isRemote) { this.setDead(); } } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/blocks/BlockCobaltOre.java package io.cyb3rwarri0r8.commumod.blocks; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.util.IIcon; /** * Created by noah on 9/8/14. */ public class BlockCobaltOre extends Block { public BlockCobaltOre(Material material) { super(material); setBlockName("cobaltOre"); setBlockTextureName(Reference.MODID + ":" + getUnlocalizedName().substring(5)); setCreativeTab(main.modTab); setStepSound(soundTypePiston); setHardness(2.5F); setResistance(5.5F); setHarvestLevel("pickaxe",1); } @Override public IIcon getIcon(int par1, int par2) { return super.getIcon(par1, par2); } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/items/food_items/foodItems.java package io.cyb3rwarri0r8.commumod.items.food_items; import cpw.mods.fml.common.registry.GameRegistry; import io.cyb3rwarri0r8.commumod.items.ModItems; import io.cyb3rwarri0r8.commumod.lib.helpers.RegisterHelper; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; /** * Created by noah on 5/29/14. */ public class foodItems { public static Item superCarrot = new FoodSuperCarrot(5, 5, false); public static Item ticTac = new FoodTicTac(3,3,false); public static Item ticTacCase = new FoodTicTacCase(); public static void loadFood() { RegisterHelper.registerItem(superCarrot); GameRegistry.addRecipe(new ItemStack(superCarrot), "XXX", "XYX", "XXX", 'X', Blocks.gold_block, 'Y', Items.apple ); RegisterHelper.registerItem(ticTac); GameRegistry.addRecipe(new ItemStack(ticTac), " ", " Y ", " X ", 'Y', Items.dye, 'X', Items.sugar ); RegisterHelper.registerItem(ticTacCase); GameRegistry.addShapelessRecipe(new ItemStack(ticTacCase), ModItems.plastic,ModItems.plastic,ModItems.plastic,ModItems.plastic); } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/items/ItemRubyAxe.java package io.cyb3rwarri0r8.commumod.items; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemAxe; import net.minecraft.item.ItemStack; import net.minecraft.world.World; /** * Created by noah on 8/22/14. */ public class ItemRubyAxe extends ItemAxe { public ItemRubyAxe(ToolMaterial material) { super(material); setUnlocalizedName("rubyAxe"); setTextureName(Reference.MODID + ":" + getUnlocalizedName().substring(5)); setCreativeTab(main.modTab); } public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer entityPlayer) { if (!world.isRemote) { world.createExplosion(entityPlayer,1.0D,1.0D,1.0D,1.0F,true); } return itemStack; } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/lib/IconRegistry.java package io.cyb3rwarri0r8.commumod.lib; import gnu.trove.map.TMap; import gnu.trove.map.hash.THashMap; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.util.IIcon; /** * CommuMod - A Minecraft Modification * Copyright (C) 2014 Cyb3rWarri0r8 * <p/> * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * <p/> * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * <p/> * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ public class IconRegistry { private static TMap<String, IIcon> icons = new THashMap<String, IIcon>(); private IconRegistry() { } public static void addIcon(String iconName, String iconLocation, IIconRegister ir) { icons.put(iconName, ir.registerIcon(iconLocation)); } public static void addIcon(String iconName, IIcon icon) { icons.put(iconName, icon); } public static IIcon getIcon(String iconName) { return icons.get(iconName); } public static IIcon getIcon(String iconName, int iconOffset) { return icons.get(iconName + iconOffset); } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/client/CreativeTabsCommuMod.java package io.cyb3rwarri0r8.commumod.client; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.cyb3rwarri0r8.commumod.blocks.ModBlocks; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; /** * Created by noah on 5/16/14. */ public class CreativeTabsCommuMod extends CreativeTabs { public CreativeTabsCommuMod(String tabLabel) { super(tabLabel); } @Override @SideOnly(Side.CLIENT) public Item getTabIconItem() { return Item.getItemFromBlock(ModBlocks.superbiumOre); } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/blocks/BlockRubyOre.java package io.cyb3rwarri0r8.commumod.blocks; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.items.ModItems; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.item.Item; import java.util.Random; /** * Created by noah on 8/8/14. */ public class BlockRubyOre extends Block { public BlockRubyOre(Material material){ super(material); setBlockName("rubyOre"); setBlockTextureName(Reference.MODID + ":" + getUnlocalizedName().substring(5)); setCreativeTab(main.modTab); setStepSound(soundTypePiston); setHardness(3.0F); setResistance(5.0F); setHarvestLevel("pickaxe",0); } @Override public Item getItemDropped(int meta, Random random, int fortune){ return ModItems.ruby; } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/main.java package io.cyb3rwarri0r8.commumod; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.registry.EntityRegistry; import cpw.mods.fml.common.registry.LanguageRegistry; import io.cyb3rwarri0r8.commumod.blocks.ModBlocks; import io.cyb3rwarri0r8.commumod.client.CreativeTabsCommuMod; import io.cyb3rwarri0r8.commumod.entity.EntityMiner; import io.cyb3rwarri0r8.commumod.entity.ModEntities; import io.cyb3rwarri0r8.commumod.fluids.ModFluids; import io.cyb3rwarri0r8.commumod.items.ModItems; import io.cyb3rwarri0r8.commumod.items.food_items.foodItems; import io.cyb3rwarri0r8.commumod.lib.ModRecipeHandler; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.lib.handler.ConfigHandler; import io.cyb3rwarri0r8.commumod.lib.handler.ModBucketHandler; import io.cyb3rwarri0r8.commumod.lib.handler.ModEventHandler; import io.cyb3rwarri0r8.commumod.lib.proxy.proxyCommon; import io.cyb3rwarri0r8.commumod.world.modWorld; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.EnumCreatureType; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.CraftingManager; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.RecipesTools; import net.minecraft.world.biome.BiomeGenBase; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Configuration; import java.util.Iterator; import java.util.List; @Mod(modid = Reference.MODID, version = Reference.VERSION, guiFactory = Reference.GuiFactoryClass) public class main { @SidedProxy(clientSide="io.cyb3rwarri0r8.commumod.lib.proxy.proxyClient", serverSide="io.cyb3rwarri0r8.commumod.lib.proxy.proxyCommon") public static proxyCommon proxy; // Create a new creative tab public static CreativeTabs modTab = new CreativeTabsCommuMod("modTab"); // Configuration file public static Configuration configFile; @Mod.Instance(Reference.MODID) public static main instance; @Mod.EventHandler public void preinit(FMLPreInitializationEvent event) { configFile = new Configuration(event.getSuggestedConfigurationFile()); ModItems.loadItems(); ModBlocks.loadBlocks(); ModFluids.init(); ModBlocks.addBlockRecipes(); foodItems.loadFood(); modWorld.initWorldGen(); ModEntities.init(); ConfigHandler.init(configFile.getConfigFile()); proxy.registerRenderers(); proxy.registerEntitySpawn(); proxy.registerTileEntities(); proxy.registerNetwork(); proxy.preinit(); } @Mod.EventHandler public void init(FMLInitializationEvent event) { ModRecipeHandler.removeRecipes(); } @Mod.EventHandler public void load(FMLPostInitializationEvent event) { //Load the event handler here MinecraftForge.EVENT_BUS.register(new ModEventHandler()); FMLCommonHandler.instance().bus().register(new ModEventHandler()); //Load the bucket handler here ModBucketHandler.INSTANCE.buckets.put(ModFluids.pureWaterBlock, ModFluids.pureWaterBucket); ModBucketHandler.INSTANCE.buckets.put(ModFluids.retawBlock, ModFluids.retawBucket); MinecraftForge.EVENT_BUS.register(ModBucketHandler.INSTANCE); } }<file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/items/ItemRubyShovel.java package io.cyb3rwarri0r8.commumod.items; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemSpade; import net.minecraft.item.ItemStack; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.world.World; /** * Created by noah on 8/22/14. */ public class ItemRubyShovel extends ItemSpade { public ItemRubyShovel(ToolMaterial material) { super(material); setUnlocalizedName("rubyShovel"); setTextureName(Reference.MODID + ":" + getUnlocalizedName().substring(5)); setCreativeTab(main.modTab); } @Override public void onUpdate(ItemStack itemStack, World world, Entity entity, int par4, boolean par5) { super.onUpdate(itemStack,world,entity,par4,par5); { EntityPlayer player = (EntityPlayer) entity; ItemStack equipped = player.getCurrentEquippedItem(); if (equipped == itemStack) { player.addPotionEffect(new PotionEffect(Potion.digSpeed.id,6,4)); } } } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/items/ItemSuperbiumAxe.java package io.cyb3rwarri0r8.commumod.items; import io.cyb3rwarri0r8.commumod.entity.EntityAxe; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemAxe; import net.minecraft.item.ItemStack; import net.minecraft.world.World; /** * Created by noah on 5/13/14. */ public class ItemSuperbiumAxe extends ItemAxe { public ItemSuperbiumAxe(ToolMaterial material) { super(material); setUnlocalizedName("superbiumAxe"); setTextureName(Reference.MODID + ":" + getUnlocalizedName().substring(5)); setCreativeTab(main.modTab); } public ItemStack onItemRightClick(ItemStack itemStack, World world, EntityPlayer player) { if (!world.isRemote) { world.spawnEntityInWorld(new EntityAxe(world, player )); }return itemStack; } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/items/ItemSuperbiumIngot.java package io.cyb3rwarri0r8.commumod.items; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.item.Item; public class ItemSuperbiumIngot extends Item { public ItemSuperbiumIngot() { super(); setUnlocalizedName("superbiumIngot"); setTextureName(Reference.MODID + ":" + getUnlocalizedName().substring(5)); setCreativeTab(main.modTab); } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/client/gui/ModGuiConfig.java package io.cyb3rwarri0r8.commumod.client.gui; import cpw.mods.fml.client.config.GuiConfig; import io.cyb3rwarri0r8.commumod.lib.handler.ConfigHandler; import io.cyb3rwarri0r8.commumod.lib.Reference; import net.minecraft.client.gui.GuiScreen; import net.minecraftforge.common.config.ConfigElement; import net.minecraftforge.common.config.Configuration; /** * Created by noah on 8/30/14. */ public class ModGuiConfig extends GuiConfig { public ModGuiConfig(GuiScreen parentScreen) { super(parentScreen, new ConfigElement(ConfigHandler.configuration.getCategory(Configuration.CATEGORY_GENERAL)).getChildElements(), Reference.MODID, false, false, GuiConfig.getAbridgedConfigPath(ConfigHandler.configuration.toString())); } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/blocks/BlockPurifier.java package io.cyb3rwarri0r8.commumod.blocks; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.cyb3rwarri0r8.commumod.entity.TileEntityPurifier; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.block.Block; import net.minecraft.block.BlockContainer; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import java.util.Random; /** * Created by noah on 9/9/14. */ public class BlockPurifier extends BlockContainer { @SideOnly(Side.CLIENT) private IIcon top; @SideOnly(Side.CLIENT) private IIcon front; private static boolean isBurning; private final boolean isIsBurning; private final Random rand = new Random(); public BlockPurifier(boolean isActive) { super(Material.rock); isIsBurning = isActive; } @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister register) { this.blockIcon = register.registerIcon(Reference.MODID + ":purifierSide"); this.front = register.registerIcon(this.isIsBurning ? Reference.MODID+":purifierFront_on" : Reference.MODID+":purifierFront_off"); this.top = register.registerIcon(Reference.MODID + ":purifierTop"); } public IIcon getIcon(int side, int meta) { return side == 1 ? this.top : (side == 0 ? this.top : (side != meta ? this.blockIcon : this.front)); } public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int par6, float par7, float par8, float par9) { player.openGui(main.instance, 0, world, x, y, z); return true; } public Item getItemDropped(int par1, Random rand, int par3) { return Item.getItemFromBlock(ModBlocks.purifier_idle); } public Item getItem(World world, int par2, int par3, int par4) { return Item.getItemFromBlock(ModBlocks.purifier_idle); } @SideOnly(Side.CLIENT) public void onBlockAdded(World world, int x, int y, int z) { super.onBlockAdded(world, x, y, z); this.direction(world, x, y, z); } private void direction(World world, int x, int y, int z) { if ( !world.isRemote ) { Block direction = world.getBlock(x, y, z - 1); Block direction1 = world.getBlock(x, y, z + 1); Block direction2 = world.getBlock(x - 1, y, z); Block direction3 = world.getBlock(x + 1, y, z); byte byte0 = 3; if (direction.func_149730_j() && direction.func_149730_j()) { byte0 = 3; } if (direction1.func_149730_j() && direction1.func_149730_j()) { byte0 = 2; } if (direction2.func_149730_j() && direction2.func_149730_j()) { byte0 = 5; } if (direction3.func_149730_j() && direction3.func_149730_j()) { byte0 = 4; } world.setBlockMetadataWithNotify(x, y, z, byte0, 2); } } public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entity, ItemStack itemStack) { int direction = MathHelper.floor_double((double) (entity.rotationYaw * 4.0F / 360.0F) + 0.5D ) & 3; if( direction == 0) { world.setBlockMetadataWithNotify(x, y, z, 2, 2); } if( direction == 1) { world.setBlockMetadataWithNotify(x, y, z, 5, 2); } if( direction == 2) { world.setBlockMetadataWithNotify(x, y, z, 3, 2); } if( direction == 3) { world.setBlockMetadataWithNotify(x, y, z, 4, 2); } if (itemStack.hasDisplayName()) { ((TileEntityPurifier) world.getTileEntity(x, y, z)).furnaceName(itemStack.getDisplayName()); } } public static void updateBlockState(boolean burning, World world, int x, int y, int z) { int direction = world.getBlockMetadata(x, y, z); TileEntity tileEntity = world.getTileEntity(x, y, z); isBurning = true; if (burning) { world.setBlock(x, y, z, ModBlocks.purifier_active); } else { world.setBlock(x, y, z, ModBlocks.purifier_idle); } isBurning = false; world.setBlockMetadataWithNotify(x, y, z, direction, 2); if(tileEntity != null) { tileEntity.validate(); world.setTileEntity(x, y, z, tileEntity); } } public void breakBlock(World world, int x, int y, int z, Block block, int meta) { if (!isBurning) { TileEntityPurifier tileEntityPurifier = (TileEntityPurifier)world.getTileEntity(x, y, z); if (tileEntityPurifier != null) { for (int i1 = 0; i1 < tileEntityPurifier.getSizeInventory(); ++i1) { ItemStack itemstack = tileEntityPurifier.getStackInSlot(i1); if (itemstack != null) { float f = this.rand.nextFloat() * 0.8F + 0.1F; float f1 = this.rand.nextFloat() * 0.8F + 0.1F; float f2 = this.rand.nextFloat() * 0.8F + 0.1F; while (itemstack.stackSize > 0) { int j1 = this.rand.nextInt(21) + 10; if (j1 > itemstack.stackSize) { j1 = itemstack.stackSize; } itemstack.stackSize -= j1; EntityItem entityitem = new EntityItem(world, (double)((float)x + f), (double)((float)y + f1), (double)((float)z + f2), new ItemStack(itemstack.getItem(), j1, itemstack.getItemDamage())); if (itemstack.hasTagCompound()) { entityitem.getEntityItem().setTagCompound((NBTTagCompound)itemstack.getTagCompound().copy()); } float f3 = 0.05F; entityitem.motionX = (double)((float)this.rand.nextGaussian() * f3); entityitem.motionY = (double)((float)this.rand.nextGaussian() * f3 + 0.2F); entityitem.motionZ = (double)((float)this.rand.nextGaussian() * f3); world.spawnEntityInWorld(entityitem); } } } world.func_147453_f(x, y, z, block); } } super.breakBlock(world, x, y, z, block, meta); } @SideOnly(Side.CLIENT) public void randomDisplayTick(World world, int x, int y, int z, Random rand) { if (this.isIsBurning) { int l = world.getBlockMetadata(x, y, z); float f = (float)x + 0.5F; float f1 = (float)y + 0.0F + rand.nextFloat() * 6.0F / 16.0F; float f2 = (float)z + 0.5F; float f3 = 0.52F; float f4 = rand.nextFloat() * 0.6F - 0.3F; if (l == 4) { world.spawnParticle("smoke", (double)(f - f3), (double)f1, (double)(f2 + f4), 0.0D, 0.0D, 0.0D); world.spawnParticle("flame", (double)(f - f3), (double)f1, (double)(f2 + f4), 0.0D, 0.0D, 0.0D); } else if (l == 5) { world.spawnParticle("smoke", (double)(f + f3), (double)f1, (double)(f2 + f4), 0.0D, 0.0D, 0.0D); world.spawnParticle("flame", (double)(f + f3), (double)f1, (double)(f2 + f4), 0.0D, 0.0D, 0.0D); } else if (l == 2) { world.spawnParticle("smoke", (double)(f + f4), (double)f1, (double)(f2 - f3), 0.0D, 0.0D, 0.0D); world.spawnParticle("flame", (double)(f + f4), (double)f1, (double)(f2 - f3), 0.0D, 0.0D, 0.0D); } else if (l == 3) { world.spawnParticle("smoke", (double)(f + f4), (double)f1, (double)(f2 + f3), 0.0D, 0.0D, 0.0D); world.spawnParticle("flame", (double)(f + f4), (double)f1, (double)(f2 + f3), 0.0D, 0.0D, 0.0D); } } } @Override public TileEntity createNewTileEntity(World p_149915_1_, int p_149915_2_) { return new TileEntityPurifier(); } } <file_sep>/README.md CommuMod [![Build Status](https://travis-ci.org/Cyb3rWarri0r8/CommuMod.svg)](https://travis-ci.org/Cyb3rWarri0r8/CommuMod) [![Stories in Ready](https://badge.waffle.io/Cyb3rWarri0r8/CommuMod.png?label=ready&title=Ready)](https://waffle.io/Cyb3rWarri0r8/CommuMod) ===== [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/Cyb3rWarri0r8/CommuMod?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/items/ItemSuperbiumDust.java package io.cyb3rwarri0r8.commumod.items; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.item.ItemRedstone; /** * Created by noah on 5/16/14. */ public class ItemSuperbiumDust extends ItemRedstone { public ItemSuperbiumDust() { super(); setUnlocalizedName("superbiumDust"); setTextureName(Reference.MODID + ":" + getUnlocalizedName().substring(5)); setCreativeTab(main.modTab); } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/blocks/BlockAradactiteBlock.java package io.cyb3rwarri0r8.commumod.blocks; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.block.Block; import net.minecraft.block.material.Material; /** * Created by noah on 5/25/14. */ public class BlockAradactiteBlock extends Block { public BlockAradactiteBlock(Material material) { super(Material.anvil); this.setBlockName("aradactiteBlock"); this.setBlockTextureName(Reference.MODID + ":" + getUnlocalizedName().substring(5)); this.setCreativeTab(main.modTab); this.setStepSound(soundTypePiston); setHardness(3.5F); setResistance(5.5F); setHarvestLevel("pickaxe", 1); } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/blocks/BlockHydrogenTNT.java package io.cyb3rwarri0r8.commumod.blocks; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import io.cyb3rwarri0r8.commumod.entity.EntityHydrogenTNTPrimed; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.projectile.EntityArrow; import net.minecraft.init.Items; import net.minecraft.util.IIcon; import net.minecraft.world.Explosion; import net.minecraft.world.World; import java.util.Random; /** * Created by noah on 10/22/14. */ public class BlockHydrogenTNT extends Block { @SideOnly(Side.CLIENT) public IIcon top; @SideOnly(Side.CLIENT) public IIcon bottom; protected BlockHydrogenTNT() { super(Material.tnt); setCreativeTab(main.modTab); setBlockName("hydrogenTNT"); setBlockTextureName(Reference.MODID + ":" + getUnlocalizedName().substring(5)); setStepSound(soundTypeGrass); } @SideOnly(Side.CLIENT) public IIcon getIcon(int p_149691_1_, int p_149691_2_) { return p_149691_1_ == 0 ? this.bottom : (p_149691_1_ == 1 ? this.top : this.blockIcon); } public void onBlockAdded(World world, int x, int y, int z) { super.onBlockAdded(world, x, y, z); if (world.isBlockIndirectlyGettingPowered(x, y, z)) { this.onBlockDestroyedByPlayer(world, x, y, z, 1); world.setBlockToAir(x, y, z); } } public void onNeighborBlockChange(World world, int x, int y, int z, Block block) { if (world.isBlockIndirectlyGettingPowered(x, y, z)) { this.onBlockDestroyedByPlayer(world, x, y, z, 1); world.setBlockToAir(x, y, z); } } /** * Returns the quantity of items to drop on block destruction. */ public int quantityDropped(Random p_149745_1_) { return 1; } /** * Called upon the block being destroyed by an explosion */ public void onBlockDestroyedByExplosion(World p_149723_1_, int p_149723_2_, int p_149723_3_, int p_149723_4_, Explosion p_149723_5_) { if (!p_149723_1_.isRemote) { EntityHydrogenTNTPrimed hydrogenTNTPrimed = new EntityHydrogenTNTPrimed(p_149723_1_, (double)((float)p_149723_2_ + 0.5F), (double)((float)p_149723_3_ + 0.5F), (double)((float)p_149723_4_ + 0.5F), p_149723_5_.getExplosivePlacedBy()); hydrogenTNTPrimed.fuse = p_149723_1_.rand.nextInt(hydrogenTNTPrimed.fuse / 4) + hydrogenTNTPrimed.fuse / 8; p_149723_1_.spawnEntityInWorld(hydrogenTNTPrimed); } } public void onBlockDestroyedByPlayer(World p_149664_1_, int p_149664_2_, int p_149664_3_, int p_149664_4_, int p_149664_5_) { this.func_150114_a(p_149664_1_, p_149664_2_, p_149664_3_, p_149664_4_, p_149664_5_, (EntityLivingBase)null); } public void func_150114_a(World p_150114_1_, int p_150114_2_, int p_150114_3_, int p_150114_4_, int p_150114_5_, EntityLivingBase p_150114_6_) { if (!p_150114_1_.isRemote) { if ((p_150114_5_ & 1) == 1) { EntityHydrogenTNTPrimed hydrogenTNTPrimed = new EntityHydrogenTNTPrimed(p_150114_1_, (double)((float)p_150114_2_ + 0.5F), (double)((float)p_150114_3_ + 0.5F), (double)((float)p_150114_4_ + 0.5F), p_150114_6_); p_150114_1_.spawnEntityInWorld(hydrogenTNTPrimed); p_150114_1_.playSoundAtEntity(hydrogenTNTPrimed, "game.tnt.primed", 1.0F, 1.0F); } } } public boolean onBlockActivated(World p_149727_1_, int p_149727_2_, int p_149727_3_, int p_149727_4_, EntityPlayer p_149727_5_, int p_149727_6_, float p_149727_7_, float p_149727_8_, float p_149727_9_) { if (p_149727_5_.getCurrentEquippedItem() != null && p_149727_5_.getCurrentEquippedItem().getItem() == Items.flint_and_steel) { this.func_150114_a(p_149727_1_, p_149727_2_, p_149727_3_, p_149727_4_, 1, p_149727_5_); p_149727_1_.setBlockToAir(p_149727_2_, p_149727_3_, p_149727_4_); p_149727_5_.getCurrentEquippedItem().damageItem(1, p_149727_5_); return true; } else { return super.onBlockActivated(p_149727_1_, p_149727_2_, p_149727_3_, p_149727_4_, p_149727_5_, p_149727_6_, p_149727_7_, p_149727_8_, p_149727_9_); } } /** * Triggered whenever an entity collides with this block (enters into the block). Args: world, x, y, z, entity */ public void onEntityCollidedWithBlock(World p_149670_1_, int p_149670_2_, int p_149670_3_, int p_149670_4_, Entity p_149670_5_) { if (p_149670_5_ instanceof EntityArrow && !p_149670_1_.isRemote) { EntityArrow entityarrow = (EntityArrow)p_149670_5_; if (entityarrow.isBurning()) { this.func_150114_a(p_149670_1_, p_149670_2_, p_149670_3_, p_149670_4_, 1, entityarrow.shootingEntity instanceof EntityLivingBase ? (EntityLivingBase)entityarrow.shootingEntity : null); p_149670_1_.setBlockToAir(p_149670_2_, p_149670_3_, p_149670_4_); } } } public boolean canDropFromExplosion(Explosion p_149659_1_) { return false; } @SideOnly(Side.CLIENT) public void registerBlockIcons(IIconRegister p_149651_1_) { this.blockIcon = p_149651_1_.registerIcon(Reference.MODID + ":" + getUnlocalizedName().substring(5) + "_side"); this.top = p_149651_1_.registerIcon(Reference.MODID + ":" + getUnlocalizedName().substring(5) + "_top"); this.bottom = p_149651_1_.registerIcon(Reference.MODID + ":" + getUnlocalizedName().substring(5) + "_bottom"); } } <file_sep>/src/main/java/io/cyb3rwarri0r8/commumod/items/ItemSuperbiumHoe.java package io.cyb3rwarri0r8.commumod.items; import io.cyb3rwarri0r8.commumod.lib.Reference; import io.cyb3rwarri0r8.commumod.main; import net.minecraft.item.ItemHoe; /** * Created by noah on 5/27/14. */ public class ItemSuperbiumHoe extends ItemHoe { public ItemSuperbiumHoe(ToolMaterial material) { super(material); setUnlocalizedName("superbiumHoe"); setTextureName(Reference.MODID + ":" + getUnlocalizedName().substring(5)); setCreativeTab(main.modTab); } }
6299f64c1f44e7271284b17ea410dec182640baa
[ "Markdown", "Java" ]
25
Java
mdf25/CommuMod
cb8931392da4baeb0738ea29ab576ab399a60f79
321e30aa2dd60edc7ab89c4003f111f40f8136d2
refs/heads/master
<repo_name>StayCake/Toilet<file_sep>/src/main/kotlin/commands/Toilet.kt package commands import Main import hazae41.minecraft.kutils.bukkit.msg import io.github.monun.kommand.getValue import io.github.monun.kommand.node.LiteralNode import org.bukkit.Sound import org.bukkit.configuration.file.FileConfiguration import org.bukkit.entity.Player import java.io.File object Toilet { private fun getSigns() : FileConfiguration { return Main.signs } private fun getSignsloc() : File { return Main.signsloc } fun register(builder: LiteralNode) { builder.requires { playerOrNull != null } builder.then("reload") { executes { if (getSignsloc().canRead()) { getSigns().load(getSignsloc()) } player.sendMessage("리로드 완료!") player.playSound(player.location, Sound.ENTITY_PLAYER_LEVELUP, 1.0F, 1.0F) } } builder.then("delete") { then("name" to string()) { executes { ctx -> val name : String by ctx getSigns().set("signs.$name",null) getSigns().save(getSignsloc()) player.msg("통로 $name 삭제 완료!") } } requires { playerOrNull != null } executes { player.msg("대상을 입력하세요.") } } } }<file_sep>/settings.gradle rootProject.name = 'Toilet'<file_sep>/src/main/kotlin/Main.kt import commands.Toilet import hazae41.minecraft.kutils.get import io.github.monun.kommand.kommand import org.bukkit.configuration.file.YamlConfiguration import org.bukkit.plugin.Plugin import org.bukkit.plugin.java.JavaPlugin import java.io.File class Main : JavaPlugin() { companion object { lateinit var instance: Plugin private set lateinit var signs: YamlConfiguration private set lateinit var signsloc: File private set lateinit var kspYml: YamlConfiguration private set lateinit var ksp: Plugin private set } override fun onEnable() { println(String.format("[%s] - 가동 시작!", description.name)) val pl = server.pluginManager.getPlugin("KoiSupport") if (pl == null) { println(String.format("[%s] - KoiSupport 연결 실패!", description.name)) server.pluginManager.disablePlugin(this) return } server.pluginManager.registerEvents(Events(), this) val kspFile = pl.dataFolder["data"]["stats.yml"] val kspYaml = YamlConfiguration() if (!kspFile.canRead()) { println("스텟 파일 연동에 실패했습니다.") } else { kspYaml.load(kspFile) } kspYml = kspYaml ksp = pl instance = this signs = YamlConfiguration.loadConfiguration(dataFolder["signs.yml"]) signsloc = dataFolder["signs.yml"] if (!dataFolder["signs.yml"].canRead()) { dataFolder.mkdir() signs.save(signsloc) } kommand { register("Toilet") { Toilet.register(this) } } } override fun onDisable() { println(String.format("[%s] - 가동 중지.", description.name)) } }<file_sep>/src/main/kotlin/Events.kt import hazae41.minecraft.kutils.bukkit.msg import hazae41.minecraft.kutils.get import net.kyori.adventure.text.Component import net.kyori.adventure.text.TextComponent import net.kyori.adventure.text.format.TextColor import org.bukkit.ChatColor import org.bukkit.Location import org.bukkit.Material import org.bukkit.block.BlockFace import org.bukkit.block.Sign import org.bukkit.block.data.type.WallSign import org.bukkit.configuration.file.FileConfiguration import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.block.Action import org.bukkit.event.block.BlockBreakEvent import org.bukkit.event.block.SignChangeEvent import org.bukkit.event.player.PlayerInteractEvent import org.bukkit.event.player.PlayerJoinEvent import org.bukkit.event.player.PlayerQuitEvent import org.bukkit.inventory.EquipmentSlot import java.io.File val Signs = listOf( Material.ACACIA_SIGN, Material.ACACIA_WALL_SIGN, Material.BIRCH_SIGN, Material.BIRCH_WALL_SIGN, Material.CRIMSON_SIGN, Material.CRIMSON_WALL_SIGN, Material.DARK_OAK_SIGN, Material.DARK_OAK_WALL_SIGN, Material.SPRUCE_SIGN, Material.SPRUCE_WALL_SIGN, Material.JUNGLE_SIGN, Material.JUNGLE_WALL_SIGN, Material.OAK_SIGN, Material.OAK_WALL_SIGN, Material.WARPED_SIGN, Material.WARPED_WALL_SIGN ) class Events : Listener { private fun getSigns() : FileConfiguration { return Main.signs } private fun getSignsloc() : File { return Main.signsloc } private fun getYaw(side: BlockFace?) : Float { return when (side) { BlockFace.EAST -> -90F BlockFace.WEST -> 90F BlockFace.SOUTH -> 0F BlockFace.NORTH -> 180F else -> 0F } } @EventHandler private fun signPlace(e: SignChangeEvent) { val p = e.player val line1 = (e.line(0) as TextComponent).content() val line2 = (e.line(1) as TextComponent).content() val line3 = (e.line(2) as TextComponent).content() val line4 = (e.line(3) as TextComponent).content() var fn = 0 val fs = line4.filter { it.isDigit() } if (fs != "") fn = fs.toInt() if (line1 == "[광산]" && p.hasPermission("admin.setup")) { if (line2 == "") { e.block.breakNaturally() p.msg("이름을 지정해주세요.") } else { val bl = e.block.location when (line3) { "입구" -> { if (getSigns().getLocation("signs.$line2.join") != null) { e.block.breakNaturally() p.msg("이미 지정되었습니다!") } else { getSigns().set("signs.$line2.join", bl) e.line( 0, Component.text("[광산]") .color(TextColor.color(85, 255, 255)) ) e.line( 1, Component.text(line2) .color(TextColor.color(255, 170, 0)) ) e.line( 2, Component.text("클릭해서 입장하기") .color(TextColor.color(85, 255, 85)) ) if (fn > 0 && line4 != "-") { getSigns().set("signs.$line2.limit",fn) e.line( 3, Component.text("Lv.$line4 이상") ) } else if (line4 == "-") { getSigns().set("signs.$line2.persistent",true) e.line( 3, Component.text("-") ) } p.msg("$line2 입구 생성 완료!") } } "출구" -> { if (getSigns().getLocation("signs.$line2.quit") != null) { e.block.breakNaturally() p.msg("이미 지정되었습니다!") } else { getSigns().set("signs.$line2.quit",bl) e.line(0, Component.text("[광산]") .color(TextColor.color(85,255,255)) ) e.line(1, Component.text(line2) .color(TextColor.color(255,170,0)) ) e.line(2, Component.text("클릭해서 나가기") .color(TextColor.color(255,85,85)) ) p.msg("$line2 출구 생성 완료!") } } else -> { e.block.breakNaturally() p.msg("입구나 출구를 적어주세요. [세번째 줄]") } } getSigns().save(getSignsloc()) } } else if (line1 == "[이동]" && p.hasPermission("admin.setup")) { if (line2 == "") { e.block.breakNaturally() p.msg("이름을 지정해주세요.") } else { val bl = e.block.location when { listOf("1","2").contains(line3) -> { if (getSigns().getLocation("gates.$line2.join") != null) { e.block.breakNaturally() p.msg("이미 지정되었습니다!") } else { getSigns().set("gates.$line2.$line3", bl) e.line( 0, Component.text("[이동]") .color(TextColor.color(85, 255, 255)) ) e.line( 1, Component.text(line2) .color(TextColor.color(255, 170, 0)) ) e.line( 2, Component.text(if (line3 == "1") "- 클릭해서 이동하기 -" else "클릭해서 이동하기") .color(TextColor.color(85, 255, 85)) ) if (fn > 0) { getSigns().set("gates.$line2.limit",fn) e.line( 3, Component.text("Lv.$line4 이상") ) } p.msg("$line2 통로 $line3 번 생성 완료!") } } else -> { e.block.breakNaturally() p.msg("1번 또는 2번을 적어주세요.. [세번째 줄]") } } getSigns().save(getSignsloc()) } } } @EventHandler private fun act1(e: BlockBreakEvent) { val p = e.player val b = e.block if (Signs.contains(b.type)) { val sign = b.state as Sign val line1 = (sign.line(0) as TextComponent).content() val line2 = (sign.line(1) as TextComponent).content() val line3 = (sign.line(2) as TextComponent).content() val line4 = (sign.line(3) as TextComponent).content() if (line1 == "[광산]" && p.hasPermission("admin.setup")) { when (line3) { "클릭해서 입장하기" -> getSigns().set("signs.$line2.join", null) "사용 중" -> getSigns().set("signs.$line2.join", null) "클릭해서 나가기" -> getSigns().set("signs.$line2.quit", null) } if (line4 != "") { getSigns().set("signs.$line2.limit",null) getSigns().set("signs.$line2.persistent",null) } p.msg("제거 완료!") getSigns().save(getSignsloc()) } else if (line1 == "[이동]"&& p.hasPermission("admin.setup")) { getSigns().set("gates.$line2.${if (line3 == "클릭해서 이동하기") 2 else 1}",null) if (line4 != "") { getSigns().set("gates.$line2.limit",null) } p.msg("제거 완료!") getSigns().save(getSignsloc()) } } } @EventHandler private fun act2(e: PlayerInteractEvent) { val p = e.player val clb = e.clickedBlock if (Signs.contains(clb?.type) && e.action == Action.RIGHT_CLICK_BLOCK && e.hand == EquipmentSlot.HAND) { val kspFile = Main.ksp.dataFolder["data"]["stats.yml"] if (!kspFile.canRead()) { p.msg("스텟 파일 연동에 문제가 있습니다.\n관리자에게 문의하세요.") } else { Main.kspYml.load(kspFile) } val lv = Main.kspYml.getInt("${e.player.uniqueId}.MineLV") val sign = e.clickedBlock?.state as Sign val line1 = (sign.line(0) as TextComponent).content() val line2 = (sign.line(1) as TextComponent).content() val line3 = (sign.line(2) as TextComponent).content() val line4 = (sign.line(3) as TextComponent).content() var fn = 0 val fs = line4.filter { it.isDigit() } if (fs != "") fn = fs.toInt() if (line1 == "[광산]") { when (line3) { "클릭해서 입장하기" -> { val warpl = getSigns().getLocation("signs.$line2.quit") if (warpl != null) { val wallsign = warpl.block.blockData as WallSign val face = wallsign.facing when { line4 != "-" && lv >= fn -> { getSigns().set("joined.${p.uniqueId}", line2) sign.line(3, Component.text(e.player.name)) p.teleportAsync(Location(warpl.world, warpl.x + 0.5, warpl.y, warpl.z + 0.5, getYaw(face), 0F)) sign.line( 2, Component.text("사용 중") .color(TextColor.color(255, 85, 85)) ) sign.update() } line4 != "-" && lv < fn -> { p.msg("입장 조건을 만족하지 않았습니다.") } line4 == "-" -> { getSigns().set("joined.${p.uniqueId}", line2) p.teleportAsync(Location(warpl.world, warpl.x + 0.5, warpl.y, warpl.z + 0.5, getYaw(face), 0F)) } } } else { p.msg("출구가 설정되어 있지 않습니다.") } } "사용 중" -> { p.msg("이미 사용중입니다.") } "클릭해서 나가기" -> { getSigns().set("joined.${p.uniqueId}",null) val warpl = getSigns().getLocation("signs.$line2.join") val limit = getSigns().getInt("signs.$line2.limit") val persistent = getSigns().getBoolean("signs.$line2.persistent") if (warpl != null) { val wallsign = warpl.block.blockData as WallSign val face = wallsign.facing val entrysign = warpl.block.state as Sign entrysign.line(3, Component.text("")) p.teleportAsync(Location(warpl.world,warpl.x+0.5,warpl.y,warpl.z+0.5, getYaw(face), 0F)) entrysign.line(2, Component.text("클릭해서 입장하기") .color(TextColor.color(85,255,85)) ) if (limit > 0) entrysign.line(3, Component.text("Lv.$limit 이상")) if (persistent) entrysign.line(3, Component.text("-")) entrysign.update() } else { p.msg("입구가 설정되어 있지 않습니다.") } } } getSigns().save(getSignsloc()) } else if (line1 == "[이동]"){ val out = if (line3 == "클릭해서 이동하기") 1 else 2 val warpl = getSigns().getLocation("gates.$line2.$out") when { warpl != null && lv >= fn -> { val wallsign = warpl.block.blockData as WallSign val face = wallsign.facing p.teleportAsync(Location(warpl.world, warpl.x + 0.5, warpl.y, warpl.z + 0.5, getYaw(face), 0F)) } warpl != null && lv < fn -> { p.msg("이동 조건을 만족하지 않았습니다.") } else -> { p.msg("출구가 설정되어 있지 않습니다.") } } getSigns().save(getSignsloc()) } } } @EventHandler private fun quitprevent(e: PlayerQuitEvent) { val p = e.player val joined = getSigns().getString("joined.${p.uniqueId}") if (joined != null) { val entstate = getSigns().getLocation("signs.$joined.join")?.block?.state if (entstate != null) { val entsign = entstate as Sign entsign.line(3, Component.text("")) entsign.line(2, Component.text("클릭해서 입장하기") .color(TextColor.color(85,255,85)) ) entsign.update() } } } @EventHandler private fun joinretrun(e: PlayerJoinEvent) { val p = e.player val joined = getSigns().getString("joined.${p.uniqueId}") if (joined != null) { val loc = getSigns().getLocation("signs.$joined.join") getSigns().set("joined.${p.uniqueId}",null) if (loc != null) { p.teleport(Location(loc.world,loc.x+0.5,loc.y,loc.z+0.5)) } else { p.teleport(p.world.spawnLocation) } getSigns().save(getSignsloc()) p.msg("${ChatColor.RED}광산 이용 중 나가는 행위를 자제해 주세요!") } } }
8e6dc9dbb94477a8302b7a8370c0ab874b642d72
[ "Kotlin", "Gradle" ]
4
Kotlin
StayCake/Toilet
9484cdf6e4f2653e68e3bb9f5bea93768c765422
e966e239ca66a748159d3ec4de1d2611e9eb3ec9
refs/heads/main
<file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Breed extends Model { use HasFactory; protected $fillable = [ 'description', 'name', 'image_url', 'child_friendly', 'dog_friendly', 'hairless', 'health_issues', 'hypoallergenic', 'intelligence', 'short_legs', 'stranger_friendly', 'temperament', 'imperial', 'metric', 'origin', 'wikipedia_url' ]; } <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCatsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('cats', function (Blueprint $table) { $table->bigIncrements("id"); $table->bigInteger('breed_id'); $table->string("name"); $table->integer("age"); $table->bigInteger("gender_id"); $table->decimal('long', 10, 7); $table->decimal('lat', 10, 7); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('cats'); } } <file_sep><?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class BreedSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('breeds')->insert( [ [ "name" => "Abyssinian", "description" => "The Abyssinian is easy to care for, and a joy to have in your home. They’re affectionate cats and love both people and other animals.", "image_url" => "https://cdn2.thecatapi.com/images/0XYvRd7oD.jpg", "child_friendly" => 3, "dog_friendly" => 4, "hairless" => 0, "health_issues" => 2, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Active, Energetic, Independent, Intelligent, Gentle", "imperial" => "7 - 10", "metric" => "3 - 5", "origin" => "Egypt", "wikipedia_url" => "https://en.wikipedia.org/wiki/Abyssinian_(cat)", ], [ "name" => "Aegean", "description" => "Native to the Greek islands known as the Cyclades in the Aegean Sea, these are natural cats, meaning they developed without humans getting involved in their breeding. As a breed, Aegean Cats are rare, although they are numerous on their home islands. They are generally friendly toward people and can be excellent cats for families with children.", "image_url" => "https://cdn2.thecatapi.com/images/ozEvzdVM-.jpg", "child_friendly" => 4, "dog_friendly" => 4, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 4, "temperament" => "Affectionate, Social, Intelligent, Playful, Active", "imperial" => "7 - 10", "metric" => "3 - 5", "origin" => "Greece", "wikipedia_url" => "https://en.wikipedia.org/wiki/Aegean_cat", ], [ "name" => "<NAME>", "description" => "American Bobtails are loving and incredibly intelligent cats possessing a distinctive wild appearance. They are extremely interactive cats that bond with their human family with great devotion.", "image_url" => "https://cdn2.thecatapi.com/images/hBXicehMA.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Intelligent, Interactive, Lively, Playful, Sensitive", "imperial" => "7 - 16", "metric" => "3 - 7", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/American_Bobtail", ], [ "name" => "<NAME>", "description" => "Distinguished by truly unique ears that curl back in a graceful arc, offering an alert, perky, happily surprised expression, they cause people to break out into a big smile when viewing their first Curl. Curls are very people-oriented, faithful, affectionate soulmates, adjusting remarkably fast to other pets, children, and new situations.", "image_url" => "https://cdn2.thecatapi.com/images/xnsqonbjW.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Affectionate, Curious, Intelligent, Interactive, Lively, Playful, Social", "imperial" => "5 - 10", "metric" => "2 - 5", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/American_Curl", ], [ "name" => "<NAME>", "description" => "The American Shorthair is known for its longevity, robust health, good looks, sweet personality, and amiability with children, dogs, and other pets.", "image_url" => "https://cdn2.thecatapi.com/images/JFPROfGtQ.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Active, Curious, Easy Going, Playful, Calm", "imperial" => "8 - 15", "metric" => "4 - 7", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/American_Shorthair", ], [ "name" => "<NAME>", "description" => "The American Wirehair tends to be a calm and tolerant cat who takes life as it comes. His favorite hobby is bird-watching from a sunny windowsill, and his hunting ability will stand you in good stead if insects enter the house.", "image_url" => "https://cdn2.thecatapi.com/images/8D--jCd21.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Affectionate, Curious, Gentle, Intelligent, Interactive, Lively, Loyal, Playful, Sensible, Social", "imperial" => "8 - 15", "metric" => "4 - 7", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/American_Wirehair", ], [ "name" => "<NAME>", "description" => "Arabian Mau cats are social and energetic. Due to their energy levels, these cats do best in homes where their owners will be able to provide them with plenty of playtime, attention and interaction from their owners. These kitties are friendly, intelligent, and adaptable, and will even get along well with other pets and children.", "image_url" => "https://cdn2.thecatapi.com/images/k71ULYfRr.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Affectionate, Agile, Curious, Independent, Playful, Loyal", "imperial" => "8 - 16", "metric" => "4 - 7", "origin" => "United Arab Emirates", "wikipedia_url" => "https://en.wikipedia.org/wiki/Arabian_Mau", ], [ "name" => "<NAME>", "description" => "The Australian Mist thrives on human companionship. Tolerant of even the youngest of children, these friendly felines enjoy playing games and being part of the hustle and bustle of a busy household. They make entertaining companions for people of all ages, and are happy to remain indoors between dusk and dawn or to be wholly indoor pets.", "image_url" => "https://cdn2.thecatapi.com/images/_6x-3TiCA.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 4, "short_legs" => 0, "stranger_friendly" => 4, "temperament" => "Lively, Social, Fun-loving, Relaxed, Affectionate", "imperial" => "7 - 15", "metric" => "3 - 7", "origin" => "Australia", "wikipedia_url" => "https://en.wikipedia.org/wiki/Australian_Mist", ], [ "name" => "Balinese", "description" => "Balinese are curious, outgoing, intelligent cats with excellent communication skills. They are known for their chatty personalities and are always eager to tell you their views on life, love, and what you’ve served them for dinner. ", "image_url" => "https://cdn2.thecatapi.com/images/13MkvUreZ.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 1, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Affectionate, Intelligent, Playful", "imperial" => "4 - 10", "metric" => "2 - 5", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Balinese_(cat)", ], [ "name" => "Bambino", "description" => "The Bambino is a breed of cat that was created as a cross between the Sphynx and the Munchkin breeds. The Bambino cat has short legs, large upright ears, and is usually hairless. They love to be handled and cuddled up on the laps of their family members.", "image_url" => "https://cdn2.thecatapi.com/images/5AdhMjeEu.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 1, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 1, "stranger_friendly" => 3, "temperament" => "Affectionate, Lively, Friendly, Intelligent", "imperial" => "4 - 9", "metric" => "2 - 4", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Bambino_cat", ], [ "name" => "Bengal", "description" => "Bengals are a lot of fun to live with, but they're definitely not the cat for everyone, or for first-time cat owners. Extremely intelligent, curious and active, they demand a lot of interaction and woe betide the owner who doesn't provide it.", "image_url" => "https://cdn2.thecatapi.com/images/O3btzLlsO.png", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 1, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Alert, Agile, Energetic, Demanding, Intelligent", "imperial" => "6 - 12", "metric" => "3 - 7", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Bengal_(cat)", ], [ "name" => "Birman", "description" => "The Birman is a docile, quiet cat who loves people and will follow them from room to room. Expect the Birman to want to be involved in what you’re doing. He communicates in a soft voice, mainly to remind you that perhaps it’s time for dinner or maybe for a nice cuddle on the sofa. He enjoys being held and will relax in your arms like a furry baby.", "image_url" => "https://cdn2.thecatapi.com/images/HOrX5gwLS.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Affectionate, Active, Gentle, Social", "imperial" => "6 - 15", "metric" => "3 - 7", "origin" => "France", "wikipedia_url" => "https://en.wikipedia.org/wiki/Birman", ], [ "name" => "Bombay", "description" => "The the golden eyes and the shiny black coa of the Bopmbay is absolutely striking. Likely to bond most with one family member, the Bombay will follow you from room to room and will almost always have something to say about what you are doing, loving attention and to be carried around, often on his caregiver's shoulder.", "image_url" => "https://cdn2.thecatapi.com/images/5iYq9NmT1.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 4, "temperament" => "Affectionate, Dependent, Gentle, Intelligent, Playful", "imperial" => "6 - 11", "metric" => "3 - 5", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Bombay_(cat)", ], [ "name" => "<NAME>", "description" => "The British Longhair is a very laid-back relaxed cat, often perceived to be very independent although they will enjoy the company of an equally relaxed and likeminded cat. They are an affectionate breed, but very much on their own terms and tend to prefer to choose to come and sit with their owners rather than being picked up.", "image_url" => "https://cdn2.thecatapi.com/images/7isAO4Cav.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 4, "temperament" => "Affectionate, Easy Going, Independent, Intelligent, Loyal, Social", "imperial" => "8 - 18", "metric" => "4 - 8", "origin" => "United Kingdom", "wikipedia_url" => "https://en.wikipedia.org/wiki/British_Longhair", ], [ "name" => "<NAME>", "description" => "The British Shorthair is a very pleasant cat to have as a companion, ans is easy going and placid. The British is a fiercely loyal, loving cat and will attach herself to every one of her family members. While loving to play, she doesn't need hourly attention. If she is in the mood to play, she will find someone and bring a toy to that person. The British also plays well by herself, and thus is a good companion for single people.", "image_url" => "https://cdn2.thecatapi.com/images/s4wQfYoEk.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 2, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 2, "temperament" => "Affectionate, Easy Going, Gentle, Loyal, Patient, calm", "imperial" => "12 - 20", "metric" => "5 - 9", "origin" => "United Kingdom", "wikipedia_url" => "https://en.wikipedia.org/wiki/British_Shorthair", ], [ "name" => "Burmese", "description" => "Burmese love being with people, playing with them, and keeping them entertained. They crave close physical contact and abhor an empty lap. They will follow their humans from room to room, and sleep in bed with them, preferably under the covers, cuddled as close as possible. At play, they will turn around to see if their human is watching and being entertained by their crazy antics.", "image_url" => "https://cdn2.thecatapi.com/images/4lXnnfxac.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 1, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Curious, Intelligent, Gentle, Social, Interactive, Playful, Lively", "imperial" => "6 - 12", "metric" => "3 - 5", "origin" => "Burma", "wikipedia_url" => "https://en.wikipedia.org/wiki/Burmese_(cat)", ], [ "name" => "Burmilla", "description" => "The Burmilla is a fairly placid cat. She tends to be an easy cat to get along with, requiring minimal care. The Burmilla is affectionate and sweet and makes a good companion, the Burmilla is an ideal companion to while away a lonely evening. Loyal, devoted, and affectionate, this cat will stay by its owner, always keeping them company.", "image_url" => "https://cdn2.thecatapi.com/images/jvg3XfEdC.jpg", "child_friendly" => 4, "dog_friendly" => 4, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Easy Going, Friendly, Intelligent, Lively, Playful, Social", "imperial" => "6 - 13", "metric" => "3 - 6", "origin" => "United Kingdom", "wikipedia_url" => "https://en.wikipedia.org/wiki/Burmilla", ], [ "name" => "<NAME>", "description" => "Perhaps the only thing about the California spangled cat that isn’t wild-like is its personality. Known to be affectionate, gentle and sociable, this breed enjoys spending a great deal of time with its owners. They are very playful, often choosing to perch in high locations and show off their acrobatic skills.", "image_url" => "https://cdn2.thecatapi.com/images/B1ERTmgph.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 4, "temperament" => "Affectionate, Curious, Intelligent, Loyal, Social", "imperial" => "10 - 15", "metric" => "5 - 7", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/California_Spangled", ], [ "name" => "Chantilly-Tiffany", "description" => "The Chantilly is a devoted companion and prefers company to being left alone. While the Chantilly is not demanding, she will \"chirp\" and \"talk\" as if having a conversation. This breed is affectionate, with a sweet temperament. It can stay still for extended periods, happily lounging in the lap of its loved one. This quality makes the Tiffany an ideal traveling companion, and an ideal house companion for senior citizens and the physically handicapped.", "image_url" => "https://cdn2.thecatapi.com/images/TR-5nAd_S.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 4, "temperament" => "Affectionate, Demanding, Interactive, Loyal", "imperial" => "7 - 12", "metric" => "3 - 5", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Chantilly-Tiffany", ], [ "name" => "Chartreux", "description" => "The Chartreux is generally silent but communicative. Short play sessions, mixed with naps and meals are their perfect day. Whilst appreciating any attention you give them, they are not demanding, content instead to follow you around devotedly, sleep on your bed and snuggle with you if you’re not feeling well.", "image_url" => "https://cdn2.thecatapi.com/images/j6oFGLpRG.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 2, "hypoallergenic" => 1, "intelligence" => 4, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Affectionate, Loyal, Intelligent, Social, Lively, Playful", "imperial" => "6 - 15", "metric" => "3 - 7", "origin" => "France", "wikipedia_url" => "https://en.wikipedia.org/wiki/Chartreux", ], [ "name" => "Chausie", "description" => "For those owners who desire a feline capable of evoking the great outdoors, the strikingly beautiful Chausie retains a bit of the wild in its appearance but has the house manners of our friendly, familiar moggies. Very playful, this cat needs a large amount of space to be able to fully embrace its hunting instincts.", "image_url" => "https://cdn2.thecatapi.com/images/vJ3lEYgXr.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 4, "temperament" => "Affectionate, Intelligent, Playful, Social", "imperial" => "7 - 15", "metric" => "3 - 7", "origin" => "Egypt", "wikipedia_url" => "https://en.wikipedia.org/wiki/Chausie", ], [ "name" => "Cheetoh", "description" => "The Cheetoh has a super affectionate nature and real love for their human companions; they are intelligent with the ability to learn quickly. You can expect that a Cheetoh will be a fun-loving kitty who enjoys playing, running, and jumping through every room in your house.", "image_url" => "https://cdn2.thecatapi.com/images/IFXsxmXLm.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 4, "temperament" => "Affectionate, Gentle, Intelligent, Social", "imperial" => "8 - 15", "metric" => "4 - 7", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Bengal_cat#Cheetoh", ], [ "name" => "<NAME>", "description" => "Colorpoint Shorthairs are an affectionate breed, devoted and loyal to their people. Sensitive to their owner’s moods, Colorpoints are more than happy to sit at your side or on your lap and purr words of encouragement on a bad day. They will constantly seek out your lap whenever it is open and in the moments when your lap is preoccupied they will stretch out in sunny spots on the ground.", "image_url" => "https://cdn2.thecatapi.com/images/oSpqGyUDS.jpg", "child_friendly" => 4, "dog_friendly" => 4, "hairless" => 0, "health_issues" => 2, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 2, "temperament" => "Affectionate, Intelligent, Playful, Social", "imperial" => "4 - 10", "metric" => "2 - 5", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Colorpoint_Shorthair", ], [ "name" => "<NAME>", "description" => "This is a confident cat who loves people and will follow them around, waiting for any opportunity to sit in a lap or give a kiss. He enjoys being handled, making it easy to take him to the veterinarian or train him for therapy work. The Cornish Rex stay in kitten mode most of their lives and well into their senior years. ", "image_url" => "https://cdn2.thecatapi.com/images/unX21IBVB.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 2, "hypoallergenic" => 1, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Affectionate, Intelligent, Active, Curious, Playful", "imperial" => "5 - 9", "metric" => "2 - 4", "origin" => "United Kingdom", "wikipedia_url" => "https://en.wikipedia.org/wiki/Cornish_Rex", ], [ "name" => "Cymric", "description" => "The Cymric is a placid, sweet cat. They do not get too upset about anything that happens in their world. They are loving companions and adore people. They are smart and dexterous, capable of using his paws to get into cabinets or to open doors.", "image_url" => "https://cdn2.thecatapi.com/images/3dbtapCWM.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Gentle, Loyal, Intelligent, Playful", "imperial" => "8 - 13", "metric" => "4 - 6", "origin" => "Canada", "wikipedia_url" => "https://en.wikipedia.org/wiki/Cymric_(cat)", ], [ "name" => "Cyprus", "description" => "Loving, loyal, social and inquisitive, the Cyprus cat forms strong ties with their families and love nothing more than to be involved in everything that goes on in their surroundings. They are not overly active by nature which makes them the perfect companion for people who would like to share their homes with a laid-back relaxed feline companion. ", "image_url" => "https://cdn2.thecatapi.com/images/tJbzb7FKo.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 4, "temperament" => "Affectionate, Social", "imperial" => "8 - 16", "metric" => "4 - 7", "origin" => "Cyprus", "wikipedia_url" => "https://en.wikipedia.org/wiki/Cyprus_cat", ], [ "name" => "<NAME>", "description" => "The favourite perch of the Devon Rex is right at head level, on the shoulder of her favorite person. She takes a lively interest in everything that is going on and refuses to be left out of any activity. Count on her to stay as close to you as possible, occasionally communicating his opinions in a quiet voice. She loves people and welcomes the attentions of friends and family alike.", "image_url" => "https://cdn2.thecatapi.com/images/4RzEwvyzz.png", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 1, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Highly interactive, Mischievous, Loyal, Social, Playful", "imperial" => "5 - 10", "metric" => "2 - 5", "origin" => "United Kingdom", "wikipedia_url" => "https://en.wikipedia.org/wiki/Devon_Rex", ], [ "name" => "Donskoy", "description" => "Donskoy are affectionate, intelligent, and easy-going. They demand lots of attention and interaction. The Donskoy also gets along well with other pets. It is now thought the same gene that causes degrees of hairlessness in the Donskoy also causes alterations in cat personality, making them calmer the less hair they have.", "image_url" => "https://cdn2.thecatapi.com/images/3KG57GfMW.jpg", "child_friendly" => 3, "dog_friendly" => 3, "hairless" => 1, "health_issues" => 3, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Playful, affectionate, loyal, social", "imperial" => "10 - 12", "metric" => "5 - 6", "origin" => "Russia", "wikipedia_url" => "https://en.wikipedia.org/wiki/Donskoy_(cat)", ], [ "name" => "<NAME>", "description" => "The Dragon Li is loyal, but not particularly affectionate. They are known to be very intelligent, and their natural breed status means that they're very active. She is is gentle with people, and has a reputation as a talented hunter of rats and other vermin.", "image_url" => "https://cdn2.thecatapi.com/images/BQMSld0A0.jpg", "child_friendly" => 3, "dog_friendly" => 3, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Intelligent, Friendly, Gentle, Loving, Loyal", "imperial" => "9 - 12", "metric" => "4 - 6", "origin" => "China", "wikipedia_url" => "https://en.wikipedia.org/wiki/Dragon_Li", ], [ "name" => "<NAME>", "description" => "The Egyptian Mau is gentle and reserved. She loves her people and desires attention and affection from them but is wary of others. Early, continuing socialization is essential with this sensitive and sometimes shy cat, especially if you plan to show or travel with her. Otherwise, she can be easily startled by unexpected noises or events.", "image_url" => "https://cdn2.thecatapi.com/images/TuSyTkt2n.jpg", "child_friendly" => 3, "dog_friendly" => 3, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 0, "intelligence" => 4, "short_legs" => 0, "stranger_friendly" => 2, "temperament" => "Agile, Dependent, Gentle, Intelligent, Lively, Loyal, Playful", "imperial" => "6 - 14", "metric" => "3 - 6", "origin" => "Egypt", "wikipedia_url" => "https://en.wikipedia.org/wiki/Egyptian_Mau", ], [ "name" => "<NAME>", "description" => "The European Burmese is a very affectionate, intelligent, and loyal cat. They thrive on companionship and will want to be with you, participating in everything you do. While they might pick a favorite family member, chances are that they will interact with everyone in the home, as well as any visitors that come to call. They are inquisitive and playful, even as adults. ", "image_url" => null, "child_friendly" => 4, "dog_friendly" => 4, "hairless" => 0, "health_issues" => 4, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Sweet, Affectionate, Loyal", "imperial" => "7 - 14", "metric" => "3 - 6", "origin" => "Burma", "wikipedia_url" => null, ], [ "name" => "<NAME>", "description" => "The Exotic Shorthair is a gentle friendly cat that has the same personality as the Persian. They love having fun, don’t mind the company of other cats and dogs, also love to curl up for a sleep in a safe place. Exotics love their own people, but around strangers they are cautious at first. Given time, they usually warm up to visitors.", "image_url" => "https://cdn2.thecatapi.com/images/YnPrYEmfe.jpg", "child_friendly" => 3, "dog_friendly" => 3, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 2, "temperament" => "Affectionate, Sweet, Loyal, Quiet, Peaceful", "imperial" => "7 - 14", "metric" => "3 - 6", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Exotic_Shorthair", ], [ "name" => "<NAME>", "description" => "The Havana Brown is human oriented, playful, and curious. She has a strong desire to spend time with her people and involve herself in everything they do. Being naturally inquisitive, the Havana Brown reaches out with a paw to touch and feel when investigating curiosities in its environment. They are truly sensitive by nature and frequently gently touch their human companions as if they are extending a paw of friendship.", "image_url" => "https://cdn2.thecatapi.com/images/njK25knLH.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Affectionate, Curious, Demanding, Friendly, Intelligent, Playful", "imperial" => "6 - 10", "metric" => "3 - 5", "origin" => "United Kingdom", "wikipedia_url" => "https://en.wikipedia.org/wiki/Havana_Brown", ], [ "name" => "Himalayan", "description" => "Calm and devoted, Himalayans make excellent companions, though they prefer a quieter home. They are playful in a sedate kind of way and enjoy having an assortment of toys. The Himalayan will stretch out next to you, sleep in your bed and even sit on your lap when she is in the mood.", "image_url" => "https://cdn2.thecatapi.com/images/CDhOtM-Ig.jpg", "child_friendly" => 2, "dog_friendly" => 2, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 2, "temperament" => "Dependent, Gentle, Intelligent, Quiet, Social", "imperial" => "7 - 14", "metric" => "3 - 6", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Himalayan_(cat)", ], [ "name" => "<NAME>", "description" => "The Japanese Bobtail is an active, sweet, loving and highly intelligent breed. They love to be with people and play seemingly endlessly. They learn their name and respond to it. They bring toys to people and play fetch with a favorite toy for hours. Bobtails are social and are at their best when in the company of people. They take over the house and are not intimidated. If a dog is in the house, Bobtails assume Bobtails are in charge.", "image_url" => "https://cdn2.thecatapi.com/images/-tm9-znzl.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Active, Agile, Clever, Easy Going, Intelligent, Lively, Loyal, Playful, Social", "imperial" => "5 - 10", "metric" => "2 - 5", "origin" => "Japan", "wikipedia_url" => "https://en.wikipedia.org/wiki/Japanese_Bobtail", ], [ "name" => "Javanese", "description" => "Javanese are endlessly interested, intelligent and active. They tend to enjoy jumping to great heights, playing with fishing pole-type or other interactive toys and just generally investigating their surroundings. He will attempt to copy things you do, such as opening doors or drawers.", "image_url" => "https://cdn2.thecatapi.com/images/xoI_EpOKe.jpg", "child_friendly" => 4, "dog_friendly" => 4, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 1, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Active, Devoted, Intelligent, Playful", "imperial" => "5 - 10", "metric" => "2 - 5", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Javanese_cat", ], [ "name" => "<NAME>", "description" => "The Khao Manee is highly intelligent, with an extrovert and inquisitive nature, however they are also very calm and relaxed, making them an idea lap cat.", "image_url" => "https://cdn2.thecatapi.com/images/165ok6ESN.jpg", "child_friendly" => 3, "dog_friendly" => 3, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 4, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Calm, Relaxed, Talkative, Playful, Warm", "imperial" => "8 - 12", "metric" => "4 - 6", "origin" => "Thailand", "wikipedia_url" => "https://en.wikipedia.org/wiki/Khao_Manee", ], [ "name" => "Korat", "description" => "The Korat is a natural breed, and one of the oldest stable cat breeds. They are highly intelligent and confident cats that can be fearless, although they are startled by loud sounds and sudden movements. Korats form strong bonds with their people and like to cuddle and stay nearby.", "image_url" => "https://cdn2.thecatapi.com/images/DbwiefiaY.png", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 2, "temperament" => "Active, Loyal, highly intelligent, Expressive, Trainable", "imperial" => "7 - 11", "metric" => "3 - 5", "origin" => "Thailand", "wikipedia_url" => "https://en.wikipedia.org/wiki/Korat", ], [ "name" => "Kurilian", "description" => "The character of the Kurilian Bobtail is independent, highly intelligent, clever, inquisitive, sociable, playful, trainable, absent of aggression and very gentle. They are devoted to their humans and when allowed are either on the lap of or sleeping in bed with their owners.", "image_url" => "https://cdn2.thecatapi.com/images/NZpO4pU56M.jpg", "child_friendly" => 5, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Independent, highly intelligent, clever, inquisitive, sociable, playful, trainable", "imperial" => "8 - 15", "metric" => "4 - 7", "origin" => "Russia", "wikipedia_url" => "https://en.wikipedia.org/wiki/Kurilian_Bobtail", ], [ "name" => "LaPerm", "description" => "LaPerms are gentle and affectionate but also very active. Unlike many active breeds, the LaPerm is also quite content to be a lap cat. The LaPerm will often follow your lead; that is, if they are busy playing and you decide to sit and relax, simply pick up your LaPerm and sit down with it, and it will stay in your lap, devouring the attention you give it.", "image_url" => "https://cdn2.thecatapi.com/images/aKbsEYjSl.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 1, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 4, "temperament" => "Affectionate, Friendly, Gentle, Intelligent, Playful, Quiet", "imperial" => "6 - 10", "metric" => "3 - 5", "origin" => "Thailand", "wikipedia_url" => "https://en.wikipedia.org/wiki/LaPerm", ], [ "name" => "<NAME>", "description" => "They are known for their size and luxurious long coat Maine Coons are considered a gentle giant. The good-natured and affable Maine Coon adapts well to many lifestyles and personalities. She likes being with people and has the habit of following them around, but isn’t needy. Most Maine Coons love water and they can be quite good swimmers.", "image_url" => "https://cdn2.thecatapi.com/images/OOD3VXAQn.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Adaptable, Intelligent, Loving, Gentle, Independent", "imperial" => "12 - 18", "metric" => "5 - 8", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Maine_Coon", ], [ "name" => "Malayan", "description" => "Malayans love to explore and even enjoy traveling by way of a cat carrier. They are quite a talkative and rather loud cat with an apparent strong will. These cats will make sure that you give it the attention it seeks and always seem to want to be held and hugged. They will constantly interact with people, even strangers. They love to play and cuddle.", "image_url" => null, "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Affectionate, Interactive, Playful, Social", "imperial" => "6 - 13", "metric" => "3 - 6", "origin" => "United Kingdom", "wikipedia_url" => "https://en.wikipedia.org/wiki/Asian_cat", ], [ "name" => "Manx", "description" => "The Manx is a placid, sweet cat that is gentle and playful. She never seems to get too upset about anything. She is a loving companion and adores being with people.", "image_url" => "https://cdn2.thecatapi.com/images/fhYh2PDcC.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Easy Going, Intelligent, Loyal, Playful, Social", "imperial" => "7 - 13", "metric" => "3 - 6", "origin" => "Isle of Man", "wikipedia_url" => "https://en.wikipedia.org/wiki/Manx_(cat)", ], [ "name" => "Munchkin", "description" => "The Munchkin is an outgoing cat who enjoys being handled. She has lots of energy and is faster and more agile than she looks. The shortness of their legs does not seem to interfere with their running and leaping abilities.", "image_url" => "https://cdn2.thecatapi.com/images/j5cVSqLer.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 1, "stranger_friendly" => 5, "temperament" => "Agile, Easy Going, Intelligent, Playful", "imperial" => "5 - 9", "metric" => "2 - 4", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Munchkin_(cat)", ], [ "name" => "Nebelung", "description" => "The Nebelung may have a reserved nature, but she loves to play (being especially fond of retrieving) and enjoys jumping or climbing to high places where she can study people and situations at her leisure before making up her mind about whether she wants to get involved.", "image_url" => "https://cdn2.thecatapi.com/images/OGTWqNNOt.jpg", "child_friendly" => 4, "dog_friendly" => 4, "hairless" => 0, "health_issues" => 2, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Gentle, Quiet, Shy, Playful", "imperial" => "7 - 11", "metric" => "3 - 5", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Nebelung", ], [ "name" => "Norwegian <NAME>", "description" => "The Norwegian Forest Cat is a sweet, loving cat. She appreciates praise and loves to interact with her parent. She makes a loving companion and bonds with her parents once she accepts them for her own. She is still a hunter at heart. She loves to chase toys as if they are real. She is territorial and patrols several times each day to make certain that all is fine.", "image_url" => "https://cdn2.thecatapi.com/images/06dgGmEOV.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 0, "intelligence" => 4, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Sweet, Active, Intelligent, Social, Playful, Lively, Curious", "imperial" => "8 - 16", "metric" => "4 - 7", "origin" => "Norway", "wikipedia_url" => "https://en.wikipedia.org/wiki/Norwegian_Forest_Cat", ], [ "name" => "Ocicat", "description" => "Loyal and devoted to their owners, the Ocicat is intelligent, confident, outgoing, and seems to have many dog traits. They can be trained to fetch toys, walk on a lead, taught to 'speak', come when called, and follow other commands. ", "image_url" => "https://cdn2.thecatapi.com/images/JAx-08Y0n.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 1, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Active, Agile, Curious, Demanding, Friendly, Gentle, Lively, Playful, Social", "imperial" => "7 - 15", "metric" => "3 - 7", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Ocicat", ], [ "name" => "Oriental", "description" => "Orientals are passionate about the people in their lives. They become extremely attached to their humans, so be prepared for a lifetime commitment. When you are not available to entertain her, an Oriental will divert herself by jumping on top of the refrigerator, opening drawers, seeking out new hideaways.", "image_url" => "https://cdn2.thecatapi.com/images/LutjkZJpH.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 1, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Energetic, Affectionate, Intelligent, Social, Playful, Curious", "imperial" => "5 - 10", "metric" => "2 - 5", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Oriental_Shorthair", ], [ "name" => "Persian", "description" => "Persians are sweet, gentle cats that can be playful or quiet and laid-back. Great with families and children, they absolutely love to lounge around the house. While they don’t mind a full house or active kids, they’ll usually hide when they need some alone time.", "image_url" => null, "child_friendly" => 2, "dog_friendly" => 2, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 2, "temperament" => "Affectionate, loyal, Sedate, Quiet", "imperial" => "9 - 14", "metric" => "4 - 6", "origin" => "Iran (Persia)", "wikipedia_url" => "https://en.wikipedia.org/wiki/Persian_(cat)", ], [ "name" => "Pixie-bob", "description" => "Companionable and affectionate, the Pixie-bob wants to be an integral part of the family. The Pixie-Bob’s ability to bond with their humans along with their patient personas make them excellent companions for children.", "image_url" => "https://cdn2.thecatapi.com/images/z7fJRNeN6.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 2, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 4, "temperament" => "Affectionate, Social, Intelligent, Loyal", "imperial" => "8 - 17", "metric" => "4 - 8", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Pixiebob", ], [ "name" => "Ragamuffin", "description" => "The Ragamuffin is calm, even tempered and gets along well with all family members. Changes in routine generally do not upset her. She is an ideal companion for those in apartments, and with children due to her patient nature.", "image_url" => "https://cdn2.thecatapi.com/images/SMuZx-bFM.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Affectionate, Friendly, Gentle, Calm", "imperial" => "8 - 20", "metric" => "4 - 9", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Ragamuffin_cat", ], [ "name" => "Ragdoll", "description" => "Ragdolls love their people, greeting them at the door, following them around the house, and leaping into a lap or snuggling in bed whenever given the chance. They are the epitome of a lap cat, enjoy being carried and collapsing into the arms of anyone who holds them.", "image_url" => "https://cdn2.thecatapi.com/images/oGefY4YoG.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 3, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Affectionate, Friendly, Gentle, Quiet, Easygoing", "imperial" => "12 - 20", "metric" => "5 - 9", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Ragdoll", ], [ "name" => "<NAME>", "description" => "Russian Blues are very loving and reserved. They do not like noisy households but they do like to play and can be quite active when outdoors. They bond very closely with their owner and are known to be compatible with other pets.", "image_url" => "https://cdn2.thecatapi.com/images/Rhj-JsTLP.jpg", "child_friendly" => 3, "dog_friendly" => 3, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 1, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 1, "temperament" => "Active, Dependent, Easy Going, Gentle, Intelligent, Loyal, Playful, Quiet", "imperial" => "5 - 11", "metric" => "2 - 5", "origin" => "Russia", "wikipedia_url" => "https://en.wikipedia.org/wiki/Russian_Blue", ], [ "name" => "Savannah", "description" => "Savannah is the feline version of a dog. Actively seeking social interaction, they are given to pouting if left out. Remaining kitten-like through life. Profoundly loyal to immediate family members whilst questioning the presence of strangers. Making excellent companions that are loyal, intelligent and eager to be involved.", "image_url" => "https://cdn2.thecatapi.com/images/a8nIYvs6S.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Curious, Social, Intelligent, Loyal, Outgoing, Adventurous, Affectionate", "imperial" => "8 - 25", "metric" => "4 - 11", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Savannah_cat", ], [ "name" => "<NAME>", "description" => "The Scottish Fold is a sweet, charming breed. She is an easy cat to live with and to care for. She is affectionate and is comfortable with all members of her family. Her tail should be handled gently. Folds are known for sleeping on their backs, and for sitting with their legs stretched out and their paws on their belly. This is called the \"Buddha Position\".", "image_url" => "https://cdn2.thecatapi.com/images/o9t0LDcsa.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 4, "hypoallergenic" => 0, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Affectionate, Intelligent, Loyal, Playful, Social, Sweet, Loving", "imperial" => "5 - 11", "metric" => "2 - 5", "origin" => "United Kingdom", "wikipedia_url" => "https://en.wikipedia.org/wiki/Scottish_Fold", ], [ "name" => "<NAME>", "description" => "The Selkirk Rex is an incredibly patient, loving, and tolerant breed. The Selkirk also has a silly side and is sometimes described as clownish. She loves being a lap cat and will be happy to chat with you in a quiet voice if you talk to her. ", "image_url" => "https://cdn2.thecatapi.com/images/II9dOZmrw.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 4, "hypoallergenic" => 1, "intelligence" => 3, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Active, Affectionate, Dependent, Gentle, Patient, Playful, Quiet, Social", "imperial" => "6 - 16", "metric" => "3 - 7", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Selkirk_Rex", ], [ "name" => "Siamese", "description" => "While Siamese cats are extremely fond of their people, they will follow you around and supervise your every move, being talkative and opinionated. They are a demanding and social cat, that do not like being left alone for long periods.", "image_url" => "https://cdn2.thecatapi.com/images/ai6Jps4sx.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 1, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Active, Agile, Clever, Sociable, Loving, Energetic", "imperial" => "8 - 15", "metric" => "4 - 7", "origin" => "Thailand", "wikipedia_url" => "https://en.wikipedia.org/wiki/Siamese_(cat)", ], [ "name" => "Siberian", "description" => "The Siberians dog like temperament and affection makes the ideal lap cat and will live quite happily indoors. Very agile and powerful, the Siberian cat can easily leap and reach high places, including the tops of refrigerators and even doors. ", "image_url" => "https://cdn2.thecatapi.com/images/3bkZAjRh1.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 2, "hypoallergenic" => 1, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 3, "temperament" => "Curious, Intelligent, Loyal, Sweet, Agile, Playful, Affectionate", "imperial" => "8 - 16", "metric" => "4 - 7", "origin" => "Russia", "wikipedia_url" => "https://en.wikipedia.org/wiki/Siberian_(cat)", ], [ "name" => "Singapura", "description" => "The Singapura is usually cautious when it comes to meeting new people, but loves attention from his family so much that she sometimes has the reputation of being a pest. This is a highly active, curious and affectionate cat. She may be small, but she knows she’s in charge", "image_url" => "https://cdn2.thecatapi.com/images/Qtncp2nRe.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Affectionate, Curious, Easy Going, Intelligent, Interactive, Lively, Loyal", "imperial" => "5 - 8", "metric" => "2 - 4", "origin" => "Singapore", "wikipedia_url" => "https://en.wikipedia.org/wiki/Singapura_(cat)", ], [ "name" => "Snowshoe", "description" => "The Snowshoe is a vibrant, energetic, affectionate and intelligent cat. They love being around people which makes them ideal for families, and becomes unhappy when left alone for long periods of time. Usually attaching themselves to one person, they do whatever they can to get your attention.", "image_url" => "https://cdn2.thecatapi.com/images/MK-sYESvO.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 4, "temperament" => "Affectionate, Social, Intelligent, Sweet-tempered", "imperial" => "7 - 12", "metric" => "3 - 5", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Snowshoe_(cat)", ], [ "name" => "Somali", "description" => "The Somali lives life to the fullest. He climbs higher, jumps farther, plays harder. Nothing escapes the notice of this highly intelligent and inquisitive cat. Somalis love the company of humans and other animals.", "image_url" => "https://cdn2.thecatapi.com/images/EPF2ejNS0.jpg", "child_friendly" => 3, "dog_friendly" => 4, "hairless" => 0, "health_issues" => 2, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Mischievous, Tenacious, Intelligent, Affectionate, Gentle, Interactive, Loyal", "imperial" => "6 - 12", "metric" => "3 - 5", "origin" => "Somalia", "wikipedia_url" => "https://en.wikipedia.org/wiki/Somali_(cat)", ], [ "name" => "Sphynx", "description" => "The Sphynx is an intelligent, inquisitive, extremely friendly people-oriented breed. Sphynx commonly greet their owners at the front door, with obvious excitement and happiness. She has an unexpected sense of humor that is often at odds with her dour expression.", "image_url" => "https://cdn2.thecatapi.com/images/BDb8ZXb1v.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 1, "health_issues" => 4, "hypoallergenic" => 1, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Loyal, Inquisitive, Friendly, Quiet, Gentle", "imperial" => "6 - 12", "metric" => "3 - 5", "origin" => "Canada", "wikipedia_url" => "https://en.wikipedia.org/wiki/Sphynx_(cat)", ], [ "name" => "Tonkinese", "description" => "Intelligent and generous with their affection, a Tonkinese will supervise all activities with curiosity. Loving, social, active, playful, yet content to be a lap cat", "image_url" => "https://cdn2.thecatapi.com/images/KBroiVNCM.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Curious, Intelligent, Social, Lively, Outgoing, Playful, Affectionate", "imperial" => "6 - 12", "metric" => "3 - 5", "origin" => "Canada", "wikipedia_url" => "https://en.wikipedia.org/wiki/Tonkinese_(cat)", ], [ "name" => "Toyger", "description" => "The Toyger has a sweet, calm personality and is generally friendly. He's outgoing enough to walk on a leash, energetic enough to play fetch and other interactive games, and confident enough to get along with other cats and friendly dogs.", "image_url" => "https://cdn2.thecatapi.com/images/O3F3_S1XN.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 2, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Playful, Social, Intelligent", "imperial" => "7 - 15", "metric" => "3 - 7", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/Toyger", ], [ "name" => "<NAME>", "description" => "This is a smart and intelligent cat which bonds well with humans. With its affectionate and playful personality the Angora is a top choice for families. The Angora gets along great with other pets in the home, but it will make clear who is in charge, and who the house belongs to", "image_url" => "https://cdn2.thecatapi.com/images/7CGV6WVXq.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 2, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 5, "temperament" => "Affectionate, Agile, Clever, Gentle, Intelligent, Playful, Social", "imperial" => "5 - 10", "metric" => "2 - 5", "origin" => "Turkey", "wikipedia_url" => "https://en.wikipedia.org/wiki/Turkish_Angora", ], [ "name" => "<NAME>", "description" => "While the Turkish Van loves to jump and climb, play with toys, retrieve and play chase, she is is big and ungainly; this is one cat who doesn’t always land on his feet. While not much of a lap cat, the Van will be happy to cuddle next to you and sleep in your bed. ", "image_url" => "https://cdn2.thecatapi.com/images/sxIXJax6h.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 4, "temperament" => "Agile, Intelligent, Loyal, Playful, Energetic", "imperial" => "7 - 20", "metric" => "3 - 9", "origin" => "Turkey", "wikipedia_url" => "https://en.wikipedia.org/wiki/Turkish_Van", ], [ "name" => "<NAME>", "description" => "York Chocolate cats are known to be true lap cats with a sweet temperament. They love to be cuddled and petted. Their curious nature makes them follow you all the time and participate in almost everything you do, even if it's related to water: unlike many other cats, York Chocolates love it.", "image_url" => "https://cdn2.thecatapi.com/images/0SxW2SQ_S.jpg", "child_friendly" => 4, "dog_friendly" => 5, "hairless" => 0, "health_issues" => 1, "hypoallergenic" => 0, "intelligence" => 5, "short_legs" => 0, "stranger_friendly" => 4, "temperament" => "Playful, Social, Intelligent, Curious, Friendly", "imperial" => "12 - 18", "metric" => "5 - 8", "origin" => "United States", "wikipedia_url" => "https://en.wikipedia.org/wiki/York_Chocolate", ] ] ); } } <file_sep>import { makeStyles, createStyles, Theme } from "@material-ui/core/styles"; export const useStyles = makeStyles((theme: Theme) => createStyles({ fullView: { height: "100vh", width: "100vw" }, }) ); <file_sep><?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateBreedsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('breeds', function (Blueprint $table) { $table->bigIncrements("id"); $table->string('name'); $table->longText('description'); $table->longText('image_url')->nullable(); $table->tinyInteger('child_friendly'); $table->tinyInteger('dog_friendly'); $table->boolean('hairless'); $table->tinyInteger('health_issues'); $table->boolean('hypoallergenic'); $table->tinyInteger('intelligence'); $table->boolean('short_legs'); $table->tinyInteger('stranger_friendly'); $table->string('temperament'); $table->string('imperial'); $table->string('metric'); $table->string('origin'); $table->longText('wikipedia_url')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('breeds'); } } <file_sep>version: '3.7' # NOTE # ports and passwords for production porpuses should be different or stronger services: nginx: image: nginx:stable-alpine container_name: nginx ports: - 8888:80 volumes: - ./backend:/var/www/html - ./nginx/default.conf:/etc/nginx/conf.d/default.conf restart: always depends_on: - backend - mysql networks: - app mysql: image: mysql:5.7 container_name: mysql restart: always environment: MYSQL_ROOT_PASSWORD: <PASSWORD> MYSQL_DATABASE: vet MYSQL_USER: doctor MYSQL_PASSWORD: <PASSWORD> ports: - "3306:3306" volumes: - mysql-data:/var/lib/mysql networks: - app backend: build: context: ./backend dockerfile: Dockerfile container_name: backend links: - mysql depends_on: - mysql ports: - 9000:80 volumes: - ./backend:/var/www/html networks: - app frontend: build: context: "./frontend" dockerfile: Dockerfile container_name: frontend tty: true ports: - 3000:3000 volumes: - ./frontend:/app depends_on: - backend networks: - app networks: app: driver: bridge volumes: mysql-data:<file_sep><?php namespace App\Http\Controllers; use App\Models\User; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; use Illuminate\Validation\ValidationException; class RegisterController extends Controller { public function register(Request $request){ $request->validate([ "name" => ["required"], "email" => ["required", "email", "unique:users"], "password" => ["<PASSWORD>", "<PASSWORD>", "<PASSWORD>"] ]); $user = User::create([ "name" => $request->name, "email" => $request->email, "password" => <PASSWORD>($request->password) ]); if ($user) { return response()->json([ "user" => $user, "token" => $user->createToken("cat_app")->plainTextToken ], 200); } throw ValidationException::withMessages([ "name" => ["The name wasn't specified"], "email" => ["The e-mail wasn't specified or invalid or is already picked"], "password" => ["<PASSWORD>"], ]); } } <file_sep>FROM php:7.4-fpm-alpine3.14 RUN docker-php-ext-install pdo pdo_mysql RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer <file_sep>import { makeStyles, createStyles, Theme } from "@material-ui/core/styles"; export const useStyles = makeStyles((theme: Theme) => createStyles({ container: { display: "flex", justifyContent: "center", alignItems: "center", height: "100%", }, root:{ height: "100vh", width: "100vw", background: "url(/cat.jpg) no-repeat center center / cover" } }) ); <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasOne; class Cat extends Model { use HasFactory; protected $fillable = [ "name", "age", "gender_id", "breed_id" ]; /** * Get the breed associated with the Cat * * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function breed(): HasOne { return $this->hasOne(Breed::class); } /** * Get the gender associated with the Cat * * @return \Illuminate\Database\Eloquent\Relations\HasOne */ public function gender(): HasOne { return $this->hasOne(Gender::class); } } <file_sep>FROM node:16.6.2-alpine3.14 WORKDIR /app # install app dependencies COPY package.json ./ COPY yarn.lock ./ RUN npm install --silent RUN npm install [email protected] -g --silent # add app COPY . ./ # start app CMD ["npm", "start"]<file_sep>import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import type { RootState } from "../"; import { UserStateType, Cat } from "../../types"; // Define the initial state using that type const initialState: UserStateType = { cats: [], loadCatStatus: "idle", }; export const userSlice = createSlice({ name: "user", initialState, reducers: { loadCatsStart: (state) => ({ ...state, cats: [], loadCatStatus: "loading", }), loadCatsSuccess: ( state, action: PayloadAction<{ cats: Cat[]; status: string }> ) => ({ ...state, cats: action.payload.cats, loadCatStatus: action.payload.status, }), loadCatsError: (state) => ({ ...state, cats: [], loadCatStatus: "error", }), addCat: (state, action: PayloadAction<Cat>) => ({ ...state, cats: [...state.cats, action.payload], }), editCat: (state, action: PayloadAction<Cat>) => ({ ...state, cats: state.cats.map((cat) => ({ ...cat, ...action.payload })), }), deleteCat: (state, action: PayloadAction<number>) => ({ ...state, cats: state.cats.filter((cat) => cat.id !== action.payload), }), }, }); // Other code such as selectors can use the imported `RootState` type export const getUserCats = (state: RootState) => state.user.cats; export default userSlice.reducer; <file_sep>import { LoginDataType } from "../types"; export const isLoggingIn = () => !!localStorage.getItem("cat_app"); export const getLoggingData: () => LoginDataType = () => { const rawData = localStorage.getItem("cat_app"); return rawData ? JSON.parse(rawData) : null; }; export const logOut = () => { localStorage.getItem("cat_app") && localStorage.removeItem("cat_app"); }; <file_sep>REACT_APP_BACKEND_URL=http://localhost:8888<file_sep># Cat App 🐱😼🐱 ## *Traditional enviroment* ### Requirements - Backend: [Xamp](https://www.apachefriends.org/es/download.html) PHP 7.4, Phpmyadmin - Frontend: [Node](https://nodejs.org/es/) Node.js and npm to execute the front end ### Initializing the project - Backend - Install Xamp - Go to phpmyadmin and make a database called `vet` - In the backend folder run `composer install` - Copy .env.example to .env and make sure you have the same credentials of the created database, `root` and the password `<PASSWORD>` (this is only for development porpuses) - Run php artisan key:generate - Run php artisan migrate - Run php artisan db:seed - Run php artisan serve - Go to localhost:8000 and you should ready to go - Frontend - Install node - In the frontend folder run `npm install && npm start` - Specify the backend_url in the .env - Go to localhost:3000 and you should ready to go ## *Docker enviroment* ### Requirements - [Docker](https://docs.docker.com/engine/install/) - [Docker-compose](https://docs.docker.com/compose/install/) ### Initializing the project - Backend - Go to backend container - Run `composer install` - Copy .env.example to .env and make sure you have the same credentials of the created database, `root` and the password `<PASSWORD>` (this is only for development porpuses) - Run php artisan key:generate - Run php artisan migrate - Run php artisan db:seed - Go to localhost in your machine and you should ready to go - Frontend - Add backend url to your `.env` file - Go to localhost:3000 in your machine and you should ready to go ## *Testing* - Frontend Just run `npm test` in the frontend folder or container - Backend Just run `./vendor/bin/phpunit` in the backend folder or container
7e50ec93f234fe31f58bea4a9c2150dc18bcd680
[ "YAML", "Markdown", "PHP", "TypeScript", "Dockerfile", "Shell" ]
15
PHP
estebansolisd/cat-app
fecfbfc4d4967f189cbc57a6f9fcbbdf4b568239
d0e893c0ec29be559fa79611a0a721abe11f342a
refs/heads/master
<file_sep>package com.guige.springbootdemo; import java.util.EnumSet; import javax.servlet.DispatcherType; import javax.servlet.ServletContext; import javax.servlet.ServletException; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletContextInitializer; import com.guige.springbootdemo.filter.TimeFilter; import com.guige.springbootdemo.listener.ListenerTest; import com.guige.springbootdemo.servlet.ServletTest; //@SpringBootApplication public class SpringbootWebApplication implements ServletContextInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { // 配置 Servlet servletContext.addServlet("servletTest",new ServletTest()) .addMapping("/servletTest"); // 配置过滤器 servletContext.addFilter("timeFilter",new TimeFilter()) .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST),true,"/*"); // 配置监听器 servletContext.addListener(new ListenerTest()); } /* public static void main(String[] args) { SpringApplication.run(SpringbootWebApplication.class, args); }*/ }<file_sep>Spirng boot笔记 目录 简介 1 入门 2 环境搭建 2 创建maven项目 2 添加依赖 3 创建目录和配置文件 3 创建启动类 4 案例演示 4 热部署 5 多环境切换 6 配置日志 7 配置 logback(官方推荐使用) 7 配置 log4j2 9 打包运行 10 Web配置 12 整合Freemarker 13 整合Thymeleaf 14 整合jsp 15 整合 Fastjson 17 自定义 Servlet 20 自定义过滤器/第三方过滤器 21 自定义监听器 22 自定义拦截器 25 配置 AOP 切面 26 错误处理 27 文件上传和下载 31 CORS 支持 33 整合 Swagger2 36 持久层配置 38 整合 JdbcTemplate 38 整合 Spring-data-jpa 42 整合 Mybatis 45 Mybatis生成代码 49 配置 Druid 数据源 51 配置 Druid 监控 53 缓存配置 54 EhCache 缓存 55 Redis 缓存 60 整合 Redis 61 整合 MongoDB 63 消息中间件 64 整合 ActiveMQ 65 整合 RabbitMQ 68 Lombok 简单入门 75 <file_sep>package com.guige.springbootdemo.dao; import com.guige.springbootdemo.entity.User; public interface UserDao { public int insert(User user); public int deleteById(Integer id); public int update(User user); public User getById(Integer id); } <file_sep><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.guige</groupId> <artifactId>springbootdemo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>springbootdemo Maven Webapp</name> <url>http://maven.apache.org</url> <!-- 定义公共资源版本 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> <relativePath /> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <!-- spring boot test依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <!-- 上边引入 parent,因此 下边无需指定版本 --> <!-- 包含 mvc,aop 等jar资源 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <!-- 去除tomcat --> <!-- <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> --> </dependency> <!-- 去除tomcat --> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> --> <!-- 热部署 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> <scope>true</scope> </dependency> <!-- 添加 Freemarker 依赖 --> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> --> <!-- 添加 Thymeleaf 依赖 --> <!-- <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> --> <!--jsp支持 --> <!-- servlet 依赖. --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <!-- tomcat 的支持. --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <!-- fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.35</version> </dependency> <!-- aop --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <!-- 工具 --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <!-- swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> <!-- mysql 驱动包 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- jdbc依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter --> <!--<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- druid --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.5</version> </dependency> <!-- cache --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <!-- 没有该配置,devtools 不生效 --> <fork>true</fork> </configuration> </plugin> <plugin> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-maven-plugin</artifactId> <version>1.3.2</version> <configuration> <configurationFile>src/main/resources/generator/generatorConfig.xml</configurationFile> <overwrite>true</overwrite> <verbose>true</verbose> </configuration> </plugin> </plugins> <finalName>springbootdemo</finalName> </build> </project> <file_sep>package com.guige.springbootdemo.mapper; import com.guige.springbootdemo.entity.ConfParser; import java.util.List; public interface ConfParserMapper { int deleteByPrimaryKey(Long id); int insert(ConfParser record); ConfParser selectByPrimaryKey(Long id); List<ConfParser> selectAll(); int updateByPrimaryKey(ConfParser record); }<file_sep>package com.guige.springbootdemo.entity; import java.util.Date; import com.alibaba.fastjson.annotation.JSONField; import lombok.Data; @Data public class User { private Integer id; private String username; private String password; @JSONField(format="yyyy-MM-dd") private Date birthday; }<file_sep>package com.guige.springbootdemo.entity; public class ConfParser { private Long id; private String prodCd; private String parserName; private String multipleDateFlag; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getProdCd() { return prodCd; } public void setProdCd(String prodCd) { this.prodCd = prodCd; } public String getParserName() { return parserName; } public void setParserName(String parserName) { this.parserName = parserName; } public String getMultipleDateFlag() { return multipleDateFlag; } public void setMultipleDateFlag(String multipleDateFlag) { this.multipleDateFlag = multipleDateFlag; } }
7b492cdf5a0635eb254a7bb4994b6537241d5111
[ "Markdown", "Java", "Maven POM" ]
7
Java
a100488/springBootDemo
1a01244ca6b257a6e3a776805ecf1e06ab5f7d0d
78892a724ed825a6c104a692cf31a5070102f133
refs/heads/master
<repo_name>bioformigoni/ByteBank<file_sep>/02-ByteBank/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _02_ByteBank { class Program { static void Main(string[] args) { ContaCorrente conta = new ContaCorrente(); conta.titular = "Gabriela"; Console.WriteLine(conta.titular); Console.WriteLine(conta.agencia); // Valor pardrão será 0 Console.WriteLine(conta.numero); // Valor pardrão será 0 Console.WriteLine(conta.saldo); // Valor pardrão será 100 pois foi atribuido na classe ContaCorrente conta2 = new ContaCorrente(); conta2.titular = "Bruno"; conta2.saldo = 200; Console.WriteLine(conta.titular); Console.WriteLine(conta.agencia); // Valor pardrão será 0 Console.WriteLine(conta.numero); // Valor pardrão será 0 Console.WriteLine(conta.saldo); // Valor será 200 pois a atribuição sobreescreve o valor padrão Console.ReadLine(); } } } <file_sep>/01-ByteBank/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _01_ByteBank { class Program { static void Main(string[] args) { // Instância da classe ContaCorrente ContaCorrente contaDaGabriela = new ContaCorrente(); contaDaGabriela.titular = "Gabriela"; contaDaGabriela.agencia = 863; contaDaGabriela.numero = 863146; contaDaGabriela.saldo = 100; Console.WriteLine(contaDaGabriela.titular); Console.WriteLine("Agencia: " + contaDaGabriela.agencia); Console.WriteLine("Numero: " + contaDaGabriela.numero); Console.WriteLine("Saldo: " + contaDaGabriela.saldo); contaDaGabriela.saldo += 200; Console.WriteLine("Saldo: " + contaDaGabriela.saldo); string titular2 = "Bruno"; int numeroAgencia2 = 863; int numero2 = 863148; double saldo2 = 50; Console.ReadLine(); } } }
e30c5e44b040c59ba105f18770abdfb0d9f9f809
[ "C#" ]
2
C#
bioformigoni/ByteBank
ec7c21b92b4e3fd442837900367bf4f17185bbf1
4fd0c5714b81aaa9be6e434da6c0b04836c24efd
refs/heads/master
<repo_name>Jacfger/dotfiles-1<file_sep>/install-system.sh/install-fish.sh #!/usr/bin/env sh sudo apt-add-repository ppa:fish-shell/release-3 sudo apt-get install fish chsh -s /usr/bin/fish #fish -c "curl -sL https://git.io/fisher | source && fisher install jorgebucaran/fisher" # Check if all fish plugins will be available already because of yadm fish -c "curl -sL https://git.io/fisher | source && fisher install jorgebucaran/fisher && fisher update" <file_sep>/install-system.sh/install-yadm.sh #!/usr/bin/env sh # This probably will need to be run separately sudo apt-get install yadm wget https://github.com/microsoft/Git-Credential-Manager-Core/releases/download/v2.0.394-beta/gcmcore-linux_amd64.2.0.394.50751.deb -O /tmp/gcmcore.deb sudo dpkg -i /tmp/gcmcore.deb git-credential-manager-core configure git config --global credential.credentialStore secretservice # requires GUI (ok?) yadm clone https://github.com/IndianBoy42/dotfiles.git
82ccbcab992a44a849d076569533052bb387e1e9
[ "Shell" ]
2
Shell
Jacfger/dotfiles-1
16a84653c9fca0b7328a4588b606f8a178eeee06
158b0bcbd5f818707385f0c428d5435f0f30eb76
refs/heads/master
<repo_name>noah18-meet/meet201617YL1cs-mod4<file_sep>/square.py from rectangle import Rectangle class Square(Rectangle) : def __init__(self,length): super(Square,self).__init__(length,length) def set_hight(self,new_height): super(Square,self).set_height(new_height) super(Square,self).set_length(new_height) ''' self.turtle.clear self.turtle.penup() self.turtle.goto(0,0) self.turtle.pendown() self.turtle.goto(self.length,0) self.turtle.goto(self.length,self.height) self.turtle.goto(0,self.height) self.turtle.goto(0,0) self.turtle.penup() self.has_been_drawn=True '''
35f2cf660dca3386ea40a5c28557bd12426967e2
[ "Python" ]
1
Python
noah18-meet/meet201617YL1cs-mod4
3e5ff72b6459b06d313b75b61292529372a7b2f4
653e8d92bdb71354fc3956a8511ece81357952e3
refs/heads/master
<file_sep>/* * SDMMD_AFC_Types.h * SDMMobileDevice * * Copyright (c) 2014, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the distribution. * * 3. Neither the name of Sam Marshall nor the names of its contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #ifndef _SDM_MD_AFC_TYPES_H_ #define _SDM_MD_AFC_TYPES_H_ #include <CoreFoundation/CoreFoundation.h> // Initialize static CFString key arrays void SDMMD_AFC_Types_Initialize(void); #pragma mark - #pragma mark DeviceInfo Keys enum AFC_Device_Info_Key_Values { AFC_Device_Info_Key_FSBlockSize = 0, AFC_Device_Info_Key_FSFreeBytes, AFC_Device_Info_Key_FSTotalBytes, AFC_Device_Info_Key_Model, AFC_Device_Info_Key_count }; #define kAFC_Device_Info_FSBlockSize "FSBlockSize" #define kAFC_Device_Info_FSFreeBytes "FSFreeBytes" #define kAFC_Device_Info_FSTotalBytes "FSTotalBytes" #define kAFC_Device_Info_Model "Model" extern CFStringRef AFC_Device_Info_Keys[AFC_Device_Info_Key_count]; #pragma mark - #pragma mark ConnectionInfo Keys enum AFC_Connection_Info_Key_Values { AFC_Connection_Info_Key_ExtendedStatus = 0, AFC_Connection_Info_Key_Version, AFC_Connection_Info_Key_count }; #define kAFC_Connection_Info_ExtendedStatus "ExtendedStatus" #define kAFC_Connection_Info_Version "Version" extern CFStringRef AFC_Connection_Info_Keys[AFC_Connection_Info_Key_count]; #pragma mark - #pragma mark FileInfo Keys enum AFC_File_Info_Key_Values { AFC_File_Info_Key_birthtime = 0, AFC_File_Info_Key_blocks, AFC_File_Info_Key_ifmt, AFC_File_Info_Key_mtime, AFC_File_Info_Key_nlink, AFC_File_Info_Key_size, AFC_File_Info_Key_count }; #define kAFC_File_Info_st_birthtime "st_birthtime" #define kAFC_File_Info_st_blocks "st_blocks" #define kAFC_File_Info_st_ifmt "st_ifmt" #define kAFC_File_Info_st_mtime "st_mtime" #define kAFC_File_Info_st_nlink "st_nlink" #define kAFC_File_Info_st_size "st_size" extern CFStringRef AFC_File_Info_Keys[AFC_File_Info_Key_count]; #pragma mark - #pragma mark AFC Packet Type enum SDMMD_AFC_Packet_Type { SDMMD_AFC_Packet_Invalid = 0, SDMMD_AFC_Packet_Status, SDMMD_AFC_Packet_Data, SDMMD_AFC_Packet_ReadDirectory = 3, SDMMD_AFC_Packet_ReadFile, SDMMD_AFC_Packet_WriteFile, SDMMD_AFC_Packet_WritePart, SDMMD_AFC_Packet_TruncFile, SDMMD_AFC_Packet_RemovePath = 8, SDMMD_AFC_Packet_MakeDirectory = 9, SDMMD_AFC_Packet_GetFileInfo = 10, SDMMD_AFC_Packet_GetDeviceInfo = 11, SDMMD_AFC_Packet_WriteFileAtomic = 12, SDMMD_AFC_Packet_FileRefOpen = 13, SDMMD_AFC_Packet_FileRefOpenResult = 14, SDMMD_AFC_Packet_FileRefRead = 15, SDMMD_AFC_Packet_FileRefWrite = 16, SDMMD_AFC_Packet_FileRefSeek, SDMMD_AFC_Packet_FileRefTell, SDMMD_AFC_Packet_FileRefTellResult, SDMMD_AFC_Packet_FileRefClose, SDMMD_AFC_Packet_FileRefSetFileSize, SDMMD_AFC_Packet_GetConnectionInfo = 22, SDMMD_AFC_Packet_SetConnectionOptions, SDMMD_AFC_Packet_RenamePath = 24, SDMMD_AFC_Packet_SetFSBlockSize, SDMMD_AFC_Packet_SetSocketBlockSize, SDMMD_AFC_Packet_FileRefLock = 27, SDMMD_AFC_Packet_MakeLink = 28, SDMMD_AFC_Packet_GetFileHash = 29, SDMMD_AFC_Packet_SetModTime = 30, SDMMD_AFC_Packet_GetFileHashWithRange, SDMMD_AFC_Packet_FileRefSetImmutableHint, SDMMD_AFC_Packet_GetSizeOfPathContents, SDMMD_AFC_Packet_RemovePathAndContents, SDMMD_AFC_Packet_DirectoryEnumeratorRefOpen, SDMMD_AFC_Packet_DirectoryEnumeratorRefOpenResult, SDMMD_AFC_Packet_DirectoryEnumeratorRefRead, SDMMD_AFC_Packet_DirectoryEnumeratorRefClose, SDMMD_AFC_Packet_Count }; static char* SDMMD_gAFCPacketTypeNames[SDMMD_AFC_Packet_Count] = { "Invalid", "Status", "Data", "ReadDirectory", "ReadFile", "WriteFile", "WritePart", "TruncFile", "RemovePath", "MakeDirectory", "GetFileInfo", "GetDeviceInfo", "WriteFileAtomic", "FileRefOpen", "FileRefOpenResult", "FileRefRead", "FileRefWrite", "FileRefSeek", "FileRefTell", "FileRefTellResult", "FileRefClose", "FileRefSetFileSize", "GetConnectionInfo", "SetConnectionOptions", "RenamePath", "SetFSBlockSize", "SetSocketBlockSize", "FileRefLock", "MakeLink", "GetFileHash", "SetModTime", "GetFileHashWithRange", "FileRefSetImmutableHint", "GetSizeOfPathContents", "RemovePathAndContents", "DirectoryEnumeratorRefOpen", "DirectoryEnumeratorRefOpenResult", "DirectoryEnumeratorRefRead", "DirectoryEnumeratorRefClose" }; #endif
ac6b8fe5f7c547999144498d26e27920aa66d472
[ "C" ]
1
C
bigfei/SDMMobileDevice
b2d408c93bd9012b2b1f6391359555c13a41c0ec
1f2ed8c55743692f9efbc9ed773d3c9545a59a13
refs/heads/master
<repo_name>AleffBruno/layoutSimplesReactJS<file_sep>/src/components/_layouts/auth/index.js import React from 'react' export default function AuthLayout({children}) { return ( <> AUTH {children} </> ) }<file_sep>/src/main/App.js import 'bootstrap/dist/css/bootstrap.min.css'; import 'font-awesome/css/font-awesome.min.css'; import './App.css'; import React from 'react'; import '../config/ReactotronConfig'; import { Router} from 'react-router-dom'; import { Provider } from 'react-redux'; import Routes from './Routes'; import history from '../services/history'; import store from '../store/index'; // import Logo from '../components/templates/Logo'; // import Nav from '../components/templates/Nav'; // import Footer from '../components/templates/Footer'; export default function App() { return ( <Provider store={store}> <Router history={history}> {/* <div className="app"> <Logo /> <Nav /> <Routes /> <Footer /> </div> */} <Routes /> </Router> </Provider> ) }<file_sep>/src/components/templates/Header.js import './Header.css'; import React from 'react'; export default function Header({icon, title, subtitle}) { return ( // d-nome = celulares o header nao aparece // d-sm-flex = se o dispositivo for sm, use display flex // flex-column = ?? // mt-3 = margin-top 3 // lead = ?? // text-muted = ?? <header className="header d-none d-sm-flex flex-column"> <h1 className="mt-3"> <i className={`fa fa-${icon}`}></i> {title} </h1> <p className="lead text-muted"> {subtitle} </p> </header> ) }<file_sep>/src/components/home/Home.js import React from 'react'; import Main from '../templates/Main'; export default function Home(props) { return ( <Main icon="home" title="Inicio" subtitle="Segundo titulo"> <div className="display-4">Bem vindo</div> <hr/> <p className="mb-0">Sistema de cadastro usando react, aqui vai ter um form</p> </Main> ) }<file_sep>/src/store/modules/auth/reducer.js const INITIAL_STATE = { token: null, signed: false, } export default function auth(state = INITIAL_STATE, action) { switch(action.type) { default: return state } }
1b26731efe2918ba5dcf10dacdc4b3ddfeefd59d
[ "JavaScript" ]
5
JavaScript
AleffBruno/layoutSimplesReactJS
fd372e207df9b12b8f2486d25257aa4c48b4a961
6823d95dc9e479bd95b09008ea953c5cbb4538f4
refs/heads/master
<file_sep>package com.zenan.watchout.service; import android.app.Service; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.media.RingtoneManager; import android.os.Binder; import android.os.CountDownTimer; import android.os.IBinder; import com.zenan.watchout.util.RingtoneUtil; public class WatchService extends Service { LocalBinder mLocalBinder; private SensorManager mSensorManager = null; private Sensor mSensor = null; private float x, y, z; private float x1 = 0, y1 = 0, z1 = 0; private float x0 = 0, y0 = 0, z0 = 0; @Override public IBinder onBind(Intent intent) { return mLocalBinder; } @Override public void onCreate() { mLocalBinder = new LocalBinder(); mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); mSensorManager.registerListener(listener, mSensor, SensorManager.SENSOR_DELAY_GAME); new CountDownTimer(1000, 1000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { mThread.start(); } }.start(); } private Thread mThread = new Thread() { @Override public void run() { x0 = x; y0 = y; z0 = z; while (true) { x1 = x; y1 = y; z1 = z; double ab = x0 * x1 + y0 * y1 + z0 * z1; double tt = (x0 * x0 + y0 * y0 + z0 * z0) * (x1 * x1 + y1 * y1 + z1 * z1); double angle = Math.acos(ab / Math.sqrt(tt)) / 2.0 / Math.PI * 360; System.out.println("x0: " + x0 + " y0: " + y0 + " z0: " + z0); System.out.println("x: " + x + " y: " + y + " z: " + z); System.out.println("x1: " + x1 + " y1: " + y1 + " z1: " + z1); System.out.println("angle: " + angle); if (angle > 45) { System.out.println("angle: " + angle); RingtoneUtil.playRingtone(getApplicationContext(), RingtoneManager.TYPE_RINGTONE); break; } } } }; SensorEventListener listener = new SensorEventListener() { @Override public void onSensorChanged(SensorEvent event) { x = event.values[0]; y = event.values[1]; z = event.values[2]; } @Override public void onAccuracyChanged(Sensor arg0, int arg1) { } }; public class LocalBinder extends Binder { public WatchService getService() { return WatchService.this; } } @Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } @Override public void onDestroy() { super.onDestroy(); sendBroadcast(new Intent("YouWillNeverKillMe")); } } <file_sep>WatchOut ======== Let android phone watch itself and your package
9ec2d5fa9eeb140ce6209fac7fe4c5766a8762b4
[ "Markdown", "Java" ]
2
Java
zenanhu/WatchOut
307d48e7e37882a496074f465b56bd1817b408dd
7aff3b9159ed6c97862c745ab84a43876ad9a9b1
refs/heads/master
<file_sep>describe("translate", function() { it("is true if a word that starts with 'o' ends in 'ay'", function() { expect(translate("out")).to.equal('outay'); }); }); describe("translate", function() { it("is true if a word that starts with a consonant has all consonants in beginning removed and has 'ay' added", function() { expect(translate("start")).to.equal('artstay'); }); }); <file_sep>var translate = function(input) { var word = input.split(''); console.log(word); var vowels = ["a","e","i","o","u"]; var consonants = ["b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y", "z"]; var i = 0; consonants.forEach(function(consonant) { if (word[i] === consonant) { i++; var count = i; console.log(count + " = " + consonant); // count = count-1; } console.log(count); var slice = word.slice(0,count+1); console.log(slice); slice = slice.join(''); console.log(slice); word.push(slice); // var slice = word.slice(0,count) // console.log(slice) // slice = slice.join(''); // console.log(count + " = " + splice); // word.push(slice); }); vowels.forEach(function(vowel) { if (word[0] === vowel) { word.push("ay"); } // else if { // consonants.forEach(function(consonant) { // if (word[0] === consonant) && () { // word.reverse().pop(); // word.reverse(); // // } // }) // } }); var string = word.join(''); console.log(word); console.log(string); return string; }; // $(document).ready(function() { // $(".btn").click(function() { // input = $("input#word").val(); // translate(input); // // console.log(input); // event.preventDefault(); // }); // // // // });
7e2c00c69dfeb97891a3c15be1a1d5d8503f477d
[ "JavaScript" ]
2
JavaScript
jeffsdev/pig-latin-translator
31603260e7d6b1965605f1d0095c9b80728ff703
4b28d347854f53820989e859c633d8b3591cf46f
refs/heads/main
<file_sep>package com.bennyplo.designgraphicswithopengl; import android.opengl.GLES32; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.Arrays; public class Sphere { private final String vertexShaderCode = "attribute vec3 aVertexPosition;"+//vertex of an object " attribute vec4 aVertexColor;"+//the colour of the object " uniform mat4 uMVPMatrix;"+//model view projection matrix " varying vec4 vColor;"+//variable to be accessed by the fragment shader " void main() {" + " gl_Position = uMVPMatrix* vec4(aVertexPosition, 1.0);"+//calculate the position of the vertex " vColor=aVertexColor;}";//get the colour from the application program private final String fragmentShaderCode = "precision mediump float;"+ //define the precision of float "varying vec4 vColor;"+ //variable from the vertex shader "void main() {"+ " gl_FragColor = vColor; }";//change the colour based on the variable from the vertex shader private final FloatBuffer vertexBuffer,colorBuffer; private final IntBuffer indexBuffer; private final int mProgram; private int mPositionHandle,mColorHandle; private int mMVPMatrixHandle; // number of coordinates per vertex in this array static final int COORDS_PER_VERTEX = 3; static final int COLOR_PER_VERTEX = 4; private int vertexCount;// number of vertices private final int vertexStride = COORDS_PER_VERTEX * 4; // 4 bytes per vertex private final int colorStride=COLOR_PER_VERTEX*4;//4 bytes per vertex float SphereVertex[] ={ }; static int SphereIndex[]={ }; static float SphereColor[]={ }; private void createSphere(float radius, int nolatitude, int nolongitude) { float vertices[] = new float[65535]; int index[] = new int[65535]; float color[] = new float[65535]; int vertexIndex = 0; int colorIndex = 0; int indx = 0; float dist = 0; for (int row = 0; row <= nolatitude; row++) { double theta = row * Math.PI / nolatitude; double sinTheta = Math.sin(theta); double cosTheta = Math.cos(theta); float tcolor = -0.5f; float tcolorinc = 1/(float)(nolongitude+1); for (int col = 0; col <= nolongitude; col++) { double phi = col * 2 * Math.PI / nolongitude; double sinPhi = Math.sin(phi); double cosPhi = Math.cos(phi); double x = cosPhi * sinTheta; double y = cosTheta; double z = sinPhi * sinTheta; vertices[vertexIndex++] = (float)(radius * x); vertices[vertexIndex++] = (float)(radius * y) + dist; vertices[vertexIndex++] = (float)(radius * z); color[colorIndex++] = 1; color[colorIndex++] = Math.abs(tcolor); color[colorIndex++] = 0; color[colorIndex++] = 1; tcolor += tcolorinc; } } // index buffer for (int row = 0; row < nolatitude; row++) { for (int col = 0; col < nolongitude; col++) { int P0 = (row * (nolongitude + 1)) + col; int P1 = P0 + nolongitude + 1; index[indx++] = P0; index[indx++] = P1; index[indx++] = P0 + 1; index[indx++] = P1; index[indx++] = P1 + 1; index[indx++] = P0 + 1; } } SphereVertex = Arrays.copyOf(vertices, vertexIndex); SphereIndex = Arrays.copyOf(index, indx); SphereColor = Arrays.copyOf(color, colorIndex); } public Sphere() { createSphere(2, 30, 30); // initialize vertex byte buffer for shape coordinates ByteBuffer bb = ByteBuffer.allocateDirect(SphereVertex.length * 4);// (# of coordinate values * 4 bytes per float) bb.order(ByteOrder.nativeOrder()); vertexBuffer = bb.asFloatBuffer(); vertexBuffer.put(SphereVertex); vertexBuffer.position(0); vertexCount=SphereVertex.length/COORDS_PER_VERTEX; ByteBuffer cb=ByteBuffer.allocateDirect(SphereColor.length * 4);// (# of coordinate values * 4 bytes per float) cb.order(ByteOrder.nativeOrder()); colorBuffer = cb.asFloatBuffer(); colorBuffer.put(SphereColor); colorBuffer.position(0); IntBuffer ib=IntBuffer.allocate(SphereIndex.length); indexBuffer=ib; indexBuffer.put(SphereIndex); indexBuffer.position(0); // prepare shaders and OpenGL program int vertexShader = MyRenderer.loadShader(GLES32.GL_VERTEX_SHADER, vertexShaderCode); int fragmentShader = MyRenderer.loadShader(GLES32.GL_FRAGMENT_SHADER, fragmentShaderCode); mProgram = GLES32.glCreateProgram(); // create empty OpenGL Program GLES32.glAttachShader(mProgram, vertexShader); // add the vertex shader to program GLES32.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program GLES32.glLinkProgram(mProgram); // link the OpenGL program to create an executable GLES32.glUseProgram(mProgram);// Add program to OpenGL environment // get handle to vertex shader's vPosition member mPositionHandle = GLES32.glGetAttribLocation(mProgram, "aVertexPosition"); // Enable a handle to the triangle vertices GLES32.glEnableVertexAttribArray(mPositionHandle); mColorHandle = GLES32.glGetAttribLocation(mProgram, "aVertexColor"); // Enable a handle to the colour GLES32.glEnableVertexAttribArray(mColorHandle); // Prepare the colour coordinate data GLES32.glVertexAttribPointer(mColorHandle, COLOR_PER_VERTEX, GLES32.GL_FLOAT, false, colorStride, colorBuffer); // get handle to shape's transformation matrix mMVPMatrixHandle = GLES32.glGetUniformLocation(mProgram, "uMVPMatrix"); MyRenderer.checkGlError("glGetUniformLocation"); } public void draw(float[] mvpMatrix) { GLES32.glUseProgram(mProgram);//use the object's shading programs // Apply the projection and view transformation GLES32.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0); MyRenderer.checkGlError("glUniformMatrix4fv"); //set the attribute of the vertex to point to the vertex buffer GLES32.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX, GLES32.GL_FLOAT, false, vertexStride, vertexBuffer); GLES32.glVertexAttribPointer(mColorHandle, COORDS_PER_VERTEX, GLES32.GL_FLOAT, false, colorStride, colorBuffer); // GLES32.glDrawElements(GLES32.GL_LINES,SphereIndex.length,GLES32.GL_UNSIGNED_INT,indexBuffer); GLES32.glDrawElements(GLES32.GL_TRIANGLES,SphereIndex.length,GLES32.GL_UNSIGNED_INT,indexBuffer); } } <file_sep>package com.bennyplo.designgraphicswithopengl; import android.opengl.GLES32; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.Arrays; public class CharacterS { private final String vertexShaderCode = "attribute vec3 aVertexPosition;"+//vertex of an object " attribute vec4 aVertexColor;"+//the colour of the object " uniform mat4 uMVPMatrix;"+//model view projection matrix " varying vec4 vColor;"+//variable to be accessed by the fragment shader " void main() {" + " gl_Position = uMVPMatrix* vec4(aVertexPosition, 1.0);"+//calculate the position of the vertex " vColor=aVertexColor;}";//get the colour from the application program private final String fragmentShaderCode = "precision mediump float;"+ //define the precision of float "varying vec4 vColor;"+ //variable from the vertex shader "void main() {"+ " gl_FragColor = vColor; }";//change the colour based on the variable from the vertex shader private final FloatBuffer vertexBuffer,colorBuffer; private final IntBuffer indexBuffer; private final int mProgram; private int mPositionHandle,mColorHandle; private int mMVPMatrixHandle; // number of coordinates per vertex in this array static final int COORDS_PER_VERTEX = 3; static final int COLOR_PER_VERTEX = 4; private int vertexCount;// number of vertices private final int vertexStride = COORDS_PER_VERTEX * 4; // 4 bytes per vertex private final int colorStride=COLOR_PER_VERTEX*4;//4 bytes per vertex float CharSVertex[] ={ }; static int CharSIndex[]={ }; static float CharSColor[]={ }; static float P[] = {2, 0, 3.2f, 0, 4, 0.8f, 2.8f, 1.3f, 2, 1.5f, 2, 2, 3.2f, 2}; // control points static float Q[] = {2, 0.2f, 2.2f, 0.2f, 3.6f, 0.4f, 2.8f, 1, 1.5f, 1.5f, 1.6f, 2.2f, 3.2f, 2.2f}; private void createCurve(float control_pts_p[], float control_pts_Q[]) { float vertices[] = new float[65535]; float color[] = new float[65535]; int index[] = new int[65535]; int vi = 0, cindx = 0, indx = 0, px = 0; double x, y; float z = 0.2f, centroidx = 0, centroidy = 0; int nosegments = (control_pts_p.length / 2) / 3; for (int i = 0; i < control_pts_p.length; i+=2) { centroidx += control_pts_p[i]; centroidy += control_pts_p[i + 1]; } centroidx /= (float)(control_pts_p.length / 2); centroidy /= (float)(control_pts_p.length / 2); for (int segments = 0; segments < nosegments; segments++) { for (float t = 0; t < 1.0f; t += 0.1f) { x = Math.pow(1 - t, 3) * control_pts_p[px] + control_pts_p[px + 2] * 3 * t * Math.pow(1 - t, 2) + control_pts_p[px + 4] * 3 * t * t * (1 - t) + control_pts_p[px + 6] * Math.pow(t, 3); y = Math.pow(1 - t, 3) * control_pts_p[px + 1] + control_pts_p[px + 3] * 3 * t * Math.pow(1 - t, 2) + control_pts_p[px + 5] * 3 * t * t * (1 - t) + control_pts_p[px + 7] * Math.pow(t, 3); vertices[vi++] = (float)x - centroidx; vertices[vi++] = (float)y - centroidy; vertices[vi++] = z; color[cindx++] = 1; color[cindx++] = 1; color[cindx++] = 0; color[cindx++] = 1; } px += 6; } px = 0; int vj = vi; for (int segments = 0; segments < nosegments; segments++) { for (float t = 0; t < 1.0f; t += 0.1f) { x = Math.pow(1 - t, 3) * control_pts_Q[px] + control_pts_Q[px + 2] * 3 * t * Math.pow(1 - t, 2) + control_pts_Q[px + 4] * 3 * t * t * (1 - t) + control_pts_Q[px + 6] * Math.pow(t, 3); y = Math.pow(1 - t, 3) * control_pts_Q[px + 1] + control_pts_Q[px + 3] * 3 * t * Math.pow(1 - t, 2) + control_pts_Q[px + 5] * 3 * t * t * (1 - t) + control_pts_Q[px + 7] * Math.pow(t, 3); vertices[vj++] = (float)x - centroidx; vertices[vj++] = (float)y - centroidy; vertices[vj++] = z; color[cindx++] = 1; color[cindx++] = 1; color[cindx++] = 0; color[cindx++] = 1; } px += 6; } // int novertices = vj; // vj here represents the total number of vertices for a 2-d S with two curves // set up indexes for the front for (int v0=0,v1=1,v2=vi/3,v3=vi/3+1; v3<novertices/3; v0++, v1++, v2++, v3++) { index[indx++] = v0; index[indx++] = v1; index[indx++] = v2; index[indx++] = v1; index[indx++] = v2; index[indx++] = v3; } // // create new vertices for the back int vk = novertices; for (int i = 0; i < novertices;) { vertices[vk++] = vertices[i++]; vertices[vk++] = vertices[i++]; vertices[vk++] = -vertices[i++]; color[cindx++] = 1; color[cindx++] = 0; color[cindx++] = 0; color[cindx++] = 1; } // novertices = vk; // update the total of vertices // back for (int v0=vj/3,v1=vj/3+1,v2=(vi+vj)/3,v3=(vi+vj)/3+1; v3<novertices/3; v0++, v1++, v2++, v3++) { index[indx++] = v0; index[indx++] = v1; index[indx++] = v2; index[indx++] = v1; index[indx++] = v2; index[indx++] = v3; } // bottom for (int v0=0,v1=1,v2=vj/3,v3=vj/3+1; v3<(vi + vj)/3; v0++, v1++, v2++, v3++) { index[indx++] = v0; index[indx++] = v1; index[indx++] = v2; index[indx++] = v1; index[indx++] = v2; index[indx++] = v3; } // top for (int v0=vi/3,v1=vi/3+1,v2=(vi+vj)/3,v3=(vi+vj)/3+1; v3<novertices/3; v0++, v1++, v2++, v3++) { index[indx++] = v0; index[indx++] = v1; index[indx++] = v2; index[indx++] = v1; index[indx++] = v2; index[indx++] = v3; } CharSVertex = Arrays.copyOf(vertices, novertices); CharSIndex = Arrays.copyOf(index, indx); CharSColor = Arrays.copyOf(color, cindx); } public CharacterS() { createCurve(P, Q); // initialize vertex byte buffer for shape coordinates ByteBuffer bb = ByteBuffer.allocateDirect(CharSVertex.length * 4);// (# of coordinate values * 4 bytes per float) bb.order(ByteOrder.nativeOrder()); vertexBuffer = bb.asFloatBuffer(); vertexBuffer.put(CharSVertex); vertexBuffer.position(0); vertexCount=CharSVertex.length/COORDS_PER_VERTEX; ByteBuffer cb=ByteBuffer.allocateDirect(CharSColor.length * 4);// (# of coordinate values * 4 bytes per float) cb.order(ByteOrder.nativeOrder()); colorBuffer = cb.asFloatBuffer(); colorBuffer.put(CharSColor); colorBuffer.position(0); IntBuffer ib=IntBuffer.allocate(CharSIndex.length); indexBuffer=ib; indexBuffer.put(CharSIndex); indexBuffer.position(0); // prepare shaders and OpenGL program int vertexShader = MyRenderer.loadShader(GLES32.GL_VERTEX_SHADER, vertexShaderCode); int fragmentShader = MyRenderer.loadShader(GLES32.GL_FRAGMENT_SHADER, fragmentShaderCode); mProgram = GLES32.glCreateProgram(); // create empty OpenGL Program GLES32.glAttachShader(mProgram, vertexShader); // add the vertex shader to program GLES32.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program GLES32.glLinkProgram(mProgram); // link the OpenGL program to create an executable GLES32.glUseProgram(mProgram);// Add program to OpenGL environment // get handle to vertex shader's vPosition member mPositionHandle = GLES32.glGetAttribLocation(mProgram, "aVertexPosition"); // Enable a handle to the triangle vertices GLES32.glEnableVertexAttribArray(mPositionHandle); mColorHandle = GLES32.glGetAttribLocation(mProgram, "aVertexColor"); // Enable a handle to the colour GLES32.glEnableVertexAttribArray(mColorHandle); // Prepare the colour coordinate data GLES32.glVertexAttribPointer(mColorHandle, COLOR_PER_VERTEX, GLES32.GL_FLOAT, false, colorStride, colorBuffer); // get handle to shape's transformation matrix mMVPMatrixHandle = GLES32.glGetUniformLocation(mProgram, "uMVPMatrix"); MyRenderer.checkGlError("glGetUniformLocation"); } public void draw(float[] mvpMatrix) { GLES32.glUseProgram(mProgram);//use the object's shading programs // Apply the projection and view transformation GLES32.glUniformMatrix4fv(mMVPMatrixHandle, 1, false, mvpMatrix, 0); MyRenderer.checkGlError("glUniformMatrix4fv"); //set the attribute of the vertex to point to the vertex buffer GLES32.glVertexAttribPointer(mPositionHandle, COORDS_PER_VERTEX, GLES32.GL_FLOAT, false, vertexStride, vertexBuffer); GLES32.glVertexAttribPointer(mColorHandle, COORDS_PER_VERTEX, GLES32.GL_FLOAT, false, colorStride, colorBuffer); // Draw the 3D character A GLES32.glDrawElements(GLES32.GL_TRIANGLES,CharSIndex.length,GLES32.GL_UNSIGNED_INT,indexBuffer); // GLES32.glDrawElements(GLES32.GL_LINES,CharSIndex.length,GLES32.GL_UNSIGNED_INT,indexBuffer); } } <file_sep>package com.bennyplo.designgraphicswithopengl; import android.content.Context; import android.opengl.GLSurfaceView; import android.util.Log; import android.view.MotionEvent; import java.util.Timer; import java.util.TimerTask; public class MyView extends GLSurfaceView { private final MyRenderer mRenderer; private Timer timer; private final float TOUCH_SCALE_FACTOR = 100.0f / 1080; private float mPreviousX; private float mPreviousY; public MyView(Context context) { super(context); setEGLContextClientVersion(2);// Create an OpenGL ES 2.0 context. mRenderer = new MyRenderer();// Set the Renderer for drawing on the GLSurfaceView setRenderer(mRenderer); // Render the view only when there is a change in the drawing data setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY); timer = new Timer(); TimerTask task = new TimerTask() { float angle = 0; float px = 0, py = 0, pz = 0; boolean dir = true; @Override public void run() { // mRenderer.setAngle(angle); // mRenderer.setXAngle(angle); mRenderer.setLightLocation(px, py, pz); requestRender(); // angle+=1; // // if (angle == 360) { // angle = 0; // } if (dir) { px += 0.1f; py += 0.1f; if (px >= 10) { dir = false; } } else { px -= 0.1f; py -= 0.1f; if (px <= -10) { dir = true; } } } }; timer.scheduleAtFixedRate(task, 0, 10); } @Override public boolean onTouchEvent(MotionEvent e) { float x = e.getX(); float y = e.getY(); switch(e.getAction()) { case MotionEvent.ACTION_MOVE: float dx = x - mPreviousX; float dy = y - mPreviousY; if (y > getHeight() / 2) { dx = dx * -1; } if (x < getWidth() / 2) { dy = dy * -1; } mRenderer.setAngle( mRenderer.getAngle() + (dx * TOUCH_SCALE_FACTOR) ); mRenderer.setXAngle( mRenderer.getXAngle() + (dy * TOUCH_SCALE_FACTOR) ); requestRender(); } mPreviousX = x; mPreviousY = y; return true; } } <file_sep># OpenGL-Android
05fa25ed35a74d0ea14fbae0a94747d16cbb9a0d
[ "Markdown", "Java" ]
4
Java
chihwu/OpenGL-Android
b9bb99e3903d9db1f44a399578a1278f95d2b961
c2637e04a015872aa640818ad851be3f172aed09
refs/heads/master
<file_sep>class SessionsController < ApplicationController def create end end <file_sep>require 'rails_helper' RSpec.describe SessionsController, type: :controller do before(:each) do User.destroy_all end let(:user) {User.create(:name => "<NAME>", :uid => 1234567 )} describe 'get create' do end end
fafcc003c4e5eeb897ee3c53a32c6e7370261377
[ "Ruby" ]
2
Ruby
RandallRobinson4/omniauth_lab-v-000
e3feaef4455c7d90148a15bebe8b3e396050550a
88f7d6c16c2d93fcc1e4acdb7e5080bfa10bc410
refs/heads/master
<file_sep><?php $action = $_REQUEST['action_to_do']; if($action == 'shutdown'){ $result = shell_exec("shutdown.sh"); } else if($action == 'reboot'){ $result = shell_exec("reboot.sh"); } else{ $result = "Please select an action"; } var_dump($result); exit; header('Location: index.php?result='.$result); ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <title>Remote Server Management</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <body> <div class="container"> <?php if(isset($_GET['result'])){ echo '<div class=""><pre>'.$_GET['result'].'</pre></div>'; } echo "<table class='table table-bordered'><tr><th>Server Name</th><th>Address</th></tr>"; $file_handle = fopen("lan-servers.txt", "r"); while (!feof($file_handle)) { $line = fgets($file_handle); $data = explode(" ", $line); echo "<tr><td>".$data[0]."</td><td>".$data[count($data)-1]."</td></tr>"; } fclose($file_handle); ?> </table> <h3 class="align-center">Select Action</h3> <form method="post" action="exec_shell.php"> <select name="action_to_do"> <option value="">Select</option> <option value="shutdown">Shutdown</option> <option value="reboot">Reboot</option> </select> <INPUT TYPE="submit" VALUE="Submit" NAME="Submit"> </form> </div> </body> </html><file_sep>#!/bin/bash # where the server list sits LAN_LIST="$HOME/lan-servers.txt" # Function to check if the server responds to ping function testServer() { if ping -c1 $ip>/dev/null 2>&1; then return 0 else return 1 fi } # get a list of IPs for the servers function getServers() { cat $LAN_LIST | egrep -v '^(#|\s*$)' | perl -ple 's/\s+/ /g;' | cut -d' ' -f 2 } # check if I can now log in to the server with no password if ! ssh -o "NumberOfPasswordPrompts 0" root@$ip '/bin/true' >/dev/null 2>&1; then # if I still can't then something is broken echo "Failed to complete key exchange with $ip - skipping this server" continue; fi fi # start to shutdown the server echo -n "Rebooting $(ssh root@$ip hostname)" # halt the remote server ssh root@$ip reboot count=0 # wait until its down or 300 seconds have passed while testServer $ip; do sleep 1; echo -n "." count=$(( $count + 1 )) # count up to 300 if [ "$count" -gt 300 ]; then # wait till 300s then ping the server if testServer $ip; then # if its alive then its already rebooted echo "Rebooting done $ip" fi fi done echo "" done <file_sep>Remote server controller web interface. ********* File description ************* Index file: There is an index file (index.php) which calls the exec_shell.php file based on the selection of rebooting or shutdown. lan_servers.txt contains the server name and IP addresses seperated by space. There are two shell scripts one for shut down another for rebooting. I assumed, the server pc already have the super user priviledge to conduct shutdown and reboot operations. ********* How to launch ************* Put the folder in htdocs folder under xampp. Run the xampp server and then launch the index.php from browser. The idea is adopted from: https://geek.co.il/2009/07/20/script-day-shutting-down-multiple-servers-at-once
cff7538f2c7a6a4d4d646437b13cd5bb2dcac87c
[ "Text", "PHP", "Shell" ]
4
PHP
monjurul003/remoteservercontroller
675b97a1ed5b482f9adc181760d415f641baf88b
f632d301d724b1a708a28dced06b93ce67988ead
refs/heads/master
<repo_name>Rodremur/10750-Beautiful-Points<file_sep>/10750.cpp /*------------------------------------------------------- * Tarea de Analisis de Algoritmos: 10750 - Beautiful Points * Fecha: 02-03-2016 * Autor: * A01064215 <NAME> * Referencia: PChome(12/7/2013). http://mypaper.pchome.com.tw/zerojudge/post/1324860219 */ #include <stdio.h> #include <math.h> #include <algorithm> using namespace std; struct Point { int x; int y; bool operator<(const Point &source) const { if (x != source.x) { return x < source.x; } return y < source.y; } }; Point pts[10000]; double pointx, pointy; int mindis; int distancex(int a, int m) { return (pts[a].x - pts[m].x)*(pts[a].x - pts[m].x); } int distancey(int a, int m) { return (pts[a].y - pts[m].y)*(pts[a].y - pts[m].y); } void closestPair(int low, int high) { if (low >= high) return; int i, j, mid; mid = (low + high) /2; closestPair(low, mid); closestPair(mid+1, high); for (i = mid; i >= low; i--) { if (distancex(i, mid) >= mindis) break; for (j = mid+1; j <= high; j++) { if (distancex(i, j) >= mindis) { break; } int v = distancex(i, j) + distancey(i, j); if (v < mindis) { mindis = v; pointx = (pts[i].x+pts[j].x)/2.0; pointy = (pts[i].y+pts[j].y)/2.0; } } } } int main(int argc, char const *argv[]) { int cases, i, j, k, n; scanf("%d", &cases); for (k = 0; k < cases; k++) { scanf("%d", &n); for (j = 0; j < n; j++) { scanf("%d %d", &pts[j].x, &pts[j].y); } sort(pts, pts+n); mindis = pow(2, 16) -1; closestPair(0, n-1); printf("%.3f %.3f\n", pointx, pointy); } }
c794763557e1fe42363e55b4e4903133cb2e168a
[ "C++" ]
1
C++
Rodremur/10750-Beautiful-Points
769f984dd4ee3b9db9bc77b4daf28c3914086bc5
0f8f8c994b8dd1eabd30d848f7e8d5b413ce740c
refs/heads/master
<repo_name>34153320/Domain_language_model_I<file_sep>/README.md # Domain_language_model_I Language models training on large scale dataset (for instance, BERT, XLnet, and GPT2) work for general purpose. However, in our daily application the language models are frequently used in specific domain. To avoid large scale retraining, and also transfer the pre-trained learned LM, here a strategy is proposed to obtain domain language model based on GPT2. <file_sep>/generate.py import tensorflow as tf import Transformer from domain_transfer import create_domain_dict """ Written by <NAME>. Part of the codes are borrowed from openai/GPT-2. """ domain_dict = ["I", "You", "My", "They", "It", "Am", "Are", "Need", "Feel", "Is", "Hungry", "Help", "Tired", "Not", "How", "Okay", "Very", "Thirsty", "Comfortable", "Right", "Please", "Hope", "Clean", "Glasses", "Nurse", "Closer", "Bring", "What", "Where", "Tell", "That", "Going", "Music", "Like", "Outside", "Do", "Have", "Faith", "Success", "Coming", "Good", "Bad", "Here", "Family", "Hello", "Goodbye", "Computer", "Yes", "Up", "No"] def top_k_logits(logits, k): if k == 0: # no truncation return logits def _top_k(): values, _ = tf.nn.top_k(logits, k=k) min_values = values[:, -1, tf.newaxis] return tf.where( logits < min_values, tf.ones_like(logits, dtype=logits.dtype) * -1e10, logits, ) return tf.cond( tf.equal(k, 0), lambda: logits, lambda: _top_k(), ) def sample_sequence(*, hparams, length, reduced_dict_index, start_token=None, batch_size=None, context=None, temperature=1, top_k=0): if start_token is None: assert context is not None, 'Specify exactly one of start_token and context!' else: assert context is None, 'Specify exactly one of start_token and context!' context = tf.fill([batch_size, 1], start_token) # mask dict is too large # dict_mask = np.zeros((hparams.n_vocab, hparams.n_vocab)) def step(hparams, tokens, past=None): lm_output = Transformer.model(hparams=hparams, X=tokens, past=past, reuse=tf.AUTO_REUSE) logits = lm_output['logits'][:, :, :hparams.n_vocab] # keep output dimension the same # tf.gather collect the corresponding logits logits = tf.gather(logits, reduced_dict_index) # logits = logits * dict_mask presents = lm_output['present'] presents.set_shape(Transformer.past_shape(hparams=hparams, batch_size=batch_size)) return { 'logits': logits, 'presents': presents, } """ For domain transfer, the general langauage model maintains the structure. Change the final softmax to adapte to specific domain knowledge. """ with tf.name_scope('sample_sequence'): def body(past, prev, output): next_outputs = step(hparams, prev, past=past) logits = next_outputs['logits'][:, -1, :] / tf.to_float(temperature) logits = top_k_logits(logits, k=top_k) samples = tf.multinomial(logits, num_samples=1, output_dtype=tf.int32) return [ next_outputs['presents'] if past is None else tf.concat([past, next_outputs['presents']], axis=-2), samples, tf.concat([output, samples], axis=1) ] past, prev, output = body(None, context, context) def cond(*args): return True memo_, curre_, tokens = tf.while_loop( cond=cond, body=body, maximum_iterations=length - 1, loop_vars=[ past, prev, output ], shape_invariants=[ tf.TensorShape(Transformer.past_shape(hparams=hparams, batch_size=batch_size)), tf.TensorShape([batch_size, None]), tf.TensorShape([batch_size, None]), ], back_prop=False, ) # tokens: outputs, curre_: current word choice, memo_: the previous word sequence. return tokens, curre_, memo_ # reduce_dict = create_domain_dict(encoder_path, domain_dict) <file_sep>/Domain_transfer.py """ Written by <NAME>. The code is used for domain transfer. From larget scale general vocabulary to domain specific vocabulary. """ import tensorflow as tf from functools import lru_cache import json import re @lru_cache() def bytes_to_unicode(): """ Returns list of utf-8 byte and corresponding list of unicode strings """ bs = list(range(ord("!"), ord("~")+1)) + list(range(ord("¡"), ord("¬")+1)) + \ list(range(ord("®"), ord("ÿ")+1)) cs = bs[:] n = 0 for b in range(2**8): if b not in bs: bs.append(b) cs.append(2**8+n) n += 1 cs = [chr(n) for n in cs] return dict(zip(bs, cs)) def get_pairs(word): """Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs def byte_decoder(): """ Reversion of bytes_to_unicode """ return {v:k for k, v in bytes_to_unicode().items()} class Encoder: def __init__(self, encoder, bpe_dict=None): # # bpe_ranks : reduced version from bpe_merges self.encoder = encoder self.decoder = {v:k for k, v in self.encoder.items()} self.byte_encoder = bytes_to_unicode() self.byte_decoder = byte_decoder() if bpe_dict is not None: self.bpe_pair = dict(zip(bpe_dict, range(len(bpe_dict)))) self.cache = {} self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""") def bpe(self, token): if token in self.cache: return self.cache[token] word = tuple(token) pairs = get_pairs(word) if not pairs: return token while True: bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float('inf'))) if bigram not in self.bpe_ranks: break first, second = bigram new_word = [] i = 0 while i < len(word): try: j = word.index(first, i) new_word.extend(word[i:j]) i = j except: new_word.extend(word[i:]) break if word[i] == first and i < len(word)-1 and word[i+1]==second: new_word.append(first+second) i += 2 else: new_word.append(word[i]) i += 1 new_word = tuple(new_word) word = new_word if len(word) == 1: break else: pairs = get_pairs(word) word = ' '.join(word) self.cache[token] = word return word def encode(self, text): if bpe_dict is not None: bpe_tokens = [] for token in re.findall(self.pat, text): token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8')) bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' ')) return bpe_tokens else: nbpe_tokens = [] if " " in text: tokens = [] text_ = text.split() tokens.append(text_[0]) for sub_str in text_[1:]: tokens.append(" " + sub_str) nbpe_tokens.extend(self.encoder[bpe_token] for bpe_token in tokens) else: nbpe_tokens.append(self.encoder[text]) return nbpe_tokens def decode(self, tokens, dict_index): """ Input digit tokens index the word sequences. tokens: int decoder is the dictionary using index as key and word as the value. """ # byte_encoder = bytes_to_unicode() text = ''.join(self.decoder[token] for token in tokens) # text = ''.join([self.decoder[dict_index[token]] for token in tokens]) text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace") return text def global_domain(global_dict, domain_voc): """ Translating domain vocabulary by global dict index. """ def create_encoder(model_path, domain_dict): with open(model_path + 'encoder.json', 'r') as read_file: complete_encoder = json.load(read_file) with open(model_path + 'vocab.bpe', 'r', encoding="utf-8") as read_file: bpe_data = read_file.read() bpe_dict = [tuple(str_.split()) for str_ in bpe_data.split('\n')[1:-1]] # get domain_encoder reduce_encoder = {} byte_decoder = byte_decoder() for sub_text in domain_dict: for keys, index_seq in complete_encoder.items(): keys = bytearray([byte_decoder[c] for c in keys]).decode('utf-8', errors='replace') if sub_text == keys or sub_text.lower()==keys or \ (" " + sub_text==keys) or (" " + sub_text.lower()==keys): # dict {k:v} reduced_encoder[keys] = index_seq # get domain bpe: excluding out-vocabulary gram bpe_merges = [tuple(merge_str.split()) for merge_str in bpe_data.split('\n')[1:-1]] # by searching the bpe_merges to find provided dict, reversely get reduced bpe self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges)))) return Encoder( encoder = reduced_encoder, # using the reduced encoder dictionary bpe_ranks = bpe_ranks, ) <file_sep>/context_sampling.py # sampling sentences based on providing contexts import fire import json import os import numpy as np import tensorflow as tf import Transformer, generate, Domain_transfer def pretrain_model( model_name="pretrained", seed = 1234, nsamples=1, batch_size=1, length = 10, temperature=1, top_k = 9, models_dir='models', ): model_dir = os.path.expanduser(os.path.expandvars(models_dir)) if batch_size is None: batch_size = 1 assert nsamples % batch_size == 0
1146b6e5b19e7ca9ebb9fd4f47088ce196cfc986
[ "Markdown", "Python" ]
4
Markdown
34153320/Domain_language_model_I
3b6a97de3619b8ecae591074332869220f2e1afb
96c682403bc77a12025c320d5455c73cfcdefec0
refs/heads/master
<file_sep> package com.example.demo; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.api.Test; class BeverageApplicationTests { @Test public void testcostCalculate() { BeverageApplication apptest = new BeverageApplication(); String[] order = { "Chai,-sugar", "Chai", "Coffee,-milk" }; double result = 0.0; try { result = apptest.costCalculate(order); } catch (Exception e) { e.printStackTrace(); } assertEquals(11.5, result); } @Test public void testCheckforvalidOrder_a() { BeverageApplication apptest = new BeverageApplication(); String[] wrongorder = { "Chai,-sugar,-milk,-water", "Chai", "Coffee,-milk" }; Throwable exception = assertThrows( Exception.class, () -> { apptest.costCalculate(wrongorder); }); assertEquals("You can not remove all the ingredients from an item.", exception.getMessage()); } @Test public void testCheckforvalidOrder_b() { BeverageApplication apptest = new BeverageApplication(); String[] emptyorder = {}; Throwable exception = assertThrows( Exception.class, () -> { apptest.costCalculate(emptyorder); }); assertEquals("Order must contain atleast one item.", exception.getMessage()); } }
ce1e166e1b34905e36e81188597c127e9a94d6aa
[ "Java" ]
1
Java
sampadapingalkar/SampadaPingalkar
19b641bb27fcb4c8638925083cd7d469486d02f0
b64f03c42baa72aaec20de865e4b74a8dd1b9932
refs/heads/master
<file_sep># -*- coding:utf-8 -*- # Author: liuyi # email: <EMAIL> # python:3.6 from selenium import webdriver import time class Zhihuishu(object): def __init__(self, url): # 账号密码 self.url = url self.web = webdriver.Chrome() self.web.get(self.url) def login(self, user, pwd): """ 登錄 :param user: 用戶名 :param pwd: 密碼 :return: """ self.wait() school = self.web.find_element_by_id("clSchoolId") # self.web.execute_script("arguments[0].value = '2245';", school) self.web.find_element_by_id("clCode").clear() self.web.find_element_by_id("clCode").send_keys(user) self.web.find_element_by_id("clPassword").clear() self.web.find_element_by_id("clPassword").send_keys(pwd) self.web.find_element_by_class_name("wall-sub-btn").click() self.web.find_element_by_id("quickSearch").send_keys("吉首大学") self.web.execute_script("arguments[0].value = '2245';", school) self.web.find_element_by_class_name("wall-sub-btn").click() url = self.web.current_url def learn(self): """ 進入課程 :return: """ self.wait() # 切換頁面 # 獲取正在學校的課程的第一個 try: #獲取學習進度 p = self.web.find_elements_by_css_selector("span.mySchedulePrice") print(p[-1].value_of_css_property("left")) curricula = self.web.find_elements_by_link_text("继续学习") for i in range(len(p)): if i >= 2: self.web.find_element_by_id("course_recruit_studying_next").click() time.sleep(2) curricula.clear() curricula = self.web.find_elements_by_link_text("继续学习") prog = p[i].value_of_css_property("left") pp = int(prog[:-3]) else: prog = p[i].text pp = int(prog[-5:-3]) print(pp) if pp >= 82: continue else: if i>=2: curricula[i-2].click() else: curricula[i].click() except BaseException as e: self.web.find_element_by_partial_link_text("开始学习").click() # 获取打开的多个窗口句柄 windows = self.web.window_handles # 切换到当前最新打开的窗口 self.web.switch_to.window(windows[-1]) def offtis(self): """ 關閉提示 :return: """ self.wait() try: # 確定提示 self.web.find_element_by_class_name("popbtn_yes").click() # 我已知曉 # self.web.find_element_by_xpath('//*[@id="j-assess-criteria_popup"]/div[9]/div/a').click() # //*[@id="j-assess-criteria_popup"]/div[9]/div/a except BaseException as e: pass time.sleep(3) try: self.web.find_element_by_css_selector('div.knowbtn_box>a').click() except BaseException as e: print(e) def play(self): """播放視頻:return:""" while True: self.wait() o = self.web.find_element_by_css_selector("div.passTime") l = o.value_of_css_property('width') print(l) if l == "100%": try: self.web.find_element_by_partial_link_text("下一节").click() time.sleep(10) except BaseException: self.web.close() # 获取打开的多个窗口句柄 windows = self.web.window_handles # 切换到当前最新打开的窗口 self.web.switch_to.window(windows[-1]) self.learn() self.offtis() else: time.sleep(10) try: self.web.find_element_by_css_selector("div#popbox_overlay") # 判斷是否出現題目 self.web.find_element_by_css_selector("a.popbtn_cancel").click() except BaseException as e: print(e) continue def wait(self): self.web.implicitly_wait(30) def main(): url = "https://passport.zhihuishu.com/login?service=http://online.zhihuishu.com/onlineSchool/#studentID" user = input("请输入你的学号后三位:") pwd = input("请输入你的密碼: ") user = "2017402" + user zhihuishu = Zhihuishu(url) zhihuishu.login(user, pwd) zhihuishu.learn() zhihuishu.offtis() time.sleep(3) zhihuishu.play() if __name__ == "__main__": main()<file_sep> 智慧树自动挂机刷课脚本 1. 使用技术:python3 + selenium + chronedriver 2. 刷完一门课需要自己重新打开软件 3. 默认播放倍数1.0 4. 章节测试需要自己做,暂不能自动答题
cc821878eec44b6fe7db5a65fe160f1968803c1f
[ "Markdown", "Python" ]
2
Python
Mcliuyi/zhihuishu
4e72618025ca49a5625dc2ee2c41b3a1e83ba1bd
14931fe6819c03a3ad6ac9ee71dbc24ccc773b32
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; 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.Shapes; namespace WpfApp1 { /// <summary> /// Interaction logic for BrailleWindow.xaml /// </summary> public partial class BrailleWindow : Window { public BrailleWindow() { InitializeComponent(); } private void SetImage(string imagePath) { var og = new Bitmap(imagePath); var bitmap = new Bitmap( og, Math.Min(og.Width, int.TryParse(WidthTB.Text, out int width) ? width : int.MaxValue) / 2 * 2, Math.Min(og.Height, int.TryParse(HeightTB.Text, out int height) ? height : int.MaxValue) / 4 * 4); for (int y = 0; y < bitmap.Height; y++) { for (int x = 0; x < bitmap.Width; x++) { bitmap.SetPixel(x, y, bitmap.GetPixel(x, y).GetBrightness() > 0.5 ? System.Drawing.Color.White : System.Drawing.Color.Black); } } char[][] charArr = GetCharArr(bitmap); StringBuilder sb = new StringBuilder(); for (int y = 0; y < charArr.Length; y++) { sb.Append(new string(charArr[y])); sb.Append(Environment.NewLine); } new TextWindow(sb.ToString()).Show(); Dispatcher.Invoke(() => { Img.Source = ToWpfBitmap(bitmap); }); } private char[][] GetCharArr(Bitmap bitmap) { char[][] ret = new char[bitmap.Height / 4][]; for (int retY = 0; retY < ret.Length; retY++) { ret[retY] = new char[bitmap.Width / 2]; for (int retX = 0; retX < ret[retY].Length; retX++) { ret[retY][retX] = '\u2800'; if (IsBlack(retX, retY, 0, 0, bitmap)) { ret[retY][retX]++; } if (IsBlack(retX, retY, 0, 1, bitmap)) { ret[retY][retX] += (char)2; } if (IsBlack(retX, retY, 0, 2, bitmap)) { ret[retY][retX] += (char)4; } if (IsBlack(retX, retY, 0, 3, bitmap)) { ret[retY][retX] += (char)8; } if (IsBlack(retX, retY, 1, 0, bitmap)) { ret[retY][retX] += (char)16; } if (IsBlack(retX, retY, 1, 1, bitmap)) { ret[retY][retX] += (char)32; } if (IsBlack(retX, retY, 1, 2, bitmap)) { ret[retY][retX] += (char)64; } if (IsBlack(retX, retY, 1, 3, bitmap)) { ret[retY][retX] += (char)128; } } } return ret; } private bool IsBlack(int retX, int retY, int x, int y, Bitmap bitmap) { System.Drawing.Color col = bitmap.GetPixel(retX * 2 + x, retY * 4 + y); return col.ToArgb() == System.Drawing.Color.Black.ToArgb(); } public static BitmapSource ToWpfBitmap(Bitmap bitmap) { using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, ImageFormat.Bmp); stream.Position = 0; BitmapImage result = new BitmapImage(); result.BeginInit(); // According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed." // Force the bitmap to load right now so we can dispose the stream. result.CacheOption = BitmapCacheOption.OnLoad; result.StreamSource = stream; result.EndInit(); result.Freeze(); return result; } } public string FileName { get; set; } private void SelectPic_Click(object sender, RoutedEventArgs e) { Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog { DefaultExt = ".png", Filter = "(*.jpeg;*.png;*.jpg;*.bmp)|*.jpeg;*.png;*.jpg;*.bmp" }; // Display OpenFileDialog by calling ShowDialog method bool? result = dlg.ShowDialog(); // Get the selected file name and display in a TextBox if (result == true) { // Open document FileName = dlg.FileName; } } private void BraillePic_Click(object sender, RoutedEventArgs e) { if (!string.IsNullOrEmpty(FileName)) { SetImage(FileName); } } } } <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.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace WpfApp1 { /// <summary> /// Interaction logic for TextWindow.xaml /// </summary> public partial class TextWindow : Window { public TextWindow(string text) { InitializeComponent(); TB.Text = text; } private void TB_PreviewMouseWheel(object sender, MouseWheelEventArgs e) { if (Keyboard.IsKeyDown(Key.LeftCtrl)) { if (e.Delta < 0) { if (TB.FontSize > 1) { TB.FontSize--; } } else { TB.FontSize++; } e.Handled = true; } } } }
07415a512f4bcc7b6d4eae1e2ffeba5f2a67bf13
[ "C#" ]
2
C#
LironMat/Brailler
a263e30310a389cc97a3d7f69475a45f518d9bdf
d454a3bef8871e598a198e34d2735a4f6060af43
refs/heads/master
<repo_name>TheCodeDestroyer/dotfiles<file_sep>/exec/node-update #!/usr/bin/env zsh # node-update - A script to handle NodeJS Update process python ~/bin/exec/check-nvm-lts.py | zsh <file_sep>/exec/check-nvm-lts.py from string import Template from os import system import subprocess installCommandTemplate = Template("source ~/.nvm/nvm.sh && nvm install ${new} --reinstall-packages-from=${old}") uninstallCommandTemplate = Template("source ~/.nvm/nvm.sh && nvm uninstall ${old}") currentVersionsCommand = "source ~/.nvm/nvm.sh && nvm ls --no-alias --no-colors" availableVersionsCommand = "source ~/.nvm/nvm.sh && nvm ls-remote --lts --no-colors | grep 'Latest'" currentVersions = [] availableVersions = [] proc = subprocess.Popen(["/bin/bash", "-i", "-c", currentVersionsCommand], stdout=subprocess.PIPE, stdin=None) out, err = proc.communicate() rawVersionList = out.decode("utf-8").strip().split("\n") #print("Current versions:") for rawVersion in rawVersionList: version = rawVersion.replace("->", "").replace("*", "").strip() currentVersions.append(version) #print(version) proc = subprocess.Popen(["/bin/bash", "-i", "-c", availableVersionsCommand], stdout=subprocess.PIPE, stdin=None) out, err = proc.communicate() rawVersionList = out.decode("utf-8").strip().split("\n") #print("Available versions:") for rawVersion in rawVersionList: foundVersion = rawVersion.replace("->", "").replace("*", "").strip() start = foundVersion.find("(") version = foundVersion if start != -1: version = foundVersion[0:start].strip() #print(version) availableVersions.append(version) proc = subprocess.Popen(["/bin/zsh", "-c", "source ~/.nvm/nvm.sh && nvm unload"]) proc.wait() print("echo '========================'") print("echo '== CHECKING INSTALLED =='") print("echo '========================'") for version in currentVersions: if version in availableVersions: print("echo '%s is already latest LTS'" %version) continue major = version.split(".")[0] newVersionList = [x for x in availableVersions if x.startswith(major)] if not newVersionList: print("echo '%s is not an LTS'" %version) continue else: print("echo '%s is out of date'" %version) newVersion = newVersionList[0] print(installCommandTemplate.substitute(new=newVersion, old=version)) print("echo 'INSTALLED %s'" %newVersion) print(uninstallCommandTemplate.substitute(old=version)) print("echo 'UNINSTALLED %s'" %version) <file_sep>/sheldon.toml # `sheldon` configuration file # ---------------------------- # # You can modify this file directly or you can use one of the following # `sheldon` commands which are provided to assist in editing the config file: # # - `sheldon add` to add a new plugin to the config file # - `sheldon edit` to open up the config file in the default editor # - `sheldon remove` to remove a plugin from the config file # # See the documentation for more https://github.com/rossmacarthur/sheldon#readme shell = "zsh" [templates] defer = "{% for file in files %}zsh-defer source \"{{ file }}\"\n{% endfor %}" [plugins] [plugins.zsh-defer] github = "romkatv/zsh-defer" [plugins.powerlevel10k] github = 'romkatv/powerlevel10k' [plugins.zsh-completions] github = 'zsh-users/zsh-completions' [plugins.fast-syntax-highlighting] github = 'zdharma-continuum/fast-syntax-highlighting' [plugins.zsh-history-substring-search] github = 'zsh-users/zsh-history-substring-search' [plugins.alias-tips] github = 'djui/alias-tips' [plugins.zsh-direnv] github = 'ptavares/zsh-direnv' apply = ["defer"] [plugins.zsh-auto-nvm] github = 'manlao/zsh-auto-nvm' apply = ["defer"] [plugins.zsh-pyenv] github = 'mattberther/zsh-pyenv' apply = ["defer"] [plugins.fasd] github = 'clvv/fasd' use = ['fasd'] [plugins.ohmyzsh] github = 'ohmyzsh/ohmyzsh' dir = 'plugins' use = [ '{history,sudo,colored-man-pages,command-not-found}/*.plugin.zsh', '{encode64,extract,fasd,httpie}/*.plugin.zsh', '{git,gitfast,git-extras,gh}/*.plugin.zsh', '{node,nvm,yarn,npm,brew}/*.plugin.zsh', '{docker,docker-compose,ansible,kubectl,helm}/*.plugin.zsh', '{flutter}/*.plugin.zsh', '{aws,gcloud}/*.plugin.zsh', '{1password}/*.plugin.zsh' ] [plugins.ohmyzsh-linux] github = 'ohmyzsh/ohmyzsh' dir = 'plugins' use = [ '{debian,minikube}/*.plugin.zsh', ] profiles = ['linux'] [plugins.ohmyzsh-macos] github = 'ohmyzsh/ohmyzsh' dir = 'plugins' use = [ '{macos}/*.plugin.zsh', ] profiles = ['macos'] [plugins.compinit] inline = 'autoload -Uz compinit && zsh-defer compinit' <file_sep>/exec/refresh-commodities.py #!/usr/bin/env python import os import math import time import json from requests import Request, Session from requests.exceptions import ConnectionError, Timeout, TooManyRedirects, HTTPError, RequestException from dotty_dict import dotty from dotenv import load_dotenv import yfinance as yf load_dotenv() token = os.getenv('NOTION_TOKEN') database_id = os.getenv('NOTION_COMODITIES_DB') session = Session() session.hooks = { 'response': lambda r, *args, **kwargs: r.raise_for_status() } def mapCoinGeckoResultToComodity(result): return { 'id': result.get('id'), 'name': result.get('name'), 'symbol': result.get('symbol', '/').upper(), 'image_url': result.get('image.large'), 'price': result.get('market_data.current_price.usd'), 'all_time_high': result.get('market_data.ath.usd'), } def getCrypto(coin_id): url = f'https://api.coingecko.com/api/v3/coins/{coin_id}' parameters = { 'localization':'false', 'tickers':'true', 'market_data':'true', 'community_data':'true', 'developer_data':'true', 'sparkline':'true' } try: response = session.get(url, params=parameters) result_dict = response.json() return dotty(result_dict) except RequestException as e: print(e.response.text) def getCryptoNetworkInfo(): url = f'https://whattomine.com/coins.json' try: response = session.get(url) result_dict = response.json() nethash_result = result_dict['coins'] return dotty(nethash_result) except RequestException as e: print(e.response.text) def getNotionData(): url = f'https://api.notion.com/v1/databases/{database_id}/query' headers={ 'Accept': 'application/json', 'Notion-Version': '2022-06-28', 'Content-Type': 'application/json', 'Authorization': f'Bearer {token}', } try: response = session.post(url, headers=headers) result_dict = response.json() comodity_list_result = result_dict['results'] return comodity_list_result except RequestException as e: print(e.response.text) def updateNotionData(comodity): del comodity['last_edited_by'] del comodity['last_edited_time'] del comodity['properties.Updated At'] comodityId = comodity.get('id') url = f'https://api.notion.com/v1/pages/{comodityId}' headers={ 'Accept': 'application/json', 'Notion-Version': '2022-06-28', 'Content-Type': 'application/json', 'Authorization': f'Bearer {token}', } try: response = session.patch(url, headers=headers,data=comodity.to_json()) except RequestException as e: print(e.response.text) def getCoin(coin_id): rawCoin = getCrypto(coin_id) coin = mapCoinGeckoResultToComodity(rawCoin) return coin def getNetworkHash(crypto_network_info, coin_symbol): for net_info_tuple in crypto_network_info.items(): net_info = net_info_tuple[1] if net_info.get('tag') == coin_symbol: nethash = net_info.get('nethash') if isinstance(nethash, int) and nethash > 0: return math.ceil(nethash / 1000000000) else: return 0 def updateCryptoComodity(comodity, crypto_network_info): coin_id = comodity.get('properties.Id.rich_text.0.text.content') if coin_id: coin = getCoin(coin_id) coin_symbol = coin.get('symbol') nethash = getNetworkHash(crypto_network_info, coin_symbol) comodity['properties.Name.title.0.text.content'] = coin.get('name') comodity['properties.Symbol.rich_text.0.text.content'] = coin_symbol comodity['properties.Price.number'] = coin.get('price') comodity['properties.All Time High.number'] = coin.get('all_time_high') comodity['properties.NetHash.number'] = nethash comodity['icon'] = { 'type': 'external', 'external': { 'url': coin.get('image_url') } } updateNotionData(comodity) time.sleep(5) def updateStockComodity(comodity, symbol): stock_raw = yf.Ticker(symbol) stock = dotty(stock_raw.info) if stock.get('regularMarketPrice'): comodity['properties.Name.title.0.text.content'] = stock.get('shortName') comodity['properties.Price.number'] = stock.get('regularMarketPrice') comodity['properties.All Time High.number'] = stock.get('fiftyTwoWeekHigh') comodity['icon'] = { 'type': 'external', 'external': { 'url': stock.get('logo_url') } } updateNotionData(comodity) def refreshComodities(): comodity_list = getNotionData() crypto_network_info = getCryptoNetworkInfo() print('importing data:') for comodityRaw in comodity_list: comodity = dotty(comodityRaw) comodityType = comodity.get('properties.Type.select.name') symbol = comodity.get('properties.Symbol.rich_text.0.text.content') if comodityType == 'Crypto': print(symbol) updateCryptoComodity(comodity, crypto_network_info) elif comodityType == 'Stock': print(symbol) updateStockComodity(comodity, symbol) refreshComodities() <file_sep>/.zshenv setopt BANG_HIST setopt EXTENDED_HISTORY setopt SHARE_HISTORY setopt HIST_EXPIRE_DUPS_FIRST setopt HIST_IGNORE_DUPS setopt HIST_IGNORE_ALL_DUPS setopt HIST_FIND_NO_DUPS setopt HIST_IGNORE_SPACE setopt HIST_SAVE_NO_DUPS setopt HIST_VERIFY setopt HIST_BEEP # EXPORTS ## Common export PATH=~/bin/exec:$PATH export EDITOR=nano export LANG="en_US.UTF-8" ## ZSH export HISTFILE="${HOME}/.zsh_history" export HISTSIZE=10000 export SAVEHIST=10000 export ZSH_CACHE_DIR="${HOME}/.zsh_cache" ### ZHS plugin stuff export ZSH_PLUGINS_ALIAS_TIPS_EXCLUDES="g st y" export ZSH_PLUGINS_ALIAS_TIPS_TEXT="You should use: " ## Android export ANDROID_SDK_ROOT=~/Work/software/android/sdk export ANDROID_HOME=$ANDROID_SDK_ROOT export PATH=$PATH:$ANDROID_SDK_ROOT/emulator export PATH=$PATH:$ANDROID_SDK_ROOT/platform-tools export PATH=$PATH:$ANDROID_SDK_ROOT/tools export PATH=$PATH:$ANDROID_SDK_ROOT/tools/bin ## Node export NVM_LAZY_LOAD=true export PATH=~/.yarn/bin:$PATH export PNPM_HOME=~/.local/share/pnpm export PATH=$PNPM_HOME:$PATH ## Python export PATH=~/.local/bin:$PATH ## Ansible export ANSIBLE_NOCOWS=1 ## Go export PATH=~/go/bin:$PATH ## Secrets export NPM_AUTH_TOKEN="op://private/npm/auth/token" export NPM_USERNAME="op://private/npm/username" export NPM_EMAIL="op://private/npm/username" export DOCKER_USERNAME="op://private/docker/username" export DOCKER_AUTH_TOKEN="op://private/docker/auth/token" # Sheldon local OS_TYPE=$(uname -s) if [[ "${OS_TYPE}" == "Darwin" ]]; then export SHELDON_PROFILE=macos elif [[ "${OS_TYPE}" == "Linux" ]]; then export SHELDON_PROFILE=linux else export SHELDON_PROFILE=unknown fi # Aliases alias ghee-default="ghee set --email <EMAIL>" alias ghee-work="ghee set --email <EMAIL>" alias ls='lsd' alias c='z' alias opn='a -e xdg-open' alias edt='f -e "$EDITOR"' alias scan-code="cloc --exclude-dir=$(tr '\n' ',' < ~/.clocignore) ./" # PNPM alias pn="pnpm" alias pni="pnpm install" alias pna="pnpm add" alias pnad="pnpm add --save-dev" alias pnap="pnpm add --save-peer" alias pnb="pnpm build" alias pnd="pnpm dev" alias pnf="pnpm format" alias pnga="pnpm add --global" alias pngls="pnpm list --global" alias pngrm="pnpm remove --global" alias pngu="pnpm upgrade --interactive --global" alias pnln="pnpm lint" alias pnrm="pnpm remove" alias pnst="pnpm start" alias pnt="pnpm test" alias pnui="pnpm upgrade --interactive" alias pnuil="pnpm update --interactive --latest" alias pnv="pnpm version" alias pny="pnpm why" # GIT alias gcmi="git commit" alias gcstg="git checkout staging" <file_sep>/.zshrc autoload -U +X compinit && compinit # Enable Powerlevel10k instant prompt. Should stay close to the top of ~/.zshrc. # Initialization code that may require console input (password prompts, [y/n] # confirmations, etc.) must go above this block; everything else may go below. if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" fi eval "$(sheldon source)" eval "$(fasd --init auto)" #PROFILES source ~/.profile #FUNCTIONS source ~/.zshfn source ~/.config/op/plugins.sh # To customize prompt, run `p10k configure` or edit ~/.p10k.zsh. [[ ! -f ~/.p10k.zsh ]] || source ~/.p10k.zsh # tabtab source for packages # uninstall by removing these lines [[ -f ~/.config/tabtab/zsh/__tabtab.zsh ]] && . ~/.config/tabtab/zsh/__tabtab.zsh || true case `uname` in Darwin) bindkey '^[[A' history-substring-search-up bindkey '^[[B' history-substring-search-down ;; Linux) bindkey "$terminfo[kcuu1]" history-substring-search-up bindkey "$terminfo[kcud1]" history-substring-search-down ;; esac #COMPLETION OPTION STACKING zstyle ':completion:*:*:docker:*' option-stacking yes zstyle ':completion:*:*:docker-*:*' option-stacking yes
6c9e515798ad6d56d4e2248eadfff3faa2187e6c
[ "TOML", "Python", "Shell" ]
6
Shell
TheCodeDestroyer/dotfiles
8741db81391e158ee405e726d46afc1ba5b9711c
9b7f256973bb24e3169850fc33050c8ddbf6b46a
refs/heads/master
<repo_name>dkapur17/Spot-o-Matic<file_sep>/frontend/src/components/NewSearch.jsx import { useState, useEffect } from 'react'; import { motion } from 'framer-motion'; import { useHistory } from 'react-router-dom'; import TinderCard from 'react-tinder-card'; import { nanoid } from 'nanoid' import axios from 'axios'; import swal from 'sweetalert'; const NewSearch = () => { return ( <motion.div className='container mt-2 justify-content-center' initial={{ y: 100, opacity: 0 }} animate={{ y: 0, opacity: 1 }} exit={{ y: 100, opacity: 0 }} transition={{ duration: 1 }} > <h1 className='display-1 text-center text-danger mb-2' id='title'>Help Us Help You!</h1> <p className='lead text-danger text-center'>Swipe RIGHT if you're interested or LEFT if you're not.</p> <CardsWrapper /> </motion.div> ) }; const CardsWrapper = () => { const lists = { 'Watch Movies': [], 'Leisure Time': ['Picnic Spots', 'Museums', 'Art Galleries', 'Historic Monuments'], 'Games/Sports': ['Indoor Games', 'Trekking/Camping'], 'Clubbing': ['Drinking', 'Dancing'], 'Eating Out': ['Indian Cuisine', 'Chinese Cuisine', 'Fast Food', 'Continental Cuisine'] }; const superSections = ['Watch Movies', 'Leisure Time', 'Games/Sports', 'Clubbing', 'Eating Out'] const [cardData, setCardData] = useState([ ...lists['Leisure Time'], ...lists['Games/Sports'], ...lists['Clubbing'], ...lists['Eating Out'], ...superSections ]); const [preferences, setPreferences] = useState({ id: nanoid(10), eatingOut: { score: 0, variants: '' }, clubbing: { score: 0, variants: '' }, playingGames: { score: 0, variants: '' }, watchingMovies: { score: 0, variants: '' }, leisureTime: { score: 0, variants: '' }, }); const [loading, setLoading] = useState(false); const history = useHistory(); useEffect(() => { const sendPreferences = async () => { try { setLoading(true); const res = await axios.post('http://localhost:5000/setPreferences', preferences); console.log(res.data); console.log(preferences); setLoading(false); history.push(`/showLink/${preferences.id}`); } catch { swal("Error!", "Unable to write to the Database. Please try again later.", "error"); history.push('/'); } } if (!cardData.length) sendPreferences(); }, [cardData, preferences, history]); const handleCardLeavingScreen = (direction, item) => { if (superSections.includes(item)) { if (direction === 'left') setCardData((currentCardData) => currentCardData.filter(cardItem => cardItem !== item && !lists[item].includes(cardItem))); else { setCardData((currentCardData) => currentCardData.filter(cardItem => cardItem !== item)); switch (item) { case "Eating Out": setPreferences((currentPreferences) => ({ ...currentPreferences, eatingOut: { score: currentPreferences.eatingOut.score + 1, variants: currentPreferences.eatingOut.variants } })); break; case "Clubbing": setPreferences((currentPreferences) => ({ ...currentPreferences, clubbing: { score: currentPreferences.clubbing.score + 1, variants: currentPreferences.clubbing.variants } })); break; case "Games/Sports": setPreferences((currentPreferences) => ({ ...currentPreferences, playingGames: { score: currentPreferences.playingGames.score + 1, variants: currentPreferences.playingGames.variants } })); break; case "Leisure Time": setPreferences((currentPreferences) => ({ ...currentPreferences, leisureTime: { score: currentPreferences.leisureTime.score + 1, variants: currentPreferences.leisureTime.variants } })); break; case "Watching Movies": setPreferences((currentPreferences) => ({ ...currentPreferences, watchingMovies: { score: currentPreferences.watchingMovies.score + 1, variants: currentPreferences.leisureTime.variants } })); break; default: break; } } } else { setCardData((currentCardData) => currentCardData.filter(cardItem => cardItem !== item)); if (direction === 'right') { if (lists["Eating Out"].includes(item)) setPreferences((currentPreferences) => ({ ...currentPreferences, eatingOut: { score: currentPreferences.eatingOut.score, variants: currentPreferences.eatingOut.variants + item + '-' } })); else if (lists["Clubbing"].includes(item)) setPreferences((currentPreferences) => ({ ...currentPreferences, clubbing: { score: currentPreferences.clubbing.score, variants: currentPreferences.clubbing.variants + item + '-' } })); else if (lists["Games/Sports"].includes(item)) setPreferences((currentPreferences) => ({ ...currentPreferences, playingGames: { score: currentPreferences.playingGames.score, variants: currentPreferences.playingGames.variants + item + '-' } })); else if (lists["Leisure Time"].includes(item)) setPreferences((currentPreferences) => ({ ...currentPreferences, leisureTime: { score: currentPreferences.leisureTime.score, variants: currentPreferences.leisureTime.variants + item + '-' } })); else if (lists["Watch Movies"].includes(item)) setPreferences((currentPreferences) => ({ ...currentPreferences, watchingMovies: { score: currentPreferences.watchingMovies.score, variants: currentPreferences.watchingMovies.variants + item + '-' } })); } } } return loading ? <div className="row justify-content-center mt-5"> <div className="spinner-border text-danger" role="status" style={{ width: "5rem", height: "5rem" }}> <span className="sr-only">Loading...</span> </div> </div> : ( <div className='cardContainer row justify-content-center mt-5'> {cardData.map((item, i) => <TinderCard key={Math.random()} className='swipe' preventSwipe={['up', 'down']} onCardLeftScreen={(direction) => handleCardLeavingScreen(direction, item)} > <div className="card text-white bg-danger mb-3" style={{ width: "40rem", height: "30rem" }}> <div className="card-header text-center"> <p className="lead">Do you like...</p> </div> <div className="card-body d-flex flex-column justify-content-center"> <h1 className="card-title display-1 text-center">{item}</h1> </div> </div> </TinderCard> )} </div> ) } export default NewSearch;<file_sep>/frontend/src/App.jsx import { Switch, Route, useLocation } from 'react-router-dom' import { AnimatePresence } from 'framer-motion' import 'bootstrap/dist/js/bootstrap' import 'bootstrap/dist/css/bootstrap.css' import 'jquery' import 'popper.js' import './App.css' import Home from './components/Home' import New from './components/New' import Continue from './components/Continue' import NewSearch from './components/NewSearch' import ShowCode from './components/ShowCode' import ContinueSearch from './components/ContinueSearch'; import DisplayResults from './components/DisplayResults' const App = () => { const location = useLocation(); return ( <AnimatePresence exitBeforeEnter> <Switch location={location} key={location.pathname}> <Route path='/' exact component={Home} /> <Route path='/new' exact component={New} /> <Route path='/continue' exact component={Continue} /> <Route path='/search/new' exact component={NewSearch} /> <Route path='/search/continue/:code' exact component={ContinueSearch} /> <Route path='/showLink/:code' exact component={ShowCode} /> <Route path='/results' exact component={DisplayResults} /> </Switch> </AnimatePresence> ) }; export default App;<file_sep>/backend/server.js const fs = require('fs'); const express = require('express'); const queries = require('./queries'); const cors = require('cors'); require('dotenv').config() const PORT = 5000 const app = express(); app.use(express.json()); app.use(express.urlencoded({ extended: true })) app.use(cors()); app.post('/setPreferences', queries.setPreferences); app.post('/getPreferences', queries.getPreferences); app.listen(PORT, () => { console.log(`Server listening on port ${PORT}`) });<file_sep>/README.md # Spot-💖-Matic ![Banner](README_ASSETS/Banner.png) *Submission for Hackthrob 2021* <hr> ### Introduction Finding love is tough, but finding things to do on your next date is even tougher. Well, no more! Introducing **Spot-o-Matic**. Spot-o-Matic takes into account your and your partner's preferences and suggests SPOTS for your next date. The UI is inspired by the universally beloved Tinder swipe-style. ![Swipe Demo GIF](README_ASSETS/swipeDemo.gif) The preferences of both partners are taken into account and passed through our *sophisticated* algorithm, that then rates the different activities based on your interests in them and then provides you a list of places on Google Maps that it thinks you would like to spend your next date at. <!-- ![Google Maps Embeds](README_ASSETS/mapEmbed.gif) --> ### How to use it It starts with one partner looking for something to do on their next date. They open up Spot-o-Matic and start a new search. They then provide their interests. Once that's done, they are given a 10 character long code. They share this code with their partner. The partner now opens Spot-o-Matic and continues the search by providing the code they recieved. They too provide their interests. The collection of the two sets of interests are evaluated and the potential SPOTs of interest are shown. ### Getting Technical The UI is created in React. It interfaces with a CockroachDB database that stores the user preferences through an Express backed. Maps were made possible by the google-maps API. <file_sep>/frontend/src/components/DisplayResults.jsx import { useState, useEffect } from 'react'; import { useHistory } from 'react-router-dom'; import { motion } from 'framer-motion' const iframeStyle = { border: "3px solid #d9534f", borderRadius: "10px" }; const DisplayResults = (props) => { const [numMaps, setNumMaps] = useState(1) const [mapQuery, setMapQuery] = useState([]) const sortScore = (a, b) => { return b.score - a.score; } const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0); const history = useHistory(); const filterQueries = (act) => { const variants = act.variants.split('-'); let max_occur = { key: '', freq: -1 }; for (let i = 0; i < variants.length; i++) { let count = countOccurrences(variants, variants[i]) if (count > max_occur.freq) max_occur = { key: variants[i], freq: count } } if (max_occur.freq === 1) { if (variants.length > 1) { setNumMaps(2); let query1 = variants[0].split(' ').join('+'); let query2 = variants[1].split(' ').join('+'); setMapQuery([query1, query2]) } else { let query1 = variants[0].split(' ').join('+'); setMapQuery([query1]) } } else { let query1 = max_occur.key.split(' ').join('+'); setMapQuery([query1]) } } useEffect(() => { const Analyzer = () => { let raw = props.location.state.preferences let data = [{ key: 'eatingOut', ...raw.eatingOut }, { key: 'leisureTime', ...raw.leisureTime }, { key: 'playingGames', ...raw.playingGames }, { key: 'clubbing', ...raw.clubbing }, { key: 'watchingMovies', ...raw.watchingMovies }] data.sort(sortScore) const best = data.filter(activity => activity.score >= 2) if (best !== []) { filterQueries(best[0]); return; } const med = data.filter(activity => activity.score === 1) if (med !== []) { filterQueries(med[0]); return; } } Analyzer(); }, []) return ( <motion.div className='container my-5 justify-content-center' initial={{ y: 100, opacity: 0 }} animate={{ y: 0, opacity: 1 }} exit={{ y: 100, opacity: 0 }} transition={{ duration: 1 }} > <h1 id='title' className='text-danger text-center display-3 mb-5'>Spot-💖-Matic suggests...</h1> {mapQuery.length === 0 ? ( <div className="d-flex justify-content-center" style={{ marginTop: '20rem' }}> <div className="spinner-grow text-primary" role="status"> <span className="sr-only">Loading...</span> </div> </div> ) : numMaps === 1 ? ( <div className='row justify-content-center'> <div> <iframe width="500" height="400" frameBorder="0" style={iframeStyle} title={`${mapQuery[0]}`} className="embed-responsive-item" src={`https://www.google.com/maps/embed/v1/search?q=${mapQuery[0]}+near+me&key=<KEY>`} allowFullScreen></iframe> <p className="text-danger text-center lead">SUGGESTED SPOTS: {mapQuery[0].split('+').join(' ').toUpperCase()}</p> </div> </div> ) : ( <div className='row justify-content-around'> <div className="col"> <iframe width="500" height="400" frameBorder="0" style={iframeStyle} title={`${mapQuery[0]}`} className="embed-responsive-item" src={`https://www.google.com/maps/embed/v1/search?q=${mapQuery[0]}+near+me&key=<KEY>`} allowFullScreen></iframe> <p className="text-danger text-center lead">SUGGESTED SPOTS: {mapQuery[0].split('+').join(' ').toUpperCase()}</p> </div> <div className="col"> <iframe width="500" height="400" frameBorder="0" style={iframeStyle} title={`${mapQuery[1]}`} className="embed-responsive-item" src={`https://www.google.com/maps/embed/v1/search?q=${mapQuery[1]}+near+me&key=<KEY>`} allowFullScreen></iframe> <p className="text-danger text-center lead">SUGGESTED SPOTS: {mapQuery[1].split('+').join(' ').toUpperCase()}</p> </div> </div> ) } <div className="row justify-content-center"> < button className="love-button" onClick={() => history.push('/')}>Another Search?</button> </div> </motion.div > ) } export default DisplayResults;<file_sep>/frontend/src/components/New.jsx import { useHistory } from 'react-router-dom'; import { motion } from 'framer-motion'; const New = () => { const history = useHistory(); const handleSubmit = () => { history.push('/search/new') }; return ( <motion.div className='container my-5 justify-content-center' initial={{ y: 100, opacity: 0 }} animate={{ y: 0, opacity: 1 }} exit={{ y: 100, opacity: 0 }} transition={{ duration: 1 }} > <h1 className="display-1 text-center text-danger mb-5" id="title">New Search</h1> <p className="lead text-danger text-center">Finding the perfect partner is tough. But whats even tougher is finding fun things to do together! Spot-O-Matic takes into account your and your partner's interests and tries to suggest activites fo you to try out. It even provides you locations (or SPOTS) to visit near you, where you can have fun with your better half. On each card, swipe <strong>RIGHT 👉</strong> if you are interested in what the card says or swipe <strong>LEFT 👈</strong> if you're not. Just let us know your interests and we will help you find the perfect SPOT for your next date 😉. </p> <div className="row justify-content-center mt-5"> <button className="love-button" onClick={handleSubmit}>Lets Do This!</button> </div> </motion.div> ) } export default New;
2e6a1de7c2eca4202d872137161f29dbb7f7bf7d
[ "JavaScript", "Markdown" ]
6
JavaScript
dkapur17/Spot-o-Matic
9f20cc8ef07065e0dfb04c043835566659b06123
1e255e262910d0108ab4a2d1f53646690333a4d4
refs/heads/master
<file_sep>import React from 'react' import { format } from 'date-fns' import { BrowserRouter as Router, Link } from "react-router-dom"; const MostViewBlogs = ({ blogs }) => { return ( <section className="blog"> <div className="container mx-auto"> <div className="text-4xl font-bold p-16 pb-10 text-center">Our Most View <span className="text-blue-500">Blogs</span></div> <div className="grid grid-cols-3 gap-10 pb-24"> {blogs.map((blog, index) => ( <div className="blog-item bg-gray-200 rounded" key={index}> <div className="overflow-hidden"> <img src={`../../images/${blog.image[0].name}`} className="blog-img transform hover:scale-110 transition duration-500" alt="" /> </div> <div className="p-4"> <p className="blog-name text-xl font-semibold mb-2">{blog.name}</p> <div className="my-2"> <span className="text-blue-500"><i class="fas fa-user"></i> </span> Admin &nbsp;&nbsp;&nbsp; <span className="text-blue-500"><i class="fas fa-calendar-alt"></i> </span>{format(new Date(2020, 1, 11), 'yyyy-MM-dd')} &nbsp;&nbsp;&nbsp; <span className="text-blue-500"><i class="fas fa-tags"></i> </span> {blog.tag.name} &nbsp;&nbsp;&nbsp; </div> <p className="my-2">{blog.desc}</p> <button className="text-base font-semibold text-blue-500"><Link to=""> Read more</Link></button> </div> </div> ))} </div> </div> </section> ) } export default MostViewBlogs <file_sep>import React from 'react' const Services = () => { return ( <section className="services"> this are services </section> ) } export default Services <file_sep>import React from 'react' import Customers from '../Customers' import Welcome from '../Welcome' import Why from '../Why' const About = () => { return ( <section className="about"> <Welcome/> <Why/> <Customers/> </section> ) } export default About <file_sep>import React from 'react' const Customers = () => { return ( <section className="customer"> <div className="container mx-auto text-white"> <div className="text-4xl font-bold p-16 pb-10 text-center">Our Happy <span className="text-blue-500">Customers</span></div> <div className="grid grid-cols-3"> <div className="text-center customer-item"> <img src="../../images/customer1.png" className="mx-auto" alt=""/> <p className="text-blue-500 text-2xl font-bold my-3">Hilpton Broad</p> <p className="mb-24 px-10">Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of cla ssical Latin literature from 45 BC, making it over 2000 years old.</p> </div> <div className="text-center customer-item"> <img src="../../images/customer2.png" className="mx-auto" alt="" /> <p className="text-blue-500 text-2xl font-bold my-3"><NAME></p> <p className="mb-24 px-10">Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of cla ssical Latin literature from 45 BC, making it over 2000 years old.</p> </div> <div className="text-center customer-item"> <img src="../../images/customer3.png" className="mx-auto" alt="" /> <p className="text-blue-500 text-2xl font-bold my-3">Stive Philips</p> <p className="mb-24 px-10">Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of cla ssical Latin literature from 45 BC, making it over 2000 years old.</p> </div> </div> </div> </section> ) } export default Customers <file_sep>import React from 'react' import { BrowserRouter as Router, Link } from "react-router-dom"; const Banner = () => { return ( <section className="banner flex text-center text-white grid justify-items-center items-center"> <div className="container mx-auto py-64"> <div className="text-5xl font-bold">Effect Of Feng Shui</div> <div className="text-medium px-64">It focuses on how things in our physical world influence how we think and behave. Feng shui originated in China and is a belief system in which there is a spiritual relationship between the physical elements of nature and is a belief system in which there is a spiritual relationship</div> <div className="my-20"> <Link className="hover-btn bg-blue-500 text-white font-bold px-6 py-2 mx-2 rounded hover:no-underline" to="/services"><span> Our Services</span></Link> <Link className="hover-btn bg-blue-500 text-white font-bold px-6 py-2 mx-2 rounded hover:no-underline" to="/contact"><span> Contact Us</span></Link> </div> </div> </section> ) } export default Banner <file_sep>import React from 'react' const Staffs = () => { return ( <section className="staff"> <div className="container mx-auto"> <div className="text-4xl font-bold p-16 pb-10 text-center">Our Professional <span className="text-blue-500">Staff</span></div> <div className="grid grid-cols-2 gap-8 mb-24"> <div className="staff-item grid grid-cols-2"> <img src="images/artist1.jpg" width="80%" alt="" /> <div className="bg-blue-500 pt-4 pl-4 pr-4 text-white -ml-16"> <p className="font-bold text-2xl"><NAME></p> <p className="text-base mb-3">Chief Advisior</p> <p className="text-md">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed et tempus erat, et luctus quam. Maecenas cursus porta tortor, vel consectetur ante volutpat imperdiet.</p> <div className="pt-2"> <i className="fab fa-facebook-f px-2"></i> <i className="fab fa-twitter px-2"></i> <i className="fab fa-google px-2"></i> <i className="fab fa-linkedin-in px-2"></i> </div> </div> </div> <div className="staff-item grid grid-cols-2"> <img src="images/artist2.jpg" width="80%" alt="" /> <div className="bg-blue-500 pt-4 pl-4 pr-4 text-white -ml-16"> <p className="font-bold text-2xl"><NAME></p> <p className="text-base mb-3">Chief Advisior</p> <p className="text-md">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed et tempus erat, et luctus quam. Maecenas cursus porta tortor, vel consectetur ante volutpat imperdiet.</p> <div className="pt-2"> <i className="fab fa-facebook-f px-2"></i> <i className="fab fa-twitter px-2"></i> <i className="fab fa-google px-2"></i> <i className="fab fa-linkedin-in px-2"></i> </div> </div> </div> <div className="staff-item grid grid-cols-2"> <div className="bg-blue-500 pt-4 pl-4 pr-4 text-white -mr-16"> <p className="font-bold text-2xl"><NAME></p> <p className="text-base mb-3">Chief Advisior</p> <p className="text-md">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed et tempus erat, et luctus quam. Maecenas cursus porta tortor, vel consectetur ante volutpat imperdiet.</p> <div className="pt-2"> <i className="fab fa-facebook-f px-2"></i> <i className="fab fa-twitter px-2"></i> <i className="fab fa-google px-2"></i> <i className="fab fa-linkedin-in px-2"></i> </div> </div> <img src="images/artist3.jpg" className="spec-img" width="80%" alt="" /> </div> <div className="staff-item grid grid-cols-2"> <div className="bg-blue-500 pt-4 pl-4 pr-4 text-white -mr-16"> <p className="font-bold text-2xl"><NAME></p> <p className="text-base mb-3">Chief Advisior</p> <p className="text-md">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed et tempus erat, et luctus quam. Maecenas cursus porta tortor, vel consectetur ante volutpat imperdiet.</p> <div className="pt-2"> <i className="fab fa-facebook-f px-2"></i> <i className="fab fa-twitter px-2"></i> <i className="fab fa-google px-2"></i> <i className="fab fa-linkedin-in px-2"></i> </div> </div> <img src="images/artist4.jpg" className="spec-img" width="80%" alt="" /> </div> </div> </div> </section> ) } export default Staffs <file_sep>import React from 'react' const Bread = ({data, bg}) => { return ( <section className={`bread text-center text-white pb-16 pt-40 ${bg}`}> <div className="text-5xl font-bold">{data}</div> <div className="line mx-auto"></div> <div className="second-line mx-auto m-2"></div> <div className="m-4 text-lg font-semibold">Home / <span className="text-blue-500">{data}</span></div> </section> ) } export default Bread <file_sep>import React, { useEffect, useState } from 'react' import { useParams } from 'react-router-dom' const DetailProduct = () => { let { id } = useParams(); const API_DETAIL_PRODUCT = `http://localhost:1337/products/${id}`; const [detail, setDetail] = useState([]); useEffect(() => { fetch(API_DETAIL_PRODUCT) .then(response => response.json()) .then(data => setDetail(data)); }, []) return ( <section className="detail-product"> <div className="container mx-auto py-20"> <div className="grid grid-cols-2"> <div className="grid grid-cols-2"> <img src={detail.image ? `../../images/${detail.image[0].name}` : "null"} alt="" className="" /> <div className=""> <p className="">{detail.name}</p> <p className="">{detail.price}</p> <p className="">{detail.short_desc}</p> <p className="">{detail.desc}</p> </div> </div> <div className=""></div> </div> </div> </section> ) } export default DetailProduct <file_sep>import React from 'react' const Why = () => { return ( <section className="why"> <div className="container mx-auto"> <div className="grid grid-cols-3"> <div className="col-span-1"></div> <div className="col-span-2 text-left"> <div className="text-4xl font-bold p-16 pb-10"><span className="text-blue-600">Why </span>Choose Us</div> <div className="why-item text-white text-xl font-semibold p-3 bg-blue-500 ml-16 mb-10 rounded">Respecting Your Time</div> <div className="why-item text-white text-xl font-semibold p-3 bg-blue-500 ml-16 mb-10 rounded">Latest In Technology</div> <div className="why-item text-white text-xl font-semibold p-3 bg-blue-500 ml-16 mb-10 rounded">Professional Staff</div> <div className="why-item text-white text-xl font-semibold p-3 bg-blue-500 ml-16 mb-32 rounded">Free Home Dilevery</div> </div> </div> </div> </section> ) } export default Why <file_sep>import React from 'react' const Contact = () => { return ( <section className="contact pt-20 bg-gray-200"> <div className="container mx-auto"> <div className="grid grid-cols-3 gap-10"> <div className="text-center border-2 border-blue-600 rounded p-10 hover-box"> <i class="fas fa-envelope fa-3x text-blue-600 m-3"></i> <p className="text-2xl font-semibold">Email</p> <p className=""><EMAIL></p> </div> <div className="text-center border-2 border-blue-600 rounded p-10 hover-box"> <i class="fas fa-phone-alt fa-3x text-blue-600 m-3"></i> <p className="text-2xl font-semibold">Phone</p> <p className="">+842094832345</p> </div> <div className="text-center border-2 border-blue-600 rounded p-10 hover-box"> <i class="fas fa-map-marker-alt fa-3x text-blue-600 m-3"></i> <p className="text-2xl font-semibold">Address</p> <p className="">Trinh Van Bo Street, Xuan Phuong, Nam Tu Liem, Ha Noi</p> </div> </div> </div> <div className="grid grid-cols-2 mt-20"> <div className=""> <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3723.863981044331!2d105.74459841501292!3d21.038127785993407!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x313454b991d80fd5%3A0x53cefc99d6b0bf6f!2sFPT%20Polytechnic%20Hanoi!5e0!3m2!1sen!2s!4v1606041303879!5m2!1sen!2s" width="100%" height="100%" frameBorder={0} style={{ border: 0 }} allowFullScreen aria-hidden="false" tabIndex={0} /> </div> <form action="" className="bg-blue-600 py-20 px-16 pt-10"> <span className="text-white text-3xl font-normal">Send A Message</span> <div className="grid grid-rows-2 gap-10 mt-10"> <div className="grid grid-cols-2 gap-10"> <input type="text" className="p-2 w-full" name="name" placeholder="Name" id="" /> <input type="text" className="p-2 w-full" name="email" placeholder="Email" id="" /> </div> <div className="grid grid-cols-2 gap-10"> <input type="text" className="p-2 w-full" name="phone" placeholder="Phone" id="" /> <input type="text" className="p-2 w-full" name="subject" placeholder="Subject" id="" /> </div> </div> <textarea className="mt-10 p-2 w-full" name="message" placeholder="Message" id="" rows="6"></textarea> <button className="border-2 border-white text-white hover:bg-blue-800 mt-4 py-2 px-4">SUBMIT</button> </form> </div> </section> ) } export default Contact <file_sep>import React from 'react' const Footer = () => { return ( <footer className="bg-blue-500"> <div className="container mx-auto p-6 text-xl font-medium text-center text-white"> Copyrights © 2018 All Rights Reserved by <NAME> </div> </footer> ) } export default Footer <file_sep>import React from 'react' const PreFooter = () => { return ( <section className="fre-footer bg-black text-white"> <div className="container mx-auto"> <div className="grid grid-cols-4 gap-x-20"> <div className="my-20"> <img src="../../images/Feng_shui_logo.png" className="pb-6" width="200px" alt=""/> <span>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.</span> </div> <div className="grid grid-rows-5 py-20"> <span className="text-2xl font-semibold text-blue-500">Help</span> <a href="">Find Your Beer</a> <a href="">Customer Service</a> <a href="">Contact</a> <a href="">Recent Orders</a> </div> <div className="grid grid-rows-5 py-20"> <span className="text-2xl font-semibold text-blue-500">Links</span> <a href="">Home</a> <a href="">Shop</a> <a href="">404 Page</a> <a href="">Login</a> </div> <div className="grid grid-rows-5 py-20"> <span className="text-2xl font-semibold text-blue-500">Our Information </span> <a href=""><i class="fa fa-map-marker" aria-hidden="true"></i> 787 Lakeview St. Marion, NC 28752</a> <a href=""><i class="fa fa-phone" aria-hidden="true"></i> +1800123654789</a> <a href=""><i class="fa fa-envelope" aria-hidden="true"></i> <EMAIL></a> </div> </div> </div> </section> ) } export default PreFooter <file_sep>import React, { useState } from 'react' import { BrowserRouter as Router, Link, useLocation, } from "react-router-dom"; const Nav = () => { const [nav, setNav] = useState(false); const changeNavBg = () => { if (window.scrollY > 100) { setNav(true); } else { setNav(false); } } window.addEventListener('scroll', changeNavBg) return ( <nav className={`z-50 ${nav ? 'nav-scrolled' : ''}`}> <div className="px-32"> <div className="grid grid-cols-5 items-center p-2"> <a href="#"><img src="../../images/Feng_shui_logo.png" width="90px" className="" alt="" /></a> <ul className="col-span-3 text-xl font-medium"> <li className="inline-block p-4"><Link className="nav-content hover:no-underline hover:text-blue-400" to="/"> Home</Link></li> <li className="inline-block p-4"><Link className="nav-content hover:no-underline hover:text-blue-400" to="/about">About</Link></li> <li className="inline-block p-4"><Link className="nav-content hover:no-underline hover:text-blue-400" to="/services">Services</Link></li> <li className="inline-block p-4"><Link className="nav-content hover:no-underline hover:text-blue-400" to="/gallery">Gallery</Link></li> <li className="inline-block p-4"><Link className="nav-content hover:no-underline hover:text-blue-400" to="/blog">Blog</Link></li> <li className="inline-block p-4"><Link className="nav-content hover:no-underline hover:text-blue-400" to="/shop">Shop</Link></li> <li className="inline-block pl-4"><Link className="nav-content hover:no-underline hover:text-blue-400" to="/contact">Contact</Link></li> </ul> <div className="text-right"> <a className="px-2 nav-content hover:no-underline hover:text-blue-400"><i className="fas fa-user"></i> Login</a> <a className="px-2 nav-content hover:no-underline hover:text-blue-400"><i className="fas fa-pencil-alt"></i> Register</a> </div> </div> </div> </nav> ) } export default Nav <file_sep>import React from 'react' const Products = () => { return ( <section className="products"> <h1 className="text-4xl py-4">Sản phẩm nổi bật</h1> <div className="grid grid-cols-3 gap-3"> <div className="pro-item border-solid border-2 border-gray-200 p-4"> <img src="./product-img-demo.jpg" className="" alt="" /> <div className="pro-title text-orange-500 text-xl font-semibold pt-5"> Tieu de bai viet </div> <div className="pro-content"> Noi dung bai viet </div> </div> <div className="pro-item border-solid border-2 border-gray-200 p-4"> <img src="./product-img-demo.jpg" className="" alt="" /> <div className="pro-title text-orange-500 text-xl font-semibold pt-5"> Tieu de bai viet </div> <div className="pro-content"> Noi dung bai viet </div> </div> <div className="pro-item border-solid border-2 border-gray-200 p-4"> <img src="./product-img-demo.jpg" className="" alt="" /> <div className="pro-title text-orange-500 text-xl font-semibold pt-5"> Tieu de bai viet </div> <div className="pro-content"> Noi dung bai viet </div> </div> </div> </section> ) } export default Products
86aa038f83b32b269e0e9d68b73f88e043d5c1fe
[ "JavaScript" ]
14
JavaScript
ducdvvph09332/PT15202-react-demo
7bcdb82c2b0772d64315e052f2624236b34c1c41
b685e9bf51050d61e749b1736e71d7b8d4d54272
refs/heads/main
<file_sep>const input = document.getElementById('todo'); const button = document.getElementById('add') const list = document.getElementById('list'); const todos = [ {text: '<NAME>', done: false}, {text: 'Programmera', done: true}, {text: 'gå hem', done: false} ]; button.addEventListener('click', onButtonClicked); updateView(); function onButtonClicked() { // Arrayfunktionen push lägger till en item till arrayns sista plats. todos.push({ text: input.value, done: false }); updateView(); } function updateView(){ list.innerHTML = ''; for(let i = 0; i < todos.length; i++) { // 1. Skapa ett li element: <li></li> const li = document.createElement('li'); li.dataset.index = i; // 2. Ändra på texten inuti li-elementet: <li>Programmera</li> li.textContent = todos[i].text; // 3. Lägg till li-elementet till vårt ul-element if(todos[i].done){ li.style.textDecoration = 'line-through' } list.appendChild(li); li.addEventListener('click', onItemClicked); } } function onItemClicked(e) { todos[e.target.dataset.index].done = !todos[e.target.dataset.index].done; updateView(); }
7cba5e770f6c2e7c80acda03217e55ea740bda83
[ "JavaScript" ]
1
JavaScript
viglot/lista
49ce38ba5f8b037e5d693f4dd58bdbcb2e8ffe99
f49865631cfbb466c1f202bf89feb59d73a2fc3c
refs/heads/master
<file_sep>package com.sha.springbootmicroservice2transaction.controller; import com.sha.springbootmicroservice2transaction.model.Transaction; import com.sha.springbootmicroservice2transaction.service.ITransactionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; /** * @author sa * @date 17.04.2021 * @time 12:40 */ @RestController @RequestMapping("api/transaction")//pre-path public class TransactionController { @Autowired private ITransactionService transactionService; @PostMapping public ResponseEntity<?> saveTransaction(@RequestBody Transaction transaction) { return new ResponseEntity<>(transactionService.saveTransaction(transaction), HttpStatus.CREATED); } @DeleteMapping("{transactionId}") public ResponseEntity<?> deleteTransaction(@PathVariable Long transactionId) { transactionService.deleteTransaction(transactionId); return new ResponseEntity<>(HttpStatus.OK); } @GetMapping("{userId}") public ResponseEntity<?> getAllTransactionsOfUser(@PathVariable Long userId) { return ResponseEntity.ok(transactionService.findAllTransactionsOfUser(userId)); } } <file_sep>## Spring Boot Microservice 2 - Transaction Service ### Endpoints #### 1- Save Transaction ``` POST /api/transaction HTTP/1.1 Host: localhost:4444 Authorization: Basic basic64(username:password) Content-Type: application/json Content-Length: 37 { "userId":1, "productId":1 } ``` #### 2- Get Transactions Of User ``` GET /api/transaction/1 HTTP/1.1 Host: localhost:4444 Authorization: Basic basic64(username:password) ``` #### 3- Delete Transaction By Id ``` DELETE /api/transaction/1 HTTP/1.1 Host: localhost:4444 Authorization: Basic basic64(username:password) ``` <file_sep>package com.sha.springbootmicroservice2transaction.repository; import com.sha.springbootmicroservice2transaction.model.Transaction; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; /** * @author sa * @date 17.04.2021 * @time 11:23 */ public interface ITransactionRepository extends JpaRepository<Transaction, Long> { List<Transaction> findAllByUserId(Long userId); } <file_sep>package com.sha.springbootmicroservice2transaction.service; import com.sha.springbootmicroservice2transaction.model.Transaction; import java.util.List; /** * @author sa * @date 17.04.2021 * @time 12:23 */ public interface ITransactionService { Transaction saveTransaction(Transaction transaction); void deleteTransaction(Long transactionId); List<Transaction> findAllTransactionsOfUser(Long userId); } <file_sep>rootProject.name = 'spring-boot-microservice-2-transaction' <file_sep>package com.sha.springbootmicroservice2transaction.security; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; /** * @author sa * @date 17.04.2021 * @time 13:27 */ @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Value("${service.security.secure-key-username}") private String SECURE_KEY_USERNAME; @Value("${service.security.secure-key-password}") private String SECURE_KEY_PASSWORD; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { PasswordEncoder encoder = new BCryptPasswordEncoder(); auth.inMemoryAuthentication() .passwordEncoder(encoder) .withUser(SECURE_KEY_USERNAME) .password(encoder.encode(SECURE_KEY_PASSWORD)) .roles("USER"); } @Override protected void configure(HttpSecurity http) throws Exception { http.httpBasic(); http.csrf().disable(); http.authorizeRequests() .antMatchers("/h2-console/**").permitAll() .anyRequest().authenticated(); http.headers().frameOptions().sameOrigin(); } }
068af245b6ea199ca6770eb26744d64617310eac
[ "Markdown", "Java", "Gradle" ]
6
Java
senolatac/spring-boot-microservice-2-transaction
8c660818626522cce1336e102c6e872073cf6524
98014c3db454462b2488893b3d23ad561942a2c0
refs/heads/master
<repo_name>kadotami/live-coding<file_sep>/live-coding.py import pyaudio import numpy as np import wave import matplotlib.pyplot as plt CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 #モノラル(2にするとステレオ) RATE = 44100 #サンプルレート(録音の音質) RECORD_SECONDS = 3 #録音時間 BPM = 60 SECONDS_OF_BEAT = 60/BPM Hz_ARRAY = [41.2, 43.65, 46.25, 49, 51.91, 55, 58.27, 61.74, 65.41, 69.3, 73.42, 77.78] SCALE_ALLAY = ['E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B', 'C', 'C#', 'D', 'D#'] def getNearestValue(target_list, num): """ 概要: リストからある値に最も近い値のindexを返却する関数 @param target_list: データ配列 @param num: 対象値 @return 対象値に最も近い値 """ # リスト要素と対象値の差分を計算し最小値のインデックスを取得 idx = np.abs(np.asarray(target_list) - num).argmin() return idx def check_scale(fft_data, freq_list): """ 概要: 最も大きい音のドレミを返す @param fft_data: fft配列 @param freq_list: 週は数配列 @return ドレミ """ max_freq = freq_list[np.argmax(fft_data)] if(max_freq < 0): max_freq = max_freq * -1 print(max_freq) while(max_freq > 82.4): max_freq = max_freq / 2 return SCALE_ALLAY[getNearestValue(Hz_ARRAY, max_freq)] if __name__ == "__main__": audio = pyaudio.PyAudio() stream = audio.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, frames_per_buffer = CHUNK) print("Now Recording...") # for i in range(int(RATE / CHUNK * 1)): # data = [] # d = np.frombuffer(stream.read(CHUNK), dtype='int16') # data.append(d) # data = np.asarray(data).flatten() # fft_data = np.abs(np.fft.fft(data)) #FFTした信号の強度 # freq_list = np.fft.fftfreq(data.shape[0], d=1.0/RATE) #周波数(グラフの横軸)の取得 # plt.plot(freq_list, fft_data) # scale = check_scale(fft_data, freq_list) # print(scale) # # plt.xlim(0, 5000) #0~5000Hzまでとりあえず表示する # plt.show() try: while stream.is_active(): data = [] for i in range(0, int(RATE / CHUNK * SECONDS_OF_BEAT)): d = np.frombuffer(stream.read(CHUNK), dtype='int16') data.append(d) data = np.asarray(data).flatten() fft_data = np.abs(np.fft.fft(data)) #FFTした信号の強度 freq_list = np.fft.fftfreq(data.shape[0], d=1.0/RATE) #周波数(グラフの横軸)の取得 scale = check_scale(fft_data, freq_list) print(scale) except KeyboardInterrupt: stream.stop_stream() stream.close() audio.terminate() print("Finished Recording.")
88a9625db7ef61a35fef11d5a55116f553165941
[ "Python" ]
1
Python
kadotami/live-coding
b3a04bbb7afaef65b737921d31dd1d8b665aaa23
d93e5d4bd136532aef0644229bd4dd856b7c1388
refs/heads/master
<repo_name>aoles/bioc_git_transition<file_sep>/run_transition.py #!/usr/bin/env python """Bioconductor run git transition code. This module assembles the functions from `git_script.py` and `svn_dump.py` so that the Bioconductor SVN --> Git transition can be run in a sequential manner. Author: <NAME> Ideas taken from <NAME>'s code in Bioconductor/mirror Usage: `python run_transition.py` """ from src.local_svn_dump import LocalSvnDump from src.git_bioconductor_repository import GitBioconductorRepository from src.lfs import Lfs import os import logging as log import ConfigParser def make_git_repo(svn_root, temp_git_repo, bare_git_repo, remote_url, package_path, lfs_object=None): # Step 4: Add release branches to all packages gitrepo = GitBioconductorRepository(svn_root, temp_git_repo, bare_git_repo, remote_url, package_path) log.info("Make git repo: Adding release branches") gitrepo.add_release_branches() # Step 5: Add commit history log.info("Make git repo: Adding commit history") gitrepo.add_commit_history() if lfs_object is not None: log.info("Running LFS transtion") lfs_object.run_lfs_transition(temp_git_repo) # Step 6: Make Git repo bare log.info("Make git repo: Creating bare repositories") gitrepo.create_bare_repos() log.info("Make git repo: Adding remotes to make git server available") gitrepo.add_remote() return def run_transition(configfile, new_svn_dump=False): """Update SVN local dump and run gitify-bioconductor. Step 0: Create dump `svnadmin create bioconductor-svn-mirror` `svnrdump dump https://hedgehog.fhcrc.org/bioconductor | svnadmin load bioconductor-svn-mirror` """ # Settings Config = ConfigParser.ConfigParser() Config.read(configfile) temp_git_repo = Config.get('Software', 'temp_git_repo') remote_url = Config.get('Software', 'remote_url') bare_git_repo = Config.get('Software', 'bare_git_repo') package_path = Config.get('Software', 'package_path') svn_root = Config.get('SVN', 'svn_root') remote_svn_server = Config.get('SVN', 'remote_svn_server') users_db = Config.get('SVN', 'users_db') svn_transition_log = Config.get('SVN', 'svn_transition_log') log.basicConfig(filename=svn_transition_log, level=log.DEBUG, format='%(asctime)s %(message)s') log.debug("Bioconductor Transition Log File: \n") # Print in the log file. for s in Config.sections(): for k, v in Config.items(s): log.info("%s: %s" % (k, v)) if not os.path.isdir(temp_git_repo): os.mkdir(temp_git_repo) # Step 1: Initial set up, get list of packs from trunk dump = LocalSvnDump(svn_root, temp_git_repo, users_db, remote_svn_server, package_path) packs = dump.get_pack_list(branch="trunk") ################################################### # Create a local dump of SVN packages in a location if new_svn_dump: log.info("Create a local SVN dump") dump.svn_dump(packs) ################################################### # Make bare repo, if it does not exist if not os.path.isdir(bare_git_repo): os.mkdir(bare_git_repo) # Make temp git repo, with all commit history log.info("Make git repo") make_git_repo(svn_root, temp_git_repo, bare_git_repo, remote_url, package_path) # EOF message log.info("Finished setting up bare git repo") return def run_experiment_data_transition(configfile, new_svn_dump=False): """Run experiment data transtion. """ # Settings Config = ConfigParser.ConfigParser() Config.read(configfile) temp_git_repo = Config.get('ExperimentData', 'temp_git_repo') remote_url = Config.get('Software', 'remote_url') bare_git_repo = Config.get('ExperimentData', 'bare_git_repo') svn_root = Config.get('ExperimentData', 'svn_root') remote_svn_server = Config.get('ExperimentData', 'remote_svn_server') package_path = Config.get('ExperimentData', 'package_path') users_db = Config.get('SVN', 'users_db') trunk = Config.get('SVN', 'trunk') data_store_path = Config.get('ExperimentData', 'data_store_path') ref_file = Config.get('ExperimentData', 'ref_file') data_log = Config.get("ExperimentData", "data_log") log.basicConfig(filename=data_log, level=log.DEBUG, format='%(asctime)s %(message)s') log.debug("Bioconductor Experiment data transition log File: \n") # Create temp_git_repo directory if not os.path.isdir(temp_git_repo): os.mkdir(temp_git_repo) # Step 1: Initial set up, get list of packs from trunk dump = LocalSvnDump(svn_root, temp_git_repo, users_db, remote_svn_server, package_path) packs = dump.get_pack_list(branch="trunk") ################################################### # Create a local dump of SVN packages in a location if new_svn_dump: log.info("Create a local SVN dump of experiment data") dump.svn_dump(packs) ################################################### # Make bare repo, if it does not exist if not os.path.isdir(bare_git_repo): os.mkdir(bare_git_repo) # Make temp git repo, with all commit history log.info("Make git repo for experiment data packages") # Create a new git LFS object lfs = Lfs(svn_root, trunk, data_store_path, ref_file, temp_git_repo) # Run make_git_repo, with new LFS object make_git_repo(svn_root, temp_git_repo, bare_git_repo, remote_url, package_path, lfs_object=lfs) # EOF message log.info("Finished setting up bare git repo for experiment data packages") return if __name__ == '__main__': run_transition("./settings.ini", new_svn_dump=True) run_experiment_data_transition("./settings.ini", new_svn_dump=False) <file_sep>/src/helper/helper.py import subprocess def is_github_repo(url): """Check if it is a valid github repo. Returns True, or False. """ cmd = ['git', 'ls-remote', url] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() if err: print("This is not a valid github URL: \n %s" % err) return False print("Out: %s" % out) return True <file_sep>/doc/workflows/maintainer-workflow.md # Developer -- Add Bioconductor package to git.bioconductor.org Bioconductor expects its developers to use a git-based version control system. This will allow the developers to easily interact with Bioconductor's private git server. Bioconductor git server is available at: 1. `SSH` read/write access to developers: `<EMAIL>` 1. `HTTPS` read only access to the world: `https://git.bioconductor.org` This document will explain a developers workflow using GitHub. ## Developer has a public GitHub repository The developers will have a public GitHub repository where they can interact with their package community, accept pull requests, issues, and other GitHub collaboration features. As the developer actively develops they will have the repository cloned on their local machine. The GitHub repository is where the developer should be maintaining his code. Eg: ``` git clone <EMAIL>:developer/<ExamplePackage>.git ``` The remotes on the package will be that of GitHub's, because it is the remote server being used by the developer. The developer can check if the remote is configured properly using, ``` git remote -v ``` This should show, ``` origin <EMAIL>:developer/example_package.git (fetch) origin [email protected]:developer/example_package.git (push) ``` the remote shows that you can `fetch` and `push` to those remote locations, this remote location is called `origin`. ## Add remotes Our goal is to add another remote location to the local repository, the Bioconductor private server. ``` git remote add upstream <EMAIL>:packages/example_package.git ``` To check if the remote has been added properly, we can check it using: ``` git remote -v ``` which should show, ``` origin <EMAIL>:developer/example_package.git (fetch) origin <EMAIL>:developer/example_package.git (push) upstream <EMAIL>:packages/example_package.git (fetch) upstream <EMAIL>:packages/example_package.git (push) ``` NOTE: To be able to `fetch` and `push` to <EMAIL>, the developer should have ssh access. More about how to get ssh access on the [Contributions.md](https://github.com/Bioconductor/BiocContributions). ## Push to remote master and remote upstream If a developer makes a change to his package, it is important that he push to BOTH his GitHub, and Bioconductor's git server. This is important if the developer wants the Bioconductor remote to be in sync. First, push to the remote `origin` in the branch `master`: ``` git push origin master ``` Second, push to the remote `upstream` in the branch `master`: ``` git push upstream master ``` This will sync BOTH the developers GitHub repository and the Bioconductor servers repository. ## Pull from remote upstream and keep things in sync One thing a developer has to do is get updates from any changes or commits made to the Bioconductor repository, To get updates from the Bioconductor repository (i.e changes made by the core team) ``` git fetch --all git merge upstream/master ``` To get updates from the GitHub repository (i.e changes made by your collaborators) ``` git merge origin/master ``` <file_sep>/doc/workflows/new-package-workflow.md # New package workflow **Goal**: You are a developer who wants to contribute a new package to Bioconductor. You have been developing on GitHub (or another git based platform). How do you contribute your package to Bioconductor? ## Steps: We use the package "BiocGenerics" as an example. 1. We assume that you have already finished developing you package according to the Bioconductor [Package Guidelines][]. 1. If you do not have your package on GitHub, we highly recommend using it. You will be able to leverage features such as Pull requests, issue tracking, and many more social coding ideas which will make your Bioconductor package community happier. To use GitHub, please [Create a new GitHub account][]. 1. The next step is to [Create a new GitHub repository][] with your package name. 1. On your **local machine** initiate "git" in your package repository ``` cd BiocGenerics git init ``` 1. Once you have initialized the git repository on your local machine, add all the contents you need for the Bioconductor package, ``` git add DESCRIPTION NAMESPACE NEWS R/* inst/* man/* tests/* vignettes/* ``` You can also just do `git add *` if you wish to add everything in the package. 1. Commit all your new additions to your local git repository, ``` git commit -m "New bioconductor package named BiocGenerics" ``` 1. Add a remote to your local git repository, `git remote add origin <EMAIL>:developer/BiocGenerics.git` 2. To check that remotes are set up properly, run the command inside your local machine's clone. `git remote -v` which should produce the result ``` origin <EMAIL>:developer/BiocGenerics.git (fetch) origin <EMAIL>:developer/BiocGenerics.git (push) ``` 1. Push the new content to your GitHub repository, so it's visible to the world `git push -u origin master` **NOTE: Check your GitHub account, and make sure you are able to view all your files.** 1. Your next step is to notify the Bioconductor team, about the package you developed to contribute to Bioconductor. You can do this be adding an issue to the [Contributions Issues][] page. Please follow that [README.md][] file on the Contributions page for additional information. 1. After adding your package to the [Contributions Issues][] page, a member from the Bioconductor core team will be assigned to your package for review. Provided the review process goes as planned and your package is accepted, it will be added to the Bioconductor git server by the core team. 1. Once your package has been accepted to Bioconductor, you should be able to see it on the [Bioconductor git server][] which is available at: **ssh read/write access to developers:** `<EMAIL>` **https read only access to the world:** `https://git.bioconductor.org` 1. For developers/maintainers, you are required to send your ssh public key to `<EMAIL>` and you will be added to the server, and given access to your package. 1. The bioconductor core team will make changes on your package for bugs or bumping a version number for a new release. So it becomes essential that you add the Bioconductor repository as another remote to your machine's local git repository. You need to add a remote, using: `git remote add upstream <EMAIL>:packages/BiocGenerics.git` 1. Fetch content from remote upstream, `git fetch upstream` **NOTE:** This step will fail if you don't have access as a developer to the Bioconductor repository. 1. Merge upstream with origin's `master` branch, `git merge upstream/master` 1. Push changes to your GitHub (`origin`) repository's branch `master`, `git push origin` 1. Developers/Maintainers make changes to the current release branch. You will need to add a branch to GitHub, to be able to push these changes. ``` # Fetch all updates git fetch upstream # Checkout new branch RELEASE_3_5, from upstream/RELEASE_3_5 git checkout -b RELEASE_3_5 upstream/RELEASE_3_5 # Push updates to remote origin's new branch RELEASE_3_5 git push -u origin RELEASE_3_5 ``` 1. Check your GitHub repository to confirm that the `master` (and optionally `RELEASE_3_5`) branches are present. [README.md]: https://github.com/Bioconductor/Contributions [Contributions Issues]: https://github.com/Bioconductor/Contributions/issues [Package Guidelines]: https://www.bioconductor.org/developers/package-guidelines/ [Create a new GitHub account]: https://help.github.com/articles/signing-up-for-a-new-github-account/ [Create a new GitHub repository]: https://help.github.com/articles/create-a-repo/ [Bioconductor git server]: https://git.bioconductor.org <file_sep>/src/lfs.py """Module to create LFS based experiment data packages. Add data content to data package. In this svn repository, the data subdir of a package is stored separately in svn. add_data.py can be used to add the data subdir to a given package. The appropriate data dir will be added to the specified package. """ import os import subprocess from git_api.git_api import git_lfs_track from git_api.git_api import git_add from git_api.git_api import git_commit import logging as log from local_svn_dump import Singleton class Lfs: """Create git LFS based experiment data packages.""" __metaclass__ = Singleton def __init__(self, svn_root, trunk, data_store_path, ref_file, temp_git_repo): """Initialize LFS class.""" self.svn_root = svn_root self.trunk = trunk self.data_store_path = data_store_path self.ref_file = ref_file self.temp_git_repo = temp_git_repo return def parse_external_refs(self, package): """Parse external refs file, and return a list of data references.""" path = package + "/" + self.ref_file with open(path, 'r') as f: refs = list(line for line in (l.strip() for l in f) if line) return refs def list_files(self, path): """List files in a path.""" ans = [os.path.join(root, f) for root, subdir, files in os.walk(path) for f in files] return [item[len(path)+1:] for item in ans] def add_data(self, package): """Add data from SVN data source to each package.""" package_dir = os.path.join(self.temp_git_repo, package) before_files = self.list_files(package_dir) try: # Get references from external_data_source.txt refs = self.parse_external_refs(package_dir) except IOError, err: log.error("Error: No data : missing file %s, in package %s " % (err.filename, package)) return for ref in refs: # TODO: PATH ISSUE here. src = "/".join([self.svn_root, self.trunk, self.data_store_path, package, ref]) dest = "/".join([package_dir, ref]) try: cmd = ['svn', 'export', '--username', 'readonly', '--password', 'readonly', '--non-interactive', src, dest] print "CMD to add data: ", cmd subprocess.check_call(cmd) except Exception as e: log.error("Error adding ref: %s, package: %s" % (ref, package)) log.error(e) after_files = self.list_files(package_dir) # Add list of files newly added to object. self.lfs_files = list(set(after_files) - set(before_files)) return def add_data_as_lfs(self, package): """Add data as git LFS.""" package_dir = os.path.join(self.temp_git_repo, package) try: for item in self.lfs_files: # Add files git_add(item, cwd=package_dir) # Track all files using lfs git_lfs_track(item, cwd=package_dir) git_add(".gitattributes", cwd=package_dir) for item in self.lfs_files: git_add(item, cwd=package_dir) except Exception as e: log.error("Error in add data as LFS, package %s" % package) log.error(e) return def commit_data_to_lfs(self, package): """Commit data as LFS to server.""" try: package_dir = os.path.join(self.temp_git_repo, package) git_commit(cwd=package_dir) except Exception as e: log.error("Error commit data to LFS in package %s" % package) log.error(e) return def run_lfs_transition(self, temp_git_repo): """Run LFS transition on all package.""" for package in os.listdir(os.path.abspath(temp_git_repo)): try: if "bioc-data-experiment" not in package: log.info("LFS: Add data to package %s" % package) self.add_data(package) log.info("LFS: Add data as LFS to package %s" % package) self.add_data_as_lfs(package) log.info("LFS: Commit data as LFS to package %s" % package) self.commit_data_to_lfs(package) except Exception as e: log.error("LFS: Error in package %s: " % package) log.error(e) pass return <file_sep>/svn_dump_update.py """Bioconductor update SVN dump code. Author: <NAME> Usage: `python svn_dump_update.py` """ from src.local_svn_dump import LocalSvnDump import logging as log import ConfigParser log.basicConfig(filename='svn_dump_update.log', format='%(asctime)s %(message)s', level=log.DEBUG) log.debug("Bioconductor SVN Dump Log File: \n") def svn_root_update(configfile): """Dump update needs to be run as git.""" Config = ConfigParser.ConfigParser() Config.read(configfile) temp_git_repo = Config.get('Software', 'temp_git_repo') svn_root = Config.get('SVN', 'svn_root') remote_svn_server = Config.get('SVN', 'remote_svn_server') users_db = Config.get('SVN', 'users_db') update_file = Config.get('SVN', 'update_file') package_path = Config.get('Software', 'package_path') for s in Config.sections(): for k, v in Config.items(s): log.info("%s: %s" % (k, v)) dump = LocalSvnDump(svn_root, temp_git_repo, users_db, remote_svn_server, package_path) dump.svn_get_revision() dump.svn_dump_update(update_file) dump.update_local_svn_dump(update_file) return def svn_experiment_root_update(configfile): """Dump update needs to be run as git.""" Config = ConfigParser.ConfigParser() Config.read(configfile) temp_git_repo = Config.get('ExperimentData', 'temp_git_repo') svn_root = Config.get('ExperimentData', 'svn_root') remote_svn_server = Config.get('ExperimentData', 'remote_svn_server') users_db = Config.get('SVN', 'users_db') update_file = Config.get('ExperimentData', 'update_file') package_path = Config.get('ExperimentData', 'package_path') for s in Config.sections(): for k, v in Config.items(s): log.info("%s: %s" % (k, v)) dump = LocalSvnDump(svn_root, temp_git_repo, users_db, remote_svn_server, package_path) dump.svn_get_revision() dump.svn_dump_update(update_file) dump.update_local_svn_dump(update_file) return if __name__ == '__main__': svn_root_update("./settings.ini") svn_experiment_root_update("./settings.ini") <file_sep>/src/git_edit_repository.py #!/usr/bin/env python """Bioconductor Git repo user interaction script docstrings. This module provides functions for working with the Bioconductor `git` repository. This module gives the bioconductor core team, to interact with the GIT server, and work with package authors. Author: <NAME> # TODO: This needs to be edited to fit new constraints. """ import os import subprocess from src.git_api.git_api import git_clone from src.git_api.git_api import git_remote_add from src.git_api.git_api import git_checkout from local_svn_dump import Singleton import logging as log class GitEditRepository(object): """Git Edit repository.""" __metaclass__ = Singleton def __init__(self, edit_repo, ssh_server): """Initialize Git edit repo.""" self.edit_repo = edit_repo self.ssh_server = ssh_server return # TODO: deprecate def extract_development_url(self, package): """Extract `DevelopmentURL` from DESCRIPTION file.""" description = os.path.join(package, 'DESCRIPTION') with open(description, 'r') as f: doc = f.read() doc_list = doc.split("\n") for i in xrange(len(doc_list)): if doc_list[i].startswith("DevelopmentURL:"): url = doc_list[i] url = url.replace("DevelopmentURL:", "") url = url.strip() return url # TODO: deprecate def set_edit_repo(self, package): """ Clone a package from bioc_git_repo to make changes. Use this function to set up a clone of an existing bioconductor-git package, to make changes and push back to the git-server. """ log.info("Set up a clone of package: %s, " "to push changes to bare_git_repo" % package) repository = self.ssh_server + "/" + package git_clone(repository, self.edit_repo, bare=False) development_url = self.extract_development_url(os.path.join(self.edit_repo, package)) git_remote_add('upstream', development_url, cwd=os.path.join(self.edit_repo, package)) return # TODO: deprecate def clone_all_edit_repo(self): """Clone all packages in git server. This clone of the entire git server is located on a seperate instance, where contents of the pacakges may be edited. After the modifications in the `edit_repo`, the contents can be pushed to the `bioc_git_repo`. """ # TODO: get list of package from servers # get list of packages from manifest file. for package in os.listdir(self.bare_git_repo): self.set_edit_repo(package) return # TODO: deprecate def daily_fetch_branch(self, package, branch): """Daily fetch from github repo. ## git checkout branch-1 ## git pull upstream branch-1:branch-1 ## git push origin branch-1 """ path = os.path.join(self.edit_repo, package) git_checkout(branch, cwd=path, new=False) # Git pull into a branch of the edit_repp cmd = ['git', 'pull', '-Xtheirs', '--no-edit', 'upstream', branch + ":" + branch] p = subprocess.Popen(cmd, cwd=path, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if ("CONFLICT" in out): log.error("Merge conflict in the package: %s" % package) log.error(out) else: # Git push cmd = ['git', 'push', 'origin', branch] subprocess.check_call(cmd, cwd=path) return # TODO: deprecate def daily_fetch(self, branch): """Daily fetch of every package in the edit_repo. Daily fetch needs to be run by the build system on the branch being updated e.g `master` or `RELEASE_3_4` """ for package in os.listdir(self.edit_repo): self.daily_fetch_branch(package, branch) return def version_bump(self, package, release=False): """Bump package version. release=False, assumes that version bump is not for a new release branch. """ description_file = os.path.join(self.edit_repo, package, 'DESCRIPTION') with open(description_file, 'r') as f: doc = f.read() doc_list = doc.split("\n") for i in xrange(len(doc_list)): if doc_list[i].startswith("Version:"): version = doc_list[i] index = i x, y, z = version.split("Version: ")[1].split(".") if release: # Special case if int(y) == 99: x = int(x) + 1 y = 0 else: y = int(y) + 1 z = 0 else: z = int(z) + 1 version = str(x) + "." + str(y) + "." + str(z) doc_list[index] = "Version: " + version with open(description_file, "w") as f: f.write("\n".join(doc_list)) log.info("Package: %s updated version to: %s" % (package, version)) return # TODO: REMOVE commit_message and use the one in git_api def commit_message(self, msg, package): """Add a commit message to package during, bioc release.""" cmd = ['git', 'commit', '-m', msg] subprocess.check_call(cmd, cwd=package) return def release_branch(self, package, new_release): """Create new release branch, make git call.""" package_dir = os.path.join(self.edit_repo, package) # checkout master git_checkout(branch="master", cwd=package_dir, new=False) # on master, version bump, release = False self.version_bump(package, release=False) self.commit_message("bump x.y.z versions to even 'y' " "prior to creation of " + new_release, package_dir) # IN THE BRANCH, version bump release=True git_checkout(branch=new_release, cwd=package_dir, new=True) self.version_bump(package, release=True) # commit messsage in branch self.commit_message(msg="Creating branch for BioC " + new_release, package=package_dir) # checkout master git_checkout(branch="master", cwd=package_dir, new=False) # version bump release=True self.version_bump(package, release=True) # Commit message self.commit_message("bump x.y.z versions to odd 'y' " "after creation of " + new_release, package_dir) log.info("New branch created for package %s" % package) return def create_new_release_branch(self, new_release): """Create a new RELEASE from master. This function is used to create a new release version, from the 'master' branch going forward. Usage: create_new_release_branch('RELEASE_3_7', '/packages/') """ for package in os.listdir(os.path.abspath(self.edit_repo)): # Create a new release branch self.release_branch(new_release, package) # TODO: Push new release branch cmd = ['git', 'push', '-u', 'origin', new_release] subprocess.check_call(cmd, cwd=os.path.join(self.edit_repo, package)) return
e4654392ee59e1d83bdf5e46d89fe4f7b7d23e0e
[ "Markdown", "Python" ]
7
Python
aoles/bioc_git_transition
240412afe89f710ee84c87b39a9a60c07b78b277
e8159ecdfdc5e9e74d016b4ad7e98ff499793993
refs/heads/main
<repo_name>GabrielCordeiroDev/firebase-cloud-functions<file_sep>/functions/src/controllers/UpdateEntryController.ts import {Request, Response} from "express"; import {db} from "../config/firebase"; export class UpdateEntryController { async handle(req: Request, res: Response): Promise<Response> { const {body: {title, text}, params: {entryId}} = req; const entry = db.collection("entries").doc(entryId); const currentEntryData = (await entry.get()).data() || {}; const entryObject = { id: entry.id, title: title || currentEntryData.title, text: text || currentEntryData.text, }; await entry.set(entryObject).catch((err) => { throw new Error(err.message); }); return res.json({ status: "success", message: "entry updated successfully", data: entryObject, }); } } <file_sep>/functions/src/controllers/DeleteEntryController.ts import {Request, Response} from "express"; import {db} from "../config/firebase"; export class DeleteEntryController { async handle(req: Request, res: Response): Promise<Response> { const {entryId} = req.params; const entry = db.collection("entries").doc(entryId); const doc = await entry.get(); if (!doc.exists) throw new Error("This entry does not exist."); await entry.delete().catch((err) => { throw new Error(err.message); }); return res.json({ status: "success", message: "entry deleted successfully", }); } } <file_sep>/README.md <h1 align="center"> Firebase Cloud Functions </h1> <p align="center"> <img alt="GitHub top language" src="https://img.shields.io/github/languages/top/GabrielCordeiroDev/firebase-cloud-functions"> <a href="https://www.linkedin.com/in/dev-gabriel-cordeiro/"> <img alt="Made by" src="https://img.shields.io/badge/made%20by-Gabriel%20Cordeiro-gree"> </a> <img alt="Repository size" src="https://img.shields.io/github/repo-size/GabrielCordeiroDev/firebase-cloud-functions"> <img alt="GitHub" src="https://img.shields.io/github/license/GabrielCordeiroDev/firebase-cloud-functions"> </p> <p align="center"> <a href="#-about-the-project">About the project</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#-technologies">Technologies</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#-getting-started">Getting started</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; <a href="#-license">License</a> </p> <p id="insomniaButton" align="center"> <a href="https://insomnia.rest/run/?label=Firebase%20Cloud%20Functions&uri=https%3A%2F%2Fraw.githubusercontent.com%2FGabrielCordeiroDev%2Ffirebase-cloud-functions%2Fmain%2FInsomnia.json" target="_blank"><img src="https://insomnia.rest/images/run.svg" alt="Run in Insomnia"></a> </p> ## 👨🏻‍💻 About the project This is a Serverless API developed with Firebase Cloud Functions for learning purposes. ## 🚀 Technologies Technologies that I used to develop this API: - [Node.js](https://nodejs.org/en/) - [TypeScript](https://www.typescriptlang.org/) - [Firebase](https://firebase.google.com/) - [Express](https://expressjs.com/pt-br/) - [Eslint](https://eslint.org/) ## 💻 Getting started Import the `Insomnia.json` on Insomnia App or click on [Run in Insomnia](#insomniaButton) button. ### Requirements - [Node.js](https://nodejs.org/en/) - [Yarn](https://classic.yarnpkg.com/) or [npm](https://www.npmjs.com/) - [Firebase CLI](https://firebase.google.com/docs/cli) > Obs.: You will need to create a [Firebase](https://firebase.google.com/) account and also a project to make Cloud Functions and Firestore Database available. **Clone the project and access the folder** ```bash $ git clone https://github.com/GabrielCordeiroDev/firebase-cloud-functions $ cd firebase-cloud-functions/functions ``` **Environment Setting** ```bash $ firebase login $ firebase functions:config:set private.key="" project.id="" client.email="" ``` **Follow the steps below** ```bash # Install the dependencies $ yarn # Make a copy of '.env.example' to '.env' # and set with YOUR environment variables $ cp .env.example .env ``` **Deploy** ``` $ yarn deploy ``` ## 📝 License This project is licensed under the MIT License - see the [LICENSE](https://github.com/GabrielCordeiroDev/firebase-cloud-functions/blob/main/LICENSE) file for details. <file_sep>/functions/src/controllers/AddEntryController.ts import {Request, Response} from "express"; import {db} from "../config/firebase"; export class AddEntryController { async handle(req: Request, res: Response): Promise<Response> { const {title, text} = req.body; const entry = db.collection("entries").doc(); const entryObject = { id: entry.id, title, text, }; await entry.set(entryObject); return res.status(201).json({ status: "success", message: "entry added successfully", data: entryObject, }); } } <file_sep>/functions/src/controllers/GetAllEntriesController.ts import {Request, Response} from "express"; import {db} from "../config/firebase"; export class GetAllEntriesController { async handle(_: Request, res: Response): Promise<Response> { const allEntries: FirebaseFirestore.DocumentData[] = []; const querySnapshot = await db.collection("entries").get(); querySnapshot.forEach((doc) => allEntries.push(doc.data())); return res.json(allEntries); } } <file_sep>/functions/src/routes.ts import {Router} from "express"; import {AddEntryController} from "./controllers/AddEntryController"; import {DeleteEntryController} from "./controllers/DeleteEntryController"; import {GetAllEntriesController} from "./controllers/GetAllEntriesController"; import {UpdateEntryController} from "./controllers/UpdateEntryController"; const router = Router(); const addEntryController = new AddEntryController(); const getAllEntriesController = new GetAllEntriesController(); const updateEntryController = new UpdateEntryController(); const deleteEntryController = new DeleteEntryController(); router.post("/entry", addEntryController.handle); router.get("/entry", getAllEntriesController.handle); router.put("/entry/:entryId", updateEntryController.handle); router.delete("/entry/:entryId", deleteEntryController.handle); export {router}; <file_sep>/functions/src/index.ts import * as functions from "firebase-functions"; import "express-async-errors"; import * as express from "express"; import {router} from "./routes"; const app = express(); app.use(router); app.use(( err: Error, req: express.Request, res: express.Response, // eslint-disable-next-line @typescript-eslint/no-unused-vars _: express.NextFunction) => { if (err instanceof Error) { return res.status(400).json({ status: "error", message: err.message, }); } return res.status(500).json({ status: "error", message: "Internal Server Error", }); }); exports.app = functions.https.onRequest(app);
b95357e5bb02b921ab7dcda5c1761ca8fe711511
[ "Markdown", "TypeScript" ]
7
TypeScript
GabrielCordeiroDev/firebase-cloud-functions
8d00633ddb5644b73391f63066e350efb67a00c8
93e169422827b865d546e80cf31b1866701b5f98
refs/heads/master
<repo_name>KevinsVision/london-web-career-031119<file_sep>/08-intro-to-ar/app/models/artist.rb class Artist < ActiveRecord::Base has_many :tracks has_many :fandoms has_many :fans, through: :fandoms end # Model: Ruby Class <=> DB Table # i.e. Artist <=> artists
8f0d150713c1ca18b7d5f9dbf3fee8c1db7be0c2
[ "Ruby" ]
1
Ruby
KevinsVision/london-web-career-031119
cc7db62d794c408e074df583e043ed94c9e88b29
6b650dbc3025240714fe6a407151da53fe0d63bd
refs/heads/master
<repo_name>mbimbij/victor_rentea_devoxxfr_2018_follow_along<file_sep>/src/main/java/com/example/demo/Application.java package com.example.demo; import java.util.function.BiFunction; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class Movie { private final Type type; Movie(Type type) { this.type = type; } enum Type { REGULAR(PriceService::computeRegularPrice), NEW_RELEASE(PriceService::computeNewReleasePrice), CHILDREN(PriceService::computeChildrenPrice); public final BiFunction<PriceService, Integer, Integer> priceAlgo; Type(BiFunction<PriceService, Integer, Integer> priceAlgo) { this.priceAlgo = priceAlgo; } } } interface FactorRepo { Double getFactor(); } class PriceService { private final FactorRepo repo; PriceService(FactorRepo repo) { this.repo = repo; } protected Integer computeNewReleasePrice(int days) { return (int) (repo.getFactor() * days); } protected Integer computeRegularPrice(int days) { return days + 1; } protected Integer computeChildrenPrice(int days) { return 5; } public Integer computePrice(Movie.Type type, int days) { return type.priceAlgo.apply(this, days); } } public class Application { public static void main(String[] args) { FactorRepo repo = mock(FactorRepo.class); when(repo.getFactor()).thenReturn(2d); PriceService priceService = new PriceService(repo); System.out.println(priceService.computeRegularPrice(2)); System.out.println(priceService.computeNewReleasePrice(2)); System.out.println(priceService.computeChildrenPrice(2)); // System.out.println(new Movie(Movie.Type.REGULAR).computePrice(2)); // System.out.println(new Movie(Movie.Type.NEW_RELEASE).computePrice(2)); // System.out.println(new Movie(Movie.Type.CHILDREN).computePrice(2)); System.out.println("commit NOW !"); } }
ad3d93f64c3c4c56e093dd0e6d3c825ccaf5f69d
[ "Java" ]
1
Java
mbimbij/victor_rentea_devoxxfr_2018_follow_along
376d99030eebe7e96815a5a2d5fe8ecb86d700c9
d455aa6fd41f4b276150d9a1de2360d7afc4c1b7
refs/heads/master
<repo_name>RyuNen344/groupie-selection<file_sep>/data/api/src/main/java/com/ryunen344/selection/api/ApiEndpoint.kt package com.ryunen344.selection.api fun apiEndpoint(): String = BuildConfig.API_ENDPOINT <file_sep>/data/repository/src/main/java/com/ryunen344/selection/repository/RepositoryModule.kt package com.ryunen344.selection.repository import com.ryunen344.selection.repository.github.GitHubRepository import org.koin.dsl.module val repositoryModule = module { single { GitHubRepository(get()) } } <file_sep>/resource/src/main/java/com/ryunen344/selection/resource/Empty.kt package com.ryunen344.selection.resource object Empty { }
01ba7ff38b11cebd7ae73c82a0e735fd502568a7
[ "Kotlin" ]
3
Kotlin
RyuNen344/groupie-selection
dc3c43a91cfe474c2cad291252806bbe44da286f
53513b393673b616bce9f807e61039f1e3904647
refs/heads/master
<file_sep>//返回顶部按钮 define(['jquery'], function($){ function toTop(){ //右侧边栏固定菜单移入移出 $(".right-bar a").on('mouseenter', function(){ $(".right-bar .iconfont").eq($(this).index()).css('color', '#333'); $(".right-bar a div").eq($(this).index()).css('display', 'block'); }); $(".right-bar a").on('mouseleave', function(){ $(".right-bar .iconfont").eq($(this).index()).css('color', '#bbb'); $(".right-bar a div").eq($(this).index()).css('display', 'none'); }) if($(window).scrollTop()>=1200){ $('#backtop').css('display', 'block'); }else{ $('#backtop').css('display', 'none'); } $(window).scroll(function(){ if($(window).scrollTop()>=1200){ $('#backtop').css('display', 'block'); }else{ $('#backtop').css('display', 'none'); } }) $('#backtop').on('click', function(ev){ ev.preventDefault(); $('html,body').animate({scrollTop:0}, 1000); }); } return {toTop: toTop}; })<file_sep>define(['jquery'], function($){ function insert(){ var navArr = ['荣耀', 'HUAWEI P系列', '荣耀畅玩系列', 'HUAWEI Mate系列', 'HUAWEI nova系列', '华为畅享系列', 'HUAWEI 麦芒系列', '移动4G+专区']; for(var i = 0; i < navArr.length; i++){ $('.cate-attr .cate-values ul').append(`<li><a href="#">${navArr[i]}</a></li>`); } $.ajax({ type: 'get', url: 'data/phone.json', success: function(arr){ for(var i = 0; i < arr.length; i++){ $(`<li> <div class="pro-panel"> <div class="p-img"> <a href="${arr[i].aUrl}"> <img src="${arr[i].imgUrl}" alt=""> </a> </div> <div class="p-title"> <a href="#">${arr[i].title}</a> </div> <div class="p-price">${arr[i].price}</div> <div class="p-button clear"> <a href="${arr[i].aUrl}" class="p-button-car">选购</a> <span class="p-button-score">${arr[i].evaluateNum}人评价</span> </div> </div> </li>`).appendTo('.phones .pro-list ul'); } }, error: function(msg){ } }); function selSort(arr, type){ for(var i = 0; i < arr.length; i++){ for(var j = i+1; j<arr.length; j++){ if(arr[i][type]>arr[j][type]){ [arr[i], arr[j]] = [arr[j], arr[i]]; } } } return arr; } function sort(sortType){ $('.sort-desc').removeClass('selected'); $(this).parent().addClass('selected'); $('.phones .pro-list').css('height', $('.phones .pro-list').height()); $('.phones .pro-list ul').html(''); $.ajax({ type: 'get', url: 'data/phone.json', success: function(arr){ //转成num for(var i = 0; i < arr.length; i++){ arr[i].priceNum = parseInt(arr[i].priceNum); arr[i].evaluateNum = parseInt(arr[i].evaluateNum); } if(sortType == 'time'){ }else{ arr = selSort(arr, sortType) } for(var i = 0; i<arr.length;i++){ $(`<li> <div class="pro-panel"> <div class="p-img"> <a href="${arr[i].aUrl}"> <img src="${arr[i].imgUrl}" alt=""> </a> </div> <div class="p-title"> <a href="#">${arr[i].title}</a> </div> <div class="p-price">${arr[i].price}</div> <div class="p-button clear"> <a href="${arr[i].aUrl}" class="p-button-car">选购</a> <span class="p-button-score">${arr[i].evaluateNum}人评价</span> </div> </div> </li>`).appendTo('.phones .pro-list ul'); } }, error: function(msg){ console.log(msg); } }); } $('#timeSort').on('click', 'a', function(){ sort.call($(this), ['time']); }); $('#priceSort').on('click', 'a', function(){ sort.call($(this), ['priceNum']); }); $('#scoreSort').on('click', 'a', function(){ sort.call($(this), ['evaluateNum']); }); } return {insert: insert} });<file_sep>console.log('phone page'); require.config({ paths:{ jquery: 'jquery-1.11.3', cookie: 'jquery.cookie', phone: 'phone', toTop: 'toTop' }, shim:{ cookie: 'jquery' } }) require(['phone', 'toTop'], function(phone, toTop){ phone.insert(); toTop.toTop(); })<file_sep>const gulp = require('gulp'); gulp.task('copy-html', function(){ return gulp.src('*.html') .pipe(gulp.dest('dest')) .pipe(connect.reload()); }) gulp.task('images', function(){ return gulp.src('img/*.{jpg,png}') .pipe(gulp.dest('dest/img')) .pipe(connect.reload()); }) gulp.task('data', function(){ return gulp.src(['*.json', '!package.json']) .pipe(gulp.dest('dest/data')) .pipe(connect.reload()); }) gulp.task('build', ['copy-html', 'images', 'data'], function(){ console.log("编译完成"); }); //scss const scss = require('gulp-scss'); const minifyCss = require('gulp-minify-css'); const rename = require('gulp-rename'); gulp.task('scss', function(){ return gulp.src('stylesheet/index.scss') .pipe(scss()) .pipe(gulp.dest('dest/css')) .pipe(minifyCss()) .pipe(rename('index.min.css')) .pipe(gulp.dest('dest/css')) .pipe(connect.reload()); }) gulp.task('phoneScss', function(){ return gulp.src('stylesheet/phone.scss') .pipe(scss()) .pipe(gulp.dest('dest/css')) .pipe(minifyCss()) .pipe(rename('phone.min.css')) .pipe(gulp.dest('dest/css')) .pipe(connect.reload()); }) gulp.task('proScss', function(){ return gulp.src('stylesheet/10086983017283.scss') .pipe(scss()) .pipe(gulp.dest('dest/css')) .pipe(minifyCss()) .pipe(rename('10086983017283.min.css')) .pipe(gulp.dest('dest/css')) .pipe(connect.reload()); }) //js gulp.task('scripts', function(){ return gulp.src(['*.js', '!gulpfile.js']) .pipe(gulp.dest('dest/js')) .pipe(connect.reload()); }) //listen gulp.task('watch', function(){ gulp.watch('*.html', ['copy-html']); gulp.watch('img/*.{jpg,png}', ['images']); gulp.watch(['*.json', '!package.json'], ['data']); gulp.watch('stylesheet/index.scss', ['scss']); gulp.watch('stylesheet/phone.scss', ['phoneScss']); gulp.watch('stylesheet/10086983017283.scss', ['proScss']); gulp.watch(['*.js', '!gulpfile.js'], ['scripts']); }) //server const connect = require('gulp-connect'); gulp.task('server', function(){ connect.server({ root: 'dest', port: 8888, livereload: true }) }) gulp.task('default', ['watch', 'server']);
047a0dd2ff970a3897e458318ccfa1d90b12d38d
[ "JavaScript" ]
4
JavaScript
wanglin1044/testmyself
4f9d6b7dfa4708794d4e39693face00b3085ddc6
7b2cb93034ca3010f12fc26241431bbc91bd1960
refs/heads/master
<file_sep>$("document").ready(function () { var submitBtn = $("#submit") function enable() { // function to enable submit button submitBtn.attr("disabled", false) submitBtn.css("background-color", " rgb(6, 202, 6)"); } function disable() { // function to disable submit button submitBtn.attr("disabled", true); submitBtn.css("background-color", "blue") } var username = $("#userName"); username.blur(function () { disable(); $(".error").remove(); //remove previous error messages let usernameVal = username.val(); //checking username if (usernameVal === "") { //empty username disable(); $(".word").after("<span class='error'>Username can not be empty!</span>"); } else if (usernameVal.length < 7) { //if length of username is less than 7 is should throw error disable(); $(".word").after("<span class='error'>Username can not be less than 6 character</span>"); } else { $(".fa-user").css("background-color", " rgb(6, 202, 6)") // enable(); } }); //checking Age var age = $("#age"); age.blur(function () { disable(); $(".error").remove(); //remove previous error messages var ageVal = age.val(); if (ageVal === "") { //empty age disable(); $(".word1").after("<span class='error'>Age field can not be empty!</span>"); } else if (ageVal < 18) { //if age is less than 18 is should throw error disable(); $(".word1").after("<span class='error' >Oop! you must be older than 17 years to apply"); } else { $(".fa-male").css("background-color", " rgb(6, 202, 6)") // enable(); } }); //checking password var password = $("#<PASSWORD>"); password.blur(() => { disable(); $(".error").remove(); //remove previous error messages var passwordVal = password.val(); if (passwordVal === "") { // empty password disable(); $(".word2").after("<span class='error'>Password can not be empty!</span>"); } else if (passwordVal.length < 8) { //if length of password is less than 8 is should throw error disable(); $(".word2").after("<span class='error'>Password can not be less than 8 character</span>"); } else { $(".pass").css("background-color", " rgb(6, 202, 6)") // enable(); } }) // comfirmed password var comfirmedPassword = $("#<PASSWORD>"); comfirmedPassword.blur(function () { let passwordVal = $("#password").val(); let comfirmedPasswordVal = comfirmedPassword.val(); $(".error").remove(); //remove previous error messages if (comfirmedPasswordVal === "") { // empty password disable(); $(".word3").after("<span class='error'>Match Password can not be empty!</span>"); } else if (comfirmedPasswordVal != passwordVal) { //checking password and comfirmed password disable(); $(".word3").after("<span class='error'>Your Passwords Must Match!</span>"); } else { enable(); $(".pass1").css("background-color", " rgb(6, 202, 6)"); // submitBtn.css("background-color", " rgb(6, 202, 6)"); } }) //Enabling the Submit button let usernameVal = username.val(); var ageVal = age.val(); var passwordVal = password.val(); let comfirmedPasswordVal = comfirmedPassword.val(); if (usernameVal.length > 6 && ageVal > 17 && passwordVal.length > 7 && comfirmedPasswordVal === passwordVal) { enable(); } });<file_sep># formValidation A simple form that collect user input and validate it using JQuery. Take a look at the form: https://sirsuccess.github.io/formValidation/.
9054409c0b080deef56ad50c722357f4f2963841
[ "JavaScript", "Markdown" ]
2
JavaScript
sirsuccess/formValidation
9640a04fdcd917a9a5e938f8a38d74c2326a1d56
55dd6014c63d3f9e46fdc7b985a334b9f8f3b4f8
refs/heads/master
<repo_name>monitotxi/yahtzee_kata_round_1<file_sep>/src/YahtzeeFactory.php <?php namespace Yahtzee; class YahtzeeFactory { /** * @param ConsoleInterface $console * @param DieRollerInterface $dieRoller * * @return Yahtzee */ public static function makeYahtzee(ConsoleInterface $console, DieRollerInterface $dieRoller) { $consoleNotifier = new ConsoleNotifier($console); return new Yahtzee( self::makeCategories(), new Scores(), $consoleNotifier, self::makeRound($console, $consoleNotifier, $dieRoller) ); } /** * @return array */ private static function makeCategories() { $categoriesList = [ 1 => 'Ones', 2 => 'Twos', 3 => 'Threes', ]; $categories = []; foreach ($categoriesList as $categoryValue => $categoryName) { $categories[] = new Category(new ScoreCalculator(), $categoryName, $categoryValue); } return $categories; } /** * @param ConsoleInterface $console * @param ConsoleNotifier $consoleNotifier * @param DieRollerInterface $dieRoller * * @return Round */ private static function makeRound( ConsoleInterface $console, ConsoleNotifier $consoleNotifier, DieRollerInterface $dieRoller ) { return new Round( self::makeDice($dieRoller), new InputLine($console), $consoleNotifier ); } /** * @param DieRollerInterface $dieRoller * * @return Dice */ public static function makeDice(DieRollerInterface $dieRoller) { $dice = []; for ($i = 1; $i <= 5; ++$i) { $dice[$i] = new PlayerDie($dieRoller); } return new Dice($dice); } } <file_sep>/tests/acceptance/YahtzeeTest.php <?php use Yahtzee\DieRollerInterface; use Yahtzee\YahtzeeFactory; class YahtzeeTest extends PHPUnit_Framework_TestCase { /** * @test */ public function play() { $userInput = [ 'D1 D2 D4', 'D2 D4', 'D2 D5', 'D3 D4 D5', 'D1 D2 D3 D4 D5', 'D1 D2 D4', ]; $console = new FakeConsole($userInput); $dieRoller = $this->getMock(DieRollerInterface::class); $dieRoller->method('roll')->willReturnOnConsecutiveCalls( 2, 4, 1, 6, 1, 1, 5, 2, 1, 5, 2, 4, 1, 6, 1, 2, 3, 6, 1, 2, 2, 4, 1, 6, 1, 5, 1, 3, 2, 3, 6, 2, 4 ); $yahtzee = YahtzeeFactory::makeYahtzee($console, $dieRoller); $yahtzee->play(); $output = $console->getOutput(); $expected = [ 'Category: Ones', 'Dice: D1:2 D2:4 D3:1 D4:6 D5:1', '[1] Dice to re-run:', 'Dice: D1:1 D2:5 D3:1 D4:2 D5:1', '[2] Dice to re-run:', 'Dice: D1:1 D2:1 D3:1 D4:5 D5:1', 'Category Ones score: 4', 'Category: Twos', 'Dice: D1:2 D2:4 D3:1 D4:6 D5:1', '[1] Dice to re-run:', 'Dice: D1:2 D2:2 D3:1 D4:6 D5:3', '[2] Dice to re-run:', 'Dice: D1:2 D2:2 D3:6 D4:1 D5:2', 'Category Twos score: 3', 'Category: Threes', 'Dice: D1:2 D2:4 D3:1 D4:6 D5:1', '[1] Dice to re-run:', 'Dice: D1:5 D2:1 D3:3 D4:2 D5:3', '[2] Dice to re-run:', 'Dice: D1:6 D2:2 D3:3 D4:4 D5:3', 'Category Threes score: 2', 'Yahtzee score', 'Ones: 4', 'Twos: 3', 'Threes: 2', 'Final score: 9', ]; $this->assertEquals($expected, $output); } } <file_sep>/tests/helpers/FakeConsole.php <?php use Yahtzee\Console; class FakeConsole extends Console { /** * @var array */ private $output = []; /** * @var array */ private $input; /** * @var int */ private $position = 0; /** * FakeConsole constructor. * * @param array $input */ public function __construct(array $input = []) { $this->input = $input; } /** * @param string $line */ public function printLine($line) { $this->output[] = $line; } /** * @return array */ public function getOutput() { return $this->output; } /** * @return string */ public function readLine() { $line = $this->input[$this->position]; ++$this->position; return $line; } } <file_sep>/src/ConsoleNotifier.php <?php namespace Yahtzee; class ConsoleNotifier { /** * @var ConsoleInterface */ private $console; /** * ConsoleNotifier constructor. * * @param ConsoleInterface $console */ public function __construct(ConsoleInterface $console) { $this->console = $console; } /** * @param array $categories * @param Scores $scores */ public function scores(array $categories, Scores $scores) { $this->printLine('Yahtzee score'); $this->printCategoriesScores($categories, $scores); $this->printLine('Final score: '.$scores->total()); } /** * @param $line */ private function printLine($line) { $this->console->printLine($line); } /** * @param array $categories * @param Scores $scores */ private function printCategoriesScores(array $categories, Scores $scores) { $allScores = $scores->all(); foreach ($categories as $category) { $this->printLine($category->getName().': '.$allScores[$category->getName()]); } } /** * @param $categoryName * * @return mixed */ public function categoryName($categoryName) { $this->printLine('Category: '.$categoryName); } /** * @param Dice $dice */ public function dice(Dice $dice) { $results = $dice->getResults(); $line = 'Dice: '; foreach ($results as $key => $value) { $str = 'D'.$key.':'.$value.' '; $line .= $str; } $this->printLine(trim($line)); } /** * @param $categoryName * @param $score */ public function categoryScore($categoryName, $score) { $this->printLine('Category '.$categoryName.' score: '.$score); } /** * @param $time */ public function diceReRun($time) { $this->printLine("[$time] Dice to re-run:"); } } <file_sep>/play_yahtzee.php <?php require __DIR__.'/vendor/autoload.php'; use Yahtzee\DieRoller; use Yahtzee\Console; use Yahtzee\YahtzeeFactory; $yahtzee = YahtzeeFactory::makeYahtzee(new Console(), new DieRoller()); $yahtzee->play(); <file_sep>/src/Round.php <?php namespace Yahtzee; class Round { /** * @var Dice */ private $dice; /** * @var InputLine */ private $inputLine; /** * @var ConsoleNotifier */ private $consoleNotifier; /** * Round constructor. * * @param Dice $dice * @param InputLine $inputLine * @param ConsoleNotifier $consoleNotifier */ public function __construct(Dice $dice, InputLine $inputLine, ConsoleNotifier $consoleNotifier) { $this->dice = $dice; $this->inputLine = $inputLine; $this->consoleNotifier = $consoleNotifier; } /** * @return Dice */ public function run() { $this->dice->rollAll(); $this->consoleNotifier->dice($this->dice); $this->reRun(); return $this->dice; } private function reRun() { $i = 1; do { $diceToReRun = $this->getDiceToReRun($i); if ($diceToReRun) { $this->reRunDice($diceToReRun); } ++$i; } while ($diceToReRun && $i <= 2); } /** * @param $i * * @return array */ private function getDiceToReRun($i) { $this->consoleNotifier->diceReRun($i); return $this->inputLine->readLine(); } /** * @param $diceToReRoll */ private function reRunDice($diceToReRoll) { $this->dice->roll($diceToReRoll); $this->consoleNotifier->dice($this->dice); } } <file_sep>/tests/unit/InputLineTest.php <?php use Yahtzee\ConsoleInterface; use Yahtzee\InputLine; class InputLineTest extends PHPUnit_Framework_TestCase { /** * @test */ public function read_user_input() { $console = $this->getMock(ConsoleInterface::class); $console->method('readLine')->willReturn('D2 D4'); $inputLine = new InputLine($console); $dice = $inputLine->readLine(); $this->assertEquals([2, 4], $dice); } /** * @test */ public function read_empty_user_input() { $console = $this->getMock(ConsoleInterface::class); $console->method('readLine')->willReturn(''); $inputLine = new InputLine($console); $dice = $inputLine->readLine(); $this->assertEmpty($dice); } } <file_sep>/src/Console.php <?php namespace Yahtzee; class Console implements ConsoleInterface { /** * @param string $line */ public function printLine($line) { echo $line."\n"; } /** * @return string */ public function readLine() { return readline(); } } <file_sep>/tests/unit/ScoreCalculatorTest.php <?php use Yahtzee\Dice; use Yahtzee\DieRollerInterface; use Yahtzee\ScoreCalculator; use Yahtzee\YahtzeeFactory; class ScoreCalculatorTest extends PHPUnit_Framework_TestCase { /** * @test */ public function calculate_score_for_categories() { $scoreCalculator = new ScoreCalculator(); $dice = $this->getDice(); $scoreOnes = $scoreCalculator->calculate(1, $dice); $this->assertEquals(2, $scoreOnes); $scoreTwos = $scoreCalculator->calculate(2, $dice); $this->assertEquals(1, $scoreTwos); } /** * @return Dice */ private function getDice() { $dieRoller = $this->getMock(DieRollerInterface::class); $dieRoller->method('roll')->willReturnOnConsecutiveCalls(2, 1, 5, 1, 3); $dice = YahtzeeFactory::makeDice($dieRoller); $dice->rollAll(); return $dice; } } <file_sep>/tests/unit/ScoresTest.php <?php use Yahtzee\Scores; class ScoresTest extends PHPUnit_Framework_TestCase { /** * @test */ public function calculate_total_score() { $scores = $this->createScores(); $this->assertEquals(2 + 5, $scores->total()); } /** * @return Scores */ private function createScores() { $scores = new Scores(); $scores->add('ones', 2); $scores->add('twos', 5); return $scores; } /** * @test */ public function get_scores() { $scores = $this->createScores(); $expected = [ 'ones' => 2, 'twos' => 5, ]; $this->assertEquals($expected, $scores->all()); } } <file_sep>/src/Scores.php <?php namespace Yahtzee; class Scores { /** * @var array */ private $scores = []; /** * @param string $categoryName * @param int $score */ public function add($categoryName, $score) { $this->scores[$categoryName] = $score; } /** * @return array */ public function all() { return $this->scores; } /** * @return int */ public function total() { return array_sum($this->scores); } } <file_sep>/src/ScoreCalculator.php <?php namespace Yahtzee; class ScoreCalculator { /** * @param int $value * @param Dice $dice * * @return int */ public function calculate($value, Dice $dice) { $score = 0; $results = $dice->getResults(); foreach ($results as $dieValue) { if ($dieValue === $value) { ++$score; } } return $score; } } <file_sep>/src/DieRoller.php <?php namespace Yahtzee; class DieRoller implements DieRollerInterface { /** * @return int */ public function roll() { return mt_rand(1, 6); } } <file_sep>/src/ConsoleInterface.php <?php namespace Yahtzee; interface ConsoleInterface { /** * @param string $line */ public function printLine($line); /** * @return string */ public function readLine(); } <file_sep>/src/PlayerDie.php <?php namespace Yahtzee; class PlayerDie { /** * @var DieRollerInterface */ private $dieRoller; /** * @var int */ private $lastResult; /** * UserDie constructor. * * @param DieRollerInterface $dieRoller */ public function __construct(DieRollerInterface $dieRoller) { $this->dieRoller = $dieRoller; } public function roll() { $this->lastResult = $this->dieRoller->roll(); } /** * @return int */ public function getResult() { return $this->lastResult; } } <file_sep>/src/InputLine.php <?php namespace Yahtzee; class InputLine { /** * @var ConsoleInterface */ private $console; /** * InputLine constructor. * * @param ConsoleInterface $console */ public function __construct(ConsoleInterface $console) { $this->console = $console; } /** * @return array */ public function readLine() { $input = $this->console->readLine(); return $this->stringToDice($input); } /** * @param string $input * * @return array */ private function stringToDice($input) { $result = []; if (preg_match_all('/D(\\d)+/', $input, $matches) != 0) { $result = $matches[1]; } return $result; } } <file_sep>/src/Yahtzee.php <?php namespace Yahtzee; class Yahtzee { /** * @var ConsoleNotifier */ private $consoleNotifier; /** * @var Round */ private $round; /** * @var Scores */ private $scores; /** * @var array */ private $categories; /** * Yahtzee constructor. * * @param array $categories * @param Scores $scores * @param ConsoleNotifier $consoleNotifier * @param Round $round */ public function __construct(array $categories, Scores $scores, ConsoleNotifier $consoleNotifier, Round $round) { $this->categories = $categories; $this->scores = $scores; $this->consoleNotifier = $consoleNotifier; $this->round = $round; } public function play() { foreach ($this->categories as $category) { $this->playCategory($category); } $this->consoleNotifier->scores($this->categories, $this->scores); } /** * @param Category $category */ private function playCategory(Category $category) { $categoryName = $category->getName(); $this->consoleNotifier->categoryName($categoryName); $dice = $this->round->run(); $score = $category->getScore($dice); $this->scores->add($categoryName, $score); $this->consoleNotifier->categoryScore($categoryName, $score); } } <file_sep>/src/DieRollerInterface.php <?php namespace Yahtzee; interface DieRollerInterface { /** * @return int */ public function roll(); } <file_sep>/tests/unit/DiceRollerTest.php <?php use Yahtzee\DieRollerInterface; use Yahtzee\YahtzeeFactory; class DiceTest extends PHPUnit_Framework_TestCase { /** * @test */ public function have_5_dice() { $dieRoller = $this->getMock(DieRollerInterface::class); $dice = YahtzeeFactory::makeDice($dieRoller); $dice->rollAll(); $this->assertCount(5, $dice->getResults()); } /** * @test */ public function re_roll_dice_specified_and_preserve_others() { $dieRoller = $this->getMock(DieRollerInterface::class); $dieRoller->method('roll')->will($this->onConsecutiveCalls(3, 4, 6, 5, 1, 2, 5)); $dice = YahtzeeFactory::makeDice($dieRoller); $dice->rollAll(); $dice->roll([1, 3]); $expected = [ 1 => 2, 2 => 4, 3 => 5, 4 => 5, 5 => 1, ]; $this->assertEquals($expected, $dice->getResults()); } } <file_sep>/src/Category.php <?php namespace Yahtzee; class Category { /** * @var string */ private $name; /** * @var ScoreCalculator */ private $scoreCalculator; /** * @var int */ private $value; /** * Category constructor. * * @param ScoreCalculator $scoreCalculator * @param $name * @param int $value */ public function __construct(ScoreCalculator $scoreCalculator, $name, $value) { $this->name = $name; $this->scoreCalculator = $scoreCalculator; $this->value = $value; } /** * @return string */ public function getName() { return $this->name; } /** * @param Dice $dice * * @return mixed */ public function getScore(Dice $dice) { return $this->scoreCalculator->calculate($this->value, $dice); } } <file_sep>/src/Dice.php <?php namespace Yahtzee; class Dice { /** * @var array */ private $currentDice; /** * @var array */ private $all; /** * Dice constructor. * * @param array $dice */ public function __construct(array $dice) { $this->currentDice = $dice; $this->all = array_keys($dice); } /** * @return array */ public function rollAll() { return $this->roll($this->all); } /** * @param array $diceToRoll * * @return array */ public function roll(array $diceToRoll) { foreach ($diceToRoll as $dieNumber) { $this->currentDice[$dieNumber]->roll(); } } /** * @return array */ public function getResults() { $results = []; foreach ($this->all as $dieNumber) { $results[$dieNumber] = $this->currentDice[$dieNumber]->getResult(); } return $results; } }
d74fe7e0d25edbe0c5a4c07a9dec1e896fe538f3
[ "PHP" ]
21
PHP
monitotxi/yahtzee_kata_round_1
42382a3e589d5269f9af656b565b0f9d711531ac
7f9944539c1367692546320615d1389e3d9925dc
refs/heads/master
<file_sep>/* * * Pset1, Mario.c * Edx-Harvardx CS50, * * By <NAME> * * Mario is a program that recreates the half-pyramid using hashes (#) for blocks. Enter the height of the pyramid * when prompted to have it inputed. The height mustn't be greater than 23. * * * * ## * ### * #### * ##### * ###### * ####### * ######## *######### * * */ #include <cs50.h> #include <stdio.h> int main(void) { // declare variable int height; // Asking user to pick and enter the correct height. do { printf("Enter the height of the half pyramid: "); height = GetInt(); } while (height <= 0 || height > 23); // Draw half pyramid. for ( int i = 0; i < height; i++) { for (int space = 0; space+(i+1) < height; space++) { printf (" "); } for (int dash = 0 ; dash-(i+1-height) <= height; dash++) { printf ("#"); } printf ("\n"); } return 0; }
34d8ff73b3a9f319123c48559a800290bfa9403d
[ "C" ]
1
C
khalid85/mario
59771d49e277a0970ba42c15103a6f7beb203e99
0abca14971f2ec780e93b99fb5d97e975d0357be
refs/heads/master
<repo_name>kidcats/tinyrender<file_sep>/Circle.hpp // // Created by cats kid on 2020/12/14. // #ifndef RASTERIZER_CIRCLE_HPP #define RASTERIZER_CIRCLE_HPP #include <eigen3/Eigen/Eigen> using namespace Eigen; class Circle { public: Vector3f v;// 中心点坐标 int r; // 半径长度 Vector3f color;// 圆的颜色 Vector3f normal;// 标准化后的坐标 Circle(); Eigen::Vector3f a() const { return v; } void setVertex(Vector3f ver); /*set i-th vertex coordinates */ void setNormal(Vector3f n); /*set i-th vertex normal vector*/ void setColor(float r, float g, float b); /*set i-th vertex color*/ std::array<Vector4f,3> toVector4() const; }; #endif //RASTERIZER_CIRCLE_HPP <file_sep>/Elliptic.cpp // // Created by 1111 on 2020/12/23. // #include "Elliptic.h" Elliptic::Elliptic() { v << 0,0,0; color << 0.0,0.0,0.0; } void Elliptic::setVertex(Vector3f ver) { v = ver; } void Elliptic::setColor(float r, float g, float b) { if ((r < 0.0 || r > 255.)|| (g < 0.0 || g > 255.)||(b < 0.0 || b > 255.)){ throw std::runtime_error("Invalid color values"); } color = Vector3f ((float )r/255,(float) g/255,(float) b/255); return; } <file_sep>/rasterizer.cpp // // Created by goksu on 4/6/19. // #include <algorithm> #include "rasterizer.hpp" #include "Circle.hpp" #include <opencv2/opencv.hpp> #include <math.h> #include <stdexcept> rst::pos_buf_id rst::rasterizer::load_positions( const std::vector<Eigen::Vector3f> &positions) { auto id = get_next_id(); // 获取下一个三角形渲染 pos_buf.emplace(id, positions); // 将要渲染的三角形的位置存入pos_buf return {id}; } rst::ind_buf_id rst::rasterizer::load_indices( const std::vector<Eigen::Vector3i> &indices) { auto id = get_next_id(); ind_buf.emplace(id, indices); return {id}; } // Bresenham's line drawing algorithm // Code taken from a stack overflow answer: https://stackoverflow.com/a/16405254 void rst::rasterizer::draw_line(Eigen::Vector3f begin, Eigen::Vector3f end) { auto x1 = begin.x(); auto y1 = begin.y(); auto x2 = end.x(); auto y2 = end.y(); Eigen::Vector3f line_color = {255, 255, 255}; int x, y, dx, dy, dx1, dy1, px, py, xe, ye, i; dx = x2 - x1; dy = y2 - y1; dx1 = fabs(dx); dy1 = fabs(dy); px = 2 * dy1 - dx1; py = 2 * dx1 - dy1; if (dy1 <= dx1) { if (dx >= 0) { x = x1; y = y1; xe = x2; } else { x = x2; y = y2; xe = x1; } Eigen::Vector3f point = Eigen::Vector3f(x, y, 1.0f); set_pixel(point, line_color); for (i = 0; x < xe; i++) { x = x + 1; if (px < 0) { px = px + 2 * dy1; } else { if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) { y = y + 1; } else { y = y - 1; } px = px + 2 * (dy1 - dx1); } // delay(0); Eigen::Vector3f point = Eigen::Vector3f(x, y, 1.0f); set_pixel(point, line_color); } } else { if (dy >= 0) { x = x1; y = y1; ye = y2; } else { x = x2; y = y2; ye = y1; } Eigen::Vector3f point = Eigen::Vector3f(x, y, 1.0f); set_pixel(point, line_color); for (i = 0; y < ye; i++) { y = y + 1; if (py <= 0) { py = py + 2 * dx1; } else { if ((dx < 0 && dy < 0) || (dx > 0 && dy > 0)) { x = x + 1; } else { x = x - 1; } py = py + 2 * (dx1 - dy1); } // delay(0); Eigen::Vector3f point = Eigen::Vector3f(x, y, 1.0f); set_pixel(point, line_color); } } } // 先假设圆在原点处,然后平移到圆心处 void rst::rasterizer::draw_circle_line(Eigen::Vector3f point, int r) { Eigen::Vector3f line_color = {255, 255, 0}; int p, y, x; int y0 = r; int p0 = 5 / 4 - r; y = y0; p = p0; Eigen::Vector3f point0 = Eigen::Vector3f(0, y0, 1.0f); set_pixel(point0, line_color); for (x = 0; x < y; ++x) { if (p > 0) { // 如果P > 0 说明yk+1 = yk - 1,pk+1 = pk + 2xk + 1 - 2yk p = p + 2 * x + 1 - 2 * y; y = y - 1; } else { // yk+1 = yk pk+1 = pk + 2xk + 3 p = p + 2 * x + 3; y = y; } Eigen::Vector3f point1 = Eigen::Vector3f(x + point.x(), y + point.y(), 1.0f); // 然后画xy对称的坐标 Eigen::Vector3f point2 = Eigen::Vector3f(y + point.x(), x + point.y(), 1.0f);; // 关于x 对称的坐标 Eigen::Vector3f point3 = Eigen::Vector3f(x + point.x(), -y + point.y(), 1.0f); Eigen::Vector3f point4 = Eigen::Vector3f(y + point.x(), -x + point.y(), 1.0f); // 关于y对称的坐标 Eigen::Vector3f point5 = Eigen::Vector3f(-x + point.x(), y + point.y(), 1.0f); Eigen::Vector3f point6 = Eigen::Vector3f(-y + point.x(), x + point.y(), 1.0f);; Eigen::Vector3f point7 = Eigen::Vector3f(-x + point.x(), -y + point.y(), 1.0f); Eigen::Vector3f point8 = Eigen::Vector3f(-y + point.x(), -x + point.y(), 1.0f); set_pixel(point1, line_color); set_pixel(point2, line_color); set_pixel(point3, line_color); set_pixel(point4, line_color); set_pixel(point5, line_color); set_pixel(point6, line_color); set_pixel(point7, line_color); set_pixel(point8, line_color); } } /** * * @param v 中心坐标,先原点,后面再移过去 * @param d1 长轴的一半 * @param d2 短轴的一半 */ void rst::rasterizer::draw_elliptic_line(Vector3f v, int d1, int d2) { Eigen::Vector3f line_color = {255, 255, 0}; Eigen::Vector3f point = Eigen::Vector3f( v.x(), v.y(), 1.0f); set_pixel(point, line_color); int rx_squ = d1 * d1; int ry_squ = d2 * d2; int x1, y1; double p1k; y1 = d2; x1 = 0; p1k = ry_squ - rx_squ * d2 + 0.25 * rx_squ; for (; ry_squ * x1 < rx_squ * y1; x1++) { if (p1k < 0) { y1 = y1; p1k = p1k + ry_squ * (2 * x1 + 3); } else { p1k = p1k + ry_squ * (2 * x1 + 3) - rx_squ * (2 * y1 - 2); y1 = y1 - 1; } // 设置点和它的对称点 Eigen::Vector3f point1 = Eigen::Vector3f(x1 + v.x(), y1 + v.y(), 1.0f); // 关于x轴对称 Eigen::Vector3f point2 = Eigen::Vector3f(x1 + v.x(), -y1 + v.y(), 1.0f); // 关于Y轴对称 Eigen::Vector3f point3 = Eigen::Vector3f(-x1 + v.x(), y1 + v.y(), 1.0f); Eigen::Vector3f point4 = Eigen::Vector3f(-x1 + v.x(), -y1 + v.y(), 1.0f); set_pixel(point1, line_color); set_pixel(point2, line_color); set_pixel(point3, line_color); set_pixel(point4, line_color); } // region2 int x2, y2; double p2k; p2k = ry_squ * (x1 + 0.5) * (x1 + 0.5) + rx_squ * (y1 - 1) * (y1 - 1) - rx_squ * ry_squ; x2 = x1 - 1; y2 = y1; for (; y2 >= 0; --y2) { if (p2k < 0) { p2k = p2k - 2 * rx_squ * (y2 - 1) + rx_squ + ry_squ * (2 * x2 + 2); x2 = x2 + 1; } else { p2k = p2k - 2 * rx_squ * (y2 - 1) + rx_squ; x2 = x2 ; } // 设置点和它的对称点 Eigen::Vector3f point1 = Eigen::Vector3f(x2 + v.x(), y2 + v.y(), 1.0f); // 关于x轴对称 Eigen::Vector3f point2 = Eigen::Vector3f(x2 + v.x(), -y2 + v.y(), 1.0f); // 关于Y轴对称 Eigen::Vector3f point3 = Eigen::Vector3f(-x2 + v.x(), y2 + v.y(), 1.0f); Eigen::Vector3f point4 = Eigen::Vector3f(-x2 + v.x(), -y2 + v.y(), 1.0f); set_pixel(point1, line_color); set_pixel(point2, line_color); set_pixel(point3, line_color); set_pixel(point4, line_color); } } auto to_vec4(const Eigen::Vector3f &v3, float w = 1.0f) { return Vector4f(v3.x(), v3.y(), v3.z(), w); } void rst::rasterizer::draw(rst::pos_buf_id pos_buffer, rst::ind_buf_id ind_buffer, rst::Primitive type) { if (type == rst::Primitive::Triangle) { auto &buf = pos_buf[pos_buffer.pos_id]; // 取出存的三角形相应的数据 auto &ind = ind_buf[ind_buffer.ind_id]; float f1 = (100 - 0.1) / 2.0; // ? float f2 = (100 + 0.1) / 2.0; Eigen::Matrix4f mvp = projection * view * model; for (auto &i : ind) // 当前三角形 { Triangle t; Eigen::Vector4f v[] = { mvp * to_vec4(buf[i[0]], 1.0f), // 将三个点全部化为齐次坐标 mvp * to_vec4(buf[i[1]], 1.0f), mvp * to_vec4(buf[i[2]], 1.0f)}; for (auto &vec : v) // 此处的v是存放了变换后的三个点的坐标, { vec = vec / vec[3]; // vec[3] 是为了将vec[3]重新化为1.0f } for (auto &vert : v) // 将三角形放大,方便看 { vert.x() = 0.5 * width * (vert.x() + 1.0); vert.y() = 0.5 * height * (vert.y() + 1.0); vert.z() = vert.z() * f1 + f2; } for (int i = 0; i < 3; ++i) { t.setVertex(i, v[i].head<3>()); // 更新三角形的新坐标 // t.setVertex(i, v[i].head<3>()); // t.setVertex(i, v[i].head<3>()); } t.setColor(0, 255.0, 0.0, 0.0); t.setColor(1, 0.0, 255.0, 0.0); t.setColor(2, 0.0, 0.0, 255.0); rasterize_wireframe(t); // 渲染新三角形 } } } void rst::rasterizer::draw_circle(rst::pos_buf_id pos_buffer, rst::ind_buf_id ind_buffer, rst::Primitive type, int r) { if (type == rst::Primitive::Circle) { auto &buf = pos_buf[pos_buffer.pos_id]; // 取出存的圆形相应的数据 auto &ind = ind_buf[ind_buffer.ind_id]; Eigen::Matrix4f mvp = projection * view * model; for (auto &i : ind) { Circle c; Eigen::Vector4f v[] = { mvp * to_vec4(buf[i[0]], 1.0f)}; // 先画一个圆 for (auto &vec : v) { vec = vec / vec[3]; // 将齐次坐标的最后一位化为1 } for (auto &vert : v) // 将图形放中间放大 { vert.x() = 0.5 * width + (vert.x() + 1.0); vert.y() = 0.5 * height + (vert.y() + 1.0); } c.setVertex(v[0].head<3>()); // 更新变换后的坐标 // 然后画1/8弧线 Eigen::Vector3f line_color = {255, 255, 0}; set_pixel(c.a(), line_color); draw_circle_line(c.a(), r); } } } void rst::rasterizer::draw_elliptic(pos_buf_id pos_buffer, ind_buf_id ind_buffer, rst::Primitive type, int d1, int d2) { if (type == rst::Primitive::Elliptic) { auto &buf = pos_buf[pos_buffer.pos_id]; // 取出存的圆形相应的数据 auto &ind = ind_buf[ind_buffer.ind_id]; Eigen::Matrix4f mvp = projection * view * model; for (auto &i : ind) { Elliptic e; Eigen::Vector4f v[] = { mvp * to_vec4(buf[i[0]], 1.0f)}; // 先画一个圆 for (auto &vec : v) { vec = vec / vec[3]; // 将齐次坐标的最后一位化为1 } for (auto &vert : v) // 将图形放中间放大 { vert.x() = 0.5 * width + (vert.x() + 1.0); vert.y() = 0.5 * height + (vert.y() + 1.0); } e.setVertex(v[0].head<3>()); Eigen::Vector3f line_color = {255, 255, 0}; draw_elliptic_line(e.a(), d1, d2); } } } void rst::rasterizer::rasterize_wireframe(const Triangle &t) { draw_line(t.c(), t.a()); draw_line(t.c(), t.b()); draw_line(t.b(), t.a()); } void rst::rasterizer::set_model(const Eigen::Matrix4f &m) { model = m; } void rst::rasterizer::set_view(const Eigen::Matrix4f &v) { view = v; } void rst::rasterizer::set_projection(const Eigen::Matrix4f &p) { projection = p; } void rst::rasterizer::clear(rst::Buffers buff) { if ((buff & rst::Buffers::Color) == rst::Buffers::Color) { std::fill(frame_buf.begin(), frame_buf.end(), Eigen::Vector3f{0, 0, 0}); } if ((buff & rst::Buffers::Depth) == rst::Buffers::Depth) { std::fill(depth_buf.begin(), depth_buf.end(), std::numeric_limits<float>::infinity()); } } rst::rasterizer::rasterizer(int w, int h) : width(w), height(h) { frame_buf.resize(w * h); depth_buf.resize(w * h); } int rst::rasterizer::get_index(int x, int y) { return (height - y) * width + x; } void rst::rasterizer::set_pixel(const Eigen::Vector3f &point, const Eigen::Vector3f &color) { //old index: auto ind = point.y() + point.x() * width; if (point.x() < 0 || point.x() >= width || point.y() < 0 || point.y() >= height) return; auto ind = (height - point.y()) * width + point.x(); frame_buf[ind] = color; } <file_sep>/Circle.cpp // // Created by cats kid on 2020/12/14. // #include "Circle.hpp" #include <stdexcept> Circle::Circle() { v << 0,0,0; color << 0,0,0; } void Circle::setVertex(Vector3f ver) { v = ver; } void Circle::setNormal(Vector3f n) { normal = n; } void Circle::setColor(float r, float g, float b) { if ((r < 0.0) || (r > 255.) || (g < 0.0) || (g > 255.) || (b < 0.0) || (b > 255.)) { throw std::runtime_error("Invalid color values"); } color = Vector3f ((float) r / 255,(float) g / 255,(float) b / 255); } //std::array<Vector4f, 3> Circle::toVector4() const //{ // std::array<Vector4f, 3> res; // std::transform(std::begin(v), std::end(v), res.begin(), [](auto& vec) { // return Vector4f(vec.x(), vec.y(), vec.z(), 1.f); // }); // return res; //}<file_sep>/Elliptic.h // // Created by 1111 on 2020/12/23. // #ifndef RASTERIZER_ELLIPTIC_H #define RASTERIZER_ELLIPTIC_H #include <eigen3/Eigen/Eigen> using namespace Eigen; class Elliptic { // 需要长轴长度,短轴长度,中心坐标 public: Vector3f v; Vector3f color; Vector3f normal; float d1,d2;//d1是长轴的一半,d2是短轴的一半 Elliptic(); Eigen::Vector3f a() const { return v; } float get_d1() const { return d1;} float get_d2() const { return d2;} void setVertex(Vector3f ver); void setColor(float r,float g,float b); }; #endif //RASTERIZER_ELLIPTIC_H
262756633e4cecccce7a5d3058f61340aecc233c
[ "C++" ]
5
C++
kidcats/tinyrender
1029dbb597799e0c21ce3c066ca3b7cb224124f7
4f994be5fa6b9bc1e645f0025e635c6a0ec8d8c2
refs/heads/master
<repo_name>PedroHas98/ProjetoMS-La-Casa-de-Papel-<file_sep>/La casa de Papel/Geometria.h #ifndef GEOMETRIA_H_INCLUDED #define GEOMETRIA_H_INCLUDED void Cilindro (int rdiv, int hdiv, float alt, float raio); void TQuadrado (GLfloat alt, GLfloat lar, GLfloat ang); #endif // GEOMETRIA_H_INCLUDED <file_sep>/La casa de Papel/Geometria.c #include "../headers/Textura.h" #include "../headers/Textura.h" #include <GL/glut.h> #include <GL/glu.h> #include <stdlib.h> #include <stdio.h> #include <math.h> void Cilindro (GLint rdiv, GLint hdiv, GLfloat alt, GLfloat raio) { int i, j; GLfloat delta, theta, theta_; GLfloat alt_, delta_H; delta = (2*M_PI)/rdiv; delta_H = alt/hdiv; for(i = 0; i < rdiv; i++) { theta = i * delta; theta_ = theta + delta; glBegin(GL_LINE_LOOP); glVertex3f(0.0, alt, 0.0); glVertex3f(raio*cos(theta), alt, raio*sin(theta)); glVertex3f(raio*cos(theta+delta), alt, raio*sin(theta+delta)); glEnd(); for (j = 0; j < hdiv; j++) { alt_ = j * delta_H; glBegin(GL_QUADS); glTexCoord2f(theta/2*M_PI, (alt_)/alt); glVertex3f(raio*cos(theta), alt_, raio*sin(theta)); glTexCoord2f(theta/2*M_PI, (alt_+delta_H)/alt); glVertex3f(raio*cos(theta), alt_+delta_H, raio*sin(theta)); glTexCoord2f(theta_/2*M_PI, (alt_+delta_H)/alt); glVertex3f(raio*cos(theta_), alt_+delta_H, raio*sin(theta+delta)); glTexCoord2f(theta_/2*M_PI, (alt_)/alt); glVertex3f(raio*cos(theta_), alt_, raio*sin(theta+delta)); glEnd(); } glBegin(GL_LINE_LOOP); glVertex3f(0.0,0.0,0.0); glVertex3f(raio*cos(theta), 0.0, raio*sin(theta)); glVertex3f(raio*cos(theta+delta), 0.0, raio*sin(theta+delta)); glEnd(); } } void TQuadrado (GLfloat lar, GLfloat alt, GLfloat ang) { glRotatef(ang, 0, 1, 0); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3f(-lar/2.0, 0, 0); glTexCoord2f(0.0, 1.0); glVertex3f(-lar/2.0, alt, 0); glTexCoord2f(1.0, 1.0); glVertex3f(lar/2.0, alt, 0); glTexCoord2f(1.0, 0.0); glVertex3f(lar/2.0, 0, 0); glEnd(); } <file_sep>/La casa de Papel/main.cpp #include <GL/glut.h> #include <GL/glu.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include "headers/LaCasa.h" #include "headers/Textura.h" #define WIDTH 1300 #define HEIGHT 720 #define FPS 16 float theta = 0.0; GLuint texturas[20]; GLuint quadros[4]; static float posx = 0.0, posz = -30.0, posy = -3.0, angle = 0.0; enum tMode {TRANSLATE = 0, SCALE} transformMode; float springiness = 50; void init(void); void initTex(void); void display(void); void defineIlumination(void); void keyboard(unsigned char key, int x, int y); void keyboard2(int key, int moposx, int mouse_y); void timer (int id); void idle (void); void initTex(void); void mouseFunc(int button, int state, int x, int y); void mouseMotionFunc(int x, int y); int nWindowID; // atributos de camera float viewerPosition[3] = { 0.0, 0.0, -2.0 }; float viewerDirection[3] = { 0.0, 0.0, 0.0 }; float viewerUp[3] = { 0.0, 1.0, 0.0 }; // valores de rotação para a navegação float navigationRotation[3] = { 0.0, 0.0, 0.0 }; // parametros do contador de frames char pixelstring[30]; int cframe = 0; int time = 0; int timebase = 0; // parâmetros para navegação // posição do mouse qauando pressionado int mousePressedX = 0, mousePressedY = 0; float lastXOffset = 0.0, lastYOffset = 0.0, lastZOffset = 0.0; // estados do botão do mouse int leftMouseButtonActive = 0, middleMouseButtonActive = 0, rightMouseButtonActive = 0; // alterar estado int shiftActive = 0, altActive = 0, ctrlActive = 0; int main (int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(WIDTH, HEIGHT); glutInitWindowPosition(100, 100); glutCreateWindow("Casa da Moeda"); glutDisplayFunc(display); glutKeyboardFunc(keyboard); glutSpecialFunc(keyboard2); glutMouseFunc(mouseFunc); glutMotionFunc(mouseMotionFunc); glutIdleFunc(idle); init(); glutMainLoop(); return 0; } void init (void) { transformMode = TRANSLATE; initTex(); glClearColor(0.50980392156862745098039215686275, 0.77647058823529411764705882352941, 0.91372549019607843137254901960784, 1); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0f, (float)WIDTH/(float)HEIGHT, 1.0f, 100.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glTranslatef(posx, posy, posz); glMatrixMode(GL_MODELVIEW); glEnable(GL_COLOR_MATERIAL); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); glEnable(GL_DEPTH_TEST); glShadeModel(GL_SMOOTH); } void initTex (void) { glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); glEnable(GL_COLOR_MATERIAL); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glGenTextures(3, texturas); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); texturas[0] = carregaBmp("textura/lacasateto.bmp"); texturas[1] = carregaBmp("textura/mpar.bmp"); texturas[2] = carregaBmp("textura/chaointerior.bmp"); texturas[3] = carregaBmp("textura/asfalto.bmp"); texturas[4] = carregaBmp("textura/porta.bmp"); texturas[5] = carregaBmp("textura/janeladecima.bmp"); texturas[6] = carregaBmp("textura/ceu.bmp"); texturas[7] = carregaBmp("textura/janela.bmp"); texturas[8] = carregaBmp("textura/Parede.bmp"); texturas[9] = carregaBmp("textura/Topo.bmp"); texturas[10] = carregaBmp("textura/quadro2.bmp"); texturas[11] = carregaBmp("textura/escada.bmp"); texturas[12] = carregaBmp("textura/textescada.bmp"); texturas[13] = carregaBmp("textura/images1.bmp"); texturas[14] = carregaBmp("textura/bancada.bmp"); texturas[15] = carregaBmp("textura/quadronovo1.bmp"); texturas[16] = carregaBmp("textura/quadron3.bmp"); texturas[17] = carregaBmp("textura/lateralescada2.bmp"); texturas[18] = carregaBmp("textura/paredesechao.bmp"); texturas[19] = carregaBmp("textura/janelinha.bmp"); } void timer (int id) { theta += 0.1; glutPostRedisplay(); glutTimerFunc(FPS, timer, 0); } void idle (void) { theta = 0.1 * glutGet(GLUT_ELAPSED_TIME); glutSwapBuffers(); glutPostRedisplay(); } void display (void) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); GLfloat lightpos[4] = { 5.0, 15.0, 10.0, 1.0 }; glLightfv(GL_LIGHT0, GL_POSITION, lightpos); glTranslatef(viewerPosition[0], viewerPosition[1], viewerPosition[2]); // adicionar rotação de navegação glRotatef(navigationRotation[0], 1.0f, 0.0f, 0.0f); glRotatef(navigationRotation[1], 0.0f, 1.0f, 0.0f); Cenario (texturas, posx, posz, theta); LaCasa(texturas, quadros, theta); theta += 0.000001; glutPostRedisplay(); glFlush(); } void keyboard (unsigned char key,int x, int y) { glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(45.0f, (float)WIDTH/(float)HEIGHT, 1.0f, 100.0f); switch(key) { case 27: exit(0); break; case 't': case 'T': transformMode = TRANSLATE; break; case 'c': case 'C': transformMode = SCALE; break; case 'w': case 'W': posz += 0.5*cos(M_PI*angle/180.0); posx += 0.5*sin(M_PI*angle/180.0); break; case 's': case 'S': posz -= 0.5*cos(M_PI*angle/180.0); posx -= 0.5*sin(M_PI*angle/180.0); break; case 'q': case 'Q': posz += -0.5*sin(M_PI*angle/180.0); posx += 0.5*cos(M_PI*angle/180.0); break; case 'e': case 'E': posz -= -0.5*sin(M_PI*angle/180.0); posx -= 0.5*cos(M_PI*angle/180.0); break; case 'r': case 'R': posy -= -0.5*sin(M_PI*angle/180.0); posy -= 0.5*cos(M_PI*angle/180.0); break; case 'f': case 'F': posy += -0.5*sin(M_PI*angle/180.0); posy += 0.5*cos(M_PI*angle/180.0); break; case 'a': case 'A': angle += 3; break; case 'd': case 'D': angle -= 3; break; } glRotatef(-angle, 0.0, 1.0, 0.0); glTranslatef(posx, posy, posz); } void keyboard2(int key, int moposx, int mouse_y) { int x=0, y=0, z=0; switch(key){ case GLUT_KEY_PAGE_UP: posz++; break; case GLUT_KEY_PAGE_DOWN: posz--; break; } glMatrixMode(GL_PROJECTION); switch(transformMode){ case TRANSLATE: glTranslatef(x, y, z); break; case SCALE: glScalef(1.0+x/10.0, 1.0+y/10.0, 1.0+z/10.0); break; } glutPostRedisplay(); } // mouse callback void mouseFunc(int button, int state, int x, int y) { // recuperar os modificadores switch (glutGetModifiers()) { case GLUT_ACTIVE_SHIFT: shiftActive = 1; break; case GLUT_ACTIVE_ALT: altActive = 1; break; case GLUT_ACTIVE_CTRL: ctrlActive = 1; break; default: shiftActive = 0; altActive = 0; ctrlActive = 0; break; } // recuperar os botões do mouse if (button == GLUT_LEFT_BUTTON){ if (state == GLUT_DOWN) { leftMouseButtonActive += 1; } else leftMouseButtonActive -= 1; } else if (button == GLUT_MIDDLE_BUTTON){ if (state == GLUT_DOWN) { middleMouseButtonActive += 1; lastXOffset = 0.0; lastYOffset = 0.0; } else middleMouseButtonActive -= 1; } else if (button == GLUT_RIGHT_BUTTON){ if (state == GLUT_DOWN) { rightMouseButtonActive += 1; lastZOffset = 0.0; } else rightMouseButtonActive -= 1; } mousePressedX = x; mousePressedY = y; } //----------------------------------------------------------------------------- void mouseMotionFunc(int x, int y) { float xOffset = 0.0, yOffset = 0.0, zOffset = 0.0; // navegação if (leftMouseButtonActive) { navigationRotation[0] += ((mousePressedY - y) * 180.0f) / 2000.0f; navigationRotation[1] += ((mousePressedX - x) * 180.0f) / 2000.0f; mousePressedY = y; mousePressedX = x; } // panning else if (middleMouseButtonActive) { xOffset = (mousePressedX + x); if (!lastXOffset == 0.0) { viewerPosition[0] -= (xOffset - lastXOffset) / 32.0; viewerDirection[0] -= (xOffset - lastXOffset) / 32.0; } lastXOffset = xOffset; yOffset = (mousePressedY + y); if (!lastYOffset == 0.0) { viewerPosition[1] += (yOffset - lastYOffset) / 32.0; viewerDirection[1] += (yOffset - lastYOffset) / 32.0; } lastYOffset = yOffset; } // profundidade do movimento else if (rightMouseButtonActive) { zOffset = (mousePressedX + x); if (!lastZOffset == 0.0) { viewerPosition[2] -= (zOffset - lastZOffset) / 30.0; viewerDirection[2] -= (zOffset - lastZOffset) / 30.0; } lastZOffset = zOffset; } } <file_sep>/La casa de Papel/LaCasa.c #include "../headers/LaCasa.h" #include "../headers/Textura.h" #include "../headers/Geometria.h" #include <GL/glut.h> #include <GL/glu.h> #include <stdlib.h> #include <stdio.h> #include <math.h> GLint pb[6][4] = { {0,1,2,3}, {3,2,6,7},{7,6,5,4}, {4,5,1,0}, {5,6,2,1},{7,4,0,3} }; GLfloat v[8][3]; static void define (float l, float c, float a) { v[0][0] = v[1][0] = v[2][0] = v[3][0] = -l/2.0; v[4][0] = v[5][0] = v[6][0] = v[7][0] = l/2.0; v[0][1] = v[1][1] = v[4][1] = v[5][1] = 0; v[2][1] = v[3][1] = v[6][1] = v[7][1] = a; v[0][2] = v[3][2] = v[4][2] = v[7][2] = c/2.0; v[1][2] = v[2][2] = v[5][2] = v[6][2] = -c/2.0; } GLint faces[6][4] = { {0, 1, 2, 3}, {3, 2, 6, 7}, {7, 6, 5, 4}, {4, 5, 1, 0}, {5, 6, 2, 1}, {7, 4, 0, 3} }; GLfloat v1[8][3] = { {-2.5, -1.5, 9}, {-2.5, -1.5, -9}, {-2.5, 1.5, -9}, {-2.5, 1.5, 9}, {2.5, -1.5, 9}, {2.5, -1.5, -9}, {2.5, 0.0, -9}, {2.5, 0.0, 9} }; GLfloat v3[8][3] = { {-0.5, -0.5, 1}, {-0.5, -0.5, -1}, {-0.5, 0.5, -1}, {-0.5, 0.5, 1}, {0.5, -0.5, 1}, {0.5, -0.5, -1}, {0.5, 0.0, -1}, {0.5, 0.0, 1} }; void drawCube(int fatorr) { int i; glPushMatrix(); glColor3f(255,193,37); glTranslatef(-6.4, 1.0, 6.5); glRotatef(180, 180, 1.0, 0.0); for (i = 0; i < 6; i++) { glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3fv(&v1[faces[i][0]][0]); glTexCoord2f(0.0, fatorr * 1.0); glVertex3fv(&v1[faces[i][1]][0]); glTexCoord2f(fatorr * 1.0, fatorr * 1.0); glVertex3fv(&v1[faces[i][2]][0]); glTexCoord2f(fatorr * 1.0, 0.0); glVertex3fv(&v1[faces[i][3]][0]); glEnd(); } glPopMatrix(); } void drawCube2(int fatorr) { int i; glPushMatrix(); glTranslatef(6.4, 1.0, 6.5); glRotatef(-180, 0, 0, 0); for (i = 0; i < 6; i++) { glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3fv(&v1[faces[i][0]][0]); glTexCoord2f(0.0, fatorr * 1.0); glVertex3fv(&v1[faces[i][1]][0]); glTexCoord2f(fatorr * 1.0, fatorr * 1.0); glVertex3fv(&v1[faces[i][2]][0]); glTexCoord2f(fatorr * 1.0, 0.0); glVertex3fv(&v1[faces[i][3]][0]); glEnd(); } glPopMatrix(); } void Bancada1(int fatorr) { int i; glPushMatrix(); glRotatef(-180, 0, 0, 0); for (i = 0; i < 6; i++) { glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3fv(&v3[faces[i][0]][0]); glTexCoord2f(0.0, fatorr * 1.0); glVertex3fv(&v3[faces[i][1]][0]); glTexCoord2f(fatorr * 1.0, fatorr * 1.0); glVertex3fv(&v3[faces[i][2]][0]); glTexCoord2f(fatorr * 1.0, 0.0); glVertex3fv(&v3[faces[i][3]][0]); glEnd(); } glPopMatrix(); } void Bancada2(int fatorr) { int i; glPushMatrix(); glRotatef(-180, 180, 0, 0); for (i = 0; i < 6; i++) { glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3fv(&v3[faces[i][0]][0]); glTexCoord2f(0.0, fatorr * 1.0); glVertex3fv(&v3[faces[i][1]][0]); glTexCoord2f(fatorr * 1.0, fatorr * 1.0); glVertex3fv(&v3[faces[i][2]][0]); glTexCoord2f(fatorr * 1.0, 0.0); glVertex3fv(&v3[faces[i][3]][0]); glEnd(); } glPopMatrix(); } void Base (float largura, float comprimento, float altura, int fatorr) { int i; define(largura, comprimento, altura); for(i = 0; i < 6; i++){ glBegin(GL_QUADS); glTexCoord2f(0.0, 0.0); glVertex3fv(&v[pb[i][0]][0]); glTexCoord2f(0.0, fatorr * 1.0); glVertex3fv(&v[pb[i][1]][0]); glTexCoord2f(fatorr * 1.0, fatorr * 1.0); glVertex3fv(&v[pb[i][2]][0]); glTexCoord2f(fatorr * 1.0, 0.0); glVertex3fv(&v[pb[i][3]][0]); glEnd(); } } void LaCasa (GLuint* t, GLuint* m, float rot){ int i; int dim = 24; int altpp = 7; //Altura pilar float niv = 0; float salto = .3; // Escadas glBindTexture(GL_TEXTURE_2D, t[11]); for (i = 0; i < 10; i++){ glTranslatef(0, .2, -0.8); glPushMatrix(); Base(dim-niv+2, dim-niv+8.5, .4, 5); glPopMatrix(); niv += salto; }; //Meio da Casa glBindTexture(GL_TEXTURE_2D, t[18]); //---------------------------------------- // Paredes laterais //parede maior glPushMatrix(); glTranslatef(-8, salto, -1.5); Base(.3, 27, altpp+5, 1); glPopMatrix(); //parede glPushMatrix(); glTranslatef(8, salto, -1.5); Base(.3, 27, altpp+5, 1); glPopMatrix(); glBindTexture(GL_TEXTURE_2D, t[14]); //lado esquerdo //paredinha divisoria glPushMatrix(); glTranslatef(-7.9, salto+6, -1.5); Base(.2, 27, .3, 1); glPopMatrix(); //paredinha divisoria glPushMatrix(); glTranslatef(-7.9, salto+5, -1.5); Base(.2, 27, .3, 1); glPopMatrix(); //paredinha divisoria glPushMatrix(); glTranslatef(7.9, salto+6, -1.5); Base(.2, 27, .3, 1); glPopMatrix(); //paredinha divisoria glPushMatrix(); glTranslatef(7.9, salto+5, -1.5); Base(.2, 27, .3, 1); glPopMatrix(); //lado direito glPushMatrix(); glTranslatef(-7.9, salto, -14.6); Base(.2, .3, 6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-7.9, salto, -5.6); Base(.2, .3, 6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-7.9, salto, 3); Base(.2, .3, 6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-7.9, salto, 11.5); Base(.2, .3, 6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(7.9, salto, -14.6); Base(.2, .3, 6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(7.9, salto, -5.6); Base(.2, .3, 6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(7.9, salto, 3); Base(.2, .3, 6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(7.9, salto, 11.5); Base(.2, .3, 6, 1); glPopMatrix(); //----------------------------------------- glBindTexture(GL_TEXTURE_2D, t[8]); // Paredes traseira glPushMatrix(); glTranslatef(0, salto-3, -16.1); Base(20, 2, altpp+8, 10); glPopMatrix(); //parede da frente glPushMatrix(); glTranslatef(0, salto, 11.8); Base(20, .5, altpp+5, 10); glPopMatrix(); //---------------------------------- //INICIO DA CRIA픈O DO TOPO // Topo central glPushMatrix(); glBindTexture(GL_TEXTURE_2D, t[1]); glTranslatef(0, salto+9, 12.2); Base(10, 0.2, 2.5, 1); glBindTexture(GL_TEXTURE_2D, t[9]); glTranslatef(0, salto, 0.2); TQuadrado(2,2,0); glPopMatrix(); //FIM DA CRIA플O DO TOPO //------------------------------------------ //INICIO DA CRIA플O DE TODAS AS PORTAS // Porta central glBindTexture(GL_TEXTURE_2D, t[4]); glPushMatrix(); glTranslatef(0, salto, 12.2); Base(2, .2, 3.4, 1); glPopMatrix(); glPushMatrix(); glTranslatef(0, salto, 11.3); Base(2, .2, 3.4, 1); glPopMatrix(); //Porta Direita glPushMatrix(); glTranslatef(6, salto, 12.2); Base(2, .2, 3.4, 1); glPopMatrix(); // Porta Esquerda glPushMatrix(); glTranslatef(-6, salto, 12.2); Base(2, .2, 3.4, 1); glPopMatrix(); //FIM DA CRIA플O DAS PORTAS //------------------------------------------ //------------------------------------------ //JANELAS MEIO LATERAL DIREITA glBindTexture(GL_TEXTURE_2D, t[7]); glPushMatrix(); glTranslatef(12, salto+5, 11.2); Base(1.6, .2, 3, 1); glPopMatrix(); glPushMatrix(); glTranslatef(15, salto+5, 11.2); Base(1.6, .2, 3, 1); glPopMatrix(); glPushMatrix(); glTranslatef(18, salto+5, 11.2); Base(1.6, .2, 3, 1); glPopMatrix(); glPushMatrix(); glTranslatef(21, salto+5, 11.2); Base(1.6, .2, 3, 1); glPopMatrix(); glPushMatrix(); glTranslatef(24, salto+5, 11.2); Base(1.6, .2, 3, 1); glPopMatrix(); glPushMatrix(); glTranslatef(27, salto+5, 11.2); Base(1.6, .2, 3, 1); glPopMatrix(); //FIM DA PRIMEIRA FILEIRA DE JANELAS //------------------------------------------------ //------------------------------------------ //JANELAS MEIO LATERAL ESQUERDA glBindTexture(GL_TEXTURE_2D, t[7]); glPushMatrix(); glTranslatef(-12, salto+5, 11.2); Base(1.6, .2, 3, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-15, salto+5, 11.2); Base(1.6, .2, 3, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-18, salto+5, 11.2); Base(1.6, .2, 3, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-21, salto+5, 11.2); Base(1.6, .2, 3, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-24, salto+5, 11.2); Base(1.6, .2, 3, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-27, salto+5, 11.2); Base(1.6, .2, 3, 1); glPopMatrix(); //FIM DA PRIMEIRA FILEIRA DE JANELAS //------------------------------------------------ //------------------------------------------------ //CRIA플O DA SEGUNDA FILEIRA DE JANELAS glBindTexture(GL_TEXTURE_2D, t[5]); glPushMatrix(); glTranslatef(12, salto+1, 11.2); Base(1.6, .2, 2.5, 1); glPopMatrix(); glPushMatrix(); glTranslatef(15, salto+1, 11.2); Base(1.6, .2, 2.5, 1); glPopMatrix(); glPushMatrix(); glTranslatef(18, salto+1, 11.2); Base(1.6, .2, 2.5, 1); glPopMatrix(); glPushMatrix(); glTranslatef(21, salto+1, 11.2); Base(1.6, .2, 2.5, 1); glPopMatrix(); glPushMatrix(); glTranslatef(24, salto+1, 11.2); Base(1.6, .2, 2.5, 1); glPopMatrix(); glPushMatrix(); glTranslatef(27, salto+1, 11.2); Base(1.6, .2, 2.5, 1); glPopMatrix(); //------------------------------------------------ //------------------------------------------------ //CRIA플O DA SEGUNDA <NAME> <NAME> glBindTexture(GL_TEXTURE_2D, t[5]); glPushMatrix(); glTranslatef(-12, salto+1, 11.2); Base(1.6, .2, 2.5, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-15, salto+1, 11.2); Base(1.6, .2, 2.5, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-18, salto+1, 11.2); Base(1.6, .2, 2.5, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-21, salto+1, 11.2); Base(1.6, .2, 2.5, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-24, salto+1, 11.2); Base(1.6, .2, 2.5, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-27, salto+1, 11.2); Base(1.6, .2, 2.5, 1); glPopMatrix(); //------------------------------------------ //------------------------------------------ //J<NAME> glBindTexture(GL_TEXTURE_2D, t[5]); glPushMatrix(); glTranslatef(15, salto-2, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(18, salto-2, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(21, salto-2, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(24, salto-2, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(27, salto-2, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); //------------------------------------------ //------------------------------------------ //<NAME> glBindTexture(GL_TEXTURE_2D, t[5]); glPushMatrix(); glTranslatef(-15, salto-2, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-18, salto-2, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-21, salto-2, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-24, salto-2, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-27, salto-2, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); //------------------------------------------ //JANELAS PARTE DE CIMA glBindTexture(GL_TEXTURE_2D, t[5]); glPushMatrix(); glTranslatef(12, salto+9, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(15, salto+9, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(18, salto+9, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(21, salto+9, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(24, salto+9, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(27, salto+9, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); //------------------------------------ // JANELAS SUPERIORES PARTE DE CIMA DAS PORTAS glBindTexture(GL_TEXTURE_2D, t[5]); glPushMatrix(); glTranslatef(-6, salto+4, 12.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); //segundajanelaporta glPushMatrix(); glTranslatef(0, salto+4, 12.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); ///terceirajanelaporta3 glPushMatrix(); glTranslatef(6, salto+4, 12.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); //------------------------------------------------- //<NAME> PARTE CENTRAL glBindTexture(GL_TEXTURE_2D, t[5]); glPushMatrix(); glTranslatef(-12, salto+9, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-15, salto+9, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-18, salto+9, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-21, salto+9, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-24, salto+9, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); glPushMatrix(); glTranslatef(-27, salto+9, 11.2); Base(1.6, .2, 1.6, 1); glPopMatrix(); //--------------------------------------------------------- //--------------------------------------------------------- // PILARES glBindTexture(GL_TEXTURE_2D, t[0]); float tr = -8; for (i = 0; i < 4; i++){ if(i==0){ glPushMatrix(); glTranslatef(tr-0.8, salto, 14); Cilindro(20, 20, altpp, .4); glPopMatrix(); glPushMatrix(); glTranslatef(tr+0.2, salto, 14); Cilindro(20, 20, altpp, .4); glPopMatrix(); } if(i==1){ glPushMatrix(); glTranslatef(tr+2.0, salto, 14); Cilindro(20, 20, altpp, .4); glPopMatrix(); glPushMatrix(); glTranslatef(tr+1.0, salto, 14); Cilindro(20, 20, altpp, .4); glPopMatrix(); } if(i==2){ glPushMatrix(); glTranslatef(tr+6.0, salto, 14); Cilindro(20, 20, altpp, .4); glPopMatrix(); glPushMatrix(); glTranslatef(tr+5.0, salto, 14); Cilindro(20, 20, altpp, .4); glPopMatrix(); } if(i==3){ glPushMatrix(); glTranslatef(tr+8.0, salto, 14); Cilindro(20, 20, altpp, .4); glPopMatrix(); glPushMatrix(); glTranslatef(tr+7.0, salto, 14); Cilindro(20, 20, altpp, .4); glPopMatrix(); } tr += 3; } tr = -10.5; //------------------------------------------------- //TETO ACIMA DOS PILARES glBindTexture(GL_TEXTURE_2D, t[1]); glPushMatrix(); glTranslatef(0, salto+altpp, 13); Base(21, 3.5, 1, 4); glPopMatrix(); //--------------------------------------------------- //PREDIO LATERAL DIREITA //-------------------------------------------- glBindTexture(GL_TEXTURE_2D, t[8]); // Paredes laterais //predio direito glPushMatrix(); glTranslatef(28.5, salto-3, 0.0); Base(.3, 22.5, 15, 10); glPopMatrix(); //------------------------------------------- //Paredes frontal e traseira do Predio direito //parede traseira glPushMatrix(); glTranslatef(19, salto-3, -11); Base(19, 12.1, altpp+8, 10); glPopMatrix(); //parede frontal glPushMatrix(); glTranslatef(19, salto-3, 11.1); Base(19, .3, altpp+8, 10); glPopMatrix(); //-------------------------------------------- //------------------------------------ //lado esquerdo glPushMatrix(); glTranslatef(-19, salto-3, -11); Base(19, 12.1, altpp+8, 10); glPopMatrix(); //parede frontal glPushMatrix(); glTranslatef(-19, salto-3, 11.1); Base(19, .3, altpp+8, 10); glPopMatrix(); glPushMatrix(); glTranslatef(-28.5, salto-3, 0.0); Base(.3, 22.5, 15, 10); glPopMatrix(); //----------------------------------------------------------- //PILAR ESCADA, 1 PILAR ESQUERDO glBindTexture(GL_TEXTURE_2D, t[17]); glPushMatrix(); glTranslatef(-2.3, salto-1, 1.5); Base(.5,.7, 3.2, 10); glPopMatrix(); //---------------------------------- //PAREDE ENTRE OS PILARES 1 E 2 LADO ESQUERDO glPushMatrix(); glRotatef(25, 25, 0, 0); glTranslatef(-2.3, salto+0.1, -2.2); Base(.3,5.2, 2.2, 10); glPopMatrix(); //-------------------------------------------- //PILAR DIREITO, 1 PILAR glPushMatrix(); glTranslatef(2.3, salto-1, 1.5); Base(.5,.7, 3.2, 10); glPopMatrix(); //------------------------------------------ //PAREDE ENTRE OS PILARES 1 E 2 DIREITO glPushMatrix(); glRotatef(25, 25, 0, 0); glTranslatef(2.3, salto+0.1, -2.2); Base(.3,5.2, 2.2, 10); glPopMatrix(); //----------------------------------------------------------- //PILAR ESCADA, 2 PILAR ESQUERDO glPushMatrix(); glTranslatef(-2.3, salto+1, -3.5); Base(.5,.5, 3.5, 10); glPopMatrix(); //-------------------------------------------- //PILAR DIREITO, 2 PILAR glPushMatrix(); glTranslatef(2.3, salto+1, -3.5); Base(.5,.5, 3.5, 10); glPopMatrix(); //----------------------------------------------------------- //PILAR ESCADA, 3 PILAR ESQUERDO glPushMatrix(); glTranslatef(-2.3, salto+4, -8.5); Base(.5,1, 3, 10); glPopMatrix(); //---------------------------------- //PAREDE ENTRE OS PILARES 2 E 3 LADO ESQUERDO glPushMatrix(); glRotatef(30, 30, 0, 0); glTranslatef(-2.3, salto-0.5, -8); Base(.3,5.3, 2.2, 10); glPopMatrix(); //-------------------------------------------- //PILAR DIREITO, 3 PILAR glPushMatrix(); glTranslatef(2.3, salto+4, -8.5); Base(.5,1, 3, 10); glPopMatrix(); //------------------------------------------ //PAREDE ENTRE OS PILARES 2 E 3 DIREITO glPushMatrix(); glRotatef(30, 30, 0, 0); glTranslatef(2.3, salto-0.5, -8); Base(.3,5.3, 2.2, 10); glPopMatrix(); //----------------------------------------------------------- //PILAR ESCADA, 4 PILAR ESQUERDO glPushMatrix(); glTranslatef(-2.3, salto+6, -15); Base(.5,.7, 3, 10); glPopMatrix(); //PAREDE ENTRE OS PILARES 3 E 4 LADO ESQUERDO glPushMatrix(); glRotatef(20, 20, 0, 0); glTranslatef(-2.3, salto+1, -14); Base(.3,6.2, 2.2, 10); glPopMatrix(); //-------------------------------------------- //PILAR DIREITO, 4 PILAR glPushMatrix(); glTranslatef(2.3, salto+6, -15); Base(.5,.7, 3, 10); glPopMatrix(); //------------------------------------------ //PAREDE ENTRE OS PILARES 3 E 4 DIREITO glPushMatrix(); glRotatef(20, 20, 0, 0); glTranslatef(2.3, salto+1, -14); Base(.3,6.2, 2.2, 10); glPopMatrix(); //-------------------------------------------- //-------------------------------------------------------- // ESCADA INTERIOR glBindTexture(GL_TEXTURE_2D, t[12]); for (i = 0; i < 14; i++){ glTranslatef(0, 0.5, -1); glPushMatrix(); Base(4, 6, 0.5, 1); glPopMatrix(); niv += salto; }; glBindTexture(GL_TEXTURE_2D, t[14]); // tetoInterior(); //-------------------------------------------------------------- //teto todo // Base do teto lado direito glBindTexture(GL_TEXTURE_2D, t[1]); glPushMatrix(); glTranslatef(0, salto+4.9,12.45); Base(57, 28, .3, 4); glPopMatrix(); //termina //QUADRO LADO ESQUERDO glBindTexture(GL_TEXTURE_2D, t[10]); glPushMatrix(); glTranslatef(7.8, salto-4.5, 23); Quadro(2, 2, t, m, 0, 1); glPopMatrix(); glBindTexture(GL_TEXTURE_2D, t[13]); glPushMatrix(); glTranslatef(7.8, salto-4.5, 20); Quadro(2, 2, t, m, 0, 1); glPopMatrix(); //QUADRO LADO DIREITO glBindTexture(GL_TEXTURE_2D, t[15]); glPushMatrix(); glTranslatef(-7.7, salto-4.5, 23); Quadro(2, 2, t, m, 0, -1); glPopMatrix(); glBindTexture(GL_TEXTURE_2D, t[16]); glPushMatrix(); glTranslatef(-7.7, salto-4.5, 20); Quadro(2, 2, t, m, 0, -1); glPopMatrix(); //----------------------------------- glBindTexture(GL_TEXTURE_2D, t[18]); drawCube(1); drawCube2(1); //BANCADAS ABAIXO DOS QUADROS glBindTexture(GL_TEXTURE_2D, t[14]); glPushMatrix(); glTranslatef(6.4,-5,23); Bancada1(1); glPopMatrix(); glPushMatrix(); glTranslatef(6.4,-5,20); Bancada1(1); glPopMatrix(); glPushMatrix(); glTranslatef(-6.4,-5,23); Bancada2(1); glPopMatrix(); glPushMatrix(); glTranslatef(-6.4,-5,20); Bancada2(1); glPopMatrix(); //------------------------------------------------------- // janela taseira central glBindTexture(GL_TEXTURE_2D, t[19]); glPushMatrix(); glTranslatef(0, salto-10, -1.1); Base(4, .2, 15, 7); glPopMatrix(); //Janela traseira Direita glPushMatrix(); glTranslatef(5, salto-9, -1.1); Base(4, .2, 11, 7); glPopMatrix(); // Janela traseira Esquerda glPushMatrix(); glTranslatef(-5, salto-9, -1.1); Base(4, .2, 11, 7); glPopMatrix(); } void Cenario (GLuint* t, float x, float z, float rot) { float p = 2*sin((3.14*rot)/180.0); glBindTexture(GL_TEXTURE_2D, t[3]); glPushMatrix(); glTranslatef(0, -0.1, 0); Base(300, 300, 0.1, 15); glPopMatrix(); glPushMatrix(); glBindTexture(GL_TEXTURE_2D, t[6]); glTranslatef(0+p, 30, 0); Base(300, 300, 0.1, 1); glPopMatrix(); } void Quadro (float lar, float alt, GLuint* t, GLuint* m, int n, int inv) { glPushMatrix(); glRotatef((float) inv * 90, 0, 1, 0); Base(lar+0.2, .1, alt+0.2, 1); glBindTexture(GL_TEXTURE_2D, m[n]); glTranslatef(0, .1, .1); TQuadrado(lar, alt, 0); glPopMatrix(); } <file_sep>/La casa de Papel/LaCasa.h #ifndef LACASA_H_INCLUDED #define LACASA_H_INCLUDED #include <GL/glut.h> #include <GL/glu.h> void Base (float largura, float comprimento, float altura, int fatorr); void LaCasa (GLuint* t, GLuint* m, float rot); void Cenario (GLuint* t, float x, float z, float rot); void Quadro (float lar, float alt, GLuint* t, GLuint* m, int n, int inv); #endif // LACASA_H_INCLUDED <file_sep>/README.md # Modelagem Casa da Moeda ### 1. Proposta para projeto; ◆ Inspiração para a cena. ● Com o grande sucesso da série la casa de papel foi desenvolvido um projeto que simula onde ocorreu o assalto da primeira temporada da série, a Casa da Moeda da Espanha. ### 2. Cenas apresentadas; ◆ Apresentação das cenas que foram modeladas. ● As cenas foram modeladas pensando e totalmente espelhada na Casa da Moeda da Espanha, que é mostrada na série. ### 3. Execução da cena; ◆ Apresentação da cena em tempo real. ● Foi feito uso de câmera virtual, o observador pode se mover por todos os lugares da cena. ### 4. Principais Funções. ◆ La Casa; ● Inicialização e montagem da cena: Essa função é a responsável por executar o projeto, todas as funções de chamada no projeto, para desenhar, são feitos nela. ◆ Base; ● É a função que tem com princípio desenhar os elementos quadrados: Função que desenha quase todos elementos da casa, foi feito uso dessa função mais genérica para que seja possível criar qualquer tipo de quadro com ela, o que busca minimizar a repetição de código. ◆ Cenário; ● Modelagem do asfalto que a Casa da Moeda da Espanha fica sobre. ◆ Movimentações do Mouse; ● Responsável por verificar a posição e movimenta a câmera virtual: Funções de click foram implementadas para o mouse em todas as direções, então para girar e visualizar é só clicar e arrastar. ◆ Movimentações do Observador; O que outras pessoas estão dizendo ● Funções de movimentação do observador na cena corresponde às teclas: Q: movimentação para o lado esquerdo; W:movimentação para frente; E:movimentação para o lado direito; A:Giro para o lado esquerdo; S: Movimentação para trás; D: Giro para o lado direito; R:Para subir na cena; F: Para descer na cena; # Como reproduzir Existem duas maneiras de reproduzir o arquivo, a primeira e mais simples, consiste apenas em abrir o arquivo executável “La casa de Papel.exe”. Daí a cena já será exibida e o usuário já pode interagir com o cenário. A segunda forma se torna um pouco mais complexa pelo fato de que o usuário precisa configurar um ambiente para executar o arquivo direto do código fonte. Neste link é possível ver um tutorial ensinando a preparar o ambiente “https://www.youtube.com/watch?v=YlvBcafLfhs”. Depois do ambiente ser preparado e está totalmente preparado basta abrir o projeto e executar. Obs.: Como o projeto faz o uso de texturas, lembre de sempre que mudar o diretorio do projeto o caminho para as imagens também precisam ser mudadas, caso opte por executar o rojeto direto no dódigo fonte.
9409196ee9abfe679c29ee66e4a1e10af60d2f3b
[ "Markdown", "C", "C++" ]
6
C
PedroHas98/ProjetoMS-La-Casa-de-Papel-
8716b7b5fecc927bbe68f442a780c0616cea77ff
1237f06d37eff95d81a49c587bfbfaa05f2da02e
refs/heads/master
<repo_name>mckinney99/deli-counter-v-000<file_sep>/deli_counter.rb # Write your code here. def line(katz_deli) array = [] if katz_deli.length < 1 puts "The line is currently empty." else katz_deli.each_with_index do |line, index| array << "#{index + 1}. #{line}" end puts "The line is currently: #{array.join(" ")}" end end def take_a_number(katz_deli, name) katz_deli << "#{name}" puts "Welcome, #{name}. You are number #{katz_deli.size} in line." end def now_serving(katz_deli) if katz_deli.length < 1 puts "There is nobody waiting to be served!" else puts "Currently serving #{katz_deli[0]}." end katz_deli.shift end
53458ed505c101c165e5a86c358919eff872ff85
[ "Ruby" ]
1
Ruby
mckinney99/deli-counter-v-000
e74a549b362f5001a982bd6462d02df8bb315f31
500511a4000652c201f7c47a32c9f34cc7935a9d
refs/heads/master
<repo_name>kittymama97/Milestone3-256<file_sep>/app/Models/JobModel.php <?php namespace App\Models; class JobModel { private $job_id; private $company_name; private $company_city; private $company_state; private $company_zip_code; private $job_title; private $job_desciption; private $date_posted; public function __construct($job_id, $company_name, $company_city, $company_state, $company_zip_code, $job_title, $job_description, $date_posted) { $this->job_id = $job_id; $this->company_name = $company_name; $this->company_city = $company_city; $this->company_state = $company_state; $this->company_zip_code = $company_zip_code; $this->job_title = $job_title; $this->job_desciption = $job_description; $this->date_posted = $date_posted; } /** * * @return mixed */ public function getJob_id() { return $this->job_id; } /** * * @param mixed $job_id */ public function setJob_id($job_id) { $this->job_id = $job_id; } /** * * @return mixed */ public function getCompany_name() { return $this->company_name; } /** * * @param mixed $company_name */ public function setCompany_name($company_name) { $this->company_name = $company_name; } /** * * @return mixed */ public function getCompany_city() { return $this->company_city; } /** * * @param mixed $company_city */ public function setCompany_city($company_city) { $this->company_city = $company_city; } /** * * @return mixed */ public function getCompany_state() { return $this->company_state; } /** * * @param mixed $company_state */ public function setCompany_state($company_state) { $this->company_state = $company_state; } /** * * @return mixed */ public function getCompany_zip_code() { return $this->company_zip_code; } /** * * @param mixed $company_zip_code */ public function setCompany_zip_code($company_zip_code) { $this->company_zip_code = $company_zip_code; } /** * * @return mixed */ public function getJob_title() { return $this->job_title; } /** * * @param mixed $job_title */ public function setJob_title($job_title) { $this->job_title = $job_title; } /** * * @return mixed */ public function getJob_desciption() { return $this->job_desciption; } /** * * @param mixed $job_desciption */ public function setJob_desciption($job_desciption) { $this->job_desciption = $job_desciption; } /** * * @return mixed */ public function getDate_posted() { return $this->date_posted; } /** * * @param mixed $date_posted */ public function setDate_posted($date_posted) { $this->date_posted = $date_posted; } }<file_sep>/app/Services/Utility/securePage.php <?php if (isset($_SESSION['principle']) == false || $_SESSION['principle'] == NULL || $_SESSION['principle'] == false) { header("Location: login2.blade.php"); }<file_sep>/app/Services/Data/JobDataService.php <?php namespace App\Services\Data; use App\Models\JobModel; use Illuminate\Support\Facades\Log; use PDO; use PDOException; use App\Services\Utility\DatabaseException; class JobDataService { private $conn = null; // best practice: do not create a database connections in a dao // so you can support atomic database transactions public function __construct($conn) { $this->conn = $conn; } public function createJobPost(JobModel $jobModel, $conn) { Log::info("Entering ProfileDataService.createJobPost()"); try { // select variables and see if the row exists $company_name = $jobModel->getCompany_name(); $company_city = $jobModel->getCompany_city(); $company_state = $jobModel->getCompany_state(); $company_zip = $jobModel->getCompany_zip_code(); $job_title = $jobModel->getJob_title(); $job_description = $jobModel->getJob_desciption(); $date_posted = $jobModel->getDate_posted(); // prepared statements is created $stmt = $this->conn->prepare("INSERT INTO `JOB` (`JOB_ID`, `COMPANY_NAME`, `COMPANY_CITY`, `COMPANY_STATE`, `COMPANY_ZIP_CODE`, `JOB_TITLE`, `JOB_DESCRIPTION`, `DATE_POSTED`) VALUES (NULL, :company_name, :company_city, :company_state, :company_zip_code, :job_title, :job_description, :date_posted);"); // binds parameters $stmt->bindParam(':company_name', $company_name); $stmt->bindParam(':company_city', $company_city); $stmt->bindParam(':company_state', $company_state); $stmt->bindParam(':company_zip_code', $company_zip); $stmt->bindParam(':job_title', $job_title); $stmt->bindParam(':job_description', $job_description); $stmt->bindParam(':date_posted', $date_posted); /* * see if skills existed and return true if found * else return false if not found */ if ($stmt->execute()) { Log::info("Exit JobDataService.createJobPost() with true"); return true; } else { Log::info("Exit JobDataService.createJobPost() with false"); return false; } } catch (PDOException $e) { // best practice: catch all exceptions (do not swallow exceptions), // log the exception, do not throw technology specific exceptions, // and throw a custom exception Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function updateJobPost(JobModel $jobModel, $conn) { Log::info("Entering ProfileDataService.updateJobPost()"); try { // select variables and see if the row exists $job_id = $jobModel->getJob_id(); $company_name = $jobModel->getCompany_name(); $company_city = $jobModel->getCompany_city(); $company_state = $jobModel->getCompany_state(); $company_zip = $jobModel->getCompany_zip_code(); $job_title = $jobModel->getJob_title(); $job_description = $jobModel->getJob_desciption(); $date_posted = $jobModel->getDate_posted(); // prepared statements is created $stmt = $this->conn->prepare("UPDATE `JOB` SET `COMPANY_NAME` = :company_name, `COMPANY_CITY` = :company_city, `COMPANY_STATE` = :company_state, `COMPANY_ZIP_CODE` = :company_zip_code, `JOB_TITLE` = :job_title, `JOB_DESCRIPTION` = :job_description, `DATE_POSTED` = :date_posted WHERE `JOB_ID` = :job_id"); // binds parameters $stmt->bindParam(':job_id', $job_id); $stmt->bindParam(':company_name', $company_name); $stmt->bindParam(':company_city', $company_city); $stmt->bindParam(':company_state', $company_state); $stmt->bindParam(':company_zip_code', $company_zip); $stmt->bindParam(':job_title', $job_title); $stmt->bindParam(':job_desciption', $job_description); $stmt->bindParam(':date_posted', $date_posted); /* * see if jobs existed and return true if found * else return false if not found */ if ($stmt->execute()) { Log::info("Exit JobDataService.updateJobPost() with true"); return true; } else { Log::info("Exit JobDataService.updateJobPost() with false"); return false; } } catch (PDOException $e) { // best practice: catch all exceptions (do not swallow exceptions), // log the exception, do not throw technology specific exceptions, // and throw a custom exception Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function deleteJobPost($id) { Log::info("Entering UserDataService.deleteUser()"); try { // prepared statement is created $stmt = $this->conn->prepare('DELETE FROM JOB WHERE JOB_ID = :id'); // bind parameter $stmt->bindParam(':id', $id); // executes statement $delete = $stmt->execute(); // returns true or false if skill has been deleted from database if ($delete) { Log::info("Exiting JobDataService.deleteJobPost() with returning true"); return true; } else { Log::info("Exiting JobDataService.deleteJobPost() with returning false"); return false; } } catch (\PDOException $e) { Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function showAllJobPosts() { Log::info("Entering JobDataService.showAllJobPosts()"); try { // select contact and see if the row exists $stmt = $this->conn->prepare('SELECT * FROM JOB'); $stmt->execute(); if ($stmt->rowCount() > 0) { // contact array is created $jobArray = array(); // fetches result from prepared statement and returns as an array while ($job = $stmt->fetch(PDO::FETCH_ASSOC)) { // inserts variables into end of array array_push($jobArray, $job); } Log::info("Exit JobDataService.showAllJobPosts() with true"); // return contact array return $jobArray; } } catch (PDOException $e) { // best practice: catch all exceptions (do not swallow exceptions), // log the exception, do not throw technology specific exceptions, // and throw a custom exception Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } } <file_sep>/app/Services/Business/UserBusinessService.php <?php // <NAME> // CST 256 // February 3, 2019 // This is my own work /* Handles user business logic and connections to database */ namespace App\Services\Business; use PDO; use App\Models\UserModel; use Illuminate\Support\Facades\Log; use App\Services\Data\UserDataService; class UserBusinessService { public function createUser(UserModel $user) { Log::info("Entering UserBusinessService.createUser()"); // best practice: externalize your app configuration // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("database.connections.mysql.password"); // best practice: do not create database connections in a dao // create connection $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find the password in user $service = new UserDataService($conn); $flag = $service->createUser($user); // return the finder results Log::info("Exit UserBusinessService.createUser() with " . $flag); return $flag; } public function updateUser(UserModel $userModel) { Log::info("Entering UserBusinessService.updateUser()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("database.connections.mysql.password"); // best practice: do not create database connections in a dao // create connection $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find users $service = new UserDataService($conn); // calls the findAllUsers command $flag = $service->updateUser($userModel); // return the finder results return $flag; Log::info("Exit UserBusinessService.displayUsers() with " . $flag); } public function displayUsers() { Log::info("Entering UserBusinessService.displayUsers()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("database.connections.mysql.password"); // best practice: do not create database connections in a dao // create connection $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find users $service = new UserDataService($conn); // calls the findAllUsers command $flag = $service->findAllUsers(); // return the finder results return $flag; Log::info("Exit UserBusinessService.displayUsers() with " . $flag); } }<file_sep>/app/Http/Controllers/ProfileController.php <?php // Milestone 1 // Login Module // <NAME> // January 20, 2019 // This is my own work /* Profile controller processes the submitted data for user profile */ namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Exception; use App\Models\SkillsModel; use App\Services\Business\ProfileBusinessService; use App\Models\EducationModel; use App\Models\JobHistoryModel; use App\Models\ContactModel; use App\Models\UserModel; use App\Services\Business\UserBusinessService; class ProfileController extends Controller { public function createSkills(Request $request) { try { // 1. process form data // get posted form data $skills = $request->input('user_skills'); $user_user_id = $request->input('user_user_id'); // assigns the data from the variables to one array named $data $data = [ 'user_skills' => $skills, 'user_user_id' => $user_user_id ]; // 2. create object model // save posted form data in user object model $userSkills = new SkillsModel(0, $skills, $user_user_id); // 3. execute business service // call security business service $service = new ProfileBusinessService(); $status = $service->createSkills($userSkills); // 4. process results from business service (navigation) // render a failed or success response view and pass the user model to it if ($status) { $data = [ 'model' => $userSkills ]; return view('createSkillsSuccess')->with($data); } else { return view('createSkillsFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function updateSkills(Request $request) { try { // 1. process form data // get posted form data $skills_id = $request->input('skills_id'); $skills = $request->input('user_skills'); // assigns the data from the variables to one array named $data $data = [ 'skills_id' => $skills_id, 'user_skills' => $skills ]; // 2. create object model // save posted form data in user object model $userSkillsUpdate = new SkillsModel(0, $skills); // 3. execute business service // call security business service $service = new ProfileBusinessService(); $status = $service->updateSkills($userSkillsUpdate); // 4. process results from business service (navigation) // render a failed or success response view and pass the user model to it if ($status) { $data = [ 'model' => $userSkillsUpdate ]; return view('updateSkillsSuccess')->with($data); } else { return view('updateSkillsFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function deleteSkills() { try { // GET method for user id $id = $_GET['SKILLS_ID']; // call user business service $service = new ProfileBusinessService(); $delete = $service->deleteSkills($id); // render a success or fail view if ($delete) { return view('deleteSkillsSuccess'); } else { return view('deleteSkillsFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function showSkills() { try { $user_user_id = $_GET['USER_USER_ID']; // call profile business service $service = new ProfileBusinessService(); $skills = $service->showSkills($user_user_id); // render a response view if ($skills) { return view('displaySkills')->with($skills); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function createEducation(Request $request) { try { // 1. process form data // get posted form data $degree = $request->input('degree'); $school_name = $request->input('school_name'); $school_city = $request->input('school_city'); $school_state = $request->input('school_state'); $school_zip_code = $request->input('school_zip_code'); $graduation_year = $request->input('graduation_year'); // assigns the data from the variables to one array named $data $data = [ 'degree' => $degree, 'school_name' => $school_name, 'school_city' => $school_city, 'school_state' => $school_state, 'school_zip_code' => $school_zip_code, 'graduation_year' => $graduation_year ]; // 2. create object model // save posted form data in user object model $education = new EducationModel(0, $degree, $school_name, $school_city, $school_state, $school_zip_code, $graduation_year); // 3. execute business service // call security business service $service = new ProfileBusinessService(); $status = $service->createEducation($education); // 4. process results from business service (navigation) // render a failed or success response view and pass the user model to it if ($status) { $data = [ 'model' => $education ]; return view('createEducationSuccess')->with($data); } else { return view('createEducationFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function updateEducation(Request $request) { try { // 1. process form data // get posted form data $degree = $request->input('degree'); $school_name = $request->input('school_name'); $school_city = $request->input('school_city'); $school_state = $request->input('school_state'); $school_zip_code = $request->input('school_zip_code'); $graduation_year = $request->input('graduation_year'); // assigns the data from the variables to one array named $data $data = [ 'degree' => $degree, 'school_name' => $school_name, 'school_city' => $school_city, 'school_state' => $school_state, 'school_zip_code' => $school_zip_code, 'graduation_year' => $graduation_year ]; // 2. create object model // save posted form data in user object model $educationUpdate = new EducationModel(0, $degree, $school_name, $school_state, $school_city, $school_zip_code, $graduation_year); // 3. execute business service // call security business service $service = new ProfileBusinessService(); $status = $service->updateEducation($educationUpdate); // 4. process results from business service (navigation) // render a failed or success response view and pass the user model to it if ($status) { $data = [ 'model' => $educationUpdate ]; return view('updateEducationSuccess')->with($data); } else { return view('updateEducationFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function deleteEducation() { try { // GET method for user id $id = $_GET['EDUCATION_ID']; // call user business service $service = new ProfileBusinessService(); $delete = $service->deleteEducation($id); // render a success or fail view if ($delete) { return view('deleteEducationSuccess'); } else { return view('deleteEducationFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function showEducation() { try { // call profile business service $service = new ProfileBusinessService(); $profile = $service->showEducation(); // render a response view if ($profile) { return view('displayProfile')->with($profile); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function createJobHistory(Request $request) { try { // 1. process form data // get posted form data $current_job = $request->input('current_job'); $previous_job = $request->input('previous_job'); $current_employment_date = $request->input('current_employment_date'); $previous_employment_date = $request->input('previous_employment_date'); $current_employment_location = $request->input('current_employment_location'); // // assigns the data from the variables to one array named $data $data = [ 'current_job' => $current_job, 'previous_job' => $previous_job, 'current_employment_date' => $current_employment_date, 'previous_employment_date' => $previous_employment_date, 'current_employment_location' => $previous_job ]; // 2. create object model // save posted form data in user object model $jobHistory = new JobHistoryModel(0, $current_job, $previous_job, $current_employment_date, $previous_employment_date, $current_employment_location); // 3. execute business service // call security business service $service = new ProfileBusinessService(); $status = $service->createJobHistory($jobHistory); // 4. process results from business service (navigation) // render a failed or success response view and pass the user model to it if ($status) { $data = [ 'model' => $jobHistory ]; return view('createJobHistorySuccess')->with($data); } else { return view('createJobHistoryFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function updateJobHistory(Request $request) { try { // 1. process form data // get posted form data $current_job = $request->input('current_job'); $previous_job = $request->input('previous_job'); $current_employment_date = $request->input('current_employment_date'); $previous_employment_date = $request->input('previous_employment_date'); $current_employment_location = $request->input('current_employment_location'); // assigns the data from the variables to one array named $data $data = [ 'current_job' => $current_job, 'previous_job' => $previous_job, 'current_employment_date' => $current_employment_date, 'previous_employment_date' => $previous_employment_date, 'current_employment_location' => $current_employment_location ]; // 2. create object model // save posted form data in user object model $jobHistoryUpdate = new EducationModel(0, $current_job, $previous_job, $current_employment_date, $previous_employment_date, $current_employment_location); // 3. execute business service // call security business service $service = new ProfileBusinessService(); $status = $service->updateJobHistory($jobHistoryUpdate); // 4. process results from business service (navigation) // render a failed or success response view and pass the user model to it if ($status) { $data = [ 'model' => $jobHistoryUpdate ]; return view('updateJobHistorySucess')->with($data); } else { return view('updateJobHistoryFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function deleteJobHistory() { try { // GET method for user id $id = $_GET['JOB_HISTORY_ID']; // call user business service $service = new ProfileBusinessService(); $delete = $service->deleteJobHistory($id); // render a success or fail view if ($delete) { return view('deleteJobHistorySuccess'); } else { return view('deleteJobHistoryFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function showJobHistory() { try { // call profile business service $service = new ProfileBusinessService(); $profile = $service->showJobHistory(); // render a response view if ($profile) { return view('displayProfile')->with($profile); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function createContactInformation(Request $request) { try { // 1. process form data // get posted form data $business_email = $request->input('business_email'); $phone_number = $request->input('phone_number'); $street_address = $request->input('street_address'); $city = $request->input('city'); $state = $request->input('state'); $zip_code = $request->input('zip_code'); $about_me = $request->input('about_me'); // assigns the data from the variables to one array named $data $data = [ 'business_email' => $business_email, 'phone_number' => $phone_number, 'street_address' => $street_address, 'city' => $city, 'state' => $state, 'zip_code' => $zip_code, 'about_me' => $about_me ]; // 2. create object model // save posted form data in user object model $contact = new ContactModel(0, $business_email, $phone_number, $street_address, $state, $city, $zip_code, $about_me); // 3. execute business service // call security business service $service = new ProfileBusinessService(); $status = $service->createContactInfo($contact); // 4. process results from business service (navigation) // render a failed or success response view and pass the user model to it if ($status) { $data = [ 'model' => $contact ]; return view('createContactInformationSuccess')->with($data); } else { return view('createContactInformationFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function updateContactInformation(Request $request) { try { // 1. process form data // get posted form data $business_email = $request->input('business_email'); $phone_number = $request->input('phone_number'); $street_address = $request->input('street_address'); $city = $request->input('city'); $state = $request->input('state'); $zip_code = $request->input('zip_code'); $about_me = $request->input('about_me'); $data = [ 'business_email' => $business_email, 'phone_number' => $phone_number, 'street_address' => $street_address, 'city' => $city, 'state' => $state, 'zip_code' => $zip_code, 'about_me' => $about_me ]; // 2. create object model // save posted form data in user object model $contact = new ContactModel(0, $business_email, $phone_number, $street_address, $city, $state, $zip_code, $about_me); // 3. execute business service // call security business service $service = new ProfileBusinessService(); $status = $service->updateContactInfo($contact); // 4. process results from business service (navigation) // render a failed or success response view and pass the user model to it if ($status) { $data = [ 'model' => $contact ]; return view('updateContactInformationSuccess')->with($data); } else { return view('updateContactInformationFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function deleteContactInformation() { try { // GET method for user id $id = $_GET['CONTACT_ID']; // call user business service $service = new ProfileBusinessService(); $delete = $service->deleteSkills($id); // render a success or fail view if ($delete) { return view('deleteContactInformationSuccess'); } else { return view('deleteContactInformationFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function showContactInformation() { try { // call profile business service $service = new ProfileBusinessService(); $profile = $service->showContactInfo(); // render a response view if ($profile) { return view('displayProfile')->with($profile); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function updateUser(Request $request) { try { // 1. process form data // get posted form data $firstname = $request->input('firstname'); $lastname = $request->input('lastname'); $email = $request->input('email'); $username = $request->input('username'); $password = $request->input('password'); // 2. create object model // save posted form data in user object model $user = new UserModel(0, $firstname, $lastname, $email, $username, $password); // 3. execute business service // call security business service $service = new UserBusinessService(); $status = $service->updateUser($user); // 4. process results from business service (navigation) // render a failed or success response view and pass the user model to it if ($status) { $data = [ 'model' => $user ]; return view('updateRegistrationSuccess')->with($data); } else { return view('updateRegistrationFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } }<file_sep>/app/Http/Controllers/AdminController.php <?php // Milestone 1 // Login Module // <NAME> // February 6, 2019 // This is my own work /* Admin controller handles user admin methods */ namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Exception; use App\Services\Business\UserBusinessService; use App\Services\Data\UserDataService; use App\Models\JobModel; use App\Services\Business\JobBusinessService; use App\Services\Data\JobDataService; class AdminController extends Controller { public function showCreatePostForm() { return view('createJobPost'); } public function showUsers() { try { // call user business service $service = new UserBusinessService(); $users = $service->displayUsers(); // render a response view if ($users) { return view('displayUsers')->with($users); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function deleteUser() { try { // GET method for user id $id = $_GET['USER_ID']; // call user business service $service = new UserBusinessService(); $delete = $service->deleteUser($id); // render a success or fail view if ($delete) { return view('deleteUserSuccess'); } else { return view('deleteUserFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function suspendUser() { try { // GET method for user id $id = $_GET['ID']; // call user business service $service = new UserBusinessService(); $suspend = $service->suspendUser($id); // renders a success or fail view if ($suspend) { return view('suspendUserSuccess'); } else { return view('suspendUserFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function unsuspendUser() { try { // GET method for user id $id = $_GET['ID']; // calls user business service $service = new UserBusinessService(); $unsuspend = $service->unsuspendUser($id); // renders a success or fail view if ($unsuspend) { return view('unsuspendUserSuccess'); } else { return view('unsuspendUserFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function createJobPost(Request $request) { try { // 1. process form data // get posted form data $company_name = $request->input('company_name'); $company_city = $request->input('company_city'); $company_state = $request->input('company_state'); $company_zip = $request->input('company_zip'); $job_title = $request->input('job_title'); $job_description = $request->input('job_description'); $date_posted = $request->input('date_posted'); // assigns the data from the variables to one array named $data $data = [ 'company_name' => $company_name, 'company_city' => $company_city, 'company_state' => $company_state, 'company_zip' => $company_zip, 'job_title' => $job_title, 'job_description' => $job_description, 'date_posted' => $date_posted ]; // 2. create object model // save posted form data in user object model $jobs = new JobModel(0, $company_name, $company_city, $company_state, $company_zip, $job_title, $job_description, $date_posted); // 3. execute business service // call security business service $service = new JobBusinessService(); $status = $service->createJobPost($jobs); // 4. process results from business service (navigation) // render a failed or success response view and pass the user model to it if ($status) { $data = [ 'model' => $jobs ]; return view('createJobPostSuccess')->with($data); } else { return view('createJobPostFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function updateJobPost(Request $request) { try { // 1. process form data // get posted form data $company_name = $request->input('company_name'); $company_city = $request->input('company_city'); $company_state = $request->input('company_state'); $company_zip = $request->input('company_zip'); $job_title = $request->input('job_title'); $job_description = $request->input('job_description'); $date_posted = $request->input('date_posted'); // assigns the data from the variables to one array named $data $data = [ 'company_name' => $company_name, 'company_city' => $company_city, 'company_state' => $company_state, 'company_zip' => $company_zip, 'job_title' => $job_title, 'job_description' => $job_description, 'date_posted' => $date_posted ]; // 2. create object model // save posted form data in user object model $jobs = new JobModel(- 1, $company_name, $company_city, $company_state, $company_zip, $job_title, $job_description, $date_posted); // 3. execute business service // call security business service $service = new JobBusinessService(); $status = $service->updateJobPost($jobs); // 4. process results from business service (navigation) // render a failed or success response view and pass the user model to it if ($status) { $data = [ 'model' => $jobs ]; return view('updateJobPostSuccess')->with($data); } else { return view('updateJobPostFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function deleteJobPost() { try { // GET method for user id $id = $_GET['JOB_ID']; // call user business service $service = new JobDataService($id); $delete = $service->deleteJobPost($id); // render a success or fail view if ($delete) { return view('deleteJobPostSuccess'); } else { return view('deleteJobPostFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } public function showAllJobPosts() { try { // call user business service $service = new JobBusinessService(); $jobs = $service->showJobPosts(); // render a response view if ($jobs) { return view('displayJobPostsAdmin')->with($jobs); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } }<file_sep>/app/Services/Data/ProfileDataService.php <?php namespace App\Services\Data; use PDO; use PDOException; use Illuminate\Support\Facades\Log; use App\Models\ContactModel; use App\Models\EducationModel; use App\Models\JobHistoryModel; use App\Models\SkillsModel; use App\Services\Utility\DatabaseException; class ProfileDataService { private $conn = null; public function __construct($conn) { $this->conn = $conn; } public function createSkills(SkillsModel $skillsModel, $conn) { Log::info("Entering ProfileDataService.createSkills()"); try { // select variables and see if the row exists $skills = $skillsModel->getUser_skills(); $user_user_id = $skillsModel->getUser_user_id(); // prepared statements is created $stmt = $this->conn->prepare("INSERT INTO SKILLS (SKILLS_ID, USER_SKILLS, USER_USER_ID) VALUES (NULL, :user_skills, :user_user_id)"); // binds parameters $stmt->bindParam(':user_skills', $skills); $stmt->bindParam('user_user_id', $user_user_id); /* * see if skills existed and return true if found * else return false if not found */ if ($stmt->execute()) { Log::info("Exit ProfileDataService.createSkills() with true"); return true; } else { Log::info("Exit ProfileDataService.createSKills() with false"); return false; } } catch (PDOException $e) { // best practice: catch all exceptions (do not swallow exceptions), // log the exception, do not throw technology specific exceptions, // and throw a custom exception Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function updateSkills(SkillsModel $skillsModel, $id) { Log::info("Entering ProfileDataService.updateSkills()"); try { // select variables and see if the row exists $skills_id = $skillsModel->getSkills_id(); $skills = $skillsModel->getUser_skill(); // prepared statements is created $stmt = $this->conn->prepare("UPDATE SKILLS SET USER_SKILLS = :user_skills WHERE SKILLS_ID = :skills_id;"); // binds parameters $stmt->bindParam(':user_skills', $skills); $stmt->bindParam(':skills_id', $skills_id); /* * see if skills existed and return true if found * else return false if not found */ if ($stmt->execute()) { Log::info("Exit ProfileDataService.updateSkills() with true"); return true; } else { Log::info("Exit ProfileDataService.updateSkills() with false"); return false; } } catch (PDOException $e) { // best practice: catch all exceptions (do not swallow exceptions), // log the exception, do not throw technology specific exceptions, // and throw a custom exception Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function deleteSkills($id) { Log::info("Entering ProfileDataService.deleteSkills()"); try { // prepared statement is created $stmt = $this->conn->prepare('DELETE FROM SKILLS WHERE SKILLS_ID = :skills_id'); // bind parameter $stmt->bindParam(':skills_id', $id); // executes statement $delete = $stmt->execute(); // returns true or false if skill has been deleted from database if ($delete) { Log::info("Exiting ProfileDataService.deleteSkills() with returning true"); return true; } else { Log::info("Exiting ProfileDataService.deleteSkills() with returning false"); return false; } } catch (\PDOException $e) { Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function findAllSkills($user_user_id) { Log::info("Entering ProfileDataService.findAllSkills()"); try { // select skills and see if the row exists $stmt = $this->conn->prepare('SELECT * FROM SKILLS WHERE USER_USER_ID = :user_user_id'); $stmt->bindParam(':user_user_id', $user_user_id); $stmt->execute(); if ($stmt->rowCount() > 0) { // skills array is created $skillsArray = array(); // fetches result from prepared statement and returns as an array while ($skills = $stmt->fetch(PDO::FETCH_ASSOC)) { // inserts variables into end of array array_push($skillsArray, $skills); } Log::info("Exit ProfileDataService.findAllSkills() with true"); // return skills array return $skillsArray; } } catch (PDOException $e) { // best practice: catch all exceptions (do not swallow exceptions), // log the exception, do not throw technology specific exceptions, // and throw a custom exception Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function createEducation(EducationModel $educationModel, $conn) { Log::info("Entering ProfileDataService.createEducation()"); try { // select variables and see if the row exists $degree = $educationModel->getDegree(); $school_name = $educationModel->getSchool_name(); $school_city = $educationModel->getSchool_city(); $school_state = $educationModel->getSchool_state(); $school_zip_code = $educationModel->getSchool_zip_code(); $graduation_year = $educationModel->getGraduation_year(); // prepared statements is created $stmt = $this->conn->prepare("INSERT INTO EDUCATION (DEGREE, SCHOOL_NAME, SCHOOL_CITY, SCHOOL_STATE, SCHOOL_ZIP_CODE, GRADUATION_YEAR) VALUES (:degree, :school_name, :school_city, :school_state, :school_zip_code, :graduation_year)"); // binds parameters $stmt->bindParam(':degree', $degree); $stmt->bindParam(':school_name', $school_name); $stmt->bindParam(':school_city', $school_city); $stmt->bindParam(':school_state', $school_state); $stmt->bindParam(':school_zip_code', $school_zip_code); $stmt->bindParam(':graduation_year', $graduation_year); /* * see if education existed and return true if found * else return false if not found */ if ($stmt->execute()) { Log::info("Exit ProfileDataService.createEducation() with true"); return true; } else { Log::info("Exit ProfileDataService.createEducation() with false"); return false; } } catch (PDOException $e) { // best practice: catch all exceptions (do not swallow exceptions), // log the exception, do not throw technology specific exceptions, // and throw a custom exception Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function updateEducation(EducationModel $educationModel, $conn) { Log::info("Entering ProfileDataService.updateEducation()"); try { // select variables and see if the row exists $degree = $educationModel->getDegree(); $school_name = $educationModel->getSchool_name(); $school_city = $educationModel->getSchool_city(); $school_state = $educationModel->getSchool_state(); $school_zip_code = $educationModel->getSchool_zip_code(); $graduation_year = $educationModel->getGraduation_year(); // prepared statements is created $stmt = $this->conn->prepare("UPDATE EDUCATION SET DEGREE = :degree, SCHOOL_NAME = :school_name, SCHOOL_CITY = :school_city, SCHOOL_STATE = :school_state, SCHOOL_ZIP_CODE = :school_zip_code, GRADUATION_YEAR = :graduation_year WHERE EDUCATION_ID = :education_id"); // binds parameters $stmt->bindParam(':degree', $degree); $stmt->bindParam(':school_name', $school_name); $stmt->bindParam(':school_city', $school_city); $stmt->bindParam(':school_state', $school_state); $stmt->bindParam(':school_zip_code', $school_zip_code); $stmt->bindParam(':graduation_year', $graduation_year); /* * see if skills existed and return true if found * else return false if not found */ if ($stmt->execute()) { Log::info("Exit ProfileDataService.updateEducation() with true"); return true; } else { Log::info("Exit ProfileDataService.updateEducation() with false"); return false; } } catch (PDOException $e) { // best practice: catch all exceptions (do not swallow exceptions), // log the exception, do not throw technology specific exceptions, // and throw a custom exception Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function deleteEducation($id) { Log::info("Entering ProfileDataService.deleteEducation()"); try { // prepared statement is created $stmt = $this->conn->prepare("DELETE FROM EDUCATION WHERE EDUCATION_ID = :education_id"); // bind parameter $stmt->bindParam(':education_id', $id); // executes statement $delete = $stmt->execute(); // returns true or false if skill has been deleted from database if ($delete) { Log::info("Exiting ProfileDataService.deleteEducation() with returning true"); return true; } else { Log::info("Exiting ProfileDataService.deleteEducation() with returning false"); return false; } } catch (\PDOException $e) { Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function findAllEducation() { Log::info("Entering ProfileDataServcce.findAllEducation()"); try { // select skills and see if the row exists $stmt = $this->conn->prepare("SELECT * FROM EDUCATION"); $stmt->execute(); if ($stmt->rowCount() > 0) { // skills array is created $educationArray = array(); // fetches result from prepared statement and returns as an array while ($education = $stmt->fetch(PDO::FETCH_ASSOC)) { // inserts variables into end of array array_push($educationArray, $education); } Log::info("Exit ProfileDataServcce.findAllEducation() with true"); // return skills array return $educationArray; } } catch (PDOException $e) { // best practice: catch all exceptions (do not swallow exceptions), // log the exception, do not throw technology specific exceptions, // and throw a custom exception Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function createJobHistory(JobHistoryModel $jobHistory, $conn) { Log::info("Entering ProfileDataService.createJobHistory()"); try { // select variables and see if the row exists $current_job = $jobHistory->getCurrent_job(); $previous_job = $jobHistory->getPrevious_job(); $current_employment_date = $jobHistory->getCurrent_employment_date(); $previous_employment_date = $jobHistory->getPrevious_employment_date(); $current_employment_location = $jobHistory->getCurrent_employment_location(); // prepared statements is created $stmt = $this->conn->prepare("INSERT INTO JOB_HISTORY (JOB_HISTORY_ID, CURRENT_JOB, PREVIOUS_JOB, CURRENT_EMPLOYMENT_DATE, PREVIOUS_EMPLOYMENT_DATE, CURRENT_EMPLOYMENT_LOCATION, USER_USER_ID) VALUES (NULL, :current_job, :previous_job, :current_employment_date, :previous_employment_date, :current_employment_location)"); // binds parameters $stmt->bindParam(':current_job', $current_job); $stmt->bindParam(':previous_job', $previous_job); $stmt->bindParam(':current_employment_date', $current_employment_date); $stmt->bindParam(':previous_employment_date', $previous_employment_date); $stmt->bindParam(':current_employment_location', $current_employment_location); /* * see if skills existed and return true if found * else return false if not found */ if ($stmt->execute()) { Log::info("Exit ProfileDataService.createJobHistory() with true"); return true; } else { Log::info("Exit ProfileDataService.createJobHistory() with false"); return false; } } catch (PDOException $e) { // best practice: catch all exceptions (do not swallow exceptions), // log the exception, do not throw technology specific exceptions, // and throw a custom exception Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function updateJobHistory(JobHistoryModel $jobHistory, $conn) { Log::info("Entering ProfileDataService.createJobHistory()"); try { // select variables and see if the row exists $current_job = $jobHistory->getCurrent_job(); $previous_job = $jobHistory->getPrevious_job(); $current_employment_date = $jobHistory->getCurrent_employment_date(); $previous_employment_date = $jobHistory->getPrevious_employment_date(); $current_employment_location = $jobHistory->getCurrent_employment_location(); // prepared statements is created $stmt = $this->conn->prepare("UPDATE JOB_HISTORY SET CURRENT_JOB = :current_job, PREVIOUS_JOB = :previous_job, CURRENT_EMPLOYMENT_DATE = :current_employment_date, PREVIOUS_EMPLOYMENT_DATE = :previous_employment_date, CURRENT_EMPLOYMENT_LOCATION = :current_employment_location WHERE JOB_HISTORY_ID = :job_history_id;)"); // binds parameters $stmt->bindParam(':current_job', $current_job); $stmt->bindParam(':previous_job', $previous_job); $stmt->bindParam(':current_employment_date', $current_employment_date); $stmt->bindParam(':previous_employment_date', $previous_employment_date); $stmt->bindParam(':current_employment_location', $current_employment_location); /* * see if job history existed and return true if found * else return false if not found */ if ($stmt->execute()) { Log::info("Exit ProfileDataService.createJobHistory() with true"); return true; } else { Log::info("Exit ProfileDataService.createJobHistory() with false"); return false; } } catch (PDOException $e) { // best practice: catch all exceptions (do not swallow exceptions), // log the exception, do not throw technology specific exceptions, // and throw a custom exception Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function deleteJobHistory($id) { Log::info("Entering ProfileDataService.deleteJobHistory()"); try { // prepared statement is created $stmt = $this->conn->prepare("DELETE FROM JOB_HISTORY WHERE JOB_HISTORY_ID = :job_history_id"); // bind parameter $stmt->bindParam(':job_history_id', $id); // executes statement $delete = $stmt->execute(); // returns true or false if skill has been deleted from database if ($delete) { Log::info("Exiting ProfileDataService.deleteJobHistory() with returning true"); return true; } else { Log::info("Exiting ProfileDataService.deleteJobHistory() with returning false"); return false; } } catch (\PDOException $e) { Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function findAllJobHistory() { Log::info("Entering ProfileDataService.findAllJobHistory()"); try { // select skills and see if the row exists $stmt = $this->conn->prepare("SELECT * FROM JOB_HISTORY WHERE USER_USER_ID = user_user_id"); $stmt->execute(); if ($stmt->rowCount() > 0) { // skills array is created $jobhistoryArray = array(); // fetches result from prepared statement and returns as an array while ($jobhistory = $stmt->fetch(PDO::FETCH_ASSOC)) { // inserts variables into end of array array_push($jobhistoryArray, $jobhistory); } Log::info("Exit ProfileDataService.findAllJobHistory() with true"); // return skills array return $jobhistoryArray; } } catch (PDOException $e) { // best practice: catch all exceptions (do not swallow exceptions), // log the exception, do not throw technology specific exceptions, // and throw a custom exception Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function createContactInformation(ContactModel $contactModel, $conn) { Log::info("Entering ProfileDataService.createContactInfo()"); try { // select variables and see if the row exists $business_email = $contactModel->getBusiness_email(); $phone_number = $contactModel->getPhone_number(); $street_address = $contactModel->getStreet_address(); $state = $contactModel->getState(); $city = $contactModel->getCity(); $zip_code = $contactModel->getZip_code(); $about_me = $contactModel->getAbout_me(); // prepared statements is created $stmt = $this->conn->prepare("INSERT INTO CONTACT (CONTACT_ID, BUSINESS_EMAIL, PHONE_NUMBER, STREET_ADDRESS, STATE, CITY, ZIP_CODE, ABOUT_ME) VALUES (NULL, :business_email, :phone_number, :street_address, :state, :city, :zip_code, :about_me)"); // binds parameters $stmt->bindParam(':business_email', $business_email); $stmt->bindParam(':phone_number', $phone_number); $stmt->bindParam(':street_address', $street_address); $stmt->bindParam(':$state', $state); $stmt->bindParam(':city', $city); $stmt->bindParam(':zip_code', $zip_code); $stmt->bindParam(':about_me', $about_me); /* * see if skills existed and return true if found * else return false if not found */ if ($stmt->execute()) { Log::info("Exit ProfileDataService.createContactInfo() with true"); return true; } else { Log::info("Exit ProfileDataService.createContactInfo() with false"); return false; } } catch (PDOException $e) { // best practice: catch all exceptions (do not swallow exceptions), // log the exception, do not throw technology specific exceptions, // and throw a custom exception Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function updateContactInformation(ContactModel $contactModel, $conn) { Log::info("Entering ProfileDataService.updateContactInfo()"); try { // select variables and see if the row exists $business_email = $contactModel->getBusiness_email(); $phone_number = $contactModel->getPhone_number(); $street_address = $contactModel->getStreet_address(); $state = $contactModel->getState(); $city = $contactModel->getCity(); $zip_code = $contactModel->getZip_code(); $about_me = $contactModel->getAbout_me(); // prepared statements is created $stmt = $this->conn->prepare("UPDATE CONTACT SET BUSINESS_EMAIL = :business_email, PHONE_NUMBER = :phone_number, STREET_ADDRESS = :street_address, STATE = :state, CITY = :city, ZIP_CODE = :zip_code, ABOUT_ME = :about_me WHERE CONTACT_ID = :contact_id"); // binds parameters $stmt->bindParam(':business_email', $business_email); $stmt->bindParam(':phone_number', $phone_number); $stmt->bindParam(':street_address', $street_address); $stmt->bindParam(':$state', $state); $stmt->bindParam(':city', $city); $stmt->bindParam(':zip_code', $zip_code); $stmt->bindParam(':about_me', $about_me); /* * see if job history existed and return true if found * else return false if not found */ if ($stmt->execute()) { Log::info("Exit ProfileDataService.updateContactInfo() with true"); return true; } else { Log::info("Exit ProfileDataService.updateContactInfo() with false"); return false; } } catch (PDOException $e) { // best practice: catch all exceptions (do not swallow exceptions), // log the exception, do not throw technology specific exceptions, // and throw a custom exception Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function deleteContactInformation($id) { Log::info("Entering ProfileDataService.deleteContactInfo()"); try { // prepared statement is created $stmt = $this->conn->prepare("DELETE FROM CONTACT WHERE CONTACT_ID = :contact_id"); // bind parameter $stmt->bindParam(':contact_id', $id); // executes statement $delete = $stmt->execute(); // returns true or false if skill has been deleted from database if ($delete) { Log::info("Exiting ProfileDataService.deleteContactInfo() with returning true"); return true; } else { Log::info("Exiting ProfileDataService.deleteContactInfo() with returning false"); return false; } } catch (\PDOException $e) { Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } public function findContactByID($id) { Log::info("Entering ProfileDataService.findAllContacts()"); try { // select contact and see if the row exists $stmt = $this->conn->prepare("SELECT * FROM CONTACT WHERE CONTACT_ID = :contact_id"); $stmt->bindParam('contact_id', $id); $stmt->execute(); if ($stmt->rowCount() > 0) { // contact array is created $contactArray = array(); // fetches result from prepared statement and returns as an array while ($contact = $stmt->fetch(PDO::FETCH_ASSOC)) { // inserts variables into end of array array_push($contactArray, $contact); } Log::info("Exit ProfileDataService.findAllContacts() with true"); // return contact array return $contactArray; } } catch (PDOException $e) { // best practice: catch all exceptions (do not swallow exceptions), // log the exception, do not throw technology specific exceptions, // and throw a custom exception Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } }<file_sep>/app/Models/SkillsModel.php <?php namespace App\Models; class SkillsModel { private $skills_id; private $user_skills; private $user_user_id; public function __construct($skills_id, $user_skills, $user_user_id) { $this->skills_id = $skills_id; $this->user_skills = $user_skills; $this->user_user_id = $user_user_id; } /** * * @return mixed */ public function getSkills_id() { return $this->skills_id; } /** * * @param mixed $skills_id */ public function setSkills_id($skills_id) { $this->skills_id = $skills_id; } /** * * @return mixed */ public function getUser_skills() { return $this->user_skills; } /** * * @param mixed $user_skills */ public function setUser_skills($user_skills) { $this->user_skills = $user_skills; } /** * @return mixed */ public function getUser_user_id() { return $this->user_user_id; } /** * @param mixed $user_user_id */ public function setUser_user_id($user_user_id) { $this->user_user_id = $user_user_id; } }<file_sep>/app/Http/Controllers/RegistrationController.php <?php // <NAME> // CST 256 // <NAME> // This is my own work // Milestone 1 // 1/20/2019 // the page that handles the process to namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\UserModel; use App\Services\Business\SecurityService; use App\Services\Business\UserBusinessService; class RegistrationController extends Controller { public function register(Request $request) { // capture form data $firstname = $request->input('firstname'); $lastname = $request->input('lastname'); $email = $request->input('email'); $username = $request->input('username'); $password = $request->input('password'); // assigns the data from the variables to one array named $data $data = [ 'firstname' => $firstname, 'lastname' => $lastname, 'email' => $email, 'username' => $username, 'password' => $<PASSWORD> ]; // 2. create object model // save posted form data in user object model $user = new UserModel(- 1, $firstname, $lastname, $email, $username, $password, 0, 0); // 3. execute business service // call security business service $service = new UserBusinessService(); $status = $service->createUser($user); // 4. process results from business service (navigation) // render a failed or success response view and pass the user model to it if ($status) { $data = [ 'model' => $user ]; return view('registrationSuccess')->with($data); } else { return view('registrationFail'); } } }<file_sep>/app/Services/Business/AdminBusinessService.php <?php // <NAME> // CST 256 // February 3, 2019 // This is my own work /* Handles user business logic and connections to database */ namespace App\Services\Business; use App\Services\Data\UserDataService; use Illuminate\Support\Facades\Log; use PDO; use App\Services\Data\AdminDataService; class AdminBusinessService { public function deleteUser($id) { Log::info("Entering UserBusinessService.deleteUser()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("<PASSWORD>.connections.mysql.password"); // create connection to database $conn = new \PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new AdminDataService($conn); $flag = $service->deleteUser($id); // return the finder results Log::info("Exit SecurityService.deleteUser() with " . $flag); return $flag; } public function suspendUser($id) { Log::info("Entering UserBusinessService.suspendUser()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("<PASSWORD>.password"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and suspend user $service = new AdminDataService($conn); $flag = $service->suspendUser($id); // return the finder results Log::info("Exit SecurityService.suspendUser() with " . $flag); return $flag; } public function unsuspendUser($id) { Log::info("Entering UserBusinessService.unsuspendUser()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("database.connections.mysql.password"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and unsuspend user $service = new AdminDataService($conn); $flag = $service->unsuspendUser($id); // return the finder results Log::info("Exit SecurityService.unsuspendUser() with " . $flag); return $flag; } }<file_sep>/routes/web.php <?php /* * |-------------------------------------------------------------------------- * | Web Routes * |-------------------------------------------------------------------------- * | * | Here is where you can register web routes for your application. These * | routes are loaded by the RouteServiceProvider within a group which * | contains the "web" middleware group. Now create something great! * | */ use Illuminate\Support\Facades\Route; Route::get('/', function () { return view('welcome'); }); Route::get('start', function () { return view('displayJobs'); }); /* * LOGIN */ // returns a login form Route::get('/login', function () { return view('login'); }); // links the login form to the login function Route::post('doLogin', 'LoginController@login'); /* * REGISTRATION */ // returns a registration form Route::get('/registration', function () { return view('registration'); }); // links the registration form to the registration function Route::post('doRegistration', 'RegistrationController@register'); /* * PROFILE */ // returns the profile view Route::get('/profile', function () { return view('profile'); }); /* * SKILLS */ Route::get('/createSkills', function () { return view('createSkills'); }); Route::post('createSkills', 'ProfileController@createSkills'); Route::get('/updateSkills', function () { return view('updateSkills'); }); Route::post('/updateSkills', 'ProfileController@updateSkills'); Route::get('/displaySkills', function () { return view('displaySkills'); }); /* * CONTACT INFORMATION */ Route::get('/createContactInformation', function () { return view('createContactInformation'); }); Route::post('createContactInformation', 'ProfileController@createContactInformation'); Route::get('/updateContactInformation', function () { return view('updateContactInformation'); }); Route::post('/updateContactInformation', 'ProfileController@updateContactInformation'); /* * EDUCATION */ Route::get('/createEducation', function () { return view('createEducation'); }); Route::post('createEducation', 'ProfileController@createEducation'); Route::get('/updateEducation', function () { return view('updateEducation'); }); Route::post('updateEducation', 'ProfileController@updateEducation'); /* * JOB HISTORY */ Route::get('/createJobHistory', function () { return view('createJobHistory'); }); Route::post('createJobHistory', 'ProfileController@createJobHistory'); Route::post('updateJobHistory', 'ProfileController@updateJobHistory'); Route::get('/updateJobHistory', function () { return view('updateJobHistory'); }); /* * REGISTRATION EDIT */ Route::get('/updateRegistration', function () { return view('updateRegistration'); }); Route::post('updateRegistration', 'ProfileController@updateUser'); /* * JOB ADMINISTRATION */ Route::get('jobPost', function () { return view('createJobPost'); }); Route::get('/usersAdmin', 'AdminController@showUsers'); Route::get('/userDelete', 'AdminController@deleteUser'); Route::get('/userSuspend', 'AdminController@suspendUser'); Route::get('/userUnsuspend', 'AdminController@unsuspendUser'); route::get('/createJobPost', 'AdminController@showCreatePostForm'); Route::get('/jobsAdmin', 'AdminController@showAllJobPosts'); Route::get('/jobEdit', 'AdminController@updateJobPost'); Route::get('/jobDelete', 'AdminController@deleteJobPost'); <file_sep>/app/Http/Controllers/LoginController.php <?php // Milestone 3 // Login Module // <NAME> and <NAME> // January 20, 2019 // This is our own work /* Login module processes the authentication of user credentials */ namespace App\Http\Controllers; use App\Models\UserModel; use App\Services\Business\SecurityService; use Illuminate\Http\Request; use Illuminate\Support\Facades\Log; use Exception; class LoginController extends Controller { // authenticates user credentials public function login(Request $request) { try { // 1. process form data // get posted form data $firstname = $request->input('firstname'); $lastname = $request->input('lastname'); $email = $request->input('email'); $username = $request->input('username'); $password = $request->input('<PASSWORD>'); $active = $request->input('active'); // 2. create object model // save posted form data in user object model $user = new UserModel(- 1, $firstname, $lastname, $email, $username, $password, 0, $active); // 3. execute business service // call security business service $service = new SecurityService(); $status = $service->login($user); // 4. process results from business service (navigation) // render a failed or success response view and pass the user model to it if ($status) { $_SESSION['principle'] = true; $_SESSION['USERNAME'] = $username; $data = [ 'model' => $user ]; return view('displayJobs')->with($data); } else if ($active == 1) { return view('suspendUser'); } else { return view('loginFail'); } } catch (Exception $e) { // best practice: call all exceptions, log the exception, and display a common error page (or use a global exception handler) // log exception and display exception view Log::error("Exception: ", array( "message" => $e->getMessage() )); $data = [ 'errorMsg' => $e->getMessage() ]; return view('exception')->with($data); } } }<file_sep>/app/Models/JobHistoryModel.php <?php namespace App\Models; class JobHistoryModel { private $job_history_id; private $current_job; private $previous_job; private $current_employment_date; private $previous_employment_date; private $current_employment_location; private $user_user_id; public function __construct($job_history_id, $current_job, $previous_job, $current_employment_date, $previous_employment_date, $current_employment_location, $user_user_id) { $this->job_history_id = $job_history_id; $this->current_job = $current_job; $this->current_employment_date = $current_employment_date; $this->previous_employment_date = $previous_employment_date; $this->current_employment_location = $current_employment_location; $this->user_user_id = $user_user_id; } /** * * @return mixed */ public function getJob_history_id() { return $this->job_history_id; } /** * * @param mixed $job_history_id */ public function setJob_history_id($job_history_id) { $this->job_history_id = $job_history_id; } /** * * @return mixed */ public function getCurrent_job() { return $this->current_job; } /** * * @param mixed $current_job */ public function setCurrent_job($current_job) { $this->current_job = $current_job; } /** * * @return mixed */ public function getPrevious_job() { return $this->previous_job; } /** * * @param mixed $previous_job */ public function setPrevious_job($previous_job) { $this->previous_job = $previous_job; } /** * * @return mixed */ public function getCurrent_employment_date() { return $this->current_employment_date; } /** * * @param mixed $current_employment_date */ public function setCurrent_employment_date($current_employment_date) { $this->current_employment_date = $current_employment_date; } /** * * @return mixed */ public function getPrevious_employment_date() { return $this->previous_employment_date; } /** * * @param mixed $previous_employment_date */ public function setPrevious_employment_date($previous_employment_date) { $this->previous_employment_date = $previous_employment_date; } /** * * @return mixed */ public function getCurrent_employment_location() { return $this->current_employment_location; } /** * * @param mixed $current_employment_location */ public function setCurrent_employment_location($current_employment_location) { $this->current_employment_location = $current_employment_location; } /** * @return mixed */ public function getUser_user_id() { return $this->user_user_id; } /** * @param mixed $user_user_id */ public function setUser_user_id($user_user_id) { $this->user_user_id = $user_user_id; } }<file_sep>/app/Services/Business/JobBusinessService.php <?php // <NAME> // CST 256 // February 3, 2019 // This is my own work /* Handles user business logic and connections to database */ namespace App\Services\Business; use PDO; use App\Models\UserModel; use Illuminate\Support\Facades\Log; use App\Models\JobModel; use App\Services\Data\JobDataService; class JobBusinessService { public function createJobPost(JobModel $jobModel) { Log::info("Entering JobBusinessService.createJobPost()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("<PASSWORD>"); // best practice: do not create database connections in a dao // create connection $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find users $service = new JobDataService($conn); // calls the createJobPost command $flag = $service->createJobPost($jobModel, $conn); // return the finder results return $flag; Log::info("Exit JobBusinessService.createJobPost() with " . $flag); } public function updateJobPost(JobModel $jobModel) { Log::info("Entering JobBusinessService.updateJobPost()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("<PASSWORD>.connections.mysql.password"); // best practice: do not create database connections in a dao // create connection $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find users $service = new JobDataService($conn); // calls the updateJobPosting command $flag = $service->updateJobPost($jobModel, $conn); // return the finder results return $flag; Log::info("Exit JobBusinessService.createJobPost() with " . $flag); } public function deleteJobPost($id) { Log::info("Entering JobBusinessService.deleteJobPost()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("database.connections.mysql.password"); // best practice: do not create database connections in a dao // create connection $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find users $service = new JobDataService($conn); // calls the deleteJobPost command $flag = $service->deleteJobPost($id); // return the finder results return $flag; Log::info("Exit JobBusinessService.deleteJobPost() with " . $flag); } public function showJobPosts() { Log::info("Entering JobBusinessService.showJobPosts()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("<PASSWORD>"); // best practice: do not create database connections in a dao // create connection $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find users $service = new JobDataService($conn); // calls the findAllUsers command $flag = $service->showAllJobPosts(); // return the finder results return $flag; Log::info("Exit JobBusinessService.showJobPosts() with " . $flag); } }<file_sep>/resources/views/exception.php <?php echo "Exception Occured: " . $errorMsg; ?> <br> <a href="login">Try Again</a> <file_sep>/app/Services/Data/AdminDataService.php <?php namespace App\Services\Data; use Illuminate\Support\Facades\Log; use App\Services\Utility\DatabaseException; class AdminDataService { private $conn = null; // best practice: do not create a database connections in a dao // so you can support atomic database transactions public function __construct($conn) { $this->conn = $conn; } // method to delete user public function deleteUser($id) { Log::info("Entering UserDataService.deleteUser()"); try { // prepared statement is created $stmt = $this->conn->prepare('DELETE FROM USER WHERE `USER_ID` = :id'); // bind parameter $stmt->bindParam(':id', $id); // executes statement $delete = $stmt->execute(); // returns true or false if user has been deleted from database if ($delete) { Log::info("Exiting UserDataService.deleteUser() with returning true"); return true; } else { Log::info("Exiting UserDataService.deleteUser() with returning false"); return false; } } catch (\PDOException $e) { Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } // method to suspend user public function suspendUser($id) { Log::info("Entering UserDataService.suspendUser()"); try { // prepared statement is created $stmt = $this->conn->prepare("UPDATE USER SET `ACTIVE` = '1' WHERE `USER_ID` = :id"); // bind parameter $stmt->bindParam(':id', $id); // executes statement $suspend = $stmt->execute(); // returns true or false if user active row has been set to 1 if ($suspend) { Log::info("Exiting UserDataService.suspendUser() with returning true"); return true; } else { Log::info("Exiting UserDataService.suspendUser() with returning false"); return false; } } catch (\PDOException $e) { Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } // method to unsuspend user account public function unsuspendUser($id) { Log::info("Entering UserDataService.unsuspendUser()"); try { // prepared statement is created $stmt = $this->conn->prepare("UPDATE USER SET `ACTIVE` = '0' WHERE `USER_ID` = :id"); // bind parameter $stmt->bindParam(':id', $id); // executes statement $suspend = $stmt->execute(); // returns true or false if user active row has been set to 0 if ($suspend) { Log::info("Exiting UserDataService.unsuspendUser() with returning true"); return true; } else { Log::info("Exiting UserDataService.unsuspendUser() with returning false"); return false; } } catch (\PDOException $e) { Log::error("Exception: ", array( "message" => $e->getMessage() )); throw new DatabaseException("Database Exception: " . $e->getMessage(), 0, $e); } } } <file_sep>/app/Services/Business/ProfileBusinessService.php <?php namespace App\Services\Business; use Illuminate\Support\Facades\Log; use PDO; use App\Models\SkillsModel; use App\Services\Data\ProfileDataService; use App\Models\EducationModel; use App\Models\JobHistoryModel; use App\Models\ContactModel; class ProfileBusinessService { public function createSkills(SkillsModel $skillsModel) { Log::info("Entering ProfileBusinessService.createSkills()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("database.connections.mysql.password"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new ProfileDataService($conn); $flag = $service->createSkills($skillsModel, $conn); // return the finder results Log::info("Exit ProfileBusinessService.createSkills() with " . $flag); return $flag; } public function updateSkills(SkillsModel $skillsModel, $id) { Log::info("Entering ProfileBusinessService.updateSkills()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("<PASSWORD>.connections.<PASSWORD>.password"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new ProfileDataService($conn); $flag = $service->updateSkills($skillsModel, $id); // return the finder results Log::info("Exit ProfileBusinessService.updateSkills() with " . $flag); return $flag; } public function deleteSkills($id) { Log::info("Entering ProfileBusinessService.deleteSkills()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("database.connections.mysql.password"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new ProfileDataService($conn); $flag = $service->deleteSkills($id); // return the finder results Log::info("Exit ProfileBusinessService.deleteSkills() with " . $flag); return $flag; } public function showSkills($user_user_id) { Log::info("Entering ProfileBusinessService.showSkills()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("database.connections.mysql.password"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new ProfileDataService($conn); $flag = $service->findAllSkills($user_user_id); // return the finder results Log::info("Exit ProfileBusinessService.showSkills() with " . $flag); return $flag; } public function createEducation(EducationModel $educationModel) { Log::info("Entering ProfileBusinessService.createEducation()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("database.connections.mysql.password"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new ProfileDataService($conn); $flag = $service->createEducation($educationModel, $conn); // return the finder results Log::info("Exit ProfileBusinessService.createEducation() with " . $flag); return $flag; } public function updateEducation(EducationModel $educationModel) { Log::info("Entering ProfileBusinessService.updateEducation()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("<PASSWORD>.connections.mysql.password"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new ProfileDataService($conn); $flag = $service->updateEducation($educationModel, $conn); // return the finder results Log::info("Exit ProfileBusinessService.updateEducation() with " . $flag); return $flag; } public function deleteEducation($id) { Log::info("Entering ProfileBusinessService.deleteEducation()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("<PASSWORD>.connections.<PASSWORD>"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new ProfileDataService($conn); $flag = $service->deleteEducation($id); // return the finder results Log::info("Exit ProfileBusinessService.deleteEducation() with " . $flag); return $flag; } public function showEducation() { Log::info("Entering ProfileBusinessService.showEducation()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("database.connections.mysql.password"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new ProfileDataService($conn); $flag = $service->findAllEducation(); // return the finder results Log::info("Exit ProfileBusinessService.showEducation() with " . $flag); return $flag; } public function createJobHistory(JobHistoryModel $jobHistory) { Log::info("Entering ProfileBusinessService.createJobHistory()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("<PASSWORD>.connections.mysql.password"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new ProfileDataService($conn); $flag = $service->createJobHistory($jobHistory, $conn); // return the finder results Log::info("Exit ProfileBusinessService.createJobHistory() with " . $flag); return $flag; } public function updateJobHistory(JobHistoryModel $jobHistory) { Log::info("Entering ProfileBusinessService.updateJobHistory()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("database.connections.mysql.password"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new ProfileDataService($conn); $flag = $service->updateJobHistory($jobHistory, $conn); // return the finder results Log::info("Exit ProfileBusinessService.updateJobHistory() with " . $flag); return $flag; } public function deleteJobHistory($id) { Log::info("Entering ProfileBusinessService.deleteJobHistory()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("<PASSWORD>"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new ProfileDataService($conn); $flag = $service->deleteJobHistory($id); // return the finder results Log::info("Exit ProfileBusinessService.deleteJobHistory() with " . $flag); return $flag; } public function showJobHistory() { Log::info("Entering ProfileBusinessService.showJobHistory()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("database.connections.mysql.password"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new ProfileDataService($conn); $flag = $service->findAllJobHistory(); // return the finder results Log::info("Exit ProfileBusinessService.showJobHistory() with " . $flag); return $flag; } public function createContactInformation(ContactModel $contactModel) { Log::info("Entering ProfileBusinessService.createContactInformation()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("<PASSWORD>"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new ProfileDataService($conn); $flag = $service->createContactInformation($contactModel, $conn); // return the finder results Log::info("Exit ProfileBusinessService.createContactInformation() with " . $flag); return $flag; } public function updateContactInformation(ContactModel $contactModel) { Log::info("Entering ProfileBusinessService.updateContactInformation()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("database.connections.mysql.password"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new ProfileDataService($conn); $flag = $service->updateContactInformation($contactModel, $conn); // return the finder results Log::info("Exit ProfileBusinessService.updateContactInformation() with " . $flag); return $flag; } public function deleteContactInformation($id) { Log::info("Entering ProfileBusinessService.deleteContactInformation()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("database.connections.mysql.password"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new ProfileDataService($conn); $flag = $service->deleteContactInformation($id); // return the finder results Log::info("Exit ProfileBusinessService.deleteContactInformation() with " . $flag); return $flag; } public function showContactInformation($id) { Log::info("Entering ProfileBusinessService.showContactInformation()"); // get credentials for accessing the database $servername = config("database.connections.mysql.host"); $dbname = config("database.connections.mysql.database"); $username = config("database.connections.mysql.username"); $password = config("database.connections.mysql.password"); // create connection to database $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // create a security service dao with this connection and try to find and delete user $service = new ProfileDataService($conn); $flag = $service->findContactByID($id); // return the finder results Log::info("Exit ProfileBusinessService.showContactInformations() with " . $flag); return $flag; } }<file_sep>/README.md # Milestone3-256 <file_sep>/app/Models/ContactModel.php <?php namespace App\Models; class ContactModel { private $contact_id; private $business_email; private $phone_number; private $street_address; private $city; private $state; private $zip_code; private $about_me; private $user_user_id; public function __construct($contact_id, $business_email, $phone_number, $street_address, $city, $state, $zip_code, $about_me, $user_user_id) { $this->contact_id = $contact_id; $this->business_email = $business_email; $this->phone_number = $phone_number; $this->street_address = $street_address; $this->city = $city; $this->state = $state; $this->zip_code = $zip_code; $this->about_me = $about_me; $this->user_user_id = $user_user_id; } /** * * @return mixed */ public function getContact_id() { return $this->contact_id; } /** * * @param mixed $contact_id */ public function setContact_id($contact_id) { $this->contact_id = $contact_id; } /** * * @return mixed */ public function getBusiness_email() { return $this->business_email; } /** * * @param mixed $business_email */ public function setBusiness_email($business_email) { $this->business_email = $business_email; } /** * * @return mixed */ public function getPhone_number() { return $this->phone_number; } /** * * @param mixed $phone_number */ public function setPhone_number($phone_number) { $this->phone_number = $phone_number; } /** * * @return mixed */ public function getStreet_address() { return $this->street_address; } /** * * @param mixed $street_address */ public function setStreet_address($street_address) { $this->street_address = $street_address; } /** * * @return mixed */ public function getState() { return $this->state; } /** * * @param mixed $state */ public function setState($state) { $this->state = $state; } /** * * @return mixed */ public function getCity() { return $this->city; } /** * * @param mixed $city */ public function setCity($city) { $this->city = $city; } /** * * @return mixed */ public function getZip_code() { return $this->zip_code; } /** * * @param mixed $zip_code */ public function setZip_code($zip_code) { $this->zip_code = $zip_code; } /** * * @return mixed */ public function getAbout_me() { return $this->about_me; } /** * * @param mixed $about_me */ public function setAbout_me($about_me) { $this->about_me = $about_me; } /** * * @return mixed */ public function getUser_user_id() { return $this->user_user_id; } /** * * @param mixed $user_user_id */ public function setUser_user_id($user_user_id) { $this->user_user_id = $user_user_id; } }<file_sep>/app/Models/CredentialsModel.php <?php namespace App\Models; class CredentialsModel { private $credentials_id; private $username; private $password; private $user_user_id; public function __construct($credentials_id, $username, $password, $user_user_id) { $this->credentials_id = $credentials_id; $this->username = $username; $this->password = $<PASSWORD>; $this->user_user_id = $user_user_id; } /** * * @return mixed */ public function getCredentials_id() { return $this->credentials_id; } /** * * @return mixed */ public function getUsername() { return $this->username; } /** * * @return mixed */ public function getPassword() { return $this-><PASSWORD>; } /** * * @param mixed $credentials_id */ public function setCredentials_id($credentials_id) { $this->credentials_id = $credentials_id; } /** * * @param mixed $username */ public function setUsername($username) { $this->username = $username; } /** * * @param mixed $password */ public function setPassword($password) { $this->password = $<PASSWORD>; } /** * @return mixed */ public function getUser_user_id() { return $this->user_user_id; } /** * @param mixed $user_user_id */ public function setUser_user_id($user_user_id) { $this->user_user_id = $user_user_id; } }<file_sep>/app/Models/EducationModel.php <?php namespace App\Models; class EducationModel { private $education_id; private $degree; private $school_name; private $school_city; private $school_state; private $school_zip_code; private $graduation_year; private $user_user_id; public function __construct($education_id, $degree, $school_name, $school_city, $school_state, $school_zip_code, $graduation_year, $user_user_id) { $this->education_id = $education_id; $this->degree = $degree; $this->school_name = $school_name; $this->school_city = $school_city; $this->school_state = $school_state; $this->school_zip_code = $school_zip_code; $this->graduation_year = $graduation_year; $this->user_user_id = $user_user_id; } /** * * @return mixed */ public function getEducation_id() { return $this->education_id; } /** * * @param mixed $education_id */ public function setEducation_id($education_id) { $this->education_id = $education_id; } /** * * @return mixed */ public function getDegree() { return $this->degree; } /** * * @param mixed $degree */ public function setDegree($degree) { $this->degree = $degree; } /** * * @return mixed */ public function getSchool_name() { return $this->school_name; } /** * * @param mixed $school_name */ public function setSchool_name($school_name) { $this->school_name = $school_name; } /** * * @return mixed */ public function getSchool_city() { return $this->school_city; } /** * * @param mixed $school_city */ public function setSchool_city($school_city) { $this->school_city = $school_city; } /** * * @return mixed */ public function getSchool_state() { return $this->school_state; } /** * * @param mixed $school_state */ public function setSchool_state($school_state) { $this->school_state = $school_state; } /** * * @return mixed */ public function getSchool_zip_code() { return $this->school_zip_code; } /** * * @param mixed $school_zip_code */ public function setSchool_zip_code($school_zip_code) { $this->school_zip_code = $school_zip_code; } /** * * @return mixed */ public function getGraduation_year() { return $this->graduation_year; } /** * * @param mixed $graduation_year */ public function setGraduation_year($graduation_year) { $this->graduation_year = $graduation_year; } }
ed3e44d9fd941f6c1c6e029925b3db064def9807
[ "Markdown", "PHP" ]
21
PHP
kittymama97/Milestone3-256
3602447f02b4735f9e8d233bd0f168b7c615502b
8571936ec9e2552646e5822f90e1c13955c9b1ad
refs/heads/master
<repo_name>ravenusmc/Black_jack<file_sep>/main.cpp /* program: Black Jack Programmer: <NAME> Date Started: 24 October 2016 Date Submitted: 29 November 2016 Other: N/A */ /* Explanation: This program is an electronic version of the casino game Black Jack. It is designed to be played with either one or two players. */ #include <iostream> #include <string> #include <iomanip> #include <cstdlib> #include <ctime> using namespace std; //******************************* //Structures //******************************* //The structure will handle the card deck. class Card { public: int valueOne; int valueTwo; string suite; string face; }; //This structure will handle the player(s) information. class PlayerInfo { public: string name; string emailAddress; string username; int winnings; }; //******************************* //Global Variables/Constants //******************************* const int DECKSIZE = 52; //This constant will hold the size of the deck const int MAXDECK = 11; //This constant is to hold the max number of cards for a players deck. const int BLACKJACK = 21; //This constant is for determining blackjack //******************************* //Prototype Functions-See Function definitions at the end of the main function //to see what each of these functions does. //******************************* void welcome(); void createDeck(Card [], int); void shuffle(Card [], int); int numberOfPlayers(); bool validPlayers(int); bool validBets(int); void game(int, Card [], int); int playAgain(); void stand(); int playerChoices(); void playerOneInfo(int, PlayerInfo); void playerTwoInfo(int, PlayerInfo); void dealTwoCards(Card [], int, Card [], int, int &, int &, PlayerInfo); void dealTwoCardsTwo(Card [], int, Card [], int, int &, int &, PlayerInfo); void dealOneCard(Card [], int, Card [], int, int &, int &, PlayerInfo); void dealOneCardTwo(Card [], int, Card [], int, int &, int &, PlayerInfo); void makeBets(int *, int, PlayerInfo, PlayerInfo); void surrender(int *, int); void surrenderTwo(int *, int); void Doubledown(Card [], int, Card [], int, int &, int &, int *, int, PlayerInfo); void DoubleDownTwo(Card [], int, Card [],int, int &, int &, int *, int, PlayerInfo); void getDealersCards(Card [], int, Card [], int, int &, int &); int dealerAddCard(Card [], int, Card [], int, int &, int &); void dealerShowCards(int, Card [], int, int); bool Winner(int playerOneTotal, int *, int, PlayerInfo); bool WinnerTwo(int playerOneTotal, int *, int, PlayerInfo); void determineWinnerOne(int, int, int *, int, int &, int &, PlayerInfo, bool); void determineWinnerTwo(int, int, int *, int, int &, int &, PlayerInfo, bool); void playerOneSurrendered(int *, int , int &, int &, PlayerInfo); void playerTwoSurrendered(int *, int, int &, int &, PlayerInfo); void pauseProgram(); void clearScreen(); void createId(int, PlayerInfo &, PlayerInfo &); void displayStats(int, int, int, PlayerInfo &, PlayerInfo &, int); bool bootedOut(PlayerInfo, PlayerInfo); void mainMenu(); void instructions(); void goodBye(); //****************************** //Main Function-This is the function which will drive the program and //handle all other functions. //****************************** int main(){ //Declaring variables int players, again, action, cardLocation, playerOneTotal, playerTwoTotal, dealerTotal; int dealerDeckSize; int *arrayForBets; int dealerWinnings = 0; int playerOneEarnings = 0; int playerTwoEarnings = 0; bool BlackJackOne = false; bool BlackJackTwo = false; bool Break = false; bool SurrenderOne = false; bool SurrenderTwo = false; bool breakOne = false; bool breakTwo = false; bool booted = false; //Declaring the structures which will contain info on the players. PlayerInfo pOne; PlayerInfo pTwo; //Creating the deck of cards Card deck[DECKSIZE]; //These structures will be used to hold the cards that the dealer, playerOne and playerTwo are dealt. //The constant is set to 11 because that is the maximun number of cards that someone can have //before Black Jack or 21 may arise. However, the main reason why these structures were created //was to allow me to have a place to hold cards, if I needed them. Which became quite useful in dealing //with aces. However, other than that, I really did not use them as much as I thought I would. Card playerOne[MAXDECK]; Card playerTwo[MAXDECK]; Card dealer[MAXDECK]; //The call to this function will great the users. welcome(); //I pause the program and then clear the screen with these two functions. pauseProgram(); clearScreen(); //Calling the main menu to allow the user to see instructions or play the game. mainMenu(); //I pause the program and then clear the screen with these two functions. pauseProgram(); clearScreen(); //This function will allow the user(s) to enter the number of players players = numberOfPlayers(); //I pause the program and then clear the screen with these two functions. pauseProgram(); clearScreen(); //Here the players create an ID for themselves. createId(players, pOne, pTwo); //Line break-To help with user output. cout << endl; //This function call will create the deck of cards. createDeck(deck, DECKSIZE); do { //These variables must be returned to zero, initial condition at the end of every round. cardLocation = 0; playerOneTotal = 0; playerTwoTotal = 0; playerOneEarnings = 0; playerTwoEarnings = 0; dealerTotal = 0; Break = false; BlackJackOne = false; BlackJackTwo = false; SurrenderOne = false; SurrenderTwo = false; breakOne = false; breakTwo = false; booted = false; //This line sets up the array for the players bets arrayForBets = new int[players]; //Clearing the screen to help with output. clearScreen(); //This function call will shuffle the deck of cards shuffle(deck, DECKSIZE); //This code will forbid the players from playing the game if they have zero or negative money. booted = bootedOut(pOne, pTwo); //If a player does have a negative balance they will be booted from the game-the while loop will break. if (booted){ break; } //Calling this function allows the player(s) to make their bets makeBets(arrayForBets, players, pOne, pTwo); //Clearing the screen to help with user output. clearScreen(); //Line breaks-to help with output. cout << endl; //This conditional statement will deal the initial first two cards based on how many players //That are playing the game. if (players == 1){ //Calling the function to deal the first two cards to the first player dealTwoCards(deck, DECKSIZE, playerOne, MAXDECK, cardLocation, playerOneTotal, pOne); //Clearing the screen to help with user output clearScreen(); }else if (players == 2){ //Calling the function to deal the first two cards to the first player dealTwoCards(deck, DECKSIZE, playerOne, MAXDECK, cardLocation, playerOneTotal, pOne); //Clearing the screen to help with output clearScreen(); //Calling the function to deal the first two cards to the second player dealTwoCardsTwo(deck, DECKSIZE, playerTwo, MAXDECK, cardLocation, playerTwoTotal, pTwo); //Clearing the screen to help with output clearScreen(); } //These functions check to see if player one or two has BLACKJACK on the initial round. //If they do, they will win twice the amount that they bet and they will not be allowed to //take any more cards. BlackJackOne = Winner(playerOneTotal, arrayForBets, players, pOne); BlackJackTwo = WinnerTwo(playerTwoTotal, arrayForBets, players, pTwo); //This is a line break to help with output cout << endl; //This function will get the dealers hand. getDealersCards(deck, DECKSIZE, dealer, MAXDECK, cardLocation, dealerTotal); //This line will help with output. cout << endl; //This conditional statement is what will allow the players to decide what actions they want to take in regards //to taking another card, stand, double down or surrendering. if ( (players == 1) && (BlackJackOne == false) ){ //This loop will repeat until breakOne is made true which will occur by the player's actions. while (breakOne == false){ playerOneInfo(playerOneTotal, pOne); action = playerChoices(); if (action == 1){ dealOneCard(deck, DECKSIZE, playerOne, MAXDECK, cardLocation, playerOneTotal, pOne); //If the player's total is greater than 21 or if it is 21 breakOne is set to true //which will end the loop if (playerOneTotal > BLACKJACK){ breakOne = true; }else if (playerOneTotal == BLACKJACK){ breakOne = true; } }else if (action == 2){ stand(); breakOne = true; }else if (action == 3){ Doubledown(deck, DECKSIZE, playerOne, MAXDECK, cardLocation, playerOneTotal, arrayForBets, players, pOne); breakOne = true; }else if (action == 4){ surrender(arrayForBets, players); breakOne = true; SurrenderOne = true; } } } else if ( (players == 2) && (BlackJackOne == false) && (BlackJackTwo == false) ){ //This loop will repeat until breakOne is made true which will occur by the players actions. while ( (breakOne == false) || (breakTwo == false) ){ if (breakOne == false){ playerOneInfo(playerOneTotal, pOne); action = playerChoices(); if (action == 1){ dealOneCard(deck, DECKSIZE, playerOne, MAXDECK, cardLocation, playerOneTotal, pOne); //If the player's total is greater than 21 or if it is 21 breakOne is set to true //which will end the loop if (playerOneTotal > BLACKJACK){ breakOne = true; }else if (playerOneTotal == BLACKJACK){ breakOne = true; } }else if (action == 2){ stand(); breakOne = true; }else if (action == 3){ Doubledown(deck, DECKSIZE, playerOne, MAXDECK, cardLocation, playerOneTotal, arrayForBets, players, pOne); breakOne = true; }else if (action == 4){ surrender(arrayForBets, players); breakOne = true; SurrenderOne = true; } clearScreen(); } if (breakTwo == false){ playerTwoInfo(playerTwoTotal, pTwo); action = playerChoices(); if (action == 1){ dealOneCardTwo(deck, DECKSIZE, playerTwo, MAXDECK, cardLocation, playerTwoTotal, pTwo); //If the player's total is greater than 21 or if it is 21 breakOne is set to true //which will end the loop if (playerTwoTotal > BLACKJACK){ breakTwo = true; }else if (playerTwoTotal == BLACKJACK){ breakTwo = true; } }else if (action == 2){ stand(); breakTwo = true; }else if (action == 3){ DoubleDownTwo(deck, DECKSIZE, playerTwo, MAXDECK, cardLocation, playerTwoTotal, arrayForBets, players, pTwo); breakTwo = true; }else if (action == 4){ surrenderTwo(arrayForBets, players); breakTwo = true; SurrenderTwo = true; } } } } //This function call will add more cards to the computer/dealer if their total is 16 or below. dealerDeckSize = dealerAddCard(deck, DECKSIZE, dealer, MAXDECK, cardLocation, dealerTotal); //This function call will show the dealers hands right before the winners are announced. dealerShowCards(dealerDeckSize, dealer, MAXDECK, dealerTotal); //This line will help to make output nicer. cout << endl; //This conditional statement will determine what the first player won or lost. if (SurrenderOne == false){ determineWinnerOne(playerOneTotal, dealerTotal, arrayForBets, players, dealerWinnings, playerOneEarnings, pOne, BlackJackOne); //Pausing the program here to help with user output pauseProgram(); }else if (SurrenderOne == true){ playerOneSurrendered(arrayForBets, players, playerOneEarnings, dealerWinnings, pOne); //Pausing the program here to help with user output pauseProgram(); } //This conditional statement will determine what the second player won or lost. if(SurrenderTwo == false && players == 2){ determineWinnerTwo(playerTwoTotal, dealerTotal, arrayForBets, players, dealerWinnings, playerTwoEarnings, pTwo, BlackJackTwo); //Pausing the program here to help with user output pauseProgram(); } else if (SurrenderTwo == true){ playerTwoSurrendered(arrayForBets, players, playerTwoEarnings, dealerWinnings, pTwo); //Pausing the program here to help with user output pauseProgram(); } //line break-to help with output. cout << endl; //This function helps with the output and attempts to clear the screen each time it is called clearScreen(); //This function will display the stats for the players. displayStats(players, playerOneEarnings, playerTwoEarnings, pOne, pTwo, dealerTotal); //line break to help with output. cout << endl; //Asking the player(s) if they want to play again. again = playAgain(); //Increasing the card location. cardLocation++; //If again is equal to 2 then the loop will end and the player(s) will exit out. The game will end at that point. } while (again != 2); //This function will display a message telling the user(s) bye. goodBye(); //Destroying the dynamically allocated memory delete [] arrayForBets; arrayForBets = nullptr; //system("pause"); //This line is for Microsoft Visual users. return 0; }// End of main function //****************************** //Functions-All of the functions used in the program are described here. //There is another section below where validation functions are described. Look for that //at the bottom. //****************************** //This function is the title menu and greets the user(s) void welcome(){ //All of these cout statements introduce the user to the game. cout << "\t\t\t***********************" << endl; cout << "\t\t\t*---------------------*" << endl; cout << "\t\t\t*---------------------*" << endl; cout << "\t\t\t*----<NAME>-----*" << endl; cout << "\t\t\t*---------------------*" << endl; cout << "\t\t\t*Welcome to Black Jack*" << endl; cout << "\t\t\t*---------------------*" << endl; cout << "\t\t\t*-------Where---------*" << endl; cout << "\t\t\t*------You Lose-------*" << endl; cout << "\t\t\t*-------We Win--------*" << endl; cout << "\t\t\t*---------------------*" << endl; cout << "\t\t\t***********************" << endl; cout << endl; }//End of welcome function //This function is what will determine the number of players in the game. int numberOfPlayers(){ //Declaring a local variable int players; //Alerting the player know that they are at the numer of players selection screen. cout << "****************************" << endl; cout << "* Choose Number of Players *" << endl; cout << "****************************" << endl; cout << endl; //The user(s) enter the number of players cout << "Please enter the number of players (1 or 2): " << endl; cin >> players; //If the user(s) enters a value that is not acceptable they go into a validation loop. while (!validPlayers(players)) { //This line alerts the user to what is the correct value that may be entered. cout << "The amount of players may only be between 1 or 2" << endl; cin >> players; } //The function will return the number of players that the user selected. return players; }// End of numberOfPlayers function //This function will allow the players to make their bets void makeBets(int *arrayForBets, int players, PlayerInfo pOne, PlayerInfo pTwo){ //This will alert the user that they are at the screen to make their bets. cout << "***************************" << endl; cout << "Place your Bets" << endl; cout << "***************************" << endl; cout << endl; cout << "Here you will enter in the amount you want to bet" << endl; cout << endl; //This loop will ask the players to make their bets. for (int i = 0; i < players; i++){ //This coditional statement will excute depending on what the value of i is. It will ensure that the //users are only able to enter in the amount of money that they have. if (i == 0){ cout << pOne.username << " please place your bet: " << endl; cout << "The bet must be between 10 and " << pOne.winnings << endl; cin >> arrayForBets[i]; //This validation loop ensures that the player may only input money within a correct range. while ( (arrayForBets[i] < 10) || (arrayForBets[i] > pOne.winnings) ){ cout << "The bets must be between 10 and " << pOne.winnings << endl; cin >> arrayForBets[i]; } }else if (i == 1){ cout << endl; cout << pTwo.username << " please place your bet: " << endl; cout << "The bet must be between 10 and " << pTwo.winnings << endl; cin >> arrayForBets[i]; //This validation loop ensures that the player may only input money within a correct range. while ( (arrayForBets[i] < 10) || (arrayForBets[i] > pTwo.winnings) ){ cout << "The bets must be between 10 and " << pTwo.winnings << endl; cin >> arrayForBets[i]; } } } //This line helps with output cout << endl; //Clearing the screen to help with output clearScreen(); //Alerting the user to what is occuring cout << "The bets are made, the cards have been shuffled and now the cards will be dealt..." << endl; //Pausing the program to help with user output. pauseProgram(); }//End of makeBets function //This function allows for the players to set up the information about who they are. void createId(int players, PlayerInfo &pOne, PlayerInfo &pTwo){ //Declaring local variables which will be used to set up the user information structures. string name; string email; string username; //Outputing the display for the player creation screen. cout << "***************************" << endl; cout << "* Player Creation Screen *" << endl; cout << "***************************" << endl; cout << endl; cout << "Here you will enter in information about your player" << endl; cout << endl; //This conditional loop will allow the players to set up their user information. if (players == 1){ cin.ignore(); cout << "Player One please enter your name: " << endl; getline(cin, name); //validation to ensure that the player enters a value for their name. while (name == ""){ cout << "You must enter some type of name!" << endl; getline(cin, name); } pOne.name = name; cout << "Player One please enter your email: " << endl; getline(cin, email); //Validation to ensure that the player enter a value for their email while (email == ""){ cout << "You must enter some type of email!" << endl; getline(cin, email); } pOne.emailAddress = email; cout << "Player One please enter a username: " << endl; cout << "The username will be used during gameplay" << endl; getline(cin, username); //Validation to ensure that the player enter a value for their username while (username == ""){ cout << "You must enter some type of username!" << endl; getline(cin, username); } pOne.username = username; pOne.winnings = 500; //I add this line because I had a slight bug where the program thought, in one player mode, that the second //player had no money and thus would enter into an endless loop. pTwo.winnings = 500; }else if (players == 2){ cin.ignore(); cout << "Player One please enter your name: " << endl; getline(cin, name); //Validation to ensure that the player enter a value for their name while (name == ""){ cout << "You must enter some type of name!" << endl; getline(cin, name); } pOne.name = name; cout << "Player One please enter your email: " << endl; getline(cin, email); //Validation to ensure that the player enter a value for their email while (email == ""){ cout << "You must enter some type of email!" << endl; getline(cin, email); } pOne.emailAddress = email; cout << "Player One please enter a username: " << endl; cout << "The username will be used during gameplay" << endl; getline(cin, username); //Validation to ensure that the player enter a value for their username while (username == ""){ cout << "You must enter some type of username!" << endl; getline(cin, username); } pOne.username = username; pOne.winnings = 500; cout << endl; cout << "Player Two please enter your name: " << endl; getline(cin, name); //Validation to ensure that the player enter a value for their name while (name == ""){ cout << "You must enter some type of name!" << endl; getline(cin, name); } pTwo.name = name; cout << "Player Two please enter your email: " << endl; getline(cin, email); //Validation to ensure that the player enter a value for their email while (email == ""){ cout << "You must enter some type of email!" << endl; getline(cin, email); } pTwo.emailAddress = email; cout << "Player TWo please enter a username: " << endl; cout << "The username will be used during gameplay" << endl; getline(cin, username); //Validation to ensure that the player enter a value for their username while (username == ""){ cout << "You must enter some type of username!" << endl; getline(cin, username); } pTwo.username = username; pTwo.winnings = 500; } }//End of createId function //This function will determine if the player has enough money to play a round. If they do not have enough money then //the function will boot them from the game. bool bootedOut(PlayerInfo pOne, PlayerInfo pTwo){ //Declaring a local variable bool booted = false; //Clearing the screen to help with player output clearScreen(); //If player one has no winnings they get booted out of the virtual casino if (pOne.winnings <= 0){ //Alerting the user to what is happening cout << pOne.username << " you attempted to make bets with money you did not have" << endl; cout << "You are now booted out of the game!" << endl; cout << "You got player two booted as well!" << endl; //Booted flag being turned to true-this will break the do-while loop. booted = true; //Pausing the program to help with player output. pauseProgram(); //Returning the booted flag to the main function return booted; //If player two has no money then they get booted out of the casino. Yes, the first player gets booted as well. }else if (pTwo.winnings <= 0){ cout << pTwo.username << " you attempted to make bets with money you did not have" << endl; cout << "You are now booted out of the game!" << endl; cout << pOne.username << " is booted as well!" << endl; booted = true; //Pausing the program to help with player output. pauseProgram(); return booted; } //returning the boolean variable to determine if the player(s) will be booted by the game. return booted; }//End of bootedOut function //This function will display the earnings of the players. void displayStats(int players, int playerOneEarnings, int playerTwoEarnings, PlayerInfo &pOne, PlayerInfo &pTwo, int dealerTotal){ //Output for the user to see what screen they are at cout << "*********************" << endl; cout << "* Round Stats *" << endl; cout << "*********************" << endl; cout << endl; //Showing the game stats for the first player if (players == 1){ cout << "Here are the stats for the amount of money each player has: " << endl; pOne.winnings = pOne.winnings + playerOneEarnings; cout << pOne.username << " has a total of: $" << pOne.winnings << endl; //Showing the game stats for the first and second player. }else if (players == 2){ cout << "Here are the stats for the amount of money each player has: " << endl; cout << endl; pOne.winnings = pOne.winnings + playerOneEarnings; pTwo.winnings = pTwo.winnings + playerTwoEarnings; cout << pOne.username << " has a total of: $" << pOne.winnings << endl; cout << pTwo.username << " has a total of: $" << pTwo.winnings << endl; } //Pausing the program to help with output pauseProgram(); //Clearing the screen clearScreen(); }//End of displayStats function //This function will deal two cards to the dealer. void getDealersCards(Card deck[], int DECKSIZE, Card dealer[], int MAXDECK, int &cardLocation, int &dealerTotal){ //This for loop will deal the initial two cards to the dealer. for (int i = 0; i < 2; i++){ dealer[i].valueOne = deck[cardLocation].valueOne; dealer[i].valueTwo = deck[cardLocation].valueTwo; dealer[i].suite = deck[cardLocation].suite; dealer[i].face = deck[cardLocation].face; //This conditional statement will determine what the value of an ace is if the dealer gets one. In this case, //if the dealer total is less than or equal to 10, the ace will be worth 11 points. Greater than 10, the ace //will be worth 1 point. if (deck[cardLocation].valueTwo == 11 && dealerTotal <= 10){ dealerTotal = dealerTotal + deck[cardLocation].valueTwo; }else if (deck[cardLocation].valueTwo == 11 && dealerTotal > 10){ dealerTotal = dealerTotal + deck[cardLocation].valueOne; }else{ dealerTotal = dealerTotal + deck[cardLocation].valueOne; } //card location is incremented so a card is not used twice. cardLocation++; } //Clearing the screen to help with user output clearScreen(); //Outputing the dealers top card cout << "********************" << endl; cout << "* Dealers Top Card *" << endl; cout << "********************" << endl; cout << endl; //This line here will get the dealers top card cout << "The dealers top card is a " << dealer[1].valueOne << " " << "of " << dealer[1].suite << endl; //Pausing and then clearing the screen to help with user output. pauseProgram(); clearScreen(); }//End of getDealersCards function //This function simply displays information for player one. void playerOneInfo(int playerOneTotal, PlayerInfo pOne){ //This line helps with the display output cout << endl; //Player ones total is outputed. cout << pOne.username << " your total is: " << playerOneTotal << endl; cout << endl; cout << pOne.username << ", what is your action: " << endl; }//End of playerOneInfo function //This function simply displays information for player two. void playerTwoInfo(int playerTwoTotal, PlayerInfo pTwo){ //This line helps with the display output cout << endl; //Player two's total is outputted. cout << pTwo.username << " your total is: " << playerTwoTotal << endl; cout << endl; cout << pTwo.username << ", what is your action: " << endl; }//End of playerOneInfo function //This function provides the menu for the options on what the player can do. int playerChoices(){ //Declaring a local variable int action; //Choices are presented for the players actions cout << "1. Hit" << endl; cout << "2. Stand" << endl; cout << "3. Double Down" << endl; cout << "4. Surrender" << endl; cout << "What is your action: " << endl; cin >> action; //If a correct selection is not made, then the user will enter a while loop that will force the user to make a //valid choice before moving on. while ( (action < 1) || (action > 4) ){ cout << "That is not a valid selection" << endl; cout << "Please enter in 1 - 4 for your choice" << endl; cin >> action; } //Returning the action that the player choose. return action; }//End of playerOneAction function //This function will continue to deal cards to the dealer until they get over 17. int dealerAddCard(Card deck [], int DECKSIZE, Card dealer[], int MAXDECK, int &cardLocation, int &dealerTotal){ //I have this variable equal two because the computer received two cards which are in the dealer structure. This means that //spots 0 and 1 are taken. Thus, the next card that the dealer gets will take up the subscript 2 location. Each time //the below loop is incremented, I will increase by one to place more cards into the dealer structure. int i = 2; //If the dealers total is below 16 they get more and more cards added to their total until it is greater than 16. while (dealerTotal <= 16){ dealer[i].valueOne = deck[cardLocation].valueOne; dealer[i].valueTwo = deck[cardLocation].valueTwo; dealer[i].suite = deck[cardLocation].suite; dealer[i].face = deck[cardLocation].face; //This conditional statement will check to see if the dealer recieved an ace. If the dealer did then the program will //assign a value of the ace based on the dealers total currently stands at. if (deck[cardLocation].valueTwo == 11 && dealerTotal <= 10){ dealerTotal = dealerTotal + deck[cardLocation].valueTwo; }else if (deck[cardLocation].valueTwo == 11 && dealerTotal > 10){ dealerTotal = dealerTotal + deck[cardLocation].valueOne; }else{ dealerTotal = dealerTotal + deck[cardLocation].valueOne; } //Incrementing card location cardLocation++; //I keep track of the number of times that the loop increments. i++; } //I then return the number of times that the deck incremented to use in the dealerShowCards function. return i; }//End of dealerAddCard Function //This function will reveal the dealers cards. void dealerShowCards(int dealerDeckSize, Card dealer[], int MAXDECK, int dealerTotal){ //Calling the clearScreen function to help with output. clearScreen(); //Alerting the user that the will now see what cards the dealer has cout << "*****************" << endl; cout << "* Dealers Cards *" << endl; cout << "*****************" << endl; //line output clearing to help with the output. cout << endl; //Outputing the following sentence to alert the user to what cards the dealer has cout << "The dealer has the following cards: " << endl; //The value of i, which is now dealerDeckSize, which was calculated in the dealerAddCard function, will be used //to determine the amount of times to loop through to show all of the dealers cards. for (int i = 0; i < dealerDeckSize; i++){ //This conditional statement will show the user if the dealer has an Ace. if (dealer[i].valueTwo != 11){ cout << "card " << i + 1 << " is a " << dealer[i].valueOne << " of " << dealer[i].suite << endl; }else if(dealer[i].valueTwo == 11){ cout << "card " << i + 1 << " is a " << dealer[i].face << "of " << dealer[i].suite << endl; } } //This cout line will help with output. cout << endl; //Displaying the dealer total cout << "The dealers total is " << dealerTotal << endl; //Pausing the program so that the player can see output. pauseProgram(); }//End of dealerShowCards function //This function will deal the first two cards to the player(s). All of the comments below also //apply to dealTwoCardsTwo. void dealTwoCards(Card deck[], int DECKSIZE, Card playerOne[], int MAXDECK, int &cardLocation, int &playerOneTotal, PlayerInfo pOne){ //Displaying the information to the player as to what their first two cards are. cout << pOne.username << " here are your first two cards: " << endl; //Helping with output cout << endl; //This for loop will give the first two cards to the first player. for (int i = 0; i < 2; i++) { cout << "Card " << i + 1 << " is the " << deck[cardLocation].face << " " << deck[cardLocation].valueOne << " of " << deck[cardLocation].suite << endl; //I am getting the total for the player by adding togather is current total to the value //of the card. playerOneTotal = playerOneTotal + deck[cardLocation].valueOne; //These lines are where the players deck structure is loaded with what they were given. This will be useful //further down in this function when an ace is given to the player. playerOne[i].valueOne = deck[cardLocation].valueOne; playerOne[i].valueTwo = deck[cardLocation].valueTwo; playerOne[i].suite = deck[cardLocation].suite; playerOne[i].face = deck[cardLocation].face; //I have to increment the cardLocation after each hand to ensure that the cards are not //repeated. cardLocation++; } //This variable is what will be used to hold the value of what an ace will be worth. int points; //This conditional block will check to see if the player has an ace value. I originally had this code in the above loop to //determine what an ace value was. The problem was that if an ace was the first card received the user had to decide if //they wanted its value to be an 1 or an 11. Thus, I had to write this much longer line of code to allow the player to //determine the value of an ace after they recieved their two cards. if (playerOne[0].valueTwo == 11){ cout << endl; cout << pOne.username << " one of your cards is an 'ACE'" << endl; cout << "This card may be worth either 1 or 11 points " << endl; cout << "You currently have a total of " << playerOneTotal << endl; cout << "1. 1 point" << endl; cout << "2. 11 points" << endl; cout << "Would you like the card to be worth 1 or 11 points: (1/2) " << endl; cin >> points; //validation loop to ensure that the correct value was entered. while ( (points < 1) || (points > 2) ){ cout << "That value is not allowed. Please enter 1 or 2" << endl; cin >> points; } //Conditional statement to determine assign the value of the ace-either a 1 or a 11. if (points == 1){ playerOne[0].valueOne = 1; }else if (points == 2){ playerOne[0].valueOne = 11; } //Assigning the value for what was selected to the new total. playerOneTotal = playerOne[0].valueOne + playerOne[1].valueOne; //Displaying the new total to the screen. cout << "Your new total is " << playerOneTotal << endl; //This conditional statement will kick in if the second card is an ace. }else if (playerOne[1].valueTwo == 11){ cout << endl; cout << pOne.username << ", one of your cards is an 'ACE'" << endl; cout << "This card may be worth either 1 or 11 points " << endl; cout << "You currently have a total of " << playerOneTotal << endl; cout << "1. 1 point" << endl; cout << "2. 11 points" << endl; cout << "Would you like the card to be worth 1 or 11 points: " << endl; cin >> points; //Validation statement to ensure that the correct value was entered. while ( (points < 1 ) || (points > 2) ){ cout << "That value is not allowed. Please enter 1 or 2" << endl; cin >> points; } //Conditional statement to determine what the value of the ace will be. if (points == 1){ playerOne[1].valueOne = 1; }else if (points == 2){ playerOne[1].valueOne = 11; } //assigning the new total playerOneTotal = playerOne[0].valueOne + playerOne[1].valueOne; //Displaying the new total. cout << "Your new total is " << playerOneTotal << endl; }else { cout << endl; cout << pOne.username << " your total is: " << playerOneTotal << endl; } //This line pauses the program and waits for user input to continue. pauseProgram(); }//End of dealTwoCars //This function will pause the program to allow the players to review information. In many ways, the only purpose of this //function is to pause the program so that the user may review information. Before adding this function, I felt that the //program was moving to 'fast'. void pauseProgram(){ char temp; cout << endl; cout << "Press any letter to continue" << endl; cin >> temp; }//End of PuaseProgram function //This function deals the cards for the second player. void dealTwoCardsTwo(Card deck[], int DECKSIZE, Card playerTwo[], int MAXDECK, int &cardLocation, int &playerTwoTotal, PlayerInfo pTwo){ //Displaying the information to the player as to what their first two cards are. cout << pTwo.username << " here are your first two cards: " << endl; //Helping with output cout << endl; //This for loop will give the first two cards to the second player. for (int i = 0; i < 2; i++) { cout << "Card " << i + 1 << " is the " << deck[cardLocation].face << " " << deck[cardLocation].valueOne << " of " << deck[cardLocation].suite << endl; playerTwoTotal = playerTwoTotal + deck[cardLocation].valueOne; //These lines are where the players deck structure is loaded with what they were given. This will be useful //further down in this function when an ace is given to the player. playerTwo[i].valueOne = deck[cardLocation].valueOne; playerTwo[i].valueTwo = deck[cardLocation].valueTwo; playerTwo[i].suite = deck[cardLocation].suite; playerTwo[i].face = deck[cardLocation].face; //I have to increment the cardLocation after each hand to ensure that the cards are not //repeated. cardLocation++; } //This variable is what will be used to hold the value of what an ace will be worth. int points; //This conditional block will check to see if the player has an ace value. I originally had this code in the above loop to //determine what an ace value was. The problem was that if an ace was the first card received the user had to decide if //they wanted its value to be an 1 or an 11. Thus, I had to write this much longer line of code to allow the player to //determine the value of an ace after they recieved their two cards. if (playerTwo[0].valueTwo == 11){ cout << endl; cout << pTwo.username << ", one of your cards is an 'ACE'" << endl; cout << "This card may be worth either 1 or 11 points " << endl; cout << pTwo.username << " you currently have a total of " << playerTwoTotal << endl; cout << "1. 1 point" << endl; cout << "2. 11 points" << endl; cout << "Would you like the card to be worth 1 or 11 points: (1/2) " << endl; cin >> points; //Validation loop to ensure that the correct value was entered. while ( (points < 1) || (points > 2) ){ cout << "That value is not allowed. Please enter 1 or 2" << endl; cin >> points; } if (points == 1){ playerTwo[0].valueOne = 1; }else if (points == 2){ playerTwo[0].valueOne = 11; } playerTwoTotal = playerTwo[0].valueOne + playerTwo[1].valueOne; cout << "Your new total is " << playerTwoTotal << endl; }else if (playerTwo[1].valueTwo == 11){ cout << endl; cout << pTwo.username << ", one of your cards is an 'ACE'" << endl; cout << "This card may be worth either 1 or 11 points " << endl; cout << pTwo.username << " you currenty have a total of " << playerTwoTotal << endl; cout << "1. 1 point" << endl; cout << "2. 11 points" << endl; cout << "Would you like the card to be worth 1 or 11 points: " << endl; cin >> points; //Validation loop to ensure that the correct value was entered. while ( (points < 1) || (points > 2) ){ cout << "That value is not allowed. Please enter 1 or 2" << endl; cin >> points; } //Conditional statement to determine what the value of the ace will be. if (points == 1){ playerTwo[1].valueOne = 1; }else if (points == 2){ playerTwo[1].valueOne = 11; } playerTwoTotal = playerTwo[0].valueOne + playerTwo[1].valueOne; cout << pTwo.username << " your new total is " << playerTwoTotal << endl; }else { cout << endl; cout << pTwo.username << " your total is: " << playerTwoTotal << endl; } //This line pauses the program and waits for user input to continue. pauseProgram(); }//End of dealTwoCardsTwo //This function will detect if player one has 21 from the initial two cards dealt. If they do, //the round will be over. bool Winner(int playerOneTotal, int *arrayForBets, int players, PlayerInfo pOne){ //Conditional statement to determine if the player has blackjack on initial two cards. if (playerOneTotal == BLACKJACK){ //Alerting the player to what is happening cout << pOne.username << " Got 21 on the initial two cards!" << endl; cout << "This means that this round will now be over!" << endl; //Pausing the program so that the player may read the above message pauseProgram(); //Increasing the bet by multiplying it by 2. arrayForBets[0] = arrayForBets[0] * 2; //Returning the flag's boolean value return true; }else { return false; } }//End of Winner Function //This function will detect if player two has 21 from the initial two cards dealt. If they do, //the round will be over. bool WinnerTwo(int playerTwoTotal, int *arrayForBets, int players, PlayerInfo pTwo){ //Conditional statement to determine if the player has blackjack on initial two cards. if (playerTwoTotal == BLACKJACK){ //Alerting the player to what is happening cout << pTwo.username << "Got 21 on the initial two cards!" << endl; cout << "This means that this round will now be over!" << endl; //Pausing the program so that the player may read the above message pauseProgram(); //Increasing the bet by multiplying it by 2. arrayForBets[1] = arrayForBets[1] * 2; //Returning the flag's boolean value return true; }else { return false; } }//End of Winner Function //This function will deal one card to the player(s) when they do the hit action void dealOneCard(Card deck[], int DECKSIZE, Card playerOne[], int MAXDECK, int &cardLocation, int &playerOneTotal, PlayerInfo pOne){ //Declaring a local variable for use in the function. int aceValue; //This line is dealing out the card to the player. cout << pOne.username << " you just recieved a " << deck[cardLocation].face << " " << deck[cardLocation].valueOne << " of " << deck[cardLocation].suite << endl; //This conditional statement will check to see if the card, that the player recieves is an ace. //If the card is an ace, the player will be allowed to choose its value. if (deck[cardLocation].valueTwo == 11){ cout << pOne.username << " you have an ace, what do you want it to equal 1 or 11?" << endl; cin >> aceValue; //If the wrong value is entered, the player goes into a validation loop. The program will not move on until //the correct value is entered. while ( (aceValue != 1) && (aceValue != 11) ){ cout << "Please enter in the correct value, 1 or 11" << endl; cin >> aceValue; } deck[cardLocation].valueOne = aceValue; } //The players new total is calculated by adding together the playerOneTotal plus the value of the new card. playerOneTotal = playerOneTotal + deck[cardLocation].valueOne; //This line displays the new total to the screen. cout << pOne.username << " your total is " << playerOneTotal << endl; //I have to increment the cardLocation after each hand to ensure that the cards are not //repeated. cardLocation++; //This line pauses and then clears the program and waits for user input to continue. pauseProgram(); clearScreen(); }//End of dealOneCard function //This function will deal one card to the second player when they do the hit action void dealOneCardTwo(Card deck[], int DECKSIZE, Card playerTwo[], int MAXDECK, int &cardLocation, int &playerTwoTotal, PlayerInfo pTwo){ //Declaring a local variable for use in the function. int aceValue; //This line is dealing out the card to the player. cout << pTwo.username << " you just recieved a " << deck[cardLocation].face << " " << deck[cardLocation].valueOne << " of " << deck[cardLocation].suite << endl; //This conditional statement will check to see if the card, that the player recieves is an ace. //If the card is an ace, the player will be allowed to choose its value. if (deck[cardLocation].valueTwo == 11){ cout << pTwo.username << " you have an ace, what do you want it to equal 1 or 11?" << endl; cin >> aceValue; //A validation loop to ensure that the player enters the correct value. while ( (aceValue != 1) && (aceValue != 11) ){ cout << "Please enter in the correct value, 1 or 11" << endl; cin >> aceValue; } deck[cardLocation].valueOne = aceValue; } //The players new total is calculated by adding together the playerOneTotal plus the value of the new card. playerTwoTotal = playerTwoTotal + deck[cardLocation].valueOne; //This line displays the new total to the screen. cout << pTwo.username << " your total is " << playerTwoTotal << endl; //I have to increment the cardLocation after each hand to ensure that the cards are not //repeated. cardLocation++; //This line pauses the program and waits for user input to continue. The following function will clear the screen. pauseProgram(); clearScreen(); }// End of dealOneCardTwo Function //This function is where the player will doubledown. void Doubledown(Card deck[], int DECKSIZE, Card playerOne[], int MAXDECK, int &cardLocation, int &playerOneTotal, int *arrayForBets, int players, PlayerInfo pOne){ //Declaring local variables float betIncrease; int aceValue; //Clearing the screen to help with user output clearScreen(); //The player is asked what percentage they want to increase their wager by. cout << pOne.username << ", please enter in a percentage (0-1) of how much you would like to increase the bet by: " << endl; cin >> betIncrease; //If the bet increase is outside of the acceptable range, the player is asked to enter the correct amount. while ( (betIncrease < 0) || (betIncrease > 1) ){ cout << "Please enter a value between 0 and 1" << endl; cin >> betIncrease; } //The player is given a card. cout << pOne.username << " you just recieved a " << deck[cardLocation].face << " " << deck[cardLocation].valueOne << " of " << deck[cardLocation].suite << endl; //The card is checked to see whether it is an ace. if (deck[cardLocation].valueTwo == 11){ cout << "You have an ace, what do you want it to equal 1 or 11?" << endl; cin >> aceValue; deck[cardLocation].valueOne = aceValue; } //Calculating the total of the cards. playerOneTotal = playerOneTotal + deck[cardLocation].valueOne; //Letting the player know what their card total is. cout << pOne.username << " your card total is at: " << playerOneTotal << endl; //Calculating the bet increase and changing the initial bet to it. arrayForBets[0] = (arrayForBets[0] * betIncrease) + arrayForBets[0]; //Telling the user what their new bet is at. cout << pOne.username << " your bet is now at " << arrayForBets[0] << endl; //This line helps with output. cout << endl; //I have to increment the cardLocation after each hand to ensure that the cards are not //repeated. cardLocation++; //This line pauses the program and waits for user input to continue. pauseProgram(); }//End of Doubledown function //This function is where the second player will doubledown. void DoubleDownTwo(Card deck[], int DECKSIZE, Card playerTwo[],int MAXDECK, int &cardLocation, int &playerTwoTotal, int *arrayForBets, int players, PlayerInfo pTwo){ //Local variables are declared float betIncrease; int aceValue; //Clearing the screen to help with user output clearScreen(); //The player is asked what percentage they want to increase their wager by. cout << pTwo.username << ", Please enter in a percentage (0-1) of how much you would like to increase the bet by: " << endl; cin >> betIncrease; //If the bet increase is outside of the acceptable range, the player is asked to enter the correct amount. while ( (betIncrease < 0) || (betIncrease > 1) ){ cout << "Please enter a value between 0 and 1" << endl; cin >> betIncrease; } //The player is given a card. cout << pTwo.username << " you just recieved a " << deck[cardLocation].face << " " << deck[cardLocation].valueOne << " of " << deck[cardLocation].suite << endl; //The card is checked to see whether it is an ace. if (deck[cardLocation].valueTwo == 11){ cout << pTwo.username << " you have an ace, what do you want it to equal 1 or 11?" << endl; cin >> aceValue; deck[cardLocation].valueOne = aceValue; } //Calculating the total of the cards. playerTwoTotal = playerTwoTotal + deck[cardLocation].valueOne; //Letting the player know what their card total is. cout << pTwo.username << " your card total is at: " << playerTwoTotal << endl; //Calculating the bet increase and changing the initial bet to it. arrayForBets[1] = (arrayForBets[1] * betIncrease) + arrayForBets[1]; //playerTwo[cardLocation] = deck[cardLocation]; Line may not be needed since I never used this. //Telling the user what their new bet is at. cout << pTwo.username << " your bet is now at " << arrayForBets[1] << endl; //This line is here to help with output cout << endl; //I have to increment the cardLocation after each hand to ensure that the cards are not //repeated. cardLocation++; //This line pauses the program and waits for user input to continue. pauseProgram(); }//End of DoubleDown Function //This function will take care of the player surrendering. void surrender(int *arrayForBets, int players){ //Creating a loss local variable to hold the amount that the player will lose. int loss; //This line will take half the players bet if they choose to surrender. loss = arrayForBets[0] * .50; //Making the value in the array equal the new loss variable. arrayForBets[0] = loss; //Letting the user know that they surrendered. cout << "You choose to surrender!" << endl; //This line pauses the program and waits for user input to continue. pauseProgram(); }//End of surrender function //This function will take care of the second player surrendering. void surrenderTwo(int *arrayForBets, int players){ //Creating a loss local variable to hold the amount that the player will lose. int loss; //This line will take half the players bet if they choose to surrender. loss = arrayForBets[1] * .50; //Making the value in the array equal the new loss variable. arrayForBets[1] = loss; //Letting the user know that they surrendered. cout << "You choose to surrender!" << endl; //This line pauses the program and waits for user input to continue. pauseProgram(); //clearing the screen to help with user experience clearScreen(); }//End of SurrenderTwo function //This function will simply alert the user that they have decided to stand //meaning that they will no longer take any cards. void stand(){ //This line is to improve output cout << endl; //Advising the player that they choose stand and what it means. cout << "You choose to stand" << endl; cout << "This means you are not asking for any more cards!" << endl; //Pausing the program to allow the user to see their action. pauseProgram(); //Clearing the screen to help with output clearScreen(); }//End of stand function //This function will ask the player if they want to play again int playAgain(){ //Declaring a local variable int again; //Letting the user know that the round is over cout << "************************" << endl; cout << "* The Round is over *" << endl; cout << "************************" << endl; cout << endl; //Giving the player the option if they want to play again. cout << "1. Play Again" << endl; cout << "2. Stop Playing" << endl; cout << endl; cout << "What is your option: " << endl; cin >> again; //Input validation is occuring to ensure that the player chooses the correct option. while (!validPlayers(again)) { cout << "You may only select 1 or 2" << endl; cin >> again; } //Returning the variable return again; }// End of PlayAgain function //This function will initialize the deck of cards. void createDeck(Card deck[], int DECKSIZE) //creates deck { //One thing that may not make a lot of sense is that is structure has a a valueTwo. This is really not neede except //for the situation involving an ACE. The value two is how I identify an ace as well. This lets the user or computer //select if they want the value of the card to be a 1 or an 11. Everything else about the structure should make sense. deck[0].valueOne = 1; deck[0].valueTwo = 11; deck[0].suite = "Spade"; deck[0].face = "ACE "; deck[1].valueOne = 2; deck[1].valueTwo = 2; deck[1].suite = "Spade"; deck[1].face = ""; deck[2].valueOne = 3; deck[2].valueTwo = 3; deck[2].suite = "Spade"; deck[2].face = ""; deck[3].valueOne = 4; deck[3].valueTwo = 4; deck[3].suite = "Spade"; deck[3].face = ""; deck[4].valueOne = 5; deck[4].valueTwo = 5; deck[4].suite = "Spade"; deck[4].face = ""; deck[5].valueOne = 6; deck[5].valueTwo = 6; deck[5].suite = "Spade"; deck[5].face = ""; deck[6].valueOne = 7; deck[6].valueTwo = 7; deck[6].suite = "Spade"; deck[6].face = ""; deck[7].valueOne = 8; deck[7].valueTwo = 8; deck[7].suite = "Spade"; deck[7].face = ""; deck[8].valueOne = 9; deck[8].valueTwo = 9; deck[8].suite = "Spade"; deck[8].face = ""; deck[9].valueOne = 10; deck[9].valueTwo = 10; deck[9].suite = "Spade"; deck[9].face = ""; deck[10].valueOne = 10; deck[10].valueTwo = 10; deck[10].suite = "Spade"; deck[10].face = "Jack"; deck[11].valueOne = 10; deck[11].valueTwo = 10; deck[11].suite = "Spade"; deck[11].face = "Queen"; deck[12].valueOne = 10; deck[12].valueTwo = 10; deck[12].suite = "Spade"; deck[12].face = "King"; deck[13].valueOne = 1; deck[13].valueTwo = 11; deck[13].suite = "Clubs"; deck[13].face = "ACE "; deck[14].valueOne = 2; deck[14].valueTwo = 2; deck[14].suite = "Clubs"; deck[14].face = ""; deck[15].valueOne = 3; deck[15].valueTwo = 3; deck[15].suite = "Clubs"; deck[15].face = ""; deck[16].valueOne = 4; deck[16].valueTwo = 4; deck[16].suite = "Clubs"; deck[16].face = ""; deck[17].valueOne = 5; deck[17].valueTwo = 5; deck[17].suite = "Clubs"; deck[17].face = ""; deck[18].valueOne = 6; deck[18].valueTwo = 6; deck[18].suite = "Clubs"; deck[18].face = ""; deck[19].valueOne = 7; deck[19].valueTwo = 7; deck[19].suite = "Clubs"; deck[19].face = ""; deck[20].valueOne = 8; deck[20].valueTwo = 8; deck[20].suite = "Clubs"; deck[20].face = ""; deck[21].valueOne = 9; deck[21].valueTwo = 9; deck[21].suite = "Clubs"; deck[21].face = ""; deck[22].valueOne = 10; deck[22].valueTwo = 10; deck[22].suite = "Clubs"; deck[22].face = ""; deck[23].valueOne = 10; deck[23].valueTwo = 10; deck[23].suite = "Clubs"; deck[23].face = "Jack"; deck[24].valueOne = 10; deck[24].valueTwo = 10; deck[24].suite = "Clubs"; deck[24].face = "Queen"; deck[25].valueOne = 10; deck[25].valueTwo = 10; deck[25].suite = "Clubs"; deck[25].face = "King"; deck[26].valueOne = 1; deck[26].valueTwo = 11; deck[26].suite = "Diamonds"; deck[26].face = "ACE "; deck[27].valueOne = 2; deck[27].valueTwo = 2; deck[27].suite = "Diamonds"; deck[27].face = ""; deck[28].valueOne = 3; deck[28].valueTwo = 3; deck[28].suite = "Diamonds"; deck[28].face = ""; deck[29].valueOne = 4; deck[29].valueTwo = 4; deck[29].suite = "Diamonds"; deck[29].face = ""; deck[30].valueOne = 5; deck[30].valueTwo = 5; deck[30].suite = "Diamonds"; deck[30].face = ""; deck[31].valueOne = 6; deck[31].valueTwo = 6; deck[31].suite = "Diamonds"; deck[31].face = ""; deck[32].valueOne = 7; deck[32].valueTwo = 7; deck[32].suite = "Diamonds"; deck[32].face = ""; deck[33].valueOne = 8; deck[33].valueTwo = 8; deck[33].suite = "Diamonds"; deck[33].face = ""; deck[34].valueOne = 9; deck[34].valueTwo = 9; deck[34].suite = "Diamonds"; deck[34].face = ""; deck[35].valueOne = 10; deck[35].valueTwo = 10; deck[35].suite = "Diamonds"; deck[35].face = ""; deck[36].valueOne = 10; deck[36].valueTwo = 10; deck[36].suite = "Diamonds"; deck[36].face = "Jack"; deck[37].valueOne = 10; deck[37].valueTwo = 10; deck[37].suite = "Diamonds"; deck[37].face = "Queen"; deck[38].valueOne = 10; deck[38].valueTwo = 10; deck[38].suite = "Diamonds"; deck[39].valueOne = 1; deck[39].valueTwo = 11; deck[39].suite = "Hearts"; deck[39].face = "ACE "; deck[40].valueOne = 2; deck[40].valueTwo = 2; deck[40].suite = "Hearts"; deck[40].face = ""; deck[41].valueOne = 3; deck[41].valueTwo = 3; deck[41].suite = "Hearts"; deck[41].face = ""; deck[42].valueOne = 4; deck[42].valueTwo = 4; deck[42].suite = "Hearts"; deck[42].face = ""; deck[43].valueOne = 5; deck[43].valueTwo = 5; deck[43].suite = "Hearts"; deck[43].face = ""; deck[44].valueOne = 6; deck[44].valueTwo = 6; deck[44].suite = "Hearts"; deck[44].face = ""; deck[45].valueOne = 7; deck[45].valueTwo = 7; deck[45].suite = "Hearts"; deck[45].face = ""; deck[46].valueOne = 8; deck[46].valueTwo = 8; deck[46].suite = "Hearts"; deck[46].face = ""; deck[47].valueOne = 9; deck[47].valueTwo = 9; deck[47].suite = "Hearts"; deck[47].face = ""; deck[48].valueOne = 10; deck[48].valueTwo = 10; deck[48].suite = "Hearts"; deck[48].face = ""; deck[49].valueOne = 10; deck[49].valueTwo = 10; deck[49].suite = "Hearts"; deck[49].face = "Jack"; deck[50].valueOne = 10; deck[50].valueTwo = 10; deck[50].suite = "Hearts"; deck[50].face = "Queen"; deck[51].valueOne = 10; deck[51].valueTwo = 10; deck[51].suite = "Hearts"; deck[51].face = "King"; }// End of createDeck Function //This function will shuffle the deck void shuffle(Card deck[], int DECKSIZE){ //Declaring variables long seed; int a = 0; const int TEMPSIZE = 52; Card temp[TEMPSIZE]; time_t * value; value = 0; //Using the system clock to produce an initial time seed = time(value); //Seeding the random number generator srand(seed); //Creating an array which will hold all the random values. int random[52]; //Here, I am filling the random array. Each number in it will be in a random order. while(a < 52) { //This line assigns a random number to the current location of what a is. random[a] = rand() % 52; //Incrementing a to fill the next flot. a++; } //A loop to shuffle cards for (int i = 0; i < 52; i++) { //Temp will hold the card. temp[i] = deck[i]; //A new card is assigned to place i. deck[i] = deck[random[i]]; //Old card is assigned to place random. deck[random[i]] = temp[i]; } }//End of shuffle function //This function will use a conditional statement to determine if player one beat the dealer. void determineWinnerOne(int playerOneTotal, int dealerTotal, int *arrayForBets, int players, int &dealerWinnings, int &playerOneEarnings, PlayerInfo pOne, bool BlackJackOne){ clearScreen(); //alerting the user to who one cout << "**************************************" << endl; cout << "* Displaying who won - " << pOne.username << " *" << endl; cout << "**************************************" << endl; cout << endl; if (BlackJackOne == true){ cout << pOne.username << " You got black jack on your initial cards!" << endl; cout << pOne.username << " you won $" << arrayForBets[0] << endl; playerOneEarnings += arrayForBets[0]; }else if (playerOneTotal == 21){ cout << pOne.username << " your total was: " << playerOneTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << pOne.username << " Wins!" << endl; arrayForBets[0] = arrayForBets[0] * 2; cout << pOne.username << " you won $" << arrayForBets[0] << endl; playerOneEarnings += arrayForBets[0]; }else if (playerOneTotal > 21 && dealerTotal > 21){ cout << pOne.username << " your total was: " << playerOneTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << pOne.username << " went BUST" << endl; cout << "Dealer wins!" << endl; cout << "The dealer won $" << arrayForBets[0] << endl; playerOneEarnings -= arrayForBets[0]; cout << pOne.username << " you lost $" << playerOneEarnings << endl; dealerWinnings += arrayForBets[0]; }else if ((playerOneTotal > dealerTotal) && (playerOneTotal <= 21)){ cout << pOne.username << " your total was: " << playerOneTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << pOne.username << " Wins!" << endl; arrayForBets[0] = arrayForBets[0] * 2; cout << "You won $" << arrayForBets[0] << endl; playerOneEarnings += arrayForBets[0]; }else if (playerOneTotal < dealerTotal && (dealerTotal > 21)){ cout << pOne.username << " your total was: " << playerOneTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << pOne.username << " Wins!" << endl; arrayForBets[0] = arrayForBets[0] * 2; cout << pOne.username << " you won $" << arrayForBets[0] << endl; playerOneEarnings += arrayForBets[0]; }else if (playerOneTotal < dealerTotal && (dealerTotal <= 21)){ cout << pOne.username << " your total was: " << playerOneTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "The dealer wins!" << endl; cout << "The dealer won $" << arrayForBets[0] << endl; playerOneEarnings -= arrayForBets[0]; cout << pOne.username << " you lost: " << playerOneEarnings << endl; dealerWinnings += arrayForBets[0]; }else if (playerOneTotal == dealerTotal){ cout << "The dealer and " << pOne.username << " have the same values" << endl; cout << "The game is a tie and no one wins anything" << endl; }else if (playerOneTotal > 21 && dealerTotal <= 21){ cout << pOne.username << " your total was: " << playerOneTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "The dealer won!" << endl; cout << "The dealer won $" << arrayForBets[0] << endl; playerOneEarnings -= arrayForBets[0]; cout << pOne.username << ", you lost $" << playerOneEarnings << endl; dealerWinnings += arrayForBets[0]; }else{ cout << pOne.username << " your total was: " << playerOneTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "The dealer won!" << endl; cout << "The dealer won $" << arrayForBets[0] << endl; dealerWinnings += arrayForBets[0]; playerOneEarnings -= arrayForBets[0]; cout << pOne.username << " you lost $" << playerOneEarnings << endl; } }//End of determineWinnerOne Function //This function will use a conditional statement to determine if player Two beat the dealer. void determineWinnerTwo(int playerTwoTotal, int dealerTotal, int *arrayForBets, int players, int &dealerWinnings, int &playerTwoEarnings, PlayerInfo pTwo, bool BlackJackTwo){ clearScreen(); //alerting the user to who one. cout << "**************************************" << endl; cout << "* Displaying who won - " << pTwo.username << " *" << endl; cout << "**************************************" << endl; cout << endl; if (BlackJackTwo == true){ cout << pTwo.username << " You got black jack on your initial cards!" << endl; cout << pTwo.username << " you won $" << arrayForBets[1] << endl; playerTwoEarnings += arrayForBets[1]; }else if (playerTwoTotal == 21){ cout << pTwo.username << " your total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << pTwo.username << " Wins!" << endl; arrayForBets[1] = arrayForBets[1] * 2; cout << pTwo.username << " you won $" << arrayForBets[1] << endl; playerTwoEarnings += arrayForBets[1]; }else if (playerTwoTotal > 21 && dealerTotal > 21){ cout << pTwo.username << " your total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << pTwo.username << " went BUST!!!" << endl; cout << "Dealer wins!" << endl; cout << "The dealer won $" << arrayForBets[1] << endl; playerTwoEarnings -= arrayForBets[1]; dealerWinnings += arrayForBets[1]; }else if((playerTwoTotal > dealerTotal) && (playerTwoTotal <= 21)){ cout << pTwo.username << " your total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << pTwo.username << " Wins!" << endl; arrayForBets[1] = arrayForBets[1] * 2; cout << pTwo.username << " you won $" << arrayForBets[1] << endl; playerTwoEarnings += arrayForBets[1]; }else if (playerTwoTotal < dealerTotal && (dealerTotal > 21)){ cout << pTwo.username << " your total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << pTwo.username << " Wins!" << endl; arrayForBets[1] = arrayForBets[1] * 2; cout << pTwo.username << " you won $" << arrayForBets[1] << endl; playerTwoEarnings += arrayForBets[1]; }else if (playerTwoTotal < dealerTotal && (dealerTotal <= 21)){ cout << pTwo.username << " your total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "The dealer wins!" << endl; cout << "The dealer won $" << arrayForBets[1] << endl; playerTwoEarnings -= arrayForBets[1]; cout << pTwo.username << " you lost $" << playerTwoEarnings << endl; dealerWinnings += arrayForBets[1]; }else if (playerTwoTotal == dealerTotal){ cout << "The dealer and " << pTwo.username << " have the same values" << endl; cout << "Neither " << pTwo.username << " or the dealer wins anything" << endl; }else if (playerTwoTotal > 21 && dealerTotal <= 21){ cout << pTwo.username << " your total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "The dealer won!" << endl; cout << "The dealer won $" << arrayForBets[1] << endl; playerTwoEarnings -= arrayForBets[1]; cout << pTwo.username << " you lost $" << playerTwoEarnings << endl; dealerWinnings += arrayForBets[1]; }else{ cout << pTwo.username << " your total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "The dealer won!" << endl; cout << "The dealer won $" << arrayForBets[1] << endl; dealerWinnings += arrayForBets[1]; playerTwoEarnings -= arrayForBets[1]; cout << pTwo.username << " you lost $" << playerTwoEarnings << endl; } }//End of determineWinnerTwo Function //This function will play only if the player surroundered in the round. void playerOneSurrendered(int *arrayForBets, int players, int &playerOneEarnings, int &dealerWinnings, PlayerInfo pOne){ //Clearing the screen to help with user output clearScreen(); //Alerting the player to the option they choose cout << pOne.username << " you choose to surrender!" << endl; //Setting the player One Earnings to the correct amount. playerOneEarnings -= arrayForBets[0]; //Alerting the player to what their new amount is. cout << pOne.username << " your total earnings are $" << playerOneEarnings << endl; //Giving the dealer the amount that the player lost. dealerWinnings += playerOneEarnings; //Alerting the user to the amount that the dealer won from the player. cout << "The dealer won " << dealerWinnings << endl; }//End of playerOneSurrendered function //This function will play only if the player surroundered in the round. void playerTwoSurrendered(int *arrayForBets, int players, int &playerTwoEarnings,int &dealerWinnings, PlayerInfo pTwo){ //Clearing the screen to help with user output clearScreen(); //Alerting the player to the option they choose cout << pTwo.username << " you choose to surrender!" << endl; //Setting the player One Earnings to the correct amount. playerTwoEarnings -= arrayForBets[1]; //Alerting the player to what their new amount is. cout << pTwo.username << " your total earnings are $" << playerTwoEarnings << endl; //Giving the dealer the amount that the player lost. dealerWinnings += playerTwoEarnings; //Alerting the user to the amount that the dealer won from the player. cout << "The dealer won " << dealerWinnings << endl; }//End of playerTwoSurrendered function //This function is what will be used to clear the screen to help with user output. Without using system clear, //it is the best that I could do. void clearScreen(){ cout << endl; cout << endl; cout << endl; cout << endl; cout << endl; cout << endl; cout << endl; cout << endl; cout << endl; cout << endl; cout << endl; cout << endl; cout << endl; cout << endl; cout << endl; cout << endl; cout << endl; }//End of clearScreen function //This is the main menu function. void mainMenu(){ //Declaring a local variable int choice; //Outputing user choices for the player. cout << "****************************" << endl; cout << "* *" << endl; cout << "* Welcome to the Main Menu *" << endl; cout << "* *" << endl; cout << "****************************" << endl; cout << endl; cout << "Please select an option" << endl; cout << endl; cout << "1. Play Black Jack" << endl; cout << "2. How to play and basic strategy" << endl; cout << endl; cout << "What is you choice?" << endl; cin >> choice; while ( (choice < 1) || (choice > 2) ){ cout << "That value is not allowed. Please enter either 1 or 2" << endl; cin >> choice; } if (choice == 1){ //Clearing the screen clearScreen(); cout << "The Game will be starting soon!" << endl; cout << endl; cout << "But first, the player(s) must place their bets and create an ID" << endl; } else if (choice == 2){ //Clearing the screen to help with output. clearScreen(); //Calling the function which will display the instrutions instructions(); } }//End of mainMenu function //Instructions function-This will display all the rules to playing black jack void instructions(){ //Clearing the screen to help with output. clearScreen(); //The below output will provide instructions on how to play the game with the user. cout << " INSTRUCTIONS TO PLAY " << endl; cout << "##########################################################" << endl; cout << " POINTS " << endl; cout << "*Aces may be worth 1 or 11 points " << endl; cout << "*Face cards are worth 10 points " << endl; cout << "*All other cards are worth the number on the card " << endl; cout << "##########################################################" << endl; //Pausing the program to help with user output. pauseProgram(); //Clearing the screen to help with output. clearScreen(); cout << "##########################################################" << endl; cout << " BASIC RULES " << endl; cout << "*The basic goal of the game is to get to 21 or 'Black Jack'" << endl; cout << "*If the player gets to 21, the player wins " << endl; cout << "*If the dealer gets 21, the dealer wins " << endl; cout << "*If the player and the dealer are both over 21, the dealer wins" << endl; cout << "*If the player and dealer have the same value then it is a tie-no one wins" << endl; cout << "*If the player is closer to 21 than the dealer, the player wins"<< endl; cout << "*If the player and the dealer both have 21, the player wins." << endl; cout << "*Each player plays against the dealer, not each other." << endl; cout << "*Basically, the player wants to get as close to 21 without going over" << endl; cout << "*If the player gets to 21 on the initial two cards, they win as well!" << endl; cout << endl; cout << " OPTIONS DURING GAMEPLAY " << endl; cout << "*Hit: Means that the player gets one more card " << endl; cout << "*Stand: Player recieves no more cards " << endl; cout << "*DoubleDown: Player recieves one more card but cannot recieve more " << endl; cout << "*Surrender: Player will lose 50% of their bet " << endl; cout << "##########################################################" << endl; //Pausing the program to help with user output. pauseProgram(); //Clearing the screen to help with output. clearScreen(); cout << "##########################################################" << endl; cout << " BASIC STRATEGY OR TIPS " << endl; cout << "*The most common card in Black Jack is a 10 " << endl; cout << "*If you have 16 or below you may want to hit... " << endl; cout << "*If you have 17 or above you may want to stand... " << endl; cout << "*Always remember what the most common card is... " << endl; cout << "*You may not want to follow these rules... " << endl; cout << endl; cout << "ARE YOU READY TO PLAY...HERE WE GO... " << endl; cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl; }//End of instructions function //This function closes out the game. void goodBye(){ //Clearing the screen to help with user output clearScreen(); //All of these cout statements introduce the user to the game. cout << "\t\t\t***********************" << endl; cout << "\t\t\t*---------------------*" << endl; cout << "\t\t\t*---------------------*" << endl; cout << "\t\t\t*----<NAME>-----*" << endl; cout << "\t\t\t*---------------------*" << endl; cout << "\t\t\t* You are now exiting *" << endl; cout << "\t\t\t*---------------------*" << endl; cout << "\t\t\t*-------Where---------*" << endl; cout << "\t\t\t*------You Lose-------*" << endl; cout << "\t\t\t*-------We Win--------*" << endl; cout << "\t\t\t*---------------------*" << endl; cout << "\t\t\t***********************" << endl; cout << endl; //Outputing a message to the user cout << "I hope you were not scared off by losing!" << endl; cout << "Come back real soon now!" << endl; //Pausing the program so that the user may read what is on the screen pauseProgram(); }//End of goodBye function //************************************** //Validation functions below this point. This one validation function is used twice in my //program to validate data. //************************************* //This function checks to ensure that the game only has one or two players. bool validPlayers(int value){ //If the value is 1 or 2 then the function returns true. if (value == 1 || value == 2){ return true; //If the value is anything else other than 1 or 2 than false will be returned }else{ return false; } }// End of validPlayers function. <file_sep>/readme.md # Black Jack ## Intro This is a black jack game made with C++. # Getting started ### Installing C++ will be needed to use this project.<file_sep>/old.cpp //This is the old version of my blackjack determine winner code before I changed it: //Writing the function for the below if then statement. if (SurrenderOne == false){ determineWinnerOne(playerOneTotal, dealerTotal, arrayForBets, players, dealerWinnings, playerOneEarnings); // if (playerOneTotal == 21){ // cout << "Player One your total was: " << playerOneTotal << endl; // cout << "The Dealers total was: " << dealerTotal << endl; // cout << "Player one Wins!" << endl; // arrayForBets[0] = arrayForBets[0] * 2; // cout << "You won $" << arrayForBets[0] << endl; // playerOneEarnings += arrayForBets[0]; // cout << "Player one your total earnings are $" << playerOneEarnings << endl; // }else if (playerOneTotal > 21 && dealerTotal > 21){ // cout << "BUST" << endl; // cout << "Dealer wins!" << endl; // cout << "The dealer won $" << arrayForBets[0] << endl; // playerOneEarnings -= arrayForBets[0]; // cout << "Player one your total earnings are $" << playerOneEarnings << endl; // dealerWinnings += arrayForBets[0]; // }else if ((playerOneTotal > dealerTotal) && (playerOneTotal <= 21)){ // cout << "Player One your total was: " << playerOneTotal << endl; // cout << "The Dealers total was: " << dealerTotal << endl; // cout << "Player one Wins!" << endl; // arrayForBets[0] = arrayForBets[0] * 2; // cout << "You won $" << arrayForBets[0] << endl; // playerOneEarnings += arrayForBets[0]; // cout << "Player one your total earnings are $" << playerOneEarnings << endl; // }else if (playerOneTotal < dealerTotal && (dealerTotal > 21)){ // cout << "Player One your total was: " << playerOneTotal << endl; // cout << "The Dealers total was: " << dealerTotal << endl; // cout << "Player one Wins!" << endl; // arrayForBets[0] = arrayForBets[0] * 2; // cout << "You won $" << arrayForBets[0] << endl; // playerOneEarnings += arrayForBets[0]; // cout << "Player one your total earnings are $" << playerOneEarnings << endl; // }else if (playerOneTotal < dealerTotal && (dealerTotal <= 21)){ // cout << "Player One your total was: " << playerOneTotal << endl; // cout << "The Dealers total was: " << dealerTotal << endl; // cout << "The dealer wins!" << endl; // cout << "The dealer won $" << arrayForBets[0] << endl; // playerOneEarnings -= arrayForBets[0]; // cout << "Player one your total earnings are $" << playerOneEarnings << endl; // dealerWinnings += arrayForBets[0]; // }else if (playerOneTotal == dealerTotal){ // cout << "The dealer and player have the same values" << endl; // cout << "The game is a tie and no one wins anything" << endl; // }else if (playerOneTotal > 21 && dealerTotal <= 21){ // cout << "Player One your total was: " << playerOneTotal << endl; // cout << "The Dealers total was: " << dealerTotal << endl; // cout << "The dealer won!" << endl; // cout << "The dealer won $" << arrayForBets[0] << endl; // playerOneEarnings -= arrayForBets[0]; // cout << "Player one your total earnings are $" << playerOneEarnings << endl; // dealerWinnings += arrayForBets[0]; // }else{ // cout << "Player One your total was: " << playerOneTotal << endl; // cout << "The Dealers total was: " << dealerTotal << endl; // cout << "The dealer won!" << endl; // cout << "The dealer won $" << arrayForBets[0] << endl; // dealerWinnings += arrayForBets[0]; // playerOneEarnings -= arrayForBets[0]; // cout << "Player one your total earnings are $" << playerOneEarnings << endl; // } }else if (SurrenderOne == true){ cout << "Player One you choose to surrender!" << endl; cout << "You now have " << arrayForBets[0] << endl; playerOneEarnings -= arrayForBets[0]; cout << "Player one your total earnings are $" << playerOneEarnings << endl; } if(SurrenderTwo == false && players == 2){ cout << endl; if (playerTwoTotal == 21){ cout << "Player Two your total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "Player Two Wins!" << endl; arrayForBets[1] = arrayForBets[1] * 2; cout << "You won $" << arrayForBets[1] << endl; playerTwoEarnings += arrayForBets[1]; cout << "Player two your total earnings are $" << playerTwoEarnings << endl; }else if (playerTwoTotal > 21 && dealerTotal > 21){ cout << "BUST" << endl; cout << "Dealer wins!" << endl; cout << "The dealer won $" << arrayForBets[1] << endl; playerTwoEarnings -= arrayForBets[1]; cout << "Player one your total earnings are $" << playerTwoEarnings << endl; dealerWinnings += arrayForBets[1]; }else if((playerTwoTotal > dealerTotal) && (playerTwoTotal <= 21)){ cout << "Player Two your total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "Player Two Wins!" << endl; arrayForBets[1] = arrayForBets[1] * 2; cout << "You won $" << arrayForBets[1] << endl; playerTwoEarnings += arrayForBets[1]; cout << "Player two your total earnings are $" << playerTwoEarnings << endl; }else if (playerTwoTotal < dealerTotal && (dealerTotal > 21)){ cout << "Player Two your total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "Player Two Wins!" << endl; arrayForBets[0] = arrayForBets[0] * 2; cout << "You won $" << arrayForBets[0] << endl; playerTwoEarnings += arrayForBets[0]; cout << "Player one your total earnings are $" << playerTwoEarnings << endl; }else if (playerTwoTotal < dealerTotal && (dealerTotal <= 21)){ cout << "Player Two your total was: " << playerOneTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "The dealer wins!" << endl; cout << "The dealer won $" << arrayForBets[1] << endl; playerTwoEarnings -= arrayForBets[1]; cout << "Player two your total earnings are $" << playerTwoEarnings << endl; dealerWinnings += arrayForBets[1]; }else if (playerTwoTotal == dealerTotal){ cout << "The dealer and player Two have the same values" << endl; cout << "Neither Player Two or the dealer wins anything" << endl; }else if (playerTwoTotal > 21 && dealerTotal <= 21){ cout << "Player Two your total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "The dealer won!" << endl; cout << "The dealer won $" << arrayForBets[1] << endl; playerTwoEarnings -= arrayForBets[1]; cout << "Player Two your total earnings are $" << playerTwoEarnings << endl; dealerWinnings += arrayForBets[1]; }else{ cout << "Player Two's total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "The dealer won!" << endl; cout << "The dealer won $" << arrayForBets[1] << endl; dealerWinnings += arrayForBets[1]; playerTwoEarnings -= arrayForBets[1]; cout << "Player Two your total earnings are $" << playerTwoEarnings << endl; } } else if (SurrenderTwo == true){ cout << "Player Two you choose to surrender!" << endl; cout << "You now have " << arrayForBets[1] << endl; playerTwoEarnings -= arrayForBets[1]; cout << "Player Two your total earnings are $" << playerTwoEarnings << endl; }<file_sep>/scrap.cpp //The code in here is all code that I was using at one point in my program but then realized that I may not need it. //I place it in here in case I do need it again. //CHECKING FOR AN ACE // if (deck[cardLocation].valueTwo == 11){ // cout << "You have an ace, what do you want it to equal 1 or 11?" << endl; // cin >> aceValue; // deck[cardLocation].valueOne = aceValue; // } // if (deck[cardLocation].valueTwo == 11){ // cout << "You have an ace, what do you want it to equal 1 or 11?" << endl; // cin >> aceValue; // deck[cardLocation].valueOne = aceValue; // } //END OF CHECKING FOR AN ACE if (players == 1){ playerOneEarnings += arrayForBets[0]; cout << "Player one your total earnings are $" << playerOneEarnings << endl; } //This will automatically end the program if the last card is reached. THIS FUNCTION MAY //NOT BEEN NEEDED BECAUSE THE PROGRAM ALWAYS RESHUFFLES THE CARD DECK AND CARD LOCATION TO //ZERO THROUGH EVERY ROUND. again = cardCheck(cardLocation, DECKSIZE, again); if (players == 2 && SurrenderOne == false && SurrenderTwo == false){ if ((playerOneTotal > dealerTotal) && (playerOneTotal <= 21)){ cout << "Player One's total was: " << playerOneTotal << endl; cout << "Player Two's total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "Player one Wins!" << endl; arrayForBets[0] = arrayForBets[0] * 2; cout << "You won $" << arrayForBets[0] << endl; playerOneEarnings += arrayForBets[0]; cout << "Player one your total earnings are $" << playerOneEarnings << endl; // arrayForBets[1] -= arrayForBets[1]; // cout << "Player two you lost $" << arrayForBets[1] << endl; }else if ((dealerTotal > playerOneTotal) ){ } } cout << "1. Hit" << endl; cout << "2. Stand" << endl; cout << "3. Double Down" << endl; cout << "4. Surrender" << endl; cout << "Player one, what is your action: " << endl; cin >> action; cout << endl; cout << "Player One your total is: " << playerOneTotal << endl; cout << "Player one, what is your action: " << endl; void determineWinnerOne(int, int, int *, int, int &, int &); determineWinnerOne(playerOneTotal, dealerTotal, arrayForBets, players, dealerWinnings, playerOneEarnings); void determineWinnerOne(int playerOneTotal, int dealerTotal, int *arrayForBets, int players, int &dealerWinnings, int &playerOneEarnings){ void determineWinnerTwo(int, int, int *, int, int &, int &); void determineWinnerTwo(int playerTwoTotal, int dealerTotal, int *arrayForBets, int players, int &dealerWinnings, int &playerTwoEarnings){ cout << endl; if (playerTwoTotal == 21){ cout << "Player Two your total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "Player Two Wins!" << endl; arrayForBets[1] = arrayForBets[1] * 2; cout << "You won $" << arrayForBets[1] << endl; playerTwoEarnings += arrayForBets[1]; cout << "Player two your total earnings are $" << playerTwoEarnings << endl; }else if (playerTwoTotal > 21 && dealerTotal > 21){ cout << "BUST" << endl; cout << "Dealer wins!" << endl; cout << "The dealer won $" << arrayForBets[1] << endl; playerTwoEarnings -= arrayForBets[1]; cout << "Player one your total earnings are $" << playerTwoEarnings << endl; dealerWinnings += arrayForBets[1]; }else if((playerTwoTotal > dealerTotal) && (playerTwoTotal <= 21)){ cout << "Player Two your total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "Player Two Wins!" << endl; arrayForBets[1] = arrayForBets[1] * 2; cout << "You won $" << arrayForBets[1] << endl; playerTwoEarnings += arrayForBets[1]; cout << "Player two your total earnings are $" << playerTwoEarnings << endl; }else if (playerTwoTotal < dealerTotal && (dealerTotal > 21)){ cout << "Player Two your total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "Player Two Wins!" << endl; arrayForBets[0] = arrayForBets[0] * 2; cout << "You won $" << arrayForBets[0] << endl; playerTwoEarnings += arrayForBets[0]; cout << "Player one your total earnings are $" << playerTwoEarnings << endl; }else if (playerTwoTotal < dealerTotal && (dealerTotal <= 21)){ cout << "Player Two your total was: " << playerOneTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "The dealer wins!" << endl; cout << "The dealer won $" << arrayForBets[1] << endl; playerTwoEarnings -= arrayForBets[1]; cout << "Player two your total earnings are $" << playerTwoEarnings << endl; dealerWinnings += arrayForBets[1]; }else if (playerTwoTotal == dealerTotal){ cout << "The dealer and player Two have the same values" << endl; cout << "Neither Player Two or the dealer wins anything" << endl; }else if (playerTwoTotal > 21 && dealerTotal <= 21){ cout << "Player Two your total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "The dealer won!" << endl; cout << "The dealer won $" << arrayForBets[1] << endl; playerTwoEarnings -= arrayForBets[1]; cout << "Player Two your total earnings are $" << playerTwoEarnings << endl; dealerWinnings += arrayForBets[1]; }else{ cout << "Player Two's total was: " << playerTwoTotal << endl; cout << "The Dealers total was: " << dealerTotal << endl; cout << "The dealer won!" << endl; cout << "The dealer won $" << arrayForBets[1] << endl; dealerWinnings += arrayForBets[1]; playerTwoEarnings -= arrayForBets[1]; cout << "Player Two your total earnings are $" << playerTwoEarnings << endl; } } //int getNum(){ // // int value; // // //Getting the system time for random number generator // unsigned seed = time(0); // //Seeding the random number generator // srand(seed); // // value = (rand() % (MAX_VALUE - MIN_VALUE + 1)) + MIN_VALUE; // // return value; //} //int random; // //srand(time(0)); //random = rand()%MAX_VALUE; //random = getNum(); //cout << random << endl; //int x = 0; // //while (x < 4){ // // random = rand()%MAX_VALUE; // cout << random << endl; // x++; // } //This function will run the main aspect of the game. //void game(int players, Card deck[], int DECKSIZE){ // // // //}//End of Game Function //This function will be the actual game function //game(players, deck, DECKSIZE); NOT USING AS OF NOW deck[0].valueOne = 1; deck[0].valueTwo = 11; deck[0].suite = "Spade"; deck[0].face = "ACE "; deck[1].valueOne = 2; deck[1].valueTwo = 2; deck[1].suite = "Spade"; deck[1].face = ""; deck[2].valueOne = 3; deck[2].valueTwo = 3; deck[2].suite = "Spade"; deck[2].face = ""; deck[3].valueOne = 4; deck[3].valueTwo = 4; deck[3].suite = "Spade"; deck[3].face = ""; deck[4].valueOne = 5; deck[4].valueTwo = 5; deck[4].suite = "Spade"; deck[4].face = ""; deck[5].valueOne = 6; deck[5].valueTwo = 6; deck[5].suite = "Spade"; deck[5].face = ""; deck[6].valueOne = 7; deck[6].valueTwo = 7; deck[6].suite = "Spade"; deck[6].face = ""; deck[7].valueOne = 8; deck[7].valueTwo = 8; deck[7].suite = "Spade"; deck[7].face = ""; deck[8].valueOne = 9; deck[8].valueTwo = 9; deck[8].suite = "Spade"; deck[8].face = ""; deck[9].valueOne = 10; deck[9].valueTwo = 10; deck[9].suite = "Spade"; deck[9].face = ""; deck[10].valueOne = 10; deck[10].valueTwo = 10; deck[10].suite = "Spade"; deck[10].face = "Jack"; deck[11].valueOne = 10; deck[11].valueTwo = 10; deck[11].suite = "Spade"; deck[11].face = "Queen"; deck[12].valueOne = 10; deck[12].valueTwo = 10; deck[12].suite = "Spade"; deck[12].face = "King"; ///// ACE CARDS FOR TESTING /////// deck[0].valueOne = 1; deck[0].valueTwo = 11; deck[0].suite = "Spade"; deck[0].face = "ACE "; deck[1].valueOne = 1; deck[1].valueTwo = 11; deck[1].suite = "Spade"; deck[1].face = "ACE "; deck[2].valueOne = 1; deck[2].valueTwo = 11; deck[2].suite = "Spade"; deck[2].face = "ACE "; deck[3].valueOne = 1; deck[3].valueTwo = 11; deck[3].suite = "Spade"; deck[3].face = "ACE "; deck[4].valueOne = 1; deck[4].valueTwo = 11; deck[4].suite = "Spade"; deck[4].face = "ACE "; deck[5].valueOne = 1; deck[5].valueTwo = 11; deck[5].suite = "Spade"; deck[5].face = "ACE "; deck[6].valueOne = 1; deck[6].valueTwo = 11; deck[6].suite = "Spade"; deck[6].face = "ACE "; deck[7].valueOne = 1; deck[7].valueTwo = 11; deck[7].suite = "Spade"; deck[7].face = "ACE "; deck[8].valueOne = 1; deck[8].valueTwo = 11; deck[8].suite = "Spade"; deck[8].face = "ACE "; deck[9].valueOne = 1; deck[9].valueTwo = 11; deck[9].suite = "Spade"; deck[9].face = "ACE "; deck[10].valueOne = 1; deck[10].valueTwo = 11; deck[10].suite = "Spade"; deck[10].face = "ACE "; deck[11].valueOne = 1; deck[11].valueTwo = 11; deck[11].suite = "Spade"; deck[11].face = "ACE "; deck[12].valueOne = 1; deck[12].valueTwo = 11; deck[12].suite = "Spade"; deck[12].face = "ACE "; //Test for 21 //This function will initialize the deck of cards. void createDeck(Card deck[], int DECKSIZE) //creates deck { //One thing that may not make a lot of sense is that is structure has a a valueTwo. This is really not needed except //for the situation involving an ACE. The value two is how I identify an ace as well as let the user or computer //select if they want the value of the card to be a 1 or an 11. Everything else about the structure should make sense. deck[0].valueOne = 1; deck[0].valueTwo = 11; deck[0].suite = "Spade"; deck[0].face = "ACE "; deck[1].valueOne = 1; deck[1].valueTwo = 11; deck[1].suite = "Spade"; deck[1].face = "ACE "; deck[2].valueOne = 1; deck[2].valueTwo = 11; deck[2].suite = "Spade"; deck[2].face = "ACE "; deck[3].valueOne = 1; deck[3].valueTwo = 11; deck[3].suite = "Spade"; deck[3].face = "ACE "; deck[4].valueOne = 1; deck[4].valueTwo = 11; deck[4].suite = "Spade"; deck[4].face = "ACE "; deck[5].valueOne = 1; deck[5].valueTwo = 11; deck[5].suite = "Spade"; deck[5].face = "ACE "; deck[6].valueOne = 1; deck[6].valueTwo = 11; deck[6].suite = "Spade"; deck[6].face = "ACE "; deck[7].valueOne = 1; deck[7].valueTwo = 11; deck[7].suite = "Spade"; deck[7].face = "ACE "; deck[8].valueOne = 1; deck[8].valueTwo = 11; deck[8].suite = "Spade"; deck[8].face = "ACE "; deck[9].valueOne = 1; deck[9].valueTwo = 11; deck[9].suite = "Spade"; deck[9].face = "ACE "; deck[10].valueOne = 1; deck[10].valueTwo = 11; deck[10].suite = "Spade"; deck[10].face = "ACE "; deck[11].valueOne = 1; deck[11].valueTwo = 11; deck[11].suite = "Spade"; deck[11].face = "ACE "; deck[12].valueOne = 1; deck[12].valueTwo = 11; deck[12].suite = "Spade"; deck[12].face = "ACE "; deck[13].valueOne = 1; deck[13].valueTwo = 11; deck[13].suite = "Clubs"; deck[13].face = "ACE "; deck[14].valueOne = 10; deck[14].valueTwo = 10; deck[14].suite = "Clubs"; deck[14].face = ""; deck[15].valueOne = 10; deck[15].valueTwo = 3; deck[15].suite = "Clubs"; deck[15].face = ""; deck[16].valueOne = 10; deck[16].valueTwo = 10; deck[16].suite = "Clubs"; deck[16].face = ""; deck[17].valueOne = 10; deck[17].valueTwo = 10; deck[17].suite = "Clubs"; deck[17].face = ""; deck[18].valueOne = 10; deck[18].valueTwo = 10; deck[18].suite = "Clubs"; deck[18].face = ""; deck[19].valueOne = 10; deck[19].valueTwo = 10; deck[19].suite = "Clubs"; deck[19].face = ""; deck[20].valueOne = 10; deck[20].valueTwo = 8; deck[20].suite = "Clubs"; deck[20].face = ""; deck[21].valueOne = 10; deck[21].valueTwo = 10; deck[21].suite = "Clubs"; deck[21].face = ""; deck[22].valueOne = 10; deck[22].valueTwo = 10; deck[22].suite = "Clubs"; deck[22].face = ""; deck[23].valueOne = 10; deck[23].valueTwo = 10; deck[23].suite = "Clubs"; deck[23].face = "Jack"; deck[24].valueOne = 10; deck[24].valueTwo = 10; deck[24].suite = "Clubs"; deck[24].face = "Queen"; deck[25].valueOne = 10; deck[25].valueTwo = 10; deck[25].suite = "Clubs"; deck[25].face = "King"; deck[26].valueOne = 1; deck[26].valueTwo = 11; deck[26].suite = "Diamonds"; deck[26].face = "ACE "; deck[27].valueOne = 10; deck[27].valueTwo = 10; deck[27].suite = "Diamonds"; deck[27].face = ""; deck[28].valueOne = 10; deck[28].valueTwo = 10; deck[28].suite = "Diamonds"; deck[28].face = ""; deck[29].valueOne = 10; deck[29].valueTwo = 10; deck[29].suite = "Diamonds"; deck[29].face = ""; deck[30].valueOne = 10; deck[30].valueTwo = 10; deck[30].suite = "Diamonds"; deck[30].face = ""; deck[31].valueOne = 10; deck[31].valueTwo = 10; deck[31].suite = "Diamonds"; deck[31].face = ""; deck[32].valueOne = 10; deck[32].valueTwo = 10; deck[32].suite = "Diamonds"; deck[32].face = ""; deck[33].valueOne = 10; deck[33].valueTwo = 10; deck[33].suite = "Diamonds"; deck[33].face = ""; deck[34].valueOne = 10; deck[34].valueTwo = 10; deck[34].suite = "Diamonds"; deck[34].face = ""; deck[35].valueOne = 10; deck[35].valueTwo = 10; deck[35].suite = "Diamonds"; deck[35].face = ""; deck[36].valueOne = 10; deck[36].valueTwo = 10; deck[36].suite = "Diamonds"; deck[36].face = "Jack"; deck[37].valueOne = 10; deck[37].valueTwo = 10; deck[37].suite = "Diamonds"; deck[37].face = "Queen"; deck[38].valueOne = 10; deck[38].valueTwo = 10; deck[38].suite = "Diamonds"; deck[39].valueOne = 1; deck[39].valueTwo = 11; deck[39].suite = "Hearts"; deck[39].face = "ACE "; deck[40].valueOne = 10; deck[40].valueTwo = 10; deck[40].suite = "Hearts"; deck[40].face = ""; deck[41].valueOne = 10; deck[41].valueTwo = 10; deck[41].suite = "Hearts"; deck[41].face = ""; deck[42].valueOne = 10; deck[42].valueTwo = 10; deck[42].suite = "Hearts"; deck[42].face = ""; deck[43].valueOne = 10; deck[43].valueTwo = 10; deck[43].suite = "Hearts"; deck[43].face = ""; deck[44].valueOne = 10; deck[44].valueTwo = 10; deck[44].suite = "Hearts"; deck[44].face = ""; deck[45].valueOne = 10; deck[45].valueTwo = 10; deck[45].suite = "Hearts"; deck[45].face = ""; deck[46].valueOne = 10; deck[46].valueTwo = 10; deck[46].suite = "Hearts"; deck[46].face = ""; deck[47].valueOne = 10; deck[47].valueTwo = 10; deck[47].suite = "Hearts"; deck[47].face = ""; deck[48].valueOne = 10; deck[48].valueTwo = 10; deck[48].suite = "Hearts"; deck[48].face = ""; deck[49].valueOne = 10; deck[49].valueTwo = 10; deck[49].suite = "Hearts"; deck[49].face = "Jack"; deck[50].valueOne = 10; deck[50].valueTwo = 10; deck[50].suite = "Hearts"; deck[50].face = "Queen"; deck[51].valueOne = 10; deck[51].valueTwo = 10; deck[51].suite = "Hearts"; deck[51].face = "King"; }// End of createDeck Function
0f7aa7ac12026544eb5fa1585dceeb427bef1e18
[ "Markdown", "C++" ]
4
C++
ravenusmc/Black_jack
431e4b767b76fe1c1ca97099025efd072ed33507
f1c22b25fe2d91c882a66b34924dbb019a03ca87